fixes for edge cases
[librarian.git] / src / 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(
18         'http://wolnelektury.pl/katalog/obraz/(?P<slug>[-a-z0-9]+)/?$'
19     )
20     template = 'http://wolnelektury.pl/katalog/obraz/%s/'
21
22
23 def as_wlpictureuri_strict(text):
24     return WLPictureURI.strict(text)
25
26
27 class PictureInfo(WorkInfo):
28     """
29     Dublin core metadata for a picture
30     """
31     FIELDS = (
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,
36               required=False),
37         Field(DCNS('subject.style'), 'styles', salias='style', multiple=True,
38               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',
44               required=False),
45         Field(DCNS('format'), 'mime_type', required=False),
46         Field(DCNS('identifier.url'), 'url', WLPictureURI,
47               strict=as_wlpictureuri_strict)
48     )
49
50
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',
59             'application/octet-stream', 'application/x-shockwave-flash',
60             'image/iff', 'image/vnd.wap.wbmp', 'image/xbm']
61
62     def __init__(self, dir_):
63         super(ImageStore, self).__init__()
64         self.dir = dir_
65
66     def path(self, slug, mime_type):
67         """
68         Finds file by slug and mime type in our iamge store.
69         Returns a file objects (perhaps should return a filename?)
70         """
71         try:
72             i = self.MIME.index(mime_type)
73         except ValueError:
74             err = ValueError(
75                 "Picture %s has unknown mime type: %s"
76                 % (slug, mime_type)
77             )
78             err.slug = slug
79             err.mime_type = mime_type
80             raise err
81         ext = self.EXT[i]
82         # add some common extensions tiff->tif, jpeg->jpg
83         return path.join(self.dir, slug + '.' + ext)
84
85
86 class WLPicture(object):
87     def __init__(self, edoc, parse_dublincore=True, image_store=None):
88         self.edoc = edoc
89         self.image_store = image_store
90
91         root_elem = edoc.getroot()
92
93         dc_path = './/' + RDFNS('RDF')
94
95         if root_elem.tag != 'picture':
96             raise ValidationError(
97                 "Invalid root element. Found '%s', should be 'picture'"
98                 % root_elem.tag
99             )
100
101         if parse_dublincore:
102             self.rdf_elem = root_elem.find(dc_path)
103
104             if self.rdf_elem is None:
105                 raise NoDublinCore(
106                     "Document has no DublinCore - which is required."
107                 )
108
109             self.picture_info = PictureInfo.from_element(self.rdf_elem)
110         else:
111             self.picture_info = None
112         self.frame = None
113
114     @classmethod
115     def from_bytes(cls, xml, *args, **kwargs):
116         return cls.from_file(six.BytesIO(xml), *args, **kwargs)
117
118     @classmethod
119     def from_file(cls, xmlfile, parse_dublincore=True, image_store=None):
120
121         # first, prepare for parsing
122         if isinstance(xmlfile, six.text_type):
123             file = open(xmlfile, 'rb')
124             try:
125                 data = file.read()
126             finally:
127                 file.close()
128         else:
129             data = xmlfile.read()
130
131         if not isinstance(data, six.text_type):
132             data = data.decode('utf-8')
133
134         data = data.replace(u'\ufeff', '')
135
136         # assume images are in the same directory
137         if image_store is None and getattr(xmlfile, 'name', None):
138             image_store = ImageStore(path.dirname(xmlfile.name))
139
140         try:
141             parser = etree.XMLParser(remove_blank_text=False)
142             tree = etree.parse(six.BytesIO(data.encode('utf-8')), parser)
143
144             me = cls(tree, parse_dublincore=parse_dublincore,
145                      image_store=image_store)
146             me.load_frame_info()
147             return me
148         except (ExpatError, XMLSyntaxError, XSLTApplyError) as e:
149             raise ParseError(e)
150
151     @property
152     def mime_type(self):
153         if self.picture_info is None:
154             raise ValueError(
155                 "DC is not loaded, hence we don't know the image type."
156             )
157         return self.picture_info.mime_type
158
159     @property
160     def slug(self):
161         return self.picture_info.url.slug
162
163     @property
164     def image_path(self):
165         if self.image_store is None:
166             raise ValueError("No image store associated with whis WLPicture.")
167
168         return self.image_store.path(self.slug, self.mime_type)
169
170     def image_file(self, *args, **kwargs):
171         return open(self.image_path, 'rb', *args, **kwargs)
172
173     def get_sem_coords(self, sem):
174         area = sem.find("div[@type='rect']")
175         if area is None:
176             area = sem.find("div[@type='whole']")
177             return [[0, 0], [-1, -1]]
178
179         def has_all_props(node, props):
180             return six.moves.reduce(
181                 and_, map(lambda prop: prop in node.attrib, props)
182             )
183
184         if not has_all_props(area, ['x1', 'x2', 'y1', 'y2']):
185             return None
186
187         def n(prop): return int(area.get(prop))
188         return [[n('x1'), n('y1')], [n('x2'), n('y2')]]
189
190     def partiter(self):
191         """
192         Iterates the parts of this picture and returns them
193         and their metadata.
194         """
195         # omg no support for //sem[(@type='theme') or (@type='object')] ?
196         for part in list(self.edoc.iterfind("//sem[@type='theme']")) +\
197                 list(self.edoc.iterfind("//sem[@type='object']")):
198             pd = {'type': part.get('type')}
199
200             coords = self.get_sem_coords(part)
201             if coords is None:
202                 continue
203             pd['coords'] = coords
204
205             def want_unicode(x):
206                 if not isinstance(x, six.text_type):
207                     return x.decode('utf-8')
208                 else:
209                     return x
210             pd['object'] = (
211                 part.attrib['type'] == 'object'
212                 and want_unicode(part.attrib.get('object', u''))
213                 or None
214             )
215             pd['themes'] = (
216                 part.attrib['type'] == 'theme'
217                 and [part.attrib.get('theme', u'')]
218                 or []
219             )
220             yield pd
221
222     def load_frame_info(self):
223         k = self.edoc.find("//sem[@object='kadr']")
224
225         if k is not None:
226             clip = self.get_sem_coords(k)
227             self.frame = clip
228             frm = Element("sem", {"type": "frame"})
229             frm.append(next(k.iter("div")))
230             self.edoc.getroot().append(frm)
231             k.getparent().remove(k)
232         else:
233             frm = self.edoc.find("//sem[@type='frame']")
234             if frm:
235                 self.frame = self.get_sem_coords(frm)
236             else:
237                 self.frame = None
238         return self