1 # -*- coding: utf-8 -*-
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
7 from librarian import IOFile, RDFNS, DCNS, Format
8 from xmlutils import Xmill, tag, tagged, ifoption, tag_open_close
9 from librarian import functions
12 from copy import deepcopy
14 IMAGE_THUMB_WIDTH = 300
16 class EduModule(Xmill):
17 def __init__(self, options=None):
18 super(EduModule, self).__init__(options)
19 self.activity_counter = 0
20 self.exercise_counter = 0
23 def swap_endlines(txt):
24 if self.options['strofa']:
25 txt = txt.replace("/\n", "<br/>\n")
27 self.register_text_filter(functions.substitute_entities)
28 self.register_text_filter(swap_endlines)
30 @tagged('div', 'stanza')
31 def handle_strofa(self, element):
32 self.options = {'strofa': True}
35 def handle_powiesc(self, element):
37 <div class="module" id="book-text">
38 <!-- <span class="teacher-toggle">
39 <input type="checkbox" name="teacher-toggle" id="teacher-toggle"/>
40 <label for="teacher-toggle">Pokaż treść dla nauczyciela</label>
45 handle_autor_utworu = tag("span", "author")
46 handle_dzielo_nadrzedne = tag("span", "collection")
47 handle_podtytul = tag("span", "subtitle")
48 handle_naglowek_akt = handle_naglowek_czesc = handle_srodtytul = tag("h2")
49 handle_naglowek_scena = tag('h2')
50 handle_naglowek_osoba = handle_naglowek_podrozdzial = tag('h3')
51 handle_akap = handle_akap_dialog = handle_akap_cd = tag('p', 'paragraph')
53 handle_wyroznienie = tag('em')
54 handle_tytul_dziela = tag('em', 'title')
55 handle_slowo_obce = tag('em', 'foreign')
57 def naglowek_to_anchor(self, naglowek):
58 return re.sub(r" +", " ", naglowek.text.strip())
60 def handle_nazwa_utworu(self, element):
62 for naglowek in element.getparent().findall('.//naglowek_rozdzial'):
63 a = etree.Element("a")
64 a.attrib["href"] = "#" + self.naglowek_to_anchor(naglowek)
65 a.text = naglowek.text
66 atxt = etree.tostring(a, encoding=unicode)
67 toc.append("<li>%s</li>" % atxt)
68 toc = "<ul class='toc'>%s</ul>" % "".join(toc)
69 add_header = "Lekcja: " if self.options['wldoc'].book_info.type in ('course', 'synthetic') else ''
70 return "<h1 class='title'><a name='top'></a>%s" % add_header, "</h1>" + toc
72 def handle_naglowek_rozdzial(self, element):
73 return_to_top = u"<a href='#top' class='top-link'>wróć do spisu treści</a>"
74 anchor = "".join(tag_open_close("a", name=self.naglowek_to_anchor(element)))
75 return return_to_top + "<h2>", anchor + "</h2>"
77 def handle_uwaga(self, _e):
80 def handle_aktywnosc(self, element):
81 self.activity_counter += 1
84 'activity_counter': self.activity_counter,
86 submill = EduModule(dict(self.options.items() + {'sub_gen': True}.items()))
88 opis = submill.generate(element.xpath('opis')[0])
90 n = element.xpath('wskazowki')
91 if n: wskazowki = submill.generate(n[0])
94 n = element.xpath('pomoce')
96 if n: pomoce = submill.generate(n[0])
99 forma = ''.join(element.xpath('forma/text()'))
101 czas = ''.join(element.xpath('czas/text()'))
103 counter = self.activity_counter
106 <div class="activity">
108 <span class="act_counter">%(counter)d.</span>
109 %(opis)s""" % locals(), \
113 <section class="infobox time"><h1>Czas</h1><p>%(czas)s min</p></section>
114 <section class="infobox kind"><h1>Metoda</h1><p>%(forma)s</p></section>
117 <div class="clearboth"></div>
121 handle_opis = ifoption(sub_gen=True)(tag('div', 'description'))
122 handle_wskazowki = ifoption(sub_gen=True)(tag('div', ('hints', 'teacher')))
124 @ifoption(sub_gen=True)
125 @tagged('section', 'infobox materials')
126 def handle_pomoce(self, _):
127 return """<h1>Pomoce</h1>""", ""
129 def handle_czas(self, *_):
132 def handle_forma(self, *_):
135 def handle_cwiczenie(self, element):
136 exercise_handlers = {
138 'uporzadkuj': Uporzadkuj,
141 'przyporzadkuj': Przyporzadkuj,
142 'prawdafalsz': PrawdaFalsz
145 typ = element.attrib['typ']
146 self.exercise_counter += 1
147 self.options = {'exercise_counter': self.exercise_counter}
148 handler = exercise_handlers[typ](self.options)
149 return handler.generate(element)
152 def handle_lista(self, element, attrs={}):
153 ltype = element.attrib.get('typ', 'punkt')
154 if not element.findall("punkt"):
155 if ltype == 'czytelnia':
156 return '<p>W przygotowaniu.</p>'
159 if ltype == 'slowniczek':
160 surl = element.attrib.get('src', None)
162 # print '** missing src on <slowniczek>, setting default'
163 surl = 'http://edukacjamedialna.edu.pl/lekcje/slowniczek/'
166 sxml = etree.fromstring(self.options['provider'].by_uri(surl).get_string())
167 self.options = {'slowniczek': True, 'slowniczek_xml': sxml }
168 pre, post = '<div class="slowniczek">', '</div>'
169 if self.options['wldoc'].book_info.url.slug != 'slowniczek':
170 post += u'<p class="see-more"><a href="%s">Zobacz cały słowniczek.</a></p>' % surl
173 listtag = {'num': 'ol',
176 'czytelnia': 'ul'}[ltype]
178 classes = attrs.get('class', '')
179 if classes: del attrs['class']
181 attrs_s = ' '.join(['%s="%s"' % kv for kv in attrs.items()])
182 if attrs_s: attrs_s = ' ' + attrs_s
184 return '<%s class="lista %s %s"%s>' % (listtag, ltype, classes, attrs_s), '</%s>' % listtag
186 def handle_punkt(self, element):
187 if self.options['slowniczek']:
188 return '<dl>', '</dl>'
190 return '<li>', '</li>'
192 def handle_definiendum(self, element):
193 nxt = element.getnext()
197 print "!! Empty <definiendum/>"
200 # let's pull definiens from another document
201 if self.options['slowniczek_xml'] is not None and (nxt is None or nxt.tag != 'definiens'):
202 sxml = self.options['slowniczek_xml']
203 defloc = sxml.xpath("//definiendum[text()='%s']" % element.text)
205 definiens = defloc[0].getnext()
206 if definiens.tag == 'definiens':
207 subgen = EduModule(self.options)
208 definiens_s = subgen.generate(definiens)
210 print '!! Missing definiendum in source:', element.text
212 return u"<dt>", u"</dt>" + definiens_s
214 def handle_definiens(self, element):
215 return u"<dd>", u"</dd>"
217 def handle_podpis(self, element):
218 return u"""<div class="caption">""", u"</div>"
220 def handle_tabela(self, element):
221 has_frames = int(element.attrib.get("ramki", "0"))
222 if has_frames: frames_c = "framed"
224 return u"""<table class="%s">""" % frames_c, u"</table>"
226 def handle_wiersz(self, element):
227 return u"<tr>", u"</tr>"
229 def handle_kol(self, element):
230 return u"<td>", u"</td>"
232 def handle_rdf__RDF(self, _):
233 # ustal w opcjach rzeczy :D
236 def handle_link(self, element):
237 if 'url' in element.attrib:
238 return tag('a', href=element.attrib['url'])(self, element)
239 elif 'material' in element.attrib:
240 material_err = u' [BRAKUJĄCY MATERIAŁ]'
241 slug = element.attrib['material']
242 make_url = lambda f: self.options['urlmapper'] \
243 .url_for_material(slug, f)
245 if 'format' in element.attrib:
246 formats = re.split(r"[, ]+",
247 element.attrib['format'])
251 formats = self.options['urlmapper'].materials(slug)
254 def_href = make_url(formats[0][0])
256 except (IndexError, self.options['urlmapper'].MaterialNotFound):
257 def_err = material_err
260 for f in formats[1:]:
262 fmt_links.append(u'<a href="%s">%s</a>' % (make_url(f[0]), f[0].upper()))
263 except self.options['urlmapper'].MaterialNotFound:
264 fmt_links.append(u'<a>%s%s</a>' % (f[0].upper(), material_err))
265 more_links = u' (%s)' % u', '.join(fmt_links) if fmt_links else u''
267 return u"<a href='%s'>" % def_href, u'%s</a>%s' % (def_err, more_links)
269 def handle_obraz(self, element):
270 name = element.attrib.get('nazwa', '').strip()
272 print '!! <obraz> missing "nazwa"'
274 alt = element.attrib.get('alt', '')
276 print '** <obraz> missing "alt"'
277 slug, ext = name.rsplit('.', 1)
278 url = self.options['urlmapper'].url_for_image(slug, ext)
279 thumb_url = self.options['urlmapper'].url_for_image(slug, ext, IMAGE_THUMB_WIDTH)
280 e = etree.Element("a", attrib={"href": url, "class": "image"})
281 e.append(etree.Element("img", attrib={"src": thumb_url, "alt": alt,
282 "width": str(IMAGE_THUMB_WIDTH)}))
283 return etree.tostring(e, encoding=unicode), u""
285 def handle_video(self, element):
286 url = element.attrib.get('url')
288 print '!! <video> missing url'
290 m = re.match(r'(?:https?://)?(?:www.)?youtube.com/watch\?(?:.*&)?v=([^&]+)(?:$|&)', url)
292 print '!! unknown <video> url scheme:', url
294 return """<iframe width="630" height="384" src="http://www.youtube.com/embed/%s"
295 frameborder="0" allowfullscreen></iframe>""" % m.group(1), ""
298 class Exercise(EduModule):
300 def __init__(self, *args, **kw):
301 self.question_counter = 0
302 super(Exercise, self).__init__(*args, **kw)
303 self.instruction_printed = False
305 @tagged('div', 'description')
306 def handle_opis(self, element):
307 return "", self.get_instruction()
309 def handle_rozw_kom(self, element):
310 return u"""<div style="display:none" class="comment">""", u"""</div>"""
312 def handle_cwiczenie(self, element):
313 self.options = {'exercise': element.attrib['typ']}
314 self.question_counter = 0
315 self.piece_counter = 0
318 <div class="exercise %(typ)s" data-type="%(typ)s">
319 <form action="#" method="POST">
320 <h3>Zadanie %(exercies_counter)d</h3>
321 <div class="buttons">
322 <span class="message"></span>
323 <input type="button" class="check" value="sprawdź"/>
324 <input type="button" class="retry" style="display:none" value="spróbuj ponownie"/>
325 <input type="button" class="solutions" value="pokaż rozwiązanie"/>
326 <input type="button" class="reset" value="reset"/>
329 """ % {'exercies_counter': self.options['exercise_counter'], 'typ': element.attrib['typ']}
331 <div class="buttons">
332 <span class="message"></span>
333 <input type="button" class="check" value="sprawdź"/>
334 <input type="button" class="retry" style="display:none" value="spróbuj ponownie"/>
335 <input type="button" class="solutions" value="pokaż rozwiązanie"/>
336 <input type="button" class="reset" value="reset"/>
341 # Add a single <pytanie> tag if it's not there
342 if not element.xpath(".//pytanie"):
343 qpre, qpost = self.handle_pytanie(element)
348 def handle_pytanie(self, element):
349 """This will handle <cwiczenie> element, when there is no <pytanie>
352 self.question_counter += 1
353 self.piece_counter = 0
354 solution = element.attrib.get('rozw', None)
355 if solution: solution_s = ' data-solution="%s"' % solution
356 else: solution_s = ''
358 handles = element.attrib.get('uchwyty', None)
360 add_class += ' handles handles-%s' % handles
361 self.options = {'handles': handles}
363 minimum = element.attrib.get('min', None)
364 if minimum: minimum_s = ' data-minimum="%d"' % int(minimum)
367 return '<div class="question%s" data-no="%d" %s>' %\
368 (add_class, self.question_counter, solution_s + minimum_s), \
371 def get_instruction(self):
372 if not self.instruction_printed:
373 self.instruction_printed = True
375 return u'<span class="instruction">%s</span>' % self.INSTRUCTION
383 class Wybor(Exercise):
384 def handle_cwiczenie(self, element):
385 pre, post = super(Wybor, self).handle_cwiczenie(element)
386 is_single_choice = True
387 pytania = element.xpath(".//pytanie")
391 solutions = re.split(r"[, ]+", p.attrib['rozw'])
392 if len(solutions) != 1:
393 is_single_choice = False
395 choices = p.xpath(".//*[@nazwa]")
397 for n in choices: uniq.add(n.attrib['nazwa'])
398 if len(choices) != len(uniq):
399 is_single_choice = False
402 self.options = {'single': is_single_choice}
405 def handle_punkt(self, element):
406 if self.options['exercise'] and element.attrib.get('nazwa', None):
407 qc = self.question_counter
408 self.piece_counter += 1
409 no = self.piece_counter
410 eid = "q%(qc)d_%(no)d" % locals()
411 aname = element.attrib.get('nazwa', None)
412 if self.options['single']:
414 <li class="question-piece" data-qc="%(qc)d" data-no="%(no)d" data-name="%(aname)s">
415 <input type="radio" name="q%(qc)d" id="%(eid)s" value="%(aname)s" />
416 <label for="%(eid)s">
417 """ % locals(), u"</label></li>"
420 <li class="question-piece" data-qc="%(qc)d" data-no="%(no)d" data-name="%(aname)s">
421 <input type="checkbox" name="%(eid)s" id="%(eid)s" />
422 <label for="%(eid)s">
423 """ % locals(), u"</label></li>"
426 return super(Wybor, self).handle_punkt(element)
429 class Uporzadkuj(Exercise):
430 INSTRUCTION = u"Kliknij wybraną odpowiedź i przeciągnij w nowe miejsce."
432 def handle_pytanie(self, element):
434 Overrides the returned content default handle_pytanie
436 # we ignore the result, returning our own
437 super(Uporzadkuj, self).handle_pytanie(element)
438 order_items = element.xpath(".//punkt/@rozw")
440 return u"""<div class="question" data-original="%s" data-no="%s">""" % \
441 (','.join(order_items), self.question_counter), \
444 def handle_punkt(self, element):
445 return """<li class="question-piece" data-pos="%(rozw)s"/>""" \
450 class Luki(Exercise):
451 INSTRUCTION = u"Przeciągnij odpowiedzi i upuść w wybranym polu."
452 def find_pieces(self, question):
453 return question.xpath(".//luka")
455 def solution_html(self, piece):
456 piece = deepcopy(piece)
459 return sub.generate(piece)
461 def handle_pytanie(self, element):
462 qpre, qpost = super(Luki, self).handle_pytanie(element)
464 luki = list(enumerate(self.find_pieces(element)))
468 for (i, luka) in luki:
470 luka_html = self.solution_html(luka)
471 luki_html += u'<span class="draggable question-piece" data-no="%d">%s</span>' % (i, luka_html)
472 self.words_html = '<div class="words">%s</div>' % luki_html
476 def handle_opis(self, element):
477 return '', self.words_html
479 def handle_luka(self, element):
480 self.piece_counter += 1
481 return '<span class="placeholder" data-solution="%d"></span>' % self.piece_counter
485 INSTRUCTION = u"Przeciągnij odpowiedzi i upuść je na słowie lub wyrażeniu, które chcesz zastąpić."
487 def find_pieces(self, question):
488 return question.xpath(".//zastap")
490 def solution_html(self, piece):
491 return piece.attrib['rozw']
493 def handle_zastap(self, element):
494 self.piece_counter += 1
495 return '<span class="placeholder zastap question-piece" data-solution="%d">' \
496 % self.piece_counter, '</span>'
499 class Przyporzadkuj(Exercise):
500 INSTRUCTION = [u"Przeciągnij odpowiedzi i upuść w wybranym polu.",
501 u"Kliknij numer odpowiedzi, przeciągnij i upuść w wybranym polu."]
503 def get_instruction(self):
504 if not self.instruction_printed:
505 self.instruction_printed = True
506 return u'<span class="instruction">%s</span>' % self.INSTRUCTION[self.options['handles'] and 1 or 0]
510 def handle_cwiczenie(self, element):
511 pre, post = super(Przyporzadkuj, self).handle_cwiczenie(element)
512 lista_with_handles = element.xpath(".//*[@uchwyty]")
513 if lista_with_handles:
514 self.options = {'handles': True}
517 def handle_pytanie(self, element):
518 pre, post = super(Przyporzadkuj, self).handle_pytanie(element)
519 minimum = element.attrib.get("min", None)
521 self.options = {"min": int(minimum)}
524 def handle_lista(self, lista):
525 if 'nazwa' in lista.attrib:
527 'data-name': lista.attrib['nazwa'],
530 self.options = {'predicate': True}
531 elif 'cel' in lista.attrib:
533 'data-target': lista.attrib['cel'],
536 self.options = {'subject': True}
539 pre, post = super(Przyporzadkuj, self).handle_lista(lista, attrs)
540 return pre, post + '<br class="clr"/>'
542 def handle_punkt(self, element):
543 if self.options['subject']:
544 self.piece_counter += 1
545 if self.options['handles']:
546 return '<li><span data-solution="%s" data-no="%s" class="question-piece draggable handle add-li">%s</span>' % (element.attrib['rozw'], self.piece_counter, self.piece_counter), '</li>'
548 return '<li data-solution="%s" data-no="%s" class="question-piece draggable">' % (element.attrib['rozw'], self.piece_counter), '</li>'
550 elif self.options['predicate']:
551 if self.options['min']:
552 placeholders = u'<li class="placeholder"/>' * self.options['min']
554 placeholders = u'<li class="placeholder multiple"/>'
555 return '<li data-predicate="%(nazwa)s">' % element.attrib, '<ul class="subjects">' + placeholders + '</ul></li>'
558 return super(Przyporzadkuj, self).handle_punkt(element)
561 class PrawdaFalsz(Exercise):
562 def handle_punkt(self, element):
563 if 'rozw' in element.attrib:
564 return u'''<li data-solution="%s" class="question-piece">
565 <span class="buttons">
566 <a href="#" data-value="true" class="true">Prawda</a>
567 <a href="#" data-value="false" class="false">Fałsz</a>
568 </span>''' % {'prawda': 'true', 'falsz': 'false'}[element.attrib['rozw']], '</li>'
570 return super(PrawdaFalsz, self).handle_punkt(element)
573 class EduModuleFormat(Format):
574 PRIMARY_MATERIAL_FORMATS = ('pdf', 'odt')
576 class MaterialNotFound(BaseException):
579 def __init__(self, wldoc, **kwargs):
580 super(EduModuleFormat, self).__init__(wldoc, **kwargs)
583 # Sort materials by slug.
584 self.materials_by_slug = {}
585 for name, att in self.wldoc.source.attachments.items():
586 parts = name.rsplit('.', 1)
590 if slug not in self.materials_by_slug:
591 self.materials_by_slug[slug] = {}
592 self.materials_by_slug[slug][ext] = att
594 edumod = EduModule({'provider': self.wldoc.provider, 'urlmapper': self, 'wldoc': self.wldoc})
596 html = edumod.generate(self.wldoc.edoc.getroot())
598 return IOFile.from_string(html.encode('utf-8'))
600 def materials(self, slug):
601 """Returns a list of pairs: (ext, iofile)."""
602 order = dict(reversed(k) for k in enumerate(self.PRIMARY_MATERIAL_FORMATS))
603 mats = self.materials_by_slug.get(slug, {}).items()
605 print "!! Material missing: '%s'" % slug
606 return sorted(mats, key=lambda (x, y): order.get(x, x))
608 def url_for_material(self, slug, fmt):
609 return "%s.%s" % (slug, fmt)
611 def url_for_image(self, slug, fmt, width=None):
612 return self.url_for_material(self, slug, fmt)
615 def transform(wldoc, stylesheet='edumed', options=None, flags=None):
616 """Transforms the WL document to XHTML.
618 If output_filename is None, returns an XML,
619 otherwise returns True if file has been written,False if it hasn't.
620 File won't be written if it has no content.
622 edumodfor = EduModuleFormat(wldoc)
623 return edumodfor.build()