1 # -*- coding: utf-8 -*-
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 from xml.parsers.expat import ExpatError
7 from datetime import date
10 from librarian import ValidationError, NoDublinCore, ParseError, DCNS, RDFNS
12 import lxml.etree as etree # ElementTree API using libxml2
13 from lxml.etree import XMLSyntaxError
20 """Single person with last name and a list of first names."""
21 def __init__(self, last_name, *first_names):
22 self.last_name = last_name
23 self.first_names = first_names
26 def from_text(cls, text):
27 parts = [ token.strip() for token in text.split(',') ]
32 raise ValueError("Invalid person name. There should be at most one comma: \"%s\"." % text)
35 if len(parts[1]) == 0:
36 # there is no non-whitespace data after the comma
37 raise ValueError("Found a comma, but no names given: \"%s\" -> %r." % (text, parts))
38 names = [ name for name in parts[1].split() if len(name) ] # all non-whitespace tokens
39 return cls(surname, *names)
42 return u" ".join(self.first_names + (self.last_name,))
44 def __eq__(self, right):
45 return self.last_name == right.last_name and self.first_names == right.first_names
47 def __cmp__(self, other):
48 return cmp((self.last_name, self.first_names), (other.last_name, other.first_names))
51 return hash((self.last_name, self.first_names))
53 def __unicode__(self):
54 if len(self.first_names) > 0:
55 return '%s, %s' % (self.last_name, ' '.join(self.first_names))
60 return 'Person(last_name=%r, first_names=*%r)' % (self.last_name, self.first_names)
65 t = time.strptime(text, '%Y-%m-%d')
67 t = time.strptime(text, '%Y')
68 return date(t[0], t[1], t[2])
70 raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
73 return Person.from_text(text)
76 if isinstance(text, unicode):
79 return text.decode('utf-8')
82 def __init__(self, uri, attr_name, type=as_unicode, multiple=False, salias=None, **kwargs):
86 self.multiple = multiple
89 self.required = kwargs.get('required', True) and not kwargs.has_key('default')
90 self.default = kwargs.get('default', [] if multiple else [None])
92 def validate_value(self, val):
95 if self.validator is None:
97 return [ self.validator(v) if v is not None else v for v in val ]
99 raise ValidationError("Multiple values not allowed for field '%s'" % self.uri)
101 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
103 if self.validator is None or val[0] is None:
105 return self.validator(val[0])
106 except ValueError, e:
107 raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
109 def validate(self, fdict):
110 if not fdict.has_key(self.uri):
111 if not self.required:
114 raise ValidationError("Required field %s not found" % self.uri)
118 return self.validate_value(f)
123 class BookInfo(object):
125 Field( DCNS('creator'), 'author', as_person),
126 Field( DCNS('title'), 'title'),
127 Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True),
128 Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True),
129 Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True),
130 Field( DCNS('audience'), 'audiences', salias='audience', multiple=True,
132 Field( DCNS('date'), 'created_at', as_date),
133 Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
134 Field( DCNS('contributor.editor'), 'editors', \
135 as_person, salias='editor', multiple=True, default=[]),
136 Field( DCNS('contributor.translator'), 'translators', \
137 as_person, salias='translator', multiple=True, default=[]),
138 Field( DCNS('contributor.technical_editor'), 'technical_editors',
139 as_person, salias='technical_editor', multiple=True, default=[]),
140 Field( DCNS('publisher'), 'publisher'),
141 Field( DCNS('source'), 'source_name', required=False),
142 Field( DCNS('source.URL'), 'source_url', required=False),
143 Field( DCNS('identifier.url'), 'url'),
144 Field( DCNS('relation.hasPart'), 'parts', multiple=True, required=False),
145 Field( DCNS('rights.license'), 'license', required=False),
146 Field( DCNS('rights'), 'license_description'),
147 Field( DCNS('language'), 'language'),
148 Field( DCNS('description'), 'description', required=False),
153 return self.url.rsplit('/', 1)[1]
156 def from_string(cls, xml):
157 from StringIO import StringIO
158 return cls.from_file(StringIO(xml))
161 def from_file(cls, xmlfile):
164 iter = etree.iterparse(xmlfile, ['start', 'end'])
165 for (event, element) in iter:
166 if element.tag == RDFNS('RDF') and event == 'start':
171 raise NoDublinCore("DublinCore section not found. \
172 Check if there are rdf:RDF and rdf:Description tags.")
174 # continue 'till the end of RDF section
175 for (event, element) in iter:
176 if element.tag == RDFNS('RDF') and event == 'end':
179 # if there is no end, Expat should yell at us with an ExpatError
181 # extract data from the element and make the info
182 return cls.from_element(desc_tag)
183 except XMLSyntaxError, e:
185 except ExpatError, e:
189 def from_element(cls, rdf_tag):
190 # the tree is already parsed, so we don't need to worry about Expat errors
192 desc = rdf_tag.find(".//" + RDFNS('Description') )
195 raise NoDublinCore("No DublinCore section found.")
197 for e in desc.getchildren():
198 fv = field_dict.get(e.tag, [])
200 field_dict[e.tag] = fv
202 return cls( desc.attrib, field_dict )
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
209 self.about = rdf_attrs.get(RDFNS('about'))
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
218 def __getattribute__(self, name):
220 field = object.__getattribute__(self, 'fmap')[name]
221 value = object.__getattribute__(self, 'prop_'+field.name)
222 if field.name == name:
224 else: # singular alias
225 if not field.multiple:
226 raise "OUCH!! for field %s" % name
229 except (KeyError, AttributeError):
230 return object.__getattribute__(self, name)
232 def __setattr__(self, name, newvalue):
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
241 object.__setattr__(self, 'prop_'+field.name, [newvalue])
242 except (KeyError, AttributeError):
243 return object.__setattr__(self, name, newvalue)
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])
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'
258 root = etree.Element(RDFNS('RDF'))
260 root = parent.makeelement(RDFNS('RDF'))
262 description = etree.SubElement(root, RDFNS('Description'))
265 description.set(RDFNS('about'), self.about)
267 for field in self.FIELDS:
268 v = getattr(self, field.name, None)
271 if len(v) == 0: continue
273 e = etree.Element(field.uri)
276 description.append(e)
278 e = etree.Element(field.uri)
280 description.append(e)
287 rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
290 for field in self.FIELDS:
291 v = getattr(self, field.name, None)
294 if len(v) == 0: continue
295 v = [ unicode(x) for x in v if x is not None ]
299 dc[field.name] = {'uri': field.uri, 'value': v}
304 result = {'about': self.about}
305 for field in self.FIELDS:
306 v = getattr(self, field.name, None)
310 if len(v) == 0: continue
311 v = [ unicode(x) for x in v if x is not None ]
314 result[field.name] = v
317 v = getattr(self, field.salias)
318 if v is not None: result[field.salias] = unicode(v)
322 def parse(file_name):
323 return BookInfo.from_file(file_name)