Add thank-you note in EPUB and PDF.
[librarian.git] / librarian / dcparser.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 from xml.parsers.expat import ExpatError
7 from datetime import date
8 import time
9
10 from librarian import (ValidationError, NoDublinCore, ParseError, DCNS, RDFNS,
11                        WLURI)
12
13 import lxml.etree as etree # ElementTree API using libxml2
14 from lxml.etree import XMLSyntaxError
15
16
17 # ==============
18 # = Converters =
19 # ==============
20 class Person(object):
21     """Single person with last name and a list of first names."""
22     def __init__(self, last_name, *first_names):
23         self.last_name = last_name
24         self.first_names = first_names
25
26     @classmethod
27     def from_text(cls, text):
28         parts = [ token.strip() for token in text.split(',') ]
29         if len(parts) == 1:
30             surname = parts[0]
31             names = []
32         elif len(parts) != 2:
33             raise ValueError("Invalid person name. There should be at most one comma: \"%s\"." % text)
34         else:
35             surname = parts[0]
36             if len(parts[1]) == 0:
37                 # there is no non-whitespace data after the comma
38                 raise ValueError("Found a comma, but no names given: \"%s\" -> %r." % (text, parts))
39             names = [ name for name in parts[1].split() if len(name) ] # all non-whitespace tokens
40         return cls(surname, *names)
41
42     def readable(self):
43         return u" ".join(self.first_names + (self.last_name,))
44
45     def __eq__(self, right):
46         return self.last_name == right.last_name and self.first_names == right.first_names
47
48     def __cmp__(self, other):
49         return cmp((self.last_name, self.first_names), (other.last_name, other.first_names))
50
51     def __hash__(self):
52         return hash((self.last_name, self.first_names))
53
54     def __unicode__(self):
55         if len(self.first_names) > 0:
56             return '%s, %s' % (self.last_name, ' '.join(self.first_names))
57         else:
58             return self.last_name
59
60     def __repr__(self):
61         return 'Person(last_name=%r, first_names=*%r)' % (self.last_name, self.first_names)
62
63 def as_date(text):
64     try:
65         try:
66             t = time.strptime(text, '%Y-%m-%d')
67         except ValueError:
68             t = time.strptime(text, '%Y')
69         return date(t[0], t[1], t[2])
70     except ValueError, e:
71         raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
72
73 def as_person(text):
74     return Person.from_text(text)
75
76 def as_unicode(text):
77     if isinstance(text, unicode):
78         return text
79     else:
80         return text.decode('utf-8')
81
82 def as_wluri_strict(text):
83     return WLURI.strict(text)
84
85 class Field(object):
86     def __init__(self, uri, attr_name, validator=as_unicode, strict=None, multiple=False, salias=None, **kwargs):
87         self.uri = uri
88         self.name = attr_name
89         self.validator = validator
90         self.strict = strict
91         self.multiple = multiple
92         self.salias = salias
93
94         self.required = kwargs.get('required', True) and not kwargs.has_key('default')
95         self.default = kwargs.get('default', [] if multiple else [None])
96
97     def validate_value(self, val, strict=False):
98         if strict and self.strict is not None:
99             validator = self.strict
100         else:
101             validator = self.validator
102         try:
103             if self.multiple:
104                 if validator is None:
105                     return val
106                 return [ validator(v) if v is not None else v for v in val ]
107             elif len(val) > 1:
108                 raise ValidationError("Multiple values not allowed for field '%s'" % self.uri)
109             elif len(val) == 0:
110                 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
111             else:
112                 if validator is None or val[0] is None:
113                     return val[0]
114                 return validator(val[0])
115         except ValueError, e:
116             raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
117
118     def validate(self, fdict, fallbacks=None, strict=False):
119         if fallbacks is None:
120             fallbacks = {}
121         if not fdict.has_key(self.uri):
122             if not self.required:
123                 # Accept single value for single fields and saliases.
124                 if self.name in fallbacks:
125                     if self.multiple:
126                         f = fallbacks[self.name]
127                     else:
128                         f = [fallbacks[self.name]]
129                 elif self.salias and self.salias in fallbacks:
130                     f = [fallbacks[self.salias]]
131                 else:
132                     f = self.default
133             else:
134                 raise ValidationError("Required field %s not found" % self.uri)
135         else:
136             f = fdict[self.uri]
137
138         return self.validate_value(f, strict=strict)
139
140     def __eq__(self, other):
141         if isinstance(other, Field) and other.name == self.name:
142             return True
143         return False
144
145
146 class DCInfo(type):
147     def __new__(meta, classname, bases, class_dict):
148         fields = list(class_dict['FIELDS'])
149
150         for base in bases[::-1]:
151             if hasattr(base, 'FIELDS'):
152                 for field in base.FIELDS[::-1]:
153                     try:
154                         fields.index(field)
155                     except ValueError:
156                         fields.insert(0, field)
157
158         class_dict['FIELDS'] = tuple(fields)
159         return super(DCInfo, meta).__new__(meta, classname, bases, class_dict)
160
161
162 class WorkInfo(object):
163     __metaclass__ = DCInfo
164
165     FIELDS = (
166         Field( DCNS('creator'), 'authors', as_person, salias='author', multiple=True),
167         Field( DCNS('title'), 'title'),
168         Field( DCNS('type'), 'type', required=False, multiple=True),
169
170         Field( DCNS('contributor.editor'), 'editors', \
171             as_person, salias='editor', multiple=True, default=[]),
172         Field( DCNS('contributor.technical_editor'), 'technical_editors',
173             as_person, salias='technical_editor', multiple=True, default=[]),
174         Field( DCNS('contributor.funding'), 'funders',
175             salias='funder', multiple=True, default=[]),
176         Field( DCNS('contributor.thanks'), 'thanks', required=False),
177
178         Field( DCNS('date'), 'created_at', as_date),
179         Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
180         Field( DCNS('publisher'), 'publisher'),
181
182         Field( DCNS('language'), 'language'),
183         Field( DCNS('description'), 'description', required=False),
184
185         Field( DCNS('source'), 'source_name', required=False),
186         Field( DCNS('source.URL'), 'source_url', required=False),
187         Field( DCNS('identifier.url'), 'url', WLURI, strict=as_wluri_strict),
188         Field( DCNS('rights.license'), 'license', required=False),
189         Field( DCNS('rights'), 'license_description'),
190     )
191
192     @classmethod
193     def from_string(cls, xml, *args, **kwargs):
194         from StringIO import StringIO
195         return cls.from_file(StringIO(xml), *args, **kwargs)
196
197     @classmethod
198     def from_file(cls, xmlfile, *args, **kwargs):
199         desc_tag = None
200         try:
201             iter = etree.iterparse(xmlfile, ['start', 'end'])
202             for (event, element) in iter:
203                 if element.tag == RDFNS('RDF') and event == 'start':
204                     desc_tag = element
205                     break
206
207             if desc_tag is None:
208                 raise NoDublinCore("DublinCore section not found. \
209                     Check if there are rdf:RDF and rdf:Description tags.")
210
211             # continue 'till the end of RDF section
212             for (event, element) in iter:
213                 if element.tag == RDFNS('RDF') and event == 'end':
214                     break
215
216             # if there is no end, Expat should yell at us with an ExpatError
217
218             # extract data from the element and make the info
219             return cls.from_element(desc_tag, *args, **kwargs)
220         except XMLSyntaxError, e:
221             raise ParseError(e)
222         except ExpatError, e:
223             raise ParseError(e)
224
225     @classmethod
226     def from_element(cls, rdf_tag, *args, **kwargs):
227         # the tree is already parsed, so we don't need to worry about Expat errors
228         field_dict = {}
229         desc = rdf_tag.find(".//" + RDFNS('Description'))
230
231         if desc is None:
232             raise NoDublinCore("No DublinCore section found.")
233
234         for e in desc.getchildren():
235             fv = field_dict.get(e.tag, [])
236             fv.append(e.text)
237             field_dict[e.tag] = fv
238
239         return cls(desc.attrib, field_dict, *args, **kwargs)
240
241     def __init__(self, rdf_attrs, dc_fields, fallbacks=None, strict=False):
242         """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
243         dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
244         given field. """
245
246         self.about = rdf_attrs.get(RDFNS('about'))
247         self.fmap = {}
248
249         for field in self.FIELDS:
250             value = field.validate(dc_fields, fallbacks=fallbacks,
251                             strict=strict)
252             setattr(self, 'prop_' + field.name, value)
253             self.fmap[field.name] = field
254             if field.salias: self.fmap[field.salias] = field
255
256     def __getattribute__(self, name):
257         try:
258             field = object.__getattribute__(self, 'fmap')[name]
259             value = object.__getattribute__(self, 'prop_'+field.name)
260             if field.name == name:
261                 return value
262             else: # singular alias
263                 if not field.multiple:
264                     raise "OUCH!! for field %s" % name
265
266                 return value[0] if value else None
267         except (KeyError, AttributeError):
268             return object.__getattribute__(self, name)
269
270     def __setattr__(self, name, newvalue):
271         try:
272             field = object.__getattribute__(self, 'fmap')[name]
273             if field.name == name:
274                 object.__setattr__(self, 'prop_'+field.name, newvalue)
275             else: # singular alias
276                 if not field.multiple:
277                     raise "OUCH! while setting field %s" % name
278
279                 object.__setattr__(self, 'prop_'+field.name, [newvalue])
280         except (KeyError, AttributeError):
281             return object.__setattr__(self, name, newvalue)
282
283     def update(self, field_dict):
284         """Update using field_dict. Verify correctness, but don't check if all
285         required fields are present."""
286         for field in self.FIELDS:
287             if field_dict.has_key(field.name):
288                 setattr(self, field.name, field_dict[field.name])
289
290     def to_etree(self, parent = None):
291         """XML representation of this object."""
292         #etree._namespace_map[str(self.RDF)] = 'rdf'
293         #etree._namespace_map[str(self.DC)] = 'dc'
294
295         if parent is None:
296             root = etree.Element(RDFNS('RDF'))
297         else:
298             root = parent.makeelement(RDFNS('RDF'))
299
300         description = etree.SubElement(root, RDFNS('Description'))
301
302         if self.about:
303             description.set(RDFNS('about'), self.about)
304
305         for field in self.FIELDS:
306             v = getattr(self, field.name, None)
307             if v is not None:
308                 if field.multiple:
309                     if len(v) == 0: continue
310                     for x in v:
311                         e = etree.Element(field.uri)
312                         if x is not None:
313                             e.text = unicode(x)
314                         description.append(e)
315                 else:
316                     e = etree.Element(field.uri)
317                     e.text = unicode(v)
318                     description.append(e)
319
320         return root
321
322     def serialize(self):
323         rdf = {}
324         rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
325
326         dc = {}
327         for field in self.FIELDS:
328             v = getattr(self, field.name, None)
329             if v is not None:
330                 if field.multiple:
331                     if len(v) == 0: continue
332                     v = [ unicode(x) for x in v if x is not None ]
333                 else:
334                     v = unicode(v)
335
336                 dc[field.name] = {'uri': field.uri, 'value': v}
337         rdf['fields'] = dc
338         return rdf
339
340     def to_dict(self):
341         result = {'about': self.about}
342         for field in self.FIELDS:
343             v = getattr(self, field.name, None)
344
345             if v is not None:
346                 if field.multiple:
347                     if len(v) == 0: continue
348                     v = [ unicode(x) for x in v if x is not None ]
349                 else:
350                     v = unicode(v)
351                 result[field.name] = v
352
353             if field.salias:
354                 v = getattr(self, field.salias)
355                 if v is not None: result[field.salias] = unicode(v)
356
357         return result
358
359
360 class BookInfo(WorkInfo):
361     FIELDS = (
362         Field( DCNS('audience'), 'audiences', salias='audience', multiple=True,
363                 required=False),
364
365         Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True,
366                 required=False),
367         Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True,
368                 required=False),
369         Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True,
370                 required=False),
371                 
372         Field( DCNS('contributor.translator'), 'translators', \
373             as_person,  salias='translator', multiple=True, default=[]),
374         Field( DCNS('relation.hasPart'), 'parts', 
375             WLURI, strict=as_wluri_strict, multiple=True, required=False),
376         Field( DCNS('relation.isVariantOf'), 'variant_of', 
377             WLURI, strict=as_wluri_strict, required=False),
378
379         Field( DCNS('relation.coverImage.url'), 'cover_url', required=False),
380         Field( DCNS('relation.coverImage.attribution'), 'cover_by', required=False),
381         Field( DCNS('relation.coverImage.source'), 'cover_source', required=False),
382     )
383
384
385 def parse(file_name, cls=BookInfo):
386     return cls.from_file(file_name)