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('description'), 'description', required=False),
152 return self.url.rsplit('/', 1)[1]
155 def from_string(cls, xml):
156 from StringIO import StringIO
157 return cls.from_file(StringIO(xml))
160 def from_file(cls, xmlfile):
163 iter = etree.iterparse(xmlfile, ['start', 'end'])
164 for (event, element) in iter:
165 if element.tag == RDFNS('RDF') and event == 'start':
170 raise NoDublinCore("DublinCore section not found. \
171 Check if there are rdf:RDF and rdf:Description tags.")
173 # continue 'till the end of RDF section
174 for (event, element) in iter:
175 if element.tag == RDFNS('RDF') and event == 'end':
178 # if there is no end, Expat should yell at us with an ExpatError
180 # extract data from the element and make the info
181 return cls.from_element(desc_tag)
182 except XMLSyntaxError, e:
184 except ExpatError, e:
188 def from_element(cls, rdf_tag):
189 # the tree is already parsed, so we don't need to worry about Expat errors
191 desc = rdf_tag.find(".//" + RDFNS('Description') )
194 raise NoDublinCore("No DublinCore section found.")
196 for e in desc.getchildren():
197 fv = field_dict.get(e.tag, [])
199 field_dict[e.tag] = fv
201 return cls( desc.attrib, field_dict )
203 def __init__(self, rdf_attrs, dc_fields):
204 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
205 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
208 self.about = rdf_attrs.get(RDFNS('about'))
211 for field in self.FIELDS:
212 value = field.validate( dc_fields )
213 setattr(self, 'prop_' + field.name, value)
214 self.fmap[field.name] = field
215 if field.salias: self.fmap[field.salias] = field
217 def __getattribute__(self, name):
219 field = object.__getattribute__(self, 'fmap')[name]
220 value = object.__getattribute__(self, 'prop_'+field.name)
221 if field.name == name:
223 else: # singular alias
224 if not field.multiple:
225 raise "OUCH!! for field %s" % name
228 except (KeyError, AttributeError):
229 return object.__getattribute__(self, name)
231 def __setattr__(self, name, newvalue):
233 field = object.__getattribute__(self, 'fmap')[name]
234 if field.name == name:
235 object.__setattr__(self, 'prop_'+field.name, newvalue)
236 else: # singular alias
237 if not field.multiple:
238 raise "OUCH! while setting field %s" % name
240 object.__setattr__(self, 'prop_'+field.name, [newvalue])
241 except (KeyError, AttributeError):
242 return object.__setattr__(self, name, newvalue)
244 def update(self, field_dict):
245 """Update using field_dict. Verify correctness, but don't check if all
246 required fields are present."""
247 for field in self.FIELDS:
248 if field_dict.has_key(field.name):
249 setattr(self, field.name, field_dict[field.name])
251 def to_etree(self, parent = None):
252 """XML representation of this object."""
253 #etree._namespace_map[str(self.RDF)] = 'rdf'
254 #etree._namespace_map[str(self.DC)] = 'dc'
257 root = etree.Element(RDFNS('RDF'))
259 root = parent.makeelement(RDFNS('RDF'))
261 description = etree.SubElement(root, RDFNS('Description'))
264 description.set(RDFNS('about'), self.about)
266 for field in self.FIELDS:
267 v = getattr(self, field.name, None)
270 if len(v) == 0: continue
272 e = etree.Element(field.uri)
275 description.append(e)
277 e = etree.Element(field.uri)
279 description.append(e)
286 rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
289 for field in self.FIELDS:
290 v = getattr(self, field.name, None)
293 if len(v) == 0: continue
294 v = [ unicode(x) for x in v if x is not None ]
298 dc[field.name] = {'uri': field.uri, 'value': v}
303 result = {'about': self.about}
304 for field in self.FIELDS:
305 v = getattr(self, field.name, None)
309 if len(v) == 0: continue
310 v = [ unicode(x) for x in v if x is not None ]
313 result[field.name] = v
316 v = getattr(self, field.salias)
317 if v is not None: result[field.salias] = unicode(v)
321 def parse(file_name):
322 return BookInfo.from_file(file_name)