1 # -*- coding: utf-8 -*-
2 from operator import and_
4 from dcparser import Field, WorkInfo, DCNS
5 from librarian import (RDFNS, ValidationError, NoDublinCore, ParseError, WLURI)
6 from xml.parsers.expat import ExpatError
8 from StringIO import StringIO
10 from lxml.etree import (XMLSyntaxError, XSLTApplyError, Element)
14 class WLPictureURI(WLURI):
15 _re_wl_uri = re.compile('http://wolnelektury.pl/katalog/obraz/(?P<slug>[-a-z0-9]+)/?$')
18 def from_slug(cls, slug):
19 uri = 'http://wolnelektury.pl/katalog/obraz/%s/' % slug
23 def as_wlpictureuri_strict(text):
24 return WLPictureURI.strict(text)
27 class PictureInfo(WorkInfo):
29 Dublin core metadata for a picture
32 Field(DCNS('language'), 'language', required=False),
33 Field(DCNS('subject.period'), 'epochs', salias='epoch', multiple=True),
34 Field(DCNS('subject.type'), 'kinds', salias='kind', multiple=True),
35 Field(DCNS('subject.genre'), 'genres', salias='genre', multiple=True, required=False),
36 Field(DCNS('subject.style'), 'styles', salias='style', multiple=True, required=False),
38 Field(DCNS('format.dimensions'), 'dimensions', required=False),
39 Field(DCNS('format.checksum.sha1'), 'sha1', required=True),
40 Field(DCNS('description.medium'), 'medium', required=False),
41 Field(DCNS('description.dimensions'), 'original_dimensions', required=False),
42 Field(DCNS('format'), 'mime_type', required=False),
43 Field(DCNS('identifier.url'), 'url', WLPictureURI, strict=as_wlpictureuri_strict)
47 class ImageStore(object):
48 EXT = ['gif', 'jpeg', 'png', 'swf', 'psd', 'bmp'
49 'tiff', 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc',
50 'aiff', 'wbmp', 'xbm']
51 MIME = ['image/gif', 'image/jpeg', 'image/png',
52 'application/x-shockwave-flash', 'image/psd', 'image/bmp',
53 'image/tiff', 'image/tiff', 'application/octet-stream',
54 'image/jp2', 'application/octet-stream', 'application/octet-stream',
55 'application/x-shockwave-flash', 'image/iff', 'image/vnd.wap.wbmp', 'image/xbm']
57 def __init__(self, dir_):
58 super(ImageStore, self).__init__()
61 def path(self, slug, mime_type):
63 Finds file by slug and mime type in our iamge store.
64 Returns a file objects (perhaps should return a filename?)
67 i = self.MIME.index(mime_type)
69 err = ValueError("Picture %s has unknown mime type: %s" % (slug, mime_type))
71 err.mime_type = mime_type
74 # add some common extensions tiff->tif, jpeg->jpg
75 return path.join(self.dir, slug + '.' + ext)
78 class WLPicture(object):
79 def __init__(self, edoc, parse_dublincore=True, image_store=None):
81 self.image_store = image_store
83 root_elem = edoc.getroot()
85 dc_path = './/' + RDFNS('RDF')
87 if root_elem.tag != 'picture':
88 raise ValidationError("Invalid root element. Found '%s', should be 'picture'" % root_elem.tag)
91 self.rdf_elem = root_elem.find(dc_path)
93 if self.rdf_elem is None:
94 raise NoDublinCore('Document has no DublinCore - which is required.')
96 self.picture_info = PictureInfo.from_element(self.rdf_elem)
98 self.picture_info = None
102 def from_string(cls, xml, *args, **kwargs):
103 return cls.from_file(StringIO(xml), *args, **kwargs)
106 def from_file(cls, xmlfile, parse_dublincore=True, image_store=None):
108 # first, prepare for parsing
109 if isinstance(xmlfile, basestring):
110 file = open(xmlfile, 'rb')
116 data = xmlfile.read()
118 if not isinstance(data, unicode):
119 data = data.decode('utf-8')
121 data = data.replace(u'\ufeff', '')
123 # assume images are in the same directory
124 if image_store is None and getattr(xmlfile, 'name', None):
125 image_store = ImageStore(path.dirname(xmlfile.name))
128 parser = etree.XMLParser(remove_blank_text=False)
129 tree = etree.parse(StringIO(data.encode('utf-8')), parser)
131 me = cls(tree, parse_dublincore=parse_dublincore, image_store=image_store)
134 except (ExpatError, XMLSyntaxError, XSLTApplyError), e:
139 if self.picture_info is None:
140 raise ValueError('DC is not loaded, hence we don\'t know the image type')
141 return self.picture_info.mime_type
145 return self.picture_info.url.slug
148 def image_path(self):
149 if self.image_store is None:
150 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)
157 def get_sem_coords(self, sem):
158 area = sem.find("div[@type='rect']")
160 area = sem.find("div[@type='whole']")
161 return [[0, 0], [-1, -1]]
163 def has_all_props(node, props):
164 return reduce(and_, map(lambda prop: prop in node.attrib, props))
166 if not has_all_props(area, ['x1', 'x2', 'y1', 'y2']):
169 def n(prop): return int(area.get(prop))
170 return [[n('x1'), n('y1')], [n('x2'), n('y2')]]
174 Iterates the parts of this picture and returns them and their metadata
176 # omg no support for //sem[(@type='theme') or (@type='object')] ?
177 for part in list(self.edoc.iterfind("//sem[@type='theme']")) +\
178 list(self.edoc.iterfind("//sem[@type='object']")):
179 pd = {'type': part.get('type')}
181 coords = self.get_sem_coords(part)
184 pd['coords'] = coords
187 if not isinstance(x, unicode):
188 return x.decode('utf-8')
191 pd['object'] = part.attrib['type'] == 'object' and want_unicode(part.attrib.get('object', u'')) or None
192 pd['themes'] = part.attrib['type'] == 'theme' and [part.attrib.get('theme', u'')] or []
195 def load_frame_info(self):
196 k = self.edoc.find("//sem[@object='kadr']")
199 clip = self.get_sem_coords(k)
201 frm = Element("sem", {"type": "frame"})
202 frm.append(k.iter("div").next())
203 self.edoc.getroot().append(frm)
204 k.getparent().remove(k)
206 frm = self.edoc.find("//sem[@type='frame']")
208 self.frame = self.get_sem_coords(frm)