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