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.activity_last = None
21 self.exercise_counter = 0
24 def swap_endlines(txt):
25 if self.options['strofa']:
26 txt = txt.replace("/\n", "<br/>\n")
28 self.register_text_filter(functions.substitute_entities)
29 self.register_escaped_text_filter(swap_endlines)
31 @tagged('div', 'stanza')
32 def handle_strofa(self, element):
33 self.options = {'strofa': True}
36 def handle_powiesc(self, element):
38 <div class="module" id="book-text">
39 <!-- <span class="teacher-toggle">
40 <input type="checkbox" name="teacher-toggle" id="teacher-toggle"/>
41 <label for="teacher-toggle">Pokaż treść dla nauczyciela</label>
46 handle_autor_utworu = tag("span", "author")
47 handle_dzielo_nadrzedne = tag("span", "collection")
48 handle_podtytul = tag("span", "subtitle")
49 handle_naglowek_akt = handle_naglowek_czesc = handle_srodtytul = tag("h2")
50 handle_naglowek_scena = tag('h2')
51 handle_naglowek_osoba = tag('h3')
52 handle_akap = handle_akap_dialog = handle_akap_cd = tag('p', 'paragraph')
54 handle_wyroznienie = tag('em')
55 handle_tytul_dziela = tag('em', 'title')
56 handle_slowo_obce = tag('em', 'foreign')
58 def naglowek_to_anchor(self, naglowek):
59 return self.options['urlmapper'].naglowek_to_anchor(naglowek)
61 def handle_nazwa_utworu(self, element):
63 for naglowek in element.getparent().findall('.//naglowek_rozdzial'):
64 a = etree.Element("a")
65 a.attrib["href"] = "#" + self.naglowek_to_anchor(naglowek)
66 a.text = naglowek.text
67 atxt = etree.tostring(a, encoding=unicode)
68 toc.append("<li>%s</li>" % atxt)
69 toc = "<ul class='toc'>%s</ul>" % "".join(toc)
70 add_header = "Lekcja: " if self.options['wldoc'].book_info.type in ('course', 'synthetic') else ''
71 return "<h1 class='title' id='top'>%s" % add_header, "</h1>" + toc
73 def handle_naglowek_rozdzial(self, element):
74 return_to_top = u"<a href='#top' class='top-link'>wróć do spisu treści</a>"
75 pre, post = tag_open_close("h2", id=self.naglowek_to_anchor(element))
76 url = self.options['urlmapper'].get_help_url(element)
78 post = " <a class='help' href='%s'>?</a>" % (url,) + post
79 return return_to_top + pre, post
81 def handle_naglowek_podrozdzial(self, element):
82 self.activity_counter = 0
83 return tag('h3')(self, element)
85 def handle_uwaga(self, _e):
88 def handle_aktywnosc(self, element):
89 self.activity_counter += 1
92 'activity_counter': self.activity_counter,
94 submill = EduModule(dict(self.options.items() + {'sub_gen': True}.items()))
96 if element.xpath('opis'):
97 opis = submill.generate(element.xpath('opis')[0])
101 n = element.xpath('wskazowki')
102 if n: wskazowki = submill.generate(n[0])
105 n = element.xpath('pomoce')
107 if n: pomoce = submill.generate(n[0])
110 forma = ''.join(element.xpath('forma/text()'))
111 get_forma_url = self.options['urlmapper'].get_forma_url
113 for form_name in forma.split(','):
114 name = form_name.strip()
115 url = get_forma_url(name)
117 forms.append("<a href='%s'>%s</a>" % (url, name))
120 forma = ', '.join(forms)
122 forma = '<section class="infobox kind"><h1>Metoda</h1><p>%s</p></section>' % forma
124 czas = ''.join(element.xpath('czas/text()'))
126 czas = '<section class="infobox time"><h1>Czas</h1><p>%s min</p></section>' % czas
128 counter = self.activity_counter
130 if element.getnext().tag == 'aktywnosc' or self.activity_last.getnext() == element:
131 counter_html = """<span class="act_counter">%(counter)d.</span>""" % locals()
135 self.activity_last = element
138 <div class="activity">
141 %(opis)s""" % locals(), \
149 <div class="clearboth"></div>
153 handle_opis = ifoption(sub_gen=True)(tag('div', 'description'))
154 handle_wskazowki = ifoption(sub_gen=True)(tag('div', ('hints', 'teacher')))
156 @ifoption(sub_gen=True)
157 @tagged('section', 'infobox materials')
158 def handle_pomoce(self, _):
159 return """<h1>Pomoce</h1>""", ""
161 def handle_czas(self, *_):
164 def handle_forma(self, *_):
167 def handle_cwiczenie(self, element):
168 exercise_handlers = {
170 'uporzadkuj': Uporzadkuj,
173 'przyporzadkuj': Przyporzadkuj,
174 'prawdafalsz': PrawdaFalsz
177 typ = element.attrib['typ']
178 self.exercise_counter += 1
179 self.options = {'exercise_counter': self.exercise_counter}
180 handler = exercise_handlers[typ](self.options)
181 return handler.generate(element)
184 def handle_lista(self, element, attrs={}):
185 ltype = element.attrib.get('typ', 'punkt')
186 if not element.findall("punkt"):
187 if ltype == 'czytelnia':
188 return '<p>W przygotowaniu.</p>'
191 if ltype == 'slowniczek':
192 surl = element.attrib.get('src', None)
194 # print '** missing src on <slowniczek>, setting default'
195 surl = 'http://edukacjamedialna.edu.pl/lekcje/slowniczek/'
196 sxml = etree.fromstring(self.options['provider'].by_uri(surl).get_string())
198 self.options = {'slowniczek': True, 'slowniczek_xml': sxml }
199 pre, post = '<div class="slowniczek">', '</div>'
200 if not self.options['wldoc'].book_info.url.slug.startswith('slowniczek'):
201 post += u'<p class="see-more"><a href="%s">Zobacz cały słowniczek.</a></p>' % surl
204 listtag = {'num': 'ol',
207 'czytelnia': 'ul'}[ltype]
209 classes = attrs.get('class', '')
210 if classes: del attrs['class']
212 attrs_s = ' '.join(['%s="%s"' % kv for kv in attrs.items()])
213 if attrs_s: attrs_s = ' ' + attrs_s
215 return '<%s class="lista %s %s"%s>' % (listtag, ltype, classes, attrs_s), '</%s>' % listtag
217 def handle_punkt(self, element):
218 if self.options['slowniczek']:
219 return '<dl>', '</dl>'
221 return '<li>', '</li>'
223 def handle_definiendum(self, element):
224 nxt = element.getnext()
228 print "!! Empty <definiendum/>"
231 # let's pull definiens from another document
232 if self.options['slowniczek_xml'] is not None and (nxt is None or nxt.tag != 'definiens'):
233 sxml = self.options['slowniczek_xml']
234 if "'" in (element.text or ''):
235 defloc = sxml.xpath("//definiendum[text()=\"%s\"]" % (element.text or '').strip())
237 defloc = sxml.xpath("//definiendum[text()='%s']" % (element.text or '').strip())
239 definiens = defloc[0].getnext()
240 if definiens.tag == 'definiens':
241 subgen = EduModule(self.options)
242 definiens_s = subgen.generate(definiens)
244 print "!! Missing definiendum in source: '%s'" % element.text
246 return u"<dt id='%s'>" % self.naglowek_to_anchor(element), u"</dt>" + definiens_s
248 def handle_definiens(self, element):
249 return u"<dd>", u"</dd>"
251 def handle_podpis(self, element):
252 return u"""<div class="caption">""", u"</div>"
254 def handle_tabela(self, element):
255 has_frames = int(element.attrib.get("ramki", "0"))
256 if has_frames: frames_c = "framed"
258 return u"""<table class="%s">""" % frames_c, u"</table>"
260 def handle_wiersz(self, element):
261 return u"<tr>", u"</tr>"
263 def handle_kol(self, element):
264 return u"<td>", u"</td>"
266 def handle_rdf__RDF(self, _):
267 # ustal w opcjach rzeczy :D
270 def handle_link(self, element):
271 if 'url' in element.attrib:
272 return tag('a', href=element.attrib['url'])(self, element)
273 elif 'material' in element.attrib:
274 material_err = u' [BRAKUJĄCY MATERIAŁ]'
275 slug = element.attrib['material']
276 make_url = lambda f: self.options['urlmapper'] \
277 .url_for_material(slug, f)
279 if 'format' in element.attrib:
280 formats = re.split(r"[, ]+",
281 element.attrib['format'])
285 formats = self.options['urlmapper'].materials(slug)
288 def_href = make_url(formats[0][0])
290 except (IndexError, self.options['urlmapper'].MaterialNotFound):
291 def_err = material_err
294 for f in formats[1:]:
296 fmt_links.append(u'<a href="%s">%s</a>' % (make_url(f[0]), f[0].upper()))
297 except self.options['urlmapper'].MaterialNotFound:
298 fmt_links.append(u'<a>%s%s</a>' % (f[0].upper(), material_err))
299 more_links = u' (%s)' % u', '.join(fmt_links) if fmt_links else u''
301 return u"<a href='%s'>" % def_href, u'%s</a>%s' % (def_err, more_links)
303 def handle_obraz(self, element):
304 name = element.attrib.get('nazwa', '').strip()
306 print '!! <obraz> missing "nazwa"'
308 alt = element.attrib.get('alt', '')
310 print '** <obraz> missing "alt"'
311 slug, ext = name.rsplit('.', 1)
312 url = self.options['urlmapper'].url_for_image(slug, ext)
313 thumb_url = self.options['urlmapper'].url_for_image(slug, ext, IMAGE_THUMB_WIDTH)
314 e = etree.Element("a", attrib={"href": url, "class": "image"})
315 e.append(etree.Element("img", attrib={"src": thumb_url, "alt": alt,
316 "width": str(IMAGE_THUMB_WIDTH)}))
317 return etree.tostring(e, encoding=unicode), u""
319 def handle_video(self, element):
320 url = element.attrib.get('url')
322 print '!! <video> missing url'
324 m = re.match(r'(?:https?://)?(?:www.)?youtube.com/watch\?(?:.*&)?v=([^&]+)(?:$|&)', url)
326 print '!! unknown <video> url scheme:', url
328 return """<iframe width="630" height="384" src="http://www.youtube.com/embed/%s"
329 frameborder="0" allowfullscreen></iframe>""" % m.group(1), ""
332 class Exercise(EduModule):
334 def __init__(self, *args, **kw):
335 self.question_counter = 0
336 super(Exercise, self).__init__(*args, **kw)
337 self.instruction_printed = False
339 @tagged('div', 'description')
340 def handle_opis(self, element):
341 return "", self.get_instruction()
343 def handle_rozw_kom(self, element):
344 return u"""<div style="display:none" class="comment">""", u"""</div>"""
346 def handle_cwiczenie(self, element):
347 self.options = {'exercise': element.attrib['typ']}
348 self.question_counter = 0
349 self.piece_counter = 0
352 <div class="exercise %(typ)s" data-type="%(typ)s">
353 <form action="#" method="POST">
354 <h3>Zadanie %(exercies_counter)d</h3>
355 <div class="buttons">
356 <span class="message"></span>
357 <input type="button" class="check" value="sprawdź"/>
358 <input type="button" class="retry" style="display:none" value="spróbuj ponownie"/>
359 <input type="button" class="solutions" value="pokaż rozwiązanie"/>
360 <input type="button" class="reset" value="reset"/>
363 """ % {'exercies_counter': self.options['exercise_counter'], 'typ': element.attrib['typ']}
365 <div class="buttons">
366 <span class="message"></span>
367 <input type="button" class="check" value="sprawdź"/>
368 <input type="button" class="retry" style="display:none" value="spróbuj ponownie"/>
369 <input type="button" class="solutions" value="pokaż rozwiązanie"/>
370 <input type="button" class="reset" value="reset"/>
375 # Add a single <pytanie> tag if it's not there
376 if not element.xpath(".//pytanie"):
377 qpre, qpost = self.handle_pytanie(element)
382 def handle_pytanie(self, element):
383 """This will handle <cwiczenie> element, when there is no <pytanie>
386 self.question_counter += 1
387 self.piece_counter = 0
388 solution = element.attrib.get('rozw', None)
389 if solution: solution_s = ' data-solution="%s"' % solution
390 else: solution_s = ''
392 handles = element.attrib.get('uchwyty', None)
394 add_class += ' handles handles-%s' % handles
395 self.options = {'handles': handles}
397 minimum = element.attrib.get('min', None)
398 if minimum: minimum_s = ' data-minimum="%d"' % int(minimum)
401 return '<div class="question%s" data-no="%d" %s>' %\
402 (add_class, self.question_counter, solution_s + minimum_s), \
405 def get_instruction(self):
406 if not self.instruction_printed:
407 self.instruction_printed = True
409 return u'<span class="instruction">%s</span>' % self.INSTRUCTION
417 class Wybor(Exercise):
418 def handle_cwiczenie(self, element):
419 pre, post = super(Wybor, self).handle_cwiczenie(element)
420 is_single_choice = True
421 pytania = element.xpath(".//pytanie")
425 solutions = re.split(r"[, ]+", p.attrib.get('rozw', ''))
426 if len(solutions) != 1:
427 is_single_choice = False
429 choices = p.xpath(".//*[@nazwa]")
431 for n in choices: uniq.add(n.attrib.get('nazwa', ''))
432 if len(choices) != len(uniq):
433 is_single_choice = False
436 self.options = {'single': is_single_choice}
439 def handle_punkt(self, element):
440 if self.options['exercise'] and element.attrib.get('nazwa', None):
441 qc = self.question_counter
442 self.piece_counter += 1
443 no = self.piece_counter
444 eid = "q%(qc)d_%(no)d" % locals()
445 aname = element.attrib.get('nazwa', None)
446 if self.options['single']:
448 <li class="question-piece" data-qc="%(qc)d" data-no="%(no)d" data-name="%(aname)s">
449 <input type="radio" name="q%(qc)d" id="%(eid)s" value="%(aname)s" />
450 <label for="%(eid)s">
451 """ % locals(), u"</label></li>"
454 <li class="question-piece" data-qc="%(qc)d" data-no="%(no)d" data-name="%(aname)s">
455 <input type="checkbox" name="%(eid)s" id="%(eid)s" />
456 <label for="%(eid)s">
457 """ % locals(), u"</label></li>"
460 return super(Wybor, self).handle_punkt(element)
463 class Uporzadkuj(Exercise):
464 INSTRUCTION = u"Kliknij wybraną odpowiedź i przeciągnij w nowe miejsce."
466 def handle_pytanie(self, element):
468 Overrides the returned content default handle_pytanie
470 # we ignore the result, returning our own
471 super(Uporzadkuj, self).handle_pytanie(element)
472 order_items = element.xpath(".//punkt/@rozw")
474 return u"""<div class="question" data-original="%s" data-no="%s">""" % \
475 (','.join(order_items), self.question_counter), \
478 def handle_punkt(self, element):
479 return """<li class="question-piece" data-pos="%(rozw)s">""" \
484 class Luki(Exercise):
485 INSTRUCTION = u"Przeciągnij odpowiedzi i upuść w wybranym polu."
486 def find_pieces(self, question):
487 return question.xpath(".//luka")
489 def solution_html(self, piece):
490 piece = deepcopy(piece)
493 return sub.generate(piece)
495 def handle_pytanie(self, element):
496 qpre, qpost = super(Luki, self).handle_pytanie(element)
498 luki = list(enumerate(self.find_pieces(element)))
502 for (i, luka) in luki:
504 luka_html = self.solution_html(luka)
505 luki_html += u'<span class="draggable question-piece" data-no="%d">%s</span>' % (i, luka_html)
506 self.words_html = '<div class="words">%s</div>' % luki_html
510 def handle_opis(self, element):
511 return '', self.words_html
513 def handle_luka(self, element):
514 self.piece_counter += 1
515 return '<span class="placeholder" data-solution="%d"></span>' % self.piece_counter
519 INSTRUCTION = u"Przeciągnij odpowiedzi i upuść je na słowie lub wyrażeniu, które chcesz zastąpić."
521 def find_pieces(self, question):
522 return question.xpath(".//zastap")
524 def solution_html(self, piece):
525 return piece.attrib.get('rozw', '')
527 def handle_zastap(self, element):
528 self.piece_counter += 1
529 return '<span class="placeholder zastap question-piece" data-solution="%d">' \
530 % self.piece_counter, '</span>'
533 class Przyporzadkuj(Exercise):
534 INSTRUCTION = [u"Przeciągnij odpowiedzi i upuść w wybranym polu.",
535 u"Kliknij numer odpowiedzi, przeciągnij i upuść w wybranym polu."]
537 def get_instruction(self):
538 if not self.instruction_printed:
539 self.instruction_printed = True
540 return u'<span class="instruction">%s</span>' % self.INSTRUCTION[self.options['handles'] and 1 or 0]
544 def handle_cwiczenie(self, element):
545 pre, post = super(Przyporzadkuj, self).handle_cwiczenie(element)
546 lista_with_handles = element.xpath(".//*[@uchwyty]")
547 if lista_with_handles:
548 self.options = {'handles': True}
551 def handle_pytanie(self, element):
552 pre, post = super(Przyporzadkuj, self).handle_pytanie(element)
553 minimum = element.attrib.get("min", None)
555 self.options = {"min": int(minimum)}
558 def handle_lista(self, lista):
559 if 'nazwa' in lista.attrib:
561 'data-name': lista.attrib['nazwa'],
564 self.options = {'predicate': True}
565 elif 'cel' in lista.attrib:
567 'data-target': lista.attrib['cel'],
570 if lista.attrib.get('krotkie'):
571 self.options = {'short': True}
572 self.options = {'subject': True}
575 pre, post = super(Przyporzadkuj, self).handle_lista(lista, attrs)
576 return pre, post + '<br class="clr"/>'
578 def handle_punkt(self, element):
579 if self.options['subject']:
580 self.piece_counter += 1
581 if self.options['handles']:
582 return '<li><span data-solution="%s" data-no="%s" class="question-piece draggable handle add-li">%s</span>' % (element.attrib.get('rozw', ''), self.piece_counter, self.piece_counter), '</li>'
585 if self.options['short']:
586 extra_class += ' short'
587 return '<li data-solution="%s" data-no="%s" class="question-piece draggable%s">' % (element.attrib.get('rozw', ''), self.piece_counter, extra_class), '</li>'
589 elif self.options['predicate']:
590 if self.options['min']:
591 placeholders = u'<li class="placeholder"></li>' * self.options['min']
593 placeholders = u'<li class="placeholder multiple"></li>'
594 return '<li data-predicate="%s">' % element.attrib.get('nazwa', ''), '<ul class="subjects">' + placeholders + '</ul></li>'
597 return super(Przyporzadkuj, self).handle_punkt(element)
600 class PrawdaFalsz(Exercise):
601 def handle_punkt(self, element):
602 if 'rozw' in element.attrib:
603 return u'''<li data-solution="%s" class="question-piece">
604 <span class="buttons">
605 <a href="#" data-value="true" class="true">Prawda</a>
606 <a href="#" data-value="false" class="false">Fałsz</a>
607 </span>''' % {'prawda': 'true', 'falsz': 'false'}[element.attrib['rozw']], '</li>'
609 return super(PrawdaFalsz, self).handle_punkt(element)
612 class EduModuleFormat(Format):
613 PRIMARY_MATERIAL_FORMATS = ('pdf', 'odt')
615 class MaterialNotFound(BaseException):
618 def __init__(self, wldoc, **kwargs):
619 super(EduModuleFormat, self).__init__(wldoc, **kwargs)
622 # Sort materials by slug.
623 self.materials_by_slug = {}
624 for name, att in self.wldoc.source.attachments.items():
625 parts = name.rsplit('.', 1)
629 if slug not in self.materials_by_slug:
630 self.materials_by_slug[slug] = {}
631 self.materials_by_slug[slug][ext] = att
633 edumod = EduModule({'provider': self.wldoc.provider, 'urlmapper': self, 'wldoc': self.wldoc})
635 html = edumod.generate(self.wldoc.edoc.getroot())
637 return IOFile.from_string(html.encode('utf-8'))
639 def materials(self, slug):
640 """Returns a list of pairs: (ext, iofile)."""
641 order = dict(reversed(k) for k in enumerate(self.PRIMARY_MATERIAL_FORMATS))
642 mats = self.materials_by_slug.get(slug, {}).items()
644 print "!! Material missing: '%s'" % slug
645 return sorted(mats, key=lambda (x, y): order.get(x, x))
647 def url_for_material(self, slug, fmt):
648 return "%s.%s" % (slug, fmt)
650 def url_for_image(self, slug, fmt, width=None):
651 return self.url_for_material(self, slug, fmt)
653 def text_to_anchor(self, text):
654 return re.sub(r" +", " ", text)
656 def naglowek_to_anchor(self, naglowek):
657 return self.text_to_anchor(naglowek.text.strip())
659 def get_forma_url(self, forma):
662 def get_help_url(self, naglowek):
666 def transform(wldoc, stylesheet='edumed', options=None, flags=None, verbose=None):
667 """Transforms the WL document to XHTML.
669 If output_filename is None, returns an XML,
670 otherwise returns True if file has been written,False if it hasn't.
671 File won't be written if it has no content.
673 edumodfor = EduModuleFormat(wldoc)
674 return edumodfor.build()