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 = parts[1].split()
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, required=False),
234 Field(DCNS('contributor.technical_editor'), 'technical_editors',
235 as_person, salias='technical_editor', multiple=True, required=False),
236 Field(DCNS('contributor.funding'), 'funders', salias='funder', multiple=True, required=False),
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', multiple=True),
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, required=False),
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)
314 meta_id = e.attrib.get('id')
315 if meta_id and meta_id.endswith('-id'):
316 field_dict[meta_id] = [val.replace('ISBN-', 'ISBN ')]
320 field_dict[e.tag] = fv
322 return cls(desc.attrib, field_dict, *args, **kwargs)
324 def __init__(self, rdf_attrs, dc_fields, fallbacks=None, strict=False):
325 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
326 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
329 self.about = rdf_attrs.get(RDFNS('about'))
332 for field in self.FIELDS:
333 value = field.validate(dc_fields, fallbacks=fallbacks, strict=strict)
334 setattr(self, 'prop_' + field.name, value)
335 self.fmap[field.name] = field
337 self.fmap[field.salias] = field
339 def __getattribute__(self, name):
341 field = object.__getattribute__(self, 'fmap')[name]
342 value = object.__getattribute__(self, 'prop_'+field.name)
343 if field.name == name:
345 else: # singular alias
346 if not field.multiple:
347 raise "OUCH!! for field %s" % name
349 return value[0] if value else None
350 except (KeyError, AttributeError):
351 return object.__getattribute__(self, name)
353 def __setattr__(self, name, newvalue):
355 field = object.__getattribute__(self, 'fmap')[name]
356 if field.name == name:
357 object.__setattr__(self, 'prop_'+field.name, newvalue)
358 else: # singular alias
359 if not field.multiple:
360 raise "OUCH! while setting field %s" % name
362 object.__setattr__(self, 'prop_'+field.name, [newvalue])
363 except (KeyError, AttributeError):
364 return object.__setattr__(self, name, newvalue)
366 def update(self, field_dict):
367 """Update using field_dict. Verify correctness, but don't check if all
368 required fields are present."""
369 for field in self.FIELDS:
370 if field.name in field_dict:
371 setattr(self, field.name, field_dict[field.name])
373 def to_etree(self, parent=None):
374 """XML representation of this object."""
375 # etree._namespace_map[str(self.RDF)] = 'rdf'
376 # etree._namespace_map[str(self.DC)] = 'dc'
379 root = etree.Element(RDFNS('RDF'))
381 root = parent.makeelement(RDFNS('RDF'))
383 description = etree.SubElement(root, RDFNS('Description'))
386 description.set(RDFNS('about'), self.about)
388 for field in self.FIELDS:
389 v = getattr(self, field.name, None)
395 e = etree.Element(field.uri)
398 description.append(e)
400 e = etree.Element(field.uri)
402 description.append(e)
407 rdf = {'about': {'uri': RDFNS('about'), 'value': self.about}}
410 for field in self.FIELDS:
411 v = getattr(self, field.name, None)
416 v = [unicode(x) for x in v if x is not None]
420 dc[field.name] = {'uri': field.uri, 'value': v}
425 result = {'about': self.about}
426 for field in self.FIELDS:
427 v = getattr(self, field.name, None)
433 v = [unicode(x) for x in v if x is not None]
436 result[field.name] = v
439 v = getattr(self, field.salias)
441 result[field.salias] = unicode(v)
446 class BookInfo(WorkInfo):
448 Field(DCNS('audience'), 'audiences', salias='audience', multiple=True, required=False),
450 Field(DCNS('subject.period'), 'epochs', salias='epoch', multiple=True, required=False),
451 Field(DCNS('subject.type'), 'kinds', salias='kind', multiple=True, required=False),
452 Field(DCNS('subject.genre'), 'genres', salias='genre', multiple=True, required=False),
454 Field(DCNS('subject.location'), 'location', required=False),
456 Field(DCNS('contributor.translator'), 'translators',
457 as_person, salias='translator', multiple=True, required=False),
458 Field(DCNS('relation.hasPart'), 'parts', WLURI, strict=as_wluri_strict, multiple=True, required=False),
459 Field(DCNS('relation.isVariantOf'), 'variant_of', WLURI, strict=as_wluri_strict, required=False),
461 Field(DCNS('relation.coverImage.url'), 'cover_url', required=False),
462 Field(DCNS('relation.coverImage.attribution'), 'cover_by', required=False),
463 Field(DCNS('relation.coverImage.source'), 'cover_source', required=False),
465 Field(WLNS('coverBarColor'), 'cover_bar_color', required=False),
466 Field(WLNS('coverBoxPosition'), 'cover_box_position', required=False),
467 Field(WLNS('coverClass'), 'cover_class', default=['default']),
468 Field('pdf-id', 'isbn_pdf', required=False),
469 Field('epub-id', 'isbn_epub', required=False),
470 Field('mobi-id', 'isbn_mobi', required=False),
471 Field('txt-id', 'isbn_txt', required=False),
472 Field('html-id', 'isbn_html', required=False),
476 def parse(file_name, cls=BookInfo):
477 return cls.from_file(file_name)