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
22 class PictureInfo(WorkInfo):
24 Dublin core metadata for a picture
27 Field(DCNS('language'), 'language', required=False),
28 Field(DCNS('subject.period'), 'epochs', salias='epoch', multiple=True),
29 Field(DCNS('subject.type'), 'kinds', salias='kind', multiple=True),
31 Field(DCNS('format.dimensions'), 'dimensions', required=False),
32 Field(DCNS('format.checksum.sha1'), 'sha1', required=True),
33 Field(DCNS('description.medium'), 'medium', required=False),
34 Field(DCNS('description.dimensions'), 'original_dimensions', required=False),
35 Field(DCNS('format'), 'mime_type', required=False),
36 Field(DCNS('identifier.url'), 'url', WLPictureURI, strict=WLPictureURI.strict),
40 class ImageStore(object):
41 EXT = ['gif', 'jpeg', 'png', 'swf', 'psd', 'bmp'
42 'tiff', 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc',
43 'aiff', 'wbmp', 'xbm']
44 MIME = ['image/gif', 'image/jpeg', 'image/png',
45 'application/x-shockwave-flash', 'image/psd', 'image/bmp',
46 'image/tiff', 'image/tiff', 'application/octet-stream',
47 'image/jp2', 'application/octet-stream', 'application/octet-stream',
48 'application/x-shockwave-flash', 'image/iff', 'image/vnd.wap.wbmp', 'image/xbm']
50 def __init__(self, dir_):
52 return super(ImageStore, self).__init__()
54 def path(self, slug, mime_type):
56 Finds file by slug and mime type in our iamge store.
57 Returns a file objects (perhaps should return a filename?)
60 i = self.MIME.index(mime_type)
62 err = ValueError("Picture %s has unknown mime type: %s" % (slug, mime_type))
64 err.mime_type = mime_type
67 # add some common extensions tiff->tif, jpeg->jpg
68 return path.join(self.dir, slug + '.' + ext)
71 class WLPicture(object):
72 def __init__(self, edoc, parse_dublincore=True, image_store=None):
74 self.image_store = image_store
76 root_elem = edoc.getroot()
78 dc_path = './/' + RDFNS('RDF')
80 if root_elem.tag != 'picture':
81 raise ValidationError("Invalid root element. Found '%s', should be 'picture'" % root_elem.tag)
84 self.rdf_elem = root_elem.find(dc_path)
86 if self.rdf_elem is None:
87 raise NoDublinCore('Document has no DublinCore - which is required.')
89 self.picture_info = PictureInfo.from_element(self.rdf_elem)
91 self.picture_info = None
94 def from_string(cls, xml, *args, **kwargs):
95 return cls.from_file(StringIO(xml), *args, **kwargs)
98 def from_file(cls, xmlfile, parse_dublincore=True, image_store=None):
100 # first, prepare for parsing
101 if isinstance(xmlfile, basestring):
102 file = open(xmlfile, 'rb')
108 data = xmlfile.read()
110 if not isinstance(data, unicode):
111 data = data.decode('utf-8')
113 data = data.replace(u'\ufeff', '')
115 # assume images are in the same directory
116 if image_store is None and xmlfile.name is not None:
117 image_store = ImageStore(path.dirname(xmlfile.name))
120 parser = etree.XMLParser(remove_blank_text=False)
121 tree = etree.parse(StringIO(data.encode('utf-8')), parser)
123 return cls(tree, parse_dublincore=parse_dublincore, image_store=image_store)
124 except (ExpatError, XMLSyntaxError, XSLTApplyError), e:
129 if self.picture_info is None:
130 raise ValueError('DC is not loaded, hence we don\'t know the image type')
131 return self.picture_info.mime_type
135 return self.picture_info.url.slug
138 def image_path(self):
139 if self.image_store is None:
140 raise ValueError("No image store associated with whis WLPicture.")
141 return self.image_store.path(self.slug, self.mime_type)
143 def image_file(self, *args, **kwargs):
144 return open(self.image_path, *args, **kwargs)
148 Iterates the parts of this picture and returns them and their metadata
150 for part in self.edoc.iter("div"):
152 pd['type'] = part.get('type')
153 if pd['type'] == 'area':
154 pd['coords'] = ((int(part.get('x1')), int(part.get('y1'))),
155 (int(part.get('x2')), int(part.get('y2'))))
161 parent = parent.getparent()
164 if parent.tag == 'sem':
165 if parent.get('type') == 'theme':
166 pd['themes'] += map(unicode.strip, unicode(parent.get('theme')).split(','))
167 elif parent.get('type') == 'object' and pd['object'] is None:
168 pd['object'] = parent.get('object')