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)
67 # check out the "N. poł X w." syntax
68 if isinstance(text, str): text = text.decode("utf-8")
69 m = re.match(u"([12]) *poł[.]? ([MCDXVI]+) *w[.]?", text)
71 half = int(m.groups()[0])
72 century = roman_to_int(str(m.groups()[1]))
73 t = ((century*100 + (half-1)*50), 1, 1)
76 t = time.strptime(text, '%Y-%m-%d')
78 t = time.strptime(text, '%Y')
79 return date(t[0], t[1], t[2])
81 raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
84 return Person.from_text(text)
87 if isinstance(text, unicode):
90 return text.decode('utf-8')
92 def as_wluri_strict(text):
93 return WLURI.strict(text)
96 def __init__(self, uri, attr_name, validator=as_unicode, strict=None, multiple=False, salias=None, **kwargs):
99 self.validator = validator
101 self.multiple = multiple
104 self.required = kwargs.get('required', True) and not kwargs.has_key('default')
105 self.default = kwargs.get('default', [] if multiple else [None])
107 def validate_value(self, val, strict=False):
108 if strict and self.strict is not None:
109 validator = self.strict
111 validator = self.validator
114 if validator is None:
116 return [ validator(v) if v is not None else v for v in val ]
118 raise ValidationError("Multiple values not allowed for field '%s'" % self.uri)
120 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
122 if validator is None or val[0] is None:
124 return validator(val[0])
125 except ValueError, e:
126 raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
128 def validate(self, fdict, fallbacks=None, strict=False):
129 if fallbacks is None:
131 if not fdict.has_key(self.uri):
132 if not self.required:
133 # Accept single value for single fields and saliases.
134 if self.name in fallbacks:
136 f = fallbacks[self.name]
138 f = [fallbacks[self.name]]
139 elif self.salias and self.salias in fallbacks:
140 f = [fallbacks[self.salias]]
144 raise ValidationError("Required field %s not found" % self.uri)
148 return self.validate_value(f, strict=strict)
150 def __eq__(self, other):
151 if isinstance(other, Field) and other.name == self.name:
157 def __new__(meta, classname, bases, class_dict):
158 fields = list(class_dict['FIELDS'])
160 for base in bases[::-1]:
161 if hasattr(base, 'FIELDS'):
162 for field in base.FIELDS[::-1]:
166 fields.insert(0, field)
168 class_dict['FIELDS'] = tuple(fields)
169 return super(DCInfo, meta).__new__(meta, classname, bases, class_dict)
172 class WorkInfo(object):
173 __metaclass__ = DCInfo
176 Field( DCNS('creator'), 'authors', as_person, salias='author', multiple=True),
177 Field( DCNS('title'), 'title'),
178 Field( DCNS('type'), 'type', required=False, multiple=True),
180 Field( DCNS('contributor.editor'), 'editors', \
181 as_person, salias='editor', multiple=True, default=[]),
182 Field( DCNS('contributor.technical_editor'), 'technical_editors',
183 as_person, salias='technical_editor', multiple=True, default=[]),
184 Field( DCNS('contributor.funding'), 'funders',
185 salias='funder', multiple=True, default=[]),
186 Field( DCNS('contributor.thanks'), 'thanks', required=False),
188 Field( DCNS('date'), 'created_at', as_date),
189 Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
190 Field( DCNS('publisher'), 'publisher'),
192 Field( DCNS('language'), 'language'),
193 Field( DCNS('description'), 'description', required=False),
195 Field( DCNS('source'), 'source_name', required=False),
196 Field( DCNS('source.URL'), 'source_url', required=False),
197 Field( DCNS('identifier.url'), 'url', WLURI, strict=as_wluri_strict),
198 Field( DCNS('rights.license'), 'license', required=False),
199 Field( DCNS('rights'), 'license_description'),
203 def from_string(cls, xml, *args, **kwargs):
204 from StringIO import StringIO
205 return cls.from_file(StringIO(xml), *args, **kwargs)
208 def from_file(cls, xmlfile, *args, **kwargs):
211 iter = etree.iterparse(xmlfile, ['start', 'end'])
212 for (event, element) in iter:
213 if element.tag == RDFNS('RDF') and event == 'start':
218 raise NoDublinCore("DublinCore section not found. \
219 Check if there are rdf:RDF and rdf:Description tags.")
221 # continue 'till the end of RDF section
222 for (event, element) in iter:
223 if element.tag == RDFNS('RDF') and event == 'end':
226 # if there is no end, Expat should yell at us with an ExpatError
228 # extract data from the element and make the info
229 return cls.from_element(desc_tag, *args, **kwargs)
230 except XMLSyntaxError, e:
232 except ExpatError, e:
236 def from_element(cls, rdf_tag, *args, **kwargs):
237 # the tree is already parsed, so we don't need to worry about Expat errors
239 desc = rdf_tag.find(".//" + RDFNS('Description'))
242 raise NoDublinCore("No DublinCore section found.")
244 for e in desc.getchildren():
245 fv = field_dict.get(e.tag, [])
247 field_dict[e.tag] = fv
249 return cls(desc.attrib, field_dict, *args, **kwargs)
251 def __init__(self, rdf_attrs, dc_fields, fallbacks=None, strict=False):
252 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
253 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
256 self.about = rdf_attrs.get(RDFNS('about'))
259 for field in self.FIELDS:
260 value = field.validate(dc_fields, fallbacks=fallbacks,
262 setattr(self, 'prop_' + field.name, value)
263 self.fmap[field.name] = field
264 if field.salias: self.fmap[field.salias] = field
266 def __getattribute__(self, name):
268 field = object.__getattribute__(self, 'fmap')[name]
269 value = object.__getattribute__(self, 'prop_'+field.name)
270 if field.name == name:
272 else: # singular alias
273 if not field.multiple:
274 raise "OUCH!! for field %s" % name
276 return value[0] if value else None
277 except (KeyError, AttributeError):
278 return object.__getattribute__(self, name)
280 def __setattr__(self, name, newvalue):
282 field = object.__getattribute__(self, 'fmap')[name]
283 if field.name == name:
284 object.__setattr__(self, 'prop_'+field.name, newvalue)
285 else: # singular alias
286 if not field.multiple:
287 raise "OUCH! while setting field %s" % name
289 object.__setattr__(self, 'prop_'+field.name, [newvalue])
290 except (KeyError, AttributeError):
291 return object.__setattr__(self, name, newvalue)
293 def update(self, field_dict):
294 """Update using field_dict. Verify correctness, but don't check if all
295 required fields are present."""
296 for field in self.FIELDS:
297 if field_dict.has_key(field.name):
298 setattr(self, field.name, field_dict[field.name])
300 def to_etree(self, parent = None):
301 """XML representation of this object."""
302 #etree._namespace_map[str(self.RDF)] = 'rdf'
303 #etree._namespace_map[str(self.DC)] = 'dc'
306 root = etree.Element(RDFNS('RDF'))
308 root = parent.makeelement(RDFNS('RDF'))
310 description = etree.SubElement(root, RDFNS('Description'))
313 description.set(RDFNS('about'), self.about)
315 for field in self.FIELDS:
316 v = getattr(self, field.name, None)
319 if len(v) == 0: continue
321 e = etree.Element(field.uri)
324 description.append(e)
326 e = etree.Element(field.uri)
328 description.append(e)
334 rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
337 for field in self.FIELDS:
338 v = getattr(self, field.name, None)
341 if len(v) == 0: continue
342 v = [ unicode(x) for x in v if x is not None ]
346 dc[field.name] = {'uri': field.uri, 'value': v}
351 result = {'about': self.about}
352 for field in self.FIELDS:
353 v = getattr(self, field.name, None)
357 if len(v) == 0: continue
358 v = [ unicode(x) for x in v if x is not None ]
361 result[field.name] = v
364 v = getattr(self, field.salias)
365 if v is not None: result[field.salias] = unicode(v)
370 class BookInfo(WorkInfo):
372 Field( DCNS('audience'), 'audiences', salias='audience', multiple=True,
375 Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True,
377 Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True,
379 Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True,
382 Field( DCNS('contributor.translator'), 'translators', \
383 as_person, salias='translator', multiple=True, default=[]),
384 Field( DCNS('relation.hasPart'), 'parts',
385 WLURI, strict=as_wluri_strict, multiple=True, required=False),
386 Field( DCNS('relation.isVariantOf'), 'variant_of',
387 WLURI, strict=as_wluri_strict, required=False),
389 Field( DCNS('relation.coverImage.url'), 'cover_url', required=False),
390 Field( DCNS('relation.coverImage.attribution'), 'cover_by', required=False),
391 Field( DCNS('relation.coverImage.source'), 'cover_source', required=False),
395 def parse(file_name, cls=BookInfo):
396 return cls.from_file(file_name)