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