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