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):
30 """Single person with last name and a list of first names."""
31 def __init__(self, last_name, *first_names):
32 self.last_name = last_name
33 self.first_names = first_names
36 def from_text(cls, text):
37 parts = [ token.strip() for token in text.split(',') ]
42 raise ValueError("Invalid person name. There should be at most one comma: \"%s\"." % text)
45 if len(parts[1]) == 0:
46 # there is no non-whitespace data after the comma
47 raise ValueError("Found a comma, but no names given: \"%s\" -> %r." % (text, parts))
48 names = [ name for name in parts[1].split() if len(name) ] # all non-whitespace tokens
49 return cls(surname, *names)
52 return u" ".join(self.first_names + (self.last_name,))
54 def __eq__(self, right):
55 return self.last_name == right.last_name and self.first_names == right.first_names
57 def __cmp__(self, other):
58 return cmp((self.last_name, self.first_names), (other.last_name, other.first_names))
61 return hash((self.last_name, self.first_names))
63 def __unicode__(self):
64 if len(self.first_names) > 0:
65 return '%s, %s' % (self.last_name, ' '.join(self.first_names))
70 return 'Person(last_name=%r, first_names=*%r)' % (self.last_name, self.first_names)
73 """Dates for digitization of pictures. It seems we need the following:
76 half centuries/decades: '2 poł. XVIII w.', 'XVII w., l. 20'
78 circa 'ok. 1813-1814', 'ok.1876-ok.1886
80 for now we will translate this to some single date losing information of course.
83 # check out the "N. poł X w." syntax
84 if isinstance(text, str): text = text.decode("utf-8")
86 century_format = u"(?:([12]) *poł[.]? +)?([MCDXVI]+) *w[.,]*(?: *l[.]? *([0-9]+))?"
87 vague_format = u"(?:po *|ok. *)?([0-9]{4})(-[0-9]{2}-[0-9]{2})?"
89 m = re.match(century_format, text)
90 m2 = re.match(vague_format, text)
94 century = roman_to_int(str(m.group(2)))
96 if decade is not None:
97 raise ValueError("Bad date format. Cannot specify both half and decade of century")
99 t = ((century*100 + (half-1)*50), 1, 1)
101 decade = int(decade or 0)
102 t = ((century*100 + decade), 1, 1)
105 mon_day = m2.group(2)
107 t = time.strptime(year + mon_day, "%Y-%m-%d")
109 t = time.strptime(year, '%Y')
113 return DatePlus(t[0], t[1], t[2])
114 except ValueError, e:
115 raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
118 return Person.from_text(text)
120 def as_unicode(text):
121 if isinstance(text, unicode):
124 return TextPlus(text.decode('utf-8'))
126 def as_wluri_strict(text):
127 return WLURI.strict(text)
130 def __init__(self, uri, attr_name, validator=as_unicode, strict=None, multiple=False, salias=None, **kwargs):
132 self.name = attr_name
133 self.validator = validator
135 self.multiple = multiple
138 self.required = kwargs.get('required', True) and not kwargs.has_key('default')
139 self.default = kwargs.get('default', [] if multiple else [None])
141 def validate_value(self, val, strict=False):
142 if strict and self.strict is not None:
143 validator = self.strict
145 validator = self.validator
148 if validator is None:
155 if hasattr(v, 'lang'):
156 setattr(nv, 'lang', v.lang)
157 new_values.append(nv)
160 raise ValidationError("Multiple values not allowed for field '%s'" % self.uri)
162 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
164 if validator is None or val[0] is None:
166 nv = validator(val[0])
167 if hasattr(val[0], 'lang'):
168 setattr(nv, 'lang', val[0].lang)
170 except ValueError, e:
171 raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
173 def validate(self, fdict, fallbacks=None, strict=False):
174 if fallbacks is None:
176 if not fdict.has_key(self.uri):
177 if not self.required:
178 # Accept single value for single fields and saliases.
179 if self.name in fallbacks:
181 f = fallbacks[self.name]
183 f = [fallbacks[self.name]]
184 elif self.salias and self.salias in fallbacks:
185 f = [fallbacks[self.salias]]
189 raise ValidationError("Required field %s not found" % self.uri)
193 return self.validate_value(f, strict=strict)
195 def __eq__(self, other):
196 if isinstance(other, Field) and other.name == self.name:
202 def __new__(meta, classname, bases, class_dict):
203 fields = list(class_dict['FIELDS'])
205 for base in bases[::-1]:
206 if hasattr(base, 'FIELDS'):
207 for field in base.FIELDS[::-1]:
211 fields.insert(0, field)
213 class_dict['FIELDS'] = tuple(fields)
214 return super(DCInfo, meta).__new__(meta, classname, bases, class_dict)
217 class WorkInfo(object):
218 __metaclass__ = DCInfo
221 Field( DCNS('creator'), 'authors', as_person, salias='author', multiple=True),
222 Field( DCNS('title'), 'title'),
223 Field( DCNS('type'), 'type', required=False, multiple=True),
225 Field( DCNS('contributor.editor'), 'editors', \
226 as_person, salias='editor', multiple=True, default=[]),
227 Field( DCNS('contributor.technical_editor'), 'technical_editors',
228 as_person, salias='technical_editor', multiple=True, default=[]),
229 Field( DCNS('contributor.funding'), 'funders',
230 salias='funder', multiple=True, default=[]),
231 Field( DCNS('contributor.thanks'), 'thanks', required=False),
233 Field( DCNS('date'), 'created_at', as_date),
234 Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
235 Field( DCNS('publisher'), 'publisher'),
237 Field( DCNS('language'), 'language'),
238 Field( DCNS('description'), 'description', required=False),
240 Field( DCNS('source'), 'source_name', required=False),
241 Field( DCNS('source.URL'), 'source_url', required=False),
242 Field( DCNS('identifier.url'), 'url', WLURI, strict=as_wluri_strict),
243 Field( DCNS('rights.license'), 'license', required=False),
244 Field( DCNS('rights'), 'license_description'),
246 Field( PLMETNS('digitisationSponsor'), 'sponsors', multiple=True, default=[]),
247 Field( WLNS('digitisationSponsorNote'), 'sponsor_note', required=False),
251 def from_string(cls, xml, *args, **kwargs):
252 from StringIO import StringIO
253 return cls.from_file(StringIO(xml), *args, **kwargs)
256 def from_file(cls, xmlfile, *args, **kwargs):
259 iter = etree.iterparse(xmlfile, ['start', 'end'])
260 for (event, element) in iter:
261 if element.tag == RDFNS('RDF') and event == 'start':
266 raise NoDublinCore("DublinCore section not found. \
267 Check if there are rdf:RDF and rdf:Description tags.")
269 # continue 'till the end of RDF section
270 for (event, element) in iter:
271 if element.tag == RDFNS('RDF') and event == 'end':
274 # if there is no end, Expat should yell at us with an ExpatError
276 # extract data from the element and make the info
277 return cls.from_element(desc_tag, *args, **kwargs)
278 except XMLSyntaxError, e:
280 except ExpatError, e:
284 def from_element(cls, rdf_tag, *args, **kwargs):
285 # the tree is already parsed, so we don't need to worry about Expat errors
287 desc = rdf_tag.find(".//" + RDFNS('Description'))
290 raise NoDublinCore("No DublinCore section found.")
294 while p is not None and lang is None:
295 lang = p.attrib.get(XMLNS('lang'))
298 for e in desc.getchildren():
299 fv = field_dict.get(e.tag, [])
300 if e.text is not None:
302 if not isinstance(text, unicode):
303 text = text.decode('utf-8')
305 val.lang = e.attrib.get(XMLNS('lang'), lang)
309 field_dict[e.tag] = fv
311 return cls(desc.attrib, field_dict, *args, **kwargs)
313 def __init__(self, rdf_attrs, dc_fields, fallbacks=None, strict=False):
314 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
315 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
318 self.about = rdf_attrs.get(RDFNS('about'))
321 for field in self.FIELDS:
322 value = field.validate(dc_fields, fallbacks=fallbacks,
324 setattr(self, 'prop_' + field.name, value)
325 self.fmap[field.name] = field
326 if field.salias: self.fmap[field.salias] = field
328 def __getattribute__(self, name):
330 field = object.__getattribute__(self, 'fmap')[name]
331 value = object.__getattribute__(self, 'prop_'+field.name)
332 if field.name == name:
334 else: # singular alias
335 if not field.multiple:
336 raise "OUCH!! for field %s" % name
338 return value[0] if value else None
339 except (KeyError, AttributeError):
340 return object.__getattribute__(self, name)
342 def __setattr__(self, name, newvalue):
344 field = object.__getattribute__(self, 'fmap')[name]
345 if field.name == name:
346 object.__setattr__(self, 'prop_'+field.name, newvalue)
347 else: # singular alias
348 if not field.multiple:
349 raise "OUCH! while setting field %s" % name
351 object.__setattr__(self, 'prop_'+field.name, [newvalue])
352 except (KeyError, AttributeError):
353 return object.__setattr__(self, name, newvalue)
355 def update(self, field_dict):
356 """Update using field_dict. Verify correctness, but don't check if all
357 required fields are present."""
358 for field in self.FIELDS:
359 if field_dict.has_key(field.name):
360 setattr(self, field.name, field_dict[field.name])
362 def to_etree(self, parent = None):
363 """XML representation of this object."""
364 #etree._namespace_map[str(self.RDF)] = 'rdf'
365 #etree._namespace_map[str(self.DC)] = 'dc'
368 root = etree.Element(RDFNS('RDF'))
370 root = parent.makeelement(RDFNS('RDF'))
372 description = etree.SubElement(root, RDFNS('Description'))
375 description.set(RDFNS('about'), self.about)
377 for field in self.FIELDS:
378 v = getattr(self, field.name, None)
381 if len(v) == 0: continue
383 e = etree.Element(field.uri)
386 description.append(e)
388 e = etree.Element(field.uri)
390 description.append(e)
396 rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
399 for field in self.FIELDS:
400 v = getattr(self, field.name, None)
403 if len(v) == 0: continue
404 v = [ unicode(x) for x in v if x is not None ]
408 dc[field.name] = {'uri': field.uri, 'value': v}
413 result = {'about': self.about}
414 for field in self.FIELDS:
415 v = getattr(self, field.name, None)
419 if len(v) == 0: continue
420 v = [ unicode(x) for x in v if x is not None ]
423 result[field.name] = v
426 v = getattr(self, field.salias)
427 if v is not None: result[field.salias] = unicode(v)
432 class BookInfo(WorkInfo):
434 Field( DCNS('audience'), 'audiences', salias='audience', multiple=True,
437 Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True,
439 Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True,
441 Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True,
444 Field( DCNS('contributor.translator'), 'translators', \
445 as_person, salias='translator', multiple=True, default=[]),
446 Field( DCNS('relation.hasPart'), 'parts',
447 WLURI, strict=as_wluri_strict, multiple=True, required=False),
448 Field( DCNS('relation.isVariantOf'), 'variant_of',
449 WLURI, strict=as_wluri_strict, required=False),
451 Field( DCNS('relation.coverImage.url'), 'cover_url', required=False),
452 Field( DCNS('relation.coverImage.attribution'), 'cover_by', required=False),
453 Field( DCNS('relation.coverImage.source'), 'cover_source', required=False),
455 Field( WLNS('coverBarColor'), 'cover_bar_color', required=False),
456 Field( WLNS('coverBoxPosition'), 'cover_box_position', required=False),
460 def parse(file_name, cls=BookInfo):
461 return cls.from_file(file_name)