Don't show activity counter if it's not adjacent to another activity (PDF)
[librarian.git] / librarian / pyhtml.py
index df94cfd..900d068 100644 (file)
@@ -5,18 +5,44 @@
 #
 from lxml import etree
 from librarian import IOFile, RDFNS, DCNS, Format
-from xmlutils import Xmill, tag, tagged, ifoption
+from xmlutils import Xmill, tag, tagged, ifoption, tag_open_close
 from librarian import functions
 import re
 import random
+from copy import deepcopy
 
+IMAGE_THUMB_WIDTH = 300
 
+try:
+    from fnpdjango.utils.text.slughifi import slughifi
+    def naglowek_to_anchor(naglowek):
+        return slughifi(naglowek.text)
+except ImportError:
+    from urllib import quote
+    def naglowek_to_anchor(naglowek):
+        return quote(re.sub(r" +", " ", naglowek.text.strip()))
+    
+    
 
 class EduModule(Xmill):
     def __init__(self, options=None):
         super(EduModule, self).__init__(options)
         self.activity_counter = 0
+        self.activity_last = None
+        self.exercise_counter = 0
+
+        # text filters
+        def swap_endlines(txt):
+            if self.options['strofa']:
+                txt = txt.replace("/\n", "<br/>\n")
+            return txt
         self.register_text_filter(functions.substitute_entities)
+        self.register_escaped_text_filter(swap_endlines)
+
+    @tagged('div', 'stanza')
+    def handle_strofa(self, element):
+        self.options = {'strofa': True}
+        return "", ""
 
     def handle_powiesc(self, element):
         return u"""
@@ -29,18 +55,41 @@ class EduModule(Xmill):
 """, u"</div>"
 
     handle_autor_utworu = tag("span", "author")
-    handle_nazwa_utworu = tag("h1", "title")
     handle_dzielo_nadrzedne = tag("span", "collection")
     handle_podtytul = tag("span", "subtitle")
     handle_naglowek_akt = handle_naglowek_czesc = handle_srodtytul = tag("h2")
-    handle_naglowek_scena = handle_naglowek_rozdzial = tag('h2')
-    handle_naglowek_osoba = handle_naglowek_podrozdzial = tag('h3')
+    handle_naglowek_scena = tag('h2')
+    handle_naglowek_osoba = tag('h3')
     handle_akap = handle_akap_dialog = handle_akap_cd = tag('p', 'paragraph')
-    handle_strofa = tag('div', 'stanza')
+
     handle_wyroznienie = tag('em')
     handle_tytul_dziela = tag('em', 'title')
     handle_slowo_obce = tag('em', 'foreign')
 
+    def handle_nazwa_utworu(self, element):
+        toc = []
+        for naglowek in element.getparent().findall('.//naglowek_rozdzial'):
+            a = etree.Element("a")
+            a.attrib["href"] = "#" + naglowek_to_anchor(naglowek)
+            a.text = naglowek.text
+            atxt = etree.tostring(a, encoding=unicode)
+            toc.append("<li>%s</li>" % atxt)
+        toc = "<ul class='toc'>%s</ul>" % "".join(toc)
+        add_header = "Lekcja: " if self.options['wldoc'].book_info.type in ('course', 'synthetic') else ''
+        return "<h1 class='title' id='top'>%s" % add_header, "</h1>" + toc
+
+    def handle_naglowek_rozdzial(self, element):
+        return_to_top = u"<a href='#top' class='top-link'>wróć do spisu treści</a>"
+        pre, post = tag_open_close("h2", id=naglowek_to_anchor(element))
+        return return_to_top + pre, post
+
+    def handle_naglowek_podrozdzial(self, element):
+        self.activity_counter = 0
+        return tag('h3')(self, element)
+
+    def handle_uwaga(self, _e):
+        return None
+
     def handle_aktywnosc(self, element):
         self.activity_counter += 1
         self.options = {
@@ -49,7 +98,10 @@ class EduModule(Xmill):
             }
         submill = EduModule(dict(self.options.items() + {'sub_gen': True}.items()))
 
