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