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('format.dimensions.digital'), 'dimensions', required=False),
34 Field(DCNS('format.dimensions.original'), 'dimensions_original', required=False),
35 Field(DCNS('format.physical'), 'physical', required=False),
36 Field(DCNS('format'), 'mime_type', required=False),
37 Field(DCNS('identifier.url'), 'url', WLPictureURI),
42 WorkInfo has a language validation code only, which we do not need.
47 class ImageStore(object):
48 EXT = ['gif', 'jpeg', 'png', 'swf', 'psd', 'bmp'
49 'tiff', 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc',
50 'aiff', 'wbmp', 'xbm']
51 MIME = ['image/gif', 'image/jpeg', 'image/png',
52 'application/x-shockwave-flash', 'image/psd', 'image/bmp',
53 'image/tiff', 'image/tiff', 'application/octet-stream',
54 'image/jp2', 'application/octet-stream', 'application/octet-stream',
55 'application/x-shockwave-flash', 'image/iff', 'image/vnd.wap.wbmp', 'image/xbm']
57 def __init__(self, dir_):
59 return super(ImageStore, self).__init__()
61 def path(self, slug, mime_type):
63 Finds file by slug and mime type in our iamge store.
64 Returns a file objects (perhaps should return a filename?)
67 i = self.MIME.index(mime_type)
69 err = ValueError("Picture %s has unknown mime type: %s" % (slug, mime_type))
71 err.mime_type = mime_type
74 # add some common extensions tiff->tif, jpeg->jpg
75 return path.join(self.dir, slug + '.' + ext)
78 class WLPicture(object):
79 def __init__(self, edoc, parse_dublincore=True, image_store=None):
81 self.image_store = image_store
83 root_elem = edoc.getroot()
85 dc_path = './/' + RDFNS('RDF')
87 if root_elem.tag != 'picture':
88 raise ValidationError("Invalid root element. Found '%s', should be 'picture'" % root_elem.tag)
91 self.rdf_elem = root_elem.find(dc_path)
93 if self.rdf_elem is None:
94 raise NoDublinCore('Document has no DublinCore - which is required.')
96 self.picture_info = PictureInfo.from_element(self.rdf_elem)
98 self.picture_info = None
101 def from_string(cls, xml, *args, **kwargs):
102 return cls.from_file(StringIO(xml), *args, **kwargs)
105 def from_file(cls, xmlfile, parse_dublincore=True, image_store=None):
107 # first, prepare for parsing
108 if isinstance(xmlfile, basestring):
109 file = open(xmlfile, 'rb')
115 data = xmlfile.read()
117 if not isinstance(data, unicode):
118 data = data.decode('utf-8')
120 data = data.replace(u'\ufeff', '')
122 # assume images are in the same directory
123 if image_store is None and xmlfile.name is not None:
124 image_store = ImageStore(path.dirname(xmlfile.name))
127 parser = etree.XMLParser(remove_blank_text=False)
128 tree = etree.parse(StringIO(data.encode('utf-8')), parser)
130 return cls(tree, parse_dublincore=parse_dublincore, image_store=image_store)
131 except (ExpatError, XMLSyntaxError, XSLTApplyError), e:
136 if self.picture_info is None:
137 raise ValueError('DC is not loaded, hence we don\'t know the image type')
138 return self.picture_info.mime_type
142 return self.picture_info.url.slug
145 def image_path(self):
146 if self.image_store is None:
147 raise ValueError("No image store associated with whis WLPicture.")
148 return self.image_store.path(self.slug, self.mime_type)
150 def image_file(self, *args, **kwargs):
151 return open(self.image_path, *args, **kwargs)