-        opis = submill.generate(element.xpath('opis')[0])
+        if element.xpath('opis'):
+            opis = submill.generate(element.xpath('opis')[0])
+        else:
+            opis = ''
 
         n = element.xpath('wskazowki')
         if n: wskazowki = submill.generate(n[0])
@@ -66,16 +118,23 @@ class EduModule(Xmill):
 
         counter = self.activity_counter
 
+        if element.getnext().tag == 'aktywnosc' or self.activity_last.getnext() == element:
+            counter_html = """<span class="act_counter">%(counter)d.</span>""" % locals()
+        else:
+            counter_html = ''
+
+        self.activity_last = element
+
         return u"""
 <div class="activity">
  <div class="text">
-  <span class="act_counter">%(counter)d.</span>
-  %(opis)s
-  %(wskazowki)s
+  %(counter_html)s
+  %(opis)s""" % locals(), \
+u"""%(wskazowki)s
  </div>
  <aside class="info">
   <section class="infobox time"><h1>Czas</h1><p>%(czas)s min</p></section>
-  <section class="infobox kind"><h1>Forma</h1><p>%(forma)s</p></section>
+  <section class="infobox kind"><h1>Metoda</h1><p>%(forma)s</p></section>
   %(pomoce)s
  </aside>
  <div class="clearboth"></div>
@@ -107,19 +166,32 @@ class EduModule(Xmill):
             }
 
         typ = element.attrib['typ']
+        self.exercise_counter += 1
+        self.options = {'exercise_counter': self.exercise_counter}
         handler = exercise_handlers[typ](self.options)
         return handler.generate(element)
 
     # Lists
     def handle_lista(self, element, attrs={}):
         ltype = element.attrib.get('typ', 'punkt')
+        if not element.findall("punkt"):
+            if ltype == 'czytelnia':
+                return '<p>W przygotowaniu.</p>'
+            else:
+                return None
         if ltype == 'slowniczek':
-            surl = element.attrib.get('href', None)
+            surl = element.attrib.get('src', None)
+            if surl is None:
+                # print '** missing src on <slowniczek>, setting default'
+                surl = 'http://edukacjamedialna.edu.pl/lekcje/slowniczek/'
             sxml = None
             if surl:
                 sxml = etree.fromstring(self.options['provider'].by_uri(surl).get_string())
             self.options = {'slowniczek': True, 'slowniczek_xml': sxml }
-            return '<div class="slowniczek">', '</div>'
+            pre, post = '<div class="slowniczek">', '</div>'
+            if self.options['wldoc'].book_info.url.slug != 'slowniczek':
+                post += u'<p class="see-more"><a href="%s">Zobacz cały słowniczek.</a></p>' % surl
+            return pre, post
 
         listtag = {'num': 'ol',
                'punkt': 'ul',
@@ -144,16 +216,21 @@ class EduModule(Xmill):
         nxt = element.getnext()
         definiens_s = ''
 
+        if not element.text:
+            print "!! Empty <definiendum/>"
+            return None
+
         # let's pull definiens from another document
-        if self.options['slowniczek_xml'] and (not nxt or nxt.tag != 'definiens'):
+        if self.options['slowniczek_xml'] is not None and (nxt is None or nxt.tag != 'definiens'):
             sxml = self.options['slowniczek_xml']
-            assert element.text != ''
             defloc = sxml.xpath("//definiendum[text()='%s']" % element.text)
             if defloc:
                 definiens = defloc[0].getnext()
                 if definiens.tag == 'definiens':
                     subgen = EduModule(self.options)
                     definiens_s = subgen.generate(definiens)
+            else:
+                print '!! Missing definiendum in source:', element.text
 
         return u"<dt>", u"</dt>" + definiens_s
 
@@ -183,20 +260,74 @@ class EduModule(Xmill):
         if 'url' in element.attrib:
             return tag('a', href=element.attrib['url'])(self, element)
         elif 'material' in element.attrib:
-            formats = re.split(r"[, ]+", element.attrib.get('format', 'odt'))
-            fmt_links = []
-            for f in formats:
-                fmt_links.append(u'<a href="%s">%s</a>' % (self.options['urlmapper'].url_for_material(element.attrib['material'], f), f.upper()))
+            material_err = u' [BRAKUJĄCY MATERIAŁ]'
+            slug = element.attrib['material']
+            make_url = lambda f: self.options['urlmapper'] \
+              .url_for_material(slug, f)
+
+            if 'format' in element.attrib:
+                formats = re.split(r"[, ]+",
+                               element.attrib['format'])
+            else:
+                formats = [None]
 
-            return u"", u' (%s)' % u' '.join(fmt_links)
+            formats = self.options['urlmapper'].materials(slug)
+
+            try:
+                def_href = make_url(formats[0][0])
+                def_err = u""
+            except (IndexError, self.options['urlmapper'].MaterialNotFound):
+                def_err = material_err
+                def_href = u""
+            fmt_links = []
+            for f in formats[1:]:
+                try:
+                    fmt_links.append(u'<a href="%s">%s</a>' % (make_url(f[0]), f[0].upper()))
+                except self.options['urlmapper'].MaterialNotFound:
+                    fmt_links.append(u'<a>%s%s</a>' % (f[0].upper(), material_err))
+            more_links = u' (%s)' % u', '.join(fmt_links) if fmt_links else u''
+
+            return u"<a href='%s'>" % def_href, u'%s</a>%s' % (def_err, more_links)
+
+    def handle_obraz(self, element):
+        name = element.attrib.get('nazwa', '').strip()
+        if not name:
+            print '!! <obraz> missing "nazwa"'
+            return
+        alt = element.attrib.get('alt', '')
+        if not alt:
+            print '** <obraz> missing "alt"'
+        slug, ext = name.rsplit('.', 1)
+        url = self.options['urlmapper'].url_for_image(slug, ext)
+        thumb_url = self.options['urlmapper'].url_for_image(slug, ext, IMAGE_THUMB_WIDTH)
+        e = etree.Element("a", attrib={"href": url, "class": "image"})
+        e.append(etree.Element("img", attrib={"src": thumb_url, "alt": alt,
+                    "width": str(IMAGE_THUMB_WIDTH)}))
+        return etree.tostring(e, encoding=unicode), u""
+
+    def handle_video(self, element):
+        url = element.attrib.get('url')
+        if not url:
+            print '!! <video> missing url'
+            return
+        m = re.match(r'(?:https?://)?(?:www.)?youtube.com/watch\?(?:.*&)?v=([^&]+)(?:$|&)', url)
+        if not m:
+            print '!! unknown <video> url scheme:', url
+            return
+        return """<iframe width="630" height="384" src="http://www.youtube.com/embed/%s"
+            frameborder="0" allowfullscreen></iframe>""" % m.group(1), ""
 
 
 class Exercise(EduModule):
+    INSTRUCTION = ""
     def __init__(self, *args, **kw):
         self.question_counter = 0
         super(Exercise, self).__init__(*args, **kw)
+        self.instruction_printed = False
 
-    handle_opis = tag('div', 'description')
+    @tagged('div', 'description')
+    def handle_opis(self, element):
+        return "", self.get_instruction()
 
     def handle_rozw_kom(self, element):
         return u"""<div style="display:none" class="comment">""", u"""</div>"""
@@ -209,7 +340,16 @@ class Exercise(EduModule):
         pre = u"""
 <div class="exercise %(typ)s" data-type="%(typ)s">
 <form action="#" method="POST">
