forked from stevenliuyi/dpm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_dzi.py
280 lines (223 loc) · 9.16 KB
/
generate_dzi.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
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
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
from bs4 import BeautifulSoup
import xml.etree.ElementTree as ET
import requests
import re
import xml.dom.minidom
import sys
import os
import pandas as pd
################################################################
## Minghua Ji (https://minghuaji.dpm.org.cn/)
################################################################
# get gv info from url (minghuaji)
def get_info_mhj():
gv_url = 'https://minghuaji.dpm.org.cn/js/gve.js'
# get response from the url
res_text = get_text_from_url(gv_url)
# find all substrings surrounded by double quotes
info = re.findall(r'"(.*?)"', res_text)
# get key and iv from the substrings
if len(info) < 5:
raise ValueError(f'Encountered error when parsing {gv_url}')
return info
# generate the dzi file
def generate_dzi_file_mhj(paint_id, info=None):
paint_url = f'https://minghuaji.dpm.org.cn/paint/appreciate?id={paint_id}'
html_string = get_text_from_url(paint_url)
soup = BeautifulSoup(html_string, 'html.parser')
image_items = soup.select_one('#gundong_id').find_all('li')
# get info
if info is None: info = get_info_mhj()
# get key and vi and use them to decrypt the encrypted string
#for i in range(len(info)): #输出info进行测试,检查info内容
# print(info2bytes(info[i]))
key = info2bytes(info[3])
iv = info2bytes(info[5])
for idx, item in enumerate(image_items):
paint_detail_url = f'{paint_url}&type={item.get("value")}'
encrypted = get_encrypted_text(paint_detail_url)
decrypted = decrypt(encrypted, key, iv)
# get xmlns and overlap
xmlns = info2bytes(info[29]).decode('utf-8')
overlap = info2bytes(info[30]).decode('utf-8')
# create dzi file
dzi_info = {
'xmlns': xmlns,
'url': decrypted[2],
'overlap': decrypted[5],
'tilesize': decrypted[1],
'format': decrypted[0],
'width': str(int(float(decrypted[4]))),
'height': str(int(float(decrypted[3]))) #修改了列表索引 2024年9月30日
}
if len(image_items) == 1:
dzi_filename = f'{paint_id}.dzi'
else:
dzi_filename = f'{paint_id}_{idx}.dzi'
write_dzi_file(dzi_filename, dzi_info)
################################################################
## Collection (https://www.dpm.org.cn/explore/collections.html)
################################################################
# get dzi info from an uncommon type of url
def get_dzi_info_bigimg(url):
html_string = get_text_from_url(url)
soup = BeautifulSoup(html_string, 'html.parser')
script = soup.find_all('script')[-1].text
if not 'OpenSeadragon' in script:
raise ValueError(f'Cannot find OpenSeadragon in {url}')
script = script.split('tileSources:')[1]
keys = ['xmlns', 'Url', 'Overlap', 'TileSize', 'Format', 'Width', 'Height']
dzi_info = {}
for key in keys:
value = re.search(rf'{key}:\s*"(.*?)",', script).group(1)
dzi_info[key.lower()] = value
return dzi_info
def generate_dzi_file_collection(paint_id):
url = f'https://www.dpm.org.cn/collection/paint/{paint_id}.html'
html_string = get_text_from_url(url)
soup = BeautifulSoup(html_string, 'html.parser')
# get dzi url
#item = soup.select_one('#hl_content')
image_items = soup.find_all('img', {'custom_tilegenerator': re.compile(r'http://en.dpm.org.cn/.*')})
tilegenerator_urls = [item.get('custom_tilegenerator').replace('dyx.html?path=/', '') for item in image_items]
# remove duplicates
tilegenerator_urls =pd.Series(tilegenerator_urls).drop_duplicates().tolist()
for idx, tilegenerator_url in enumerate(tilegenerator_urls):
if not 'bigimg' in tilegenerator_url:
tilegenerator = get_text_from_url(tilegenerator_url)
# get dzi info
root = ET.fromstring(tilegenerator)
dzi_info = {
'xmlns': root.attrib['xmnls'],
'url': tilegenerator_url.replace('http:','https:').replace('.xml', '_files/'),
'overlap': root.attrib['Overlap'],
'tilesize': root.attrib['TileSize'],
'format': root.attrib['Format'],
'width': root[0].attrib['Width'],
'height': root[0].attrib['Height']
}
else:
dzi_info = get_dzi_info_bigimg(tilegenerator_url)
if len(image_items) == 1:
dzi_filename = f'{paint_id}.dzi'
else:
dzi_filename = f'{paint_id}_{idx}.dzi'
write_dzi_file(dzi_filename, dzi_info)
################################################################
## Digital Catalog (https://digicol.dpm.org.cn/)
################################################################
# get gv info from url (digicol)
def get_info_digicol():
gv_url = 'https://digicol.dpm.org.cn/js/gve.js'
# get response from the url
res_text = get_text_from_url(gv_url)
info = re.findall(r'"(.*?)"', res_text)[3]
info = info2bytes(info).decode('utf-8').split('|')
return info
# generate the dzi file
def generate_dzi_file_digicol(paint_id, info=None):
paint_url = f'https://digicol.dpm.org.cn/cultural/listCulturalImage?id={paint_id}'
html_string = get_text_from_url(paint_url)
soup = BeautifulSoup(html_string, 'html.parser')
# get image id
image_id = soup.select_one('#swiper-wrapper-img').select_one('div').get('value')
# get info
if info is None: info = get_info_digicol()
# get key and vi and use them to decrypt the encrypted string
key = info[35].encode('utf-8')
iv = info[45].encode('utf-8')
paint_detail_url = f'https://digicol.dpm.org.cn/cultural/details?id={image_id}'
encrypted = get_encrypted_text(paint_detail_url)
decrypted = decrypt(encrypted, key, iv)
# create dzi file
dzi_info = {
'xmlns': 'http://schemas.microsoft.com/deepzoom/2009',
'url': decrypted[0],
'overlap': '1',
'tilesize': decrypted[4],
'format': decrypted[1],
'width': str(int(float(decrypted[2]))),
'height': str(int(float(decrypted[3])))
}
dzi_filename = f'{paint_id}.dzi'
write_dzi_file(dzi_filename, dzi_info)
################################################################
## common functions
################################################################
# get text from url
def get_text_from_url(url):
# get response from the url
res = requests.get(url)
# check for successful request
if res.status_code != 200:
raise ValueError(f'Encountered error when visiting {url}: {res.status_code}')
return res.text
# convert info to bytes
def info2bytes(info):
return bytes.fromhex(info.replace('\\x',''))
# decrypt the encrypted string
def decrypt(encrypted, key, iv):
# create cipher object
cipher = AES.new(key, AES.MODE_CBC, iv)
# decrypt the encrypted string
decrypted = cipher.decrypt(base64.b64decode(encrypted))
decrypted = unpad(decrypted, 16).decode('utf-8').split('^')
return decrypted
# get the encrypted string from the paint url
def get_encrypted_text(paint_url):
# get response from the url
res_text = get_text_from_url(paint_url)
# find the first substring that matches the encrypted string
match = re.search(r'gv.init\("(.*?)"', res_text)
if match:
encrypted = match.group(1)
return encrypted
else:
raise ValueError(f'Cannot find encrypted string in {paint_url}')
def generate_dzi_file(website, paint_id, info=None):
if website == 'mhj':
generate_dzi_file_mhj(paint_id, info)
elif website == 'collection':
generate_dzi_file_collection(paint_id)
elif website == 'digicol':
generate_dzi_file_digicol(paint_id, info)
else:
raise ValueError(f'Unknown website {website}')
def write_dzi_file(dzi_filename, dzi_info):
# check if paintings folder exists
if not os.path.exists('paintings'):
os.makedirs('paintings')
# create dzi file
file = open(f'paintings/{dzi_filename}', 'wb')
doc = xml.dom.minidom.Document()
image = doc.createElementNS(dzi_info['xmlns'], 'Image')
image.setAttribute('xmlns', dzi_info['xmlns'])
image.setAttribute('Url', dzi_info['url'])
image.setAttribute('Overlap', dzi_info['overlap'])
image.setAttribute('TileSize', dzi_info['tilesize'])
image.setAttribute('Format', dzi_info['format'])
size = doc.createElementNS(dzi_info['xmlns'], 'Size')
size.setAttribute('Width', dzi_info['width'])
size.setAttribute('Height', dzi_info['height'])
image.appendChild(size)
doc.appendChild(image)
descriptor = doc.toxml(encoding='UTF-8')
file.write(descriptor)
file.close()
# get gv info from url
def get_info(website):
if website == 'mhj':
return get_info_mhj()
elif website == 'collection':
return None
elif website == 'digicol':
return get_info_digicol()
if __name__ == '__main__':
# create the directory to store the dzi files
if not os.path.exists('paintings'): os.makedirs('paintings')
website = sys.argv[1]
paint_id = sys.argv[2]
generate_dzi_file(website=website, id=paint_id)