Python 3.4-3.7 support;
[librarian.git] / librarian / picture.py
1 # -*- coding: utf-8 -*-
2 from __future__ import unicode_literals
3
4 from operator import and_
5
6 from .dcparser import Field, WorkInfo, DCNS
7 from librarian import (RDFNS, ValidationError, NoDublinCore, ParseError, WLURI)
8 from xml.parsers.expat import ExpatError
9 from os import path
10 from lxml import etree
11 from lxml.etree import (XMLSyntaxError, XSLTApplyError, Element)
12 import re
13 import six
14
15
16 class WLPictureURI(WLURI):
17     _re_wl_uri = re.compile('http://wolnelektury.pl/katalog/obraz/(?P<slug>[-a-z0-9]+)/?$')
18
19     @classmethod
20     def from_slug(cls, slug):
21         uri = 'http://wolnelektury.pl/katalog/obraz/%s/' % slug
22         return cls(uri)
23
24
25 def as_wlpictureuri_strict(text):
26     return WLPictureURI.strict(text)
27
28
29 class PictureInfo(WorkInfo):
30     """
31     Dublin core metadata for a picture
32     """
33     FIELDS = (
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),
39
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)
46     )
47
48
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']
58
59     def __init__(self, dir_):
60         super(ImageStore, self).__init__()
61         self.dir = dir_
62
63     def path(self, slug, mime_type):
64         """
65         Finds file by slug and mime type in our iamge store.
66         Returns a file objects (perhaps should return a filename?)
67         """
68         try:
69             i = self.MIME.index(mime_type)
70         except ValueError:
71             err = ValueError("Picture %s has unknown mime type: %s" % (slug, mime_type))
72             err.slug = slug
73             err.mime_type = mime_type
74             raise err
75         ext = self.EXT[i]
76         # add some common extensions tiff->tif, jpeg->jpg
77         return path.join(self.dir, slug + '.' + ext)
78
79
80 class WLPicture(object):
81     def __init__(self, edoc, parse_dublincore=True, image_store=None):
82         self.edoc = edoc
83         self.image_store = image_store
84
85         root_elem = edoc.getroot()
86
87         dc_path = './/' + RDFNS('RDF')
88
89         if root_elem.tag != 'picture':
90             raise ValidationError("Invalid root element. Found '%s', should be 'picture'" % root_elem.tag)
91
92         if parse_dublincore:
93             self.rdf_elem = root_elem.find(dc_path)
94
95             if self.rdf_elem is None:
96                 raise NoDublinCore('Document has no DublinCore - which is required.')
97
98             self.picture_info = PictureInfo.from_element(self.rdf_elem)
99         else:
100             self.picture_info = None
101         self.frame = None
102
103     @classmethod
104     def from_bytes(cls, xml, *args, **kwargs):
105         return cls.from_file(six.BytesIO(xml), *args, **kwargs)
106
107     @classmethod
108     def from_file(cls, xmlfile, parse_dublincore=True, image_store=None):
109
110         # first, prepare for parsing
111         if isinstance(xmlfile, six.text_type):
112             file = open(xmlfile, 'rb')
113             try:
114                 data = file.read()
115             finally:
116                 file.close()
117         else:
118             data = xmlfile.read()
119
120         if not isinstance(data, six.text_type):
121             data = data.decode('utf-8')
122
123         data = data.replace(u'\ufeff', '')
124
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))
128
129         try:
130             parser = etree.XMLParser(remove_blank_text=False)
131             tree = etree.parse(six.BytesIO(data.encode('utf-8')), parser)
132
133             me = cls(tree, parse_dublincore=parse_dublincore, image_store=image_store)
134             me.load_frame_info()
135             return me
136         except (ExpatError, XMLSyntaxError, XSLTApplyError) as e:
137             raise ParseError(e)
138
139     @property
140     def mime_type(self):
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
144
145     @property
146     def slug(self):
147         return self.picture_info.url.slug
148
149     @property
150     def image_path(self):
151         if self.image_store is None:
152             raise ValueError("No image store associated with whis WLPicture.")
153
154         return self.image_store.path(self.slug, self.mime_type)
155
156     def image_file(self, *args, **kwargs):
157         return open(self.image_path, *args, **kwargs)
158
159     def get_sem_coords(self, sem):
160         area = sem.find("div[@type='rect']")
161         if area is None:
162             area = sem.find("div[@type='whole']")
163             return [[0, 0], [-1, -1]]
164
165         def has_all_props(node, props):
166             return reduce(and_, map(lambda prop: prop in node.attrib, props))
167
168         if not has_all_props(area, ['x1', 'x2', 'y1', 'y2']):
169             return None
170
171         def n(prop): return int(area.get(prop))
172         return [[n('x1'), n('y1')], [n('x2'), n('y2')]]
173
174     def partiter(self):
175         """
176         Iterates the parts of this picture and returns them and their metadata
177         """
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')}
182
183             coords = self.get_sem_coords(part)
184             if coords is None:
185                 continue
186             pd['coords'] = coords
187
188             def want_unicode(x):
189                 if not isinstance(x, six.text_type):
190                     return x.decode('utf-8')
191                 else:
192                     return x
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 []
195             yield pd
196
197     def load_frame_info(self):
198         k = self.edoc.find("//sem[@object='kadr']")
199         
200         if k is not None:
201             clip = self.get_sem_coords(k)
202             self.frame = clip
203             frm = Element("sem", {"type": "frame"})
204             frm.append(k.iter("div").next())
205             self.edoc.getroot().append(frm)
206             k.getparent().remove(k)
207         else:
208             frm = self.edoc.find("//sem[@type='frame']")
209             if frm:
210                 self.frame = self.get_sem_coords(frm)
211             else:
212                 self.frame = None
213         return self