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,
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'),
248 def from_string(cls, xml, *args, **kwargs):
249 from StringIO import StringIO
250 return cls.from_file(StringIO(xml), *args, **kwargs)
253 def from_file(cls, xmlfile, *args, **kwargs):
256 iter = etree.iterparse(xmlfile, ['start', 'end'])
257 for (event, element) in iter:
258 if element.tag == RDFNS('RDF') and event == 'start':
263 raise NoDublinCore("DublinCore section not found. \
264 Check if there are rdf:RDF and rdf:Description tags.")
266 # continue 'till the end of RDF section
267 for (event, element) in iter:
268 if element.tag == RDFNS('RDF') and event == 'end':
271 # if there is no end, Expat should yell at us with an ExpatError
273 # extract data from the element and make the info
274 return cls.from_element(desc_tag, *args, **kwargs)
275 except XMLSyntaxError, e:
277 except ExpatError, e:
281 def from_element(cls, rdf_tag, *args, **kwargs):
282 # the tree is already parsed, so we don't need to worry about Expat errors
284 desc = rdf_tag.find(".//" + RDFNS('Description'))
287 raise NoDublinCore("No DublinCore section found.")
291 while p is not None and lang is None:
292 lang = p.attrib.get(XMLNS('lang'))
295 for e in desc.getchildren():
296 fv = field_dict.get(e.tag, [])
297 if e.text is not None:
299 if not isinstance(text, unicode):
300 text = text.decode('utf-8')
302 val.lang = e.attrib.get(XMLNS('lang'), lang)
306 field_dict[e.tag] = fv
308 return cls(desc.attrib, field_dict, *args, **kwargs)
310 def __init__(self, rdf_attrs, dc_fields, fallbacks=None, strict=False):
311 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
312 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
315 self.about = rdf_attrs.get(RDFNS('about'))
318 for field in self.FIELDS:
319 value = field.validate(dc_fields, fallbacks=fallbacks,
321 setattr(self, 'prop_' + field.name, value)
322 self.fmap[field.name] = field
323 if field.salias: self.fmap[field.salias] = field
325 def __getattribute__(self, name):
327 field = object.__getattribute__(self, 'fmap')[name]
328 value = object.__getattribute__(self, 'prop_'+field.name)
329 if field.name == name:
331 else: # singular alias
332 if not field.multiple:
333 raise "OUCH!! for field %s" % name
335 return value[0] if value else None
336 except (KeyError, AttributeError):
337 return object.__getattribute__(self, name)
339 def __setattr__(self, name, newvalue):
341 field = object.__getattribute__(self, 'fmap')[name]
342 if field.name == name:
343 object.__setattr__(self, 'prop_'+field.name, newvalue)
344 else: # singular alias
345 if not field.multiple:
346 raise "OUCH! while setting field %s" % name
348 object.__setattr__(self, 'prop_'+field.name, [newvalue])
349 except (KeyError, AttributeError):
350 return object.__setattr__(self, name, newvalue)
352 def update(self, field_dict):
353 """Update using field_dict. Verify correctness, but don't check if all
354 required fields are present."""
355 for field in self.FIELDS:
356 if field_dict.has_key(field.name):
357 setattr(self, field.name, field_dict[field.name])
359 def to_etree(self, parent = None):
360 """XML representation of this object."""
361 #etree._namespace_map[str(self.RDF)] = 'rdf'
362 #etree._namespace_map[str(self.DC)] = 'dc'
365 root = etree.Element(RDFNS('RDF'))
367 root = parent.makeelement(RDFNS('RDF'))
369 description = etree.SubElement(root, RDFNS('Description'))
372 description.set(RDFNS('about'), self.about)
374 for field in self.FIELDS:
375 v = getattr(self, field.name, None)
378 if len(v) == 0: continue
380 e = etree.Element(field.uri)
383 description.append(e)
385 e = etree.Element(field.uri)
387 description.append(e)
393 rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
396 for field in self.FIELDS:
397 v = getattr(self, field.name, None)
400 if len(v) == 0: continue
401 v = [ unicode(x) for x in v if x is not None ]
405 dc[field.name] = {'uri': field.uri, 'value': v}
410 result = {'about': self.about}
411 for field in self.FIELDS:
412 v = getattr(self, field.name, None)
416 if len(v) == 0: continue
417 v = [ unicode(x) for x in v if x is not None ]
420 result[field.name] = v
423 v = getattr(self, field.salias)
424 if v is not None: result[field.salias] = unicode(v)
429 class BookInfo(WorkInfo):
431 Field( DCNS('audience'), 'audiences', salias='audience', multiple=True,
434 Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True,
436 Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True,
438 Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True,
441 Field( DCNS('contributor.translator'), 'translators', \
442 as_person, salias='translator', multiple=True, default=[]),
443 Field( DCNS('relation.hasPart'), 'parts',
444 WLURI, strict=as_wluri_strict, multiple=True, required=False),
445 Field( DCNS('relation.isVariantOf'), 'variant_of',
446 WLURI, strict=as_wluri_strict, required=False),
448 Field( DCNS('relation.coverImage.url'), 'cover_url', required=False),
449 Field( DCNS('relation.coverImage.attribution'), 'cover_by', required=False),
450 Field( DCNS('relation.coverImage.source'), 'cover_source', required=False),
454 def parse(file_name, cls=BookInfo):
455 return cls.from_file(file_name)