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