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 import (ValidationError, NoDublinCore, ParseError, DCNS, RDFNS,
13 import lxml.etree as etree # ElementTree API using libxml2
14 from lxml.etree import XMLSyntaxError
21 """Single person with last name and a list of first names."""
22 def __init__(self, last_name, *first_names):
23 self.last_name = last_name
24 self.first_names = first_names
27 def from_text(cls, text):
28 parts = [ token.strip() for token in text.split(',') ]
33 raise ValueError("Invalid person name. There should be at most one comma: \"%s\"." % text)
36 if len(parts[1]) == 0:
37 # there is no non-whitespace data after the comma
38 raise ValueError("Found a comma, but no names given: \"%s\" -> %r." % (text, parts))
39 names = [ name for name in parts[1].split() if len(name) ] # all non-whitespace tokens
40 return cls(surname, *names)
43 return u" ".join(self.first_names + (self.last_name,))
45 def __eq__(self, right):
46 return self.last_name == right.last_name and self.first_names == right.first_names
48 def __cmp__(self, other):
49 return cmp((self.last_name, self.first_names), (other.last_name, other.first_names))
52 return hash((self.last_name, self.first_names))
54 def __unicode__(self):
55 if len(self.first_names) > 0:
56 return '%s, %s' % (self.last_name, ' '.join(self.first_names))
61 return 'Person(last_name=%r, first_names=*%r)' % (self.last_name, self.first_names)
66 t = time.strptime(text, '%Y-%m-%d')
68 t = time.strptime(text, '%Y')
69 return date(t[0], t[1], t[2])
71 raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
74 return Person.from_text(text)
77 if isinstance(text, unicode):
80 return text.decode('utf-8')
82 def as_wluri_strict(text):
83 return WLURI.strict(text)
86 def __init__(self, uri, attr_name, validator=as_unicode, strict=None, multiple=False, salias=None, **kwargs):
89 self.validator = validator
91 self.multiple = multiple
94 self.required = kwargs.get('required', True) and not kwargs.has_key('default')
95 self.default = kwargs.get('default', [] if multiple else [None])
97 def validate_value(self, val, strict=False):
98 if strict and self.strict is not None:
99 validator = self.strict
101 validator = self.validator
104 if validator is None:
106 return [ validator(v) if v is not None else v for v in val ]
108 raise ValidationError("Multiple values not allowed for field '%s'" % self.uri)
110 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
112 if validator is None or val[0] is None:
114 return validator(val[0])
115 except ValueError, e:
116 raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
118 def validate(self, fdict, fallbacks=None, strict=False):
119 if fallbacks is None:
121 if not fdict.has_key(self.uri):
122 if not self.required:
123 # Accept single value for single fields and saliases.
124 if self.name in fallbacks:
126 f = fallbacks[self.name]
128 f = [fallbacks[self.name]]
129 elif self.salias and self.salias in fallbacks:
130 f = [fallbacks[self.salias]]
134 raise ValidationError("Required field %s not found" % self.uri)
138 return self.validate_value(f, strict=strict)
140 def __eq__(self, other):
141 if isinstance(other, Field) and other.name == self.name:
147 def __new__(meta, classname, bases, class_dict):
148 fields = list(class_dict['FIELDS'])
150 for base in bases[::-1]:
151 if hasattr(base, 'FIELDS'):
152 for field in base.FIELDS[::-1]:
156 fields.insert(0, field)
158 class_dict['FIELDS'] = tuple(fields)
159 return super(DCInfo, meta).__new__(meta, classname, bases, class_dict)
162 class WorkInfo(object):
163 __metaclass__ = DCInfo
166 Field( DCNS('creator'), 'authors', as_person, salias='author', multiple=True),
167 Field( DCNS('title'), 'title'),
168 Field( DCNS('type'), 'type', required=False, multiple=True),
170 Field( DCNS('contributor.editor'), 'editors', \
171 as_person, salias='editor', multiple=True, default=[]),
172 Field( DCNS('contributor.technical_editor'), 'technical_editors',
173 as_person, salias='technical_editor', multiple=True, default=[]),
175 Field( DCNS('date'), 'created_at', as_date),
176 Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
177 Field( DCNS('publisher'), 'publisher'),
179 Field( DCNS('language'), 'language'),
180 Field( DCNS('description'), 'description', required=False),
182 Field( DCNS('source'), 'source_name', required=False),
183 Field( DCNS('source.URL'), 'source_url', required=False),
184 Field( DCNS('identifier.url'), 'url', WLURI, strict=as_wluri_strict),
185 Field( DCNS('rights.license'), 'license', required=False),
186 Field( DCNS('rights'), 'license_description'),
190 def from_string(cls, xml, *args, **kwargs):
191 from StringIO import StringIO
192 return cls.from_file(StringIO(xml), *args, **kwargs)
195 def from_file(cls, xmlfile, *args, **kwargs):
198 iter = etree.iterparse(xmlfile, ['start', 'end'])
199 for (event, element) in iter:
200 if element.tag == RDFNS('RDF') and event == 'start':
205 raise NoDublinCore("DublinCore section not found. \
206 Check if there are rdf:RDF and rdf:Description tags.")
208 # continue 'till the end of RDF section
209 for (event, element) in iter:
210 if element.tag == RDFNS('RDF') and event == 'end':
213 # if there is no end, Expat should yell at us with an ExpatError
215 # extract data from the element and make the info
216 return cls.from_element(desc_tag, *args, **kwargs)
217 except XMLSyntaxError, e:
219 except ExpatError, e:
223 def from_element(cls, rdf_tag, *args, **kwargs):
224 # the tree is already parsed, so we don't need to worry about Expat errors
226 desc = rdf_tag.find(".//" + RDFNS('Description'))
229 raise NoDublinCore("No DublinCore section found.")
231 for e in desc.getchildren():
232 fv = field_dict.get(e.tag, [])
234 field_dict[e.tag] = fv
236 return cls(desc.attrib, field_dict, *args, **kwargs)
238 def __init__(self, rdf_attrs, dc_fields, fallbacks=None, strict=False):
239 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
240 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
243 self.about = rdf_attrs.get(RDFNS('about'))
246 for field in self.FIELDS:
247 value = field.validate(dc_fields, fallbacks=fallbacks,
249 setattr(self, 'prop_' + field.name, value)
250 self.fmap[field.name] = field
251 if field.salias: self.fmap[field.salias] = field
253 def __getattribute__(self, name):
255 field = object.__getattribute__(self, 'fmap')[name]
256 value = object.__getattribute__(self, 'prop_'+field.name)
257 if field.name == name:
259 else: # singular alias
260 if not field.multiple:
261 raise "OUCH!! for field %s" % name
263 return value[0] if value else None
264 except (KeyError, AttributeError):
265 return object.__getattribute__(self, name)
267 def __setattr__(self, name, newvalue):
269 field = object.__getattribute__(self, 'fmap')[name]
270 if field.name == name:
271 object.__setattr__(self, 'prop_'+field.name, newvalue)
272 else: # singular alias
273 if not field.multiple:
274 raise "OUCH! while setting field %s" % name
276 object.__setattr__(self, 'prop_'+field.name, [newvalue])
277 except (KeyError, AttributeError):
278 return object.__setattr__(self, name, newvalue)
280 def update(self, field_dict):
281 """Update using field_dict. Verify correctness, but don't check if all
282 required fields are present."""
283 for field in self.FIELDS:
284 if field_dict.has_key(field.name):
285 setattr(self, field.name, field_dict[field.name])
287 def to_etree(self, parent = None):
288 """XML representation of this object."""
289 #etree._namespace_map[str(self.RDF)] = 'rdf'
290 #etree._namespace_map[str(self.DC)] = 'dc'
293 root = etree.Element(RDFNS('RDF'))
295 root = parent.makeelement(RDFNS('RDF'))
297 description = etree.SubElement(root, RDFNS('Description'))
300 description.set(RDFNS('about'), self.about)
302 for field in self.FIELDS:
303 v = getattr(self, field.name, None)
306 if len(v) == 0: continue
308 e = etree.Element(field.uri)
311 description.append(e)
313 e = etree.Element(field.uri)
315 description.append(e)
321 rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
324 for field in self.FIELDS:
325 v = getattr(self, field.name, None)
328 if len(v) == 0: continue
329 v = [ unicode(x) for x in v if x is not None ]
333 dc[field.name] = {'uri': field.uri, 'value': v}
338 result = {'about': self.about}
339 for field in self.FIELDS:
340 v = getattr(self, field.name, None)
344 if len(v) == 0: continue
345 v = [ unicode(x) for x in v if x is not None ]
348 result[field.name] = v
351 v = getattr(self, field.salias)
352 if v is not None: result[field.salias] = unicode(v)
357 class BookInfo(WorkInfo):
359 Field( DCNS('audience'), 'audiences', salias='audience', multiple=True,
362 Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True,
364 Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True,
366 Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True,
369 Field( DCNS('contributor.translator'), 'translators', \
370 as_person, salias='translator', multiple=True, default=[]),
371 Field( DCNS('relation.hasPart'), 'parts',
372 WLURI, strict=as_wluri_strict, multiple=True, required=False),
373 Field( DCNS('relation.isVariantOf'), 'variant_of',
374 WLURI, strict=as_wluri_strict, required=False),
376 Field( DCNS('relation.coverImage.url'), 'cover_url', required=False),
377 Field( DCNS('relation.coverImage.attribution'), 'cover_by', required=False),
378 Field( DCNS('relation.coverImage.source'), 'cover_source', required=False),
382 def parse(file_name, cls=BookInfo):
383 return cls.from_file(file_name)