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