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.
8 class ParseError(Exception):
10 """ Dirty workaround for Python Unicode handling problems. """
13 def __unicode__(self):
14 """ Dirty workaround for Python Unicode handling problems. """
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")
53 NCXNS = XMLNamespace("http://www.daisy.org/z3986/2005/ncx/")
54 OPFNS = XMLNamespace("http://www.idpf.org/2007/opf")
56 WLNS = EmptyNamespace()
59 class DocProvider(object):
60 """ Base class for a repository of XML files.
61 Used for generating joined files, like EPUBs
64 def by_slug(self, slug):
67 def __getitem__(self, slug):
68 return self.by_slug(slug)
70 def by_uri(self, uri):
71 return self.by_slug(uri.rsplit('/', 1)[1])
74 class DirDocProvider(DocProvider):
75 """ Serve docs from a directory of files in form <slug>.xml """
77 def __init__(self, dir):
81 def by_slug(self, slug):
82 return open(os.path.join(self.dir, '%s.xml' % slug))
85 import lxml.etree as etree
88 DEFAULT_BOOKINFO = dcparser.BookInfo(
89 { RDFNS('about'): u'http://wiki.wolnepodreczniki.pl/Lektury:Template'}, \
90 { DCNS('creator'): [u'Some, Author'],
91 DCNS('title'): [u'Some Title'],
92 DCNS('subject.period'): [u'Unknown'],
93 DCNS('subject.type'): [u'Unknown'],
94 DCNS('subject.genre'): [u'Unknown'],
95 DCNS('date'): ['1970-01-01'],
96 DCNS('language'): [u'pol'],
97 # DCNS('date'): [creation_date],
98 DCNS('publisher'): [u"Fundacja Nowoczesna Polska"],
100 [u"""Publikacja zrealizowana w ramach projektu
101 Wolne Lektury (http://wolnelektury.pl). Reprodukcja cyfrowa
102 wykonana przez Bibliotekę Narodową z egzemplarza
103 pochodzącego ze zbiorów BN."""],
104 DCNS('identifier.url'):
105 [u"http://wolnelektury.pl/katalog/lektura/template"],
107 [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
109 def xinclude_forURI(uri):
110 e = etree.Element(XINS("include"))
112 return etree.tostring(e, encoding=unicode)
114 def wrap_text(ocrtext, creation_date, bookinfo=DEFAULT_BOOKINFO):
115 """Wrap the text within the minimal XML structure with a DC template."""
116 bookinfo.created_at = creation_date
118 dcstring = etree.tostring(bookinfo.to_etree(), \
119 method='xml', encoding=unicode, pretty_print=True)
121 return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext + \
122 u'\n</plain-text>\n</utwor>';
125 def serialize_raw(element):
126 b = u'' + (element.text or '')
128 for child in element.iterchildren():
129 e = etree.tostring(child, method='xml', encoding=unicode, pretty_print=True)
135 'raw': serialize_raw,
138 def serialize_children(element, format='raw'):
139 return SERIALIZERS[format](element)
141 def get_resource(path):
142 return os.path.join(os.path.dirname(__file__), path)