-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
505 lines (438 loc) · 18 KB
/
Copy pathserver.py
File metadata and controls
505 lines (438 loc) · 18 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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
import socketserver
import socket
import http.server
import json
import cgi
from http.server import HTTPServer, BaseHTTPRequestHandler
import os
import random
import re
class Response:
NONE = "201-None"
DATA_NOT_FOUND = "401-DataNotFound"
# 获得本机 IP
def get_host_ip():
try:
# 创建一个 socket 对象
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 连接到一个公共 DNS 服务器(可以随便选择)
s.connect(("8.8.8.8", 80))
# 获取本地 IP 地址
ip_address = s.getsockname()[0]
finally:
s.close()
return ip_address
IP = get_host_ip()
# 设置服务器端口
PORT = 8000
url = f"http://{IP}:{PORT}"
# 一些本地路径
from utils.path import root
image_dir = os.path.join(root, "images")
user_data_dir = os.path.join(root, "users/datas")
# http://10.133.4.94:8000/image?group=FourLLIE&id=00690
# 服务器 HTTP 处理器
class UserStudyHandler(BaseHTTPRequestHandler):
# 获取所有图像方法
@staticmethod
def get_groups(exclude_groups=None):
groups = os.listdir(image_dir)
if exclude_groups is None:
return groups
return [group for group in groups if group not in exclude_groups]
# 获取所有的图像 ID
@staticmethod
def get_image_ids():
image_ids = []
for group in UserStudyHandler.get_groups():
tmp_image_ids = []
for image_id in os.listdir(os.path.join(image_dir, group)):
tmp_image_ids.append(image_id)
# 取交集
if len(image_ids) == 0:
image_ids = tmp_image_ids
else:
image_ids = list(set(image_ids) & set(tmp_image_ids))
return image_ids
# 判断用户 ID 是否合法
@staticmethod
def check_available_user_id(user_id):
illlegal_chars = r'\\|/|\*|~|"|<|>|\|'
if re.search(illlegal_chars, user_id):
return False
return True
def do_GET(self):
# 获取请求路径
path = self.path
# e.g. /image?group=FourLLIE&id=00690.png
if path.startswith("/image?"):
# 获取所有 params
params = dict(param.split("=") for param in path.split("?")[1].split("&"))
group = params["group"]
image_id = params["id"]
# 发送响应头
self.send_response(200)
self.send_header("Content-type", "image/jpeg")
self.end_headers()
# 发送响应体
if '.' not in image_id:
image_id += '.png'
image_path = os.path.join(image_dir, group, image_id)
with open(image_path, "rb") as f:
self.wfile.write(f.read())
# e.g. /images/FourLLIE/00690.png
elif path.startswith("/images/"):
image_path = path[1:]
if ".." in image_path:
self.send_response(404)
self.end_headers()
return
# 发送响应体
if os.path.isdir(image_path):
# # 发送响应头
# self.send_response(200)
# self.send_header("Content-type", "application/json")
# self.end_headers()
#
# # 发送目录结构
# dir_path = {"paths": os.listdir(image_path)}
# json_data = json.dumps(dir_path)
# self.wfile.write(json_data.encode())
pass
if os.path.isfile(image_path):
# 发送响应头
self.send_response(200)
self.send_header("Content-type", "image/jpeg")
self.end_headers()
# 发送图片
with open(image_path, "rb") as f:
self.wfile.write(f.read())
else:
self.send_response(404)
self.end_headers()
return
# e.g. /image_ids, /image_ids?group=FourLLIE
elif path.startswith("/image_ids"):
# 获取所有 params
if len(path.split("?")) > 1:
params = dict(param.split("=") for param in path.split("?")[1].split("&"))
else:
params = {}
# 发送响应头
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
# 发送指定组的图片 ID 列表
image_ids = []
if params.get("group"):
group = params["group"]
for image_id in os.listdir(os.path.join(image_dir, group)):
image_ids.append(os.path.splitext(image_id)[0])
else:
image_ids = self.get_image_ids()
# 排序
image_ids.sort()
# 发送响应体
json_data = json.dumps({"ids": image_ids})
self.wfile.write(json_data.encode())
# 获取所有图像组
elif path.startswith("/image_groups"):
# 获取所有 params
if len(path.split("?")) > 1:
params = dict(param.split("=") for param in path.split("?")[1].split("&"))
else:
params = {}
# 发送所有组的名称列表
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
exclude_groups = None
if params.get("exclude"):
exclude_groups = params["exclude"].split(",")
image_groups = self.get_groups(exclude_groups)
# 发送响应体
json_data = json.dumps({"groups": image_groups})
self.wfile.write(json_data.encode())
# 获取所有图像组的数量(除了 input 和 GT)
elif path.startswith("/available_image_groups_number"):
# 获取所有 params
if len(path.split("?")) > 1:
params = dict(param.split("=") for param in path.split("?")[1].split("&"))
else:
params = {}
# 发送所有组的名称列表
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
exclude_groups = None
if params.get("exclude"):
exclude_groups = params["exclude"].split(",")
image_groups = self.get_groups(exclude_groups)
# 发送响应体
json_data = json.dumps({"number": len(image_groups)})
self.wfile.write(json_data.encode())
elif path.startswith("/js/"):
css_path = path[1:]
if ".." in css_path:
self.send_response(404)
self.end_headers()
return
if os.path.isfile(css_path):
# 发送响应头
self.send_response(200)
self.send_header("Content-type", "text/javascript")
self.end_headers()
# 发送响应体
with open(css_path, "rb") as f:
self.wfile.write(f.read())
else:
self.send_response(404)
self.end_headers()
return
elif path.startswith("/css/"):
css_path = path[1:]
if ".." in css_path:
self.send_response(404)
self.end_headers()
return
if os.path.isfile(css_path):
# 发送响应头
self.send_response(200)
self.send_header("Content-type", "text/css")
self.end_headers()
# 发送响应体
with open(css_path, "rb") as f:
self.wfile.write(f.read())
else:
self.send_response(404)
self.end_headers()
return
elif path == "/style.css":
# 发送响应头
self.send_response(200)
self.send_header("Content-type", "text/css")
self.end_headers()
# 发送响应体
with open("style.css", "rb") as f:
self.wfile.write(f.read())
# 服务器数据
elif path.startswith("/server"):
# 处理默认请求
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
# 发送响应体
with open("index.html", "rb") as f:
self.wfile.write(f.read())
# 用户注册时,检查用户是否存在
elif path.startswith("/interface/contains_user?"):
# 获取所有 params
params = dict(param.split("=") for param in path.split("?")[1].split("&"))
user_id = params["user_id"]
any_exist = False
if self.check_available_user_id(user_id):
# 处理默认请求
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
# 检查文件 users/datas/ 下是否包含 {user_id}.dat 文件
dat_path = os.path.join(user_data_dir, f"{user_id}.dat")
any_exist = os.path.exists(dat_path)
print(f"User {user_id} exists: {any_exist}")
# 发送响应体
json_data = json.dumps({"exists": any_exist})
self.wfile.write(json_data.encode())
# 用户 User-Study 测验界面
elif path.startswith("/interface?"):
# 处理默认请求
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
# 发送响应体
with open("pages/interface.html", "rb") as f:
self.wfile.write(f.read())
# 用户 User-Study 测验界面
elif path.startswith("/interface/"):
# 处理默认请求
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
# 发送响应体
with open("pages/interface.html", "rb") as f:
self.wfile.write(f.read())
# 其他 html 界面
elif path.startswith("/html"):
path = path[6:]
if ".." in path:
self.send_response(404)
self.end_headers()
return
if os.path.isfile(path) and path.endswith(".html"):
# 发送响应头
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
# 发送响应体
with open(path, "rb") as f:
self.wfile.write(f.read())
else:
self.send_response(404)
self.end_headers()
return
# 用户登录界面
elif path.startswith("/"):
# 处理默认请求
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
# 发送响应体
with open("pages/login.html", "rb") as f:
self.wfile.write(f.read())
else:
# 处理其他请求
self.send_response(404)
self.end_headers()
def get_select_id(self, can_select_ids):
# 随机选取一个 ID
if not self.get_groups():
select_id = Response.DATA_NOT_FOUND
elif can_select_ids is None or len(can_select_ids) == 0:
select_id = Response.NONE
else:
select_id = random.choice(can_select_ids)
return select_id
def do_POST(self):
# 获取请求路径
path = self.path
# e.g. /interface/select?user_id=test
if path.startswith("/interface/select?"):
# 获取所有 params
params = dict(param.split("=") for param in path.split("?")[1].split("&"))
user_id = params["user_id"]
# 处理不合法请求
if not self.check_available_user_id(user_id):
# 获取 ID
select_id = self.get_select_id(None)
# 发送响应体
json_data = json.dumps({"next_id": select_id})
self.wfile.write(json_data.encode())
return
dat_path = os.path.join(user_data_dir, f"{user_id}.dat")
print(f"User {user_id} selected an image.", end=" ")
try:
# 处理传送的数据,为 form-data 的格式
form = cgi.FieldStorage(
fp=self.rfile,
environ={"REQUEST_METHOD": "POST", "CONTENT_TYPE": self.headers["Content-Type"]}
)
data = {field: form.getvalue(field) for field in form}
print(f"Data: {data}")
select_id = data["select_id"]
select_group = data["select_group"]
# 将数据写入文件
if select_id != "None" and select_group != "None":
print(f"Selected image ID: {select_id}, Group: {select_group}")
any_exist = os.path.exists(dat_path)
if any_exist:
# 将 select_gid 以 append 方式写入文件
with open(dat_path, "a") as f:
if data.get("select_id") and data["select_id"] != Response.NONE:
f.write(f"{select_id}, {select_group}\n")
else:
# 创建文件并写入 select_gid
with open(dat_path, "w") as f:
if data.get("select_id") and data["select_id"] != Response.NONE:
f.write(f"{select_id}, {select_group}\n")
else:
print("No image selected.")
except Exception as e:
print(f"\nError: {e}")
# 处理默认请求
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
# 读入文件内容
select_ids = []
if os.path.exists(dat_path):
with open(dat_path, "r") as f:
select_ids = f.read().strip().split(",")[0]
# 计算可以选取的 ID,即 image_ids 中不包含 select_ids 的 ID
image_ids = self.get_image_ids()
can_select_ids = list(set(image_ids) - set(select_ids))
# 获取 ID
select_id = self.get_select_id(can_select_ids)
# 发送响应体
json_data = json.dumps({"next_id": select_id})
self.wfile.write(json_data.encode())
elif path.startswith("/interface/rating?"):
# 获取所有 params
params = dict(param.split("=") for param in path.split("?")[1].split("&"))
user_id = params["user_id"]
# 处理不合法请求
if not self.check_available_user_id(user_id):
# 获取 ID
select_id = self.get_select_id(None)
# 发送响应体
json_data = json.dumps({"next_id": select_id})
self.wfile.write(json_data.encode())
return
dat_path = os.path.join(user_data_dir, f"{user_id}.dat")
print(f"User {user_id} selected an image.", end=" ")
try:
# 处理传送的数据,为 form-data 的格式
form = cgi.FieldStorage(
fp=self.rfile,
environ={"REQUEST_METHOD": "POST", "CONTENT_TYPE": self.headers["Content-Type"]}
)
data = {field: form.getvalue(field) for field in form}
print(f"Data: {data}")
# 将数据写入文件
any_exist = os.path.exists(dat_path)
if any_exist:
# 将 select_gid 以 append 方式写入文件
with open(dat_path, "a") as f:
if data.get("id") and data["id"] != Response.NONE:
f.write(f"{data}\n")
else:
# 创建文件并写入 select_gid
with open(dat_path, "w") as f:
if data.get("id") and data["id"] != Response.NONE:
f.write(f"{data}\n")
except Exception as e:
print(f"\nError: {e}")
# 处理默认请求
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
# 读入文件内容(其中的 id)
select_ids = []
if os.path.exists(dat_path):
with open(dat_path, "r") as f:
read_datas = f.read().strip().split("\n")
for read_data in read_datas:
id_re = re.findall(r"'id': '(.*?)'", read_data)
if id_re:
_id = id_re[0]
select_ids.append(_id)
# 计算可以选取的 ID,即 image_ids 中不包含 select_ids 的 ID
image_ids = self.get_image_ids()
can_select_ids = list(set(image_ids) - set(select_ids))
# 获取 ID
select_id = self.get_select_id(can_select_ids)
# 发送响应体
json_data = json.dumps({"next_id": select_id})
self.wfile.write(json_data.encode())
if __name__ == "__main__":
os.makedirs(user_data_dir, exist_ok=True)
with HTTPServer((IP, PORT), UserStudyHandler) as httpd:
print(f"Server started at {url}/")
# 设置 print 的输出文件
import sys
import datetime
os.makedirs("logs", exist_ok=True)
time = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
sys.stdout = open(f"logs/server_{time}.log", "w")
# 创建一个服务器,并绑定到指定的端口
print(f"Server started at {url}/")
# 开始监听并处理请求
httpd.serve_forever()