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