-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathartscraper.py
76 lines (62 loc) · 2.55 KB
/
artscraper.py
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
import json
import glob
import requests
import re
import os
# Sanitize a string to create a valid filename
def sanitize_filename(filename):
invalid_chars = "<>:\"/\\|?*"
for char in invalid_chars:
filename = filename.replace(char, "_")
return filename
art_images = "art_images"
processed_log = os.path.join("art_images", ".processed_entries.json")
# Ensure the art_images directory exists
if not os.path.exists(art_images):
os.makedirs(art_images)
# Initialize or load processed entries from the log
if not os.path.exists(processed_log):
with open(processed_log, 'w') as log_file:
json.dump({"filenames": {}, "count": 0}, log_file)
with open(processed_log, 'r') as log_file:
log_data = json.load(log_file)
processed_entries = log_data["filenames"]
file_count = log_data["count"] - 1
list_JSON_paths = glob.glob(os.path.join("work", '*.json'))
for file_path in list_JSON_paths:
with open(file_path, encoding='utf-8') as f:
openJSON = json.load(f)
title = openJSON.get("title", "Unknown")
date = openJSON.get("displaydate", "")
artist = openJSON.get("attribution", "Unknown")
# Generate the filename and sanitize it
filename = sanitize_filename(f"{title}_{date}_{artist}.jpg").replace(' ', '_')
filepath = os.path.join(art_images, filename)
if filename not in processed_entries:
print(f"Processing file #{file_count + 1}: {filename}")
# Store metadata
processed_entries[filename] = {
"title": title,
"displaydate": date,
"attribution": artist
}
if not os.path.exists(filepath):
URL_to_Image = openJSON.get("iiif", "")
if URL_to_Image:
response = requests.get(URL_to_Image)
if response.status_code == 200:
with open(filepath, 'wb') as img:
img.write(response.content)
print(f"Downloaded {filename}")
file_count += 1
print(file_count)
log_data["count"] = file_count
with open(processed_log, 'w') as log_file:
json.dump(log_data, log_file, indent=4)
else:
print(f"Failed to download {filename}")
else:
print(f"{filename} already exists. Skipping download.")
else:
print(f"Skipping already processed entry: {filename}")
print("Finished processing. Total files processed: {count}")