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.
10 class ParseError(Exception):
12 """ Dirty workaround for Python Unicode handling problems. """
15 def __unicode__(self):
16 """ Dirty workaround for Python Unicode handling problems. """
19 class ValidationError(Exception):
22 class NoDublinCore(ValidationError):
23 """There's no DublinCore section, and it's required."""
26 class NoProvider(Exception):
27 """There's no DocProvider specified, and it's needed."""
30 class XMLNamespace(object):
31 '''A handy structure to repsent names in an XML namespace.'''
33 def __init__(self, uri):
36 def __call__(self, tag):
37 return '{%s}%s' % (self.uri, tag)
39 def __contains__(self, tag):
40 return tag.startswith('{' + str(self) + '}')
43 return 'XMLNamespace(%r)' % self.uri
46 return '%s' % self.uri
48 class EmptyNamespace(XMLNamespace):
50 super(EmptyNamespace, self).__init__('')
52 def __call__(self, tag):
55 # some common namespaces we use
56 RDFNS = XMLNamespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
57 DCNS = XMLNamespace('http://purl.org/dc/elements/1.1/')
58 XINS = XMLNamespace("http://www.w3.org/2001/XInclude")
59 XHTMLNS = XMLNamespace("http://www.w3.org/1999/xhtml")
60 NCXNS = XMLNamespace("http://www.daisy.org/z3986/2005/ncx/")
61 OPFNS = XMLNamespace("http://www.idpf.org/2007/opf")
63 WLNS = EmptyNamespace()
67 """Represents a WL URI. Extracts slug and language from it."""
72 _re_wl_uri = re.compile('http://wolnelektury.pl/katalog/lektura/'
73 '(?P<slug>[-a-z]+)(/(?P<lang>[a-z]{3})/?)?')
75 def __init__(self, uri):
77 match = self._re_wl_uri.match(uri)
79 self.slug = match.group('slug')
80 self.language = match.group('lang')
83 class DocProvider(object):
84 """Base class for a repository of XML files.
86 Used for generating joined files, like EPUBs.
89 def by_slug_and_lang(self, slug, lang=None):
90 """Should return a file-like object with a WL document XML."""
91 raise NotImplementedError
93 def by_slug(self, slug):
94 """Should return a file-like object with a WL document XML."""
95 return self.by_slug_and_lang(slug)
97 def by_uri(self, uri):
98 """Should return a file-like object with a WL document XML."""
100 return self.by_slug_and_lang(wluri.slug, wluri.language)
103 class DirDocProvider(DocProvider):
104 """ Serve docs from a directory of files in form <slug>.xml """
106 def __init__(self, dir_):
109 return super(DirDocProvider, self).__init__()
111 def by_slug_and_lang(self, slug, lang=None):
112 fname = "%s%s.xml" % (slug, ".%s" % lang if lang else "")
113 return open(os.path.join(self.dir, fname))
116 import lxml.etree as etree
119 DEFAULT_BOOKINFO = dcparser.BookInfo(
120 { RDFNS('about'): u'http://wiki.wolnepodreczniki.pl/Lektury:Template'},
121 { DCNS('creator'): [u'Some, Author'],
122 DCNS('title'): [u'Some Title'],
123 DCNS('subject.period'): [u'Unknown'],
124 DCNS('subject.type'): [u'Unknown'],
125 DCNS('subject.genre'): [u'Unknown'],
126 DCNS('date'): ['1970-01-01'],
127 DCNS('language'): [u'pol'],
128 # DCNS('date'): [creation_date],
129 DCNS('publisher'): [u"Fundacja Nowoczesna Polska"],
131 [u"""Publikacja zrealizowana w ramach projektu
132 Wolne Lektury (http://wolnelektury.pl). Reprodukcja cyfrowa
133 wykonana przez Bibliotekę Narodową z egzemplarza
134 pochodzącego ze zbiorów BN."""],
135 DCNS('identifier.url'):
136 [u"http://wolnelektury.pl/katalog/lektura/template"],
138 [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
140 def xinclude_forURI(uri):
141 e = etree.Element(XINS("include"))
143 return etree.tostring(e, encoding=unicode)
145 def wrap_text(ocrtext, creation_date, bookinfo=DEFAULT_BOOKINFO):
146 """Wrap the text within the minimal XML structure with a DC template."""
147 bookinfo.created_at = creation_date
149 dcstring = etree.tostring(bookinfo.to_etree(), \
150 method='xml', encoding=unicode, pretty_print=True)
152 return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext + \
153 u'\n</plain-text>\n</utwor>'
156 def serialize_raw(element):
157 b = u'' + (element.text or '')
159 for child in element.iterchildren():
160 e = etree.tostring(child, method='xml', encoding=unicode,
167 'raw': serialize_raw,
170 def serialize_children(element, format='raw'):
171 return SERIALIZERS[format](element)
173 def get_resource(path):
174 return os.path.join(os.path.dirname(__file__), path)
177 class OutputFile(object):
178 """Represents a file returned by one of the converters."""
185 os.unlink(self._filename)
187 def __nonzero__(self):
188 return self._string is not None or self._filename is not None
191 def from_string(cls, string):
192 """Converter returns contents of a file as a string."""
195 instance._string = string
199 def from_filename(cls, filename):
200 """Converter returns contents of a file as a named file."""
203 instance._filename = filename
206 def get_string(self):
207 """Get file's contents as a string."""
209 if self._filename is not None:
210 with open(self._filename) as f:
216 """Get file as a file-like object."""
218 if self._string is not None:
219 from StringIO import StringIO
220 return StringIO(self._string)
221 elif self._filename is not None:
222 return open(self._filename)
224 def get_filename(self):
225 """Get file as a fs path."""
227 if self._filename is not None:
228 return self._filename
229 elif self._string is not None:
230 from tempfile import NamedTemporaryFile
231 temp = NamedTemporaryFile(prefix='librarian-', delete=False)
232 temp.write(self._string)
234 self._filename = temp.name
235 return self._filename
239 def save_as(self, path):
240 """Save file to a path. Create directories, if necessary."""
242 dirname = os.path.dirname(os.path.abspath(path))
243 if not os.path.isdir(dirname):
245 shutil.copy(self.get_filename(), path)