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]+)(/(?P<lang>[a-z]{3}))?/?$')
16 def __init__(self, *args, **kw):
17 super(WLPictureURI, self).__init__(*args, **kw)
20 def from_slug_and_lang(cls, slug, lang):
21 uri = 'http://wolnelektury.pl/katalog/obraz/%s/' % slug
24 def filename_stem(self):
28 class PictureInfo(WorkInfo):
30 Dublin core metadata for a picture
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),
37 Field(DCNS('format.dimensions'), 'dimensions', required=False),
38 Field(DCNS('format.checksum.sha1'), 'sha1', required=True),
39 Field(DCNS('description.medium'), 'medium', required=False),
40 Field(DCNS('description.dimensions'), 'original_dimensions', required=False),
41 Field(DCNS('format'), 'mime_type', required=False),
42 Field(DCNS('identifier.url'), 'url', WLPictureURI),
47 WorkInfo has a language validation code only, which we do not need.
52 class ImageStore(object):
53 EXT = ['gif', 'jpeg', 'png', 'swf', 'psd', 'bmp'
54 'tiff', 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc',
55 'aiff', 'wbmp', 'xbm']
56 MIME = ['image/gif', 'image/jpeg', 'image/png',
57 'application/x-shockwave-flash', 'image/psd', 'image/bmp',
58 'image/tiff', 'image/tiff', 'application/octet-stream',
59 'image/jp2', 'application/octet-stream', 'application/octet-stream',
60 'application/x-shockwave-flash', 'image/iff', 'image/vnd.wap.wbmp', 'image/xbm']
62 def __init__(self, dir_):
64 return 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)
74 err = ValueError("Picture %s has unknown mime type: %s" % (slug, mime_type))
76 err.mime_type = mime_type
79 # add some common extensions tiff->tif, jpeg->jpg
80 return path.join(self.dir, slug + '.' + ext)
83 class WLPicture(object):
84 def __init__(self, edoc, parse_dublincore=True, image_store=None):
86 self.image_store = image_store
88 root_elem = edoc.getroot()
90 dc_path = './/' + RDFNS('RDF')
92 if root_elem.tag != 'picture':
93 raise ValidationError("Invalid root element. Found '%s', should be 'picture'" % root_elem.tag)
96 self.rdf_elem = root_elem.find(dc_path)
98 if self.rdf_elem is None:
99 raise NoDublinCore('Document has no DublinCore - which is required.')
101 self.picture_info = PictureInfo.from_element(self.rdf_elem)
103 self.picture_info = None
106 def from_string(cls, xml, *args, **kwargs):
107 return cls.from_file(StringIO(xml), *args, **kwargs)
110 def from_file(cls, xmlfile, parse_dublincore=True, image_store=None):
112 # first, prepare for parsing
113 if isinstance(xmlfile, basestring):
114 file = open(xmlfile, 'rb')
120 data = xmlfile.read()
122 if not isinstance(data, unicode):
123 data = data.decode('utf-8')
125 data = data.replace(u'\ufeff', '')
127 # assume images are in the same directory
128 if image_store is None and xmlfile.name is not None:
129 image_store = ImageStore(path.dirname(xmlfile.name))
132 parser = etree.XMLParser(remove_blank_text=False)
133 tree = etree.parse(StringIO(data.encode('utf-8')), parser)
135 return cls(tree, parse_dublincore=parse_dublincore, image_store=image_store)
136 except (ExpatError, XMLSyntaxError, XSLTApplyError), e:
141 if self.picture_info is None:
142 raise ValueError('DC is not loaded, hence we don\'t know the image type')
143 return self.picture_info.mime_type
147 return self.picture_info.url.slug
150 def image_path(self):
151 if self.image_store is None:
152 raise ValueError("No image store associated with whis WLPicture.")
153 return self.image_store.path(self.slug, self.mime_type)
155 def image_file(self, *args, **kwargs):
156 return open(self.image_path, *args, **kwargs)
160 Iterates the parts of this picture and returns them and their metadata
162 for part in self.edoc.iter("div"):
164 pd['type'] = part.get('type')
165 if pd['type'] == 'area':
166 pd['coords'] = ((int(part.get('x1')), int(part.get('y1'))),
167 (int(part.get('x2')), int(part.get('y2'))))
173 parent = parent.getparent()
176 if parent.tag == 'sem':
177 if parent.get('type') == 'theme':
178 pd['themes'] += map(unicode.strip, unicode(parent.get('theme')).split(','))
179 elif parent.get('type') == 'object' and pd['object'] is None:
180 pd['object'] = parent.get('object')