Add funders info.
[librarian.git] / librarian / dcparser.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 from xml.parsers.expat import ExpatError
7 from datetime import date
8 import time
9
10 from librarian import (ValidationError, NoDublinCore, ParseError, DCNS, RDFNS,
11                        WLURI)
12
13 import lxml.etree as etree # ElementTree API using libxml2
14 from lxml.etree import XMLSyntaxError
15
16
17 # ==============
18 # = Converters =
19 # ==============
20 class Person(object):
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
25
26     @classmethod
27     def from_text(cls, text):
28         parts = [ token.strip() for token in text.split(',') ]
29         if len(parts) == 1:
30             surname = parts[0]
31             names = []
32         elif len(parts) != 2:
33             raise ValueError("Invalid person name. There should be at most one comma: \"%s\"." % text)
34         else:
35             surname = parts[0]
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)
41
42     def readable(self):
43         return u" ".join(self.first_names + (self.last_name,))
44
45     def __eq__(self, right):
46         return self.last_name == right.last_name and self.first_names == right.first_names
47
48     def __cmp__(self, other):
49         return cmp((self.last_name, self.first_names), (other.last_name, other.first_names))
50
51     def __hash__(self):
52         return hash((self.last_name, self.first_names))
53
54     def __unicode__(self):
55         if len(self.first_names) > 0:
56             return '%s, %s' % (self.last_name, ' '.join(self.first_names))
57         else:
58             return self.last_name
59
60     def __repr__(self):
61         return 'Person(last_name=%r, first_names=*%r)' % (self.last_name, self.first_names)
62
63 def as_date(text):
64     try:
65         try:
66             t = time.strptime(text, '%Y-%m-%d')
67         except ValueError:
68             t = time.strptime(text, '%Y')
69         return date(t[0], t[1], t[2])
70     except ValueError, e:
71         raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
72
73 def as_person(text):
74     return Person.from_text(text)
75
76 def as_unicode(text):
77     if isinstance(text, unicode):
78         return text
79     else:
80         return text.decode('utf-8')
81
82 def as_wluri_strict(text):
83     return WLURI.strict(text)
84
85 class Field(object):
86     def __init__(self, uri, attr_name, validator=as_unicode, strict=None, multiple=False, salias=None, **kwargs):
87         self.uri = uri
88         self.name = attr_name
89         self.validator = validator
90         self.strict = strict
91         self.multiple = multiple
92         self.salias = salias
93
94         self.required = kwargs.get('required', True) and not kwargs.has_key('default')
95         self.default = kwargs.get('default', [] if multiple else [None])
96
97     def validate_value(self, val, strict=False):
98         if strict and self.strict is not None:
99             validator = self.strict
100         else:
101             validator = self.validator
102         try:
103             if self.multiple:
104                 if validator is None:
105                     return val
106                 return [ validator(v) if v is not None else v for v in val ]
107             elif len(val) > 1:
108                 raise ValidationError("Multiple values not allowed for field '%s'" % self.uri)
109             elif len(val) == 0:
110                 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
111             else:
112                 if validator is None or val[0] is None:
113                     return val[0]
114                 return validator(val[0])
115         except ValueError, e:
116             raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
117
118     def validate(self, fdict, fallbacks=None, strict=False):
119         if fallbacks is None:
120             fallbacks = {}
121         if not fdict.has_key(self.uri):
122             if not self.required:
123                 # Accept single value for single fields and saliases.
124                 if self.name in fallbacks:
125                     if self.multiple:
126                         f = fallbacks[self.name]
127                     else:
128                         f = [fallbacks[self.name]]
129                 elif self.salias and self.salias in fallbacks:
130                     f = [fallbacks[self.salias]]
131                 else:
132                     f = self.default
133             else:
134                 raise ValidationError("Required field %s not found" % self.uri)
135         else:
136             f = fdict[self.uri]
137
138         return self.validate_value(f, strict=strict)
139
140     def __eq__(self, other):
141         if isinstance(other, Field) and other.name == self.name:
142             return True
143         return False
144
145
146 class DCInfo(type):
147     def __new__(meta, classname, bases, class_dict):
148         fields = list(class_dict['FIELDS'])
149
150         for base in bases[::-1]:
151             if hasattr(base, 'FIELDS'):
152                 for field in base.FIELDS[::-1]:
153                     try:
154                         fields.index(field)
155                     except ValueError:
156                         fields.insert(0, field)
157
158         class_dict['FIELDS'] = tuple(fields)
159         return super(DCInfo, meta).__new__(meta, classname, bases, class_dict)
160
161
162 class WorkInfo(object):
163     __metaclass__ = DCInfo
164
165     FIELDS = (
166         Field( DCNS('creator'), 'authors', as_person, salias='author', multiple=True),
167         Field( DCNS('title'), 'title'),
168         Field( DCNS('type'), 'type', required=False, multiple=True),
169
170         Field( DCNS('contributor.editor'), 'editors', \
171             as_person, salias='editor', multiple=True, default=[]),
172         Field( DCNS('contributor.technical_editor'), 'technical_editors',
173             as_person, salias='technical_editor', multiple=True, default=[]),
174         Field( DCNS('contributor.funding'), 'funders',
175             salias='funder', multiple=True, default=[]),
176
177         Field( DCNS('date'), 'created_at', as_date),
178         Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
179         Field( DCNS('publisher'), 'publisher'),
180
181         Field( DCNS('language'), 'language'),
182         Field( DCNS('description'), 'description', required=False),
183
184         Field( DCNS('source'), 'source_name', required=False),
185         Field( DCNS('source.URL'), 'source_url', required=False),
186         Field( DCNS('identifier.url'), 'url', WLURI, strict=as_wluri_strict),
187         Field( DCNS('rights.license'), 'license', required=False),
188         Field( DCNS('rights'), 'license_description'),
189     )
190
191     @classmethod
192     def from_string(cls, xml, *args, **kwargs):
193         from StringIO import StringIO
194         return cls.from_file(StringIO(xml), *args, **kwargs)
195
196     @classmethod
197     def from_file(cls, xmlfile, *args, **kwargs):
198         desc_tag = None
199         try:
200             iter = etree.iterparse(xmlfile, ['start', 'end'])
201             for (event, element) in iter:
202                 if element.tag == RDFNS('RDF') and event == 'start':
203                     desc_tag = element
204                     break
205
206             if desc_tag is None:
207                 raise NoDublinCore("DublinCore section not found. \
208                     Check if there are rdf:RDF and rdf:Description tags.")
209
210             # continue 'till the end of RDF section
211             for (event, element) in iter:
212                 if element.tag == RDFNS('RDF') and event == 'end':
213                     break
214
215             # if there is no end, Expat should yell at us with an ExpatError
216
217             # extract data from the element and make the info
218             return cls.from_element(desc_tag, *args, **kwargs)
219         except XMLSyntaxError, e:
220             raise ParseError(e)
221         except ExpatError, e:
222             raise ParseError(e)
223
224     @classmethod
225     def from_element(cls, rdf_tag, *args, **kwargs):
226         # the tree is already parsed, so we don't need to worry about Expat errors
227         field_dict = {}
228         desc = rdf_tag.find(".//" + RDFNS('Description'))
229
230         if desc is None:
231             raise NoDublinCore("No DublinCore section found.")
232
233         for e in desc.getchildren():
234             fv = field_dict.get(e.tag, [])
235             fv.append(e.text)
236             field_dict[e.tag] = fv
237
238         return cls(desc.attrib, field_dict, *args, **kwargs)
239
240     def __init__(self, rdf_attrs, dc_fields, fallbacks=None, strict=False):
241         """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
242         dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
243         given field. """
244
245         self.about = rdf_attrs.get(RDFNS('about'))
246         self.fmap = {}
247
248         for field in self.FIELDS:
249             value = field.validate(dc_fields, fallbacks=fallbacks,
250                             strict=strict)
251             setattr(self, 'prop_' + field.name, value)
252             self.fmap[field.name] = field
253             if field.salias: self.fmap[field.salias] = field
254
255     def __getattribute__(self, name):
256         try:
257             field = object.__getattribute__(self, 'fmap')[name]
258             value = object.__getattribute__(self, 'prop_'+field.name)
259             if field.name == name:
260                 return value
261             else: # singular alias
262                 if not field.multiple:
263                     raise "OUCH!! for field %s" % name
264
265                 return value[0] if value else None
266         except (KeyError, AttributeError):
267             return object.__getattribute__(self, name)
268
269     def __setattr__(self, name, newvalue):
270         try:
271             field = object.__getattribute__(self, 'fmap')[name]
272             if field.name == name:
273                 object.__setattr__(self, 'prop_'+field.name, newvalue)
274             else: # singular alias
275                 if not field.multiple:
276                     raise "OUCH! while setting field %s" % name
277
278                 object.__setattr__(self, 'prop_'+field.name, [newvalue])
279         except (KeyError, AttributeError):
280             return object.__setattr__(self, name, newvalue)
281
282     def update(self, field_dict):
283         """Update using field_dict. Verify correctness, but don't check if all
284         required fields are present."""
285         for field in self.FIELDS:
286             if field_dict.has_key(field.name):
287                 setattr(self, field.name, field_dict[field.name])
288
289     def to_etree(self, parent = None):
290         """XML representation of this object."""
291         #etree._namespace_map[str(self.RDF)] = 'rdf'
292         #etree._namespace_map[str(self.DC)] = 'dc'
293
294         if parent is None:
295             root = etree.Element(RDFNS('RDF'))
296         else:
297             root = parent.makeelement(RDFNS('RDF'))
298
299         description = etree.SubElement(root, RDFNS('Description'))
300
301         if self.about:
302             description.set(RDFNS('about'), self.about)
303
304         for field in self.FIELDS:
305             v = getattr(self, field.name, None)
306             if v is not None:
307                 if field.multiple:
308                     if len(v) == 0: continue
309                     for x in v:
310                         e = etree.Element(field.uri)
311                         if x is not None:
312                             e.text = unicode(x)
313                         description.append(e)
314                 else:
315                     e = etree.Element(field.uri)
316                     e.text = unicode(v)
317                     description.append(e)
318
319         return root
320
321     def serialize(self):
322         rdf = {}
323         rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
324
325         dc = {}
326         for field in self.FIELDS:
327             v = getattr(self, field.name, None)
328             if v is not None:
329                 if field.multiple:
330                     if len(v) == 0: continue
331                     v = [ unicode(x) for x in v if x is not None ]
332                 else:
333                     v = unicode(v)
334
335                 dc[field.name] = {'uri': field.uri, 'value': v}
336         rdf['fields'] = dc
337         return rdf
338
339     def to_dict(self):
340         result = {'about': self.about}
341         for field in self.FIELDS:
342             v = getattr(self, field.name, None)
343
344             if v is not None:
345                 if field.multiple:
346                     if len(v) == 0: continue
347                     v = [ unicode(x) for x in v if x is not None ]
348                 else:
349                     v = unicode(v)
350                 result[field.name] = v
351
352             if field.salias:
353                 v = getattr(self, field.salias)
354                 if v is not None: result[field.salias] = unicode(v)
355
356         return result
357
358
359 class BookInfo(WorkInfo):
360     FIELDS = (
361         Field( DCNS('audience'), 'audiences', salias='audience', multiple=True,
362                 required=False),
363
364         Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True,
365                 required=False),
366         Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True,
367                 required=False),
368         Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True,
369                 required=False),
370                 
371         Field( DCNS('contributor.translator'), 'translators', \
372             as_person,  salias='translator', multiple=True, default=[]),
373         Field( DCNS('relation.hasPart'), 'parts', 
374             WLURI, strict=as_wluri_strict, multiple=True, required=False),
375         Field( DCNS('relation.isVariantOf'), 'variant_of', 
376             WLURI, strict=as_wluri_strict, required=False),
377
378         Field( DCNS('relation.coverImage.url'), 'cover_url', required=False),
379         Field( DCNS('relation.coverImage.attribution'), 'cover_by', required=False),
380         Field( DCNS('relation.coverImage.source'), 'cover_source', required=False),
381     )
382
383
384 def parse(file_name, cls=BookInfo):
385     return cls.from_file(file_name)