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