5c4a35584236cc8b60fc5c2aa8595c3b1a5dea21
[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     pass
10
11 class ValidationError(Exception):
12     pass
13
14 class NoDublinCore(ValidationError):
15     pass
16
17 class XMLNamespace(object):
18     '''A handy structure to repsent names in an XML namespace.'''
19
20     def __init__(self, uri):
21         self.uri = uri
22
23     def __call__(self, tag):
24         return '{%s}%s' % (self.uri, tag)
25
26     def __contains__(self, tag):
27         return tag.startswith('{' + str(self) + '}')
28
29     def __repr__(self):
30         return 'XMLNamespace(%r)' % self.uri
31
32     def __str__(self):
33         return '%s' % self.uri
34
35 class EmptyNamespace(XMLNamespace):
36     def __init__(self):
37         super(EmptyNamespace, self).__init__('')
38
39     def __call__(self, tag):
40         return tag
41
42 # some common namespaces we use
43 RDFNS = XMLNamespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
44 DCNS = XMLNamespace('http://purl.org/dc/elements/1.1/')
45 XINS = XMLNamespace("http://www.w3.org/2001/XInclude")
46 XHTMLNS = XMLNamespace("http://www.w3.org/1999/xhtml")
47 NCXNS = XMLNamespace("http://www.daisy.org/z3986/2005/ncx/")
48 OPFNS = XMLNamespace("http://www.idpf.org/2007/opf")
49
50 WLNS = EmptyNamespace()
51
52
53 class DocProvider(object):
54     """ Base class for a repository of XML files.
55         Used for generating joined files, like EPUBs
56     """
57
58     def by_slug(self, slug):
59         raise NotImplemented
60
61     def __getitem__(self, slug):
62         return self.by_slug(slug)
63
64     def by_uri(self, uri):
65         return self.by_slug(uri.rsplit('/', 1)[1])
66
67
68 class DirDocProvider(DocProvider):
69     """ Serve docs from a directory of files in form <slug>.xml """
70
71     def __init__(self, dir):
72         self.dir = dir
73         self.files = {}
74
75     def by_slug(self, slug):
76         return open(os.path.join(self.dir, '%s.xml' % slug))
77
78
79 import lxml.etree as etree
80 import dcparser
81
82 DEFAULT_BOOKINFO = dcparser.BookInfo(
83         { RDFNS('about'): u'http://wiki.wolnepodreczniki.pl/Lektury:Template'}, \
84         { DCNS('creator'): [u'Some, Author'],
85           DCNS('title'): [u'Some Title'],
86           DCNS('subject.period'): [u'Unknown'],
87           DCNS('subject.type'): [u'Unknown'],
88           DCNS('subject.genre'): [u'Unknown'],
89           DCNS('date'): ['1970-01-01'],
90           # DCNS('date'): [creation_date],
91           DCNS('publisher'): [u"Fundacja Nowoczesna Polska"],
92           DCNS('description'):
93           [u"""Publikacja zrealizowana w ramach projektu
94              Wolne Lektury (http://wolnelektury.pl). Reprodukcja cyfrowa
95              wykonana przez Bibliotekę Narodową z egzemplarza
96              pochodzącego ze zbiorów BN."""],
97           DCNS('identifier.url'):
98             [u"http://wolnelektury.pl/katalog/lektura/template"],
99           DCNS('rights'):
100             [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
101
102 def xinclude_forURI(uri):
103     e = etree.Element(XINS("include"))
104     e.set("href", uri)
105     return etree.tostring(e, encoding=unicode)
106
107 def wrap_text(ocrtext, creation_date, bookinfo=DEFAULT_BOOKINFO):
108     """Wrap the text within the minimal XML structure with a DC template."""
109     bookinfo.created_at = creation_date
110
111     dcstring = etree.tostring(bookinfo.to_etree(), \
112         method='xml', encoding=unicode, pretty_print=True)
113
114     return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext + \
115         u'\n</plain-text>\n</utwor>';
116
117
118 def serialize_raw(element):
119     b = u'' + (element.text or '')
120
121     for child in element.iterchildren():
122         e = etree.tostring(child, method='xml', encoding=unicode, pretty_print=True)
123         b += e
124
125     return b
126
127 SERIALIZERS = {
128     'raw': serialize_raw,
129 }
130
131 def serialize_children(element, format='raw'):
132     return SERIALIZERS[format](element)
133
134 def get_resource(path):
135     return os.path.join(os.path.dirname(__file__), path)
136