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
6 from StringIO import StringIO
8 from lxml.etree import (XMLSyntaxError, XSLTApplyError, Element)
10 from functools import *
11 from operator import *
13 class WLPictureURI(WLURI):
14 _re_wl_uri = re.compile('http://wolnelektury.pl/katalog/obraz/'
15 '(?P<slug>[-a-z0-9]+)/?$')
18 def from_slug(cls, slug):
19 uri = 'http://wolnelektury.pl/katalog/obraz/%s/' % slug
22 def as_wlpictureuri_strict(text):
23 return WLPictureURI.strict(text)
26 class PictureInfo(WorkInfo):
28 Dublin core metadata for a picture
31 Field(DCNS('language'), 'language', required=False),
32 Field(DCNS('subject.period'), 'epochs', salias='epoch', multiple=True),
33 Field(DCNS('subject.type'), 'kinds', salias='kind', multiple=True),
34 Field(DCNS('subject.genre'), 'genres', salias='genre', multiple=True, required=False),
36 Field(DCNS('format.dimensions'), 'dimensions', required=False),
37 Field(DCNS('format.checksum.sha1'), 'sha1', required=True),
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 strict=as_wlpictureuri_strict),
46 class ImageStore(object):
47 EXT = ['gif', 'jpeg', 'png', 'swf', 'psd', 'bmp'
48 'tiff', 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc',
49 'aiff', 'wbmp', 'xbm']
50 MIME = ['image/gif', 'image/jpeg', 'image/png',
51 'application/x-shockwave-flash', 'image/psd', 'image/bmp',
52 'image/tiff', 'image/tiff', 'application/octet-stream',
53 'image/jp2', 'application/octet-stream', 'application/octet-stream',
54 'application/x-shockwave-flash', 'image/iff', 'image/vnd.wap.wbmp', 'image/xbm']
56 def __init__(self, dir_):
58 return super(ImageStore, self).__init__()
60 def path(self, slug, mime_type):
62 Finds file by slug and mime type in our iamge store.
63 Returns a file objects (perhaps should return a filename?)
66 i = self.MIME.index(mime_type)
68 err = ValueError("Picture %s has unknown mime type: %s" % (slug, mime_type))
70 err.mime_type = mime_type
73 # add some common extensions tiff->tif, jpeg->jpg
74 return path.join(self.dir, slug + '.' + ext)
77 class WLPicture(object):
78 def __init__(self, edoc, parse_dublincore=True, image_store=None):
80 self.image_store = image_store
82 root_elem = edoc.getroot()
84 dc_path = './/' + RDFNS('RDF')
86 if root_elem.tag != 'picture':
87 raise ValidationError("Invalid root element. Found '%s', should be 'picture'" % root_elem.tag)
90 self.rdf_elem = root_elem.find(dc_path)
92 if self.rdf_elem is None:
93 raise NoDublinCore('Document has no DublinCore - which is required.')
95 self.picture_info = PictureInfo.from_element(self.rdf_elem)
97 self.picture_info = None
100 def from_string(cls, xml, *args, **kwargs):
101 return cls.from_file(StringIO(xml), *args, **kwargs)
104 def from_file(cls, xmlfile, parse_dublincore=True, image_store=None):
106 # first, prepare for parsing
107 if isinstance(xmlfile, basestring):
108 file = open(xmlfile, 'rb')
114 data = xmlfile.read()
116 if not isinstance(data, unicode):
117 data = data.decode('utf-8')
119 data = data.replace(u'\ufeff', '')
121 # assume images are in the same directory
122 if image_store is None and xmlfile.name is not None:
123 image_store = ImageStore(path.dirname(xmlfile.name))
126 parser = etree.XMLParser(remove_blank_text=False)
127 tree = etree.parse(StringIO(data.encode('utf-8')), parser)
129 me = cls(tree, parse_dublincore=parse_dublincore, image_store=image_store)
132 except (ExpatError, XMLSyntaxError, XSLTApplyError), e:
137 if self.picture_info is None:
138 raise ValueError('DC is not loaded, hence we don\'t know the image type')
139 return self.picture_info.mime_type
143 return self.picture_info.url.slug
146 def image_path(self):
147 if self.image_store is None:
148 raise ValueError("No image store associated with whis WLPicture.")
150 return self.image_store.path(self.slug, self.mime_type)
152 def image_file(self, *args, **kwargs):
153 return open(self.image_path, *args, **kwargs)
155 def get_sem_coords(self, sem):
156 area = sem.find("div[@type='rect']")
158 area = sem.find("div[@type='whole']")
159 return ((0, 0), (-1, -1))
161 def has_all_props(node, props):
162 return reduce(and_, map(lambda prop: prop in node.attrib, props))
164 if has_all_props(area, ['x1', 'x2', 'y1', 'y2']) == False:
167 def n(prop): return int(area.get(prop))
168 return ((n('x1'), n('y1')), (n('x2'), n('y2')))
173 Iterates the parts of this picture and returns them and their metadata
175 # omg no support for //sem[(@type='theme') or (@type='object')] ?
176 for part in list(self.edoc.iterfind("//sem[@type='theme']")) + list(self.edoc.iterfind("//sem[@type='object']")):
178 pd['type'] = part.get('type')
180 coords = self.get_sem_coords(part)
181 if coords is None: continue
182 pd['coords'] = coords
185 if not isinstance(x, unicode): return x.decode('utf-8')
187 pd['object'] = part.attrib['type'] == 'object' and want_unicode(part.attrib.get('object', u'')) or None
188 pd['themes'] = part.attrib['type'] == 'theme' and [part.attrib.get('theme', u'')] or []
191 def load_frame_info(self):
192 k = self.edoc.find("//sem[@object='kadr']")
195 clip = self.get_sem_coords(k)
197 frm = Element("sem", {"type": "frame"})
198 frm.append(k.iter("div").next())
199 self.edoc.getroot().append(frm)
200 k.getparent().remove(k)
202 frm = self.edoc.find("//sem[@type='frame']")
204 self.frame = self.get_sem_coords(frm)