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