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