-""" % element.attrib
+<h3>Zadanie %(exercies_counter)d</h3>
+<div class="buttons">
+<span class="message"></span>
+<input type="button" class="check" value="sprawdź"/>
+<input type="button" class="retry" style="display:none" value="spróbuj ponownie"/>
+<input type="button" class="solutions" value="pokaż rozwiązanie"/>
+<input type="button" class="reset" value="reset"/>
+</div>
+
+""" % {'exercies_counter': self.options['exercise_counter'], 'typ': element.attrib['typ']}
         post = u"""
 <div class="buttons">
 <span class="message"></span>
@@ -251,16 +391,37 @@ class Exercise(EduModule):
             (add_class, self.question_counter, solution_s + minimum_s), \
             "</div>"
 
+    def get_instruction(self):
+        if not self.instruction_printed:
+            self.instruction_printed = True
+            if self.INSTRUCTION:
+                return u'<span class="instruction">%s</span>' % self.INSTRUCTION
+            else:
+                return ""
+        else:
+            return ""
+
+
 
 class Wybor(Exercise):
     def handle_cwiczenie(self, element):
         pre, post = super(Wybor, self).handle_cwiczenie(element)
         is_single_choice = True
-        for p in element.xpath(".//pytanie"):
-            solutions = re.split(r"[, ]+", p.attrib['rozw'])
+        pytania = element.xpath(".//pytanie")
+        if not pytania:
+            pytania = [element]
+        for p in pytania:
+            solutions = re.split(r"[, ]+", p.attrib.get('rozw', ''))
             if len(solutions) != 1:
                 is_single_choice = False
                 break
+            choices = p.xpath(".//*[@nazwa]")
+            uniq = set()
+            for n in choices: uniq.add(n.attrib.get('nazwa', ''))
+            if len(choices) != len(uniq):
+                is_single_choice = False
+                break
+
         self.options = {'single': is_single_choice}
         return pre, post
 
@@ -289,6 +450,8 @@ class Wybor(Exercise):
 
 
 class Uporzadkuj(Exercise):
+    INSTRUCTION = u"Kliknij wybraną odpowiedź i przeciągnij w nowe miejsce."
+
     def handle_pytanie(self, element):
         """
 Overrides the returned content default handle_pytanie
