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