-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIIIFcrawler.php
More file actions
350 lines (324 loc) · 9.91 KB
/
IIIFcrawler.php
File metadata and controls
350 lines (324 loc) · 9.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
<?php
/**
* IIIF Crawler - See README.md for details.
*
* PHP version 8
*
* Copyright (C) Villanova University 2015-2026.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see
* <https://www.gnu.org/licenses/>.
*
* @author Demian Katz <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
*/
// Validate URL parameter
$url = isset($argv[1]) ? $argv[1] : null;
if (empty($url)) {
die("Usage: {$argv[0]} [IIIF Manifest URL] [MIME type to harvest]\n");
}
// Default MIME parameter to image/jpeg if not supplied
$mime = isset($argv[2]) ? $argv[2] : 'image/jpeg';
// Create the crawler
$crawler = new Crawler($url, $mime);
$data = $crawler->crawl(getcwd());
extract($data);
$errors = $crawler->getErrors();
// Done! Report results.
echo "$harvested $mime file(s) harvested from $urlCount URL(s).\n";
if (!empty($errors)) {
echo "ERRORS:\n" . implode("\n", $errors) . "\n";
}
/**
* Crawler class.
*/
class Crawler
{
/**
* Starting point URL
*
* @var string
*/
protected $startUrl;
/**
* MIME type to harvest
*
* @var string
*/
protected $mime;
/**
* File extension to use on saved files
*
* @var string
*/
protected $extension;
/**
* Error list
*
* @var array
*/
protected $errors = [];
/**
* Retrieved URL count
*
* @var int
*/
protected $urlCount = 0;
/**
* Harvested file count
*
* @var int
*/
protected $harvested = 0;
/**
* Constructor
*
* @param string $url Starting point URL
* @param string $mime MIME type to harvest
*/
public function __construct($url, $mime)
{
$this->startUrl = $url;
$this->mime = $mime;
$this->extension = $this->getExtensionFromMime($mime);
}
/**
* Start the crawling process; return array of statistical data.
*
* @param string $targetDir Directory to harvest files into.
*
* @return array
*/
public function crawl($targetDir)
{
$this->getUrl($this->startUrl, $targetDir);
return ['harvested' => $this->harvested, 'urlCount' => $this->urlCount];
}
/**
* Retrieve the contents of a URL.
*
* @param string $url URL to fetch.
* @param string $targetDir Directory to harvest files into.
*
* @return void
*/
protected function getUrl($url, $targetDir)
{
// Load the JSON
if (!$json = file_get_contents($url)) {
return $this->addError("Problem retrieving $url.\n");
}
// Parse the JSON
if (!$data = json_decode($json)) {
return $this->addError("Problem decoding JSON from $url.\n");
}
// Increment counter
$this->urlCount++;
// Detect collections or sequences within the data:
$members = $this->checkForCollectionMembers($data);
if (!empty($members)) {
return $this->harvestCollection($members, $targetDir);
}
if (!empty($data->sequences) && is_array($data->sequences)) {
return $this->harvestFromV2Manifest($data, $targetDir);
}
if (!empty($data->items) && is_array($data->items)) {
return $this->harvestFromV3Manifest($data, $targetDir);
}
// If we found nothing, fail:
return $this->addError("No collections or sequences found in manifest.\n");
}
/**
* Given JSON extracted from a IIIF URL, check for collection contents. Return an
* empty array if nothing relevant is found.
*
* @param array $data Raw JSON data.
*
* @return array
*/
protected function checkForCollectionMembers($data)
{
$members = isset($data->members) && is_array($data->members)
? $data->members : [];
if (isset($data->collections) && is_array($data->collections)) {
$members = array_merge($members, $data->collections);
}
if (isset($data->manifests) && is_array($data->manifests)) {
$members = array_merge($members, $data->manifests);
}
return $members;
}
/**
* Given JSON extracted from a IIIF collection, harvest all sub-parts.
*
* @param array $members Members to harvest.
* @param string $targetDir Directory to harvest files into.
*
* @return void
*/
protected function harvestCollection($members, $targetDir)
{
$prefix = 0;
foreach ($members as $member) {
$dirName = preg_replace('/[^a-zA-Z0-9-_]+/', '_', $member->label);
$newTarget = $targetDir . '/' . str_pad($prefix, 10, '0', STR_PAD_LEFT) . '-' . $dirName;
if (!file_exists($newTarget) && !is_dir($newTarget)) {
mkdir($newTarget);
}
echo "Loading collection content: " . $member->{'@id'} . "\n";
$this->getUrl($member->{'@id'}, $newTarget);
$prefix++;
}
}
/**
* Given JSON data representing a v2 manifest, harvest all images.
*
* @param array $data Manifest data
* @param string $targetDir Directory to harvest files into.
*
* @return void
*/
protected function harvestFromV2Manifest($data, $targetDir)
{
// Loop through sequences
foreach ($data->sequences as $seqNum => $sequence) {
if (!isset($sequence->canvases) || !is_array($sequence->canvases)
|| empty($sequence->canvases)
) {
echo "No canvases found in sequence $seqNum.\n";
continue;
}
// Loop through canvases
foreach ($sequence->canvases as $canvNum => $canvas) {
// Grab the next file
$nextFilename = $targetDir . '/' . $this->getFilename($seqNum, $canvNum);
if (!$this->saveMatchingFile($canvas, $nextFilename)) {
echo "No matching {$this->mime} found for sequence $seqNum, canvas $canvNum\n";
} else {
echo "Saved $nextFilename\n";
$this->harvested++;
}
}
}
}
/**
* Given JSON data representing a v3 manifest, harvest all images.
*
* @param array $data Manifest data
* @param string $targetDir Directory to harvest files into.
*
* @return void
*/
protected function harvestFromV3Manifest($data, $targetDir)
{
// Loop through canvases
foreach ($data->items as $canvNum => $canvas) {
// Grab the next file
$nextFilename = $targetDir . '/' . $this->getFilename(0, $canvNum);
if (!$this->saveMatchingFile($canvas, $nextFilename)) {
echo "No matching {$this->mime} found for canvas $canvNum\n";
} else {
echo "Saved $nextFilename\n";
$this->harvested++;
}
}
}
/**
* Log an error.
*
* @param string $error Message to log
*
* @return void
*/
protected function addError($error)
{
$this->errors[] = $error;
}
/**
* Get the logged errors.
*
* @return array
*/
public function getErrors()
{
return $this->errors;
}
/**
* Return a file extension for the given MIME type.
*
* @param string $mime MIME type
*
* @return string
*/
protected function getExtensionFromMime($mime)
{
switch ($mime) {
case 'image/tiff':
return 'tif';
case 'image/jpeg':
return 'jpg';
case 'text/plain':
return 'txt';
default:
return 'bin';
}
}
/**
* Determine a filename based on sequence and canvas numbers.
*
* @param int $seqNum Sequence number
* @param int $canvNum Canvas number
*
* @return string
*/
protected function getFilename($seqNum, $canvNum)
{
return str_pad($seqNum, 10, '0', STR_PAD_LEFT) . '-'
. str_pad($canvNum, 10, '0', STR_PAD_LEFT) . '.' . $this->extension;
}
/**
* Extract a file matching a mime type from a canvas and save it to disk.
* Return true if match found, false otherwise.
*
* @param array $canvas Canvas to search
* @param string $file Filename to save
*
* @return bool
*/
protected function saveMatchingFile($canvas, $file)
{
foreach (['images', 'items', 'rendering'] as $section) {
if (isset($canvas->$section) && is_array($canvas->$section)) {
foreach ($canvas->$section as $item) {
if ($section == 'images') {
$item = $item->resource;
}
if ($section == 'items') {
$item = $item->items[0];
}
$itemId = $item->{'@id'} ?? $item->id ?? null;
$format = $item->format ?? $item->body->format ?? null;
if ($format == $this->mime && $itemId) {
if (file_exists($file)) {
echo "$file already exists; skipping...\n";
} else {
file_put_contents($file, file_get_contents($itemId));
}
return true;
}
}
}
}
return false;
}
}