Even shorter NOTCIE.
[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 class ParseError(Exception):
7     
8     def __init__(self, cause, message=None):
9         self.cause = cause
10         try:
11             self.message = message or self.cause.message
12         except:
13             self.message = "No message."
14
15 class ValidationError(Exception):
16     pass
17
18 class NoDublinCore(ValidationError):
19     pass
20
21 class XMLNamespace(object):
22     '''A handy structure to repsent names in an XML namespace.'''
23
24     def __init__(self, uri):
25         self.uri = uri
26
27     def __call__(self, tag):
28         return '{%s}%s' % (self.uri, tag)
29
30     def __contains__(self, tag):
31         return tag.startswith('{'+str(self)+'}')
32
33     def __repr__(self):
34         return 'XMLNamespace(%r)' % self.uri
35
36     def __str__(self):
37         return '%s' % self.uri
38
39 class EmptyNamespace(XMLNamespace):
40     def __init__(self):
41         super(EmptyNamespace, self).__init__('')
42
43     def __call__(self, tag):
44         return tag
45
46 # some common namespaces we use
47 RDFNS = XMLNamespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
48 DCNS = XMLNamespace('http://purl.org/dc/elements/1.1/')
49 XINS = XMLNamespace("http://www.w3.org/2001/XInclude")
50 XHTMLNS = XMLNamespace("http://www.w3.org/1999/xhtml")
51
52 WLNS = EmptyNamespace()
53
54 import lxml.etree as etree
55 import dcparser
56
57 DEFAULT_BOOKINFO = dcparser.BookInfo(
58         { RDFNS('about'): u'http://wiki.wolnepodreczniki.pl/Lektury:Template'},\
59         { DCNS('creator'): [u'Some, Author'],
60           DCNS('title'): [u'Some Title'],
61           DCNS('subject.period'): [u'Unknown'],
62           DCNS('subject.type'): [u'Unknown'],
63           DCNS('subject.genre'): [u'Unknown'],
64           DCNS('date'): ['1970-01-01'],
65           # DCNS('date'): [creation_date],
66           DCNS('publisher'): [u"Fundacja Nowoczesna Polska"],
67           DCNS('description'):
68           [u"""Publikacja zrealizowana w ramach projektu
69              Wolne Lektury (http://wolnelektury.pl). Reprodukcja cyfrowa
70              wykonana przez Bibliotekę Narodową z egzemplarza
71              pochodzącego ze zbiorów BN."""],
72           DCNS('identifier.url'):
73             [u"http://wolnelektury.pl/katalog/lektura/template"],
74           DCNS('rights'):
75             [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
76
77 def xinclude_forURI(uri):
78     e = etree.Element( XINS("include") )
79     e.set("href", uri)
80     return etree.tostring(e, encoding=unicode)
81     
82 def wrap_text(ocrtext, creation_date, bookinfo=DEFAULT_BOOKINFO):
83     """Wrap the text within the minimal XML structure with a DC template."""
84     bookinfo.created_at = creation_date
85     
86     dcstring = etree.tostring(bookinfo.to_etree(),\
87         method='xml', encoding=unicode, pretty_print=True)
88
89     return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext +\
90         u'\n</plain-text>\n</utwor>';
91
92
93 def serialize_raw(element):
94     b = u'' + (element.text or '')
95
96     for child in element.iterchildren():
97         e = etree.tostring(child, method='xml', encoding=unicode, pretty_print=True)
98         b += e
99
100     return b
101
102 SERIALIZERS = {
103     'raw': serialize_raw,
104 }
105
106 def serialize_children(element, format='raw'):
107     return SERIALIZERS[format](element)