1 # -*- coding: utf-8 -*-
2 from __future__ import unicode_literals
4 from operator import and_
6 from .dcparser import Field, WorkInfo, DCNS
7 from librarian import (RDFNS, ValidationError, NoDublinCore, ParseError, WLURI)
8 from xml.parsers.expat import ExpatError
10 from lxml import etree
11 from lxml.etree import (XMLSyntaxError, XSLTApplyError, Element)
16 class WLPictureURI(WLURI):
17 _re_wl_uri = re.compile('http://wolnelektury.pl/katalog/obraz/(?P<slug>[-a-z0-9]+)/?$')
20 def from_slug(cls, slug):
21 uri = 'http://wolnelektury.pl/katalog/obraz/%s/' % slug
25 def as_wlpictureuri_strict(text):
26 return WLPictureURI.strict(text)
29 class PictureInfo(WorkInfo):
31 Dublin core metadata for a picture
34 Field(DCNS('language'), 'language', required=False),
35 Field(DCNS('subject.period'), 'epochs', salias='epoch', multiple=True),
36 Field(DCNS('subject.type'), 'kinds', salias='kind', multiple=True),
37 Field(DCNS('subject.genre'), 'genres', salias='genre', multiple=True, required=False),
38 Field(DCNS('subject.style'), 'styles', salias='style', multiple=True, required=False),
40 Field(DCNS('format.dimensions'), 'dimensions', required=False),
41 Field(DCNS('format.checksum.sha1'), 'sha1', required=True),
42 Field(DCNS('description.medium'), 'medium', required=False),
43 Field(DCNS('description.dimensions'), 'original_dimensions', required=False),
44 Field(DCNS('format'), 'mime_type', required=False),
45 Field(DCNS('identifier.url'), 'url', WLPictureURI, strict=as_wlpictureuri_strict)
49 class ImageStore(object):
50 EXT = ['gif', 'jpeg', 'png', 'swf', 'psd', 'bmp'
51 'tiff', 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc',
52 'aiff', 'wbmp', 'xbm']
53 MIME = ['image/gif', 'image/jpeg', 'image/png',
54 'application/x-shockwave-flash', 'image/psd', 'image/bmp',
55 'image/tiff', 'image/tiff', 'application/octet-stream',
56 'image/jp2', 'application/octet-stream', 'application/octet-stream',
57 'application/x-shockwave-flash', 'image/iff', 'image/vnd.wap.wbmp', 'image/xbm']
59 def __init__(self, dir_):
60 super(ImageStore, self).__init__()
63 def path(self, slug, mime_type):
65 Finds file by slug and mime type in our iamge store.
66 Returns a file objects (perhaps should return a filename?)
69 i = self.MIME.index(mime_type)
71 err = ValueError("Picture %s has unknown mime type: %s" % (slug, mime_type))
73 err.mime_type = mime_type
76 # add some common extensions tiff->tif, jpeg->jpg
77 return path.join(self.dir, slug + '.' + ext)
80 class WLPicture(object):
81 def __init__(self, edoc, parse_dublincore=True, image_store=None):
83 self.image_store = image_store
85 root_elem = edoc.getroot()
87 dc_path = './/' + RDFNS('RDF')
89 if root_elem.tag != 'picture':
90 raise ValidationError("Invalid root element. Found '%s', should be 'picture'" % root_elem.tag)
93 self.rdf_elem = root_elem.find(dc_path)
95 if self.rdf_elem is None:
96 raise NoDublinCore('Document has no DublinCore - which is required.')
98 self.picture_info = PictureInfo.from_element(self.rdf_elem)
100 self.picture_info = None
104 def from_bytes(cls, xml, *args, **kwargs):
105 return cls.from_file(six.BytesIO(xml), *args, **kwargs)
108 def from_file(cls, xmlfile, parse_dublincore=True, image_store=None):
110 # first, prepare for parsing
111 if isinstance(xmlfile, six.text_type):
112 file = open(xmlfile, 'rb')
118 data = xmlfile.read()
120 if not isinstance(data, six.text_type):
121 data = data.decode('utf-8')
123 data = data.replace(u'\ufeff', '')
125 # assume images are in the same directory
126 if image_store is None and getattr(xmlfile, 'name', None):
127 image_store = ImageStore(path.dirname(xmlfile.name))
130 parser = etree.XMLParser(remove_blank_text=False)
131 tree = etree.parse(six.BytesIO(data.encode('utf-8')), parser)
133 me = cls(tree, parse_dublincore=parse_dublincore, image_store=image_store)
136 except (ExpatError, XMLSyntaxError, XSLTApplyError) as e:
141 if self.picture_info is None:
142 raise ValueError('DC is not loaded, hence we don\'t know the image type')
143 return self.picture_info.mime_type
147 return self.picture_info.url.slug
150 def image_path(self):
151 if self.image_store is None:
152 raise ValueError("No image store associated with whis WLPicture.")
154 return self.image_store.path(self.slug, self.mime_type)
156 def image_file(self, *args, **kwargs):
157 return open(self.image_path, 'rb', *args, **kwargs)
159 def get_sem_coords(self, sem):
160 area = sem.find("div[@type='rect']")
162 area = sem.find("div[@type='whole']")
163 return [[0, 0], [-1, -1]]
165 def has_all_props(node, props):
166 return reduce(and_, map(lambda prop: prop in node.attrib, props))
168 if not has_all_props(area, ['x1', 'x2', 'y1', 'y2']):
171 def n(prop): return int(area.get(prop))
172 return [[n('x1'), n('y1')], [n('x2'), n('y2')]]
176 Iterates the parts of this picture and returns them and their metadata
178 # omg no support for //sem[(@type='theme') or (@type='object')] ?
179 for part in list(self.edoc.iterfind("//sem[@type='theme']")) +\
180 list(self.edoc.iterfind("//sem[@type='object']")):
181 pd = {'type': part.get('type')}
183 coords = self.get_sem_coords(part)
186 pd['coords'] = coords
189 if not isinstance(x, six.text_type):
190 return x.decode('utf-8')
193 pd['object'] = part.attrib['type'] == 'object' and want_unicode(part.attrib.get('object', u'')) or None
194 pd['themes'] = part.attrib['type'] == 'theme' and [part.attrib.get('theme', u'')] or []
197 def load_frame_info(self):
198 k = self.edoc.find("//sem[@object='kadr']")
201 clip = self.get_sem_coords(k)
203 frm = Element("sem", {"type": "frame"})
204 frm.append(k.iter("div").next())
205 self.edoc.getroot().append(frm)
206 k.getparent().remove(k)
208 frm = self.edoc.find("//sem[@type='frame']")
210 self.frame = self.get_sem_coords(frm)