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