Data for #3396: picture style, full creation date.
[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'),
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         Field( WLNS('developmentStage'), 'stage', required=False),
249     )
250
251     @classmethod
252     def from_string(cls, xml, *args, **kwargs):
253         from StringIO import StringIO
254         return cls.from_file(StringIO(xml), *args, **kwargs)
255
256     @classmethod
257     def from_file(cls, xmlfile, *args, **kwargs):
258         desc_tag = None
259         try:
260             iter = etree.iterparse(xmlfile, ['start', 'end'])
261             for (event, element) in iter:
262                 if element.tag == RDFNS('RDF') and event == 'start':
263                     desc_tag = element
264                     break
265
266             if desc_tag is None:
267                 raise NoDublinCore("DublinCore section not found. \
268                     Check if there are rdf:RDF and rdf:Description tags.")
269
270             # continue 'till the end of RDF section
271             for (event, element) in iter:
272                 if element.tag == RDFNS('RDF') and event == 'end':
273                     break
274
275             # if there is no end, Expat should yell at us with an ExpatError
276
277             # extract data from the element and make the info
278             return cls.from_element(desc_tag, *args, **kwargs)
279         except XMLSyntaxError, e:
280             raise ParseError(e)
281         except ExpatError, e:
282             raise ParseError(e)
283
284     @classmethod
285     def from_element(cls, rdf_tag, *args, **kwargs):
286         # the tree is already parsed, so we don't need to worry about Expat errors
287         field_dict = {}
288         desc = rdf_tag.find(".//" + RDFNS('Description'))
289
290         if desc is None:
291             raise NoDublinCore("No DublinCore section found.")
292
293         lang = None
294         p = desc
295         while p is not None and lang is None:
296             lang = p.attrib.get(XMLNS('lang'))
297             p = p.getparent()
298
299         for e in desc.getchildren():
300             fv = field_dict.get(e.tag, [])
301             if e.text is not None:
302                 text = e.text
303                 if not isinstance(text, unicode):
304                     text = text.decode('utf-8')
305                 val = TextPlus(text)
306                 val.lang = e.attrib.get(XMLNS('lang'), lang)
307             else:
308                 val = e.text
309             fv.append(val)
310             field_dict[e.tag] = fv
311
312         return cls(desc.attrib, field_dict, *args, **kwargs)
313
314     def __init__(self, rdf_attrs, dc_fields, fallbacks=None, strict=False):
315         """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
316         dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
317         given field. """
318
319         self.about = rdf_attrs.get(RDFNS('about'))
320         self.fmap = {}
321
322         for field in self.FIELDS:
323             value = field.validate(dc_fields, fallbacks=fallbacks,
324                             strict=strict)
325             setattr(self, 'prop_' + field.name, value)
326             self.fmap[field.name] = field
327             if field.salias: self.fmap[field.salias] = field
328
329     def __getattribute__(self, name):
330         try:
331             field = object.__getattribute__(self, 'fmap')[name]
332             value = object.__getattribute__(self, 'prop_'+field.name)
333             if field.name == name:
334                 return value
335             else: # singular alias
336                 if not field.multiple:
337                     raise "OUCH!! for field %s" % name
338
339                 return value[0] if value else None
340         except (KeyError, AttributeError):
341             return object.__getattribute__(self, name)
342
343     def __setattr__(self, name, newvalue):
344         try:
345             field = object.__getattribute__(self, 'fmap')[name]
346             if field.name == name:
347                 object.__setattr__(self, 'prop_'+field.name, newvalue)
348             else: # singular alias
349                 if not field.multiple:
350                     raise "OUCH! while setting field %s" % name
351
352                 object.__setattr__(self, 'prop_'+field.name, [newvalue])
353         except (KeyError, AttributeError):
354             return object.__setattr__(self, name, newvalue)
355
356     def update(self, field_dict):
357         """Update using field_dict. Verify correctness, but don't check if all
358         required fields are present."""
359         for field in self.FIELDS:
360             if field_dict.has_key(field.name):
361                 setattr(self, field.name, field_dict[field.name])
362
363     def to_etree(self, parent = None):
364         """XML representation of this object."""
365         #etree._namespace_map[str(self.RDF)] = 'rdf'
366         #etree._namespace_map[str(self.DC)] = 'dc'
367
368         if parent is None:
369             root = etree.Element(RDFNS('RDF'))
370         else:
371             root = parent.makeelement(RDFNS('RDF'))
372
373         description = etree.SubElement(root, RDFNS('Description'))
374
375         if self.about:
376             description.set(RDFNS('about'), self.about)
377
378         for field in self.FIELDS:
379             v = getattr(self, field.name, None)
380             if v is not None:
381                 if field.multiple:
382                     if len(v) == 0: continue
383                     for x in v:
384                         e = etree.Element(field.uri)
385                         if x is not None:
386                             e.text = unicode(x)
387                         description.append(e)
388                 else:
389                     e = etree.Element(field.uri)
390                     e.text = unicode(v)
391                     description.append(e)
392
393         return root
394
395     def serialize(self):
396         rdf = {}
397         rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
398
399         dc = {}
400         for field in self.FIELDS:
401             v = getattr(self, field.name, None)
402             if v is not None:
403                 if field.multiple:
404                     if len(v) == 0: continue
405                     v = [ unicode(x) for x in v if x is not None ]
406                 else:
407                     v = unicode(v)
408
409                 dc[field.name] = {'uri': field.uri, 'value': v}
410         rdf['fields'] = dc
411         return rdf
412
413     def to_dict(self):
414         result = {'about': self.about}
415         for field in self.FIELDS:
416             v = getattr(self, field.name, None)
417
418             if v is not None:
419                 if field.multiple:
420                     if len(v) == 0: continue
421                     v = [ unicode(x) for x in v if x is not None ]
422                 else:
423                     v = unicode(v)
424                 result[field.name] = v
425
426             if field.salias:
427                 v = getattr(self, field.salias)
428                 if v is not None: result[field.salias] = unicode(v)
429
430         return result
431
432
433 class BookInfo(WorkInfo):
434     FIELDS = (
435         Field( DCNS('audience'), 'audiences', salias='audience', multiple=True,
436                 required=False),
437
438         Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True,
439                 required=False),
440         Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True,
441                 required=False),
442         Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True,
443                 required=False),
444                 
445         Field( DCNS('contributor.translator'), 'translators', \
446             as_person,  salias='translator', multiple=True, default=[]),
447         Field( DCNS('relation.hasPart'), 'parts', 
448             WLURI, strict=as_wluri_strict, multiple=True, required=False),
449         Field( DCNS('relation.isVariantOf'), 'variant_of', 
450             WLURI, strict=as_wluri_strict, required=False),
451
452         Field( DCNS('relation.coverImage.url'), 'cover_url', required=False),
453         Field( DCNS('relation.coverImage.attribution'), 'cover_by', required=False),
454         Field( DCNS('relation.coverImage.source'), 'cover_source', required=False),
455         # WLCover-specific.
456         Field( WLNS('coverBarColor'), 'cover_bar_color', required=False),
457         Field( WLNS('coverBoxPosition'), 'cover_box_position', required=False),
458     )
459
460
461 def parse(file_name, cls=BookInfo):
462     return cls.from_file(file_name)