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 from __future__ import with_statement
12 class ParseError(Exception):
14 """ Dirty workaround for Python Unicode handling problems. """
17 def __unicode__(self):
18 """ Dirty workaround for Python Unicode handling problems. """
21 class ValidationError(Exception):
24 class NoDublinCore(ValidationError):
25 """There's no DublinCore section, and it's required."""
28 class NoProvider(Exception):
29 """There's no DocProvider specified, and it's needed."""
32 class XMLNamespace(object):
33 '''A handy structure to repsent names in an XML namespace.'''
35 def __init__(self, uri):
38 def __call__(self, tag):
39 return '{%s}%s' % (self.uri, tag)
41 def __contains__(self, tag):
42 return tag.startswith('{' + str(self) + '}')
45 return 'XMLNamespace(%r)' % self.uri
48 return '%s' % self.uri
50 class EmptyNamespace(XMLNamespace):
52 super(EmptyNamespace, self).__init__('')
54 def __call__(self, tag):
57 # some common namespaces we use
58 RDFNS = XMLNamespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
59 DCNS = XMLNamespace('http://purl.org/dc/elements/1.1/')
60 XINS = XMLNamespace("http://www.w3.org/2001/XInclude")
61 XHTMLNS = XMLNamespace("http://www.w3.org/1999/xhtml")
62 NCXNS = XMLNamespace("http://www.daisy.org/z3986/2005/ncx/")
63 OPFNS = XMLNamespace("http://www.idpf.org/2007/opf")
65 WLNS = EmptyNamespace()
69 """Represents a WL URI. Extracts slug and language from it."""
70 DEFAULT_LANGUAGE = u'pol'
75 example = 'http://wolnelektury.pl/katalog/lektura/template/'
76 _re_wl_uri = re.compile('http://wolnelektury.pl/katalog/lektura/'
77 '(?P<slug>[-a-z0-9]+)(/(?P<lang>[a-z]{3}))?/?$')
79 def __init__(self, uri=None):
83 match = self._re_wl_uri.match(uri)
85 raise ValueError('Supplied URI (%s) does not match '
86 'the WL document URI template.' % uri)
87 self.slug = match.group('slug')
88 self.language = match.group('lang') or self.DEFAULT_LANGUAGE
91 def from_slug_and_lang(cls, slug, lang):
92 """Contructs an URI from slug and language code.
94 >>> WLURI.from_slug_and_lang('a-slug', WLURI.DEFAULT_LANGUAGE).uri
95 'http://wolnelektury.pl/katalog/lektura/a-slug/'
96 >>> WLURI.from_slug_and_lang('a-slug', 'deu').uri
97 'http://wolnelektury.pl/katalog/lektura/a-slug/deu/'
101 lang = cls.DEFAULT_LANGUAGE
102 uri = 'http://wolnelektury.pl/katalog/lektura/%s/' % slug
103 if lang is not None and lang != cls.DEFAULT_LANGUAGE:
107 def __unicode__(self):
113 def __eq__(self, other):
114 return self.slug, self.language == other.slug, other.language
116 def filename_stem(self):
118 if self.language != self.DEFAULT_LANGUAGE:
119 stem += '_' + self.language
122 def validate_language(self, language):
123 if language != self.language:
124 raise ValidationError("Incorrect language definition in URI")
127 class DocProvider(object):
128 """Base class for a repository of XML files.
130 Used for generating joined files, like EPUBs.
133 def by_slug_and_lang(self, slug, lang=None):
134 """Should return a file-like object with a WL document XML."""
135 raise NotImplementedError
137 def by_slug(self, slug):
138 """Should return a file-like object with a WL document XML."""
139 return self.by_slug_and_lang(slug)
141 def by_uri(self, uri):
142 """Should return a file-like object with a WL document XML."""
144 return self.by_slug_and_lang(wluri.slug, wluri.language)
147 class DirDocProvider(DocProvider):
148 """ Serve docs from a directory of files in form <slug>.xml """
150 def __init__(self, dir_):
153 return super(DirDocProvider, self).__init__()
155 def by_slug_and_lang(self, slug, lang=None):
156 fname = WLURI.from_slug_and_lang(slug, lang).filename_stem() + '.xml'
157 return open(os.path.join(self.dir, fname))
160 import lxml.etree as etree
163 DEFAULT_BOOKINFO = dcparser.BookInfo(
164 { RDFNS('about'): u'http://wiki.wolnepodreczniki.pl/Lektury:Template'},
165 { DCNS('creator'): [u'Some, Author'],
166 DCNS('title'): [u'Some Title'],
167 DCNS('subject.period'): [u'Unknown'],
168 DCNS('subject.type'): [u'Unknown'],
169 DCNS('subject.genre'): [u'Unknown'],
170 DCNS('date'): ['1970-01-01'],
171 DCNS('language'): [WLURI.DEFAULT_LANGUAGE],
172 # DCNS('date'): [creation_date],
173 DCNS('publisher'): [u"Fundacja Nowoczesna Polska"],
175 [u"""Publikacja zrealizowana w ramach projektu
176 Wolne Lektury (http://wolnelektury.pl). Reprodukcja cyfrowa
177 wykonana przez Bibliotekę Narodową z egzemplarza
178 pochodzącego ze zbiorów BN."""],
179 DCNS('identifier.url'): [WLURI.example],
181 [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
183 def xinclude_forURI(uri):
184 e = etree.Element(XINS("include"))
186 return etree.tostring(e, encoding=unicode)
188 def wrap_text(ocrtext, creation_date, bookinfo=DEFAULT_BOOKINFO):
189 """Wrap the text within the minimal XML structure with a DC template."""
190 bookinfo.created_at = creation_date
192 dcstring = etree.tostring(bookinfo.to_etree(), \
193 method='xml', encoding=unicode, pretty_print=True)
195 return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext + \
196 u'\n</plain-text>\n</utwor>'
199 def serialize_raw(element):
200 b = u'' + (element.text or '')
202 for child in element.iterchildren():
203 e = etree.tostring(child, method='xml', encoding=unicode,
210 'raw': serialize_raw,
213 def serialize_children(element, format='raw'):
214 return SERIALIZERS[format](element)
216 def get_resource(path):
217 return os.path.join(os.path.dirname(__file__), path)
220 class OutputFile(object):
221 """Represents a file returned by one of the converters."""
228 os.unlink(self._filename)
230 def __nonzero__(self):
231 return self._string is not None or self._filename is not None
234 def from_string(cls, string):
235 """Converter returns contents of a file as a string."""
238 instance._string = string
242 def from_filename(cls, filename):
243 """Converter returns contents of a file as a named file."""
246 instance._filename = filename
249 def get_string(self):
250 """Get file's contents as a string."""
252 if self._filename is not None:
253 with open(self._filename) as f:
259 """Get file as a file-like object."""
261 if self._string is not None:
262 from StringIO import StringIO
263 return StringIO(self._string)
264 elif self._filename is not None:
265 return open(self._filename)
267 def get_filename(self):
268 """Get file as a fs path."""
270 if self._filename is not None:
271 return self._filename
272 elif self._string is not None:
273 from tempfile import NamedTemporaryFile
274 temp = NamedTemporaryFile(prefix='librarian-', delete=False)
275 temp.write(self._string)
277 self._filename = temp.name
278 return self._filename
282 def save_as(self, path):
283 """Save file to a path. Create directories, if necessary."""
285 dirname = os.path.dirname(os.path.abspath(path))
286 if not os.path.isdir(dirname):
288 shutil.copy(self.get_filename(), path)