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.
6 class ParseError(Exception):
8 def __init__(self, cause, message=None):
11 self.message = message or self.cause.message
13 self.message = "No message."
15 class ValidationError(Exception):
18 class NoDublinCore(ValidationError):
21 class XMLNamespace(object):
22 '''A handy structure to repsent names in an XML namespace.'''
24 def __init__(self, uri):
27 def __call__(self, tag):
28 return '{%s}%s' % (self.uri, tag)
30 def __contains__(self, tag):
31 return tag.startswith('{'+str(self)+'}')
34 return 'XMLNamespace(%r)' % self.uri
37 return '%s' % self.uri
39 class EmptyNamespace(XMLNamespace):
41 super(EmptyNamespace, self).__init__('')
43 def __call__(self, tag):
46 # some common namespaces we use
47 RDFNS = XMLNamespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
48 DCNS = XMLNamespace('http://purl.org/dc/elements/1.1/')
49 XINS = XMLNamespace("http://www.w3.org/2001/XInclude")
50 XHTMLNS = XMLNamespace("http://www.w3.org/1999/xhtml")
52 WLNS = EmptyNamespace()
54 import lxml.etree as etree
57 DEFAULT_BOOKINFO = dcparser.BookInfo(
58 { RDFNS('about'): u'http://wiki.wolnepodreczniki.pl/Lektury:Template'},\
59 { DCNS('creator'): [u'Some, Author'],
60 DCNS('title'): [u'Some Title'],
61 DCNS('subject.period'): [u'Unknown'],
62 DCNS('subject.type'): [u'Unknown'],
63 DCNS('subject.genre'): [u'Unknown'],
64 DCNS('date'): ['1970-01-01'],
65 # DCNS('date'): [creation_date],
66 DCNS('publisher'): [u"Fundacja Nowoczesna Polska"],
68 [u"""Publikacja zrealizowana w ramach projektu
69 Wolne Lektury (http://wolnelektury.pl). Reprodukcja cyfrowa
70 wykonana przez Bibliotekę Narodową z egzemplarza
71 pochodzącego ze zbiorów BN."""],
72 DCNS('identifier.url'):
73 [u"http://wolnelektury.pl/katalog/lektura/template"],
75 [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
77 def xinclude_forURI(uri):
78 e = etree.Element( XINS("include") )
80 return etree.tostring(e, encoding=unicode)
82 def wrap_text(ocrtext, creation_date, bookinfo=DEFAULT_BOOKINFO):
83 """Wrap the text within the minimal XML structure with a DC template."""
84 bookinfo.created_at = creation_date
86 dcstring = etree.tostring(bookinfo.to_etree(),\
87 method='xml', encoding=unicode, pretty_print=True)
89 return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext +\
90 u'\n</plain-text>\n</utwor>';
93 def serialize_raw(element):
94 b = u'' + (element.text or '')
96 for child in element.iterchildren():
97 e = etree.tostring(child, method='xml', encoding=unicode, pretty_print=True)
103 'raw': serialize_raw,
106 def serialize_children(element, format='raw'):
107 return SERIALIZERS[format](element)