1 # -*- coding: utf-8 -*-
2 from xml.parsers.expat import ExpatError
3 from datetime import date
6 from librarian import ValidationError, NoDublinCore, ParseError, DCNS, RDFNS
8 import lxml.etree as etree # ElementTree API using libxml2
9 from lxml.etree import XMLSyntaxError
16 """Single person with last name and a list of first names."""
17 def __init__(self, last_name, *first_names):
18 self.last_name = last_name
19 self.first_names = first_names
22 def from_text(cls, text):
23 parts = [ token.strip() for token in text.split(',') ]
28 raise ValueError("Invalid person name. There should be at most one comma: \"%s\"." % text)
31 if len(parts[1]) == 0:
32 # there is no non-whitespace data after the comma
33 raise ValueError("Found a comma, but no names given: \"%s\" -> %r." % (text, parts))
34 names = [ name for name in parts[1].split() if len(name) ] # all non-whitespace tokens
35 return cls(surname, *names)
37 def __eq__(self, right):
38 return self.last_name == right.last_name and self.first_names == right.first_names
41 def __unicode__(self):
42 if len(self.first_names) > 0:
43 return '%s, %s' % (self.last_name, ' '.join(self.first_names))
48 return 'Person(last_name=%r, first_names=*%r)' % (self.last_name, self.first_names)
53 t = time.strptime(text, '%Y-%m-%d')
55 t = time.strptime(text, '%Y')
56 return date(t[0], t[1], t[2])
58 raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
61 return Person.from_text(text)
64 if isinstance(text, unicode):
67 return text.decode('utf-8')
70 def __init__(self, uri, attr_name, type=as_unicode, multiple=False, salias=None, **kwargs):
74 self.multiple = multiple
77 self.required = kwargs.get('required', True) and not kwargs.has_key('default')
78 self.default = kwargs.get('default', [] if multiple else [None])
80 def validate_value(self, val):
83 if self.validator is None:
85 return [ self.validator(v) if v is not None else v for v in val ]
87 raise ValidationError("Mulitply values not allowed for field '%s'" % self.uri)
89 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
91 if self.validator is None or val[0] is None:
93 return self.validator(val[0])
95 raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
97 def validate(self, fdict):
98 if not fdict.has_key(self.uri):
102 raise ValidationError("Required field %s not found" % self.uri)
106 return self.validate_value(f)
111 class BookInfo(object):
113 Field( DCNS('creator'), 'author', as_person),
114 Field( DCNS('title'), 'title'),
115 Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True),
116 Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True),
117 Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True),
118 Field( DCNS('date'), 'created_at', as_date),
119 Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
120 Field( DCNS('contributor.editor'), 'editors', \
121 as_person, salias='editor', multiple=True, default=[]),
122 Field( DCNS('contributor.translator'), 'translators', \
123 as_person, salias='translator', multiple=True, default=[]),
124 Field( DCNS('contributor.technical_editor'), 'technical_editors',
125 as_person, salias='technical_editor', multiple=True, default=[]),
126 Field( DCNS('publisher'), 'publisher'),
127 Field( DCNS('source'), 'source_name', required=False),
128 Field( DCNS('source.URL'), 'source_url', required=False),
129 Field( DCNS('identifier.url'), 'url'),
130 Field( DCNS('relation.hasPart'), 'parts', multiple=True, required=False),
131 Field( DCNS('rights.license'), 'license', required=False),
132 Field( DCNS('rights'), 'license_description'),
136 def from_string(cls, xml):
137 from StringIO import StringIO
138 return cls.from_file(StringIO(xml))
141 def from_file(cls, xmlfile):
144 iter = etree.iterparse(xmlfile, ['start', 'end'])
145 for (event, element) in iter:
146 if element.tag == RDFNS('RDF') and event == 'start':
151 raise NoDublinCore("DublinCore section not found. \
152 Check if there are rdf:RDF and rdf:Description tags.")
154 # continue 'till the end of RDF section
155 for (event, element) in iter:
156 if element.tag == RDFNS('RDF') and event == 'end':
159 # if there is no end, Expat should yell at us with an ExpatError
161 # extract data from the element and make the info
162 return cls.from_element(desc_tag)
163 except XMLSyntaxError, e:
165 except ExpatError, e:
169 def from_element(cls, rdf_tag):
170 # the tree is already parsed, so we don't need to worry about Expat errors
172 desc = rdf_tag.find(".//" + RDFNS('Description') )
175 raise NoDublinCore("No DublinCore section found.")
177 for e in desc.getchildren():
178 fv = field_dict.get(e.tag, [])
180 field_dict[e.tag] = fv
182 return cls( desc.attrib, field_dict )
184 def __init__(self, rdf_attrs, dc_fields):
185 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
186 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
189 self.about = rdf_attrs.get(RDFNS('about'))
192 for field in self.FIELDS:
193 value = field.validate( dc_fields )
194 setattr(self, 'prop_' + field.name, value)
195 self.fmap[field.name] = field
196 if field.salias: self.fmap[field.salias] = field
198 def __getattribute__(self, name):
200 field = object.__getattribute__(self, 'fmap')[name]
201 value = object.__getattribute__(self, 'prop_'+field.name)
202 if field.name == name:
204 else: # singular alias
205 if not field.multiple:
206 raise "OUCH!! for field %s" % name
209 except (KeyError, AttributeError):
210 return object.__getattribute__(self, name)
212 def __setattr__(self, name, newvalue):
214 field = object.__getattribute__(self, 'fmap')[name]
215 if field.name == name:
216 object.__setattr__(self, 'prop_'+field.name, newvalue)
217 else: # singular alias
218 if not field.multiple:
219 raise "OUCH! while setting field %s" % name
221 object.__setattr__(self, 'prop_'+field.name, [newvalue])
222 except (KeyError, AttributeError):
223 return object.__setattr__(self, name, newvalue)
225 def update(self, field_dict):
226 """Update using field_dict. Verify correctness, but don't check if all
227 required fields are present."""
228 for field in self.FIELDS:
229 if field_dict.has_key(field.name):
230 setattr(self, field.name, field_dict[field.name])
232 def to_etree(self, parent = None):
233 """XML representation of this object."""
234 #etree._namespace_map[str(self.RDF)] = 'rdf'
235 #etree._namespace_map[str(self.DC)] = 'dc'
238 root = etree.Element(RDFNS('RDF'))
240 root = parent.makeelement(RDFNS('RDF'))
242 description = etree.SubElement(root, RDFNS('Description'))
245 description.set(RDFNS('about'), self.about)
247 for field in self.FIELDS:
248 v = getattr(self, field.name, None)
251 if len(v) == 0: continue
253 e = etree.Element(field.uri)
255 description.append(e)
257 e = etree.Element(field.uri)
259 description.append(e)
266 rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
269 for field in self.FIELDS:
270 v = getattr(self, field.name, None)
273 if len(v) == 0: continue
274 v = [ unicode(x) for x in v if v is not None ]
278 dc[field.name] = {'uri': field.uri, 'value': v}
283 result = {'about': self.about}
284 for field in self.FIELDS:
285 v = getattr(self, field.name, None)
289 if len(v) == 0: continue
290 v = [ unicode(x) for x in v if v is not None ]
293 result[field.name] = v
296 v = getattr(self, field.salias)
297 if v is not None: result[field.salias] = unicode(v)
301 def parse(file_name):
302 return BookInfo.from_file(file_name)