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