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)
67 t = time.strptime(text, '%Y-%m-%d')
69 t = time.strptime(text, '%Y')
70 return date(t[0], t[1], t[2])
72 raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
76 return Person.from_text(text)
80 if isinstance(text, unicode):
83 return text.decode('utf-8')
86 def as_wluri_strict(text):
87 return WLURI.strict(text)
91 def __init__(self, uri, attr_name, validator=as_unicode, strict=None, multiple=False, salias=None, **kwargs):
94 self.validator = validator
96 self.multiple = multiple
99 self.required = kwargs.get('required', True) and 'default' not in kwargs
100 self.default = kwargs.get('default', [] if multiple else [None])
102 def validate_value(self, val, strict=False):
103 val = [v.strip() if v is not None else v for v in val]
104 if strict and self.strict is not None:
105 validator = self.strict
107 validator = self.validator
110 if validator is None:
112 return [validator(v) if v is not None else v for v in val]
114 raise ValidationError("Multiple values not allowed for field '%s'" % self.uri)
116 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
118 if validator is None or val[0] is None:
120 return validator(val[0])
121 except ValueError, e:
122 raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
124 def validate(self, fdict, fallbacks=None, strict=False):
125 if fallbacks is None:
127 if self.uri not in fdict:
128 if not self.required:
129 # Accept single value for single fields and saliases.
130 if self.name in fallbacks:
132 f = fallbacks[self.name]
134 f = [fallbacks[self.name]]
135 elif self.salias and self.salias in fallbacks:
136 f = [fallbacks[self.salias]]
140 raise ValidationError("Required field %s not found" % self.uri)
144 return self.validate_value(f, strict=strict)
146 def __eq__(self, other):
147 if isinstance(other, Field) and other.name == self.name and other.uri == self.uri:
153 def __new__(mcs, classname, bases, class_dict):
154 fields = list(class_dict['FIELDS'])
156 for base in bases[::-1]:
157 if hasattr(base, 'FIELDS'):
158 for field in base.FIELDS[::-1]:
162 fields.insert(0, field)
164 class_dict['FIELDS'] = tuple(fields)
165 return super(DCInfo, mcs).__new__(mcs, classname, bases, class_dict)
168 class WorkInfo(object):
169 __metaclass__ = DCInfo
172 Field(DCNS('creator.expert'), 'authors_expert', as_person, salias='author', required=False, multiple=True),
173 Field(DCNS('creator.methodologist'), 'authors_methodologist', as_person, salias='author', required=False,
175 Field(DCNS('creator.scenario'), 'authors_scenario', as_person, salias='author', required=False, multiple=True),
176 Field(DCNS('creator.textbook'), 'authors_textbook', as_person, salias='author', required=False, multiple=True),
177 Field(DCNS('requires'), 'requires', required=False, multiple=True),
178 Field(DCNS('title'), 'title'),
179 Field(DCNS('type'), 'type', required=False),
181 Field(DCNS('contributor.editor'), 'editors', as_person, salias='editor', multiple=True, default=[]),
182 Field(DCNS('contributor.technical_editor'), 'technical_editors', as_person, salias='technical_editor',
183 multiple=True, default=[]),
185 Field(DCNS('date'), 'created_at', as_date),
186 Field(DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
187 Field(DCNS('publisher'), 'publisher'),
189 Field(DCNS('subject.competence'), 'competences', multiple=True, required=False),
190 Field(DCNS('subject.curriculum'), 'curriculum', multiple=True, required=False),
191 Field(DCNS('subject.curriculum.new'), 'curriculum_new', multiple=True, required=False),
193 Field(DCNS('language'), 'language'),
194 Field(DCNS('description'), 'description', required=False),
196 Field(DCNS('source'), 'source_name', required=False),
197 Field(DCNS('source.URL'), 'source_url', required=False),
198 Field(DCNS('identifier.url'), 'url', WLURI, strict=as_wluri_strict),
199 Field(DCNS('rights.license'), 'license', required=False),
200 Field(DCNS('rights'), 'license_description'),
204 def from_string(cls, xml, *args, **kwargs):
205 from StringIO import StringIO
206 return cls.from_file(StringIO(xml), *args, **kwargs)
209 def from_file(cls, xmlfile, *args, **kwargs):
212 elements = etree.iterparse(xmlfile, ['start', 'end'])
213 for (event, element) in elements:
214 if element.tag == RDFNS('RDF') and event == 'start':
219 raise NoDublinCore("DublinCore section not found. \
220 Check if there are rdf:RDF and rdf:Description tags.")
222 # continue 'till the end of RDF section
223 for (event, element) in elements:
224 if element.tag == RDFNS('RDF') and event == 'end':
227 # if there is no end, Expat should yell at us with an ExpatError
229 # extract data from the element and make the info
230 return cls.from_element(desc_tag, *args, **kwargs)
231 except XMLSyntaxError, e:
233 except ExpatError, e:
237 def from_element(cls, rdf_tag, *args, **kwargs):
238 # the tree is already parsed, so we don't need to worry about Expat errors
240 desc = rdf_tag.find(".//" + RDFNS('Description'))
243 raise NoDublinCore("No DublinCore section found.")
245 for e in desc.getchildren():
246 fv = field_dict.get(e.tag, [])
248 field_dict[e.tag] = fv
250 return cls(desc.attrib, field_dict, *args, **kwargs)
252 def __init__(self, rdf_attrs, dc_fields, fallbacks=None, strict=False):
253 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
254 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
257 self.about = rdf_attrs.get(RDFNS('about'))
260 for field in self.FIELDS:
261 value = field.validate(dc_fields, fallbacks=fallbacks, strict=strict)
263 value = getattr(self, 'prop_' + field.name, []) + value
264 setattr(self, 'prop_' + field.name, value)
265 self.fmap[field.name] = field
267 self.fmap[field.salias] = field
269 def __getattribute__(self, name):
271 field = object.__getattribute__(self, 'fmap')[name]
272 value = object.__getattribute__(self, 'prop_'+field.name)
273 if field.name == name:
277 if not field.multiple:
278 raise "OUCH!! for field %s" % name
280 return value[0] if value else None
281 except (KeyError, AttributeError):
282 return object.__getattribute__(self, name)
284 def __setattr__(self, name, newvalue):
286 field = object.__getattribute__(self, 'fmap')[name]
287 if field.name == name:
288 object.__setattr__(self, 'prop_'+field.name, newvalue)
291 if not field.multiple:
292 raise "OUCH! while setting field %s" % name
294 object.__setattr__(self, 'prop_'+field.name, [newvalue])
295 except (KeyError, AttributeError):
296 return object.__setattr__(self, name, newvalue)
298 def update(self, field_dict):
299 """Update using field_dict. Verify correctness, but don't check if all
300 required fields are present."""
301 for field in self.FIELDS:
302 if field.name in field_dict:
303 setattr(self, field.name, field_dict[field.name])
305 def to_etree(self, parent=None):
306 """XML representation of this object."""
307 # etree._namespace_map[str(self.RDF)] = 'rdf'
308 # etree._namespace_map[str(self.DC)] = 'dc'
311 root = etree.Element(RDFNS('RDF'))
313 root = parent.makeelement(RDFNS('RDF'))
315 description = etree.SubElement(root, RDFNS('Description'))
318 description.set(RDFNS('about'), self.about)
320 for field in self.FIELDS:
321 v = getattr(self, field.name, None)
327 e = etree.Element(field.uri)
330 description.append(e)
332 e = etree.Element(field.uri)
334 description.append(e)
339 rdf = {'about': {'uri': RDFNS('about'), 'value': self.about}}
342 for field in self.FIELDS:
343 v = getattr(self, field.name, None)
348 v = [unicode(x) for x in v if x is not None]
352 dc[field.name] = {'uri': field.uri, 'value': v}
357 result = {'about': self.about}
358 for field in self.FIELDS:
359 v = getattr(self, field.name, None)
365 v = [unicode(x) for x in v if x is not None]
368 result[field.name] = v
371 v = getattr(self, field.salias)
373 result[field.salias] = unicode(v)
378 class BookInfo(WorkInfo):
380 Field(DCNS('audience'), 'audiences', salias='audience', multiple=True, required=False),
382 Field(DCNS('subject.period'), 'epochs', salias='epoch', multiple=True, required=False),
383 Field(DCNS('subject.type'), 'kinds', salias='kind', multiple=True, required=False),
384 Field(DCNS('subject.genre'), 'genres', salias='genre', multiple=True, required=False),
386 Field(DCNS('contributor.translator'), 'translators', as_person, salias='translator', multiple=True,
388 Field(DCNS('relation.hasPart'), 'parts', WLURI, strict=as_wluri_strict, multiple=True, required=False),
389 Field(DCNS('relation.isVariantOf'), 'variant_of', WLURI, strict=as_wluri_strict, required=False),
390 Field(DCNS('relation'), 'relations', WLURI, strict=as_wluri_strict, multiple=True, required=False),
392 Field(DCNS('relation.coverImage.url'), 'cover_url', required=False),
393 Field(DCNS('relation.coverImage.attribution'), 'cover_by', required=False),
394 Field(DCNS('relation.coverImage.source'), 'cover_source', required=False),
398 def parse(file_name, cls=BookInfo):
399 return cls.from_file(file_name)