8883f92928cb00e4b5b94ac2afbd39e69365d32f
[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         val = [v.strip() if v is not None else v for v in val]
99         if strict and self.strict is not None:
100             validator = self.strict
101         else:
102             validator = self.validator
103         try:
104             if self.multiple:
105                 if validator is None:
106                     return val
107                 return [ validator(v) if v is not None else v for v in val ]
108             elif len(val) > 1:
109                 raise ValidationError("Multiple values not allowed for field '%s'" % self.uri)
110             elif len(val) == 0:
111                 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
112             else:
113                 if validator is None or val[0] is None:
114                     return val[0]
115                 return validator(val[0])
116         except ValueError, e:
117             raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
118
119     def validate(self, fdict, fallbacks=None, strict=False):
120         if fallbacks is None:
121             fallbacks = {}
122         if not fdict.has_key(self.uri):
123             if not self.required:
124                 # Accept single value for single fields and saliases.
125                 if self.name in fallbacks:
126                     if self.multiple:
127                         f = fallbacks[self.name]
128                     else:
129                         f = [fallbacks[self.name]]
130                 elif self.salias and self.salias in fallbacks:
131                     f = [fallbacks[self.salias]]
132                 else:
133                     f = self.default
134             else:
135                 raise ValidationError("Required field %s not found" % self.uri)
136         else:
137             f = fdict[self.uri]
138
139         return self.validate_value(f, strict=strict)
140
141     def __eq__(self, other):
142         if isinstance(other, Field) and other.name == self.name and other.uri == self.uri:
143             return True
144         return False
145
146
147 class DCInfo(type):
148     def __new__(meta, classname, bases, class_dict):
149         fields = list(class_dict['FIELDS'])
150
151         for base in bases[::-1]:
152             if hasattr(base, 'FIELDS'):
153                 for field in base.FIELDS[::-1]:
154                     try:
155                         fields.index(field)
156                     except ValueError:
157                         fields.insert(0, field)
158
159         class_dict['FIELDS'] = tuple(fields)
160         return super(DCInfo, meta).__new__(meta, classname, bases, class_dict)
161
162
163 class WorkInfo(object):
164     __metaclass__ = DCInfo
165
166     FIELDS = (
167         Field( DCNS('creator.expert'), 'authors_expert', as_person, salias='author', required=False, multiple=True),
168         Field( DCNS('creator.scenario'), 'authors_scenario', as_person, salias='author', required=False, multiple=True),
169         Field( DCNS('creator.textbook'), 'authors_textbook', as_person, salias='author', required=False, multiple=True),
170         Field( DCNS('requires'), 'requires', required=False, multiple=True),
171         Field( DCNS('title'), 'title'),
172         Field( DCNS('type'), 'type', required=False),
173
174         Field( DCNS('contributor.editor'), 'editors', \
175             as_person, salias='editor', multiple=True, default=[]),
176         Field( DCNS('contributor.technical_editor'), 'technical_editors',
177             as_person, salias='technical_editor', multiple=True, default=[]),
178
179         Field( DCNS('date'), 'created_at', as_date),
180         Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
181         Field( DCNS('publisher'), 'publisher'),
182
183         Field( DCNS('subject.competence'), 'competences', multiple=True, required=False),
184         Field( DCNS('subject.curriculum'), 'curriculum', multiple=True, required=False),
185
186         Field( DCNS('language'), 'language'),
187         Field( DCNS('description'), 'description', required=False),
188
189         Field( DCNS('source'), 'source_name', required=False),
190         Field( DCNS('source.URL'), 'source_url', required=False),
191         Field( DCNS('identifier.url'), 'url', WLURI, strict=as_wluri_strict),
192         Field( DCNS('rights.license'), 'license', required=False),
193         Field( DCNS('rights'), 'license_description'),
194     )
195
196     @classmethod
197     def from_string(cls, xml, *args, **kwargs):
198         from StringIO import StringIO
199         return cls.from_file(StringIO(xml), *args, **kwargs)
200
201     @classmethod
202     def from_file(cls, xmlfile, *args, **kwargs):
203         desc_tag = None
204         try:
205             iter = etree.iterparse(xmlfile, ['start', 'end'])
206             for (event, element) in iter:
207                 if element.tag == RDFNS('RDF') and event == 'start':
208                     desc_tag = element
209                     break
210
211             if desc_tag is None:
212                 raise NoDublinCore("DublinCore section not found. \
213                     Check if there are rdf:RDF and rdf:Description tags.")
214
215             # continue 'till the end of RDF section
216             for (event, element) in iter:
217                 if element.tag == RDFNS('RDF') and event == 'end':
218                     break
219
220             # if there is no end, Expat should yell at us with an ExpatError
221
222             # extract data from the element and make the info
223             return cls.from_element(desc_tag, *args, **kwargs)
224         except XMLSyntaxError, e:
225             raise ParseError(e)
226         except ExpatError, e:
227             raise ParseError(e)
228
229     @classmethod
230     def from_element(cls, rdf_tag, *args, **kwargs):
231         # the tree is already parsed, so we don't need to worry about Expat errors
232         field_dict = {}
233         desc = rdf_tag.find(".//" + RDFNS('Description'))
234
235         if desc is None:
236             raise NoDublinCore("No DublinCore section found.")
237
238         for e in desc.getchildren():
239             fv = field_dict.get(e.tag, [])
240             fv.append(e.text)
241             field_dict[e.tag] = fv
242
243         return cls(desc.attrib, field_dict, *args, **kwargs)
244
245     def __init__(self, rdf_attrs, dc_fields, fallbacks=None, strict=False):
246         """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
247         dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
248         given field. """
249
250         self.about = rdf_attrs.get(RDFNS('about'))
251         self.fmap = {}
252
253         for field in self.FIELDS:
254             value = field.validate(dc_fields, fallbacks=fallbacks,
255                             strict=strict)
256             if field.multiple:
257                 value = getattr(self, 'prop_' + field.name, []) + value
258             setattr(self, 'prop_' + field.name, value)
259             self.fmap[field.name] = field
260             if field.salias: self.fmap[field.salias] = field
261
262     def __getattribute__(self, name):
263         try:
264             field = object.__getattribute__(self, 'fmap')[name]
265             value = object.__getattribute__(self, 'prop_'+field.name)
266             if field.name == name:
267                 return value
268             else: # singular alias
269                 if not field.multiple:
270                     raise "OUCH!! for field %s" % name
271
272                 return value[0] if value else None
273         except (KeyError, AttributeError):
274             return object.__getattribute__(self, name)
275
276     def __setattr__(self, name, newvalue):
277         try:
278             field = object.__getattribute__(self, 'fmap')[name]
279             if field.name == name:
280                 object.__setattr__(self, 'prop_'+field.name, newvalue)
281             else: # singular alias
282                 if not field.multiple:
283                     raise "OUCH! while setting field %s" % name
284
285                 object.__setattr__(self, 'prop_'+field.name, [newvalue])
286         except (KeyError, AttributeError):
287             return object.__setattr__(self, name, newvalue)
288
289     def update(self, field_dict):
290         """Update using field_dict. Verify correctness, but don't check if all
291         required fields are present."""
292         for field in self.FIELDS:
293             if field_dict.has_key(field.name):
294                 setattr(self, field.name, field_dict[field.name])
295
296     def to_etree(self, parent = None):
297         """XML representation of this object."""
298         #etree._namespace_map[str(self.RDF)] = 'rdf'
299         #etree._namespace_map[str(self.DC)] = 'dc'
300
301         if parent is None:
302             root = etree.Element(RDFNS('RDF'))
303         else:
304             root = parent.makeelement(RDFNS('RDF'))
305
306         description = etree.SubElement(root, RDFNS('Description'))
307
308         if self.about:
309             description.set(RDFNS('about'), self.about)
310
311         for field in self.FIELDS:
312             v = getattr(self, field.name, None)
313             if v is not None:
314                 if field.multiple:
315                     if len(v) == 0: continue
316                     for x in v:
317                         e = etree.Element(field.uri)
318                         if x is not None:
319                             e.text = unicode(x)
320                         description.append(e)
321                 else:
322                     e = etree.Element(field.uri)
323                     e.text = unicode(v)
324                     description.append(e)
325
326         return root
327
328     def serialize(self):
329         rdf = {}
330         rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
331
332         dc = {}
333         for field in self.FIELDS:
334             v = getattr(self, field.name, None)
335             if v is not None:
336                 if field.multiple:
337                     if len(v) == 0: continue
338                     v = [ unicode(x) for x in v if x is not None ]
339                 else:
340                     v = unicode(v)
341
342                 dc[field.name] = {'uri': field.uri, 'value': v}
343         rdf['fields'] = dc
344         return rdf
345
346     def to_dict(self):
347         result = {'about': self.about}
348         for field in self.FIELDS:
349             v = getattr(self, field.name, None)
350
351             if v is not None:
352                 if field.multiple:
353                     if len(v) == 0: continue
354                     v = [ unicode(x) for x in v if x is not None ]
355                 else:
356                     v = unicode(v)
357                 result[field.name] = v
358
359             if field.salias:
360                 v = getattr(self, field.salias)
361                 if v is not None: result[field.salias] = unicode(v)
362
363         return result
364
365
366 class BookInfo(WorkInfo):
367     FIELDS = (
368         Field( DCNS('audience'), 'audiences', salias='audience', multiple=True,
369                 required=False),
370
371         Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True,
372                 required=False),
373         Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True,
374                 required=False),
375         Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True,
376                 required=False),
377
378         Field( DCNS('contributor.translator'), 'translators', \
379             as_person,  salias='translator', multiple=True, default=[]),
380         Field( DCNS('relation.hasPart'), 'parts',
381             WLURI, strict=as_wluri_strict, multiple=True, required=False),
382         Field( DCNS('relation.isVariantOf'), 'variant_of',
383             WLURI, strict=as_wluri_strict, required=False),
384         Field( DCNS('relation'), 'relations',
385             WLURI, strict=as_wluri_strict, multiple=True, required=False),
386
387         Field( DCNS('relation.coverImage.url'), 'cover_url', required=False),
388         Field( DCNS('relation.coverImage.attribution'), 'cover_by', required=False),
389         Field( DCNS('relation.coverImage.source'), 'cover_source', required=False),
390     )
391
392
393 def parse(file_name, cls=BookInfo):
394     return cls.from_file(file_name)