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