@@ -302,19 +465,21 @@ Overrides the returned content default handle_pytanie
             u"""</div>"""
 
     def handle_punkt(self, element):
-        return """<li class="question-piece" data-pos="%(rozw)s"/>""" \
+        return """<li class="question-piece" data-pos="%(rozw)s">""" \
             % element.attrib,\
             "</li>"
 
 
 class Luki(Exercise):
+    INSTRUCTION = u"Przeciągnij odpowiedzi i upuść w wybranym polu."
     def find_pieces(self, question):
         return question.xpath(".//luka")
 
     def solution_html(self, piece):
-        return piece.text + ''.join(
-            [etree.tostring(n, encoding=unicode)
-             for n in piece])
+        piece = deepcopy(piece)
+        piece.tail = None
+        sub = EduModule()
+        return sub.generate(piece)
 
     def handle_pytanie(self, element):
         qpre, qpost = super(Luki, self).handle_pytanie(element)
@@ -340,11 +505,13 @@ class Luki(Exercise):
 
 
 class Zastap(Luki):
+    INSTRUCTION = u"Przeciągnij odpowiedzi i upuść je na słowie lub wyrażeniu, które chcesz zastąpić."
+
     def find_pieces(self, question):
         return question.xpath(".//zastap")
 
     def solution_html(self, piece):
-        return piece.attrib['rozw']
+        return piece.attrib.get('rozw', '')
 
     def handle_zastap(self, element):
         self.piece_counter += 1
@@ -353,6 +520,23 @@ class Zastap(Luki):
 
 
 class Przyporzadkuj(Exercise):
+    INSTRUCTION = [u"Przeciągnij odpowiedzi i upuść w wybranym polu.",
+                   u"Kliknij numer odpowiedzi, przeciągnij i upuść w wybranym polu."]
+
+    def get_instruction(self):
+        if not self.instruction_printed:
+            self.instruction_printed = True
+            return u'<span class="instruction">%s</span>' % self.INSTRUCTION[self.options['handles'] and 1 or 0]
+        else:
+            return ""
+
+    def handle_cwiczenie(self, element):
+        pre, post = super(Przyporzadkuj, self).handle_cwiczenie(element)
+        lista_with_handles = element.xpath(".//*[@uchwyty]")
+        if lista_with_handles:
+            self.options = {'handles': True}
+        return pre, post
+
     def handle_pytanie(self, element):
         pre, post = super(Przyporzadkuj, self).handle_pytanie(element)
         minimum = element.attrib.get("min", None)
