ee3c61dfe8800091b70dd3bbcca6b83d1f325711
[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]+)/?$')
15
16     @classmethod
17     def from_slug(cls, slug):
18         uri = 'http://wolnelektury.pl/katalog/obraz/%s/' % slug
19         return cls(uri)
20
21 def as_wlpictureuri_strict(text):
22     return WLPictureURI.strict(text)
23
24
25 class PictureInfo(WorkInfo):
26     """
27     Dublin core metadata for a picture
28     """
29     FIELDS = (
30         Field(DCNS('language'), 'language', required=False),
31         Field(DCNS('subject.period'), 'epochs', salias='epoch', multiple=True),
32         Field(DCNS('subject.type'), 'kinds', salias='kind', multiple=True),
33
34         Field(DCNS('format.dimensions'), 'dimensions', required=False),
35         Field(DCNS('format.checksum.sha1'), 'sha1', required=True),
36         Field(DCNS('description.medium'), 'medium', required=False),
37         Field(DCNS('description.dimensions'), 'original_dimensions', required=False),
38         Field(DCNS('format'), 'mime_type', required=False),
39         Field(DCNS('identifier.url'), 'url', WLPictureURI,
40             strict=as_wlpictureuri_strict),
41         )
42
43
44 class ImageStore(object):
45     EXT = ['gif', 'jpeg', 'png', 'swf', 'psd', 'bmp'
46             'tiff', 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc',
47             'aiff', 'wbmp', 'xbm']
48     MIME = ['image/gif', 'image/jpeg', 'image/png',
49             'application/x-shockwave-flash', 'image/psd', 'image/bmp',
50             'image/tiff', 'image/tiff', 'application/octet-stream',
51             'image/jp2', 'application/octet-stream', 'application/octet-stream',
52             'application/x-shockwave-flash', 'image/iff', 'image/vnd.wap.wbmp', 'image/xbm']
53
54     def __init__(self, dir_):
55         self.dir = dir_
56         return super(ImageStore, self).__init__()
57
58     def path(self, slug, mime_type):
59         """
60         Finds file by slug and mime type in our iamge store.
61         Returns a file objects (perhaps should return a filename?)
62         """
63         try:
64             i = self.MIME.index(mime_type)
65         except ValueError:
66             err = ValueError("Picture %s has unknown mime type: %s" % (slug, mime_type))
67             err.slug = slug
68             err.mime_type = mime_type
69             raise err
70         ext = self.EXT[i]
71         # add some common extensions tiff->tif, jpeg->jpg
72         return path.join(self.dir, slug + '.' + ext)
73
74
75 class WLPicture(object):
76     def __init__(self, edoc, parse_dublincore=True, image_store=None):
77         self.edoc = edoc
78         self.image_store = image_store
79
80         root_elem = edoc.getroot()
81
82         dc_path = './/' + RDFNS('RDF')
83
84         if root_elem.tag != 'picture':
85             raise ValidationError("Invalid root element. Found '%s', should be 'picture'" % root_elem.tag)
86
87         if parse_dublincore:
88             self.rdf_elem = root_elem.find(dc_path)
89
90             if self.rdf_elem is None:
91                 raise NoDublinCore('Document has no DublinCore - which is required.')
92
93             self.picture_info = PictureInfo.from_element(self.rdf_elem)
94         else:
95             self.picture_info = None
96
97     @classmethod
98     def from_string(cls, xml, *args, **kwargs):
99         return cls.from_file(StringIO(xml), *args, **kwargs)
100
101     @classmethod
102     def from_file(cls, xmlfile, parse_dublincore=True, image_store=None):
103
104         # first, prepare for parsing
105         if isinstance(xmlfile, basestring):
106             file = open(xmlfile, 'rb')
107             try:
108                 data = file.read()
109             finally:
110                 file.close()
111         else:
112             data = xmlfile.read()
113
114         if not isinstance(data, unicode):
115             data = data.decode('utf-8')
116
117         data = data.replace(u'\ufeff', '')
118
119         # assume images are in the same directory
120         if image_store is None and xmlfile.name is not None:
121             image_store = ImageStore(path.dirname(xmlfile.name))
122
123         try:
124             parser = etree.XMLParser(remove_blank_text=False)
125             tree = etree.parse(StringIO(data.encode('utf-8')), parser)
126
127             return cls(tree, parse_dublincore=parse_dublincore, image_store=image_store)
128         except (ExpatError, XMLSyntaxError, XSLTApplyError), e:
129             raise ParseError(e)
130
131     @property
132     def mime_type(self):
133         if self.picture_info is None:
134             raise ValueError('DC is not loaded, hence we don\'t know the image type')
135         return self.picture_info.mime_type
136
137     @property
138     def slug(self):
139         return self.picture_info.url.slug
140
141     @property
142     def image_path(self):
143         if self.image_store is None:
144             raise ValueError("No image store associated with whis WLPicture.")
145         return self.image_store.path(self.slug, self.mime_type)
146
147     def image_file(self, *args, **kwargs):
148         return open(self.image_path, *args, **kwargs)
149
150     def partiter(self):
151         """
152         Iterates the parts of this picture and returns them and their metadata
153         """
154         for part in self.edoc.iter("div"):
155             pd = {}
156             pd['type'] = part.get('type')
157             if pd['type'] == 'area':
158                 pd['coords'] = ((int(part.get('x1')), int(part.get('y1'))),
159                                 (int(part.get('x2')), int(part.get('y2'))))
160
161             pd['themes'] = []
162             pd['object'] = None
163             parent = part
164             while True:
165                 parent = parent.getparent()
166                 if parent is None:
167                     break
168                 if parent.tag == 'sem':
169                     if parent.get('type') == 'theme':
170                         pd['themes'] += map(unicode.strip, unicode(parent.get('theme')).split(','))
171                     elif parent.get('type') == 'object' and pd['object'] is None:
172                         pd['object'] = parent.get('object')
173             yield pd