1 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
4 from operator import and_
7 from .dcparser import Field, WorkInfo, DCNS
8 from librarian import (RDFNS, ValidationError, NoDublinCore, ParseError, WLURI)
9 from xml.parsers.expat import ExpatError
11 from lxml import etree
12 from lxml.etree import (XMLSyntaxError, XSLTApplyError, Element)
16 class WLPictureURI(WLURI):
17 _re_wl_uri = re.compile(
18 'http://wolnelektury.pl/katalog/obraz/(?P<slug>[-a-z0-9]+)/?$'
20 template = 'http://wolnelektury.pl/katalog/obraz/%s/'
23 def as_wlpictureuri_strict(text):
24 return WLPictureURI.strict(text)
27 class PictureInfo(WorkInfo):
29 Dublin core metadata for a picture
32 Field(DCNS('language'), 'language', required=False),
33 Field(DCNS('subject.period'), 'epochs', salias='epoch', multiple=True),
34 Field(DCNS('subject.type'), 'kinds', salias='kind', multiple=True),
35 Field(DCNS('subject.genre'), 'genres', salias='genre', multiple=True,
37 Field(DCNS('subject.style'), 'styles', salias='style', multiple=True,
40 Field(DCNS('format.dimensions'), 'dimensions', required=False),
41 Field(DCNS('format.checksum.sha1'), 'sha1', required=True),
42 Field(DCNS('description.medium'), 'medium', required=False),
43 Field(DCNS('description.dimensions'), 'original_dimensions',
45 Field(DCNS('format'), 'mime_type', required=False),
46 Field(DCNS('identifier.url'), 'url', WLPictureURI,
47 strict=as_wlpictureuri_strict)
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',
59 'application/octet-stream', 'application/x-shockwave-flash',
60 'image/iff', 'image/vnd.wap.wbmp', 'image/xbm']
62 def __init__(self, dir_):
63 super(ImageStore, self).__init__()
66 def path(self, slug, mime_type):
68 Finds file by slug and mime type in our iamge store.
69 Returns a file objects (perhaps should return a filename?)
72 i = self.MIME.index(mime_type)
75 "Picture %s has unknown mime type: %s"
79 err.mime_type = mime_type
82 # add some common extensions tiff->tif, jpeg->jpg
83 return path.join(self.dir, slug + '.' + ext)
87 def __init__(self, edoc, parse_dublincore=True, image_store=None):
89 self.image_store = image_store
91 root_elem = edoc.getroot()
93 dc_path = './/' + RDFNS('RDF')
95 if root_elem.tag != 'picture':
96 raise ValidationError(
97 "Invalid root element. Found '%s', should be 'picture'"
102 self.rdf_elem = root_elem.find(dc_path)
104 if self.rdf_elem is None:
106 "Document has no DublinCore - which is required."
109 self.picture_info = PictureInfo.from_element(self.rdf_elem)
111 self.picture_info = None
115 def from_bytes(cls, xml, *args, **kwargs):
116 return cls.from_file(io.BytesIO(xml), *args, **kwargs)
119 def from_file(cls, xmlfile, parse_dublincore=True, image_store=None):
121 # first, prepare for parsing
122 if isinstance(xmlfile, str):
123 file = open(xmlfile, 'rb')
129 data = xmlfile.read()
131 if not isinstance(data, str):
132 data = data.decode('utf-8')
134 data = data.replace('\ufeff', '')
136 # assume images are in the same directory
137 if image_store is None and getattr(xmlfile, 'name', None):
138 image_store = ImageStore(path.dirname(xmlfile.name))
141 parser = etree.XMLParser(remove_blank_text=False)
142 tree = etree.parse(io.BytesIO(data.encode('utf-8')), parser)
144 me = cls(tree, parse_dublincore=parse_dublincore,
145 image_store=image_store)
148 except (ExpatError, XMLSyntaxError, XSLTApplyError) as e:
153 if self.picture_info is None:
155 "DC is not loaded, hence we don't know the image type."
157 return self.picture_info.mime_type
161 return self.picture_info.url.slug
164 def image_path(self):
165 if self.image_store is None:
166 raise ValueError("No image store associated with whis WLPicture.")
168 return self.image_store.path(self.slug, self.mime_type)
170 def image_file(self, *args, **kwargs):
171 return open(self.image_path, 'rb', *args, **kwargs)
173 def get_sem_coords(self, sem):
174 area = sem.find("div[@type='rect']")
176 area = sem.find("div[@type='whole']")
177 return [[0, 0], [-1, -1]]
179 def has_all_props(node, props):
180 return functools.reduce(
181 and_, map(lambda prop: prop in node.attrib, props)
184 if not has_all_props(area, ['x1', 'x2', 'y1', 'y2']):
187 def n(prop): return int(area.get(prop))
188 return [[n('x1'), n('y1')], [n('x2'), n('y2')]]
192 Iterates the parts of this picture and returns them
195 # omg no support for //sem[(@type='theme') or (@type='object')] ?
196 for part in list(self.edoc.iterfind("//sem[@type='theme']")) +\
197 list(self.edoc.iterfind("//sem[@type='object']")):
198 pd = {'type': part.get('type')}
200 coords = self.get_sem_coords(part)
203 pd['coords'] = coords
206 if not isinstance(x, str):
207 return x.decode('utf-8')
211 part.attrib['type'] == 'object'
212 and want_unicode(part.attrib.get('object', ''))
216 part.attrib['type'] == 'theme'
217 and [part.attrib.get('theme', '')]
222 def load_frame_info(self):
223 k = self.edoc.find("//sem[@object='kadr']")
226 clip = self.get_sem_coords(k)
228 frm = Element("sem", {"type": "frame"})
229 frm.append(next(k.iter("div")))
230 self.edoc.getroot().append(frm)
231 k.getparent().remove(k)
233 frm = self.edoc.find("//sem[@type='frame']")
235 self.frame = self.get_sem_coords(frm)