@@ -372,7 +556,7 @@ class Przyporzadkuj(Exercise):
                 'data-target': lista.attrib['cel'],
                 'class': 'subject'
             }
-            self.options = {'subject': True, 'handles': 'uchwyty' in lista.attrib}
+            self.options = {'subject': True}
         else:
             attrs = {}
         pre, post = super(Przyporzadkuj, self).handle_lista(lista, attrs)
@@ -382,16 +566,16 @@ class Przyporzadkuj(Exercise):
         if self.options['subject']:
             self.piece_counter += 1
             if self.options['handles']:
-                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>'
+                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>'
             else:
-                return '<li data-solution="%s" data-no="%s" class="question-piece draggable">' % (element.attrib['rozw'], self.piece_counter), '</li>'
+                return '<li data-solution="%s" data-no="%s" class="question-piece draggable">' % (element.attrib.get('rozw', ''), self.piece_counter), '</li>'
 
         elif self.options['predicate']:
             if self.options['min']:
-                placeholders = u'<li class="placeholder"/>' * self.options['min']
+                placeholders = u'<li class="placeholder"></li>' * self.options['min']
             else:
-                placeholders = u'<li class="placeholder multiple"/>'
-            return '<li data-predicate="%(nazwa)s">' % element.attrib, '<ul class="subjects">' + placeholders + '</ul></li>'
+                placeholders = u'<li class="placeholder multiple"></li>'
+            return '<li data-predicate="%s">' % element.attrib.get('nazwa', ''), '<ul class="subjects">' + placeholders + '</ul></li>'
 
         else:
             return super(Przyporzadkuj, self).handle_punkt(element)
@@ -410,21 +594,45 @@ class PrawdaFalsz(Exercise):
 
 
 class EduModuleFormat(Format):
+    PRIMARY_MATERIAL_FORMATS = ('pdf', 'odt')
+
+    class MaterialNotFound(BaseException):
+        pass
+
     def __init__(self, wldoc, **kwargs):
         super(EduModuleFormat, self).__init__(wldoc, **kwargs)
 
     def build(self):
-        edumod = EduModule({'provider': self.wldoc.provider, 'urlmapper': self})
+        # Sort materials by slug.
+        self.materials_by_slug = {}
+        for name, att in self.wldoc.source.attachments.items():
+            parts = name.rsplit('.', 1)
+            if len(parts) == 1:
+                continue
+            slug, ext = parts
+            if slug not in self.materials_by_slug:
+                self.materials_by_slug[slug] = {}
+            self.materials_by_slug[slug][ext] = att
+
+        edumod = EduModule({'provider': self.wldoc.provider, 'urlmapper': self, 'wldoc': self.wldoc})
 
         html = edumod.generate(self.wldoc.edoc.getroot())
 
         return IOFile.from_string(html.encode('utf-8'))
 
-    def url_for_material(self, slug, fmt=None):
-        # No briliant idea for an API here.
-        if fmt:
-            return "%s.%s" % (slug, fmt)
-        return slug
+    def materials(self, slug):
+        """Returns a list of pairs: (ext, iofile)."""
+        order = dict(reversed(k) for k in enumerate(self.PRIMARY_MATERIAL_FORMATS))
+        mats = self.materials_by_slug.get(slug, {}).items()
+        if not mats:
+            print "!! Material missing: '%s'" % slug
+        return sorted(mats, key=lambda (x, y): order.get(x, x))
+
+    def url_for_material(self, slug, fmt):
+        return "%s.%s" % (slug, fmt)
+
+    def url_for_image(self, slug, fmt, width=None):
+        return self.url_for_material(self, slug, fmt)
 
 
 def transform(wldoc, stylesheet='edumed', options=None, flags=None):