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)
12 class WLPictureURI(WLURI):
13 _re_wl_uri = re.compile('http://wolnelektury.pl/katalog/obraz/'
14 '(?P<slug>[-a-z0-9]+)/?$')
17 def from_slug(cls, slug):
18 uri = 'http://wolnelektury.pl/katalog/obraz/%s/' % slug
21 def as_wlpictureuri_strict(text):
22 return WLPictureURI.strict(text)
25 class PictureInfo(WorkInfo):
27 Dublin core metadata for a picture
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),
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),
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']
55 def __init__(self, dir_):
57 return super(ImageStore, self).__init__()
59 def path(self, slug, mime_type):
61 Finds file by slug and mime type in our iamge store.
62 Returns a file objects (perhaps should return a filename?)
65 i = self.MIME.index(mime_type)
67 err = ValueError("Picture %s has unknown mime type: %s" % (slug, mime_type))
69 err.mime_type = mime_type
72 # add some common extensions tiff->tif, jpeg->jpg
73 return path.join(self.dir, slug + '.' + ext)
76 class WLPicture(object):
77 def __init__(self, edoc, parse_dublincore=True, image_store=None):
79 self.image_store = image_store
81 root_elem = edoc.getroot()
83 dc_path = './/' + RDFNS('RDF')
85 if root_elem.tag != 'picture':
86 raise ValidationError("Invalid root element. Found '%s', should be 'picture'" % root_elem.tag)
89 self.rdf_elem = root_elem.find(dc_path)
91 if self.rdf_elem is None:
92 raise NoDublinCore('Document has no DublinCore - which is required.')
94 self.picture_info = PictureInfo.from_element(self.rdf_elem)
96 self.picture_info = None
99 def from_string(cls, xml, *args, **kwargs):
100 return cls.from_file(StringIO(xml), *args, **kwargs)
103 def from_file(cls, xmlfile, parse_dublincore=True, image_store=None):
105 # first, prepare for parsing
106 if isinstance(xmlfile, basestring):
107 file = open(xmlfile, 'rb')
113 data = xmlfile.read()
115 if not isinstance(data, unicode):
116 data = data.decode('utf-8')
118 data = data.replace(u'\ufeff', '')
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))
125 parser = etree.XMLParser(remove_blank_text=False)
126 tree = etree.parse(StringIO(data.encode('utf-8')), parser)
128 return cls(tree, parse_dublincore=parse_dublincore, image_store=image_store)
129 except (ExpatError, XMLSyntaxError, XSLTApplyError), e:
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
140 return self.picture_info.url.slug
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)
148 def image_file(self, *args, **kwargs):
149 return open(self.image_path, *args, **kwargs)
153 Iterates the parts of this picture and returns them and their metadata
155 for part in self.edoc.iter("div"):
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'))))
166 parent = parent.getparent()
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')