0f5c99ab0bdba61c086b00944c6720d44a348dde
[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)
9 import re
10
11
12 class WLPictureURI(WLURI):
13     _re_wl_uri = re.compile('http://wolnelektury.pl/katalog/obraz/'
14             '(?P<slug>[-a-z0-9]+)(/(?P<lang>[a-z]{3}))?/?$')
15
16     def __init__(self, *args, **kw):
17         super(WLPictureURI, self).__init__(*args, **kw)
18
19     @classmethod
20     def from_slug_and_lang(cls, slug, lang):
21         uri = 'http://wolnelektury.pl/katalog/obraz/%s/' % slug
22         return cls(uri)
23
24     def filename_stem(self):
25         return self.slug
26
27
28 class PictureInfo(WorkInfo):
29     """
30     Dublin core metadata for a picture
31     """
32     FIELDS = (
33         Field(DCNS('language'), 'language', required=False),
34         Field(DCNS('subject.period'), 'epochs', salias='epoch', multiple=True),
35         Field(DCNS('subject.type'), 'kinds', salias='kind', multiple=True),
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         )
44
45     def validate(self):
46         """
47         WorkInfo has a language validation code only, which we do not need.
48         """
49         pass
50
51
52 class ImageStore(object):
53     EXT = ['gif', 'jpeg', 'png', 'swf', 'psd', 'bmp'
54             'tiff', 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc',
55             'aiff', 'wbmp', 'xbm']
56     MIME = ['image/gif', 'image/jpeg', 'image/png',
57             'application/x-shockwave-flash', 'image/psd', 'image/bmp',
58             'image/tiff', 'image/tiff', 'application/octet-stream',
59             'image/jp2', 'application/octet-stream', 'application/octet-stream',
60             'application/x-shockwave-flash', 'image/iff', 'image/vnd.wap.wbmp', 'image/xbm']
61
62     def __init__(self, dir_):
63         self.dir = dir_
64         return super(ImageStore, self).__init__()
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("Picture %s has unknown mime type: %s" % (slug, mime_type))
75             err.slug = slug
76             err.mime_type = mime_type
77             raise err
78         ext = self.EXT[i]
79         # add some common extensions tiff->tif, jpeg->jpg
80         return path.join(self.dir, slug + '.' + ext)
81
82
83 class WLPicture(object):
84     def __init__(self, edoc, parse_dublincore=True, image_store=None):
85         self.edoc = edoc
86         self.image_store = image_store
87
88         root_elem = edoc.getroot()
89
90         dc_path = './/' + RDFNS('RDF')
91
92         if root_elem.tag != 'picture':
93             raise ValidationError("Invalid root element. Found '%s', should be 'picture'" % root_elem.tag)
94
95         if parse_dublincore:
96             self.rdf_elem = root_elem.find(dc_path)
97
98             if self.rdf_elem is None:
99                 raise NoDublinCore('Document has no DublinCore - which is required.')
100
101             self.picture_info = PictureInfo.from_element(self.rdf_elem)
102         else:
103             self.picture_info = None
104
105     @classmethod
106     def from_string(cls, xml, *args, **kwargs):
107         return cls.from_file(StringIO(xml), *args, **kwargs)
108
109     @classmethod
110     def from_file(cls, xmlfile, parse_dublincore=True, image_store=None):
111
112         # first, prepare for parsing
113         if isinstance(xmlfile, basestring):
114             file = open(xmlfile, 'rb')
115             try:
116                 data = file.read()
117             finally:
118                 file.close()
119         else:
120             data = xmlfile.read()
121
122         if not isinstance(data, unicode):
123             data = data.decode('utf-8')
124
125         data = data.replace(u'\ufeff', '')
126
127         # assume images are in the same directory
128         if image_store is None and xmlfile.name is not None:
129             image_store = ImageStore(path.dirname(xmlfile.name))
130
131         try:
132             parser = etree.XMLParser(remove_blank_text=False)
133             tree = etree.parse(StringIO(data.encode('utf-8')), parser)
134
135             return cls(tree, parse_dublincore=parse_dublincore, image_store=image_store)
136         except (ExpatError, XMLSyntaxError, XSLTApplyError), 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         return self.image_store.path(self.slug, self.mime_type)
154
155     def image_file(self, *args, **kwargs):
156         return open(self.image_path, *args, **kwargs)
157
158     def partiter(self):
159         """
160         Iterates the parts of this picture and returns them and their metadata
161         """
162         for part in self.edoc.iter("div"):
163             pd = {}
164             pd['type'] = part.get('type')
165             if pd['type'] == 'area':
166                 pd['coords'] = ((int(part.get('x1')), int(part.get('y1'))),
167                                 (int(part.get('x2')), int(part.get('y2'))))
168
169             pd['themes'] = []
170             pd['object'] = None
171             parent = part
172             while True:
173                 parent = parent.getparent()
174                 if parent is None:
175                     break
176                 if parent.tag == 'sem':
177                     if parent.get('type') == 'theme':
178                         pd['themes'] += map(unicode.strip, unicode(parent.get('theme')).split(','))
179                     elif parent.get('type') == 'object' and pd['object'] is None:
180                         pd['object'] = parent.get('object')
181             yield pd