1 # -*- coding: utf-8 -*-
3 # Copyright © 2008,2009,2010 Fundacja Nowoczesna Polska
5 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
6 # For full license text see COPYING or <http://www.gnu.org/licenses/agpl.html>
8 from xml.parsers.expat import ExpatError
9 from datetime import date
12 from librarian import ValidationError, NoDublinCore, ParseError, DCNS, RDFNS
14 import lxml.etree as etree # ElementTree API using libxml2
15 from lxml.etree import XMLSyntaxError
22 """Single person with last name and a list of first names."""
23 def __init__(self, last_name, *first_names):
24 self.last_name = last_name
25 self.first_names = first_names
28 def from_text(cls, text):
29 parts = [ token.strip() for token in text.split(',') ]
34 raise ValueError("Invalid person name. There should be at most one comma: \"%s\"." % text)
37 if len(parts[1]) == 0:
38 # there is no non-whitespace data after the comma
39 raise ValueError("Found a comma, but no names given: \"%s\" -> %r." % (text, parts))
40 names = [ name for name in parts[1].split() if len(name) ] # all non-whitespace tokens
41 return cls(surname, *names)
43 def __eq__(self, right):
44 return self.last_name == right.last_name and self.first_names == right.first_names
47 def __unicode__(self):
48 if len(self.first_names) > 0:
49 return '%s, %s' % (self.last_name, ' '.join(self.first_names))
54 return 'Person(last_name=%r, first_names=*%r)' % (self.last_name, self.first_names)
59 t = time.strptime(text, '%Y-%m-%d')
61 t = time.strptime(text, '%Y')
62 return date(t[0], t[1], t[2])
64 raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
67 return Person.from_text(text)
70 if isinstance(text, unicode):
73 return text.decode('utf-8')
76 def __init__(self, uri, attr_name, type=as_unicode, multiple=False, salias=None, **kwargs):
80 self.multiple = multiple
83 self.required = kwargs.get('required', True) and not kwargs.has_key('default')
84 self.default = kwargs.get('default', [] if multiple else [None])
86 def validate_value(self, val):
89 if self.validator is None:
91 return [ self.validator(v) if v is not None else v for v in val ]
93 raise ValidationError("Mulitply values not allowed for field '%s'" % self.uri)
95 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
97 if self.validator is None or val[0] is None:
99 return self.validator(val[0])
100 except ValueError, e:
101 raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
103 def validate(self, fdict):
104 if not fdict.has_key(self.uri):
105 if not self.required:
108 raise ValidationError("Required field %s not found" % self.uri)
112 return self.validate_value(f)
117 class BookInfo(object):
119 Field( DCNS('creator'), 'author', as_person),
120 Field( DCNS('title'), 'title'),
121 Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True),
122 Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True),
123 Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True),
124 Field( DCNS('date'), 'created_at', as_date),
125 Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
126 Field( DCNS('contributor.editor'), 'editors', \
127 as_person, salias='editor', multiple=True, default=[]),
128 Field( DCNS('contributor.translator'), 'translators', \
129 as_person, salias='translator', multiple=True, default=[]),
130 Field( DCNS('contributor.technical_editor'), 'technical_editors',
131 as_person, salias='technical_editor', multiple=True, default=[]),
132 Field( DCNS('publisher'), 'publisher'),
133 Field( DCNS('source'), 'source_name', required=False),
134 Field( DCNS('source.URL'), 'source_url', required=False),
135 Field( DCNS('identifier.url'), 'url'),
136 Field( DCNS('relation.hasPart'), 'parts', multiple=True, required=False),
137 Field( DCNS('rights.license'), 'license', required=False),
138 Field( DCNS('rights'), 'license_description'),
142 def from_string(cls, xml):
143 from StringIO import StringIO
144 return cls.from_file(StringIO(xml))
147 def from_file(cls, xmlfile):
150 iter = etree.iterparse(xmlfile, ['start', 'end'])
151 for (event, element) in iter:
152 if element.tag == RDFNS('RDF') and event == 'start':
157 raise NoDublinCore("DublinCore section not found. \
158 Check if there are rdf:RDF and rdf:Description tags.")
160 # continue 'till the end of RDF section
161 for (event, element) in iter:
162 if element.tag == RDFNS('RDF') and event == 'end':
165 # if there is no end, Expat should yell at us with an ExpatError
167 # extract data from the element and make the info
168 return cls.from_element(desc_tag)
169 except XMLSyntaxError, e:
171 except ExpatError, e:
175 def from_element(cls, rdf_tag):
176 # the tree is already parsed, so we don't need to worry about Expat errors
178 desc = rdf_tag.find(".//" + RDFNS('Description') )
181 raise NoDublinCore("No DublinCore section found.")
183 for e in desc.getchildren():
184 fv = field_dict.get(e.tag, [])
186 field_dict[e.tag] = fv
188 return cls( desc.attrib, field_dict )
190 def __init__(self, rdf_attrs, dc_fields):
191 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
192 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
195 self.about = rdf_attrs.get(RDFNS('about'))
198 for field in self.FIELDS:
199 value = field.validate( dc_fields )
200 setattr(self, 'prop_' + field.name, value)
201 self.fmap[field.name] = field
202 if field.salias: self.fmap[field.salias] = field
204 def __getattribute__(self, name):
206 field = object.__getattribute__(self, 'fmap')[name]
207 value = object.__getattribute__(self, 'prop_'+field.name)
208 if field.name == name:
210 else: # singular alias
211 if not field.multiple:
212 raise "OUCH!! for field %s" % name
215 except (KeyError, AttributeError):
216 return object.__getattribute__(self, name)
218 def __setattr__(self, name, newvalue):
220 field = object.__getattribute__(self, 'fmap')[name]
221 if field.name == name:
222 object.__setattr__(self, 'prop_'+field.name, newvalue)
223 else: # singular alias
224 if not field.multiple:
225 raise "OUCH! while setting field %s" % name
227 object.__setattr__(self, 'prop_'+field.name, [newvalue])
228 except (KeyError, AttributeError):
229 return object.__setattr__(self, name, newvalue)
231 def update(self, field_dict):
232 """Update using field_dict. Verify correctness, but don't check if all
233 required fields are present."""
234 for field in self.FIELDS:
235 if field_dict.has_key(field.name):
236 setattr(self, field.name, field_dict[field.name])
238 def to_etree(self, parent = None):
239 """XML representation of this object."""
240 #etree._namespace_map[str(self.RDF)] = 'rdf'
241 #etree._namespace_map[str(self.DC)] = 'dc'
244 root = etree.Element(RDFNS('RDF'))
246 root = parent.makeelement(RDFNS('RDF'))
248 description = etree.SubElement(root, RDFNS('Description'))
251 description.set(RDFNS('about'), self.about)
253 for field in self.FIELDS:
254 v = getattr(self, field.name, None)
257 if len(v) == 0: continue
259 e = etree.Element(field.uri)
261 description.append(e)
263 e = etree.Element(field.uri)
265 description.append(e)
272 rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
275 for field in self.FIELDS:
276 v = getattr(self, field.name, None)
279 if len(v) == 0: continue
280 v = [ unicode(x) for x in v if v is not None ]
284 dc[field.name] = {'uri': field.uri, 'value': v}
289 result = {'about': self.about}
290 for field in self.FIELDS:
291 v = getattr(self, field.name, None)
295 if len(v) == 0: continue
296 v = [ unicode(x) for x in v if v is not None ]
299 result[field.name] = v
302 v = getattr(self, field.salias)
303 if v is not None: result[field.salias] = unicode(v)
307 def parse(file_name):
308 return BookInfo.from_file(file_name)