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
15 class EduModule(Xmill):
16 def __init__(self, options=None):
17 super(EduModule, self).__init__(options)
18 self.activity_counter = 0
19 self.register_text_filter(lambda t: functions.substitute_entities(None, t))
21 def handle_powiesc(self, element):
23 <div class="module" id="book-text">
24 <!-- <span class="teacher-toggle">
25 <input type="checkbox" name="teacher-toggle" id="teacher-toggle"/>
26 <label for="teacher-toggle">Pokaż treść dla nauczyciela</label>
31 handle_autor_utworu = tag("span", "author")
32 handle_nazwa_utworu = tag("h1", "title")
33 handle_dzielo_nadrzedne = tag("span", "collection")
34 handle_podtytul = tag("span", "subtitle")
35 handle_naglowek_akt = handle_naglowek_czesc = handle_srodtytul = tag("h2")
36 handle_naglowek_scena = handle_naglowek_rozdzial = tag('h3')
37 handle_naglowek_osoba = handle_naglowek_podrozdzial = tag('h4')
38 handle_akap = handle_akap_dialog = handle_akap_cd = tag('p', 'paragraph')
39 handle_strofa = tag('div', 'stanza')
41 def handle_aktywnosc(self, element):
42 self.activity_counter += 1
45 'activity_counter': self.activity_counter,
47 submill = EduModule(dict(self.options.items() + {'sub_gen': True}.items()))
49 opis = submill.generate(element.xpath('opis')[0])
51 n = element.xpath('wskazowki')
52 if n: wskazowki = submill.generate(n[0])
55 n = element.xpath('pomoce')
57 if n: pomoce = submill.generate(n[0])
60 forma = ''.join(element.xpath('forma/text()'))
62 czas = ''.join(element.xpath('czas/text()'))
64 counter = self.activity_counter
67 <div class="activity">
68 <div class="text">%(counter)d.
73 <p>Czas: %(czas)s min</p>
74 <p>Forma: %(forma)s</p>
77 <div class="clearboth"></div>
81 handle_opis = ifoption(sub_gen=True)(tag('div', 'description'))
82 handle_wskazowki = ifoption(sub_gen=True)(tag('div', ('hints', 'teacher')))
84 @ifoption(sub_gen=True)
85 @tagged('div', 'materials')
86 def handle_pomoce(self, _):
89 def handle_czas(self, *_):
92 def handle_forma(self, *_):
95 def handle_cwiczenie(self, element):
98 'uporzadkuj': Uporzadkuj,
101 'przyporzadkuj': Przyporzadkuj,
102 'prawdafalsz': PrawdaFalsz
105 typ = element.attrib['typ']
106 handler = exercise_handlers[typ](self.options)
107 return handler.generate(element)
110 def handle_lista(self, element, attrs={}):
111 ltype = element.attrib.get('typ', 'punkt')
112 if ltype == 'slowniczek':
113 surl = element.attrib.get('href', None)
116 sxml = etree.fromstring(self.options['provider'].by_uri(surl).get_string())
117 self.options = {'slowniczek': True, 'slowniczek_xml': sxml }
118 return '<div class="slowniczek">', '</div>'
120 listtag = {'num': 'ol',
123 'czytelnia': 'ul'}[ltype]
125 classes = attrs.get('class', '')
126 if classes: del attrs['class']
128 attrs_s = ' '.join(['%s="%s"' % kv for kv in attrs.items()])
129 if attrs_s: attrs_s = ' ' + attrs_s
131 return '<%s class="lista %s %s"%s>' % (listtag, ltype, classes, attrs_s), '</%s>' % listtag
133 def handle_punkt(self, element):
134 if self.options['slowniczek']:
135 return '<dl>', '</dl>'
137 return '<li>', '</li>'
139 def handle_definiendum(self, element):
140 nxt = element.getnext()
143 # let's pull definiens from another document
144 if self.options['slowniczek_xml'] and (not nxt or nxt.tag != 'definiens'):
145 sxml = self.options['slowniczek_xml']
146 assert element.text != ''
147 defloc = sxml.xpath("//definiendum[text()='%s']" % element.text)
149 definiens = defloc[0].getnext()
150 if definiens.tag == 'definiens':
151 subgen = EduModule(self.options)
152 definiens_s = subgen.generate(definiens)
154 return u"<dt>", u"</dt>" + definiens_s
156 def handle_definiens(self, element):
157 return u"<dd>", u"</dd>"
160 def handle_podpis(self, element):
161 return u"""<div class="caption">""", u"</div>"
163 def handle_tabela(self, element):
164 has_frames = int(element.attrib.get("ramki", "0"))
165 if has_frames: frames_c = "framed"
167 return u"""<table class="%s">""" % frames_c, u"</table>"
169 def handle_wiersz(self, element):
170 return u"<tr>", u"</tr>"
172 def handle_kol(self, element):
173 return u"<td>", u"</td>"
175 def handle_rdf__RDF(self, _):
176 # ustal w opcjach rzeczy :D
179 def handle_link(self, element):
180 if 'material' in element.attrib:
181 formats = re.split(r"[, ]+", element.attrib['format'])
184 fmt_links.append(u'<a href="%s">%s</a>' % (self.options['urlmapper'].url_for_material(element.attrib['material'], f), f.upper()))
186 return u"", u' (%s)' % u' '.join(fmt_links)
189 class Exercise(EduModule):
190 def __init__(self, *args, **kw):
191 self.question_counter = 0
192 super(Exercise, self).__init__(*args, **kw)
194 def handle_rozw_kom(self, element):
195 return u"""<div style="display:none" class="comment">""", u"""</div>"""
197 def handle_cwiczenie(self, element):
198 self.options = {'exercise': element.attrib['typ']}
199 self.question_counter = 0
200 self.piece_counter = 0
203 <div class="exercise %(typ)s" data-type="%(typ)s">
204 <form action="#" method="POST">
207 <div class="buttons">
208 <span class="message"></span>
209 <input type="button" class="check" value="sprawdź"/>
210 <input type="button" class="retry" style="display:none" value="spróbuj ponownie"/>
211 <input type="button" class="solutions" value="pokaż rozwiązanie"/>
212 <input type="button" class="reset" value="reset"/>
217 # Add a single <pytanie> tag if it's not there
218 if not element.xpath(".//pytanie"):
219 qpre, qpost = self.handle_pytanie(element)
224 def handle_pytanie(self, element):
225 """This will handle <cwiczenie> element, when there is no <pytanie>
228 self.question_counter += 1
229 self.piece_counter = 0
230 solution = element.attrib.get('rozw', None)
231 if solution: solution_s = ' data-solution="%s"' % solution
232 else: solution_s = ''
234 handles = element.attrib.get('uchwyty', None)
236 add_class += ' handles handles-%s' % handles
237 self.options = {'handles': handles}
239 minimum = element.attrib.get('min', None)
240 if minimum: minimum_s = ' data-minimum="%d"' % int(minimum)
243 return '<div class="question%s" data-no="%d" %s>' %\
244 (add_class, self.question_counter, solution_s + minimum_s), \
248 class Wybor(Exercise):
249 def handle_cwiczenie(self, element):
250 pre, post = super(Wybor, self).handle_cwiczenie(element)
251 is_single_choice = True
252 for p in element.xpath(".//pytanie"):
253 solutions = re.split(r"[, ]+", p.attrib['rozw'])
254 if len(solutions) != 1:
255 is_single_choice = False
257 self.options = {'single': is_single_choice}
260 def handle_punkt(self, element):
261 if self.options['exercise'] and element.attrib.get('nazwa', None):
262 qc = self.question_counter
263 self.piece_counter += 1
264 no = self.piece_counter
265 eid = "q%(qc)d_%(no)d" % locals()
266 aname = element.attrib.get('nazwa', None)
267 if self.options['single']:
269 <li class="question-piece" data-qc="%(qc)d" data-no="%(no)d" data-name="%(aname)s">
270 <input type="radio" name="q%(qc)d" id="%(eid)s" value="%(aname)s" />
271 <label for="%(eid)s">
272 """ % locals(), u"</label></li>"
275 <li class="question-piece" data-qc="%(qc)d" data-no="%(no)d" data-name="%(aname)s">
276 <input type="checkbox" name="%(eid)s" id="%(eid)s" />
277 <label for="%(eid)s">
278 """ % locals(), u"</label></li>"
281 return super(Wybor, self).handle_punkt(element)
284 class Uporzadkuj(Exercise):
285 def handle_pytanie(self, element):
287 Overrides the returned content default handle_pytanie
289 # we ignore the result, returning our own
290 super(Uporzadkuj, self).handle_pytanie(element)
291 order_items = element.xpath(".//punkt/@rozw")
293 return u"""<div class="question" data-original="%s" data-no="%s">""" % \
294 (','.join(order_items), self.question_counter), \
297 def handle_punkt(self, element):
298 return """<li class="question-piece" data-pos="%(rozw)s"/>""" \
303 class Luki(Exercise):
304 def find_pieces(self, question):
305 return question.xpath("//luka")
307 def solution_html(self, piece):
308 return piece.text + ''.join(
309 [etree.tostring(n, encoding=unicode)
312 def handle_pytanie(self, element):
313 qpre, qpost = super(Luki, self).handle_pytanie(element)
315 luki = list(enumerate(self.find_pieces(element)))
319 for (i, luka) in luki:
321 luka_html = self.solution_html(luka)
322 luki_html += u'<span class="draggable question-piece" data-no="%d">%s</span>' % (i, luka_html)
323 self.words_html = '<div class="words">%s</div>' % luki_html
327 def handle_opis(self, element):
328 pre, post = super(Luki, self).handle_opis(element)
329 return pre, self.words_html + post
331 def handle_luka(self, element):
332 self.piece_counter += 1
333 return '<span class="placeholder" data-solution="%d"></span>' % self.piece_counter
337 def find_pieces(self, question):
338 return question.xpath("//zastap")
340 def solution_html(self, piece):
341 return piece.attrib['rozw']
343 def handle_zastap(self, element):
344 self.piece_counter += 1
345 return '<span class="placeholder zastap question-piece" data-solution="%d">' \
346 % self.piece_counter, '</span>'
349 class Przyporzadkuj(Exercise):
350 def handle_pytanie(self, element):
351 pre, post = super(Przyporzadkuj, self).handle_pytanie(element)
352 minimum = element.attrib.get("min", None)
354 self.options = {"min": int(minimum)}
357 def handle_lista(self, lista):
358 if 'nazwa' in lista.attrib:
360 'data-name': lista.attrib['nazwa'],
363 self.options = {'predicate': True}
364 elif 'cel' in lista.attrib:
366 'data-target': lista.attrib['cel'],
369 self.options = {'subject': True, 'handles': 'uchwyty' in lista.attrib}
372 pre, post = super(Przyporzadkuj, self).handle_lista(lista, attrs)
373 return pre, post + '<br class="clr"/>'
375 def handle_punkt(self, element):
376 if self.options['subject']:
377 self.piece_counter += 1
378 if self.options['handles']:
379 return '<li><span data-solution="%s" data-no="%s" class="question-piece draggable handle">%s</span>' % (element.attrib['rozw'], self.piece_counter, self.piece_counter), '</li>'
381 return '<li data-solution="%s" data-no="%s" class="question-piece draggable">' % (element.attrib['rozw'], self.piece_counter), '</li>'
383 elif self.options['predicate']:
384 if self.options['min']:
385 placeholders = u'<li class="placeholder"/>' * self.options['min']
387 placeholders = u'<li class="placeholder multiple"/>'
388 return '<li data-predicate="%(nazwa)s">' % element.attrib, '<ul class="subjects">' + placeholders + '</ul></li>'
391 return super(Przyporzadkuj, self).handle_punkt(element)
394 class PrawdaFalsz(Exercise):
395 def handle_punkt(self, element):
396 if 'rozw' in element.attrib:
397 return u'''<li data-solution="%s" class="question-piece">
398 <span class="buttons">
399 <a href="#" data-value="true" class="true">Prawda</a>
400 <a href="#" data-value="false" class="false">Fałsz</a>
401 </span>''' % {'prawda': 'true', 'falsz': 'false'}[element.attrib['rozw']], '</li>'
403 return super(PrawdaFalsz, self).handle_punkt(element)
406 class EduModuleFormat(Format):
407 def __init__(self, wldoc, **kwargs):
408 super(EduModuleFormat, self).__init__(wldoc, **kwargs)
411 edumod = EduModule({'provider': self.wldoc.provider, 'urlmapper': self})
413 html = edumod.generate(self.wldoc.edoc.getroot())
415 return IOFile.from_string(html.encode('utf-8'))
417 def url_for_material(self, slug, fmt=None):
418 # No briliant idea for an API here.
420 return "%s.%s" % (slug, fmt)
424 def transform(wldoc, stylesheet='edumed', options=None, flags=None):
425 """Transforms the WL document to XHTML.
427 If output_filename is None, returns an XML,
428 otherwise returns True if file has been written,False if it hasn't.
429 File won't be written if it has no content.
431 edumodfor = EduModuleFormat(wldoc)
432 return edumodfor.build()