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