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
48 def __unicode__(self):
49 if len(self.first_names) > 0:
50 return '%s, %s' % (self.last_name, ' '.join(self.first_names))
55 return 'Person(last_name=%r, first_names=*%r)' % (self.last_name, self.first_names)
60 t = time.strptime(text, '%Y-%m-%d')
62 t = time.strptime(text, '%Y')
63 return date(t[0], t[1], t[2])
65 raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
68 return Person.from_text(text)
71 if isinstance(text, unicode):
74 return text.decode('utf-8')
77 def __init__(self, uri, attr_name, type=as_unicode, multiple=False, salias=None, **kwargs):
81 self.multiple = multiple
84 self.required = kwargs.get('required', True) and not kwargs.has_key('default')
85 self.default = kwargs.get('default', [] if multiple else [None])
87 def validate_value(self, val):
90 if self.validator is None:
92 return [ self.validator(v) if v is not None else v for v in val ]
94 raise ValidationError("Multiple values not allowed for field '%s'" % self.uri)
96 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
98 if self.validator is None or val[0] is None:
100 return self.validator(val[0])
101 except ValueError, e:
102 raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
104 def validate(self, fdict):
105 if not fdict.has_key(self.uri):
106 if not self.required:
109 raise ValidationError("Required field %s not found" % self.uri)
113 return self.validate_value(f)
118 class BookInfo(object):
120 Field( DCNS('creator'), 'author', as_person),
121 Field( DCNS('title'), 'title'),
122 Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True),
123 Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True),
124 Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True),
125 Field( DCNS('date'), 'created_at', as_date),
126 Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
127 Field( DCNS('contributor.editor'), 'editors', \
128 as_person, salias='editor', multiple=True, default=[]),
129 Field( DCNS('contributor.translator'), 'translators', \
130 as_person, salias='translator', multiple=True, default=[]),
131 Field( DCNS('contributor.technical_editor'), 'technical_editors',
132 as_person, salias='technical_editor', multiple=True, default=[]),
133 Field( DCNS('publisher'), 'publisher'),
134 Field( DCNS('source'), 'source_name', required=False),
135 Field( DCNS('source.URL'), 'source_url', required=False),
136 Field( DCNS('identifier.url'), 'url'),
137 Field( DCNS('relation.hasPart'), 'parts', multiple=True, required=False),
138 Field( DCNS('rights.license'), 'license', required=False),
139 Field( DCNS('rights'), 'license_description'),
140 Field( DCNS('description'), 'description', required=False),
145 return self.url.rsplit('/', 1)[1]
148 def from_string(cls, xml):
149 from StringIO import StringIO
150 return cls.from_file(StringIO(xml))
153 def from_file(cls, xmlfile):
156 iter = etree.iterparse(xmlfile, ['start', 'end'])
157 for (event, element) in iter:
158 if element.tag == RDFNS('RDF') and event == 'start':
163 raise NoDublinCore("DublinCore section not found. \
164 Check if there are rdf:RDF and rdf:Description tags.")
166 # continue 'till the end of RDF section
167 for (event, element) in iter:
168 if element.tag == RDFNS('RDF') and event == 'end':
171 # if there is no end, Expat should yell at us with an ExpatError
173 # extract data from the element and make the info
174 return cls.from_element(desc_tag)
175 except XMLSyntaxError, e:
177 except ExpatError, e:
181 def from_element(cls, rdf_tag):
182 # the tree is already parsed, so we don't need to worry about Expat errors
184 desc = rdf_tag.find(".//" + RDFNS('Description') )
187 raise NoDublinCore("No DublinCore section found.")
189 for e in desc.getchildren():
190 fv = field_dict.get(e.tag, [])
192 field_dict[e.tag] = fv
194 return cls( desc.attrib, field_dict )
196 def __init__(self, rdf_attrs, dc_fields):
197 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
198 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
201 self.about = rdf_attrs.get(RDFNS('about'))
204 for field in self.FIELDS:
205 value = field.validate( dc_fields )
206 setattr(self, 'prop_' + field.name, value)
207 self.fmap[field.name] = field
208 if field.salias: self.fmap[field.salias] = field
210 def __getattribute__(self, name):
212 field = object.__getattribute__(self, 'fmap')[name]
213 value = object.__getattribute__(self, 'prop_'+field.name)
214 if field.name == name:
216 else: # singular alias
217 if not field.multiple:
218 raise "OUCH!! for field %s" % name
221 except (KeyError, AttributeError):
222 return object.__getattribute__(self, name)
224 def __setattr__(self, name, newvalue):
226 field = object.__getattribute__(self, 'fmap')[name]
227 if field.name == name:
228 object.__setattr__(self, 'prop_'+field.name, newvalue)
229 else: # singular alias
230 if not field.multiple:
231 raise "OUCH! while setting field %s" % name
233 object.__setattr__(self, 'prop_'+field.name, [newvalue])
234 except (KeyError, AttributeError):
235 return object.__setattr__(self, name, newvalue)
237 def update(self, field_dict):
238 """Update using field_dict. Verify correctness, but don't check if all
239 required fields are present."""
240 for field in self.FIELDS:
241 if field_dict.has_key(field.name):
242 setattr(self, field.name, field_dict[field.name])
244 def to_etree(self, parent = None):
245 """XML representation of this object."""
246 #etree._namespace_map[str(self.RDF)] = 'rdf'
247 #etree._namespace_map[str(self.DC)] = 'dc'
250 root = etree.Element(RDFNS('RDF'))
252 root = parent.makeelement(RDFNS('RDF'))
254 description = etree.SubElement(root, RDFNS('Description'))
257 description.set(RDFNS('about'), self.about)
259 for field in self.FIELDS:
260 v = getattr(self, field.name, None)
263 if len(v) == 0: continue
265 e = etree.Element(field.uri)
267 description.append(e)
269 e = etree.Element(field.uri)
271 description.append(e)
278 rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
281 for field in self.FIELDS:
282 v = getattr(self, field.name, None)
285 if len(v) == 0: continue
286 v = [ unicode(x) for x in v if v is not None ]
290 dc[field.name] = {'uri': field.uri, 'value': v}
295 result = {'about': self.about}
296 for field in self.FIELDS:
297 v = getattr(self, field.name, None)
301 if len(v) == 0: continue
302 v = [ unicode(x) for x in v if v is not None ]
305 result[field.name] = v
308 v = getattr(self, field.salias)
309 if v is not None: result[field.salias] = unicode(v)
313 def parse(file_name):
314 return BookInfo.from_file(file_name)