1 # -*- coding: utf-8 -*-
3 # Copyright © 2008,2009,2010 Fundacja Nowoczesna Polska
5 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
6 # For full license text see COPYING or <http://www.gnu.org/licenses/agpl.html>
8 class ParseError(Exception):
10 def __init__(self, cause, message=None):
13 self.message = message or self.cause.message
15 self.message = "No message."
17 class ValidationError(Exception):
20 class NoDublinCore(ValidationError):
23 class XMLNamespace(object):
24 '''A handy structure to repsent names in an XML namespace.'''
26 def __init__(self, uri):
29 def __call__(self, tag):
30 return '{%s}%s' % (self.uri, tag)
32 def __contains__(self, tag):
33 return tag.startswith('{'+str(self)+'}')
36 return 'XMLNamespace(%r)' % self.uri
39 return '%s' % self.uri
41 class EmptyNamespace(XMLNamespace):
43 super(EmptyNamespace, self).__init__('')
45 def __call__(self, tag):
48 # some common namespaces we use
49 RDFNS = XMLNamespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
50 DCNS = XMLNamespace('http://purl.org/dc/elements/1.1/')
51 XINS = XMLNamespace("http://www.w3.org/2001/XInclude")
52 XHTMLNS = XMLNamespace("http://www.w3.org/1999/xhtml")
54 WLNS = EmptyNamespace()
56 import lxml.etree as etree
59 DEFAULT_BOOKINFO = dcparser.BookInfo(
60 { RDFNS('about'): u'http://wiki.wolnepodreczniki.pl/Lektury:Template'},\
61 { DCNS('creator'): [u'Some, Author'],
62 DCNS('title'): [u'Some Title'],
63 DCNS('subject.period'): [u'Unknown'],
64 DCNS('subject.type'): [u'Unknown'],
65 DCNS('subject.genre'): [u'Unknown'],
66 DCNS('date'): ['1970-01-01'],
67 # DCNS('date'): [creation_date],
68 DCNS('publisher'): [u"Fundacja Nowoczesna Polska"],
70 [u"""Publikacja zrealizowana w ramach projektu
71 Wolne Lektury (http://wolnelektury.pl). Reprodukcja cyfrowa
72 wykonana przez Bibliotekę Narodową z egzemplarza
73 pochodzącego ze zbiorów BN."""],
74 DCNS('identifier.url'):
75 [u"http://wolnelektury.pl/katalog/lektura/template"],
77 [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
79 def xinclude_forURI(uri):
80 e = etree.Element( XINS("include") )
82 return etree.tostring(e, encoding=unicode)
84 def wrap_text(ocrtext, creation_date, bookinfo=DEFAULT_BOOKINFO):
85 """Wrap the text within the minimal XML structure with a DC template."""
86 bookinfo.created_at = creation_date
88 dcstring = etree.tostring(bookinfo.to_etree(),\
89 method='xml', encoding=unicode, pretty_print=True)
91 return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext +\
92 u'\n</plain-text>\n</utwor>';
95 def serialize_raw(element):
96 b = u'' + (element.text or '')
98 for child in element.iterchildren():
99 e = etree.tostring(child, method='xml', encoding=unicode, pretty_print=True)
105 'raw': serialize_raw,
108 def serialize_children(element, format='raw'):
109 return SERIALIZERS[format](element)