1 # -*- coding: utf-8 -*-
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 from __future__ import unicode_literals
8 from xml.parsers.expat import ExpatError
9 from datetime import date
10 from functools import total_ordering
14 from librarian.util import roman_to_int
16 from librarian import (ValidationError, NoDublinCore, ParseError, DCNS, RDFNS,
17 XMLNS, WLURI, WLNS, PLMETNS)
19 import lxml.etree as etree # ElementTree API using libxml2
20 from lxml.etree import XMLSyntaxError
23 class TextPlus(six.text_type):
34 @six.python_2_unicode_compatible
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
43 def from_text(cls, text):
44 parts = [token.strip() for token in text.split(',')]
50 "Invalid person name. "
51 "There should be at most one comma: \"%s\"."
52 % text.encode('utf-8')
56 if len(parts[1]) == 0:
57 # there is no non-whitespace data after the comma
59 "Found a comma, but no names given: \"%s\" -> %r."
62 names = parts[1].split()
63 return cls(surname, *names)
66 return u" ".join(self.first_names + (self.last_name,))
68 def __eq__(self, right):
69 return (self.last_name == right.last_name
70 and self.first_names == right.first_names)
72 def __lt__(self, other):
73 return ((self.last_name, self.first_names)
74 < (other.last_name, other.first_names))
77 return hash((self.last_name, self.first_names))
80 if len(self.first_names) > 0:
81 return '%s, %s' % (self.last_name, ' '.join(self.first_names))
86 return 'Person(last_name=%r, first_names=*%r)' % (
87 self.last_name, self.first_names
93 Dates for digitization of pictures. It seems we need the following:
96 half centuries/decades: '2 poł. XVIII w.', 'XVII w., l. 20'
98 circa 'ok. 1813-1814', 'ok.1876-ok.1886
101 For now we will translate this to some single date
102 losing information of course.
105 # check out the "N. poł X w." syntax
106 if isinstance(text, six.binary_type):
107 text = text.decode("utf-8")
110 u"(?:([12]) *poł[.]? +)?([MCDXVI]+) *w[.,]*(?: *l[.]? *([0-9]+))?"
112 vague_format = u"(?:po *|ok. *)?([0-9]{4})(-[0-9]{2}-[0-9]{2})?"
114 m = re.match(century_format, text)
115 m2 = re.match(vague_format, text)
119 century = roman_to_int(m.group(2))
121 if decade is not None:
124 "Cannot specify both half and decade of century."
127 t = ((century*100 + (half-1)*50), 1, 1)
129 decade = int(decade or 0)
130 t = ((century*100 + decade), 1, 1)
133 mon_day = m2.group(2)
135 t = time.strptime(year + mon_day, "%Y-%m-%d")
137 t = time.strptime(year, '%Y')
141 return DatePlus(t[0], t[1], t[2])
143 raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
147 return Person.from_text(text)
150 def as_unicode(text):
151 if isinstance(text, six.text_type):
154 return TextPlus(text.decode('utf-8'))
157 def as_wluri_strict(text):
158 return WLURI.strict(text)
162 def __init__(self, uri, attr_name, validator=as_unicode, strict=None,
163 multiple=False, salias=None, **kwargs):
165 self.name = attr_name
166 self.validator = validator
168 self.multiple = multiple
171 self.required = (kwargs.get('required', True)
172 and 'default' not in kwargs)
173 self.default = kwargs.get('default', [] if multiple else [None])
175 def validate_value(self, val, strict=False):
176 if strict and self.strict is not None:
177 validator = self.strict
179 validator = self.validator
182 if validator is None:
189 if hasattr(v, 'lang'):
190 setattr(nv, 'lang', v.lang)
191 new_values.append(nv)
194 raise ValidationError(
195 "Multiple values not allowed for field '%s'" % self.uri
198 raise ValidationError(
199 "Field %s has no value to assign. Check your defaults."
203 if validator is None or val[0] is None:
205 nv = validator(val[0])
206 if hasattr(val[0], 'lang'):
207 setattr(nv, 'lang', val[0].lang)
209 except ValueError as e:
210 raise ValidationError(
211 "Field '%s' - invald value: %s"
212 % (self.uri, e.message)
215 def validate(self, fdict, fallbacks=None, strict=False, validate_required=True):
216 if fallbacks is None:
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:
223 f = fallbacks[self.name]
225 f = [fallbacks[self.name]]
226 elif self.salias and self.salias in fallbacks:
227 f = [fallbacks[self.salias]]
230 elif validate_required:
231 raise ValidationError("Required field %s not found" % self.uri)
237 return self.validate_value(f, strict=strict)
239 def __eq__(self, other):
240 if isinstance(other, Field) and other.name == self.name:
246 def __new__(mcs, classname, bases, class_dict):
247 fields = list(class_dict['FIELDS'])
249 for base in bases[::-1]:
250 if hasattr(base, 'FIELDS'):
251 for field in base.FIELDS[::-1]:
255 fields.insert(0, field)
257 class_dict['FIELDS'] = tuple(fields)
258 return super(DCInfo, mcs).__new__(mcs, classname, bases, class_dict)
261 class WorkInfo(six.with_metaclass(DCInfo, object)):
263 Field(DCNS('creator'), 'authors', as_person, salias='author',
265 Field(DCNS('title'), 'title'),
266 Field(DCNS('type'), 'type', required=False, multiple=True),
268 Field(DCNS('contributor.editor'), 'editors',
269 as_person, salias='editor', multiple=True, required=False),
270 Field(DCNS('contributor.technical_editor'), 'technical_editors',
271 as_person, salias='technical_editor', multiple=True,
273 Field(DCNS('contributor.funding'), 'funders', salias='funder',
274 multiple=True, required=False),
275 Field(DCNS('contributor.thanks'), 'thanks', required=False),
277 Field(DCNS('date'), 'created_at'),
278 Field(DCNS('date.pd'), 'released_to_public_domain_at', as_date,
280 Field(DCNS('publisher'), 'publisher', multiple=True),
282 Field(DCNS('language'), 'language'),
283 Field(DCNS('description'), 'description', required=False),
285 Field(DCNS('source'), 'source_name', required=False),
286 Field(DCNS('source.URL'), 'source_urls', salias='source_url',
287 multiple=True, required=False),
288 Field(DCNS('identifier.url'), 'url', WLURI, strict=as_wluri_strict),
289 Field(DCNS('rights.license'), 'license', required=False),
290 Field(DCNS('rights'), 'license_description'),
292 Field(PLMETNS('digitisationSponsor'), 'sponsors', multiple=True,
294 Field(WLNS('digitisationSponsorNote'), 'sponsor_note', required=False),
295 Field(WLNS('contentWarning'), 'content_warnings', multiple=True,
297 Field(WLNS('developmentStage'), 'stage', required=False),
301 def from_bytes(cls, xml, *args, **kwargs):
302 return cls.from_file(six.BytesIO(xml), *args, **kwargs)
305 def from_file(cls, xmlfile, *args, **kwargs):
308 iter = etree.iterparse(xmlfile, ['start', 'end'])
309 for (event, element) in iter:
310 if element.tag == RDFNS('RDF') and event == 'start':
315 raise NoDublinCore("DublinCore section not found. \
316 Check if there are rdf:RDF and rdf:Description tags.")
318 # continue 'till the end of RDF section
319 for (event, element) in iter:
320 if element.tag == RDFNS('RDF') and event == 'end':
323 # if there is no end, Expat should yell at us with an ExpatError
325 # extract data from the element and make the info
326 return cls.from_element(desc_tag, *args, **kwargs)
327 except XMLSyntaxError as e:
329 except ExpatError as e:
333 def from_element(cls, rdf_tag, *args, **kwargs):
334 # The tree is already parsed,
335 # so we don't need to worry about Expat errors.
337 desc = rdf_tag.find(".//" + RDFNS('Description'))
341 "There must be a '%s' element inside the RDF."
342 % RDFNS('Description')
347 while p is not None and lang is None:
348 lang = p.attrib.get(XMLNS('lang'))
351 for e in desc.getchildren():
352 fv = field_dict.get(e.tag, [])
353 if e.text is not None:
355 if not isinstance(text, six.text_type):
356 text = text.decode('utf-8')
358 val.lang = e.attrib.get(XMLNS('lang'), lang)
360 meta_id = e.attrib.get('id')
361 if meta_id and meta_id.endswith('-id'):
362 field_dict[meta_id] = [val.replace('ISBN-', 'ISBN ')]
366 field_dict[e.tag] = fv
368 return cls(desc.attrib, field_dict, *args, **kwargs)
370 def __init__(self, rdf_attrs, dc_fields, fallbacks=None, strict=False, validate_required=True):
372 rdf_attrs should be a dictionary-like object with any attributes
373 of the RDF:Description.
374 dc_fields - dictionary mapping DC fields (with namespace) to
375 list of text values for the given field.
378 self.about = rdf_attrs.get(RDFNS('about'))
381 for field in self.FIELDS:
382 value = field.validate(dc_fields, fallbacks=fallbacks,
383 strict=strict, validate_required=validate_required)
384 setattr(self, 'prop_' + field.name, value)
385 self.fmap[field.name] = field
387 self.fmap[field.salias] = field
389 def __getattribute__(self, name):
391 field = object.__getattribute__(self, 'fmap')[name]
392 value = object.__getattribute__(self, 'prop_'+field.name)
393 if field.name == name:
395 else: # singular alias
396 if not field.multiple:
397 raise "OUCH!! for field %s" % name
399 return value[0] if value else None
400 except (KeyError, AttributeError):
401 return object.__getattribute__(self, name)
403 def __setattr__(self, name, newvalue):
405 field = object.__getattribute__(self, 'fmap')[name]
406 if field.name == name:
407 object.__setattr__(self, 'prop_'+field.name, newvalue)
408 else: # singular alias
409 if not field.multiple:
410 raise "OUCH! while setting field %s" % name
412 object.__setattr__(self, 'prop_'+field.name, [newvalue])
413 except (KeyError, AttributeError):
414 return object.__setattr__(self, name, newvalue)
416 def update(self, field_dict):
418 Update using field_dict. Verify correctness, but don't check
419 if all required fields are present.
421 for field in self.FIELDS:
422 if field.name in field_dict:
423 setattr(self, field.name, field_dict[field.name])
425 def to_etree(self, parent=None):
426 """XML representation of this object."""
427 # etree._namespace_map[str(self.RDF)] = 'rdf'
428 # etree._namespace_map[str(self.DC)] = 'dc'
431 root = etree.Element(RDFNS('RDF'))
433 root = parent.makeelement(RDFNS('RDF'))
435 description = etree.SubElement(root, RDFNS('Description'))
438 description.set(RDFNS('about'), self.about)
440 for field in self.FIELDS:
441 v = getattr(self, field.name, None)
447 e = etree.Element(field.uri)
449 e.text = six.text_type(x)
450 description.append(e)
452 e = etree.Element(field.uri)
453 e.text = six.text_type(v)
454 description.append(e)
459 rdf = {'about': {'uri': RDFNS('about'), 'value': self.about}}
462 for field in self.FIELDS:
463 v = getattr(self, field.name, None)
468 v = [six.text_type(x) for x in v if x is not None]
472 dc[field.name] = {'uri': field.uri, 'value': v}
477 result = {'about': self.about}
478 for field in self.FIELDS:
479 v = getattr(self, field.name, None)
485 v = [six.text_type(x) for x in v if x is not None]
488 result[field.name] = v
491 v = getattr(self, field.salias)
493 result[field.salias] = six.text_type(v)
498 class BookInfo(WorkInfo):
500 Field(DCNS('audience'), 'audiences', salias='audience', multiple=True,
503 Field(DCNS('subject.period'), 'epochs', salias='epoch', multiple=True,
505 Field(DCNS('subject.type'), 'kinds', salias='kind', multiple=True,
507 Field(DCNS('subject.genre'), 'genres', salias='genre', multiple=True,
510 Field(DCNS('subject.location'), 'location', required=False),
512 Field(DCNS('contributor.translator'), 'translators',
513 as_person, salias='translator', multiple=True, required=False),
514 Field(DCNS('relation.hasPart'), 'parts', WLURI, strict=as_wluri_strict,
515 multiple=True, required=False),
516 Field(DCNS('relation.isVariantOf'), 'variant_of', WLURI,
517 strict=as_wluri_strict, required=False),
519 Field(DCNS('relation.coverImage.url'), 'cover_url', required=False),
520 Field(DCNS('relation.coverImage.attribution'), 'cover_by',
522 Field(DCNS('relation.coverImage.source'), 'cover_source',
525 Field(WLNS('coverBarColor'), 'cover_bar_color', required=False),
526 Field(WLNS('coverBoxPosition'), 'cover_box_position', required=False),
527 Field(WLNS('coverClass'), 'cover_class', default=['default']),
528 Field(WLNS('coverLogoUrl'), 'cover_logo_urls', multiple=True,
531 Field('pdf-id', 'isbn_pdf', required=False),
532 Field('epub-id', 'isbn_epub', required=False),
533 Field('mobi-id', 'isbn_mobi', required=False),
534 Field('txt-id', 'isbn_txt', required=False),
535 Field('html-id', 'isbn_html', required=False),
539 def parse(file_name, cls=BookInfo):
540 return cls.from_file(file_name)