python 2.5 does not support tuple.index()
[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('description.medium'), 'medium', required=False),
39         Field(DCNS('description.dimensions'), 'original_dimensions', required=False),
40         Field(DCNS('format'), 'mime_type', required=False),
41         Field(DCNS('identifier.url'), 'url', WLPictureURI),
42         )
43
44     def validate(self):
45         """
46         WorkInfo has a language validation code only, which we do not need.
47         """
48         pass
49
50
51 class ImageStore(object):
52     EXT = ['gif', 'jpeg', 'png', 'swf', 'psd', 'bmp'
53             'tiff', 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc',
54             'aiff', 'wbmp', 'xbm']
55     MIME = ['image/gif', 'image/jpeg', 'image/png',
56             'application/x-shockwave-flash', 'image/psd', 'image/bmp',
57             'image/tiff', 'image/tiff', 'application/octet-stream',
58             'image/jp2', 'application/octet-stream', 'application/octet-stream',
59             'application/x-shockwave-flash', 'image/iff', 'image/vnd.wap.wbmp', 'image/xbm']
60
61     def __init__(self, dir_):
62         self.dir = dir_
63         return super(ImageStore, self).__init__()
64
65     def path(self, slug, mime_type):
66         """
67         Finds file by slug and mime type in our iamge store.
68         Returns a file objects (perhaps should return a filename?)
69         """
70         try:
71             i = self.MIME.index(mime_type)
72         except ValueError:
73             err = ValueError("Picture %s has unknown mime type: %s" % (slug, mime_type))
74             err.slug = slug
75             err.mime_type = mime_type
76             raise err
77         ext = self.EXT[i]
78         # add some common extensions tiff->tif, jpeg->jpg
79         return path.join(self.dir, slug + '.' + ext)
80
81
82 class WLPicture(object):
83     def __init__(self, edoc, parse_dublincore=True, image_store=None):
84         self.edoc = edoc
85         self.image_store = image_store
86
87         root_elem = edoc.getroot()
88
89         dc_path = './/' + RDFNS('RDF')
90
91         if root_elem.tag != 'picture':
92             raise ValidationError("Invalid root element. Found '%s', should be 'picture'" % root_elem.tag)
93
94         if parse_dublincore:
95             self.rdf_elem = root_elem.find(dc_path)
96
97             if self.rdf_elem is None:
98                 raise NoDublinCore('Document has no DublinCore - which is required.')
99
100             self.picture_info = PictureInfo.from_element(self.rdf_elem)
101         else:
102             self.picture_info = None
103
104     @classmethod
105     def from_string(cls, xml, *args, **kwargs):
106         return cls.from_file(StringIO(xml), *args, **kwargs)
107
108     @classmethod
109     def from_file(cls, xmlfile, parse_dublincore=True, image_store=None):
110
111         # first, prepare for parsing
112         if isinstance(xmlfile, basestring):
113             file = open(xmlfile, 'rb')
114             try:
115                 data = file.read()
116             finally:
117                 file.close()
118         else:
119             data = xmlfile.read()
120
121         if not isinstance(data, unicode):
122             data = data.decode('utf-8')
123
124         data = data.replace(u'\ufeff', '')
125
126         # assume images are in the same directory
127         if image_store is None and xmlfile.name is not None:
128             image_store = ImageStore(path.dirname(xmlfile.name))
129
130         try:
131             parser = etree.XMLParser(remove_blank_text=False)
132             tree = etree.parse(StringIO(data.encode('utf-8')), parser)
133
134             return cls(tree, parse_dublincore=parse_dublincore, image_store=image_store)
135         except (ExpatError, XMLSyntaxError, XSLTApplyError), e:
136             raise ParseError(e)
137
138     @property
139     def mime_type(self):
140         if self.picture_info is None:
141             raise ValueError('DC is not loaded, hence we don\'t know the image type')
142         return self.picture_info.mime_type
143
144     @property
145     def slug(self):
146         return self.picture_info.url.slug
147
148     @property
149     def image_path(self):
150         if self.image_store is None:
151             raise ValueError("No image store associated with whis WLPicture.")
152         return self.image_store.path(self.slug, self.mime_type)
153
154     def image_file(self, *args, **kwargs):
155         return open(self.image_path, *args, **kwargs)