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(',')]
 
  49             raise ValueError("Invalid person name. There should be at most one comma: \"%s\"." % text.encode('utf-8'))
 
  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)
 
  59         return u" ".join(self.first_names + (self.last_name,))
 
  61     def __eq__(self, right):
 
  62         return self.last_name == right.last_name and self.first_names == right.first_names
 
  64     def __lt__(self, other):
 
  65         return (self.last_name, self.first_names) < (other.last_name, other.first_names)
 
  68         return hash((self.last_name, self.first_names))
 
  71         if len(self.first_names) > 0:
 
  72             return '%s, %s' % (self.last_name, ' '.join(self.first_names))
 
  77         return 'Person(last_name=%r, first_names=*%r)' % (self.last_name, self.first_names)
 
  81     """Dates for digitization of pictures. It seems we need the following:
 
  84 half centuries/decades: '2 poł. XVIII w.', 'XVII w., l. 20'
 
  86 circa 'ok. 1813-1814', 'ok.1876-ok.1886
 
  88 for now we will translate this to some single date losing information of course.
 
  91         # check out the "N. poł X w." syntax
 
  92         if isinstance(text, six.binary_type):
 
  93             text = text.decode("utf-8")
 
  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})?"
 
  98         m = re.match(century_format, text)
 
  99         m2 = re.match(vague_format, text)
 
 103             century = roman_to_int(m.group(2))
 
 105                 if decade is not None:
 
 106                     raise ValueError("Bad date format. Cannot specify both half and decade of century")
 
 108                 t = ((century*100 + (half-1)*50), 1, 1)
 
 110                 decade = int(decade or 0)
 
 111                 t = ((century*100 + decade), 1, 1)
 
 114             mon_day = m2.group(2)
 
 116                 t = time.strptime(year + mon_day, "%Y-%m-%d")
 
 118                 t = time.strptime(year, '%Y')
 
 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.")
 
 128     return Person.from_text(text)
 
 131 def as_unicode(text):
 
 132     if isinstance(text, six.text_type):
 
 135         return TextPlus(text.decode('utf-8'))
 
 138 def as_wluri_strict(text):
 
 139     return WLURI.strict(text)
 
 143     def __init__(self, uri, attr_name, validator=as_unicode, strict=None, multiple=False, salias=None, **kwargs):
 
 145         self.name = attr_name
 
 146         self.validator = validator
 
 148         self.multiple = multiple
 
 151         self.required = kwargs.get('required', True) and 'default' not in kwargs
 
 152         self.default = kwargs.get('default', [] if multiple else [None])
 
 154     def validate_value(self, val, strict=False):
 
 155         if strict and self.strict is not None:
 
 156             validator = self.strict
 
 158             validator = self.validator
 
 161                 if validator is None:
 
 168                         if hasattr(v, 'lang'):
 
 169                             setattr(nv, 'lang', v.lang)
 
 170                     new_values.append(nv)
 
 173                 raise ValidationError("Multiple values not allowed for field '%s'" % self.uri)
 
 175                 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
 
 177                 if validator is None or val[0] is None:
 
 179                 nv = validator(val[0])
 
 180                 if hasattr(val[0], 'lang'):
 
 181                     setattr(nv, 'lang', val[0].lang)
 
 183         except ValueError as e:
 
 184             raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
 
 186     def validate(self, fdict, fallbacks=None, strict=False):
 
 187         if fallbacks is None:
 
 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:
 
 194                         f = fallbacks[self.name]
 
 196                         f = [fallbacks[self.name]]
 
 197                 elif self.salias and self.salias in fallbacks:
 
 198                     f = [fallbacks[self.salias]]
 
 202                 raise ValidationError("Required field %s not found" % self.uri)
 
 206         return self.validate_value(f, strict=strict)
 
 208     def __eq__(self, other):
 
 209         if isinstance(other, Field) and other.name == self.name:
 
 215     def __new__(mcs, classname, bases, class_dict):
 
 216         fields = list(class_dict['FIELDS'])
 
 218         for base in bases[::-1]:
 
 219             if hasattr(base, 'FIELDS'):
 
 220                 for field in base.FIELDS[::-1]:
 
 224                         fields.insert(0, field)
 
 226         class_dict['FIELDS'] = tuple(fields)
 
 227         return super(DCInfo, mcs).__new__(mcs, classname, bases, class_dict)
 
 230 class WorkInfo(six.with_metaclass(DCInfo, object)):
 
 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),
 
 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),
 
 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),
 
 247         Field(DCNS('language'), 'language'),
 
 248         Field(DCNS('description'), 'description', required=False),
 
 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'),
 
 256         Field(PLMETNS('digitisationSponsor'), 'sponsors', multiple=True, required=False),
 
 257         Field(WLNS('digitisationSponsorNote'), 'sponsor_note', required=False),
 
 258         Field(WLNS('developmentStage'), 'stage', required=False),
 
 262     def from_bytes(cls, xml, *args, **kwargs):
 
 263         return cls.from_file(six.BytesIO(xml), *args, **kwargs)
 
 266     def from_file(cls, xmlfile, *args, **kwargs):
 
 269             iter = etree.iterparse(xmlfile, ['start', 'end'])
 
 270             for (event, element) in iter:
 
 271                 if element.tag == RDFNS('RDF') and event == 'start':
 
 276                 raise NoDublinCore("DublinCore section not found. \
 
 277                     Check if there are rdf:RDF and rdf:Description tags.")
 
 279             # continue 'till the end of RDF section
 
 280             for (event, element) in iter:
 
 281                 if element.tag == RDFNS('RDF') and event == 'end':
 
 284             # if there is no end, Expat should yell at us with an ExpatError
 
 286             # extract data from the element and make the info
 
 287             return cls.from_element(desc_tag, *args, **kwargs)
 
 288         except XMLSyntaxError as e:
 
 290         except ExpatError as e:
 
 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
 
 297         desc = rdf_tag.find(".//" + RDFNS('Description'))
 
 300             raise NoDublinCore("No DublinCore section found.")
 
 304         while p is not None and lang is None:
 
 305             lang = p.attrib.get(XMLNS('lang'))
 
 308         for e in desc.getchildren():
 
 309             fv = field_dict.get(e.tag, [])
 
 310             if e.text is not None:
 
 312                 if not isinstance(text, six.text_type):
 
 313                     text = text.decode('utf-8')
 
 315                 val.lang = e.attrib.get(XMLNS('lang'), lang)
 
 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 ')]
 
 323             field_dict[e.tag] = fv
 
 325         return cls(desc.attrib, field_dict, *args, **kwargs)
 
 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
 
 332         self.about = rdf_attrs.get(RDFNS('about'))
 
 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
 
 340                 self.fmap[field.salias] = field
 
 342     def __getattribute__(self, name):
 
 344             field = object.__getattribute__(self, 'fmap')[name]
 
 345             value = object.__getattribute__(self, 'prop_'+field.name)
 
 346             if field.name == name:
 
 348             else:  # singular alias
 
 349                 if not field.multiple:
 
 350                     raise "OUCH!! for field %s" % name
 
 352                 return value[0] if value else None
 
 353         except (KeyError, AttributeError):
 
 354             return object.__getattribute__(self, name)
 
 356     def __setattr__(self, name, newvalue):
 
 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
 
 365                 object.__setattr__(self, 'prop_'+field.name, [newvalue])
 
 366         except (KeyError, AttributeError):
 
 367             return object.__setattr__(self, name, newvalue)
 
 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])
 
 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'
 
 382             root = etree.Element(RDFNS('RDF'))
 
 384             root = parent.makeelement(RDFNS('RDF'))
 
 386         description = etree.SubElement(root, RDFNS('Description'))
 
 389             description.set(RDFNS('about'), self.about)
 
 391         for field in self.FIELDS:
 
 392             v = getattr(self, field.name, None)
 
 398                         e = etree.Element(field.uri)
 
 400                             e.text = six.text_type(x)
 
 401                         description.append(e)
 
 403                     e = etree.Element(field.uri)
 
 404                     e.text = six.text_type(v)
 
 405                     description.append(e)
 
 410         rdf = {'about': {'uri': RDFNS('about'), 'value': self.about}}
 
 413         for field in self.FIELDS:
 
 414             v = getattr(self, field.name, None)
 
 419                     v = [six.text_type(x) for x in v if x is not None]
 
 423                 dc[field.name] = {'uri': field.uri, 'value': v}
 
 428         result = {'about': self.about}
 
 429         for field in self.FIELDS:
 
 430             v = getattr(self, field.name, None)
 
 436                     v = [six.text_type(x) for x in v if x is not None]
 
 439                 result[field.name] = v
 
 442                 v = getattr(self, field.salias)
 
 444                     result[field.salias] = six.text_type(v)
 
 449 class BookInfo(WorkInfo):
 
 451         Field(DCNS('audience'), 'audiences', salias='audience', multiple=True, required=False),
 
 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),
 
 457         Field(DCNS('subject.location'), 'location', required=False),
 
 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),
 
 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),
 
 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),
 
 479 def parse(file_name, cls=BookInfo):
 
 480     return cls.from_file(file_name)