1 # -*- coding: utf-8 -*-
2 from xml.parsers.expat import ExpatError
3 from datetime import date
6 from librarian import ValidationError, NoDublinCore
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)
112 class XMLNamespace(object):
113 '''Represents XML namespace.'''
115 def __init__(self, uri):
118 def __call__(self, tag):
119 return '{%s}%s' % (self.uri, tag)
121 def __contains__(self, tag):
122 return tag.startswith(str(self))
125 return 'XMLNamespace(%r)' % self.uri
128 return '%s' % self.uri
131 class BookInfo(object):
132 RDF = XMLNamespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
133 DC = XMLNamespace('http://purl.org/dc/elements/1.1/')
136 Field( DC('creator'), 'author', as_person),
137 Field( DC('title'), 'title'),
138 Field( DC('subject.period'), 'epoches', salias='epoch', multiple=True),
139 Field( DC('subject.type'), 'kinds', salias='kind', multiple=True),
140 Field( DC('subject.genre'), 'genres', salias='genre', multiple=True),
141 Field( DC('date'), 'created_at', as_date),
142 Field( DC('date.pd'), 'released_to_public_domain_at', as_date, required=False),
143 Field( DC('contributor.editor'), 'editors', \
144 as_person, salias='editor', multiple=True, default=[]),
145 Field( DC('contributor.translator'), 'translators', \
146 as_person, salias='translator', multiple=True, default=[]),
147 Field( DC('contributor.technical_editor'), 'technical_editors',
148 as_person, salias='technical_editor', multiple=True, default=[]),
149 Field( DC('publisher'), 'publisher'),
150 Field( DC('source'), 'source_name', required=False),
151 Field( DC('source.URL'), 'source_url', required=False),
152 Field( DC('identifier.url'), 'url'),
153 Field( DC('relation.hasPart'), 'parts', multiple=True, required=False),
154 Field( DC('rights.license'), 'license', required=False),
155 Field( DC('rights'), 'license_description'),
159 def from_string(cls, xml):
160 from StringIO import StringIO
161 return cls.from_file(StringIO(xml))
164 def from_file(cls, xmlfile):
167 iter = etree.iterparse(xmlfile, ['start', 'end'])
168 for (event, element) in iter:
169 if element.tag == cls.RDF('RDF') and event == 'start':
174 raise NoDublinCore("DublinCore section not found. \
175 Check if there are rdf:RDF and rdf:Description tags.")
177 # continue 'till the end of RDF section
178 for (event, element) in iter:
179 if element.tag == cls.RDF('RDF') and event == 'end':
182 # if there is no end, Expat should yell at us with an ExpatError
184 # extract data from the element and make the info
185 return cls.from_element(desc_tag)
186 except XMLSyntaxError, e:
188 except ExpatError, e:
192 def from_element(cls, rdf_tag):
193 # the tree is already parsed, so we don't need to worry about Expat errors
195 desc = rdf_tag.find(".//" + cls.RDF('Description') )
198 raise NoDublinCore("No DublinCore section found.")
200 for e in desc.getchildren():
201 fv = field_dict.get(e.tag, [])
203 field_dict[e.tag] = fv
205 return cls( desc.attrib, field_dict )
207 def __init__(self, rdf_attrs, dc_fields):
208 """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
209 dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the
212 self.about = rdf_attrs.get(self.RDF('about'))
215 for field in self.FIELDS:
216 value = field.validate( dc_fields )
217 setattr(self, 'prop_' + field.name, value)
218 self.fmap[field.name] = field
219 if field.salias: self.fmap[field.salias] = field
221 def __getattribute__(self, name):
223 field = object.__getattribute__(self, 'fmap')[name]
224 value = object.__getattribute__(self, 'prop_'+field.name)
225 if field.name == name:
227 else: # singular alias
228 if not field.multiple:
229 raise "OUCH!! for field %s" % name
232 except (KeyError, AttributeError):
233 return object.__getattribute__(self, name)
235 def __setattr__(self, name, newvalue):
237 field = object.__getattribute__(self, 'fmap')[name]
238 if field.name == name:
239 object.__setattr__(self, 'prop_'+field.name, newvalue)
240 else: # singular alias
241 if not field.multiple:
242 raise "OUCH! while setting field %s" % name
244 object.__setattr__(self, 'prop_'+field.name, [newvalue])
245 except (KeyError, AttributeError):
246 return object.__setattr__(self, name, newvalue)
248 def update(self, field_dict):
249 """Update using field_dict. Verify correctness, but don't check if all
250 required fields are present."""
251 for field in self.FIELDS:
252 if field_dict.has_key(field.name):
253 setattr(self, field.name, field_dict[field.name])
255 def to_etree(self, parent = None):
256 """XML representation of this object."""
257 #etree._namespace_map[str(self.RDF)] = 'rdf'
258 #etree._namespace_map[str(self.DC)] = 'dc'
261 root = etree.Element(self.RDF('RDF'))
263 root = parent.makeelement(self.RDF('RDF'))
265 description = etree.SubElement(root, self.RDF('Description'))
268 description.set(self.RDF('about'), self.about)
270 for field in self.FIELDS:
271 v = getattr(self, field.name, None)
274 if len(v) == 0: continue
276 e = etree.Element(field.uri)
278 description.append(e)
280 e = etree.Element(field.uri)
282 description.append(e)
287 result = {'about': self.about}
288 for field in self.FIELDS:
289 v = getattr(self, field.name, None)
293 if len(v) == 0: continue
294 v = [ unicode(x) for x in v ]
297 result[field.name] = v
300 v = getattr(self, field.salias)
301 if v is not None: result[field.salias] = v
305 def parse(file_name):
306 return BookInfo.from_file(file_name)