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("Multiple 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'),
137 Field( DCNS('description'), 'description', required=False),
142 return self.url.rsplit('/', 1)[1]
145 def from_string(cls, xml):
146 from StringIO import StringIO
147 return cls.from_file(StringIO(xml))
150 def from_file(cls, xmlfile):
153 iter = etree.iterparse(xmlfile, ['start', 'end'])
154 for (event, element) in iter:
155 if element.tag == RDFNS('RDF') and event == 'start':
160 raise NoDublinCore("DublinCore section not found. \
161 Check if there are rdf:RDF and rdf:Description tags.")
163 # continue 'till the end of RDF section
164 for (event, element) in iter:
165 if element.tag == RDFNS('RDF') and event == 'end':
168 # if there is no end, Expat should yell at us with an ExpatError
170 # extract data from the element and make the info
171 return cls.from_element(desc_tag)
172 except XMLSyntaxError, e:
174 except ExpatError, e:
178 def from_element(cls, rdf_tag):
179 # the tree is already parsed, so we don't need to worry about Expat errors
181 desc = rdf_tag.find(".//" + RDFNS('Description') )
184 raise NoDublinCore("No DublinCore section found.")
186 for e in desc.getchildren():
187 fv = field_dict.get(e.tag, [])
189 field_dict[e.tag] = fv
191 return cls( desc.attrib, field_dict )
193 def __init__(self, rdf_attrs, dc_fields):
194 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
195 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
198 self.about = rdf_attrs.get(RDFNS('about'))
201 for field in self.FIELDS:
202 value = field.validate( dc_fields )
203 setattr(self, 'prop_' + field.name, value)
204 self.fmap[field.name] = field
205 if field.salias: self.fmap[field.salias] = field
207 def __getattribute__(self, name):
209 field = object.__getattribute__(self, 'fmap')[name]
210 value = object.__getattribute__(self, 'prop_'+field.name)
211 if field.name == name:
213 else: # singular alias
214 if not field.multiple:
215 raise "OUCH!! for field %s" % name
218 except (KeyError, AttributeError):
219 return object.__getattribute__(self, name)
221 def __setattr__(self, name, newvalue):
223 field = object.__getattribute__(self, 'fmap')[name]
224 if field.name == name:
225 object.__setattr__(self, 'prop_'+field.name, newvalue)
226 else: # singular alias
227 if not field.multiple:
228 raise "OUCH! while setting field %s" % name
230 object.__setattr__(self, 'prop_'+field.name, [newvalue])
231 except (KeyError, AttributeError):
232 return object.__setattr__(self, name, newvalue)
234 def update(self, field_dict):
235 """Update using field_dict. Verify correctness, but don't check if all
236 required fields are present."""
237 for field in self.FIELDS:
238 if field_dict.has_key(field.name):
239 setattr(self, field.name, field_dict[field.name])
241 def to_etree(self, parent = None):
242 """XML representation of this object."""
243 #etree._namespace_map[str(self.RDF)] = 'rdf'
244 #etree._namespace_map[str(self.DC)] = 'dc'
247 root = etree.Element(RDFNS('RDF'))
249 root = parent.makeelement(RDFNS('RDF'))
251 description = etree.SubElement(root, RDFNS('Description'))
254 description.set(RDFNS('about'), self.about)
256 for field in self.FIELDS:
257 v = getattr(self, field.name, None)
260 if len(v) == 0: continue
262 e = etree.Element(field.uri)
264 description.append(e)
266 e = etree.Element(field.uri)
268 description.append(e)
275 rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
278 for field in self.FIELDS:
279 v = getattr(self, field.name, None)
282 if len(v) == 0: continue
283 v = [ unicode(x) for x in v if v is not None ]
287 dc[field.name] = {'uri': field.uri, 'value': v}
292 result = {'about': self.about}
293 for field in self.FIELDS:
294 v = getattr(self, field.name, None)
298 if len(v) == 0: continue
299 v = [ unicode(x) for x in v if v is not None ]
302 result[field.name] = v
305 v = getattr(self, field.salias)
306 if v is not None: result[field.salias] = unicode(v)
310 def parse(file_name):
311 return BookInfo.from_file(file_name)