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(functions.substitute_entities)
 
  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('h2')
 
  37     handle_naglowek_osoba = handle_naglowek_podrozdzial = tag('h3')
 
  38     handle_akap = handle_akap_dialog = handle_akap_cd = tag('p', 'paragraph')
 
  39     handle_strofa = tag('div', 'stanza')
 
  40     handle_wyroznienie = tag('em')
 
  41     handle_tytul_dziela = tag('em', 'title')
 
  42     handle_slowo_obce = tag('em', 'foreign')
 
  44     def handle_aktywnosc(self, element):
 
  45         self.activity_counter += 1
 
  48             'activity_counter': self.activity_counter,
 
  50         submill = EduModule(dict(self.options.items() + {'sub_gen': True}.items()))
 
  52         opis = submill.generate(element.xpath('opis')[0])
 
  54         n = element.xpath('wskazowki')
 
  55         if n: wskazowki = submill.generate(n[0])
 
  58         n = element.xpath('pomoce')
 
  60         if n: pomoce = submill.generate(n[0])
 
  63         forma = ''.join(element.xpath('forma/text()'))
 
  65         czas = ''.join(element.xpath('czas/text()'))
 
  67         counter = self.activity_counter
 
  70 <div class="activity">
 
  72   <span class="act_counter">%(counter)d.</span>
 
  77   <section class="infobox time"><h1>Czas</h1><p>%(czas)s min</p></section>
 
  78   <section class="infobox kind"><h1>Forma</h1><p>%(forma)s</p></section>
 
  81  <div class="clearboth"></div>
 
  85     handle_opis = ifoption(sub_gen=True)(tag('div', 'description'))
 
  86     handle_wskazowki = ifoption(sub_gen=True)(tag('div', ('hints', 'teacher')))
 
  88     @ifoption(sub_gen=True)
 
  89     @tagged('section', 'infobox materials')
 
  90     def handle_pomoce(self, _):
 
  91         return """<h1>Pomoce</h1>""", ""
 
  93     def handle_czas(self, *_):
 
  96     def handle_forma(self, *_):
 
  99     def handle_cwiczenie(self, element):
 
 100         exercise_handlers = {
 
 102             'uporzadkuj': Uporzadkuj,
 
 105             'przyporzadkuj': Przyporzadkuj,
 
 106             'prawdafalsz': PrawdaFalsz
 
 109         typ = element.attrib['typ']
 
 110         handler = exercise_handlers[typ](self.options)
 
 111         return handler.generate(element)
 
 114     def handle_lista(self, element, attrs={}):
 
 115         ltype = element.attrib.get('typ', 'punkt')
 
 116         if ltype == 'slowniczek':
 
 117             surl = element.attrib.get('href', None)
 
 120                 sxml = etree.fromstring(self.options['provider'].by_uri(surl).get_string())
 
 121             self.options = {'slowniczek': True, 'slowniczek_xml': sxml }
 
 122             return '<div class="slowniczek">', '</div>'
 
 124         listtag = {'num': 'ol',
 
 127                'czytelnia': 'ul'}[ltype]
 
 129         classes = attrs.get('class', '')
 
 130         if classes: del attrs['class']
 
 132         attrs_s = ' '.join(['%s="%s"' % kv for kv in attrs.items()])
 
 133         if attrs_s: attrs_s = ' ' + attrs_s
 
 135         return '<%s class="lista %s %s"%s>' % (listtag, ltype, classes, attrs_s), '</%s>' % listtag
 
 137     def handle_punkt(self, element):
 
 138         if self.options['slowniczek']:
 
 139             return '<dl>', '</dl>'
 
 141             return '<li>', '</li>'
 
 143     def handle_definiendum(self, element):
 
 144         nxt = element.getnext()
 
 147         # let's pull definiens from another document
 
 148         if self.options['slowniczek_xml'] and (not nxt or nxt.tag != 'definiens'):
 
 149             sxml = self.options['slowniczek_xml']
 
 150             assert element.text != ''
 
 151             defloc = sxml.xpath("//definiendum[text()='%s']" % element.text)
 
 153                 definiens = defloc[0].getnext()
 
 154                 if definiens.tag == 'definiens':
 
 155                     subgen = EduModule(self.options)
 
 156                     definiens_s = subgen.generate(definiens)
 
 158         return u"<dt>", u"</dt>" + definiens_s
 
 160     def handle_definiens(self, element):
 
 161         return u"<dd>", u"</dd>"
 
 163     def handle_podpis(self, element):
 
 164         return u"""<div class="caption">""", u"</div>"
 
 166     def handle_tabela(self, element):
 
 167         has_frames = int(element.attrib.get("ramki", "0"))
 
 168         if has_frames: frames_c = "framed"
 
 170         return u"""<table class="%s">""" % frames_c, u"</table>"
 
 172     def handle_wiersz(self, element):
 
 173         return u"<tr>", u"</tr>"
 
 175     def handle_kol(self, element):
 
 176         return u"<td>", u"</td>"
 
 178     def handle_rdf__RDF(self, _):
 
 179         # ustal w opcjach  rzeczy :D
 
 182     def handle_link(self, element):
 
 183         if 'url' in element.attrib:
 
 184             return tag('a', href=element.attrib['url'])(self, element)
 
 185         elif 'material' in element.attrib:
 
 186             formats = re.split(r"[, ]+", element.attrib['format'])
 
 189                 fmt_links.append(u'<a href="%s">%s</a>' % (self.options['urlmapper'].url_for_material(element.attrib['material'], f), f.upper()))
 
 191             return u"", u' (%s)' % u' '.join(fmt_links)
 
 194 class Exercise(EduModule):
 
 195     def __init__(self, *args, **kw):
 
 196         self.question_counter = 0
 
 197         super(Exercise, self).__init__(*args, **kw)
 
 199     def handle_rozw_kom(self, element):
 
 200         return u"""<div style="display:none" class="comment">""", u"""</div>"""
 
 202     def handle_cwiczenie(self, element):
 
 203         self.options = {'exercise': element.attrib['typ']}
 
 204         self.question_counter = 0
 
 205         self.piece_counter = 0
 
 208 <div class="exercise %(typ)s" data-type="%(typ)s">
 
 209 <form action="#" method="POST">
 
 212 <div class="buttons">
 
 213 <span class="message"></span>
 
 214 <input type="button" class="check" value="sprawdź"/>
 
 215 <input type="button" class="retry" style="display:none" value="spróbuj ponownie"/>
 
 216 <input type="button" class="solutions" value="pokaż rozwiązanie"/>
 
 217 <input type="button" class="reset" value="reset"/>
 
 222         # Add a single <pytanie> tag if it's not there
 
 223         if not element.xpath(".//pytanie"):
 
 224             qpre, qpost = self.handle_pytanie(element)
 
 229     def handle_pytanie(self, element):
 
 230         """This will handle <cwiczenie> element, when there is no <pytanie>
 
 233         self.question_counter += 1
 
 234         self.piece_counter = 0
 
 235         solution = element.attrib.get('rozw', None)
 
 236         if solution: solution_s = ' data-solution="%s"' % solution
 
 237         else: solution_s = ''
 
 239         handles = element.attrib.get('uchwyty', None)
 
 241             add_class += ' handles handles-%s' % handles
 
 242             self.options = {'handles': handles}
 
 244         minimum = element.attrib.get('min', None)
 
 245         if minimum: minimum_s = ' data-minimum="%d"' % int(minimum)
 
 248         return '<div class="question%s" data-no="%d" %s>' %\
 
 249             (add_class, self.question_counter, solution_s + minimum_s), \
 
 253 class Wybor(Exercise):
 
 254     def handle_cwiczenie(self, element):
 
 255         pre, post = super(Wybor, self).handle_cwiczenie(element)
 
 256         is_single_choice = True
 
 257         for p in element.xpath(".//pytanie"):
 
 258             solutions = re.split(r"[, ]+", p.attrib['rozw'])
 
 259             if len(solutions) != 1:
 
 260                 is_single_choice = False
 
 262         self.options = {'single': is_single_choice}
 
 265     def handle_punkt(self, element):
 
 266         if self.options['exercise'] and element.attrib.get('nazwa', None):
 
 267             qc = self.question_counter
 
 268             self.piece_counter += 1
 
 269             no = self.piece_counter
 
 270             eid = "q%(qc)d_%(no)d" % locals()
 
 271             aname = element.attrib.get('nazwa', None)
 
 272             if self.options['single']:
 
 274 <li class="question-piece" data-qc="%(qc)d" data-no="%(no)d" data-name="%(aname)s">
 
 275 <input type="radio" name="q%(qc)d" id="%(eid)s" value="%(aname)s" />
 
 276 <label for="%(eid)s">
 
 277                 """ % locals(), u"</label></li>"
 
 280 <li class="question-piece" data-qc="%(qc)d" data-no="%(no)d" data-name="%(aname)s">
 
 281 <input type="checkbox" name="%(eid)s" id="%(eid)s" />
 
 282 <label for="%(eid)s">
 
 283 """ % locals(), u"</label></li>"
 
 286             return super(Wybor, self).handle_punkt(element)
 
 289 class Uporzadkuj(Exercise):
 
 290     def handle_pytanie(self, element):
 
 292 Overrides the returned content default handle_pytanie
 
 294         # we ignore the result, returning our own
 
 295         super(Uporzadkuj, self).handle_pytanie(element)
 
 296         order_items = element.xpath(".//punkt/@rozw")
 
 298         return u"""<div class="question" data-original="%s" data-no="%s">""" % \
 
 299             (','.join(order_items), self.question_counter), \
 
 302     def handle_punkt(self, element):
 
 303         return """<li class="question-piece" data-pos="%(rozw)s"/>""" \
 
 308 class Luki(Exercise):
 
 309     def find_pieces(self, question):
 
 310         return question.xpath(".//luka")
 
 312     def solution_html(self, piece):
 
 313         return piece.text + ''.join(
 
 314             [etree.tostring(n, encoding=unicode)
 
 317     def handle_pytanie(self, element):
 
 318         qpre, qpost = super(Luki, self).handle_pytanie(element)
 
 320         luki = list(enumerate(self.find_pieces(element)))
 
 324         for (i, luka) in luki:
 
 326             luka_html = self.solution_html(luka)
 
 327             luki_html += u'<span class="draggable question-piece" data-no="%d">%s</span>' % (i, luka_html)
 
 328         self.words_html = '<div class="words">%s</div>' % luki_html
 
 332     def handle_opis(self, element):
 
 333         return '', self.words_html
 
 335     def handle_luka(self, element):
 
 336         self.piece_counter += 1
 
 337         return '<span class="placeholder" data-solution="%d"></span>' % self.piece_counter
 
 341     def find_pieces(self, question):
 
 342         return question.xpath(".//zastap")
 
 344     def solution_html(self, piece):
 
 345         return piece.attrib['rozw']
 
 347     def handle_zastap(self, element):
 
 348         self.piece_counter += 1
 
 349         return '<span class="placeholder zastap question-piece" data-solution="%d">' \
 
 350             % self.piece_counter, '</span>'
 
 353 class Przyporzadkuj(Exercise):
 
 354     def handle_pytanie(self, element):
 
 355         pre, post = super(Przyporzadkuj, self).handle_pytanie(element)
 
 356         minimum = element.attrib.get("min", None)
 
 358             self.options = {"min": int(minimum)}
 
 361     def handle_lista(self, lista):
 
 362         if 'nazwa' in lista.attrib:
 
 364                 'data-name': lista.attrib['nazwa'],
 
 367             self.options = {'predicate': True}
 
 368         elif 'cel' in lista.attrib:
 
 370                 'data-target': lista.attrib['cel'],
 
 373             self.options = {'subject': True, 'handles': 'uchwyty' in lista.attrib}
 
 376         pre, post = super(Przyporzadkuj, self).handle_lista(lista, attrs)
 
 377         return pre, post + '<br class="clr"/>'
 
 379     def handle_punkt(self, element):
 
 380         if self.options['subject']:
 
 381             self.piece_counter += 1
 
 382             if self.options['handles']:
 
 383                 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>'
 
 385                 return '<li data-solution="%s" data-no="%s" class="question-piece draggable">' % (element.attrib['rozw'], self.piece_counter), '</li>'
 
 387         elif self.options['predicate']:
 
 388             if self.options['min']:
 
 389                 placeholders = u'<li class="placeholder"/>' * self.options['min']
 
 391                 placeholders = u'<li class="placeholder multiple"/>'
 
 392             return '<li data-predicate="%(nazwa)s">' % element.attrib, '<ul class="subjects">' + placeholders + '</ul></li>'
 
 395             return super(Przyporzadkuj, self).handle_punkt(element)
 
 398 class PrawdaFalsz(Exercise):
 
 399     def handle_punkt(self, element):
 
 400         if 'rozw' in element.attrib:
 
 401             return u'''<li data-solution="%s" class="question-piece">
 
 402             <span class="buttons">
 
 403             <a href="#" data-value="true" class="true">Prawda</a>
 
 404             <a href="#" data-value="false" class="false">Fałsz</a>
 
 405         </span>''' % {'prawda': 'true', 'falsz': 'false'}[element.attrib['rozw']], '</li>'
 
 407             return super(PrawdaFalsz, self).handle_punkt(element)
 
 410 class EduModuleFormat(Format):
 
 411     def __init__(self, wldoc, **kwargs):
 
 412         super(EduModuleFormat, self).__init__(wldoc, **kwargs)
 
 415         edumod = EduModule({'provider': self.wldoc.provider, 'urlmapper': self})
 
 417         html = edumod.generate(self.wldoc.edoc.getroot())
 
 419         return IOFile.from_string(html.encode('utf-8'))
 
 421     def url_for_material(self, slug, fmt=None):
 
 422         # No briliant idea for an API here.
 
 424             return "%s.%s" % (slug, fmt)
 
 428 def transform(wldoc, stylesheet='edumed', options=None, flags=None):
 
 429     """Transforms the WL document to XHTML.
 
 431     If output_filename is None, returns an XML,
 
 432     otherwise returns True if file has been written,False if it hasn't.
 
 433     File won't be written if it has no content.
 
 435     edumodfor = EduModuleFormat(wldoc)
 
 436     return edumodfor.build()