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
23 """Single person with last name and a list of first names."""
24 def __init__(self, last_name, *first_names):
25 self.last_name = last_name
26 self.first_names = first_names
29 def from_text(cls, text):
30 parts = [ token.strip() for token in text.split(',') ]
35 raise ValueError("Invalid person name. There should be at most one comma: \"%s\"." % text)
38 if len(parts[1]) == 0:
39 # there is no non-whitespace data after the comma
40 raise ValueError("Found a comma, but no names given: \"%s\" -> %r." % (text, parts))
41 names = [ name for name in parts[1].split() if len(name) ] # all non-whitespace tokens
42 return cls(surname, *names)
45 return u" ".join(self.first_names + (self.last_name,))
47 def __eq__(self, right):
48 return self.last_name == right.last_name and self.first_names == right.first_names
50 def __cmp__(self, other):
51 return cmp((self.last_name, self.first_names), (other.last_name, other.first_names))
54 return hash((self.last_name, self.first_names))
56 def __unicode__(self):
57 if len(self.first_names) > 0:
58 return '%s, %s' % (self.last_name, ' '.join(self.first_names))
63 return 'Person(last_name=%r, first_names=*%r)' % (self.last_name, self.first_names)
66 """Dates for digitization of pictures. It seems we need the following:
69 half centuries/decades: '2 poł. XVIII w.', 'XVII w., l. 20'
71 circa 'ok. 1813-1814', 'ok.1876-ok.1886
73 for now we will translate this to some single date losing information of course.
76 # check out the "N. poł X w." syntax
77 if isinstance(text, str): text = text.decode("utf-8")
78 century_format = u"(?:([12]) *poł[.]? +)?([MCDXVI]+) *w[.,]*(?: *l[.]? *([0-9]+))?"
79 vague_format = u"(?:po *|ok. *)?([0-9]{4})(-[0-9]{2}-[0-9]{2})?"
81 m = re.match(century_format, text)
82 m2 = re.match(vague_format, text)
86 century = roman_to_int(str(m.group(2)))
88 if decade is not None:
89 raise ValueError("Bad date format. Cannot specify both half and decade of century")
91 t = ((century*100 + (half-1)*50), 1, 1)
93 decade = int(decade or 0)
94 t = ((century*100 + decade), 1, 1)
99 t = time.strptime(year + mon_day, "%Y-%m-%d")
101 t = time.strptime(year, '%Y')
105 return date(t[0], t[1], t[2])
106 except ValueError, e:
107 raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
110 return Person.from_text(text)
112 def as_unicode(text):
113 if isinstance(text, unicode):
116 return text.decode('utf-8')
118 def as_wluri_strict(text):
119 return WLURI.strict(text)
122 def __init__(self, uri, attr_name, validator=as_unicode, strict=None, multiple=False, salias=None, **kwargs):
124 self.name = attr_name
125 self.validator = validator
127 self.multiple = multiple
130 self.required = kwargs.get('required', True) and not kwargs.has_key('default')
131 self.default = kwargs.get('default', [] if multiple else [None])
133 def validate_value(self, val, strict=False):
134 if strict and self.strict is not None:
135 validator = self.strict
137 validator = self.validator
140 if validator is None:
142 return [ validator(v) if v is not None else v for v in val ]
144 raise ValidationError("Multiple values not allowed for field '%s'" % self.uri)
146 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
148 if validator is None or val[0] is None:
150 return validator(val[0])
151 except ValueError, e:
152 raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
154 def validate(self, fdict, fallbacks=None, strict=False):
155 if fallbacks is None:
157 if not fdict.has_key(self.uri):
158 if not self.required:
159 # Accept single value for single fields and saliases.
160 if self.name in fallbacks:
162 f = fallbacks[self.name]
164 f = [fallbacks[self.name]]
165 elif self.salias and self.salias in fallbacks:
166 f = [fallbacks[self.salias]]
170 raise ValidationError("Required field %s not found" % self.uri)
174 return self.validate_value(f, strict=strict)
176 def __eq__(self, other):
177 if isinstance(other, Field) and other.name == self.name:
183 def __new__(meta, classname, bases, class_dict):
184 fields = list(class_dict['FIELDS'])
186 for base in bases[::-1]:
187 if hasattr(base, 'FIELDS'):
188 for field in base.FIELDS[::-1]:
192 fields.insert(0, field)
194 class_dict['FIELDS'] = tuple(fields)
195 return super(DCInfo, meta).__new__(meta, classname, bases, class_dict)
198 class WorkInfo(object):
199 __metaclass__ = DCInfo
202 Field( DCNS('creator'), 'authors', as_person, salias='author', multiple=True),
203 Field( DCNS('title'), 'title'),
204 Field( DCNS('type'), 'type', required=False, multiple=True),
206 Field( DCNS('contributor.editor'), 'editors', \
207 as_person, salias='editor', multiple=True, default=[]),
208 Field( DCNS('contributor.technical_editor'), 'technical_editors',
209 as_person, salias='technical_editor', multiple=True, default=[]),
210 Field( DCNS('contributor.funding'), 'funders',
211 salias='funder', multiple=True, default=[]),
212 Field( DCNS('contributor.thanks'), 'thanks', required=False),
214 Field( DCNS('date'), 'created_at', as_date),
215 Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
216 Field( DCNS('publisher'), 'publisher'),
218 Field( DCNS('language'), 'language'),
219 Field( DCNS('description'), 'description', required=False),
221 Field( DCNS('source'), 'source_name', required=False),
222 Field( DCNS('source.URL'), 'source_url', required=False),
223 Field( DCNS('identifier.url'), 'url', WLURI, strict=as_wluri_strict),
224 Field( DCNS('rights.license'), 'license', required=False),
225 Field( DCNS('rights'), 'license_description'),
229 def from_string(cls, xml, *args, **kwargs):
230 from StringIO import StringIO
231 return cls.from_file(StringIO(xml), *args, **kwargs)
234 def from_file(cls, xmlfile, *args, **kwargs):
237 iter = etree.iterparse(xmlfile, ['start', 'end'])
238 for (event, element) in iter:
239 if element.tag == RDFNS('RDF') and event == 'start':
244 raise NoDublinCore("DublinCore section not found. \
245 Check if there are rdf:RDF and rdf:Description tags.")
247 # continue 'till the end of RDF section
248 for (event, element) in iter:
249 if element.tag == RDFNS('RDF') and event == 'end':
252 # if there is no end, Expat should yell at us with an ExpatError
254 # extract data from the element and make the info
255 return cls.from_element(desc_tag, *args, **kwargs)
256 except XMLSyntaxError, e:
258 except ExpatError, e:
262 def from_element(cls, rdf_tag, *args, **kwargs):
263 # the tree is already parsed, so we don't need to worry about Expat errors
265 desc = rdf_tag.find(".//" + RDFNS('Description'))
268 raise NoDublinCore("No DublinCore section found.")
270 for e in desc.getchildren():
271 fv = field_dict.get(e.tag, [])
273 field_dict[e.tag] = fv
275 return cls(desc.attrib, field_dict, *args, **kwargs)
277 def __init__(self, rdf_attrs, dc_fields, fallbacks=None, strict=False):
278 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
279 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
282 self.about = rdf_attrs.get(RDFNS('about'))
285 for field in self.FIELDS:
286 value = field.validate(dc_fields, fallbacks=fallbacks,
288 setattr(self, 'prop_' + field.name, value)
289 self.fmap[field.name] = field
290 if field.salias: self.fmap[field.salias] = field
292 def __getattribute__(self, name):
294 field = object.__getattribute__(self, 'fmap')[name]
295 value = object.__getattribute__(self, 'prop_'+field.name)
296 if field.name == name:
298 else: # singular alias
299 if not field.multiple:
300 raise "OUCH!! for field %s" % name
302 return value[0] if value else None
303 except (KeyError, AttributeError):
304 return object.__getattribute__(self, name)
306 def __setattr__(self, name, newvalue):
308 field = object.__getattribute__(self, 'fmap')[name]
309 if field.name == name:
310 object.__setattr__(self, 'prop_'+field.name, newvalue)
311 else: # singular alias
312 if not field.multiple:
313 raise "OUCH! while setting field %s" % name
315 object.__setattr__(self, 'prop_'+field.name, [newvalue])
316 except (KeyError, AttributeError):
317 return object.__setattr__(self, name, newvalue)
319 def update(self, field_dict):
320 """Update using field_dict. Verify correctness, but don't check if all
321 required fields are present."""
322 for field in self.FIELDS:
323 if field_dict.has_key(field.name):
324 setattr(self, field.name, field_dict[field.name])
326 def to_etree(self, parent = None):
327 """XML representation of this object."""
328 #etree._namespace_map[str(self.RDF)] = 'rdf'
329 #etree._namespace_map[str(self.DC)] = 'dc'
332 root = etree.Element(RDFNS('RDF'))
334 root = parent.makeelement(RDFNS('RDF'))
336 description = etree.SubElement(root, RDFNS('Description'))
339 description.set(RDFNS('about'), self.about)
341 for field in self.FIELDS:
342 v = getattr(self, field.name, None)
345 if len(v) == 0: continue
347 e = etree.Element(field.uri)
350 description.append(e)
352 e = etree.Element(field.uri)
354 description.append(e)
360 rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
363 for field in self.FIELDS:
364 v = getattr(self, field.name, None)
367 if len(v) == 0: continue
368 v = [ unicode(x) for x in v if x is not None ]
372 dc[field.name] = {'uri': field.uri, 'value': v}
377 result = {'about': self.about}
378 for field in self.FIELDS:
379 v = getattr(self, field.name, None)
383 if len(v) == 0: continue
384 v = [ unicode(x) for x in v if x is not None ]
387 result[field.name] = v
390 v = getattr(self, field.salias)
391 if v is not None: result[field.salias] = unicode(v)
396 class BookInfo(WorkInfo):
398 Field( DCNS('audience'), 'audiences', salias='audience', multiple=True,
401 Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True,
403 Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True,
405 Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True,
408 Field( DCNS('contributor.translator'), 'translators', \
409 as_person, salias='translator', multiple=True, default=[]),
410 Field( DCNS('relation.hasPart'), 'parts',
411 WLURI, strict=as_wluri_strict, multiple=True, required=False),
412 Field( DCNS('relation.isVariantOf'), 'variant_of',
413 WLURI, strict=as_wluri_strict, required=False),
415 Field( DCNS('relation.coverImage.url'), 'cover_url', required=False),
416 Field( DCNS('relation.coverImage.attribution'), 'cover_by', required=False),
417 Field( DCNS('relation.coverImage.source'), 'cover_source', required=False),
421 def parse(file_name, cls=BookInfo):
422 return cls.from_file(file_name)