Merge branch 'pdf'
[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
8 class ParseError(Exception):
9     def __str__(self):
10         """ Dirty workaround for Python Unicode handling problems. """
11         return self.message
12
13     def __unicode__(self):
14         """ Dirty workaround for Python Unicode handling problems. """
15         return self.message
16
17 class ValidationError(Exception):
18     pass
19
20 class NoDublinCore(ValidationError):
21     pass
22
23 class XMLNamespace(object):
24     '''A handy structure to repsent names in an XML namespace.'''
25
26     def __init__(self, uri):
27         self.uri = uri
28
29     def __call__(self, tag):
30         return '{%s}%s' % (self.uri, tag)
31
32     def __contains__(self, tag):
33         return tag.startswith('{' + str(self) + '}')
34
35     def __repr__(self):
36         return 'XMLNamespace(%r)' % self.uri
37
38     def __str__(self):
39         return '%s' % self.uri
40
41 class EmptyNamespace(XMLNamespace):
42     def __init__(self):
43         super(EmptyNamespace, self).__init__('')
44
45     def __call__(self, tag):
46         return tag
47
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")
55
56 WLNS = EmptyNamespace()
57
58
59 class DocProvider(object):
60     """ Base class for a repository of XML files.
61         Used for generating joined files, like EPUBs
62     """
63
64     def by_slug(self, slug):
65         raise NotImplemented
66
67     def __getitem__(self, slug):
68         return self.by_slug(slug)
69
70     def by_uri(self, uri):
71         return self.by_slug(uri.rsplit('/', 1)[1])
72
73
74 class DirDocProvider(DocProvider):
75     """ Serve docs from a directory of files in form <slug>.xml """
76
77     def __init__(self, dir):
78         self.dir = dir
79         self.files = {}
80
81     def by_slug(self, slug):
82         return open(os.path.join(self.dir, '%s.xml' % slug))
83
84
85 import lxml.etree as etree
86 import dcparser
87
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"],
99           DCNS('description'):
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"],
106           DCNS('rights'):
107             [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
108
109 def xinclude_forURI(uri):
110     e = etree.Element(XINS("include"))
111     e.set("href", uri)
112     return etree.tostring(e, encoding=unicode)
113
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
117
118     dcstring = etree.tostring(bookinfo.to_etree(), \
119         method='xml', encoding=unicode, pretty_print=True)
120
121     return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext + \
122         u'\n</plain-text>\n</utwor>';
123
124
125 def serialize_raw(element):
126     b = u'' + (element.text or '')
127
128     for child in element.iterchildren():
129         e = etree.tostring(child, method='xml', encoding=unicode, pretty_print=True)
130         b += e
131
132     return b
133
134 SERIALIZERS = {
135     'raw': serialize_raw,
136 }
137
138 def serialize_children(element, format='raw'):
139     return SERIALIZERS[format](element)
140
141 def get_resource(path):
142     return os.path.join(os.path.dirname(__file__), path)
143