converters interface changed: WLDocument in, OutputFile out
[librarian.git] / librarian / __init__.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 import os
7 import re
8 import shutil
9
10 class ParseError(Exception):
11     def __str__(self):
12         """ Dirty workaround for Python Unicode handling problems. """
13         return self.message
14
15     def __unicode__(self):
16         """ Dirty workaround for Python Unicode handling problems. """
17         return self.message
18
19 class ValidationError(Exception):
20     pass
21
22 class NoDublinCore(ValidationError):
23     """There's no DublinCore section, and it's required."""
24     pass
25
26 class NoProvider(Exception):
27     """There's no DocProvider specified, and it's needed."""
28     pass
29
30 class XMLNamespace(object):
31     '''A handy structure to repsent names in an XML namespace.'''
32
33     def __init__(self, uri):
34         self.uri = uri
35
36     def __call__(self, tag):
37         return '{%s}%s' % (self.uri, tag)
38
39     def __contains__(self, tag):
40         return tag.startswith('{' + str(self) + '}')
41
42     def __repr__(self):
43         return 'XMLNamespace(%r)' % self.uri
44
45     def __str__(self):
46         return '%s' % self.uri
47
48 class EmptyNamespace(XMLNamespace):
49     def __init__(self):
50         super(EmptyNamespace, self).__init__('')
51
52     def __call__(self, tag):
53         return tag
54
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")
62
63 WLNS = EmptyNamespace()
64
65
66 class WLURI(object):
67     """Represents a WL URI. Extracts slug and language from it."""
68
69     slug = None
70     language = None
71
72     _re_wl_uri = re.compile('http://wolnelektury.pl/katalog/lektura/'
73             '(?P<slug>[-a-z]+)(/(?P<lang>[a-z]{3})/?)?')
74
75     def __init__(self, uri):
76         self.uri = uri
77         match = self._re_wl_uri.match(uri)
78         assert match
79         self.slug = match.group('slug')
80         self.language = match.group('lang')
81
82
83 class DocProvider(object):
84     """Base class for a repository of XML files.
85
86     Used for generating joined files, like EPUBs.
87     """
88
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
92
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)
96
97     def by_uri(self, uri):
98         """Should return a file-like object with a WL document XML."""
99         wluri = WLURI(uri)
100         return self.by_slug_and_lang(wluri.slug, wluri.language)
101
102
103 class DirDocProvider(DocProvider):
104     """ Serve docs from a directory of files in form <slug>.xml """
105
106     def __init__(self, dir_):
107         self.dir = dir_
108         self.files = {}
109         return super(DirDocProvider, self).__init__()
110
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))
114
115
116 import lxml.etree as etree
117 import dcparser
118
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"],
130           DCNS('description'):
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"],
137           DCNS('rights'):
138             [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
139
140 def xinclude_forURI(uri):
141     e = etree.Element(XINS("include"))
142     e.set("href", uri)
143     return etree.tostring(e, encoding=unicode)
144
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
148
149     dcstring = etree.tostring(bookinfo.to_etree(), \
150         method='xml', encoding=unicode, pretty_print=True)
151
152     return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext + \
153         u'\n</plain-text>\n</utwor>'
154
155
156 def serialize_raw(element):
157     b = u'' + (element.text or '')
158
159     for child in element.iterchildren():
160         e = etree.tostring(child, method='xml', encoding=unicode,
161                 pretty_print=True)
162         b += e
163
164     return b
165
166 SERIALIZERS = {
167     'raw': serialize_raw,
168 }
169
170 def serialize_children(element, format='raw'):
171     return SERIALIZERS[format](element)
172
173 def get_resource(path):
174     return os.path.join(os.path.dirname(__file__), path)
175
176
177 class OutputFile(object):
178     """Represents a file returned by one of the converters."""
179
180     _string = None
181     _filename = None
182
183     def __del__(self):
184         if self._filename:
185             os.unlink(self._filename)
186
187     def __nonzero__(self):
188         return self._string is not None or self._filename is not None
189
190     @classmethod
191     def from_string(cls, string):
192         """Converter returns contents of a file as a string."""
193
194         instance = cls()
195         instance._string = string
196         return instance
197
198     @classmethod
199     def from_filename(cls, filename):
200         """Converter returns contents of a file as a named file."""
201
202         instance = cls()
203         instance._filename = filename
204         return instance
205
206     def get_string(self):
207         """Get file's contents as a string."""
208
209         if self._filename is not None:
210             with open(self._filename) as f:
211                 return f.read()
212         else:
213             return self._string
214
215     def get_file(self):
216         """Get file as a file-like object."""
217
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)
223
224     def get_filename(self):
225         """Get file as a fs path."""
226
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)
233             temp.close()
234             self._filename = temp.name
235             return self._filename
236         else:
237             return None
238
239     def save_as(self, path):
240         """Save file to a path. Create directories, if necessary."""
241
242         dirname = os.path.dirname(os.path.abspath(path))
243         if not os.path.isdir(dirname):
244             os.makedirs(dirname)
245         shutil.copy(self.get_filename(), path)