Added copyright notice about AGPL. Removed setuputils in favour of plain distutils.
[librarian.git] / librarian / dcparser.py
1 # -*- coding: utf-8 -*-
2 #
3 #    This file is part of Librarian.
4 #
5 #    Copyright © 2008,2009,2010 Fundacja Nowoczesna Polska <fundacja@nowoczesnapolska.org.pl>
6 #    
7 #    For full list of contributors see AUTHORS file. 
8 #
9 #    This program is free software: you can redistribute it and/or modify
10 #    it under the terms of the GNU Affero General Public License as published by
11 #    the Free Software Foundation, either version 3 of the License, or
12 #    (at your option) any later version.
13 #
14 #    This program is distributed in the hope that it will be useful,
15 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
16 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 #    GNU Affero General Public License for more details.
18 #
19 #    You should have received a copy of the GNU Affero General Public License
20 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 #
22 from xml.parsers.expat import ExpatError
23 from datetime import date
24 import time
25
26 from librarian import ValidationError, NoDublinCore, ParseError, DCNS, RDFNS
27
28 import lxml.etree as etree # ElementTree API using libxml2
29 from lxml.etree import XMLSyntaxError
30
31
32 # ==============
33 # = Converters =
34 # ==============
35 class Person(object):
36     """Single person with last name and a list of first names."""
37     def __init__(self, last_name, *first_names):
38         self.last_name = last_name
39         self.first_names = first_names
40         
41     @classmethod
42     def from_text(cls, text):
43         parts = [ token.strip() for token in text.split(',') ]
44         if len(parts) == 1:
45             surname = parts[0]
46             names = []
47         elif len(parts) != 2:
48             raise ValueError("Invalid person name. There should be at most one comma: \"%s\"." % text)
49         else:
50             surname = parts[0]
51             if len(parts[1]) == 0:
52                 # there is no non-whitespace data after the comma
53                 raise ValueError("Found a comma, but no names given: \"%s\" -> %r." % (text, parts))
54             names = [ name for name in parts[1].split() if len(name) ] # all non-whitespace tokens
55         return cls(surname, *names)
56     
57     def __eq__(self, right):
58         return self.last_name == right.last_name and self.first_names == right.first_names
59     
60     
61     def __unicode__(self):
62         if len(self.first_names) > 0:
63             return '%s, %s' % (self.last_name, ' '.join(self.first_names))
64         else:
65             return self.last_name
66         
67     def __repr__(self):
68         return 'Person(last_name=%r, first_names=*%r)' % (self.last_name, self.first_names)
69
70 def as_date(text):
71     try:
72         try:
73             t = time.strptime(text, '%Y-%m-%d')
74         except ValueError:
75             t = time.strptime(text, '%Y')
76         return date(t[0], t[1], t[2])
77     except ValueError, e:
78         raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
79
80 def as_person(text):
81     return Person.from_text(text)
82
83 def as_unicode(text):
84     if isinstance(text, unicode):
85         return text
86     else:
87         return text.decode('utf-8')
88
89 class Field(object):
90     def __init__(self, uri, attr_name, type=as_unicode, multiple=False, salias=None, **kwargs):
91         self.uri = uri
92         self.name = attr_name
93         self.validator = type
94         self.multiple = multiple
95         self.salias = salias
96
97         self.required = kwargs.get('required', True) and not kwargs.has_key('default')
98         self.default = kwargs.get('default', [] if multiple else [None])
99
100     def validate_value(self, val):
101         try:
102             if self.multiple:
103                 if self.validator is None:
104                     return val
105                 return [ self.validator(v) if v is not None else v for v in val ]
106             elif len(val) > 1:
107                 raise ValidationError("Mulitply values not allowed for field '%s'" % self.uri)
108             elif len(val) == 0:
109                 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
110             else:
111                 if self.validator is None or val[0] is None:
112                     return val[0]
113                 return self.validator(val[0])
114         except ValueError, e:
115             raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
116
117     def validate(self, fdict):
118         if not fdict.has_key(self.uri):
119             if not self.required:
120                 f = self.default
121             else:
122                 raise ValidationError("Required field %s not found" % self.uri)
123         else:
124             f = fdict[self.uri]
125
126         return self.validate_value(f)
127
128
129
130
131 class BookInfo(object):    
132     FIELDS = (
133         Field( DCNS('creator'), 'author', as_person),
134         Field( DCNS('title'), 'title'),
135         Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True),
136         Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True),
137         Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True),
138         Field( DCNS('date'), 'created_at', as_date),
139         Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
140         Field( DCNS('contributor.editor'), 'editors', \
141             as_person, salias='editor', multiple=True, default=[]),
142         Field( DCNS('contributor.translator'), 'translators', \
143             as_person,  salias='translator', multiple=True, default=[]),
144         Field( DCNS('contributor.technical_editor'), 'technical_editors',
145             as_person, salias='technical_editor', multiple=True, default=[]),
146         Field( DCNS('publisher'), 'publisher'),
147         Field( DCNS('source'), 'source_name', required=False),
148         Field( DCNS('source.URL'), 'source_url', required=False),
149         Field( DCNS('identifier.url'), 'url'),
150         Field( DCNS('relation.hasPart'), 'parts', multiple=True, required=False),
151         Field( DCNS('rights.license'), 'license', required=False),
152         Field( DCNS('rights'), 'license_description'),
153     )
154
155     @classmethod
156     def from_string(cls, xml):
157         from StringIO import StringIO
158         return cls.from_file(StringIO(xml))
159    
160     @classmethod
161     def from_file(cls, xmlfile):
162         desc_tag = None        
163         try:
164             iter = etree.iterparse(xmlfile, ['start', 'end'])            
165             for (event, element) in iter:
166                 if element.tag == RDFNS('RDF') and event == 'start':
167                     desc_tag = element
168                     break
169
170             if desc_tag is None:
171                 raise NoDublinCore("DublinCore section not found. \
172                     Check if there are rdf:RDF and rdf:Description tags.")
173
174             # continue 'till the end of RDF section
175             for (event, element) in iter:
176                 if element.tag == RDFNS('RDF') and event == 'end':
177                     break
178
179             # if there is no end, Expat should yell at us with an ExpatError
180             
181             # extract data from the element and make the info
182             return cls.from_element(desc_tag)
183         except XMLSyntaxError, e:
184             raise ParseError(e)
185         except ExpatError, e:
186             raise ParseError(e)
187
188     @classmethod
189     def from_element(cls, rdf_tag):
190         # the tree is already parsed, so we don't need to worry about Expat errors
191         field_dict = {}
192         desc = rdf_tag.find(".//" + RDFNS('Description') )
193         
194         if desc is None:
195             raise NoDublinCore("No DublinCore section found.")
196
197         for e in desc.getchildren():
198             fv = field_dict.get(e.tag, [])
199             fv.append(e.text)
200             field_dict[e.tag] = fv
201                 
202         return cls( desc.attrib, field_dict )
203
204     def __init__(self, rdf_attrs, dc_fields):
205         """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
206         dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the 
207         given field. """
208
209         self.about = rdf_attrs.get(RDFNS('about'))
210         self.fmap = {}
211
212         for field in self.FIELDS:
213             value = field.validate( dc_fields )
214             setattr(self, 'prop_' + field.name, value)
215             self.fmap[field.name] = field
216             if field.salias: self.fmap[field.salias] = field
217
218     def __getattribute__(self, name):
219         try:
220             field = object.__getattribute__(self, 'fmap')[name]
221             value = object.__getattribute__(self, 'prop_'+field.name)
222             if field.name == name:
223                 return value
224             else: # singular alias
225                 if not field.multiple:
226                     raise "OUCH!! for field %s" % name
227                 
228                 return value[0]
229         except (KeyError, AttributeError):
230             return object.__getattribute__(self, name)
231
232     def __setattr__(self, name, newvalue):
233         try:
234             field = object.__getattribute__(self, 'fmap')[name]
235             if field.name == name:
236                 object.__setattr__(self, 'prop_'+field.name, newvalue)
237             else: # singular alias
238                 if not field.multiple:
239                     raise "OUCH! while setting field %s" % name
240
241                 object.__setattr__(self, 'prop_'+field.name, [newvalue])
242         except (KeyError, AttributeError):
243             return object.__setattr__(self, name, newvalue)
244
245     def update(self, field_dict):
246         """Update using field_dict. Verify correctness, but don't check if all 
247         required fields are present."""
248         for field in self.FIELDS:
249             if field_dict.has_key(field.name):
250                 setattr(self, field.name, field_dict[field.name])
251
252     def to_etree(self, parent = None):
253         """XML representation of this object."""
254         #etree._namespace_map[str(self.RDF)] = 'rdf'
255         #etree._namespace_map[str(self.DC)] = 'dc'
256         
257         if parent is None:
258             root = etree.Element(RDFNS('RDF'))
259         else:
260             root = parent.makeelement(RDFNS('RDF'))
261
262         description = etree.SubElement(root, RDFNS('Description'))
263         
264         if self.about:
265             description.set(RDFNS('about'), self.about)
266         
267         for field in self.FIELDS:
268             v = getattr(self, field.name, None)
269             if v is not None:
270                 if field.multiple:
271                     if len(v) == 0: continue
272                     for x in v:
273                         e = etree.Element(field.uri)
274                         e.text = unicode(x)
275                         description.append(e)
276                 else:
277                     e = etree.Element(field.uri)
278                     e.text = unicode(v)
279                     description.append(e)
280         
281         return root
282
283
284     def serialize(self):
285         rdf = {}
286         rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
287
288         dc = {}
289         for field in self.FIELDS:
290             v = getattr(self, field.name, None)
291             if v is not None:
292                 if field.multiple:
293                     if len(v) == 0: continue
294                     v = [ unicode(x) for x in v if v is not None ]
295                 else:
296                     v = unicode(v)
297                     
298                 dc[field.name] = {'uri': field.uri, 'value': v}
299         rdf['fields'] = dc
300         return rdf
301
302     def to_dict(self):
303         result = {'about': self.about}
304         for field in self.FIELDS:
305             v = getattr(self, field.name, None)
306
307             if v is not None:
308                 if field.multiple:
309                     if len(v) == 0: continue
310                     v = [ unicode(x) for x in v if v is not None ]
311                 else:
312                     v = unicode(v)
313                 result[field.name] = v
314
315             if field.salias:
316                 v = getattr(self, field.salias)
317                 if v is not None: result[field.salias] = unicode(v)
318         
319         return result
320
321 def parse(file_name):
322     return BookInfo.from_file(file_name)