piffle 0.5.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- piffle/__init__.py +1 -0
- piffle/image.py +746 -0
- piffle/presentation.py +138 -0
- piffle-0.5.1.dist-info/METADATA +147 -0
- piffle-0.5.1.dist-info/RECORD +7 -0
- piffle-0.5.1.dist-info/WHEEL +4 -0
- piffle-0.5.1.dist-info/licenses/LICENSE +201 -0
piffle/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.5.1"
|
piffle/image.py
ADDED
|
@@ -0,0 +1,746 @@
|
|
|
1
|
+
# iiifclient
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
|
|
4
|
+
from collections import OrderedDict
|
|
5
|
+
from urllib.parse import urlparse
|
|
6
|
+
|
|
7
|
+
from cached_property import cached_property
|
|
8
|
+
import requests
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class IIIFImageClientException(Exception):
|
|
12
|
+
"""IIIFImageClient custom exception class"""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ParseError(IIIFImageClientException):
|
|
16
|
+
"""Exception raised when an IIIF image could not be parsed"""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
# NOTE: possible image component base class?
|
|
20
|
+
# commonalities so far: setting defaults on init / parse
|
|
21
|
+
# handling exact matches like full/square? (but maybe only region/size),
|
|
22
|
+
# validating options (and could add option type checking)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ImageRegion(object):
|
|
26
|
+
"""IIIF Image region. Intended to be used with :class:`IIIFImageClient`.
|
|
27
|
+
Can be initialized with related image object and region options.
|
|
28
|
+
|
|
29
|
+
When associated with an image, region is callable and will return
|
|
30
|
+
an updated image object with the modified region options.
|
|
31
|
+
|
|
32
|
+
:param img: :class:`IIFImageClient`
|
|
33
|
+
:param full: full region, defaults to true
|
|
34
|
+
:param square: square region, defaults to false
|
|
35
|
+
:param x: x coordinate
|
|
36
|
+
:param y: y coordinate
|
|
37
|
+
:param width: region width
|
|
38
|
+
:param height: region height
|
|
39
|
+
:param percent: region is a percentage
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
# region options
|
|
43
|
+
options = OrderedDict(
|
|
44
|
+
[
|
|
45
|
+
("full", False),
|
|
46
|
+
("square", False),
|
|
47
|
+
("x", None),
|
|
48
|
+
("y", None),
|
|
49
|
+
("width", None),
|
|
50
|
+
("height", None),
|
|
51
|
+
("percent", False),
|
|
52
|
+
]
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
region_defaults = {
|
|
56
|
+
"full": True,
|
|
57
|
+
"square": False,
|
|
58
|
+
"x": None,
|
|
59
|
+
"y": None,
|
|
60
|
+
"width": None,
|
|
61
|
+
"height": None,
|
|
62
|
+
"percent": False,
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
coords = ["x", "y", "width", "height"]
|
|
66
|
+
|
|
67
|
+
def __init__(self, img=None, **options):
|
|
68
|
+
self.img = img
|
|
69
|
+
self.options = self.region_defaults.copy()
|
|
70
|
+
if options:
|
|
71
|
+
self.set_options(**options)
|
|
72
|
+
|
|
73
|
+
def __call__(self, **options):
|
|
74
|
+
if self.img is not None:
|
|
75
|
+
img = self.img.get_copy()
|
|
76
|
+
img.region.set_options(**options)
|
|
77
|
+
return img
|
|
78
|
+
|
|
79
|
+
def set_options(self, **options):
|
|
80
|
+
"""Update region options. Same parameters as initialiation."""
|
|
81
|
+
allowed_options = list(self.options.keys())
|
|
82
|
+
# error if an unrecoganized option is specified
|
|
83
|
+
for key in options:
|
|
84
|
+
if key not in allowed_options:
|
|
85
|
+
raise IIIFImageClientException("Unknown option: %s" % key)
|
|
86
|
+
|
|
87
|
+
# error if some but not all coordinates are specified
|
|
88
|
+
# or if percentage is specified but not all coordinates are present
|
|
89
|
+
if (
|
|
90
|
+
any([coord in options for coord in self.coords]) or "percent" in options
|
|
91
|
+
) and not all([coord in options for coord in self.coords]):
|
|
92
|
+
# partial region specified
|
|
93
|
+
raise IIIFImageClientException("Incomplete region specified")
|
|
94
|
+
|
|
95
|
+
# TODO: do we need to type checking? bool/int/float?
|
|
96
|
+
|
|
97
|
+
self.options.update(**options)
|
|
98
|
+
# if any non-full value is specified, set full to false
|
|
99
|
+
# NOTE: if e.g. square is specified but false, this is wrong
|
|
100
|
+
allowed_options.remove("full")
|
|
101
|
+
if any([(key in allowed_options and options[key]) for key in options.keys()]):
|
|
102
|
+
self.options["full"] = False
|
|
103
|
+
|
|
104
|
+
def as_dict(self):
|
|
105
|
+
"""Return region options as a dictionary"""
|
|
106
|
+
return self.options
|
|
107
|
+
|
|
108
|
+
def __str__(self):
|
|
109
|
+
"""Render region information in IIIF region format"""
|
|
110
|
+
if self.options["full"]:
|
|
111
|
+
return "full"
|
|
112
|
+
if self.options["square"]:
|
|
113
|
+
return "square"
|
|
114
|
+
|
|
115
|
+
coords = "%(x)g,%(y)g,%(width)g,%(height)g" % self.options
|
|
116
|
+
if self.options["percent"]:
|
|
117
|
+
return "pct:%s" % coords
|
|
118
|
+
|
|
119
|
+
return coords
|
|
120
|
+
|
|
121
|
+
def parse(self, region):
|
|
122
|
+
"""Parse an IIIF Image region string and update the current region"""
|
|
123
|
+
|
|
124
|
+
# reset to defaults before parsing
|
|
125
|
+
self.options = self.region_defaults.copy()
|
|
126
|
+
|
|
127
|
+
# full?
|
|
128
|
+
if region == "full":
|
|
129
|
+
self.options["full"] = True
|
|
130
|
+
# return immediately
|
|
131
|
+
return
|
|
132
|
+
|
|
133
|
+
self.options["full"] = False
|
|
134
|
+
|
|
135
|
+
if region == "square":
|
|
136
|
+
self.options["square"] = True
|
|
137
|
+
# return immediately
|
|
138
|
+
return self
|
|
139
|
+
|
|
140
|
+
# percent?
|
|
141
|
+
if "pct" in region:
|
|
142
|
+
self.options["percent"] = True
|
|
143
|
+
region = region.split("pct:")[1]
|
|
144
|
+
|
|
145
|
+
# split to dictionary
|
|
146
|
+
# if percentage type, cast to float
|
|
147
|
+
try:
|
|
148
|
+
if self.options["percent"]:
|
|
149
|
+
coords = [float(region_c) for region_c in region.split(",")]
|
|
150
|
+
# else, force int
|
|
151
|
+
else:
|
|
152
|
+
coords = [int(region_c) for region_c in region.split(",")]
|
|
153
|
+
except ValueError:
|
|
154
|
+
# failure converting to integer or float
|
|
155
|
+
raise ParseError("Invalid region coordinates: %s" % region)
|
|
156
|
+
|
|
157
|
+
if len(coords) != 4:
|
|
158
|
+
raise ParseError("Invalid region coordinates: %s" % region)
|
|
159
|
+
|
|
160
|
+
x, y, width, height = coords
|
|
161
|
+
self.options.update({"x": x, "y": y, "width": width, "height": height})
|
|
162
|
+
|
|
163
|
+
def canonicalize(self):
|
|
164
|
+
"""Canonicalize the current region options so that
|
|
165
|
+
serialization results in canonical format."""
|
|
166
|
+
# From the spec:
|
|
167
|
+
# “full” if the whole image is requested, (including a “square”
|
|
168
|
+
# region of a square image), otherwise the x,y,w,h syntax.
|
|
169
|
+
|
|
170
|
+
if self.options["full"]:
|
|
171
|
+
# nothing to do
|
|
172
|
+
return
|
|
173
|
+
|
|
174
|
+
# if already in x,y,w,h format - nothing to do
|
|
175
|
+
if not any(
|
|
176
|
+
[self.options["full"], self.options["square"], self.options["percent"]]
|
|
177
|
+
):
|
|
178
|
+
return
|
|
179
|
+
|
|
180
|
+
# possbly an error here for every other case if self.img is not set,
|
|
181
|
+
# since it's probably not possible to canonicalize without knowing
|
|
182
|
+
# image size (any exceptions?)
|
|
183
|
+
if self.img is None:
|
|
184
|
+
raise IIIFImageClientException("Cannot canonicalize without image")
|
|
185
|
+
|
|
186
|
+
if self.options["square"]:
|
|
187
|
+
# if image is square, then return full
|
|
188
|
+
if self.img is not None and self.img.image_width == self.img.image_height:
|
|
189
|
+
self.options["full"] = True
|
|
190
|
+
self.options["square"] = False
|
|
191
|
+
return
|
|
192
|
+
|
|
193
|
+
# otherwise convert to x,y,w,h
|
|
194
|
+
# from the spec:
|
|
195
|
+
# The region is defined as an area where the width and height
|
|
196
|
+
# are both equal to the length of the shorter dimension of the
|
|
197
|
+
# complete image. The region may be positioned anywhere in the
|
|
198
|
+
# longer dimension of the image content at the server’s
|
|
199
|
+
# discretion, and centered is often a reasonable default.
|
|
200
|
+
|
|
201
|
+
# determine size of the short edge
|
|
202
|
+
short_edge = min(self.img.image_width, self.img.image_height)
|
|
203
|
+
width = height = short_edge
|
|
204
|
+
# calculate starting long edge point to center the square
|
|
205
|
+
if self.img.image_height == short_edge:
|
|
206
|
+
y = 0
|
|
207
|
+
x = (self.img.image_width - short_edge) / 2
|
|
208
|
+
else:
|
|
209
|
+
x = 0
|
|
210
|
+
y = (self.img.image_height - short_edge) / 2
|
|
211
|
+
|
|
212
|
+
self.options.update(
|
|
213
|
+
{"x": x, "y": y, "width": width, "height": height, "square": False}
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
if self.options["percent"]:
|
|
217
|
+
# convert percentages to x,y,w,h
|
|
218
|
+
# From the spec:
|
|
219
|
+
# The region to be returned is specified as a sequence of
|
|
220
|
+
# percentages of the full image’s dimensions, as reported in
|
|
221
|
+
# the image information document. Thus, x represents the number
|
|
222
|
+
# of pixels from the 0 position on the horizontal axis, calculated
|
|
223
|
+
# as a percentage of the reported width. w represents the width
|
|
224
|
+
# of the region, also calculated as a percentage of the reported
|
|
225
|
+
# width. The same applies to y and h respectively. These may be
|
|
226
|
+
# floating point numbers.
|
|
227
|
+
|
|
228
|
+
# convert percentages to dimensions based on image size
|
|
229
|
+
self.options.update(
|
|
230
|
+
{
|
|
231
|
+
"percent": False,
|
|
232
|
+
"x": int((self.options["x"] / 100) * self.img.image_width),
|
|
233
|
+
"y": int((self.options["y"] / 100) * self.img.image_height),
|
|
234
|
+
"width": int((self.options["width"] / 100) * self.img.image_width),
|
|
235
|
+
"height": int(
|
|
236
|
+
(self.options["height"] / 100) * self.img.image_height
|
|
237
|
+
),
|
|
238
|
+
}
|
|
239
|
+
)
|
|
240
|
+
return
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
class ImageSize(object):
|
|
244
|
+
"""IIIF Image Size. Intended to be used with :class:`IIIFImageClient`.
|
|
245
|
+
Can be initialized with related image object and size options.
|
|
246
|
+
|
|
247
|
+
When associated with an image, size is callable and will return
|
|
248
|
+
an updated image object with the modified size.
|
|
249
|
+
|
|
250
|
+
:param img: :class:`IIFImageClient`
|
|
251
|
+
:param width: optional width
|
|
252
|
+
:param height: optional height
|
|
253
|
+
:param percent: optional percent
|
|
254
|
+
:param exact: size should be exact (boolean, optional)
|
|
255
|
+
"""
|
|
256
|
+
|
|
257
|
+
# size options
|
|
258
|
+
options = OrderedDict(
|
|
259
|
+
[
|
|
260
|
+
("full", False),
|
|
261
|
+
("max", False),
|
|
262
|
+
("width", None),
|
|
263
|
+
("height", None),
|
|
264
|
+
("percent", None),
|
|
265
|
+
("exact", False),
|
|
266
|
+
]
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
# NOTE: full is being deprecated and replaced with max;
|
|
270
|
+
# full is deprecated in 2.1 and will be removed for 3.0
|
|
271
|
+
# Eventually piffle will need to address that, maybe with some kind of
|
|
272
|
+
# support for selecting a particular version of the IIIF image spec.
|
|
273
|
+
# For now, default size is still full, and max and full are treated as
|
|
274
|
+
# separate modes. A parsed url with max will return max, and a parsed
|
|
275
|
+
# url with full will return full, but that will probably change
|
|
276
|
+
# once the deprecated full is handled properly.
|
|
277
|
+
|
|
278
|
+
size_defaults = {
|
|
279
|
+
"full": True,
|
|
280
|
+
"max": False,
|
|
281
|
+
"width": None,
|
|
282
|
+
"height": None,
|
|
283
|
+
"percent": None,
|
|
284
|
+
"exact": False,
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
def __init__(self, img=None, **options):
|
|
288
|
+
self.img = img
|
|
289
|
+
self.options = self.size_defaults.copy()
|
|
290
|
+
if options:
|
|
291
|
+
self.set_options(**options)
|
|
292
|
+
|
|
293
|
+
def __call__(self, **options):
|
|
294
|
+
if self.img is not None:
|
|
295
|
+
img = self.img.get_copy()
|
|
296
|
+
img.size.set_options(**options)
|
|
297
|
+
return img
|
|
298
|
+
|
|
299
|
+
def set_options(self, **options):
|
|
300
|
+
"""Update size options. Same parameters as initialiation."""
|
|
301
|
+
allowed_options = list(self.options.keys())
|
|
302
|
+
# error if an unrecoganized option is specified
|
|
303
|
+
for key in options:
|
|
304
|
+
if key not in allowed_options:
|
|
305
|
+
raise IIIFImageClientException("Unknown option: %s" % key)
|
|
306
|
+
|
|
307
|
+
# TODO: do we need to type checking? bool/int/float?
|
|
308
|
+
|
|
309
|
+
self.options.update(**options)
|
|
310
|
+
# if any non-full value is specified, set full to false
|
|
311
|
+
# NOTE: if e.g. square is specified but false, this is wrong
|
|
312
|
+
allowed_options.remove("full")
|
|
313
|
+
if any([key in allowed_options and options[key] for key in options.keys()]):
|
|
314
|
+
self.options["full"] = False
|
|
315
|
+
|
|
316
|
+
def as_dict(self):
|
|
317
|
+
"""Return size options as a dictionary"""
|
|
318
|
+
return self.options
|
|
319
|
+
|
|
320
|
+
def __str__(self):
|
|
321
|
+
if self.options["full"]:
|
|
322
|
+
return "full"
|
|
323
|
+
if self.options["max"]:
|
|
324
|
+
return "max"
|
|
325
|
+
if self.options["percent"]:
|
|
326
|
+
return "pct:%g" % self.options["percent"]
|
|
327
|
+
|
|
328
|
+
size = "%s,%s" % (self.options["width"] or "", self.options["height"] or "")
|
|
329
|
+
if self.options["exact"]:
|
|
330
|
+
return "!%s" % size
|
|
331
|
+
return size
|
|
332
|
+
|
|
333
|
+
def parse(self, size):
|
|
334
|
+
# reset to defaults before parsing
|
|
335
|
+
self.options = self.size_defaults.copy()
|
|
336
|
+
|
|
337
|
+
# full?
|
|
338
|
+
if size == "full":
|
|
339
|
+
self.options["full"] = True
|
|
340
|
+
return
|
|
341
|
+
|
|
342
|
+
# for any other case, full should be false
|
|
343
|
+
self.options["full"] = False
|
|
344
|
+
|
|
345
|
+
# max?
|
|
346
|
+
if size == "max":
|
|
347
|
+
self.options["max"] = True
|
|
348
|
+
return
|
|
349
|
+
|
|
350
|
+
# percent?
|
|
351
|
+
if "pct" in size:
|
|
352
|
+
try:
|
|
353
|
+
self.options["percent"] = float(size.split(":")[1])
|
|
354
|
+
return
|
|
355
|
+
except ValueError:
|
|
356
|
+
raise ParseError("Error parsing size: %s" % size)
|
|
357
|
+
|
|
358
|
+
# exact?
|
|
359
|
+
if size.startswith("!"):
|
|
360
|
+
self.options["exact"] = True
|
|
361
|
+
size = size.lstrip("!")
|
|
362
|
+
|
|
363
|
+
# split width and height
|
|
364
|
+
width, height = size.split(",")
|
|
365
|
+
try:
|
|
366
|
+
if width != "":
|
|
367
|
+
self.options["width"] = int(width)
|
|
368
|
+
if height != "":
|
|
369
|
+
self.options["height"] = int(height)
|
|
370
|
+
except ValueError:
|
|
371
|
+
raise ParseError("Error parsing size: %s" % size)
|
|
372
|
+
|
|
373
|
+
def canonicalize(self):
|
|
374
|
+
"""Canonicalize the current size options so that
|
|
375
|
+
serialization results in canonical format."""
|
|
376
|
+
# From the spec:
|
|
377
|
+
# “full” if the default size is requested,
|
|
378
|
+
# the w, syntax for images that should be scaled maintaining the
|
|
379
|
+
# aspect ratio, and the w,h syntax for explicit sizes that change
|
|
380
|
+
# the aspect ratio.
|
|
381
|
+
# Note: The size keyword “full” will be replaced with “max” in
|
|
382
|
+
# version 3.0
|
|
383
|
+
|
|
384
|
+
if self.options["full"]:
|
|
385
|
+
# nothing to do
|
|
386
|
+
return
|
|
387
|
+
|
|
388
|
+
# possbly an error here for every other case if self.img is not set,
|
|
389
|
+
# since it's probably not possible to canonicalize without knowing
|
|
390
|
+
# image size (any exceptions?)
|
|
391
|
+
if self.img is None:
|
|
392
|
+
raise IIIFImageClientException("Cannot canonicalize without image")
|
|
393
|
+
|
|
394
|
+
if self.options["percent"]:
|
|
395
|
+
# convert percentage to w,h
|
|
396
|
+
scale = self.options["percent"] / 100
|
|
397
|
+
self.options.update(
|
|
398
|
+
{
|
|
399
|
+
"height": int(self.img.image_height * scale),
|
|
400
|
+
"width": int(self.img.image_width * scale),
|
|
401
|
+
"percent": None,
|
|
402
|
+
}
|
|
403
|
+
)
|
|
404
|
+
return
|
|
405
|
+
|
|
406
|
+
if self.options["exact"]:
|
|
407
|
+
# from the spec:
|
|
408
|
+
# The image content is scaled for the best fit such that the
|
|
409
|
+
# resulting width and height are less than or equal to the
|
|
410
|
+
# requested width and height. The exact scaling may be determined
|
|
411
|
+
# by the service provider, based on characteristics including
|
|
412
|
+
# image quality and system performance. The dimensions of the
|
|
413
|
+
# returned image content are calculated to maintain the aspect
|
|
414
|
+
# ratio of the extracted region.
|
|
415
|
+
|
|
416
|
+
# determine which edge results in a smaller scale
|
|
417
|
+
wscale = float(self.options["width"]) / float(self.img.image_width)
|
|
418
|
+
hscale = float(self.options["height"]) / float(self.img.image_height)
|
|
419
|
+
scale = min(wscale, hscale)
|
|
420
|
+
# use that scale on original image size, to preserve
|
|
421
|
+
# original aspect ratio
|
|
422
|
+
self.options.update(
|
|
423
|
+
{
|
|
424
|
+
"exact": False,
|
|
425
|
+
"height": int(scale * self.img.image_height),
|
|
426
|
+
"width": int(scale * self.img.image_width),
|
|
427
|
+
}
|
|
428
|
+
)
|
|
429
|
+
return
|
|
430
|
+
|
|
431
|
+
# if height only is specified (,h), convert to width only (w,)
|
|
432
|
+
if self.options["height"] and self.options["width"] is None:
|
|
433
|
+
# determine the scale in use, and convert from
|
|
434
|
+
# height only to width only
|
|
435
|
+
scale = float(self.options["height"]) / float(self.img.image_height)
|
|
436
|
+
self.options.update(
|
|
437
|
+
{"height": None, "width": int(scale * self.img.image_width)}
|
|
438
|
+
)
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
class ImageRotation(object):
|
|
442
|
+
"""IIIF Image rotation Intended to be used with :class:`IIIFImageClient`.
|
|
443
|
+
Can be initialized with related image object and rotation options.
|
|
444
|
+
|
|
445
|
+
When associated with an image, rotation is callable and will return
|
|
446
|
+
an updated image object with the modified rotatoin options.
|
|
447
|
+
|
|
448
|
+
:param img: :class:`IIFImageClient`
|
|
449
|
+
:param degrees: degrees rotation, optional
|
|
450
|
+
:param mirrored: image should be mirrored (boolean, optional, default
|
|
451
|
+
is False)
|
|
452
|
+
"""
|
|
453
|
+
|
|
454
|
+
# rotation options
|
|
455
|
+
options = OrderedDict(
|
|
456
|
+
[
|
|
457
|
+
("degrees", None),
|
|
458
|
+
("mirrored", False),
|
|
459
|
+
]
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
rotation_defaults = {"degrees": 0, "mirrored": False}
|
|
463
|
+
|
|
464
|
+
def __init__(self, img=None, **options):
|
|
465
|
+
self.img = img
|
|
466
|
+
self.options = self.rotation_defaults.copy()
|
|
467
|
+
if options:
|
|
468
|
+
self.set_options(**options)
|
|
469
|
+
|
|
470
|
+
def __call__(self, **options):
|
|
471
|
+
if self.img is not None:
|
|
472
|
+
img = self.img.get_copy()
|
|
473
|
+
img.rotation.set_options(**options)
|
|
474
|
+
return img
|
|
475
|
+
|
|
476
|
+
def set_options(self, **options):
|
|
477
|
+
"""Update size options. Same parameters as initialiation."""
|
|
478
|
+
allowed_options = self.options.keys()
|
|
479
|
+
# error if an unrecoganized option is specified
|
|
480
|
+
for key in options:
|
|
481
|
+
if key not in allowed_options:
|
|
482
|
+
raise IIIFImageClientException("Unknown option: %s" % key)
|
|
483
|
+
|
|
484
|
+
# TODO: do we need to type checking? bool/int/float?
|
|
485
|
+
|
|
486
|
+
self.options.update(**options)
|
|
487
|
+
|
|
488
|
+
def as_dict(self):
|
|
489
|
+
"""Return rotation options as a dictionary"""
|
|
490
|
+
return self.options
|
|
491
|
+
|
|
492
|
+
def __str__(self):
|
|
493
|
+
return "%s%g" % (
|
|
494
|
+
"!" if self.options["mirrored"] else "",
|
|
495
|
+
self.options["degrees"],
|
|
496
|
+
)
|
|
497
|
+
|
|
498
|
+
def parse(self, rotation):
|
|
499
|
+
# reset to defaults before parsing
|
|
500
|
+
self.options = self.rotation_defaults.copy()
|
|
501
|
+
|
|
502
|
+
if str(rotation).startswith("!"):
|
|
503
|
+
self.options["mirrored"] = True
|
|
504
|
+
rotation = rotation.lstrip("!")
|
|
505
|
+
|
|
506
|
+
# rotation allows float
|
|
507
|
+
self.options["degrees"] = float(rotation)
|
|
508
|
+
|
|
509
|
+
def canonicalize(self):
|
|
510
|
+
"""Canonicalize the current region options so that
|
|
511
|
+
serialization results in canonical format."""
|
|
512
|
+
# NOTE: explicitly including a canonicalize as a method to make it
|
|
513
|
+
# clear that this field supports canonicalization, but no work
|
|
514
|
+
# is needed since the existing render does the right things:
|
|
515
|
+
# - trim any trailing zeros in a decimal value
|
|
516
|
+
# - leading zero if less than 1
|
|
517
|
+
# - ! if mirrored, followed by integer if possible
|
|
518
|
+
return
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
class IIIFImageClient(object):
|
|
522
|
+
"""Simple IIIF Image API client for generating IIIF image urls
|
|
523
|
+
in an object-oriented, pythonic fashion. Can be extended,
|
|
524
|
+
when custom logic is needed to set the image id. Provides
|
|
525
|
+
a fluid interface, so that IIIF methods can be chained, e.g.::
|
|
526
|
+
|
|
527
|
+
iiif_img.size(width=300).rotation(90).format('png')
|
|
528
|
+
|
|
529
|
+
Note that this returns a new image instance with the specified
|
|
530
|
+
options, and the original image will remain unchanged.
|
|
531
|
+
|
|
532
|
+
.. Note::
|
|
533
|
+
|
|
534
|
+
Method to set quality not yet available.
|
|
535
|
+
"""
|
|
536
|
+
|
|
537
|
+
api_endpoint = None
|
|
538
|
+
image_id = None
|
|
539
|
+
default_format = "jpg"
|
|
540
|
+
|
|
541
|
+
# iiif defaults for each sections
|
|
542
|
+
image_defaults = {
|
|
543
|
+
"quality": "default", # color, gray, bitonal, default
|
|
544
|
+
"fmt": default_format,
|
|
545
|
+
}
|
|
546
|
+
allowed_formats = ["jpg", "tif", "png", "gif", "jp2", "pdf", "webp"]
|
|
547
|
+
|
|
548
|
+
def __init__(
|
|
549
|
+
self,
|
|
550
|
+
api_endpoint=None,
|
|
551
|
+
image_id=None,
|
|
552
|
+
region=None,
|
|
553
|
+
size=None,
|
|
554
|
+
rotation=None,
|
|
555
|
+
quality=None,
|
|
556
|
+
fmt=None,
|
|
557
|
+
):
|
|
558
|
+
self.image_options = self.image_defaults.copy()
|
|
559
|
+
# NOTE: using underscore to differenteate objects from methods
|
|
560
|
+
# but it could be reasonable to make objects public
|
|
561
|
+
self.region = ImageRegion(self)
|
|
562
|
+
self.size = ImageSize(self)
|
|
563
|
+
self.rotation = ImageRotation(self)
|
|
564
|
+
|
|
565
|
+
if api_endpoint is not None:
|
|
566
|
+
# remove any trailing slash to avoid duplicate slashes
|
|
567
|
+
self.api_endpoint = api_endpoint.rstrip("/")
|
|
568
|
+
|
|
569
|
+
# FIXME: image_id is not required on init to allow subclassing
|
|
570
|
+
# and customizing via get_image_id, but should probably cause
|
|
571
|
+
# an error if you attempt to serialize the url and it is not set
|
|
572
|
+
# (same for a few other options, probably, too...)
|
|
573
|
+
if image_id is not None:
|
|
574
|
+
self.image_id = image_id
|
|
575
|
+
|
|
576
|
+
# for now, if region option is specified parse as string
|
|
577
|
+
if region is not None:
|
|
578
|
+
self.region.parse(region)
|
|
579
|
+
if size is not None:
|
|
580
|
+
self.size.parse(size)
|
|
581
|
+
if rotation is not None:
|
|
582
|
+
self.rotation.parse(rotation)
|
|
583
|
+
|
|
584
|
+
if quality is not None:
|
|
585
|
+
self.image_options["quality"] = quality
|
|
586
|
+
if fmt is not None:
|
|
587
|
+
self.image_options["fmt"] = fmt
|
|
588
|
+
|
|
589
|
+
def get_image_id(self):
|
|
590
|
+
"Image id to be used in contructing urls"
|
|
591
|
+
return self.image_id
|
|
592
|
+
|
|
593
|
+
def __str__(self):
|
|
594
|
+
info = self.image_options.copy()
|
|
595
|
+
info.update(
|
|
596
|
+
{
|
|
597
|
+
"endpoint": self.api_endpoint,
|
|
598
|
+
"id": self.get_image_id(),
|
|
599
|
+
"region": str(self.region),
|
|
600
|
+
"size": str(self.size),
|
|
601
|
+
"rot": str(self.rotation),
|
|
602
|
+
}
|
|
603
|
+
)
|
|
604
|
+
return (
|
|
605
|
+
"%(endpoint)s/%(id)s/%(region)s/%(size)s/%(rot)s/%(quality)s.%(fmt)s" % info
|
|
606
|
+
)
|
|
607
|
+
|
|
608
|
+
def __repr__(self):
|
|
609
|
+
return "<IIIFImageClient %s>" % self.get_image_id()
|
|
610
|
+
# include non-defaults?
|
|
611
|
+
|
|
612
|
+
def info(self):
|
|
613
|
+
"JSON info url"
|
|
614
|
+
return "%(endpoint)s/%(id)s/info.json" % {
|
|
615
|
+
"endpoint": self.api_endpoint,
|
|
616
|
+
"id": self.get_image_id(),
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
@cached_property
|
|
620
|
+
def image_info(self):
|
|
621
|
+
"Retrieve image information provided as JSON at info url"
|
|
622
|
+
resp = requests.get(self.info())
|
|
623
|
+
if resp.status_code == requests.codes.ok:
|
|
624
|
+
return resp.json()
|
|
625
|
+
|
|
626
|
+
resp.raise_for_status()
|
|
627
|
+
|
|
628
|
+
@property
|
|
629
|
+
def image_width(self):
|
|
630
|
+
"Image width as reported in :attr:`image_info`"
|
|
631
|
+
return self.image_info["width"]
|
|
632
|
+
|
|
633
|
+
@property
|
|
634
|
+
def image_height(self):
|
|
635
|
+
"Image height as reported in :attr:`image_info`"
|
|
636
|
+
return self.image_info["height"]
|
|
637
|
+
|
|
638
|
+
def get_copy(self):
|
|
639
|
+
"Get a clone of the current settings for modification."
|
|
640
|
+
clone = self.__class__(self.api_endpoint, self.image_id, **self.image_options)
|
|
641
|
+
# copy region, size, and rotation - no longer included in
|
|
642
|
+
# image_options dict
|
|
643
|
+
clone.region.set_options(**self.region.as_dict())
|
|
644
|
+
clone.size.set_options(**self.size.as_dict())
|
|
645
|
+
clone.rotation.set_options(**self.rotation.as_dict())
|
|
646
|
+
return clone
|
|
647
|
+
|
|
648
|
+
# method to set quality not yet implemented
|
|
649
|
+
|
|
650
|
+
def format(self, image_format):
|
|
651
|
+
"Set output image format"
|
|
652
|
+
if image_format not in self.allowed_formats:
|
|
653
|
+
raise IIIFImageClientException("Image format %s unknown" % image_format)
|
|
654
|
+
img = self.get_copy()
|
|
655
|
+
img.image_options["fmt"] = image_format
|
|
656
|
+
return img
|
|
657
|
+
|
|
658
|
+
def canonicalize(self):
|
|
659
|
+
"""Canonicalize the URI"""
|
|
660
|
+
img = self.get_copy()
|
|
661
|
+
img.region.canonicalize()
|
|
662
|
+
img.size.canonicalize()
|
|
663
|
+
img.rotation.canonicalize()
|
|
664
|
+
return img
|
|
665
|
+
|
|
666
|
+
@classmethod
|
|
667
|
+
def init_from_url(cls, url):
|
|
668
|
+
"""Init ImageClient using Image API parameters from URI. Detect
|
|
669
|
+
image vs. info request. Can count reliably from the end of the URI
|
|
670
|
+
backwards, but cannot assume how many slashes make up the api_endpoint.
|
|
671
|
+
Returns new instance of IIIFImageClient.
|
|
672
|
+
Per http://iiif.io/api/image/2.0/#image-request-uri-syntax, using
|
|
673
|
+
slashes to parse URI"""
|
|
674
|
+
|
|
675
|
+
# first parse as a url
|
|
676
|
+
parsed_url = urlparse(url)
|
|
677
|
+
# then split the path on slashes
|
|
678
|
+
# and remove any empty strings
|
|
679
|
+
path_components = [path for path in parsed_url.path.split("/") if path]
|
|
680
|
+
if not path_components:
|
|
681
|
+
raise ParseError("Invalid IIIF image url: %s" % url)
|
|
682
|
+
# pop off last portion of the url to determine if this is an info url
|
|
683
|
+
path_basename = path_components.pop()
|
|
684
|
+
opts = {}
|
|
685
|
+
|
|
686
|
+
# info request
|
|
687
|
+
if path_basename == "info.json":
|
|
688
|
+
# NOTE: this is unlikely to happen; more likely, if information is
|
|
689
|
+
# missing, we will misinterpret the api endpoint or the image id
|
|
690
|
+
if len(path_components) < 1:
|
|
691
|
+
raise ParseError("Invalid IIIF image information url: %s" % url)
|
|
692
|
+
image_id = path_components.pop()
|
|
693
|
+
|
|
694
|
+
# image request
|
|
695
|
+
else:
|
|
696
|
+
# check for enough IIIF parameters
|
|
697
|
+
if len(path_components) < 4:
|
|
698
|
+
raise ParseError("Invalid IIIF image request: %s" % url)
|
|
699
|
+
|
|
700
|
+
# pop off url portions as they are used so we can easily
|
|
701
|
+
# make use of leftover path to reconstruct the api endpoint
|
|
702
|
+
quality, fmt = path_basename.split(".")
|
|
703
|
+
rotation = path_components.pop()
|
|
704
|
+
size = path_components.pop()
|
|
705
|
+
region = path_components.pop()
|
|
706
|
+
image_id = path_components.pop()
|
|
707
|
+
opts.update(
|
|
708
|
+
{
|
|
709
|
+
"region": region,
|
|
710
|
+
"size": size,
|
|
711
|
+
"rotation": rotation,
|
|
712
|
+
"quality": quality,
|
|
713
|
+
"fmt": fmt,
|
|
714
|
+
}
|
|
715
|
+
)
|
|
716
|
+
|
|
717
|
+
# construct the api endpoint url from the parsed url and whatever
|
|
718
|
+
# portions of the url path are leftover
|
|
719
|
+
# remove empty strings from the remaining path components
|
|
720
|
+
path_components = [p for p in path_components if p]
|
|
721
|
+
api_endpoint = "%s://%s/%s" % (
|
|
722
|
+
parsed_url.scheme,
|
|
723
|
+
parsed_url.netloc,
|
|
724
|
+
"/".join(path_components) if path_components else "",
|
|
725
|
+
)
|
|
726
|
+
|
|
727
|
+
# init and return instance
|
|
728
|
+
return cls(api_endpoint=api_endpoint, image_id=image_id, **opts)
|
|
729
|
+
|
|
730
|
+
def as_dict(self):
|
|
731
|
+
"""
|
|
732
|
+
Dictionary of with all image request options.
|
|
733
|
+
request parameters. Returns a dictionary with all image request
|
|
734
|
+
parameters parsed to their most granular level. Can be helpful
|
|
735
|
+
for acting logically on particular request parameters like height,
|
|
736
|
+
width, mirroring, etc.
|
|
737
|
+
"""
|
|
738
|
+
return OrderedDict(
|
|
739
|
+
[
|
|
740
|
+
("region", self.region.as_dict()),
|
|
741
|
+
("size", self.size.as_dict()),
|
|
742
|
+
("rotation", self.rotation.as_dict()),
|
|
743
|
+
("quality", self.image_options["quality"]),
|
|
744
|
+
("format", self.image_options["fmt"]),
|
|
745
|
+
]
|
|
746
|
+
)
|
piffle/presentation.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os.path
|
|
3
|
+
import urllib
|
|
4
|
+
|
|
5
|
+
import addict
|
|
6
|
+
|
|
7
|
+
import requests
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class IIIFException(Exception):
|
|
11
|
+
"""Custom exception for IIIF errors"""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def get_iiif_url(url):
|
|
15
|
+
"""Wrapper around :meth:`requests.get` to support conditionally
|
|
16
|
+
adding an auth tokens or other parameters."""
|
|
17
|
+
request_options = {}
|
|
18
|
+
# TODO: need some way of configuring hooks for e.g. setting auth tokens
|
|
19
|
+
return requests.get(url, **request_options)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class IIIFPresentation(addict.Dict):
|
|
23
|
+
""":class:`addict.Dict` subclass for read access to IIIF Presentation
|
|
24
|
+
content"""
|
|
25
|
+
|
|
26
|
+
# TODO: document sample use, e.g. @ fields
|
|
27
|
+
|
|
28
|
+
at_fields = ["type", "id", "context"]
|
|
29
|
+
|
|
30
|
+
@classmethod
|
|
31
|
+
def from_file(cls, path):
|
|
32
|
+
"""Initialize :class:`IIIFPresentation` from a file."""
|
|
33
|
+
with open(path) as manifest:
|
|
34
|
+
data = json.loads(manifest.read())
|
|
35
|
+
return cls(data)
|
|
36
|
+
|
|
37
|
+
@classmethod
|
|
38
|
+
def from_url(cls, uri):
|
|
39
|
+
"""Iniitialize :class:`IIIFPresentation` from a URL.
|
|
40
|
+
|
|
41
|
+
:raises: :class:`IIIFException` if URL is not retrieved successfully,
|
|
42
|
+
if the response is not JSON content, or if the JSON cannot be parsed.
|
|
43
|
+
"""
|
|
44
|
+
response = get_iiif_url(uri)
|
|
45
|
+
if response.status_code == requests.codes.ok:
|
|
46
|
+
try:
|
|
47
|
+
return cls(response.json())
|
|
48
|
+
except json.decoder.JSONDecodeError as err:
|
|
49
|
+
# if json fails, two possibilities:
|
|
50
|
+
# - we didn't actually get json (e.g. redirect for auth)
|
|
51
|
+
if "application/json" not in response.headers["content-type"]:
|
|
52
|
+
raise IIIFException("No JSON found at %s" % uri)
|
|
53
|
+
# - there is something wrong with the json
|
|
54
|
+
raise IIIFException("Error parsing JSON for %s: %s" % (uri, err))
|
|
55
|
+
|
|
56
|
+
raise IIIFException(
|
|
57
|
+
"Error retrieving manifest at %s: %s %s"
|
|
58
|
+
% (uri, response.status_code, response.reason)
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
@classmethod
|
|
62
|
+
def is_url(cls, url):
|
|
63
|
+
"""Utility method to check if a path is a url or file"""
|
|
64
|
+
return urllib.parse.urlparse(url).scheme != ""
|
|
65
|
+
|
|
66
|
+
@classmethod
|
|
67
|
+
def from_file_or_url(cls, path):
|
|
68
|
+
"""Iniitialize :class:`IIIFPresentation` from a file or a url."""
|
|
69
|
+
if os.path.isfile(path):
|
|
70
|
+
return cls.from_file(path)
|
|
71
|
+
elif cls.is_url(path):
|
|
72
|
+
return cls.from_url(path)
|
|
73
|
+
else:
|
|
74
|
+
raise IIIFException("File not found: %s" % path)
|
|
75
|
+
|
|
76
|
+
@classmethod
|
|
77
|
+
def short_id(cls, uri):
|
|
78
|
+
"""Generate a short id from full manifest/canvas uri identifiers
|
|
79
|
+
for use in local urls. Logic is based on the recommended
|
|
80
|
+
url pattern from the IIIF Presentation 2.0 specification."""
|
|
81
|
+
|
|
82
|
+
# shortening should work reliably for uris that follow
|
|
83
|
+
# recommended url patterns from the spec
|
|
84
|
+
# http://iiif.io/api/presentation/2.0/#a-summary-of-recommended-uri-patterns
|
|
85
|
+
# manifest: {scheme}://{host}/{prefix}/{identifier}/manifest
|
|
86
|
+
# canvas: {scheme}://{host}/{prefix}/{identifier}/canvas/{name}
|
|
87
|
+
|
|
88
|
+
# remove trailing /manifest at the end of the url, if present
|
|
89
|
+
if uri.endswith("/manifest"):
|
|
90
|
+
uri = uri[: -len("/manifest")]
|
|
91
|
+
# split on slashes and return the last portion
|
|
92
|
+
return uri.split("/")[-1]
|
|
93
|
+
|
|
94
|
+
def __missing__(self, key):
|
|
95
|
+
raise KeyError(self._key(key))
|
|
96
|
+
|
|
97
|
+
def _key(self, key):
|
|
98
|
+
# convert key to @key if in the list of fields that requires it
|
|
99
|
+
if key in self.at_fields:
|
|
100
|
+
key = "@%s" % key
|
|
101
|
+
return key
|
|
102
|
+
|
|
103
|
+
def __getattr__(self, key):
|
|
104
|
+
try:
|
|
105
|
+
# addict getattr just calls getitem
|
|
106
|
+
return super().__getattr__(self._key(key))
|
|
107
|
+
except KeyError:
|
|
108
|
+
# python hasattr checks for attribute error
|
|
109
|
+
# translate key error to attribute error,
|
|
110
|
+
# since in an attr dict it's kind of both
|
|
111
|
+
raise AttributeError
|
|
112
|
+
|
|
113
|
+
def __getitem__(self, key):
|
|
114
|
+
"""
|
|
115
|
+
Access a value associated with a key.
|
|
116
|
+
"""
|
|
117
|
+
val = super().__getitem__(self._key(key))
|
|
118
|
+
return val
|
|
119
|
+
|
|
120
|
+
def __setitem__(self, key, value):
|
|
121
|
+
"""
|
|
122
|
+
Add a key-value pair to the instance.
|
|
123
|
+
"""
|
|
124
|
+
return super().__setitem__(self._key(key), value)
|
|
125
|
+
|
|
126
|
+
def __delitem__(self, key):
|
|
127
|
+
"""
|
|
128
|
+
Delete a key-value pair
|
|
129
|
+
"""
|
|
130
|
+
super().__delitem__(self._key(key))
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def first_label(self):
|
|
134
|
+
# label can be a string or list of strings
|
|
135
|
+
if isinstance(self.label, str):
|
|
136
|
+
return self.label
|
|
137
|
+
else:
|
|
138
|
+
return self.label[0]
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: piffle
|
|
3
|
+
Version: 0.5.1
|
|
4
|
+
Summary: Python library for working with IIIF Image and Presentation APIs
|
|
5
|
+
Project-URL: Homepage, https://github.com/princeton-cdh/piffle
|
|
6
|
+
Project-URL: Repository, https://github.com/princeton-cdh/piffle
|
|
7
|
+
Project-URL: Changelog, https://github.com/Princeton-CDH/piffle/blob/main/README.md
|
|
8
|
+
Author-email: The Center for Digital Humanities at Princeton <cdhdevteam@princeton.edu>
|
|
9
|
+
License: Apache License, Version 2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: iiif
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
15
|
+
Classifier: Natural Language :: English
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
24
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
25
|
+
Requires-Python: >=3.8
|
|
26
|
+
Requires-Dist: addict
|
|
27
|
+
Requires-Dist: cached-property
|
|
28
|
+
Requires-Dist: requests
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: pre-commit; extra == 'dev'
|
|
31
|
+
Requires-Dist: pytest-cov; extra == 'dev'
|
|
32
|
+
Requires-Dist: pytest>=3.6; extra == 'dev'
|
|
33
|
+
Provides-Extra: test
|
|
34
|
+
Requires-Dist: pytest-cov; extra == 'test'
|
|
35
|
+
Requires-Dist: pytest>=3.6; extra == 'test'
|
|
36
|
+
Description-Content-Type: text/markdown
|
|
37
|
+
|
|
38
|
+
# piffle
|
|
39
|
+
|
|
40
|
+
Python library for generating and parsing [IIIF Image API](http://iiif.io/api/image/2.1/) URLs in an
|
|
41
|
+
object-oriented, pythonic fashion.
|
|
42
|
+
|
|
43
|
+
[](https://github.com/Princeton-CDH/piffle/actions/workflows/unit_tests.yml)
|
|
44
|
+
[](https://codecov.io/gh/Princeton-CDH/piffle)
|
|
45
|
+
[](https://codeclimate.com/github/Princeton-CDH/piffle/maintainability)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
Piffle is tested on Python 3.8—3.12.
|
|
49
|
+
|
|
50
|
+
Piffle was originally developed by Rebecca Sutton Koeser at Emory University as a part of [Readux](https://github.com/ecds/readux) and forked as a separate project under [emory-lits-labs](https://github.com/emory-lits-labs/). It was later transferred to Rebecca Sutton Koeser at the Center for Digital Humanities at Princeton.
|
|
51
|
+
|
|
52
|
+
## Installation and example use:
|
|
53
|
+
|
|
54
|
+
`pip install piffle`
|
|
55
|
+
|
|
56
|
+
Example use for generating an IIIF image url:
|
|
57
|
+
|
|
58
|
+
```
|
|
59
|
+
>>> from piffle.image import IIIFImageClient
|
|
60
|
+
>>> myimg = IIIFImageClient('http://image.server/path/', 'myimgid')
|
|
61
|
+
>>> print myimg
|
|
62
|
+
http://image.server/path/myimgid/full/full/0/default.jpg
|
|
63
|
+
>>> print myimg.info()
|
|
64
|
+
http://image.server/path/myimgid/info.json"
|
|
65
|
+
>>> print myimg.size(width=120).format('png')
|
|
66
|
+
http://image.server/path/myimgid/full/120,/0/default.png
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Example use for parsing an IIIF image url:
|
|
70
|
+
|
|
71
|
+
```
|
|
72
|
+
>>> from piffle.image import IIIFImageClient
|
|
73
|
+
>>> myimg = IIIFImageClient.init_from_url('http://www.example.org/image-service/abcd1234/full/full/0/default.jpg')
|
|
74
|
+
>>> print myimg
|
|
75
|
+
http://www.example.org/image-service/abcd1234/full/full/0/default.jpg
|
|
76
|
+
>>> print myimg.info()
|
|
77
|
+
http://www.example.org/image-service/abcd1234/info.json
|
|
78
|
+
>>> myimg.as_dict()['size']['full']
|
|
79
|
+
True
|
|
80
|
+
>>> myimg.as_dict()['size']['exact']
|
|
81
|
+
False
|
|
82
|
+
>>> myimg.as_dict()['rotation']['degrees']
|
|
83
|
+
0.0
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Example use for reading a IIIF manifest:
|
|
87
|
+
|
|
88
|
+
```
|
|
89
|
+
>>> from piffle.image import IIIFImageClient
|
|
90
|
+
>>> from piffle.presentation import IIIFPresentation
|
|
91
|
+
>>> manifest = IIIFPresentation.from_url('https://iiif.bodleian.ox.ac.uk/iiif/manifest/60834383-7146-41ab-bfe1-48ee97bc04be.json')
|
|
92
|
+
>>> manifest.label
|
|
93
|
+
'Bodleian Library MS. Bodl. 264'
|
|
94
|
+
>>> manifest.id
|
|
95
|
+
'https://iiif.bodleian.ox.ac.uk/iiif/manifest/60834383-7146-41ab-bfe1-48ee97bc04be.json'
|
|
96
|
+
>>> manifest.type
|
|
97
|
+
'sc:Manifest'
|
|
98
|
+
>>> for canvas in manifest.sequences[0].canvases[:5]:
|
|
99
|
+
... image_id = canvas.images[0].resource.id
|
|
100
|
+
... iiif_img = IIIFImageClient(*image_id.rsplit('/', 1))
|
|
101
|
+
... print(str(iiif_img.size(height=250)))
|
|
102
|
+
...
|
|
103
|
+
https://iiif.bodleian.ox.ac.uk/iiif/image/90701d49-5e0c-4fb5-9c7d-45af96565468/full/,250/0/default.jpg
|
|
104
|
+
https://iiif.bodleian.ox.ac.uk/iiif/image/e878cc78-acd3-43ca-ba6e-90a392f15891/full/,250/0/default.jpg
|
|
105
|
+
https://iiif.bodleian.ox.ac.uk/iiif/image/0f1ed064-a972-4215-b884-d8d658acefc5/full/,250/0/default.jpg
|
|
106
|
+
https://iiif.bodleian.ox.ac.uk/iiif/image/6fe52b9a-5bb7-4b5b-bbcd-ad0489fcad2a/full/,250/0/default.jpg
|
|
107
|
+
https://iiif.bodleian.ox.ac.uk/iiif/image/483ff8ec-347d-4070-8442-dbc15bc7b4de/full/,250/0/default.jpg
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Development and Testing
|
|
111
|
+
|
|
112
|
+
This project uses [git-flow](https://github.com/nvie/gitflow) branching conventions.
|
|
113
|
+
|
|
114
|
+
Install locally for development (the use of a python virtualenv is recommended):
|
|
115
|
+
|
|
116
|
+
`pip install -e .`
|
|
117
|
+
|
|
118
|
+
Install test dependencies:
|
|
119
|
+
|
|
120
|
+
`pip install -e ".[dev]"`
|
|
121
|
+
|
|
122
|
+
Run unit tests: `py.test` or `python setup.py test`
|
|
123
|
+
|
|
124
|
+
### Install pre-commit hooks
|
|
125
|
+
|
|
126
|
+
Anyone who wants to contribute to this codebase should install the configured pre-commit hooks:
|
|
127
|
+
|
|
128
|
+
```
|
|
129
|
+
pre-commit install
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
This will configure a pre-commit hooks to automatically lint and format python code with [ruff](https://github.com/astral-sh/ruff) and [black](https://github.com/psf/black).
|
|
133
|
+
|
|
134
|
+
Pre-commit hooks and formatting conventions were added at version 0.5, so ``git blame`` may not reflect the true author of a given change. To make ``git blame`` more accurate, ignore formatting revisions:
|
|
135
|
+
|
|
136
|
+
```
|
|
137
|
+
git blame <FILE> --ignore-revs-file .git-blame-ignore-revs
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Or configure your git to always ignore styling revision commits:
|
|
141
|
+
```
|
|
142
|
+
git config blame.ignoreRevsFile .git-blame-ignore-revs
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## Publishing python packages
|
|
146
|
+
|
|
147
|
+
A new python package is automatically built and published to [PyPI](https://pypi.python.org/pypi) using a GitHub Actions workflow when a new release is created on GitHub.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
piffle/__init__.py,sha256=eZ1bOun1DDVV0YLOBW4wj2FP1ajReLjbIrGmzN7ASBw,22
|
|
2
|
+
piffle/image.py,sha256=bli2O_t4MMQmw9AF-W9mTLN_fFcx2LCoQIX95j-wB68,26486
|
|
3
|
+
piffle/presentation.py,sha256=TAcNvfRbaggHsqp-RVX2yYaY4qcfqBEYov7bCE8OOpc,4591
|
|
4
|
+
piffle-0.5.1.dist-info/METADATA,sha256=u8LR39DZT0PCJHNV09q2PQsmz79F1CuJWbAZ8fAxt3A,5968
|
|
5
|
+
piffle-0.5.1.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
|
|
6
|
+
piffle-0.5.1.dist-info/licenses/LICENSE,sha256=tAkwu8-AdEyGxGoSvJ2gVmQdcicWw3j1ZZueVV74M-E,11357
|
|
7
|
+
piffle-0.5.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright {yyyy} {name of copyright owner}
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|