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),
34 Field(DCNS('format.dimensions'), 'dimensions', required=False),
35 Field(DCNS('format.checksum.sha1'), 'sha1', required=True),
36 Field(DCNS('description.medium'), 'medium', required=False),
37 Field(DCNS('description.dimensions'), 'original_dimensions', required=False),
38 Field(DCNS('format'), 'mime_type', required=False),
39 Field(DCNS('identifier.url'), 'url', WLPictureURI,
40 strict=as_wlpictureuri_strict),
44 class ImageStore(object):
45 EXT = ['gif', 'jpeg', 'png', 'swf', 'psd', 'bmp'
46 'tiff', 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc',
47 'aiff', 'wbmp', 'xbm']
48 MIME = ['image/gif', 'image/jpeg', 'image/png',
49 'application/x-shockwave-flash', 'image/psd', 'image/bmp',
50 'image/tiff', 'image/tiff', 'application/octet-stream',
51 'image/jp2', 'application/octet-stream', 'application/octet-stream',
52 'application/x-shockwave-flash', 'image/iff', 'image/vnd.wap.wbmp', 'image/xbm']
54 def __init__(self, dir_):
56 return super(ImageStore, self).__init__()
58 def path(self, slug, mime_type):
60 Finds file by slug and mime type in our iamge store.
61 Returns a file objects (perhaps should return a filename?)
64 i = self.MIME.index(mime_type)
66 err = ValueError("Picture %s has unknown mime type: %s" % (slug, mime_type))
68 err.mime_type = mime_type
71 # add some common extensions tiff->tif, jpeg->jpg
72 return path.join(self.dir, slug + '.' + ext)
75 class WLPicture(object):
76 def __init__(self, edoc, parse_dublincore=True, image_store=None):
78 self.image_store = image_store
80 root_elem = edoc.getroot()
82 dc_path = './/' + RDFNS('RDF')
84 if root_elem.tag != 'picture':
85 raise ValidationError("Invalid root element. Found '%s', should be 'picture'" % root_elem.tag)
88 self.rdf_elem = root_elem.find(dc_path)
90 if self.rdf_elem is None:
91 raise NoDublinCore('Document has no DublinCore - which is required.')
93 self.picture_info = PictureInfo.from_element(self.rdf_elem)
95 self.picture_info = None
98 def from_string(cls, xml, *args, **kwargs):
99 return cls.from_file(StringIO(xml), *args, **kwargs)
102 def from_file(cls, xmlfile, parse_dublincore=True, image_store=None):
104 # first, prepare for parsing
105 if isinstance(xmlfile, basestring):
106 file = open(xmlfile, 'rb')
112 data = xmlfile.read()
114 if not isinstance(data, unicode):
115 data = data.decode('utf-8')
117 data = data.replace(u'\ufeff', '')
119 # assume images are in the same directory
120 if image_store is None and xmlfile.name is not None:
121 image_store = ImageStore(path.dirname(xmlfile.name))
124 parser = etree.XMLParser(remove_blank_text=False)
125 tree = etree.parse(StringIO(data.encode('utf-8')), parser)
127 return cls(tree, parse_dublincore=parse_dublincore, image_store=image_store)
128 except (ExpatError, XMLSyntaxError, XSLTApplyError), e:
133 if self.picture_info is None:
134 raise ValueError('DC is not loaded, hence we don\'t know the image type')
135 return self.picture_info.mime_type
139 return self.picture_info.url.slug
142 def image_path(self):
143 if self.image_store is None:
144 raise ValueError("No image store associated with whis WLPicture.")
145 return self.image_store.path(self.slug, self.mime_type)
147 def image_file(self, *args, **kwargs):
148 return open(self.image_path, *args, **kwargs)
152 Iterates the parts of this picture and returns them and their metadata
154 for part in self.edoc.iter("div"):
156 pd['type'] = part.get('type')
157 if pd['type'] == 'area':
158 pd['coords'] = ((int(part.get('x1')), int(part.get('y1'))),
159 (int(part.get('x2')), int(part.get('y2'))))
165 parent = parent.getparent()
168 if parent.tag == 'sem':
169 if parent.get('type') == 'theme':
170 pd['themes'] += map(unicode.strip, unicode(parent.get('theme')).split(','))
171 elif parent.get('type') == 'object' and pd['object'] is None:
172 pd['object'] = parent.get('object')