2 from dcparser import (as_person, as_date, Field, WorkInfo, DCNS)
3 from librarian import (RDFNS, ValidationError, NoDublinCore, ParseError, WLURI)
4 from xml.parsers.expat import ExpatError
6 from StringIO import StringIO
8 from lxml.etree import (XMLSyntaxError, XSLTApplyError)
12 class WLPictureURI(WLURI):
13 _re_wl_uri = re.compile('http://wolnelektury.pl/katalog/obraz/'
14 '(?P<slug>[-a-z0-9]+)(/(?P<lang>[a-z]{3}))?/?$')
16 def __init__(self, *args, **kw):
17 super(WLPictureURI, self).__init__(*args, **kw)
20 def from_slug_and_lang(cls, slug, lang):
21 uri = 'http://wolnelektury.pl/katalog/obraz/%s/' % slug
24 def filename_stem(self):
28 class PictureInfo(WorkInfo):
30 Dublin core metadata for a picture
33 Field(DCNS('language'), 'language', required=False),
34 Field(DCNS('subject.period'), 'epochs', salias='epoch', multiple=True),
35 Field(DCNS('subject.type'), 'kinds', salias='kind', multiple=True),
37 Field(DCNS('format.dimensions'), 'dimensions', required=False),
38 Field(DCNS('description.medium'), 'medium', required=False),
39 Field(DCNS('description.dimensions'), 'original_dimensions', required=False),
40 Field(DCNS('format'), 'mime_type', required=False),
41 Field(DCNS('identifier.url'), 'url', WLPictureURI),
46 WorkInfo has a language validation code only, which we do not need.
51 class ImageStore(object):
52 EXT = ['gif', 'jpeg', 'png', 'swf', 'psd', 'bmp'
53 'tiff', 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc',
54 'aiff', 'wbmp', 'xbm']
55 MIME = ['image/gif', 'image/jpeg', 'image/png',
56 'application/x-shockwave-flash', 'image/psd', 'image/bmp',
57 'image/tiff', 'image/tiff', 'application/octet-stream',
58 'image/jp2', 'application/octet-stream', 'application/octet-stream',
59 'application/x-shockwave-flash', 'image/iff', 'image/vnd.wap.wbmp', 'image/xbm']
61 def __init__(self, dir_):
63 return super(ImageStore, self).__init__()
65 def path(self, slug, mime_type):
67 Finds file by slug and mime type in our iamge store.
68 Returns a file objects (perhaps should return a filename?)
71 i = self.MIME.index(mime_type)
73 err = ValueError("Picture %s has unknown mime type: %s" % (slug, mime_type))
75 err.mime_type = mime_type
78 # add some common extensions tiff->tif, jpeg->jpg
79 return path.join(self.dir, slug + '.' + ext)
82 class WLPicture(object):
83 def __init__(self, edoc, parse_dublincore=True, image_store=None):
85 self.image_store = image_store
87 root_elem = edoc.getroot()
89 dc_path = './/' + RDFNS('RDF')
91 if root_elem.tag != 'picture':
92 raise ValidationError("Invalid root element. Found '%s', should be 'picture'" % root_elem.tag)
95 self.rdf_elem = root_elem.find(dc_path)
97 if self.rdf_elem is None:
98 raise NoDublinCore('Document has no DublinCore - which is required.')
100 self.picture_info = PictureInfo.from_element(self.rdf_elem)
102 self.picture_info = None
105 def from_string(cls, xml, *args, **kwargs):
106 return cls.from_file(StringIO(xml), *args, **kwargs)
109 def from_file(cls, xmlfile, parse_dublincore=True, image_store=None):
111 # first, prepare for parsing
112 if isinstance(xmlfile, basestring):
113 file = open(xmlfile, 'rb')
119 data = xmlfile.read()
121 if not isinstance(data, unicode):
122 data = data.decode('utf-8')
124 data = data.replace(u'\ufeff', '')
126 # assume images are in the same directory
127 if image_store is None and xmlfile.name is not None:
128 image_store = ImageStore(path.dirname(xmlfile.name))
131 parser = etree.XMLParser(remove_blank_text=False)
132 tree = etree.parse(StringIO(data.encode('utf-8')), parser)
134 return cls(tree, parse_dublincore=parse_dublincore, image_store=image_store)
135 except (ExpatError, XMLSyntaxError, XSLTApplyError), e:
140 if self.picture_info is None:
141 raise ValueError('DC is not loaded, hence we don\'t know the image type')
142 return self.picture_info.mime_type
146 return self.picture_info.url.slug
149 def image_path(self):
150 if self.image_store is None:
151 raise ValueError("No image store associated with whis WLPicture.")
152 return self.image_store.path(self.slug, self.mime_type)
154 def image_file(self, *args, **kwargs):
155 return open(self.image_path, *args, **kwargs)
159 Iterates the parts of this picture and returns them and their metadata
161 for part in self.edoc.iter("div"):
163 pd['type'] = part.get('type')
164 if pd['type'] == 'area':
165 pd['coords'] = ((int(part.get('x1')), int(part.get('y1'))),
166 (int(part.get('x2')), int(part.get('y2'))))
172 parent = parent.getparent()
175 if parent.tag == 'sem':
176 if parent.get('type') == 'theme':
177 pd['themes'] += map(unicode.strip, unicode(parent.get('theme')).split(','))
178 elif parent.get('type') == 'object' and not pd['object']:
179 pd['object'] = parent.get('name')