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
14 class EduModule(Xmill):
15 def __init__(self, options=None):
16 super(EduModule, self).__init__(options)
17 self.activity_counter = 0
18 self.exercise_counter = 0
21 def swap_endlines(txt):
22 if self.options['strofa']:
23 txt = txt.replace("/\n", "<br/>\n")
25 self.register_text_filter(functions.substitute_entities)
26 self.register_text_filter(swap_endlines)
28 @tagged('div', 'stanza')
29 def handle_strofa(self, element):
30 self.options = {'strofa': True}
33 def handle_powiesc(self, element):
35 <div class="module" id="book-text">
36 <!-- <span class="teacher-toggle">
37 <input type="checkbox" name="teacher-toggle" id="teacher-toggle"/>
38 <label for="teacher-toggle">Pokaż treść dla nauczyciela</label>
43 handle_autor_utworu = tag("span", "author")
44 handle_dzielo_nadrzedne = tag("span", "collection")
45 handle_podtytul = tag("span", "subtitle")
46 handle_naglowek_akt = handle_naglowek_czesc = handle_srodtytul = tag("h2")
47 handle_naglowek_scena = tag('h2')
48 handle_naglowek_osoba = handle_naglowek_podrozdzial = tag('h3')
49 handle_akap = handle_akap_dialog = handle_akap_cd = tag('p', 'paragraph')
51 handle_wyroznienie = tag('em')
52 handle_tytul_dziela = tag('em', 'title')
53 handle_slowo_obce = tag('em', 'foreign')
55 def naglowek_to_anchor(self, naglowek):
56 return re.sub(r" +", " ", naglowek.text.strip())
58 def handle_nazwa_utworu(self, element):
60 for naglowek in element.getparent().findall('.//naglowek_rozdzial'):
61 a = etree.Element("a")
62 a.attrib["href"] = "#" + self.naglowek_to_anchor(naglowek)
63 a.text = naglowek.text
64 atxt = etree.tostring(a, encoding=unicode)
65 toc.append("<li>%s</li>" % atxt)
66 toc = "<ul class='toc'>%s</ul>" % "".join(toc)
67 add_header = "Lekcja: " if self.options['wldoc'].book_info.type in ('course', 'synthetic') else ''
68 return "<h1 class='title'>%s" % add_header, "</h1>" + toc
71 def handle_naglowek_rozdzial(self, element):
72 return "", "".join(tag_open_close("a", name=self.naglowek_to_anchor(element)))
74 def handle_uwaga(self, _e):
77 def handle_aktywnosc(self, element):
78 self.activity_counter += 1
81 'activity_counter': self.activity_counter,
83 submill = EduModule(dict(self.options.items() + {'sub_gen': True}.items()))
85 opis = submill.generate(element.xpath('opis')[0])
87 n = element.xpath('wskazowki')
88 if n: wskazowki = submill.generate(n[0])
91 n = element.xpath('pomoce')
93 if n: pomoce = submill.generate(n[0])
96 forma = ''.join(element.xpath('forma/text()'))
98 czas = ''.join(element.xpath('czas/text()'))
100 counter = self.activity_counter
103 <div class="activity">
105 <span class="act_counter">%(counter)d.</span>
106 %(opis)s""" % locals(), \
110 <section class="infobox time"><h1>Czas</h1><p>%(czas)s min</p></section>
111 <section class="infobox kind"><h1>Metoda</h1><p>%(forma)s</p></section>
114 <div class="clearboth"></div>
118 handle_opis = ifoption(sub_gen=True)(tag('div', 'description'))
119 handle_wskazowki = ifoption(sub_gen=True)(tag('div', ('hints', 'teacher')))
121 @ifoption(sub_gen=True)
122 @tagged('section', 'infobox materials')
123 def handle_pomoce(self, _):
124 return """<h1>Pomoce</h1>""", ""
126 def handle_czas(self, *_):
129 def handle_forma(self, *_):
132 def handle_cwiczenie(self, element):
133 exercise_handlers = {
135 'uporzadkuj': Uporzadkuj,
138 'przyporzadkuj': Przyporzadkuj,
139 'prawdafalsz': PrawdaFalsz
142 typ = element.attrib['typ']
143 self.exercise_counter += 1
144 print self.exercise_counter
145 self.options = {'exercise_counter': self.exercise_counter}
146 handler = exercise_handlers[typ](self.options)
147 return handler.generate(element)
150 def handle_lista(self, element, attrs={}):
151 ltype = element.attrib.get('typ', 'punkt')
152 if ltype == 'slowniczek':
153 surl = element.attrib.get('src', None)
155 # print '** missing src on <slowniczek>, setting default'
156 surl = 'http://edukacjamedialna.edu.pl/slowniczek'
159 sxml = etree.fromstring(self.options['provider'].by_uri(surl).get_string())
160 self.options = {'slowniczek': True, 'slowniczek_xml': sxml }
161 return '<div class="slowniczek">', '</div>'
163 listtag = {'num': 'ol',
166 'czytelnia': 'ul'}[ltype]
168 classes = attrs.get('class', '')
169 if classes: del attrs['class']
171 attrs_s = ' '.join(['%s="%s"' % kv for kv in attrs.items()])
172 if attrs_s: attrs_s = ' ' + attrs_s
174 return '<%s class="lista %s %s"%s>' % (listtag, ltype, classes, attrs_s), '</%s>' % listtag
176 def handle_punkt(self, element):
177 if self.options['slowniczek']:
178 return '<dl>', '</dl>'
180 return '<li>', '</li>'
182 def handle_definiendum(self, element):
183 nxt = element.getnext()
187 print "!! Empty <definiendum/>"
190 # let's pull definiens from another document
191 if self.options['slowniczek_xml'] is not None and (nxt is None or nxt.tag != 'definiens'):
192 sxml = self.options['slowniczek_xml']
193 defloc = sxml.xpath("//definiendum[text()='%s']" % element.text)
195 definiens = defloc[0].getnext()
196 if definiens.tag == 'definiens':
197 subgen = EduModule(self.options)
198 definiens_s = subgen.generate(definiens)
200 print '!! Missing definiendum in source:', element.text
202 return u"<dt>", u"</dt>" + definiens_s
204 def handle_definiens(self, element):
205 return u"<dd>", u"</dd>"
207 def handle_podpis(self, element):
208 return u"""<div class="caption">""", u"</div>"
210 def handle_tabela(self, element):
211 has_frames = int(element.attrib.get("ramki", "0"))
212 if has_frames: frames_c = "framed"
214 return u"""<table class="%s">""" % frames_c, u"</table>"
216 def handle_wiersz(self, element):
217 return u"<tr>", u"</tr>"
219 def handle_kol(self, element):
220 return u"<td>", u"</td>"
222 def handle_rdf__RDF(self, _):
223 # ustal w opcjach rzeczy :D
226 def handle_link(self, element):
227 if 'url' in element.attrib:
228 return tag('a', href=element.attrib['url'])(self, element)
229 elif 'material' in element.attrib:
230 material_err = u' [BRAKUJĄCY MATERIAŁ]'
231 slug = element.attrib['material']
232 make_url = lambda f: self.options['urlmapper'] \
233 .url_for_material(slug, f)
235 if 'format' in element.attrib:
236 formats = re.split(r"[, ]+",
237 element.attrib['format'])
241 formats = self.options['urlmapper'].materials(slug)
244 def_href = make_url(formats[0][0])
246 except (IndexError, self.options['urlmapper'].MaterialNotFound):
247 def_err = material_err
250 for f in formats[1:]:
252 fmt_links.append(u'<a href="%s">%s</a>' % (make_url(f[0]), f[0].upper()))
253 except self.options['urlmapper'].MaterialNotFound:
254 fmt_links.append(u'<a>%s%s</a>' % (f[0].upper(), material_err))
255 more_links = u' (%s)' % u', '.join(fmt_links) if fmt_links else u''
257 return u"<a href='%s'>" % def_href, u'%s</a>%s' % (def_err, more_links)
260 class Exercise(EduModule):
261 def __init__(self, *args, **kw):
262 self.question_counter = 0
263 super(Exercise, self).__init__(*args, **kw)
265 handle_opis = tag('div', 'description')
267 def handle_rozw_kom(self, element):
268 return u"""<div style="display:none" class="comment">""", u"""</div>"""
270 def handle_cwiczenie(self, element):
271 self.options = {'exercise': element.attrib['typ']}
272 self.question_counter = 0
273 self.piece_counter = 0
276 <div class="exercise %(typ)s" data-type="%(typ)s">
277 <form action="#" method="POST">
278 <h3>Zadanie %(exercies_counter)d</h3>
279 <div class="buttons">
280 <span class="message"></span>
281 <input type="button" class="check" value="sprawdź"/>
282 <input type="button" class="retry" style="display:none" value="spróbuj ponownie"/>
283 <input type="button" class="solutions" value="pokaż rozwiązanie"/>
284 <input type="button" class="reset" value="reset"/>
287 """ % {'exercies_counter': self.options['exercise_counter'], 'typ': element.attrib['typ']}
289 <div class="buttons">
290 <span class="message"></span>
291 <input type="button" class="check" value="sprawdź"/>
292 <input type="button" class="retry" style="display:none" value="spróbuj ponownie"/>
293 <input type="button" class="solutions" value="pokaż rozwiązanie"/>
294 <input type="button" class="reset" value="reset"/>
299 # Add a single <pytanie> tag if it's not there
300 if not element.xpath(".//pytanie"):
301 qpre, qpost = self.handle_pytanie(element)
306 def handle_pytanie(self, element):
307 """This will handle <cwiczenie> element, when there is no <pytanie>
310 self.question_counter += 1
311 self.piece_counter = 0
312 solution = element.attrib.get('rozw', None)
313 if solution: solution_s = ' data-solution="%s"' % solution
314 else: solution_s = ''
316 handles = element.attrib.get('uchwyty', None)
318 add_class += ' handles handles-%s' % handles
319 self.options = {'handles': handles}
321 minimum = element.attrib.get('min', None)
322 if minimum: minimum_s = ' data-minimum="%d"' % int(minimum)
325 return '<div class="question%s" data-no="%d" %s>' %\
326 (add_class, self.question_counter, solution_s + minimum_s), \
330 class Wybor(Exercise):
331 def handle_cwiczenie(self, element):
332 pre, post = super(Wybor, self).handle_cwiczenie(element)
333 is_single_choice = True
334 pytania = element.xpath(".//pytanie")
338 solutions = re.split(r"[, ]+", p.attrib['rozw'])
339 if len(solutions) != 1:
340 is_single_choice = False
342 choices = p.xpath(".//*[@nazwa]")
344 for n in choices: uniq.add(n.attrib['nazwa'])
345 if len(choices) != len(uniq):
346 is_single_choice = False
349 self.options = {'single': is_single_choice}
352 def handle_punkt(self, element):
353 if self.options['exercise'] and element.attrib.get('nazwa', None):
354 qc = self.question_counter
355 self.piece_counter += 1
356 no = self.piece_counter
357 eid = "q%(qc)d_%(no)d" % locals()
358 aname = element.attrib.get('nazwa', None)
359 if self.options['single']:
361 <li class="question-piece" data-qc="%(qc)d" data-no="%(no)d" data-name="%(aname)s">
362 <input type="radio" name="q%(qc)d" id="%(eid)s" value="%(aname)s" />
363 <label for="%(eid)s">
364 """ % locals(), u"</label></li>"
367 <li class="question-piece" data-qc="%(qc)d" data-no="%(no)d" data-name="%(aname)s">
368 <input type="checkbox" name="%(eid)s" id="%(eid)s" />
369 <label for="%(eid)s">
370 """ % locals(), u"</label></li>"
373 return super(Wybor, self).handle_punkt(element)
376 class Uporzadkuj(Exercise):
377 def handle_pytanie(self, element):
379 Overrides the returned content default handle_pytanie
381 # we ignore the result, returning our own
382 super(Uporzadkuj, self).handle_pytanie(element)
383 order_items = element.xpath(".//punkt/@rozw")
385 return u"""<div class="question" data-original="%s" data-no="%s">""" % \
386 (','.join(order_items), self.question_counter), \
389 def handle_punkt(self, element):
390 return """<li class="question-piece" data-pos="%(rozw)s"/>""" \
395 class Luki(Exercise):
396 def find_pieces(self, question):
397 return question.xpath(".//luka")
399 def solution_html(self, piece):
401 return sub.generate(piece)
403 # return piece.text + ''.join(
404 # [etree.tostring(n, encoding=unicode)
407 def handle_pytanie(self, element):
408 qpre, qpost = super(Luki, self).handle_pytanie(element)
410 luki = list(enumerate(self.find_pieces(element)))
414 for (i, luka) in luki:
416 luka_html = self.solution_html(luka)
417 luki_html += u'<span class="draggable question-piece" data-no="%d">%s</span>' % (i, luka_html)
418 self.words_html = '<div class="words">%s</div>' % luki_html
422 def handle_opis(self, element):
423 return '', self.words_html
425 def handle_luka(self, element):
426 self.piece_counter += 1
427 return '<span class="placeholder" data-solution="%d"></span>' % self.piece_counter
431 def find_pieces(self, question):
432 return question.xpath(".//zastap")
434 def solution_html(self, piece):
435 return piece.attrib['rozw']
437 def handle_zastap(self, element):
438 self.piece_counter += 1
439 return '<span class="placeholder zastap question-piece" data-solution="%d">' \
440 % self.piece_counter, '</span>'
443 class Przyporzadkuj(Exercise):
444 def handle_pytanie(self, element):
445 pre, post = super(Przyporzadkuj, self).handle_pytanie(element)
446 minimum = element.attrib.get("min", None)
448 self.options = {"min": int(minimum)}
451 def handle_lista(self, lista):
452 if 'nazwa' in lista.attrib:
454 'data-name': lista.attrib['nazwa'],
457 self.options = {'predicate': True}
458 elif 'cel' in lista.attrib:
460 'data-target': lista.attrib['cel'],
463 self.options = {'subject': True, 'handles': 'uchwyty' in lista.attrib}
466 pre, post = super(Przyporzadkuj, self).handle_lista(lista, attrs)
467 return pre, post + '<br class="clr"/>'
469 def handle_punkt(self, element):
470 if self.options['subject']:
471 self.piece_counter += 1
472 if self.options['handles']:
473 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>'
475 return '<li data-solution="%s" data-no="%s" class="question-piece draggable">' % (element.attrib['rozw'], self.piece_counter), '</li>'
477 elif self.options['predicate']:
478 if self.options['min']:
479 placeholders = u'<li class="placeholder"/>' * self.options['min']
481 placeholders = u'<li class="placeholder multiple"/>'
482 return '<li data-predicate="%(nazwa)s">' % element.attrib, '<ul>' + placeholders + '</ul></li>'
485 return super(Przyporzadkuj, self).handle_punkt(element)
488 class PrawdaFalsz(Exercise):
489 def handle_punkt(self, element):
490 if 'rozw' in element.attrib:
491 return u'''<li data-solution="%s" class="question-piece">
492 <span class="buttons">
493 <a href="#" data-value="true" class="true">Prawda</a>
494 <a href="#" data-value="false" class="false">Fałsz</a>
495 </span>''' % {'prawda': 'true', 'falsz': 'false'}[element.attrib['rozw']], '</li>'
497 return super(PrawdaFalsz, self).handle_punkt(element)
500 class EduModuleFormat(Format):
501 PRIMARY_MATERIAL_FORMATS = ('pdf', 'odt')
503 class MaterialNotFound(BaseException):
506 def __init__(self, wldoc, **kwargs):
507 super(EduModuleFormat, self).__init__(wldoc, **kwargs)
510 # Sort materials by slug.
511 self.materials_by_slug = {}
512 for name, att in self.wldoc.source.attachments.items():
513 parts = name.rsplit('.', 1)
517 if slug not in self.materials_by_slug:
518 self.materials_by_slug[slug] = {}
519 self.materials_by_slug[slug][ext] = att
521 edumod = EduModule({'provider': self.wldoc.provider, 'urlmapper': self, 'wldoc': self.wldoc})
523 html = edumod.generate(self.wldoc.edoc.getroot())
525 return IOFile.from_string(html.encode('utf-8'))
527 def materials(self, slug):
528 """Returns a list of pairs: (ext, iofile)."""
529 order = dict(reversed(k) for k in enumerate(self.PRIMARY_MATERIAL_FORMATS))
530 mats = self.materials_by_slug.get(slug, {}).items()
532 print "!! Material missing: '%s'" % slug
533 return sorted(mats, key=lambda (x, y): order.get(x, x))
535 def url_for_material(self, slug, fmt):
536 return "%s.%s" % (slug, fmt)
539 def transform(wldoc, stylesheet='edumed', options=None, flags=None):
540 """Transforms the WL document to XHTML.
542 If output_filename is None, returns an XML,
543 otherwise returns True if file has been written,False if it hasn't.
544 File won't be written if it has no content.
546 edumodfor = EduModuleFormat(wldoc)
547 return edumodfor.build()