eeb750ac7fdb705714299fc7fafe0ffa24e96bba
[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 __future__ import unicode_literals
7
8 from xml.parsers.expat import ExpatError
9 from datetime import date
10 from functools import total_ordering
11 import time
12 import re
13 import six
14 from librarian.util import roman_to_int
15
16 from librarian import (ValidationError, NoDublinCore, ParseError, DCNS, RDFNS,
17                        XMLNS, WLURI, WLNS, PLMETNS)
18
19 import lxml.etree as etree  # ElementTree API using libxml2
20 from lxml.etree import XMLSyntaxError
21
22
23 class TextPlus(six.text_type):
24     pass
25
26
27 class DatePlus(date):
28     pass
29
30
31 # ==============
32 # = Converters =
33 # ==============
34 @six.python_2_unicode_compatible
35 @total_ordering
36 class Person(object):
37     """Single person with last name and a list of first names."""
38     def __init__(self, last_name, *first_names):
39         self.last_name = last_name
40         self.first_names = first_names
41
42     @classmethod
43     def from_text(cls, text):
44         parts = [token.strip() for token in text.split(',')]
45         if len(parts) == 1:
46             surname = parts[0]
47             names = []
48         elif len(parts) != 2:
49             raise ValueError("Invalid person name. There should be at most one comma: \"%s\"." % text.encode('utf-8'))
50         else:
51             surname = parts[0]
52             if len(parts[1]) == 0:
53                 # there is no non-whitespace data after the comma
54                 raise ValueError("Found a comma, but no names given: \"%s\" -> %r." % (text, parts))
55             names = parts[1].split()
56         return cls(surname, *names)
57
58     def readable(self):
59         return u" ".join(self.first_names + (self.last_name,))
60
61     def __eq__(self, right):
62         return self.last_name == right.last_name and self.first_names == right.first_names
63
64     def __lt__(self, other):
65         return (self.last_name, self.first_names) < (other.last_name, other.first_names)
66
67     def __hash__(self):
68         return hash((self.last_name, self.first_names))
69
70     def __str__(self):
71         if len(self.first_names) > 0:
72             return '%s, %s' % (self.last_name, ' '.join(self.first_names))
73         else:
74             return self.last_name
75
76     def __repr__(self):
77         return 'Person(last_name=%r, first_names=*%r)' % (self.last_name, self.first_names)
78
79
80 def as_date(text):
81     """Dates for digitization of pictures. It seems we need the following:
82 ranges:         '1350-1450',
83 centuries:      "XVIII w.'
84 half centuries/decades: '2 poł. XVIII w.', 'XVII w., l. 20'
85 later-then: 'po 1450'
86 circa 'ok. 1813-1814', 'ok.1876-ok.1886
87 turn: 1893/1894
88 for now we will translate this to some single date losing information of course.
89     """
90     try:
91         # check out the "N. poł X w." syntax
92         if isinstance(text, six.binary_type):
93             text = text.decode("utf-8")
94
95         century_format = u"(?:([12]) *poł[.]? +)?([MCDXVI]+) *w[.,]*(?: *l[.]? *([0-9]+))?"
96         vague_format = u"(?:po *|ok. *)?([0-9]{4})(-[0-9]{2}-[0-9]{2})?"
97
98         m = re.match(century_format, text)
99         m2 = re.match(vague_format, text)
100         if m:
101             half = m.group(1)
102             decade = m.group(3)
103             century = roman_to_int(m.group(2))
104             if half is not None:
105                 if decade is not None:
106                     raise ValueError("Bad date format. Cannot specify both half and decade of century")
107                 half = int(half)
108                 t = ((century*100 + (half-1)*50), 1, 1)
109             else:
110                 decade = int(decade or 0)
111                 t = ((century*100 + decade), 1, 1)
112         elif m2:
113             year = m2.group(1)
114             mon_day = m2.group(2)
115             if mon_day:
116                 t = time.strptime(year + mon_day, "%Y-%m-%d")
117             else:
118                 t = time.strptime(year, '%Y')
119         else:
120             raise ValueError
121
122         return DatePlus(t[0], t[1], t[2])
123     except ValueError as e:
124         raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
125
126
127 def as_person(text):
128     return Person.from_text(text)
129
130
131 def as_unicode(text):
132     if isinstance(text, six.text_type):
133         return text
134     else:
135         return TextPlus(text.decode('utf-8'))
136
137
138 def as_wluri_strict(text):
139     return WLURI.strict(text)
140
141
142 class Field(object):
143     def __init__(self, uri, attr_name, validator=as_unicode, strict=None, multiple=False, salias=None, **kwargs):
144         self.uri = uri
145         self.name = attr_name
146         self.validator = validator
147         self.strict = strict
148         self.multiple = multiple
149         self.salias = salias
150
151         self.required = kwargs.get('required', True) and 'default' not in kwargs
152         self.default = kwargs.get('default', [] if multiple else [None])
153
154     def validate_value(self, val, strict=False):
155         if strict and self.strict is not None:
156             validator = self.strict
157         else:
158             validator = self.validator
159         try:
160             if self.multiple:
161                 if validator is None:
162                     return val
163                 new_values = []
164                 for v in val:
165                     nv = v
166                     if v is not None:
167                         nv = validator(v)
168                         if hasattr(v, 'lang'):
169                             setattr(nv, 'lang', v.lang)
170                     new_values.append(nv)
171                 return new_values
172             elif len(val) > 1:
173                 raise ValidationError("Multiple values not allowed for field '%s'" % self.uri)
174             elif len(val) == 0:
175                 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
176             else:
177                 if validator is None or val[0] is None:
178                     return val[0]
179                 nv = validator(val[0])
180                 if hasattr(val[0], 'lang'):
181                     setattr(nv, 'lang', val[0].lang)
182                 return nv
183         except ValueError as e:
184             raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
185
186     def validate(self, fdict, fallbacks=None, strict=False):
187         if fallbacks is None:
188             fallbacks = {}
189         if self.uri not in fdict:
190             if not self.required:
191                 # Accept single value for single fields and saliases.
192                 if self.name in fallbacks:
193                     if self.multiple:
194                         f = fallbacks[self.name]
195                     else:
196                         f = [fallbacks[self.name]]
197                 elif self.salias and self.salias in fallbacks:
198                     f = [fallbacks[self.salias]]
199                 else:
200                     f = self.default
201             else:
202                 raise ValidationError("Required field %s not found" % self.uri)
203         else:
204             f = fdict[self.uri]
205
206         return self.validate_value(f, strict=strict)
207
208     def __eq__(self, other):
209         if isinstance(other, Field) and other.name == self.name:
210             return True
211         return False
212
213
214 class DCInfo(type):
215     def __new__(mcs, classname, bases, class_dict):
216         fields = list(class_dict['FIELDS'])
217
218         for base in bases[::-1]:
219             if hasattr(base, 'FIELDS'):
220                 for field in base.FIELDS[::-1]:
221                     try:
222                         fields.index(field)
223                     except ValueError:
224                         fields.insert(0, field)
225
226         class_dict['FIELDS'] = tuple(fields)
227         return super(DCInfo, mcs).__new__(mcs, classname, bases, class_dict)
228
229
230 class WorkInfo(six.with_metaclass(DCInfo, object)):
231     FIELDS = (
232         Field(DCNS('creator'), 'authors', as_person, salias='author', multiple=True),
233         Field(DCNS('title'), 'title'),
234         Field(DCNS('type'), 'type', required=False, multiple=True),
235
236         Field(DCNS('contributor.editor'), 'editors',
237               as_person, salias='editor', multiple=True, required=False),
238         Field(DCNS('contributor.technical_editor'), 'technical_editors',
239               as_person, salias='technical_editor', multiple=True, required=False),
240         Field(DCNS('contributor.funding'), 'funders', salias='funder', multiple=True, required=False),
241         Field(DCNS('contributor.thanks'), 'thanks', required=False),
242
243         Field(DCNS('date'), 'created_at'),
244         Field(DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
245         Field(DCNS('publisher'), 'publisher', multiple=True),
246
247         Field(DCNS('language'), 'language'),
248         Field(DCNS('description'), 'description', required=False),
249
250         Field(DCNS('source'), 'source_name', required=False),
251         Field(DCNS('source.URL'), 'source_url', required=False),
252         Field(DCNS('identifier.url'), 'url', WLURI, strict=as_wluri_strict),
253         Field(DCNS('rights.license'), 'license', required=False),
254         Field(DCNS('rights'), 'license_description'),
255
256         Field(PLMETNS('digitisationSponsor'), 'sponsors', multiple=True, required=False),
257         Field(WLNS('digitisationSponsorNote'), 'sponsor_note', required=False),
258         Field(WLNS('developmentStage'), 'stage', required=False),
259     )
260
261     @classmethod
262     def from_bytes(cls, xml, *args, **kwargs):
263         return cls.from_file(six.BytesIO(xml), *args, **kwargs)
264
265     @classmethod
266     def from_file(cls, xmlfile, *args, **kwargs):
267         desc_tag = None
268         try:
269             iter = etree.iterparse(xmlfile, ['start', 'end'])
270             for (event, element) in iter:
271                 if element.tag == RDFNS('RDF') and event == 'start':
272                     desc_tag = element
273                     break
274
275             if desc_tag is None:
276                 raise NoDublinCore("DublinCore section not found. \
277                     Check if there are rdf:RDF and rdf:Description tags.")
278
279             # continue 'till the end of RDF section
280             for (event, element) in iter:
281                 if element.tag == RDFNS('RDF') and event == 'end':
282                     break
283
284             # if there is no end, Expat should yell at us with an ExpatError
285
286             # extract data from the element and make the info
287             return cls.from_element(desc_tag, *args, **kwargs)
288         except XMLSyntaxError as e:
289             raise ParseError(e)
290         except ExpatError as e:
291             raise ParseError(e)
292
293     @classmethod
294     def from_element(cls, rdf_tag, *args, **kwargs):
295         # the tree is already parsed, so we don't need to worry about Expat errors
296         field_dict = {}
297         desc = rdf_tag.find(".//" + RDFNS('Description'))
298
299         if desc is None:
300             raise NoDublinCore("No DublinCore section found.")
301
302         lang = None
303         p = desc
304         while p is not None and lang is None:
305             lang = p.attrib.get(XMLNS('lang'))
306             p = p.getparent()
307
308         for e in desc.getchildren():
309             fv = field_dict.get(e.tag, [])
310             if e.text is not None:
311                 text = e.text
312                 if not isinstance(text, six.text_type):
313                     text = text.decode('utf-8')
314                 val = TextPlus(text)
315                 val.lang = e.attrib.get(XMLNS('lang'), lang)
316                 if e.tag == 'meta':
317                     meta_id = e.attrib.get('id')
318                     if meta_id and meta_id.endswith('-id'):
319                         field_dict[meta_id] = [val.replace('ISBN-', 'ISBN ')]
320             else:
321                 val = e.text
322             fv.append(val)
323             field_dict[e.tag] = fv
324
325         return cls(desc.attrib, field_dict, *args, **kwargs)
326
327     def __init__(self, rdf_attrs, dc_fields, fallbacks=None, strict=False):
328         """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
329         dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
330         given field. """
331
332         self.about = rdf_attrs.get(RDFNS('about'))
333         self.fmap = {}
334
335         for field in self.FIELDS:
336             value = field.validate(dc_fields, fallbacks=fallbacks, strict=strict)
337             setattr(self, 'prop_' + field.name, value)
338             self.fmap[field.name] = field
339             if field.salias:
340                 self.fmap[field.salias] = field
341
342     def __getattribute__(self, name):
343         try:
344             field = object.__getattribute__(self, 'fmap')[name]
345             value = object.__getattribute__(self, 'prop_'+field.name)
346             if field.name == name:
347                 return value
348             else:  # singular alias
349                 if not field.multiple:
350                     raise "OUCH!! for field %s" % name
351
352                 return value[0] if value else None
353         except (KeyError, AttributeError):
354             return object.__getattribute__(self, name)
355
356     def __setattr__(self, name, newvalue):
357         try:
358             field = object.__getattribute__(self, 'fmap')[name]
359             if field.name == name:
360                 object.__setattr__(self, 'prop_'+field.name, newvalue)
361             else:  # singular alias
362                 if not field.multiple:
363                     raise "OUCH! while setting field %s" % name
364
365                 object.__setattr__(self, 'prop_'+field.name, [newvalue])
366         except (KeyError, AttributeError):
367             return object.__setattr__(self, name, newvalue)
368
369     def update(self, field_dict):
370         """Update using field_dict. Verify correctness, but don't check if all
371         required fields are present."""
372         for field in self.FIELDS:
373             if field.name in field_dict:
374                 setattr(self, field.name, field_dict[field.name])
375
376     def to_etree(self, parent=None):
377         """XML representation of this object."""
378         # etree._namespace_map[str(self.RDF)] = 'rdf'
379         # etree._namespace_map[str(self.DC)] = 'dc'
380
381         if parent is None:
382             root = etree.Element(RDFNS('RDF'))
383         else:
384             root = parent.makeelement(RDFNS('RDF'))
385
386         description = etree.SubElement(root, RDFNS('Description'))
387
388         if self.about:
389             description.set(RDFNS('about'), self.about)
390
391         for field in self.FIELDS:
392             v = getattr(self, field.name, None)
393             if v is not None:
394                 if field.multiple:
395                     if len(v) == 0:
396                         continue
397                     for x in v:
398                         e = etree.Element(field.uri)
399                         if x is not None:
400                             e.text = six.text_type(x)
401                         description.append(e)
402                 else:
403                     e = etree.Element(field.uri)
404                     e.text = six.text_type(v)
405                     description.append(e)
406
407         return root
408
409     def serialize(self):
410         rdf = {'about': {'uri': RDFNS('about'), 'value': self.about}}
411
412         dc = {}
413         for field in self.FIELDS:
414             v = getattr(self, field.name, None)
415             if v is not None:
416                 if field.multiple:
417                     if len(v) == 0:
418                         continue
419                     v = [six.text_type(x) for x in v if x is not None]
420                 else:
421                     v = six.text_type(v)
422
423                 dc[field.name] = {'uri': field.uri, 'value': v}
424         rdf['fields'] = dc
425         return rdf
426
427     def to_dict(self):
428         result = {'about': self.about}
429         for field in self.FIELDS:
430             v = getattr(self, field.name, None)
431
432             if v is not None:
433                 if field.multiple:
434                     if len(v) == 0:
435                         continue
436                     v = [six.text_type(x) for x in v if x is not None]
437                 else:
438                     v = six.text_type(v)
439                 result[field.name] = v
440
441             if field.salias:
442                 v = getattr(self, field.salias)
443                 if v is not None:
444                     result[field.salias] = six.text_type(v)
445
446         return result
447
448
449 class BookInfo(WorkInfo):
450     FIELDS = (
451         Field(DCNS('audience'), 'audiences', salias='audience', multiple=True, required=False),
452
453         Field(DCNS('subject.period'), 'epochs', salias='epoch', multiple=True, required=False),
454         Field(DCNS('subject.type'), 'kinds', salias='kind', multiple=True, required=False),
455         Field(DCNS('subject.genre'), 'genres', salias='genre', multiple=True, required=False),
456
457         Field(DCNS('subject.location'), 'location', required=False),
458
459         Field(DCNS('contributor.translator'), 'translators',
460               as_person,  salias='translator', multiple=True, required=False),
461         Field(DCNS('relation.hasPart'), 'parts', WLURI, strict=as_wluri_strict, multiple=True, required=False),
462         Field(DCNS('relation.isVariantOf'), 'variant_of', WLURI, strict=as_wluri_strict, required=False),
463
464         Field(DCNS('relation.coverImage.url'), 'cover_url', required=False),
465         Field(DCNS('relation.coverImage.attribution'), 'cover_by', required=False),
466         Field(DCNS('relation.coverImage.source'), 'cover_source', required=False),
467         # WLCover-specific.
468         Field(WLNS('coverBarColor'), 'cover_bar_color', required=False),
469         Field(WLNS('coverBoxPosition'), 'cover_box_position', required=False),
470         Field(WLNS('coverClass'), 'cover_class', default=['default']),
471         Field('pdf-id',  'isbn_pdf',  required=False),
472         Field('epub-id', 'isbn_epub', required=False),
473         Field('mobi-id', 'isbn_mobi', required=False),
474         Field('txt-id',  'isbn_txt',  required=False),
475         Field('html-id', 'isbn_html', required=False),
476     )
477
478
479 def parse(file_name, cls=BookInfo):
480     return cls.from_file(file_name)