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 val = [v.strip() if v is not None else v for v in val]
99 if strict and self.strict is not None:
100 validator = self.strict
102 validator = self.validator
105 if validator is None:
107 return [ validator(v) if v is not None else v for v in val ]
109 raise ValidationError("Multiple values not allowed for field '%s'" % self.uri)
111 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
113 if validator is None or val[0] is None:
115 return validator(val[0])
116 except ValueError, e:
117 raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
119 def validate(self, fdict, fallbacks=None, strict=False):
120 if fallbacks is None:
122 if not fdict.has_key(self.uri):
123 if not self.required:
124 # Accept single value for single fields and saliases.
125 if self.name in fallbacks:
127 f = fallbacks[self.name]
129 f = [fallbacks[self.name]]
130 elif self.salias and self.salias in fallbacks:
131 f = [fallbacks[self.salias]]
135 raise ValidationError("Required field %s not found" % self.uri)
139 return self.validate_value(f, strict=strict)
141 def __eq__(self, other):
142 if isinstance(other, Field) and other.name == self.name:
148 def __new__(meta, classname, bases, class_dict):
149 fields = list(class_dict['FIELDS'])
151 for base in bases[::-1]:
152 if hasattr(base, 'FIELDS'):
153 for field in base.FIELDS[::-1]:
157 fields.insert(0, field)
159 class_dict['FIELDS'] = tuple(fields)
160 return super(DCInfo, meta).__new__(meta, classname, bases, class_dict)
163 class WorkInfo(object):
164 __metaclass__ = DCInfo
167 Field( DCNS('creator.expert'), 'authors', as_person, salias='author', multiple=True),
168 Field( DCNS('creator.scenario'), 'authors', as_person, salias='author', multiple=True),
169 Field( DCNS('creator.textbook'), 'authors', as_person, salias='author', multiple=True),
170 Field( DCNS('title'), 'title'),
171 Field( DCNS('type'), 'type', required=False, multiple=True),
173 Field( DCNS('contributor.editor'), 'editors', \
174 as_person, salias='editor', multiple=True, default=[]),
175 Field( DCNS('contributor.technical_editor'), 'technical_editors',
176 as_person, salias='technical_editor', multiple=True, default=[]),
178 Field( DCNS('date'), 'created_at', as_date),
179 Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
180 Field( DCNS('publisher'), 'publisher'),
182 Field( DCNS('subject.competence'), 'competences', multiple=True, required=False),
183 Field( DCNS('subject.curriculum'), 'curriculum', multiple=True, required=False),
185 Field( DCNS('language'), 'language'),
186 Field( DCNS('description'), 'description', required=False),
188 Field( DCNS('source'), 'source_name', required=False),
189 Field( DCNS('source.URL'), 'source_url', required=False),
190 Field( DCNS('identifier.url'), 'url', WLURI, strict=as_wluri_strict),
191 Field( DCNS('rights.license'), 'license', required=False),
192 Field( DCNS('rights'), 'license_description'),
196 def from_string(cls, xml, *args, **kwargs):
197 from StringIO import StringIO
198 return cls.from_file(StringIO(xml), *args, **kwargs)
201 def from_file(cls, xmlfile, *args, **kwargs):
204 iter = etree.iterparse(xmlfile, ['start', 'end'])
205 for (event, element) in iter:
206 if element.tag == RDFNS('RDF') and event == 'start':
211 raise NoDublinCore("DublinCore section not found. \
212 Check if there are rdf:RDF and rdf:Description tags.")
214 # continue 'till the end of RDF section
215 for (event, element) in iter:
216 if element.tag == RDFNS('RDF') and event == 'end':
219 # if there is no end, Expat should yell at us with an ExpatError
221 # extract data from the element and make the info
222 return cls.from_element(desc_tag, *args, **kwargs)
223 except XMLSyntaxError, e:
225 except ExpatError, e:
229 def from_element(cls, rdf_tag, *args, **kwargs):
230 # the tree is already parsed, so we don't need to worry about Expat errors
232 desc = rdf_tag.find(".//" + RDFNS('Description'))
235 raise NoDublinCore("No DublinCore section found.")
237 for e in desc.getchildren():
238 fv = field_dict.get(e.tag, [])
240 field_dict[e.tag] = fv
242 return cls(desc.attrib, field_dict, *args, **kwargs)
244 def __init__(self, rdf_attrs, dc_fields, fallbacks=None, strict=False):
245 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
246 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
249 self.about = rdf_attrs.get(RDFNS('about'))
252 for field in self.FIELDS:
253 value = field.validate(dc_fields, fallbacks=fallbacks,
255 setattr(self, 'prop_' + field.name, value)
256 self.fmap[field.name] = field
257 if field.salias: self.fmap[field.salias] = field
259 def __getattribute__(self, name):
261 field = object.__getattribute__(self, 'fmap')[name]
262 value = object.__getattribute__(self, 'prop_'+field.name)
263 if field.name == name:
265 else: # singular alias
266 if not field.multiple:
267 raise "OUCH!! for field %s" % name
269 return value[0] if value else None
270 except (KeyError, AttributeError):
271 return object.__getattribute__(self, name)
273 def __setattr__(self, name, newvalue):
275 field = object.__getattribute__(self, 'fmap')[name]
276 if field.name == name:
277 object.__setattr__(self, 'prop_'+field.name, newvalue)
278 else: # singular alias
279 if not field.multiple:
280 raise "OUCH! while setting field %s" % name
282 object.__setattr__(self, 'prop_'+field.name, [newvalue])
283 except (KeyError, AttributeError):
284 return object.__setattr__(self, name, newvalue)
286 def update(self, field_dict):
287 """Update using field_dict. Verify correctness, but don't check if all
288 required fields are present."""
289 for field in self.FIELDS:
290 if field_dict.has_key(field.name):
291 setattr(self, field.name, field_dict[field.name])
293 def to_etree(self, parent = None):
294 """XML representation of this object."""
295 #etree._namespace_map[str(self.RDF)] = 'rdf'
296 #etree._namespace_map[str(self.DC)] = 'dc'
299 root = etree.Element(RDFNS('RDF'))
301 root = parent.makeelement(RDFNS('RDF'))
303 description = etree.SubElement(root, RDFNS('Description'))
306 description.set(RDFNS('about'), self.about)
308 for field in self.FIELDS:
309 v = getattr(self, field.name, None)
312 if len(v) == 0: continue
314 e = etree.Element(field.uri)
317 description.append(e)
319 e = etree.Element(field.uri)
321 description.append(e)
327 rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
330 for field in self.FIELDS:
331 v = getattr(self, field.name, None)
334 if len(v) == 0: continue
335 v = [ unicode(x) for x in v if x is not None ]
339 dc[field.name] = {'uri': field.uri, 'value': v}
344 result = {'about': self.about}
345 for field in self.FIELDS:
346 v = getattr(self, field.name, None)
350 if len(v) == 0: continue
351 v = [ unicode(x) for x in v if x is not None ]
354 result[field.name] = v
357 v = getattr(self, field.salias)
358 if v is not None: result[field.salias] = unicode(v)
363 class BookInfo(WorkInfo):
365 Field( DCNS('audience'), 'audiences', salias='audience', multiple=True,
368 Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True,
370 Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True,
372 Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True,
375 Field( DCNS('contributor.translator'), 'translators', \
376 as_person, salias='translator', multiple=True, default=[]),
377 Field( DCNS('relation.hasPart'), 'parts',
378 WLURI, strict=as_wluri_strict, multiple=True, required=False),
379 Field( DCNS('relation.isVariantOf'), 'variant_of',
380 WLURI, strict=as_wluri_strict, required=False),
382 Field( DCNS('relation.coverImage.url'), 'cover_url', required=False),
383 Field( DCNS('relation.coverImage.attribution'), 'cover_by', required=False),
384 Field( DCNS('relation.coverImage.source'), 'cover_source', required=False),
388 def parse(file_name, cls=BookInfo):
389 return cls.from_file(file_name)