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,
13 import lxml.etree as etree # ElementTree API using libxml2
14 from lxml.etree import XMLSyntaxError
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
27 def from_text(cls, text):
28 parts = [ token.strip() for token in text.split(',') ]
33 raise ValueError("Invalid person name. There should be at most one comma: \"%s\"." % text)
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)
43 return u" ".join(self.first_names + (self.last_name,))
45 def __eq__(self, right):
46 return self.last_name == right.last_name and self.first_names == right.first_names
48 def __cmp__(self, other):
49 return cmp((self.last_name, self.first_names), (other.last_name, other.first_names))
52 return hash((self.last_name, self.first_names))
54 def __unicode__(self):
55 if len(self.first_names) > 0:
56 return '%s, %s' % (self.last_name, ' '.join(self.first_names))
61 return 'Person(last_name=%r, first_names=*%r)' % (self.last_name, self.first_names)
66 t = time.strptime(text, '%Y-%m-%d')
68 t = time.strptime(text, '%Y')
69 return date(t[0], t[1], t[2])
71 raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
74 return Person.from_text(text)
77 if isinstance(text, unicode):
80 return text.decode('utf-8')
83 def __init__(self, uri, attr_name, type=as_unicode, multiple=False, salias=None, **kwargs):
87 self.multiple = multiple
90 self.required = kwargs.get('required', True) and not kwargs.has_key('default')
91 self.default = kwargs.get('default', [] if multiple else [None])
93 def validate_value(self, val):
96 if self.validator is None:
98 return [ self.validator(v) if v is not None else v for v in val ]
100 raise ValidationError("Multiple values not allowed for field '%s'" % self.uri)
102 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
104 if self.validator is None or val[0] is None:
106 return self.validator(val[0])
107 except ValueError, e:
108 raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
110 def validate(self, fdict):
111 if not fdict.has_key(self.uri):
112 if not self.required:
115 raise ValidationError("Required field %s not found" % self.uri)
119 return self.validate_value(f)
124 class BookInfo(object):
126 Field( DCNS('creator'), 'author', as_person),
127 Field( DCNS('title'), 'title'),
128 Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True),
129 Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True),
130 Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True),
131 Field( DCNS('audience'), 'audiences', salias='audience', multiple=True,
133 Field( DCNS('date'), 'created_at', as_date),
134 Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
135 Field( DCNS('contributor.editor'), 'editors', \
136 as_person, salias='editor', multiple=True, default=[]),
137 Field( DCNS('contributor.translator'), 'translators', \
138 as_person, salias='translator', multiple=True, default=[]),
139 Field( DCNS('contributor.technical_editor'), 'technical_editors',
140 as_person, salias='technical_editor', multiple=True, default=[]),
141 Field( DCNS('publisher'), 'publisher'),
142 Field( DCNS('source'), 'source_name', required=False),
143 Field( DCNS('source.URL'), 'source_url', required=False),
144 Field( DCNS('identifier.url'), 'url', WLURI),
145 Field( DCNS('relation.hasPart'), 'parts', multiple=True, required=False),
146 Field( DCNS('rights.license'), 'license', required=False),
147 Field( DCNS('rights'), 'license_description'),
148 Field( DCNS('language'), 'language'),
149 Field( DCNS('description'), 'description', required=False),
153 def from_string(cls, xml):
154 from StringIO import StringIO
155 return cls.from_file(StringIO(xml))
158 def from_file(cls, xmlfile):
161 iter = etree.iterparse(xmlfile, ['start', 'end'])
162 for (event, element) in iter:
163 if element.tag == RDFNS('RDF') and event == 'start':
168 raise NoDublinCore("DublinCore section not found. \
169 Check if there are rdf:RDF and rdf:Description tags.")
171 # continue 'till the end of RDF section
172 for (event, element) in iter:
173 if element.tag == RDFNS('RDF') and event == 'end':
176 # if there is no end, Expat should yell at us with an ExpatError
178 # extract data from the element and make the info
179 return cls.from_element(desc_tag)
180 except XMLSyntaxError, e:
182 except ExpatError, e:
186 def from_element(cls, rdf_tag):
187 # the tree is already parsed, so we don't need to worry about Expat errors
189 desc = rdf_tag.find(".//" + RDFNS('Description') )
192 raise NoDublinCore("No DublinCore section found.")
194 for e in desc.getchildren():
195 fv = field_dict.get(e.tag, [])
197 field_dict[e.tag] = fv
199 return cls( desc.attrib, field_dict )
201 def __init__(self, rdf_attrs, dc_fields):
202 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
203 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
206 self.about = rdf_attrs.get(RDFNS('about'))
209 for field in self.FIELDS:
210 value = field.validate( dc_fields )
211 setattr(self, 'prop_' + field.name, value)
212 self.fmap[field.name] = field
213 if field.salias: self.fmap[field.salias] = field
218 self.url.validate_language(self.language)
220 def __getattribute__(self, name):
222 field = object.__getattribute__(self, 'fmap')[name]
223 value = object.__getattribute__(self, 'prop_'+field.name)
224 if field.name == name:
226 else: # singular alias
227 if not field.multiple:
228 raise "OUCH!! for field %s" % name
231 except (KeyError, AttributeError):
232 return object.__getattribute__(self, name)
234 def __setattr__(self, name, newvalue):
236 field = object.__getattribute__(self, 'fmap')[name]
237 if field.name == name:
238 object.__setattr__(self, 'prop_'+field.name, newvalue)
239 else: # singular alias
240 if not field.multiple:
241 raise "OUCH! while setting field %s" % name
243 object.__setattr__(self, 'prop_'+field.name, [newvalue])
244 except (KeyError, AttributeError):
245 return object.__setattr__(self, name, newvalue)
247 def update(self, field_dict):
248 """Update using field_dict. Verify correctness, but don't check if all
249 required fields are present."""
250 for field in self.FIELDS:
251 if field_dict.has_key(field.name):
252 setattr(self, field.name, field_dict[field.name])
254 def to_etree(self, parent = None):
255 """XML representation of this object."""
256 #etree._namespace_map[str(self.RDF)] = 'rdf'
257 #etree._namespace_map[str(self.DC)] = 'dc'
260 root = etree.Element(RDFNS('RDF'))
262 root = parent.makeelement(RDFNS('RDF'))
264 description = etree.SubElement(root, RDFNS('Description'))
267 description.set(RDFNS('about'), self.about)
269 for field in self.FIELDS:
270 v = getattr(self, field.name, None)
273 if len(v) == 0: continue
275 e = etree.Element(field.uri)
278 description.append(e)
280 e = etree.Element(field.uri)
282 description.append(e)
289 rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
292 for field in self.FIELDS:
293 v = getattr(self, field.name, None)
296 if len(v) == 0: continue
297 v = [ unicode(x) for x in v if x is not None ]
301 dc[field.name] = {'uri': field.uri, 'value': v}
306 result = {'about': self.about}
307 for field in self.FIELDS:
308 v = getattr(self, field.name, None)
312 if len(v) == 0: continue
313 v = [ unicode(x) for x in v if x is not None ]
316 result[field.name] = v
319 v = getattr(self, field.salias)
320 if v is not None: result[field.salias] = unicode(v)
324 def parse(file_name):
325 return BookInfo.from_file(file_name)