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')
83 def __init__(self, uri, attr_name, type=as_unicode, multiple=False, salias=None, **kwargs):
87 self.multiple = multiple
90 self.required = kwargs.get('required', True) and not kwargs.has_key('default')
91 self.default = kwargs.get('default', [] if multiple else [None])
93 def validate_value(self, val):
96 if self.validator is None:
98 return [ self.validator(v) if v is not None else v for v in val ]
100 raise ValidationError("Multiple values not allowed for field '%s'" % self.uri)
102 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
104 if self.validator is None or val[0] is None:
106 return self.validator(val[0])
107 except ValueError, e:
108 raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
110 def validate(self, fdict):
111 if not fdict.has_key(self.uri):
112 if not self.required:
115 raise ValidationError("Required field %s not found" % self.uri)
119 return self.validate_value(f)
121 def __eq__(self, other):
122 if isinstance(other, Field) and other.name == self.name:
128 def __new__(meta, classname, bases, class_dict):
129 fields = list(class_dict['FIELDS'])
131 for base in bases[::-1]:
132 if hasattr(base, 'FIELDS'):
133 for field in base.FIELDS[::-1]:
137 fields.insert(0, field)
139 class_dict['FIELDS'] = tuple(fields)
140 return super(DCInfo, meta).__new__(meta, classname, bases, class_dict)
143 class WorkInfo(object):
144 __metaclass__ = DCInfo
147 Field( DCNS('creator'), 'authors', as_person, salias='author', multiple=True),
148 Field( DCNS('title'), 'title'),
149 Field( DCNS('type'), 'type', required=False, multiple=True),
151 Field( DCNS('contributor.editor'), 'editors', \
152 as_person, salias='editor', multiple=True, default=[]),
153 Field( DCNS('contributor.technical_editor'), 'technical_editors',
154 as_person, salias='technical_editor', multiple=True, default=[]),
156 Field( DCNS('date'), 'created_at', as_date),
157 Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
158 Field( DCNS('publisher'), 'publisher'),
160 Field( DCNS('language'), 'language'),
161 Field( DCNS('description'), 'description', required=False),
163 Field( DCNS('source'), 'source_name', required=False),
164 Field( DCNS('source.URL'), 'source_url', required=False),
165 Field( DCNS('identifier.url'), 'url', WLURI),
166 Field( DCNS('rights.license'), 'license', required=False),
167 Field( DCNS('rights'), 'license_description'),
171 def from_string(cls, xml):
172 from StringIO import StringIO
173 return cls.from_file(StringIO(xml))
176 def from_file(cls, xmlfile):
179 iter = etree.iterparse(xmlfile, ['start', 'end'])
180 for (event, element) in iter:
181 if element.tag == RDFNS('RDF') and event == 'start':
186 raise NoDublinCore("DublinCore section not found. \
187 Check if there are rdf:RDF and rdf:Description tags.")
189 # continue 'till the end of RDF section
190 for (event, element) in iter:
191 if element.tag == RDFNS('RDF') and event == 'end':
194 # if there is no end, Expat should yell at us with an ExpatError
196 # extract data from the element and make the info
197 return cls.from_element(desc_tag)
198 except XMLSyntaxError, e:
200 except ExpatError, e:
204 def from_element(cls, rdf_tag):
205 # the tree is already parsed, so we don't need to worry about Expat errors
207 desc = rdf_tag.find(".//" + RDFNS('Description'))
210 raise NoDublinCore("No DublinCore section found.")
212 for e in desc.getchildren():
213 fv = field_dict.get(e.tag, [])
215 field_dict[e.tag] = fv
218 return cls(desc.attrib, field_dict)
220 def __init__(self, rdf_attrs, dc_fields):
221 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
222 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
225 self.about = rdf_attrs.get(RDFNS('about'))
228 for field in self.FIELDS:
229 value = field.validate( dc_fields )
230 setattr(self, 'prop_' + field.name, value)
231 self.fmap[field.name] = field
232 if field.salias: self.fmap[field.salias] = field
237 self.url.validate_language(self.language)
239 def __getattribute__(self, name):
241 field = object.__getattribute__(self, 'fmap')[name]
242 value = object.__getattribute__(self, 'prop_'+field.name)
243 if field.name == name:
245 else: # singular alias
246 if not field.multiple:
247 raise "OUCH!! for field %s" % name
250 except (KeyError, AttributeError):
251 return object.__getattribute__(self, name)
253 def __setattr__(self, name, newvalue):
255 field = object.__getattribute__(self, 'fmap')[name]
256 if field.name == name:
257 object.__setattr__(self, 'prop_'+field.name, newvalue)
258 else: # singular alias
259 if not field.multiple:
260 raise "OUCH! while setting field %s" % name
262 object.__setattr__(self, 'prop_'+field.name, [newvalue])
263 except (KeyError, AttributeError):
264 return object.__setattr__(self, name, newvalue)
266 def update(self, field_dict):
267 """Update using field_dict. Verify correctness, but don't check if all
268 required fields are present."""
269 for field in self.FIELDS:
270 if field_dict.has_key(field.name):
271 setattr(self, field.name, field_dict[field.name])
273 def to_etree(self, parent = None):
274 """XML representation of this object."""
275 #etree._namespace_map[str(self.RDF)] = 'rdf'
276 #etree._namespace_map[str(self.DC)] = 'dc'
279 root = etree.Element(RDFNS('RDF'))
281 root = parent.makeelement(RDFNS('RDF'))
283 description = etree.SubElement(root, RDFNS('Description'))
286 description.set(RDFNS('about'), self.about)
288 for field in self.FIELDS:
289 v = getattr(self, field.name, None)
292 if len(v) == 0: continue
294 e = etree.Element(field.uri)
297 description.append(e)
299 e = etree.Element(field.uri)
301 description.append(e)
307 rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
310 for field in self.FIELDS:
311 v = getattr(self, field.name, None)
314 if len(v) == 0: continue
315 v = [ unicode(x) for x in v if x is not None ]
319 dc[field.name] = {'uri': field.uri, 'value': v}
324 result = {'about': self.about}
325 for field in self.FIELDS:
326 v = getattr(self, field.name, None)
330 if len(v) == 0: continue
331 v = [ unicode(x) for x in v if x is not None ]
334 result[field.name] = v
337 v = getattr(self, field.salias)
338 if v is not None: result[field.salias] = unicode(v)
343 class BookInfo(WorkInfo):
345 Field( DCNS('audience'), 'audiences', salias='audience', multiple=True,
348 Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True),
349 Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True),
350 Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True),
352 Field( DCNS('contributor.translator'), 'translators', \
353 as_person, salias='translator', multiple=True, default=[]),
354 Field( DCNS('relation.hasPart'), 'parts', WLURI, multiple=True, required=False),
356 Field( DCNS('relation.cover_image.url'), 'cover_url', required=False),
357 Field( DCNS('relation.cover_image.attribution'), 'cover_by', required=False),
358 Field( DCNS('relation.cover_image.source'), 'cover_source', required=False),
362 def parse(file_name, cls=BookInfo):
363 return cls.from_file(file_name)