dirty workaround for python unicode problems
[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.message
12
13     def __unicode__(self):
14         """ Dirty workaround for Python Unicode handling problems. """
15         return self.message.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('date'): [creation_date],
97           DCNS('publisher'): [u"Fundacja Nowoczesna Polska"],
98           DCNS('description'):
99           [u"""Publikacja zrealizowana w ramach projektu
100              Wolne Lektury (http://wolnelektury.pl). Reprodukcja cyfrowa
101              wykonana przez Bibliotekę Narodową z egzemplarza
102              pochodzącego ze zbiorów BN."""],
103           DCNS('identifier.url'):
104             [u"http://wolnelektury.pl/katalog/lektura/template"],
105           DCNS('rights'):
106             [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
107
108 def xinclude_forURI(uri):
109     e = etree.Element(XINS("include"))
110     e.set("href", uri)
111     return etree.tostring(e, encoding=unicode)
112
113 def wrap_text(ocrtext, creation_date, bookinfo=DEFAULT_BOOKINFO):
114     """Wrap the text within the minimal XML structure with a DC template."""
115     bookinfo.created_at = creation_date
116
117     dcstring = etree.tostring(bookinfo.to_etree(), \
118         method='xml', encoding=unicode, pretty_print=True)
119
120     return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext + \
121         u'\n</plain-text>\n</utwor>';
122
123
124 def serialize_raw(element):
125     b = u'' + (element.text or '')
126
127     for child in element.iterchildren():
128         e = etree.tostring(child, method='xml', encoding=unicode, pretty_print=True)
129         b += e
130
131     return b
132
133 SERIALIZERS = {
134     'raw': serialize_raw,
135 }
136
137 def serialize_children(element, format='raw'):
138     return SERIALIZERS[format](element)
139
140 def get_resource(path):
141     return os.path.join(os.path.dirname(__file__), path)
142