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 xml.parsers.expat import ExpatError
 
   7 from datetime import date
 
  10 from librarian.util import roman_to_int
 
  12 from librarian import (ValidationError, NoDublinCore, ParseError, DCNS, RDFNS,
 
  13                        XMLNS, WLURI, WLNS, PLMETNS)
 
  15 import lxml.etree as etree  # ElementTree API using libxml2
 
  16 from lxml.etree import XMLSyntaxError
 
  19 class TextPlus(unicode):
 
  31     """Single person with last name and a list of first names."""
 
  32     def __init__(self, last_name, *first_names):
 
  33         self.last_name = last_name
 
  34         self.first_names = first_names
 
  37     def from_text(cls, text):
 
  38         parts = [token.strip() for token in text.split(',')]
 
  43             raise ValueError("Invalid person name. There should be at most one comma: \"%s\"." % text.encode('utf-8'))
 
  46             if len(parts[1]) == 0:
 
  47                 # there is no non-whitespace data after the comma
 
  48                 raise ValueError("Found a comma, but no names given: \"%s\" -> %r." % (text, parts))
 
  49             names = [name for name in parts[1].split() if len(name)]  # all non-whitespace tokens
 
  50         return cls(surname, *names)
 
  53         return u" ".join(self.first_names + (self.last_name,))
 
  55     def __eq__(self, right):
 
  56         return self.last_name == right.last_name and self.first_names == right.first_names
 
  58     def __cmp__(self, other):
 
  59         return cmp((self.last_name, self.first_names), (other.last_name, other.first_names))
 
  62         return hash((self.last_name, self.first_names))
 
  64     def __unicode__(self):
 
  65         if len(self.first_names) > 0:
 
  66             return '%s, %s' % (self.last_name, ' '.join(self.first_names))
 
  71         return 'Person(last_name=%r, first_names=*%r)' % (self.last_name, self.first_names)
 
  75     """Dates for digitization of pictures. It seems we need the following:
 
  78 half centuries/decades: '2 poł. XVIII w.', 'XVII w., l. 20'
 
  80 circa 'ok. 1813-1814', 'ok.1876-ok.1886
 
  82 for now we will translate this to some single date losing information of course.
 
  85         # check out the "N. poł X w." syntax
 
  86         if isinstance(text, str):
 
  87             text = text.decode("utf-8")
 
  89         century_format = u"(?:([12]) *poł[.]? +)?([MCDXVI]+) *w[.,]*(?: *l[.]? *([0-9]+))?"
 
  90         vague_format = u"(?:po *|ok. *)?([0-9]{4})(-[0-9]{2}-[0-9]{2})?"
 
  92         m = re.match(century_format, text)
 
  93         m2 = re.match(vague_format, text)
 
  97             century = roman_to_int(str(m.group(2)))
 
  99                 if decade is not None:
 
 100                     raise ValueError("Bad date format. Cannot specify both half and decade of century")
 
 102                 t = ((century*100 + (half-1)*50), 1, 1)
 
 104                 decade = int(decade or 0)
 
 105                 t = ((century*100 + decade), 1, 1)
 
 108             mon_day = m2.group(2)
 
 110                 t = time.strptime(year + mon_day, "%Y-%m-%d")
 
 112                 t = time.strptime(year, '%Y')
 
 116         return DatePlus(t[0], t[1], t[2])
 
 117     except ValueError, e:
 
 118         raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
 
 122     return Person.from_text(text)
 
 125 def as_unicode(text):
 
 126     if isinstance(text, unicode):
 
 129         return TextPlus(text.decode('utf-8'))
 
 132 def as_wluri_strict(text):
 
 133     return WLURI.strict(text)
 
 137     def __init__(self, uri, attr_name, validator=as_unicode, strict=None, multiple=False, salias=None, **kwargs):
 
 139         self.name = attr_name
 
 140         self.validator = validator
 
 142         self.multiple = multiple
 
 145         self.required = kwargs.get('required', True) and 'default' not in kwargs
 
 146         self.default = kwargs.get('default', [] if multiple else [None])
 
 148     def validate_value(self, val, strict=False):
 
 149         if strict and self.strict is not None:
 
 150             validator = self.strict
 
 152             validator = self.validator
 
 155                 if validator is None:
 
 162                         if hasattr(v, 'lang'):
 
 163                             setattr(nv, 'lang', v.lang)
 
 164                     new_values.append(nv)
 
 167                 raise ValidationError("Multiple values not allowed for field '%s'" % self.uri)
 
 169                 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
 
 171                 if validator is None or val[0] is None:
 
 173                 nv = validator(val[0])
 
 174                 if hasattr(val[0], 'lang'):
 
 175                     setattr(nv, 'lang', val[0].lang)
 
 177         except ValueError, e:
 
 178             raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
 
 180     def validate(self, fdict, fallbacks=None, strict=False):
 
 181         if fallbacks is None:
 
 183         if self.uri not in fdict:
 
 184             if not self.required:
 
 185                 # Accept single value for single fields and saliases.
 
 186                 if self.name in fallbacks:
 
 188                         f = fallbacks[self.name]
 
 190                         f = [fallbacks[self.name]]
 
 191                 elif self.salias and self.salias in fallbacks:
 
 192                     f = [fallbacks[self.salias]]
 
 196                 raise ValidationError("Required field %s not found" % self.uri)
 
 200         return self.validate_value(f, strict=strict)
 
 202     def __eq__(self, other):
 
 203         if isinstance(other, Field) and other.name == self.name:
 
 209     def __new__(mcs, classname, bases, class_dict):
 
 210         fields = list(class_dict['FIELDS'])
 
 212         for base in bases[::-1]:
 
 213             if hasattr(base, 'FIELDS'):
 
 214                 for field in base.FIELDS[::-1]:
 
 218                         fields.insert(0, field)
 
 220         class_dict['FIELDS'] = tuple(fields)
 
 221         return super(DCInfo, mcs).__new__(mcs, classname, bases, class_dict)
 
 224 class WorkInfo(object):
 
 225     __metaclass__ = DCInfo
 
 228         Field(DCNS('creator'), 'authors', as_person, salias='author', multiple=True),
 
 229         Field(DCNS('title'), 'title'),
 
 230         Field(DCNS('type'), 'type', required=False, multiple=True),
 
 232         Field(DCNS('contributor.editor'), 'editors',
 
 233               as_person, salias='editor', multiple=True, default=[]),
 
 234         Field(DCNS('contributor.technical_editor'), 'technical_editors',
 
 235               as_person, salias='technical_editor', multiple=True, default=[]),
 
 236         Field(DCNS('contributor.funding'), 'funders', salias='funder', multiple=True, default=[]),
 
 237         Field(DCNS('contributor.thanks'), 'thanks', required=False),
 
 239         Field(DCNS('date'), 'created_at'),
 
 240         Field(DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
 
 241         Field(DCNS('publisher'), 'publisher'),
 
 243         Field(DCNS('language'), 'language'),
 
 244         Field(DCNS('description'), 'description', required=False),
 
 246         Field(DCNS('source'), 'source_name', required=False),
 
 247         Field(DCNS('source.URL'), 'source_url', required=False),
 
 248         Field(DCNS('identifier.url'), 'url', WLURI, strict=as_wluri_strict),
 
 249         Field(DCNS('rights.license'), 'license', required=False),
 
 250         Field(DCNS('rights'), 'license_description'),
 
 252         Field(PLMETNS('digitisationSponsor'), 'sponsors', multiple=True, default=[]),
 
 253         Field(WLNS('digitisationSponsorNote'), 'sponsor_note', required=False),
 
 254         Field(WLNS('developmentStage'), 'stage', required=False),
 
 258     def from_string(cls, xml, *args, **kwargs):
 
 259         from StringIO import StringIO
 
 260         return cls.from_file(StringIO(xml), *args, **kwargs)
 
 263     def from_file(cls, xmlfile, *args, **kwargs):
 
 266             iter = etree.iterparse(xmlfile, ['start', 'end'])
 
 267             for (event, element) in iter:
 
 268                 if element.tag == RDFNS('RDF') and event == 'start':
 
 273                 raise NoDublinCore("DublinCore section not found. \
 
 274                     Check if there are rdf:RDF and rdf:Description tags.")
 
 276             # continue 'till the end of RDF section
 
 277             for (event, element) in iter:
 
 278                 if element.tag == RDFNS('RDF') and event == 'end':
 
 281             # if there is no end, Expat should yell at us with an ExpatError
 
 283             # extract data from the element and make the info
 
 284             return cls.from_element(desc_tag, *args, **kwargs)
 
 285         except XMLSyntaxError, e:
 
 287         except ExpatError, e:
 
 291     def from_element(cls, rdf_tag, *args, **kwargs):
 
 292         # the tree is already parsed, so we don't need to worry about Expat errors
 
 294         desc = rdf_tag.find(".//" + RDFNS('Description'))
 
 297             raise NoDublinCore("No DublinCore section found.")
 
 301         while p is not None and lang is None:
 
 302             lang = p.attrib.get(XMLNS('lang'))
 
 305         for e in desc.getchildren():
 
 306             fv = field_dict.get(e.tag, [])
 
 307             if e.text is not None:
 
 309                 if not isinstance(text, unicode):
 
 310                     text = text.decode('utf-8')
 
 312                 val.lang = e.attrib.get(XMLNS('lang'), lang)
 
 316             field_dict[e.tag] = fv
 
 318         return cls(desc.attrib, field_dict, *args, **kwargs)
 
 320     def __init__(self, rdf_attrs, dc_fields, fallbacks=None, strict=False):
 
 321         """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
 
 322         dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
 
 325         self.about = rdf_attrs.get(RDFNS('about'))
 
 328         for field in self.FIELDS:
 
 329             value = field.validate(dc_fields, fallbacks=fallbacks, strict=strict)
 
 330             setattr(self, 'prop_' + field.name, value)
 
 331             self.fmap[field.name] = field
 
 333                 self.fmap[field.salias] = field
 
 335     def __getattribute__(self, name):
 
 337             field = object.__getattribute__(self, 'fmap')[name]
 
 338             value = object.__getattribute__(self, 'prop_'+field.name)
 
 339             if field.name == name:
 
 341             else:  # singular alias
 
 342                 if not field.multiple:
 
 343                     raise "OUCH!! for field %s" % name
 
 345                 return value[0] if value else None
 
 346         except (KeyError, AttributeError):
 
 347             return object.__getattribute__(self, name)
 
 349     def __setattr__(self, name, newvalue):
 
 351             field = object.__getattribute__(self, 'fmap')[name]
 
 352             if field.name == name:
 
 353                 object.__setattr__(self, 'prop_'+field.name, newvalue)
 
 354             else:  # singular alias
 
 355                 if not field.multiple:
 
 356                     raise "OUCH! while setting field %s" % name
 
 358                 object.__setattr__(self, 'prop_'+field.name, [newvalue])
 
 359         except (KeyError, AttributeError):
 
 360             return object.__setattr__(self, name, newvalue)
 
 362     def update(self, field_dict):
 
 363         """Update using field_dict. Verify correctness, but don't check if all
 
 364         required fields are present."""
 
 365         for field in self.FIELDS:
 
 366             if field.name in field_dict:
 
 367                 setattr(self, field.name, field_dict[field.name])
 
 369     def to_etree(self, parent=None):
 
 370         """XML representation of this object."""
 
 371         # etree._namespace_map[str(self.RDF)] = 'rdf'
 
 372         # etree._namespace_map[str(self.DC)] = 'dc'
 
 375             root = etree.Element(RDFNS('RDF'))
 
 377             root = parent.makeelement(RDFNS('RDF'))
 
 379         description = etree.SubElement(root, RDFNS('Description'))
 
 382             description.set(RDFNS('about'), self.about)
 
 384         for field in self.FIELDS:
 
 385             v = getattr(self, field.name, None)
 
 391                         e = etree.Element(field.uri)
 
 394                         description.append(e)
 
 396                     e = etree.Element(field.uri)
 
 398                     description.append(e)
 
 403         rdf = {'about': {'uri': RDFNS('about'), 'value': self.about}}
 
 406         for field in self.FIELDS:
 
 407             v = getattr(self, field.name, None)
 
 412                     v = [unicode(x) for x in v if x is not None]
 
 416                 dc[field.name] = {'uri': field.uri, 'value': v}
 
 421         result = {'about': self.about}
 
 422         for field in self.FIELDS:
 
 423             v = getattr(self, field.name, None)
 
 429                     v = [unicode(x) for x in v if x is not None]
 
 432                 result[field.name] = v
 
 435                 v = getattr(self, field.salias)
 
 437                     result[field.salias] = unicode(v)
 
 442 class BookInfo(WorkInfo):
 
 444         Field(DCNS('audience'), 'audiences', salias='audience', multiple=True, required=False),
 
 446         Field(DCNS('subject.period'), 'epochs', salias='epoch', multiple=True, required=False),
 
 447         Field(DCNS('subject.type'), 'kinds', salias='kind', multiple=True, required=False),
 
 448         Field(DCNS('subject.genre'), 'genres', salias='genre', multiple=True, required=False),
 
 450         Field(DCNS('contributor.translator'), 'translators',
 
 451               as_person,  salias='translator', multiple=True, default=[]),
 
 452         Field(DCNS('relation.hasPart'), 'parts', WLURI, strict=as_wluri_strict, multiple=True, required=False),
 
 453         Field(DCNS('relation.isVariantOf'), 'variant_of', WLURI, strict=as_wluri_strict, required=False),
 
 455         Field(DCNS('relation.coverImage.url'), 'cover_url', required=False),
 
 456         Field(DCNS('relation.coverImage.attribution'), 'cover_by', required=False),
 
 457         Field(DCNS('relation.coverImage.source'), 'cover_source', required=False),
 
 459         Field(WLNS('coverBarColor'), 'cover_bar_color', required=False),
 
 460         Field(WLNS('coverBoxPosition'), 'cover_box_position', required=False),
 
 464 def parse(file_name, cls=BookInfo):
 
 465     return cls.from_file(file_name)