549142ba3d974a4d11b64ce4d4acb90793fa8e82
[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 def as_bool(text):
157     return text == 'true'
158 as_bool.no_lang = True
159
160 def as_wluri_strict(text):
161     return WLURI.strict(text)
162
163
164 class Field(object):
165     def __init__(self, uri, attr_name, validator=as_unicode, strict=None,
166                  multiple=False, salias=None, **kwargs):
167         self.uri = uri
168         self.name = attr_name
169         self.validator = validator
170         self.strict = strict
171         self.multiple = multiple
172         self.salias = salias
173
174         self.required = (kwargs.get('required', True)
175                          and 'default' not in kwargs)
176         self.default = kwargs.get('default', [] if multiple else [None])
177
178     def validate_value(self, val, strict=False):
179         if strict and self.strict is not None:
180             validator = self.strict
181         else:
182             validator = self.validator
183         try:
184             if self.multiple:
185                 if validator is None:
186                     return val
187                 new_values = []
188                 for v in val:
189                     nv = v
190                     if v is not None:
191                         nv = validator(v)
192                         if hasattr(v, 'lang'):
193                             setattr(nv, 'lang', v.lang)
194                     new_values.append(nv)
195                 return new_values
196             elif len(val) > 1:
197                 raise ValidationError(
198                     "Multiple values not allowed for field '%s'" % self.uri
199                 )
200             elif len(val) == 0:
201                 raise ValidationError(
202                     "Field %s has no value to assign. Check your defaults."
203                     % self.uri
204                 )
205             else:
206                 if validator is None or val[0] is None:
207                     return val[0]
208                 nv = validator(val[0])
209                 if hasattr(val[0], 'lang') and not hasattr(validator, 'no_lang'):
210                     setattr(nv, 'lang', val[0].lang)
211                 return nv
212         except ValueError as e:
213             raise ValidationError(
214                 "Field '%s' - invald value: %s"
215                 % (self.uri, e.message)
216             )
217
218     def validate(self, fdict, fallbacks=None, strict=False, validate_required=True):
219         if fallbacks is None:
220             fallbacks = {}
221         if self.uri not in fdict:
222             if not self.required:
223                 # Accept single value for single fields and saliases.
224                 if self.name in fallbacks:
225                     if self.multiple:
226                         f = fallbacks[self.name]
227                     else:
228                         f = [fallbacks[self.name]]
229                 elif self.salias and self.salias in fallbacks:
230                     f = [fallbacks[self.salias]]
231                 else:
232                     f = self.default
233             elif validate_required:
234                 raise ValidationError("Required field %s not found" % self.uri)
235             else:
236                 return None
237         else:
238             f = fdict[self.uri]
239
240         return self.validate_value(f, strict=strict)
241
242     def __eq__(self, other):
243         if isinstance(other, Field) and other.name == self.name:
244             return True
245         return False
246
247
248 class DCInfo(type):
249     def __new__(mcs, classname, bases, class_dict):
250         fields = list(class_dict['FIELDS'])
251
252         for base in bases[::-1]:
253             if hasattr(base, 'FIELDS'):
254                 for field in base.FIELDS[::-1]:
255                     try:
256                         fields.index(field)
257                     except ValueError:
258                         fields.insert(0, field)
259
260         class_dict['FIELDS'] = tuple(fields)
261         return super(DCInfo, mcs).__new__(mcs, classname, bases, class_dict)
262
263
264 class WorkInfo(six.with_metaclass(DCInfo, object)):
265     FIELDS = (
266         Field(DCNS('creator'), 'authors', as_person, salias='author',
267               multiple=True),
268         Field(DCNS('title'), 'title'),
269         Field(DCNS('type'), 'type', required=False, multiple=True),
270
271         Field(DCNS('contributor.editor'), 'editors',
272               as_person, salias='editor', multiple=True, required=False),
273         Field(DCNS('contributor.technical_editor'), 'technical_editors',
274               as_person, salias='technical_editor', multiple=True,
275               required=False),
276         Field(DCNS('contributor.funding'), 'funders', salias='funder',
277               multiple=True, required=False),
278         Field(DCNS('contributor.thanks'), 'thanks', required=False),
279
280         Field(DCNS('date'), 'created_at'),
281         Field(DCNS('date.pd'), 'released_to_public_domain_at', as_date,
282               required=False),
283         Field(DCNS('publisher'), 'publisher', multiple=True),
284
285         Field(DCNS('language'), 'language'),
286         Field(DCNS('description'), 'description', required=False),
287
288         Field(DCNS('source'), 'source_name', required=False),
289         Field(DCNS('source.URL'), 'source_urls', salias='source_url',
290               multiple=True, required=False),
291         Field(DCNS('identifier.url'), 'url', WLURI, strict=as_wluri_strict),
292         Field(DCNS('rights.license'), 'license', required=False),
293         Field(DCNS('rights'), 'license_description'),
294
295         Field(PLMETNS('digitisationSponsor'), 'sponsors', multiple=True,
296               required=False),
297         Field(WLNS('digitisationSponsorNote'), 'sponsor_note', required=False),
298         Field(WLNS('contentWarning'), 'content_warnings', multiple=True,
299               required=False),
300         Field(WLNS('developmentStage'), 'stage', required=False),
301     )
302
303     @classmethod
304     def from_bytes(cls, xml, *args, **kwargs):
305         return cls.from_file(six.BytesIO(xml), *args, **kwargs)
306
307     @classmethod
308     def from_file(cls, xmlfile, *args, **kwargs):
309         desc_tag = None
310         try:
311             iter = etree.iterparse(xmlfile, ['start', 'end'])
312             for (event, element) in iter:
313                 if element.tag == RDFNS('RDF') and event == 'start':
314                     desc_tag = element
315                     break
316
317             if desc_tag is None:
318                 raise NoDublinCore("DublinCore section not found. \
319                     Check if there are rdf:RDF and rdf:Description tags.")
320
321             # continue 'till the end of RDF section
322             for (event, element) in iter:
323                 if element.tag == RDFNS('RDF') and event == 'end':
324                     break
325
326             # if there is no end, Expat should yell at us with an ExpatError
327
328             # extract data from the element and make the info
329             return cls.from_element(desc_tag, *args, **kwargs)
330         except XMLSyntaxError as e:
331             raise ParseError(e)
332         except ExpatError as e:
333             raise ParseError(e)
334
335     @classmethod
336     def from_element(cls, rdf_tag, *args, **kwargs):
337         # The tree is already parsed,
338         # so we don't need to worry about Expat errors.
339         field_dict = {}
340         desc = rdf_tag.find(".//" + RDFNS('Description'))
341
342         if desc is None:
343             raise NoDublinCore(
344                 "There must be a '%s' element inside the RDF."
345                 % RDFNS('Description')
346             )
347
348         lang = None
349         p = desc
350         while p is not None and lang is None:
351             lang = p.attrib.get(XMLNS('lang'))
352             p = p.getparent()
353
354         for e in desc.getchildren():
355             fv = field_dict.get(e.tag, [])
356             if e.text is not None:
357                 text = e.text
358                 if not isinstance(text, six.text_type):
359                     text = text.decode('utf-8')
360                 val = TextPlus(text)
361                 val.lang = e.attrib.get(XMLNS('lang'), lang)
362                 if e.tag == 'meta':
363                     meta_id = e.attrib.get('id')
364                     if meta_id and meta_id.endswith('-id'):
365                         field_dict[meta_id] = [val.replace('ISBN-', 'ISBN ')]
366             else:
367                 val = e.text
368             fv.append(val)
369             field_dict[e.tag] = fv
370
371         return cls(desc.attrib, field_dict, *args, **kwargs)
372
373     def __init__(self, rdf_attrs, dc_fields, fallbacks=None, strict=False, validate_required=True):
374         """
375         rdf_attrs should be a dictionary-like object with any attributes
376         of the RDF:Description.
377         dc_fields - dictionary mapping DC fields (with namespace) to
378         list of text values for the given field.
379         """
380
381         self.about = rdf_attrs.get(RDFNS('about'))
382         self.fmap = {}
383
384         for field in self.FIELDS:
385             value = field.validate(dc_fields, fallbacks=fallbacks,
386                                    strict=strict, validate_required=validate_required)
387             setattr(self, 'prop_' + field.name, value)
388             self.fmap[field.name] = field
389             if field.salias:
390                 self.fmap[field.salias] = field
391
392     def __getattribute__(self, name):
393         try:
394             field = object.__getattribute__(self, 'fmap')[name]
395             value = object.__getattribute__(self, 'prop_'+field.name)
396             if field.name == name:
397                 return value
398             else:  # singular alias
399                 if not field.multiple:
400                     raise "OUCH!! for field %s" % name
401
402                 return value[0] if value else None
403         except (KeyError, AttributeError):
404             return object.__getattribute__(self, name)
405
406     def __setattr__(self, name, newvalue):
407         try:
408             field = object.__getattribute__(self, 'fmap')[name]
409             if field.name == name:
410                 object.__setattr__(self, 'prop_'+field.name, newvalue)
411             else:  # singular alias
412                 if not field.multiple:
413                     raise "OUCH! while setting field %s" % name
414
415                 object.__setattr__(self, 'prop_'+field.name, [newvalue])
416         except (KeyError, AttributeError):
417             return object.__setattr__(self, name, newvalue)
418
419     def update(self, field_dict):
420         """
421         Update using field_dict. Verify correctness, but don't check
422         if all required fields are present.
423         """
424         for field in self.FIELDS:
425             if field.name in field_dict:
426                 setattr(self, field.name, field_dict[field.name])
427
428     def to_etree(self, parent=None):
429         """XML representation of this object."""
430         # etree._namespace_map[str(self.RDF)] = 'rdf'
431         # etree._namespace_map[str(self.DC)] = 'dc'
432
433         if parent is None:
434             root = etree.Element(RDFNS('RDF'))
435         else:
436             root = parent.makeelement(RDFNS('RDF'))
437
438         description = etree.SubElement(root, RDFNS('Description'))
439
440         if self.about:
441             description.set(RDFNS('about'), self.about)
442
443         for field in self.FIELDS:
444             v = getattr(self, field.name, None)
445             if v is not None:
446                 if field.multiple:
447                     if len(v) == 0:
448                         continue
449                     for x in v:
450                         e = etree.Element(field.uri)
451                         if x is not None:
452                             e.text = six.text_type(x)
453                         description.append(e)
454                 else:
455                     e = etree.Element(field.uri)
456                     e.text = six.text_type(v)
457                     description.append(e)
458
459         return root
460
461     def serialize(self):
462         rdf = {'about': {'uri': RDFNS('about'), 'value': self.about}}
463
464         dc = {}
465         for field in self.FIELDS:
466             v = getattr(self, field.name, None)
467             if v is not None:
468                 if field.multiple:
469                     if len(v) == 0:
470                         continue
471                     v = [six.text_type(x) for x in v if x is not None]
472                 else:
473                     v = six.text_type(v)
474
475                 dc[field.name] = {'uri': field.uri, 'value': v}
476         rdf['fields'] = dc
477         return rdf
478
479     def to_dict(self):
480         result = {'about': self.about}
481         for field in self.FIELDS:
482             v = getattr(self, field.name, None)
483
484             if v is not None:
485                 if field.multiple:
486                     if len(v) == 0:
487                         continue
488                     v = [six.text_type(x) for x in v if x is not None]
489                 else:
490                     v = six.text_type(v)
491                 result[field.name] = v
492
493             if field.salias:
494                 v = getattr(self, field.salias)
495                 if v is not None:
496                     result[field.salias] = six.text_type(v)
497
498         return result
499
500
501 class BookInfo(WorkInfo):
502     FIELDS = (
503         Field(DCNS('audience'), 'audiences', salias='audience', multiple=True,
504               required=False),
505
506         Field(DCNS('subject.period'), 'epochs', salias='epoch', multiple=True,
507               required=False),
508         Field(DCNS('subject.type'), 'kinds', salias='kind', multiple=True,
509               required=False),
510         Field(DCNS('subject.genre'), 'genres', salias='genre', multiple=True,
511               required=False),
512         Field(WLNS('category.legimi'), 'legimi', required=False),
513
514         Field(DCNS('subject.location'), 'location', required=False),
515
516         Field(DCNS('contributor.translator'), 'translators',
517               as_person,  salias='translator', multiple=True, required=False),
518         Field(DCNS('relation.hasPart'), 'parts', WLURI, strict=as_wluri_strict,
519               multiple=True, required=False),
520         Field(DCNS('relation.isVariantOf'), 'variant_of', WLURI,
521               strict=as_wluri_strict, required=False),
522
523         Field(DCNS('relation.coverImage.url'), 'cover_url', required=False),
524         Field(DCNS('relation.coverImage.attribution'), 'cover_by',
525               required=False),
526         Field(DCNS('relation.coverImage.source'), 'cover_source',
527               required=False),
528         # WLCover-specific.
529         Field(WLNS('coverBarColor'), 'cover_bar_color', required=False),
530         Field(WLNS('coverBoxPosition'), 'cover_box_position', required=False),
531         Field(WLNS('coverClass'), 'cover_class', default=['default']),
532         Field(WLNS('coverLogoUrl'), 'cover_logo_urls', multiple=True,
533               required=False),
534         Field(WLNS('endnotes'), 'endnotes', as_bool,
535               required=False),
536
537         Field('pdf-id',  'isbn_pdf',  required=False),
538         Field('epub-id', 'isbn_epub', required=False),
539         Field('mobi-id', 'isbn_mobi', required=False),
540         Field('txt-id',  'isbn_txt',  required=False),
541         Field('html-id', 'isbn_html', required=False),
542     )
543
544
545 def parse(file_name, cls=BookInfo):
546     return cls.from_file(file_name)