-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathserver.py
More file actions
2074 lines (1832 loc) · 63.2 KB
/
Copy pathserver.py
File metadata and controls
2074 lines (1832 loc) · 63.2 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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations
from pathlib import Path
from flask import Flask, abort, send_file, Response, request, redirect
import mimetypes
import sqlite3
import json
import html
import config as cfg
from io import BytesIO
import render_daily_photo as rdp
ROOT_DIR = Path(__file__).resolve().parent
# --- config ---
DOWNLOAD_KEY = str(getattr(cfg, "DOWNLOAD_KEY", "") or "").strip()
if not DOWNLOAD_KEY:
raise SystemExit("config.py 里没有配置 DOWNLOAD_KEY")
DB_PATH = Path(str(getattr(cfg, "DB_PATH", "./photos.db") or "./photos.db")).expanduser()
if not DB_PATH.is_absolute():
DB_PATH = (ROOT_DIR / DB_PATH).resolve()
IMAGE_DIR = Path(str(getattr(cfg, "IMAGE_DIR", "") or "")).expanduser()
if not IMAGE_DIR.is_absolute():
IMAGE_DIR = (ROOT_DIR / IMAGE_DIR).resolve()
BIN_OUTPUT_DIR = Path(str(getattr(cfg, "BIN_OUTPUT_DIR", "./output") or "./output")).expanduser()
if not BIN_OUTPUT_DIR.is_absolute():
BIN_OUTPUT_DIR = (ROOT_DIR / BIN_OUTPUT_DIR).resolve()
BIN_OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
FLASK_HOST = str(getattr(cfg, "FLASK_HOST", "0.0.0.0") or "0.0.0.0")
FLASK_PORT = int(getattr(cfg, "FLASK_PORT", 8765) or 8765)
# 是否开启照片库 WebUI(跑通后建议关闭,只保留 ESP32 下载接口)
ENABLE_REVIEW_WEBUI = bool(getattr(cfg, "ENABLE_REVIEW_WEBUI", True))
DAILY_PHOTO_QUANTITY = int(getattr(cfg, "DAILY_PHOTO_QUANTITY", 5) or 5)
if DAILY_PHOTO_QUANTITY < 1:
DAILY_PHOTO_QUANTITY = 1
# review 分页:每页 100 张
REVIEW_PAGE_SIZE = 100
# /review 日期筛选的可用 MM-DD 列表缓存(避免每次都扫全库)
_MD_CACHE: dict[str, object] = {"md_list": [], "built_at": 0.0}
_MD_CACHE_TTL_SEC = 300.0 # 5 分钟
def _load_all_md_list() -> list[str]:
"""从全库提取所有存在的 MM-DD(去重、排序)。用于前端“随机一天”。"""
if not DB_PATH.exists():
return []
# 简单 TTL 缓存
import time
now = time.time()
try:
built_at = float(_MD_CACHE.get("built_at") or 0.0)
except Exception:
built_at = 0.0
if (now - built_at) < _MD_CACHE_TTL_SEC:
cached = _MD_CACHE.get("md_list")
if isinstance(cached, list):
return [str(x) for x in cached]
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
rows = c.execute("SELECT exif_json FROM photo_scores").fetchall()
conn.close()
s: set[str] = set()
for (exif_json,) in rows:
d = extract_date_from_exif(exif_json)
if d and len(d) >= 10:
md = d[5:10]
if len(md) == 5 and md[2] == "-":
s.add(md)
md_list = sorted(s)
_MD_CACHE["md_list"] = md_list
_MD_CACHE["built_at"] = now
return md_list
app = Flask(__name__)
def _require_webui_enabled() -> None:
if not ENABLE_REVIEW_WEBUI:
abort(404)
def _safe_join(base: Path, rel: str) -> Path:
"""防目录穿越:只允许 base 下的相对路径"""
p = (base / rel).resolve()
if not str(p).startswith(str(base.resolve())):
raise ValueError("path traversal blocked")
return p
def _send_static_file(p: Path) -> Response:
if not p.exists() or not p.is_file():
abort(404)
if p.suffix.lower() == ".bin":
return send_file(p, mimetype="application/octet-stream", as_attachment=False)
mt, _ = mimetypes.guess_type(str(p))
if mt:
return send_file(p, mimetype=mt, as_attachment=False)
return send_file(p, as_attachment=False)
def _make_image_url(path_str: str) -> str:
"""
把数据库里的本地图片路径转换成 HTTP 可访问的 /images/... 路径。
要求图片在 IMAGE_DIR 目录下;不在则返回空,避免 file:// 污染与 canvas 跨域。
"""
try:
p = Path(path_str).expanduser().resolve()
rel = p.relative_to(IMAGE_DIR.resolve())
return "/images/" + str(rel).replace("\\", "/")
except Exception:
return ""
# --------------------------
# DB helpers
# --------------------------
def load_rows(page: int = 1, page_size: int = REVIEW_PAGE_SIZE, md: str = "", sort: str = "memory"):
"""分页读取 review 数据。支持按 MM-DD 过滤与排序。返回 (rows, total_count)."""
if not DB_PATH.exists():
raise SystemExit(f"找不到数据库文件: {DB_PATH}")
if page < 1:
page = 1
if page_size < 1:
page_size = REVIEW_PAGE_SIZE
offset = (page - 1) * page_size
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
# 从 exif_json 里提取 datetime,再拼 MM-DD
# 期望格式:"YYYY:MM:DD HH:MM:SS"(extract_date_from_exif 也按这个假设)
dt_expr = "json_extract(exif_json, '$.datetime')"
md_expr = f"(substr({dt_expr}, 6, 2) || '-' || substr({dt_expr}, 9, 2))"
where_sql = ""
params: list[object] = []
md = (md or "").strip()
if md and len(md) == 5 and md[2] == "-":
where_sql = f"WHERE {dt_expr} IS NOT NULL AND {md_expr} = ?"
params.append(md)
# total_count 也要跟随过滤
if where_sql:
total_count = c.execute(f"SELECT COUNT(1) FROM photo_scores {where_sql}", params).fetchone()[0]
else:
total_count = c.execute("SELECT COUNT(1) FROM photo_scores").fetchone()[0]
# 排序
sort = (sort or "memory").strip()
if sort == "beauty":
order_sql = "ORDER BY COALESCE(beauty_score, -1) DESC, COALESCE(memory_score, -1) DESC, path"
elif sort == "time_new":
# 直接按 datetime 字符串排序(固定格式下可按字典序比较);NULL 放最后
order_sql = f"ORDER BY ({dt_expr} IS NULL) ASC, {dt_expr} DESC, path"
elif sort == "time_old":
order_sql = f"ORDER BY ({dt_expr} IS NULL) ASC, {dt_expr} ASC, path"
else:
# 默认 memory
order_sql = "ORDER BY COALESCE(memory_score, -1) DESC, COALESCE(beauty_score, -1) DESC, path"
base_sql = f"""
SELECT path,
caption,
type,
memory_score,
beauty_score,
reason,
exif_json,
width,
height,
orientation,
used_at,
side_caption
FROM photo_scores
{where_sql}
{order_sql}
LIMIT ? OFFSET ?
"""
q_params = list(params) + [page_size, offset]
rows = c.execute(base_sql, q_params).fetchall()
conn.close()
return rows, int(total_count)
def load_sim_rows():
if not DB_PATH.exists():
raise SystemExit(f"找不到数据库文件: {DB_PATH}")
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
rows = c.execute(
"""
SELECT path,
caption,
type,
memory_score,
beauty_score,
reason,
side_caption,
exif_json,
width,
height,
orientation,
used_at,
exif_gps_lat,
exif_gps_lon,
exif_city
FROM photo_scores
"""
).fetchall()
conn.close()
return rows
# 新增:只加载指定日期集合的照片,加速 /sim
def load_sim_rows_for_dates(dates: list[str]):
"""只加载指定日期(YYYY-MM-DD)集合内的照片,用于 /sim 加速。"""
if not dates:
return []
if not DB_PATH.exists():
raise SystemExit(f"找不到数据库文件: {DB_PATH}")
# 过滤掉不合法日期字符串,避免 SQL 注入(虽然我们用参数化,但也别喂垃圾)
safe_dates = []
for d in dates:
d = (d or "").strip()
if len(d) == 10 and d[4] == "-" and d[7] == "-":
safe_dates.append(d)
if not safe_dates:
return []
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
dt_expr = "json_extract(exif_json, '$.datetime')"
# exif datetime 形如 YYYY:MM:DD HH:MM:SS,取前 10 位并把 : 替换成 - -> YYYY-MM-DD
date_expr = f"replace(substr({dt_expr}, 1, 10), ':', '-')"
placeholders = ",".join(["?"] * len(safe_dates))
sql = f"""
SELECT path,
caption,
type,
memory_score,
beauty_score,
reason,
side_caption,
exif_json,
width,
height,
orientation,
used_at,
exif_gps_lat,
exif_gps_lon,
exif_city
FROM photo_scores
WHERE {dt_expr} IS NOT NULL
AND {date_expr} IN ({placeholders})
"""
rows = c.execute(sql, tuple(safe_dates)).fetchall()
conn.close()
return rows
def get_photo_meta_by_path(abs_path: str):
"""
从 DB 找到渲染需要的字段:date/side/lat/lon/city。
abs_path 必须是数据库里 photo_scores.path 的原值(通常是绝对路径)。
"""
if not DB_PATH.exists():
return None
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
row = c.execute(
"""
SELECT path,
exif_json,
side_caption,
memory_score,
exif_gps_lat,
exif_gps_lon,
exif_city
FROM photo_scores
WHERE path = ?
LIMIT 1
""",
(abs_path,),
).fetchone()
conn.close()
if not row:
return None
path, exif_json, side_caption, memory_score, gps_lat, gps_lon, exif_city = row
date_str = extract_date_from_exif(exif_json)
if not date_str:
return None
return {
"path": str(path),
"date": date_str,
"side": side_caption or "",
"memory": float(memory_score) if memory_score is not None else None,
"lat": gps_lat,
"lon": gps_lon,
"city": exif_city or "",
}
def summarize_exif(exif_json: str | None) -> str:
if not exif_json:
return ""
try:
data = json.loads(exif_json)
except Exception:
return ""
dtv = data.get("datetime")
make = data.get("make")
model = data.get("model")
iso = data.get("iso")
exp = data.get("exposure_time")
fnum = data.get("f_number")
fl = data.get("focal_length")
lat = data.get("gps_lat")
lon = data.get("gps_lon")
parts = []
if dtv:
parts.append(f"时间: {dtv}")
if make or model:
cam = f"{make or ''} {model or ''}".strip()
if cam:
parts.append(f"设备: {cam}")
exp_parts = []
if iso:
exp_parts.append(f"ISO {iso}")
if exp:
exp_parts.append(f"快门 {exp}")
if fnum:
exp_parts.append(f"光圈 {fnum}")
if fl:
exp_parts.append(f"焦距 {fl}")
if exp_parts:
parts.append(" / ".join(exp_parts))
if lat is not None and lon is not None:
try:
parts.append(f"GPS: {float(lat):.5f}, {float(lon):.5f}")
except Exception:
parts.append(f"GPS: {lat}, {lon}")
return ";".join(str(p) for p in parts if p)
def extract_date_from_exif(exif_json: str | None) -> str:
if not exif_json:
return ""
try:
data = json.loads(exif_json)
except Exception:
return ""
dtv = data.get("datetime")
if not dtv:
return ""
try:
date_part = str(dtv).split()[0] # "2018:03:18"
parts = date_part.replace(":", "-").split("-")
if len(parts) >= 3:
return f"{parts[0]}-{parts[1]}-{parts[2]}"
except Exception:
return ""
return ""
# --------------------------
# HTML builders
# --------------------------
def build_html(rows, page: int, page_size: int, total_count: int):
items_html = []
for path, caption, ptype, m_score, b_score, reason, exif_json, width, height, orientation, used_at, side_caption in rows:
safe_caption = html.escape(caption or "").replace("\n", "<br>")
safe_side = html.escape(side_caption or "").replace("\n", "<br>")
safe_type = html.escape(ptype or "")
safe_reason = html.escape(reason or "")
exif_summary = summarize_exif(exif_json)
safe_exif = html.escape(exif_summary or "")
date_str = extract_date_from_exif(exif_json)
safe_date = html.escape(date_str or "")
md_str = ""
if date_str and len(date_str) >= 10:
md_str = date_str[5:10]
safe_md = html.escape(md_str or "")
res_str = ""
if width and height:
try:
res_str = f"{int(width)} x {int(height)}"
except Exception:
res_str = f"{width} x {height}"
orient_str = orientation or ""
used_str = used_at or ""
img_uri = _make_image_url(str(path))
if not img_uri:
continue
score_html = ""
if m_score is not None or b_score is not None:
parts = []
if m_score is not None:
parts.append(f"回忆度: {m_score:.1f}")
if b_score is not None:
parts.append(f"美观度: {b_score:.1f}")
score_line = " / ".join(parts)
score_html = f'<div class="score">{score_line}</div>'
type_html = f'<div class="type">类型: {safe_type}</div>' if safe_type else ""
exif_html = f'<div class="exif">{safe_exif}</div>' if safe_exif else ""
reason_html = f'<div class="reason">理由: {safe_reason}</div>' if safe_reason else ""
items_html.append(f"""
<div class="item"
data-date="{safe_date}"
data-md="{safe_md}"
data-memory="{m_score if m_score is not None else ''}"
data-beauty="{b_score if b_score is not None else ''}">
<div class="img-wrap">
<a class="img-link" href="/sim?img={html.escape(img_uri)}" title="打开该照片的模拟器" onclick="window.stop();">
<img src="{img_uri}" loading="lazy">
</a>
</div>
{f'<div class="side-under">{safe_side}</div>' if safe_side else ''}
<div class="meta">
<div class="path">{html.escape(str(path))}</div>
{type_html}
{score_html}
{reason_html}
{exif_html}
<div class="extra">
{f"拍摄日期: {safe_date}" if safe_date else ""}
{(" · 分辨率: " + html.escape(res_str)) if res_str else ""}
{(" · 方向: " + html.escape(orient_str)) if orient_str else ""}
{(" · 已上屏: " + html.escape(used_str)) if used_str else ""}
</div>
<div class="caption">{safe_caption}</div>
</div>
</div>
""")
items_str = "\n".join(items_html)
total_pages = (total_count + page_size - 1) // page_size
# 从请求参数回填(用于显示)
md_q = (request.args.get("md", "") or "").strip()
sort_q = (request.args.get("sort", "") or "memory").strip() or "memory"
md_hint = f" · 筛选日期 {html.escape(md_q)}" if (md_q and len(md_q) == 5) else ""
html_str = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>InkTime照片数据库</title>
<style>
:root{{
--bg: #0b0c10;
--panel: rgba(255,255,255,0.06);
--card: rgba(255,255,255,0.10);
--card2: rgba(255,255,255,0.08);
--text: rgba(255,255,255,0.92);
--muted: rgba(255,255,255,0.62);
--muted2: rgba(255,255,255,0.48);
--line: rgba(255,255,255,0.14);
--accent: #8ab4ff;
--accent2:#9cffd6;
--shadow: 0 18px 60px rgba(0,0,0,0.45);
--shadow2: 0 10px 28px rgba(0,0,0,0.35);
--radius: 14px;
}}
body{{
margin:0;
padding:0;
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, sans-serif;
background: radial-gradient(1200px 800px at 20% 0%, rgba(138,180,255,0.18), transparent 45%),
radial-gradient(900px 700px at 90% 20%, rgba(156,255,214,0.14), transparent 55%),
linear-gradient(180deg, #07080b 0%, #0b0c10 40%, #0b0c10 100%);
color: var(--text);
}}
.container{{
max-width: 1320px;
margin: 26px auto 60px;
padding: 0 18px;
}}
h1{{
font-size: 22px;
margin: 0 0 8px;
letter-spacing: 0.2px;
}}
.subtitle{{
font-size: 13px;
color: var(--muted);
margin: 0 0 14px;
line-height: 1.35;
}}
.controls{{
display:flex;
flex-wrap:wrap;
gap: 10px;
align-items:center;
margin: 12px 0 14px;
font-size: 13px;
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 10px 12px;
box-shadow: var(--shadow2);
backdrop-filter: blur(10px);
}}
.controls label{{
display:inline-flex;
align-items:center;
gap: 8px;
color: var(--muted);
white-space: nowrap;
}}
.controls select{{
padding: 7px 10px;
font-size: 13px;
color: var(--text);
background: rgba(255,255,255,0.08);
border: 1px solid rgba(255,255,255,0.16);
border-radius: 10px;
outline: none;
}}
.controls select:focus{{
border-color: rgba(138,180,255,0.7);
box-shadow: 0 0 0 3px rgba(138,180,255,0.16);
}}
.controls button{{
padding: 7px 12px;
font-size: 13px;
cursor: pointer;
color: var(--text);
background: rgba(255,255,255,0.10);
border: 1px solid rgba(255,255,255,0.16);
border-radius: 10px;
transition: transform .08s ease, background .15s ease, border-color .15s ease, opacity .15s ease;
}}
.controls button:hover{{
background: rgba(255,255,255,0.14);
border-color: rgba(255,255,255,0.26);
}}
.controls button:active{{
transform: translateY(1px);
}}
.controls button:disabled{{
opacity: 0.45;
cursor: not-allowed;
}}
.controls.pager{{
background: rgba(255,255,255,0.05);
}}
.status{{
font-size: 12px;
color: var(--muted);
margin: 8px 0 12px;
}}
.grid{{
display:grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 16px;
}}
.item{{
background: linear-gradient(180deg, var(--card) 0%, var(--card2) 100%);
border: 1px solid rgba(255,255,255,0.14);
border-radius: var(--radius);
overflow: hidden;
box-shadow: var(--shadow2);
display:flex;
flex-direction:column;
transition: transform .12s ease, border-color .15s ease, box-shadow .15s ease;
}}
.item:hover{{
transform: translateY(-2px);
border-color: rgba(138,180,255,0.38);
box-shadow: var(--shadow);
}}
.img-wrap{{
width:100%;
background: rgba(0,0,0,0.55);
display:flex;
align-items:center;
justify-content:center;
max-height: 260px;
overflow:hidden;
}}
.img-wrap img{{
width:100%;
height:auto;
display:block;
object-fit: cover;
filter: saturate(1.04) contrast(1.02);
}}
.img-link{{ display:block; width:100%; }}
.img-link:link, .img-link:visited{{ text-decoration:none; }}
.side-under{{
padding: 10px 12px 0;
font-size: 12px;
color: var(--text);
line-height: 1.45;
word-break: break-word;
opacity: 0.92;
}}
.meta{{
padding: 10px 12px 12px;
font-size: 13px;
color: var(--text);
}}
.path{{
font-size: 11px;
color: var(--muted2);
margin-bottom: 6px;
word-break: break-all;
}}
.type{{
font-size: 12px;
color: var(--muted);
margin-bottom: 4px;
}}
.score{{
font-size: 13px;
font-weight: 650;
margin-bottom: 6px;
color: var(--accent2);
}}
.reason{{
font-size: 12px;
color: var(--muted);
margin-bottom: 6px;
line-height: 1.45;
}}
.exif{{
font-size: 11px;
color: var(--muted2);
margin-bottom: 8px;
line-height: 1.45;
}}
.extra{{
font-size: 11px;
color: var(--muted2);
margin-bottom: 8px;
line-height: 1.45;
}}
.caption{{
margin-top: 6px;
font-size: 13px;
line-height: 1.55;
color: var(--text);
}}
@media (max-width: 560px){{
.container{{ padding: 0 14px; }}
.grid{{ grid-template-columns: 1fr; }}
.controls{{ gap: 8px; }}
}}
</style>
</head>
<body>
<div class="container">
<h1>InkTime照片数据库</h1>
<div class="subtitle">
数据库:{html.escape(str(DB_PATH))}{md_hint} · 当前页 {page} · 本页 {len(rows)} 张 · 总计 {total_count} 张(每页 {page_size} 张)
</div>
<div class="controls">
<label>
月份:
<select id="monthFilter">
<option value="">全部</option>
<option value="01">1 月</option><option value="02">2 月</option><option value="03">3 月</option>
<option value="04">4 月</option><option value="05">5 月</option><option value="06">6 月</option>
<option value="07">7 月</option><option value="08">8 月</option><option value="09">9 月</option>
<option value="10">10 月</option><option value="11">11 月</option><option value="12">12 月</option>
</select>
</label>
<label>
日期:
<select id="dayFilter">
<option value="">全部</option>
{''.join([f'<option value="{i:02d}">{i} 日</option>' for i in range(1, 32)])}
</select>
</label>
<label>
排序:
<select id="sortBy">
<option value="memory">按回忆度</option>
<option value="beauty">按美观度</option>
<option value="time_new">按时间(新→旧)</option>
<option value="time_old">按时间(旧→新)</option>
</select>
</label>
<button type="button" id="randomDateBtn">随机一天</button>
<button type="button" id="homeBtn">回到首页</button>
</div>
<div class="controls pager" style="justify-content: space-between;">
<div>
<button type="button" id="prevPageBtn">上一页</button>
<button type="button" id="nextPageBtn">下一页</button>
</div>
<div class="subtitle" style="margin:0;">第 <span id="pageNum">{page}</span> 页 / 共 <span id="pageTotal">{total_pages}</span> 页</div>
</div>
<div class="status" id="statusLine"></div>
<div class="grid">
{items_str}
</div>
<div class="controls pager" style="justify-content: space-between; margin-top: 18px;">
<div>
<button type="button" id="prevPageBtnBottom">上一页</button>
<button type="button" id="nextPageBtnBottom">下一页</button>
</div>
<div class="subtitle" style="margin:0;">第 <span>{page}</span> 页 / 共 <span>{total_pages}</span> 页</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {{
const monthSelect = document.getElementById('monthFilter');
const daySelect = document.getElementById('dayFilter');
const sortSelect = document.getElementById('sortBy');
const statusLine = document.getElementById('statusLine');
const randomBtn = document.getElementById('randomDateBtn');
const homeBtn = document.getElementById('homeBtn');
const currentPage = {page};
const totalPages = {total_pages};
const prevBtn = document.getElementById('prevPageBtn');
const nextBtn = document.getElementById('nextPageBtn');
const prevBtnBottom = document.getElementById('prevPageBtnBottom');
const nextBtnBottom = document.getElementById('nextPageBtnBottom');
// 任何跳转前先中断当前页面的图片/资源加载,避免请求排队导致“点击无响应”
function navigateTo(urlStr) {{
try {{
window.stop();
}} catch (e) {{
// ignore
}}
window.location.href = urlStr;
}}
function getParams() {{
const url = new URL(window.location.href);
const md = (url.searchParams.get('md') || '').trim();
const sort = (url.searchParams.get('sort') || '').trim() || 'memory';
const page = parseInt(url.searchParams.get('page') || '1', 10) || 1;
return {{ url, md, sort, page }};
}}
function setSelectsFromUrl() {{
const p = getParams();
// sort
if (sortSelect) sortSelect.value = p.sort;
// md -> month/day
if (p.md && p.md.length === 5 && p.md.indexOf('-') === 2) {{
const parts = p.md.split('-');
if (parts.length === 2) {{
if (monthSelect) monthSelect.value = parts[0];
if (daySelect) daySelect.value = parts[1];
}}
if (statusLine) statusLine.textContent = '当前筛选:' + p.md + '(全库)';
}} else {{
if (monthSelect) monthSelect.value = '';
if (daySelect) daySelect.value = '';
if (statusLine) statusLine.textContent = '';
}}
}}
function buildReviewUrl(md, sort, page) {{
const url = new URL(window.location.href);
url.pathname = '/review';
if (md && md.length === 5 && md.indexOf('-') === 2) url.searchParams.set('md', md);
else url.searchParams.delete('md');
if (sort) url.searchParams.set('sort', sort);
else url.searchParams.delete('sort');
url.searchParams.set('page', String(page || 1));
return url.toString();
}}
function goPage(p) {{
const params = getParams();
navigateTo(buildReviewUrl(params.md, params.sort, p));
}}
function goHome() {{
const params = getParams();
navigateTo(buildReviewUrl('', params.sort || 'memory', 1));
}}
async function pickRandomDate() {{
// 从后端拿“真实存在的日期集合”,前端随机一个,然后让后端按 md 过滤
try {{
// 先停止当前页面的图片加载,释放连接
try {{ window.stop(); }} catch (e) {{}}
const resp = await fetch('/api/md_list');
if (!resp.ok) throw new Error('HTTP ' + resp.status);
const data = await resp.json();
const arr = Array.isArray(data) ? data : (Array.isArray(data.md_list) ? data.md_list : []);
if (!arr.length) {{
if (statusLine) statusLine.textContent = '全库没有任何可用日期(exif datetime 缺失)。';
return;
}}
const idx = Math.floor(Math.random() * arr.length);
const md = String(arr[idx] || '').trim();
const params = getParams();
navigateTo(buildReviewUrl(md, params.sort || 'memory', 1));
}} catch (e) {{
if (statusLine) statusLine.textContent = '随机失败:' + e;
}}
}}
function onMonthDayChange() {{
const mVal = (monthSelect && monthSelect.value) ? monthSelect.value : '';
const dVal = (daySelect && daySelect.value) ? daySelect.value : '';
const sortBy = (sortSelect && sortSelect.value) ? sortSelect.value : 'memory';
if (!mVal && !dVal) {{
navigateTo(buildReviewUrl('', sortBy, 1));
return;
}}
if (mVal && dVal) {{
const md = mVal + '-' + dVal;
navigateTo(buildReviewUrl(md, sortBy, 1));
return;
}}
// 只选了一个,不跳转,避免生成无意义的 md
}}
function onSortChange() {{
const params = getParams();
const sortBy = (sortSelect && sortSelect.value) ? sortSelect.value : 'memory';
navigateTo(buildReviewUrl(params.md, sortBy, 1));
}}
// 分页按钮
if (prevBtn) {{
prevBtn.disabled = currentPage <= 1;
prevBtn.addEventListener('click', () => goPage(Math.max(1, currentPage - 1)));
}}
if (nextBtn) {{
nextBtn.disabled = currentPage >= totalPages;
nextBtn.addEventListener('click', () => goPage(Math.min(totalPages, currentPage + 1)));
}}
if (prevBtnBottom) {{
prevBtnBottom.disabled = currentPage <= 1;
prevBtnBottom.addEventListener('click', () => goPage(Math.max(1, currentPage - 1)));
}}
if (nextBtnBottom) {{
nextBtnBottom.disabled = currentPage >= totalPages;
nextBtnBottom.addEventListener('click', () => goPage(Math.min(totalPages, currentPage + 1)));
}}
if (monthSelect) monthSelect.addEventListener('change', onMonthDayChange);
if (daySelect) daySelect.addEventListener('change', onMonthDayChange);
if (sortSelect) sortSelect.addEventListener('change', onSortChange);
if (randomBtn) randomBtn.addEventListener('click', pickRandomDate);
if (homeBtn) homeBtn.addEventListener('click', goHome);
// 兜底:用户在图片疯狂加载时点击任何链接/按钮,先 stop(),避免导航请求排队
document.addEventListener('click', function (ev) {{
const t = ev.target;
if (!t) return;
const a = t.closest ? t.closest('a') : null;
const btn = t.closest ? t.closest('button') : null;
// 只要是链接或按钮点击,就先中断当前加载
if (a || btn) {{
try {{ window.stop(); }} catch (e) {{}}
}}
}}, true);
setSelectsFromUrl();
}});
</script>
</body>
</html>
"""
return html_str
def build_simulator_html(sim_rows, selected_img: str = ""):
# 空数据时不要做任何无意义的循环,避免前端 JS 大对象
if not sim_rows:
sim_rows = []
items = []
def _parse_tags(ptype_val) -> list[str]:
"""把 DB 的 type 字段解析成 tag 数组。
兼容三种常见存储:
- JSON 数组: ["人物","日常"]
- 伪数组文本: [人物, 日常] / [人物,日常]
- 普通字符串: 人物,日常 / 人物
注意:这里是容错解析,目的是不让 /sim 因坏数据 500。
"""
if ptype_val is None:
return []
s = str(ptype_val).strip()
if not s:
return []
# 1) 先尝试严格 JSON
if s.startswith("[") and s.endswith("]"):
try:
arr = json.loads(s)
if isinstance(arr, list):
out = []
for x in arr:
t = str(x).strip()
if t:
out.append(t)
return out
except Exception:
# JSON 不合法:继续走容错
pass
# 2) 容错:去掉最外层 [] 以及引号,然后按逗号/中文逗号切
if s.startswith("[") and s.endswith("]"):
s = s[1:-1].strip()
# 去掉可能出现的引号
s = s.replace('"', '').replace("'", "")
parts = [p.strip() for p in s.replace(',', ',').split(',')]
out = [p for p in parts if p]
return out
for (
path,
caption,
ptype,
memory_score,
beauty_score,
reason,
side_caption,
exif_json,
width,
height,
orientation,
used_at,
gps_lat,
gps_lon,
exif_city,
) in sim_rows:
date_str = extract_date_from_exif(exif_json)
if not date_str:
continue
img_uri = _make_image_url(str(path))
if not img_uri:
continue
# tags: 保证为数组,优先解析 JSON/容错
type_value = _parse_tags(ptype)
items.append({
"path": img_uri,