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 m = re.match(u"([12]) *poł[.]? ([MCDXVI]+) .*[.]?", text)
70 half = int(m.groups()[0])
71 century = roman_to_int(str(m.groups()[1]))
72 t = ((century*100 + (half-1)*50), 1, 1)
75 t = time.strptime(text, '%Y-%m-%d')
77 t = time.strptime(text, '%Y')
78 return date(t[0], t[1], t[2])
80 raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
83 return Person.from_text(text)
86 if isinstance(text, unicode):
89 return text.decode('utf-8')
92 def __init__(self, uri, attr_name, type=as_unicode, multiple=False, salias=None, **kwargs):
96 self.multiple = multiple
99 self.required = kwargs.get('required', True) and not kwargs.has_key('default')
100 self.default = kwargs.get('default', [] if multiple else [None])
102 def validate_value(self, val):
105 if self.validator is None:
107 return [ self.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 self.validator is None or val[0] is None:
115 return self.validator(val[0])
116 except ValueError, e:
117 raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
119 def validate(self, fdict):
120 if not fdict.has_key(self.uri):
121 if not self.required:
124 raise ValidationError("Required field %s not found" % self.uri)
128 return self.validate_value(f)
130 def __eq__(self, other):
131 if isinstance(other, Field) and other.name == self.name:
137 def __new__(meta, classname, bases, class_dict):
138 fields = list(class_dict['FIELDS'])
140 for base in bases[::-1]:
141 if hasattr(base, 'FIELDS'):
142 for field in base.FIELDS[::-1]:
146 fields.insert(0, field)
148 class_dict['FIELDS'] = tuple(fields)
149 return super(DCInfo, meta).__new__(meta, classname, bases, class_dict)
152 class WorkInfo(object):
153 __metaclass__ = DCInfo
156 Field( DCNS('creator'), 'authors', as_person, salias='author', multiple=True),
157 Field( DCNS('title'), 'title'),
158 Field( DCNS('type'), 'type', required=False, multiple=True),
160 Field( DCNS('contributor.editor'), 'editors', \
161 as_person, salias='editor', multiple=True, default=[]),
162 Field( DCNS('contributor.technical_editor'), 'technical_editors',
163 as_person, salias='technical_editor', multiple=True, default=[]),
165 Field( DCNS('date'), 'created_at', as_date),
166 Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
167 Field( DCNS('publisher'), 'publisher'),
169 Field( DCNS('language'), 'language'),
170 Field( DCNS('description'), 'description', required=False),
172 Field( DCNS('source'), 'source_name', required=False),
173 Field( DCNS('source.URL'), 'source_url', required=False),
174 Field( DCNS('identifier.url'), 'url', WLURI),
175 Field( DCNS('rights.license'), 'license', required=False),
176 Field( DCNS('rights'), 'license_description'),
180 def from_string(cls, xml):
181 from StringIO import StringIO
182 return cls.from_file(StringIO(xml))
185 def from_file(cls, xmlfile):
188 iter = etree.iterparse(xmlfile, ['start', 'end'])
189 for (event, element) in iter:
190 if element.tag == RDFNS('RDF') and event == 'start':
195 raise NoDublinCore("DublinCore section not found. \
196 Check if there are rdf:RDF and rdf:Description tags.")
198 # continue 'till the end of RDF section
199 for (event, element) in iter:
200 if element.tag == RDFNS('RDF') and event == 'end':
203 # if there is no end, Expat should yell at us with an ExpatError
205 # extract data from the element and make the info
206 return cls.from_element(desc_tag)
207 except XMLSyntaxError, e:
209 except ExpatError, e:
213 def from_element(cls, rdf_tag):
214 # the tree is already parsed, so we don't need to worry about Expat errors
216 desc = rdf_tag.find(".//" + RDFNS('Description'))
219 raise NoDublinCore("No DublinCore section found.")
221 for e in desc.getchildren():
222 fv = field_dict.get(e.tag, [])
224 field_dict[e.tag] = fv
226 return cls(desc.attrib, field_dict)
228 def __init__(self, rdf_attrs, dc_fields):
229 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
230 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
233 self.about = rdf_attrs.get(RDFNS('about'))
236 for field in self.FIELDS:
237 value = field.validate( dc_fields )
238 setattr(self, 'prop_' + field.name, value)
239 self.fmap[field.name] = field
240 if field.salias: self.fmap[field.salias] = field
245 self.url.validate_language(self.language)
247 def __getattribute__(self, name):
249 field = object.__getattribute__(self, 'fmap')[name]
250 value = object.__getattribute__(self, 'prop_'+field.name)
251 if field.name == name:
253 else: # singular alias
254 if not field.multiple:
255 raise "OUCH!! for field %s" % name
258 except (KeyError, AttributeError):
259 return object.__getattribute__(self, name)
261 def __setattr__(self, name, newvalue):
263 field = object.__getattribute__(self, 'fmap')[name]
264 if field.name == name:
265 object.__setattr__(self, 'prop_'+field.name, newvalue)
266 else: # singular alias
267 if not field.multiple:
268 raise "OUCH! while setting field %s" % name
270 object.__setattr__(self, 'prop_'+field.name, [newvalue])
271 except (KeyError, AttributeError):
272 return object.__setattr__(self, name, newvalue)
274 def update(self, field_dict):
275 """Update using field_dict. Verify correctness, but don't check if all
276 required fields are present."""
277 for field in self.FIELDS:
278 if field_dict.has_key(field.name):
279 setattr(self, field.name, field_dict[field.name])
281 def to_etree(self, parent = None):
282 """XML representation of this object."""
283 #etree._namespace_map[str(self.RDF)] = 'rdf'
284 #etree._namespace_map[str(self.DC)] = 'dc'
287 root = etree.Element(RDFNS('RDF'))
289 root = parent.makeelement(RDFNS('RDF'))
291 description = etree.SubElement(root, RDFNS('Description'))
294 description.set(RDFNS('about'), self.about)
296 for field in self.FIELDS:
297 v = getattr(self, field.name, None)
300 if len(v) == 0: continue
302 e = etree.Element(field.uri)
305 description.append(e)
307 e = etree.Element(field.uri)
309 description.append(e)
315 rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
318 for field in self.FIELDS:
319 v = getattr(self, field.name, None)
322 if len(v) == 0: continue
323 v = [ unicode(x) for x in v if x is not None ]
327 dc[field.name] = {'uri': field.uri, 'value': v}
332 result = {'about': self.about}
333 for field in self.FIELDS:
334 v = getattr(self, field.name, None)
338 if len(v) == 0: continue
339 v = [ unicode(x) for x in v if x is not None ]
342 result[field.name] = v
345 v = getattr(self, field.salias)
346 if v is not None: result[field.salias] = unicode(v)
351 class BookInfo(WorkInfo):
353 Field( DCNS('audience'), 'audiences', salias='audience', multiple=True,
356 Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True),
357 Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True),
358 Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True),
360 Field( DCNS('contributor.translator'), 'translators', \
361 as_person, salias='translator', multiple=True, default=[]),
362 Field( DCNS('relation.hasPart'), 'parts', WLURI, multiple=True, required=False),
364 Field( DCNS('relation.cover_image.url'), 'cover_url', required=False),
365 Field( DCNS('relation.cover_image.attribution'), 'cover_by', required=False),
366 Field( DCNS('relation.cover_image.source'), 'cover_source', required=False),
370 def parse(file_name, cls=BookInfo):
371 return cls.from_file(file_name)