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)
41 def __eq__(self, right):
42 return self.last_name == right.last_name and self.first_names == right.first_names
45 def __unicode__(self):
46 if len(self.first_names) > 0:
47 return '%s, %s' % (self.last_name, ' '.join(self.first_names))
52 return 'Person(last_name=%r, first_names=*%r)' % (self.last_name, self.first_names)
57 t = time.strptime(text, '%Y-%m-%d')
59 t = time.strptime(text, '%Y')
60 return date(t[0], t[1], t[2])
62 raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
65 return Person.from_text(text)
68 if isinstance(text, unicode):
71 return text.decode('utf-8')
74 def __init__(self, uri, attr_name, type=as_unicode, multiple=False, salias=None, **kwargs):
78 self.multiple = multiple
81 self.required = kwargs.get('required', True) and not kwargs.has_key('default')
82 self.default = kwargs.get('default', [] if multiple else [None])
84 def validate_value(self, val):
87 if self.validator is None:
89 return [ self.validator(v) if v is not None else v for v in val ]
91 raise ValidationError("Mulitply values not allowed for field '%s'" % self.uri)
93 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
95 if self.validator is None or val[0] is None:
97 return self.validator(val[0])
99 raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
101 def validate(self, fdict):
102 if not fdict.has_key(self.uri):
103 if not self.required:
106 raise ValidationError("Required field %s not found" % self.uri)
110 return self.validate_value(f)
115 class BookInfo(object):
117 Field( DCNS('creator'), 'author', as_person),
118 Field( DCNS('title'), 'title'),
119 Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True),
120 Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True),
121 Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True),
122 Field( DCNS('date'), 'created_at', as_date),
123 Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
124 Field( DCNS('contributor.editor'), 'editors', \
125 as_person, salias='editor', multiple=True, default=[]),
126 Field( DCNS('contributor.translator'), 'translators', \
127 as_person, salias='translator', multiple=True, default=[]),
128 Field( DCNS('contributor.technical_editor'), 'technical_editors',
129 as_person, salias='technical_editor', multiple=True, default=[]),
130 Field( DCNS('publisher'), 'publisher'),
131 Field( DCNS('source'), 'source_name', required=False),
132 Field( DCNS('source.URL'), 'source_url', required=False),
133 Field( DCNS('identifier.url'), 'url'),
134 Field( DCNS('relation.hasPart'), 'parts', multiple=True, required=False),
135 Field( DCNS('rights.license'), 'license', required=False),
136 Field( DCNS('rights'), 'license_description'),
141 return self.url.rsplit('/', 1)[1]
144 def from_string(cls, xml):
145 from StringIO import StringIO
146 return cls.from_file(StringIO(xml))
149 def from_file(cls, xmlfile):
152 iter = etree.iterparse(xmlfile, ['start', 'end'])
153 for (event, element) in iter:
154 if element.tag == RDFNS('RDF') and event == 'start':
159 raise NoDublinCore("DublinCore section not found. \
160 Check if there are rdf:RDF and rdf:Description tags.")
162 # continue 'till the end of RDF section
163 for (event, element) in iter:
164 if element.tag == RDFNS('RDF') and event == 'end':
167 # if there is no end, Expat should yell at us with an ExpatError
169 # extract data from the element and make the info
170 return cls.from_element(desc_tag)
171 except XMLSyntaxError, e:
173 except ExpatError, e:
177 def from_element(cls, rdf_tag):
178 # the tree is already parsed, so we don't need to worry about Expat errors
180 desc = rdf_tag.find(".//" + RDFNS('Description') )
183 raise NoDublinCore("No DublinCore section found.")
185 for e in desc.getchildren():
186 fv = field_dict.get(e.tag, [])
188 field_dict[e.tag] = fv
190 return cls( desc.attrib, field_dict )
192 def __init__(self, rdf_attrs, dc_fields):
193 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
194 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
197 self.about = rdf_attrs.get(RDFNS('about'))
200 for field in self.FIELDS:
201 value = field.validate( dc_fields )
202 setattr(self, 'prop_' + field.name, value)
203 self.fmap[field.name] = field
204 if field.salias: self.fmap[field.salias] = field
206 def __getattribute__(self, name):
208 field = object.__getattribute__(self, 'fmap')[name]
209 value = object.__getattribute__(self, 'prop_'+field.name)
210 if field.name == name:
212 else: # singular alias
213 if not field.multiple:
214 raise "OUCH!! for field %s" % name
217 except (KeyError, AttributeError):
218 return object.__getattribute__(self, name)
220 def __setattr__(self, name, newvalue):
222 field = object.__getattribute__(self, 'fmap')[name]
223 if field.name == name:
224 object.__setattr__(self, 'prop_'+field.name, newvalue)
225 else: # singular alias
226 if not field.multiple:
227 raise "OUCH! while setting field %s" % name
229 object.__setattr__(self, 'prop_'+field.name, [newvalue])
230 except (KeyError, AttributeError):
231 return object.__setattr__(self, name, newvalue)
233 def update(self, field_dict):
234 """Update using field_dict. Verify correctness, but don't check if all
235 required fields are present."""
236 for field in self.FIELDS:
237 if field_dict.has_key(field.name):
238 setattr(self, field.name, field_dict[field.name])
240 def to_etree(self, parent = None):
241 """XML representation of this object."""
242 #etree._namespace_map[str(self.RDF)] = 'rdf'
243 #etree._namespace_map[str(self.DC)] = 'dc'
246 root = etree.Element(RDFNS('RDF'))
248 root = parent.makeelement(RDFNS('RDF'))
250 description = etree.SubElement(root, RDFNS('Description'))
253 description.set(RDFNS('about'), self.about)
255 for field in self.FIELDS:
256 v = getattr(self, field.name, None)
259 if len(v) == 0: continue
261 e = etree.Element(field.uri)
263 description.append(e)
265 e = etree.Element(field.uri)
267 description.append(e)
274 rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
277 for field in self.FIELDS:
278 v = getattr(self, field.name, None)
281 if len(v) == 0: continue
282 v = [ unicode(x) for x in v if v is not None ]
286 dc[field.name] = {'uri': field.uri, 'value': v}
291 result = {'about': self.about}
292 for field in self.FIELDS:
293 v = getattr(self, field.name, None)
297 if len(v) == 0: continue
298 v = [ unicode(x) for x in v if v is not None ]
301 result[field.name] = v
304 v = getattr(self, field.salias)
305 if v is not None: result[field.salias] = unicode(v)
309 def parse(file_name):
310 return BookInfo.from_file(file_name)