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
9 from librarian import functions
14 DEFAULT_MATERIAL_FORMAT = 'odt'
17 class EduModule(Xmill):
18 def __init__(self, options=None):
19 super(EduModule, self).__init__(options)
20 self.activity_counter = 0
21 self.register_text_filter(functions.substitute_entities)
23 def handle_powiesc(self, element):
25 <div class="module" id="book-text">
26 <!-- <span class="teacher-toggle">
27 <input type="checkbox" name="teacher-toggle" id="teacher-toggle"/>
28 <label for="teacher-toggle">Pokaż treść dla nauczyciela</label>
33 handle_autor_utworu = tag("span", "author")
34 handle_nazwa_utworu = tag("h1", "title")
35 handle_dzielo_nadrzedne = tag("span", "collection")
36 handle_podtytul = tag("span", "subtitle")
37 handle_naglowek_akt = handle_naglowek_czesc = handle_srodtytul = tag("h2")
38 handle_naglowek_scena = handle_naglowek_rozdzial = tag('h2')
39 handle_naglowek_osoba = handle_naglowek_podrozdzial = tag('h3')
40 handle_akap = handle_akap_dialog = handle_akap_cd = tag('p', 'paragraph')
41 handle_strofa = tag('div', 'stanza')
42 handle_wyroznienie = tag('em')
43 handle_tytul_dziela = tag('em', 'title')
44 handle_slowo_obce = tag('em', 'foreign')
46 def handle_uwaga(self, _e):
49 def handle_aktywnosc(self, element):
50 self.activity_counter += 1
53 'activity_counter': self.activity_counter,
55 submill = EduModule(dict(self.options.items() + {'sub_gen': True}.items()))
57 opis = submill.generate(element.xpath('opis')[0])
59 n = element.xpath('wskazowki')
60 if n: wskazowki = submill.generate(n[0])
63 n = element.xpath('pomoce')
65 if n: pomoce = submill.generate(n[0])
68 forma = ''.join(element.xpath('forma/text()'))
70 czas = ''.join(element.xpath('czas/text()'))
72 counter = self.activity_counter
75 <div class="activity">
77 <span class="act_counter">%(counter)d.</span>
82 <section class="infobox time"><h1>Czas</h1><p>%(czas)s min</p></section>
83 <section class="infobox kind"><h1>Forma</h1><p>%(forma)s</p></section>
86 <div class="clearboth"></div>
90 handle_opis = ifoption(sub_gen=True)(tag('div', 'description'))
91 handle_wskazowki = ifoption(sub_gen=True)(tag('div', ('hints', 'teacher')))
93 @ifoption(sub_gen=True)
94 @tagged('section', 'infobox materials')
95 def handle_pomoce(self, _):
96 return """<h1>Pomoce</h1>""", ""
98 def handle_czas(self, *_):
101 def handle_forma(self, *_):
104 def handle_cwiczenie(self, element):
105 exercise_handlers = {
107 'uporzadkuj': Uporzadkuj,
110 'przyporzadkuj': Przyporzadkuj,
111 'prawdafalsz': PrawdaFalsz
114 typ = element.attrib['typ']
115 handler = exercise_handlers[typ](self.options)
116 return handler.generate(element)
119 def handle_lista(self, element, attrs={}):
120 ltype = element.attrib.get('typ', 'punkt')
121 if ltype == 'slowniczek':
122 surl = element.attrib.get('href', None)
125 sxml = etree.fromstring(self.options['provider'].by_uri(surl).get_string())
126 self.options = {'slowniczek': True, 'slowniczek_xml': sxml }
127 return '<div class="slowniczek">', '</div>'
129 listtag = {'num': 'ol',
132 'czytelnia': 'ul'}[ltype]
134 classes = attrs.get('class', '')
135 if classes: del attrs['class']
137 attrs_s = ' '.join(['%s="%s"' % kv for kv in attrs.items()])
138 if attrs_s: attrs_s = ' ' + attrs_s
140 return '<%s class="lista %s %s"%s>' % (listtag, ltype, classes, attrs_s), '</%s>' % listtag
142 def handle_punkt(self, element):
143 if self.options['slowniczek']:
144 return '<dl>', '</dl>'
146 return '<li>', '</li>'
148 def handle_definiendum(self, element):
149 nxt = element.getnext()
152 # let's pull definiens from another document
153 if self.options['slowniczek_xml'] and (not nxt or nxt.tag != 'definiens'):
154 sxml = self.options['slowniczek_xml']
155 assert element.text != ''
156 defloc = sxml.xpath("//definiendum[text()='%s']" % element.text)
158 definiens = defloc[0].getnext()
159 if definiens.tag == 'definiens':
160 subgen = EduModule(self.options)
161 definiens_s = subgen.generate(definiens)
163 return u"<dt>", u"</dt>" + definiens_s
165 def handle_definiens(self, element):
166 return u"<dd>", u"</dd>"
168 def handle_podpis(self, element):
169 return u"""<div class="caption">""", u"</div>"
171 def handle_tabela(self, element):
172 has_frames = int(element.attrib.get("ramki", "0"))
173 if has_frames: frames_c = "framed"
175 return u"""<table class="%s">""" % frames_c, u"</table>"
177 def handle_wiersz(self, element):
178 return u"<tr>", u"</tr>"
180 def handle_kol(self, element):
181 return u"<td>", u"</td>"
183 def handle_rdf__RDF(self, _):
184 # ustal w opcjach rzeczy :D
187 def handle_link(self, element):
188 if 'url' in element.attrib:
189 return tag('a', href=element.attrib['url'])(self, element)
190 elif 'material' in element.attrib:
191 formats = re.split(r"[, ]+",
192 element.attrib.get('format', DEFAULT_MATERIAL_FORMAT))
193 make_url = lambda f: self.options['urlmapper'] \
194 .url_for_material(element.attrib['material'], f)
195 def_href = make_url(formats[0])
197 for f in formats[1:]:
198 fmt_links.append(u'<a href="%s">%s</a>' % (make_url(f), f.upper()))
199 more_links = u' (%s)' % u', '.join(fmt_links) if fmt_links else u''
201 return u"<a href='%s'>" % def_href, u'</a>%s' % more_links
204 class Exercise(EduModule):
205 def __init__(self, *args, **kw):
206 self.question_counter = 0
207 super(Exercise, self).__init__(*args, **kw)
209 handle_opis = tag('div', 'description')
211 def handle_rozw_kom(self, element):
212 return u"""<div style="display:none" class="comment">""", u"""</div>"""
214 def handle_cwiczenie(self, element):
215 self.options = {'exercise': element.attrib['typ']}
216 self.question_counter = 0
217 self.piece_counter = 0
220 <div class="exercise %(typ)s" data-type="%(typ)s">
221 <form action="#" method="POST">
224 <div class="buttons">
225 <span class="message"></span>
226 <input type="button" class="check" value="sprawdź"/>
227 <input type="button" class="retry" style="display:none" value="spróbuj ponownie"/>
228 <input type="button" class="solutions" value="pokaż rozwiązanie"/>
229 <input type="button" class="reset" value="reset"/>
234 # Add a single <pytanie> tag if it's not there
235 if not element.xpath(".//pytanie"):
236 qpre, qpost = self.handle_pytanie(element)
241 def handle_pytanie(self, element):
242 """This will handle <cwiczenie> element, when there is no <pytanie>
245 self.question_counter += 1
246 self.piece_counter = 0
247 solution = element.attrib.get('rozw', None)
248 if solution: solution_s = ' data-solution="%s"' % solution
249 else: solution_s = ''
251 handles = element.attrib.get('uchwyty', None)
253 add_class += ' handles handles-%s' % handles
254 self.options = {'handles': handles}
256 minimum = element.attrib.get('min', None)
257 if minimum: minimum_s = ' data-minimum="%d"' % int(minimum)
260 return '<div class="question%s" data-no="%d" %s>' %\
261 (add_class, self.question_counter, solution_s + minimum_s), \
265 class Wybor(Exercise):
266 def handle_cwiczenie(self, element):
267 pre, post = super(Wybor, self).handle_cwiczenie(element)
268 is_single_choice = True
269 for p in element.xpath(".//pytanie"):
270 solutions = re.split(r"[, ]+", p.attrib['rozw'])
271 if len(solutions) != 1:
272 is_single_choice = False
274 choices = element.xpath(".//*[@nazwa]")
276 for n in choices: uniq.add(n.attrib['nazwa'])
277 if len(choices) != len(uniq):
278 is_single_choice = False
281 self.options = {'single': is_single_choice}
284 def handle_punkt(self, element):
285 if self.options['exercise'] and element.attrib.get('nazwa', None):
286 qc = self.question_counter
287 self.piece_counter += 1
288 no = self.piece_counter
289 eid = "q%(qc)d_%(no)d" % locals()
290 aname = element.attrib.get('nazwa', None)
291 if self.options['single']:
293 <li class="question-piece" data-qc="%(qc)d" data-no="%(no)d" data-name="%(aname)s">
294 <input type="radio" name="q%(qc)d" id="%(eid)s" value="%(aname)s" />
295 <label for="%(eid)s">
296 """ % locals(), u"</label></li>"
299 <li class="question-piece" data-qc="%(qc)d" data-no="%(no)d" data-name="%(aname)s">
300 <input type="checkbox" name="%(eid)s" id="%(eid)s" />
301 <label for="%(eid)s">
302 """ % locals(), u"</label></li>"
305 return super(Wybor, self).handle_punkt(element)
308 class Uporzadkuj(Exercise):
309 def handle_pytanie(self, element):
311 Overrides the returned content default handle_pytanie
313 # we ignore the result, returning our own
314 super(Uporzadkuj, self).handle_pytanie(element)
315 order_items = element.xpath(".//punkt/@rozw")
317 return u"""<div class="question" data-original="%s" data-no="%s">""" % \
318 (','.join(order_items), self.question_counter), \
321 def handle_punkt(self, element):
322 return """<li class="question-piece" data-pos="%(rozw)s"/>""" \
327 class Luki(Exercise):
328 def find_pieces(self, question):
329 return question.xpath(".//luka")
331 def solution_html(self, piece):
332 return piece.text + ''.join(
333 [etree.tostring(n, encoding=unicode)
336 def handle_pytanie(self, element):
337 qpre, qpost = super(Luki, self).handle_pytanie(element)
339 luki = list(enumerate(self.find_pieces(element)))
343 for (i, luka) in luki:
345 luka_html = self.solution_html(luka)
346 luki_html += u'<span class="draggable question-piece" data-no="%d">%s</span>' % (i, luka_html)
347 self.words_html = '<div class="words">%s</div>' % luki_html
351 def handle_opis(self, element):
352 return '', self.words_html
354 def handle_luka(self, element):
355 self.piece_counter += 1
356 return '<span class="placeholder" data-solution="%d"></span>' % self.piece_counter
360 def find_pieces(self, question):
361 return question.xpath(".//zastap")
363 def solution_html(self, piece):
364 return piece.attrib['rozw']
366 def handle_zastap(self, element):
367 self.piece_counter += 1
368 return '<span class="placeholder zastap question-piece" data-solution="%d">' \
369 % self.piece_counter, '</span>'
372 class Przyporzadkuj(Exercise):
373 def handle_pytanie(self, element):
374 pre, post = super(Przyporzadkuj, self).handle_pytanie(element)
375 minimum = element.attrib.get("min", None)
377 self.options = {"min": int(minimum)}
380 def handle_lista(self, lista):
381 if 'nazwa' in lista.attrib:
383 'data-name': lista.attrib['nazwa'],
386 self.options = {'predicate': True}
387 elif 'cel' in lista.attrib:
389 'data-target': lista.attrib['cel'],
392 self.options = {'subject': True, 'handles': 'uchwyty' in lista.attrib}
395 pre, post = super(Przyporzadkuj, self).handle_lista(lista, attrs)
396 return pre, post + '<br class="clr"/>'
398 def handle_punkt(self, element):
399 if self.options['subject']:
400 self.piece_counter += 1
401 if self.options['handles']:
402 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>'
404 return '<li data-solution="%s" data-no="%s" class="question-piece draggable">' % (element.attrib['rozw'], self.piece_counter), '</li>'
406 elif self.options['predicate']:
407 if self.options['min']:
408 placeholders = u'<li class="placeholder"/>' * self.options['min']
410 placeholders = u'<li class="placeholder multiple"/>'
411 return '<li data-predicate="%(nazwa)s">' % element.attrib, '<ul class="subjects">' + placeholders + '</ul></li>'
414 return super(Przyporzadkuj, self).handle_punkt(element)
417 class PrawdaFalsz(Exercise):
418 def handle_punkt(self, element):
419 if 'rozw' in element.attrib:
420 return u'''<li data-solution="%s" class="question-piece">
421 <span class="buttons">
422 <a href="#" data-value="true" class="true">Prawda</a>
423 <a href="#" data-value="false" class="false">Fałsz</a>
424 </span>''' % {'prawda': 'true', 'falsz': 'false'}[element.attrib['rozw']], '</li>'
426 return super(PrawdaFalsz, self).handle_punkt(element)
429 class EduModuleFormat(Format):
430 def __init__(self, wldoc, **kwargs):
431 super(EduModuleFormat, self).__init__(wldoc, **kwargs)
434 edumod = EduModule({'provider': self.wldoc.provider, 'urlmapper': self})
436 html = edumod.generate(self.wldoc.edoc.getroot())
438 return IOFile.from_string(html.encode('utf-8'))
440 def url_for_material(self, slug, fmt=None):
441 # No briliant idea for an API here.
443 return "%s.%s" % (slug, fmt)
447 def transform(wldoc, stylesheet='edumed', options=None, flags=None):
448 """Transforms the WL document to XHTML.
450 If output_filename is None, returns an XML,
451 otherwise returns True if file has been written,False if it hasn't.
452 File won't be written if it has no content.
454 edumodfor = EduModuleFormat(wldoc)
455 return edumodfor.build()