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