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)
77 century = roman_to_int(str(m.groups()[1]))
78 t = ((century*100 + (half-1)*50), 1, 1)
80 text = re.sub(r"(po|ok[.]?) *", "", text)
82 t = time.strptime(text, '%Y-%m-%d')
84 t = time.strptime(re.split(r'[-/]', text)[0], '%Y')
85 return date(t[0], t[1], t[2])
87 raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
90 return Person.from_text(text)
93 if isinstance(text, unicode):
96 return text.decode('utf-8')
98 def as_wluri_strict(text):
99 return WLURI.strict(text)
102 def __init__(self, uri, attr_name, validator=as_unicode, strict=None, multiple=False, salias=None, **kwargs):
104 self.name = attr_name
105 self.validator = validator
107 self.multiple = multiple
110 self.required = kwargs.get('required', True) and not kwargs.has_key('default')
111 self.default = kwargs.get('default', [] if multiple else [None])
113 def validate_value(self, val, strict=False):
114 if strict and self.strict is not None:
115 validator = self.strict
117 validator = self.validator
120 if validator is None:
122 return [ validator(v) if v is not None else v for v in val ]
124 raise ValidationError("Multiple values not allowed for field '%s'" % self.uri)
126 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
128 if validator is None or val[0] is None:
130 return validator(val[0])
131 except ValueError, e:
132 raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
134 def validate(self, fdict, fallbacks=None, strict=False):
135 if fallbacks is None:
137 if not fdict.has_key(self.uri):
138 if not self.required:
139 # Accept single value for single fields and saliases.
140 if self.name in fallbacks:
142 f = fallbacks[self.name]
144 f = [fallbacks[self.name]]
145 elif self.salias and self.salias in fallbacks:
146 f = [fallbacks[self.salias]]
150 raise ValidationError("Required field %s not found" % self.uri)
154 return self.validate_value(f, strict=strict)
156 def __eq__(self, other):
157 if isinstance(other, Field) and other.name == self.name:
163 def __new__(meta, classname, bases, class_dict):
164 fields = list(class_dict['FIELDS'])
166 for base in bases[::-1]:
167 if hasattr(base, 'FIELDS'):
168 for field in base.FIELDS[::-1]:
172 fields.insert(0, field)
174 class_dict['FIELDS'] = tuple(fields)
175 return super(DCInfo, meta).__new__(meta, classname, bases, class_dict)
178 class WorkInfo(object):
179 __metaclass__ = DCInfo
182 Field( DCNS('creator'), 'authors', as_person, salias='author', multiple=True),
183 Field( DCNS('title'), 'title'),
184 Field( DCNS('type'), 'type', required=False, multiple=True),
186 Field( DCNS('contributor.editor'), 'editors', \
187 as_person, salias='editor', multiple=True, default=[]),
188 Field( DCNS('contributor.technical_editor'), 'technical_editors',
189 as_person, salias='technical_editor', multiple=True, default=[]),
190 Field( DCNS('contributor.funding'), 'funders',
191 salias='funder', multiple=True, default=[]),
192 Field( DCNS('contributor.thanks'), 'thanks', required=False),
194 Field( DCNS('date'), 'created_at', as_date),
195 Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
196 Field( DCNS('publisher'), 'publisher'),
198 Field( DCNS('language'), 'language'),
199 Field( DCNS('description'), 'description', required=False),
201 Field( DCNS('source'), 'source_name', required=False),
202 Field( DCNS('source.URL'), 'source_url', required=False),
203 Field( DCNS('identifier.url'), 'url', WLURI, strict=as_wluri_strict),
204 Field( DCNS('rights.license'), 'license', required=False),
205 Field( DCNS('rights'), 'license_description'),
209 def from_string(cls, xml, *args, **kwargs):
210 from StringIO import StringIO
211 return cls.from_file(StringIO(xml), *args, **kwargs)
214 def from_file(cls, xmlfile, *args, **kwargs):
217 iter = etree.iterparse(xmlfile, ['start', 'end'])
218 for (event, element) in iter:
219 if element.tag == RDFNS('RDF') and event == 'start':
224 raise NoDublinCore("DublinCore section not found. \
225 Check if there are rdf:RDF and rdf:Description tags.")
227 # continue 'till the end of RDF section
228 for (event, element) in iter:
229 if element.tag == RDFNS('RDF') and event == 'end':
232 # if there is no end, Expat should yell at us with an ExpatError
234 # extract data from the element and make the info
235 return cls.from_element(desc_tag, *args, **kwargs)
236 except XMLSyntaxError, e:
238 except ExpatError, e:
242 def from_element(cls, rdf_tag, *args, **kwargs):
243 # the tree is already parsed, so we don't need to worry about Expat errors
245 desc = rdf_tag.find(".//" + RDFNS('Description'))
248 raise NoDublinCore("No DublinCore section found.")
250 for e in desc.getchildren():
251 fv = field_dict.get(e.tag, [])
253 field_dict[e.tag] = fv
255 return cls(desc.attrib, field_dict, *args, **kwargs)
257 def __init__(self, rdf_attrs, dc_fields, fallbacks=None, strict=False):
258 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
259 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
262 self.about = rdf_attrs.get(RDFNS('about'))
265 for field in self.FIELDS:
266 value = field.validate(dc_fields, fallbacks=fallbacks,
268 setattr(self, 'prop_' + field.name, value)
269 self.fmap[field.name] = field
270 if field.salias: self.fmap[field.salias] = field
272 def __getattribute__(self, name):
274 field = object.__getattribute__(self, 'fmap')[name]
275 value = object.__getattribute__(self, 'prop_'+field.name)
276 if field.name == name:
278 else: # singular alias
279 if not field.multiple:
280 raise "OUCH!! for field %s" % name
282 return value[0] if value else None
283 except (KeyError, AttributeError):
284 return object.__getattribute__(self, name)
286 def __setattr__(self, name, newvalue):
288 field = object.__getattribute__(self, 'fmap')[name]
289 if field.name == name:
290 object.__setattr__(self, 'prop_'+field.name, newvalue)
291 else: # singular alias
292 if not field.multiple:
293 raise "OUCH! while setting field %s" % name
295 object.__setattr__(self, 'prop_'+field.name, [newvalue])
296 except (KeyError, AttributeError):
297 return object.__setattr__(self, name, newvalue)
299 def update(self, field_dict):
300 """Update using field_dict. Verify correctness, but don't check if all
301 required fields are present."""
302 for field in self.FIELDS:
303 if field_dict.has_key(field.name):
304 setattr(self, field.name, field_dict[field.name])
306 def to_etree(self, parent = None):
307 """XML representation of this object."""
308 #etree._namespace_map[str(self.RDF)] = 'rdf'
309 #etree._namespace_map[str(self.DC)] = 'dc'
312 root = etree.Element(RDFNS('RDF'))
314 root = parent.makeelement(RDFNS('RDF'))
316 description = etree.SubElement(root, RDFNS('Description'))
319 description.set(RDFNS('about'), self.about)
321 for field in self.FIELDS:
322 v = getattr(self, field.name, None)
325 if len(v) == 0: continue
327 e = etree.Element(field.uri)
330 description.append(e)
332 e = etree.Element(field.uri)
334 description.append(e)
340 rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
343 for field in self.FIELDS:
344 v = getattr(self, field.name, None)
347 if len(v) == 0: continue
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)
363 if len(v) == 0: continue
364 v = [ unicode(x) for x in v if x is not None ]
367 result[field.name] = v
370 v = getattr(self, field.salias)
371 if v is not None: result[field.salias] = unicode(v)
376 class BookInfo(WorkInfo):
378 Field( DCNS('audience'), 'audiences', salias='audience', multiple=True,
381 Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True,
383 Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True,
385 Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True,
388 Field( DCNS('contributor.translator'), 'translators', \
389 as_person, salias='translator', multiple=True, default=[]),
390 Field( DCNS('relation.hasPart'), 'parts',
391 WLURI, strict=as_wluri_strict, multiple=True, required=False),
392 Field( DCNS('relation.isVariantOf'), 'variant_of',
393 WLURI, strict=as_wluri_strict, required=False),
395 Field( DCNS('relation.coverImage.url'), 'cover_url', required=False),
396 Field( DCNS('relation.coverImage.attribution'), 'cover_by', required=False),
397 Field( DCNS('relation.coverImage.source'), 'cover_source', required=False),
401 def parse(file_name, cls=BookInfo):
402 return cls.from_file(file_name)