SAkizuki commited on
Commit
bfcf1d1
·
verified ·
1 Parent(s): c9c4952

Auto-sync from GitHub Actions

Browse files
api_fastapi.py CHANGED
@@ -27,11 +27,15 @@ FastAPI 适配层(可选)。
27
  from __future__ import annotations
28
 
29
  import asyncio
 
30
  import time
31
  from pathlib import Path
32
  from typing import Any
33
  from typing import Literal
34
  from fastapi import FastAPI, HTTPException, Request
 
 
 
35
  from fastapi.openapi.docs import get_swagger_ui_html, get_swagger_ui_oauth2_redirect_html
36
  from fastapi.staticfiles import StaticFiles
37
  from pydantic import BaseModel, ConfigDict, Field
@@ -49,6 +53,16 @@ LayerName = Literal['英文', '中文扩展词', '释义', '中文核心词', 'a
49
  CategoryName = Literal['General', 'Artist', 'Copyright', 'Character', 'Meta']
50
  GroupMode = Literal['off', 'expand', 'diverse']
51
 
 
 
 
 
 
 
 
 
 
 
52
 
53
  class SearchIn(BaseModel):
54
  model_config = ConfigDict(
@@ -116,6 +130,7 @@ class RelatedTagOut(BaseModel):
116
 
117
 
118
  class SearchOut(BaseModel):
 
119
  tags_all: str
120
  tags_sfw: str
121
  results: list[TagOut]
@@ -158,12 +173,13 @@ async def _correct_tags(tagger: DanbooruTagger, tags: list[str]) -> tuple[list[s
158
 
159
  def _with_corrections(results: list[dict[str, Any]], corrections: dict[str, str]) -> dict[str, Any]:
160
  if not corrections:
161
- return {"results": results}
162
  correction_notes = [f"{bad} → {good}" for bad, good in corrections.items()]
163
  return {
164
  "correction_note": "标签拼写错误,已经纠错: " + ", ".join(correction_notes),
165
  "corrections": corrections,
166
  "results": results,
 
167
  }
168
 
169
 
@@ -182,6 +198,22 @@ app = FastAPI(
182
  )
183
 
184
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  app.mount(
186
  "/docs-assets",
187
  StaticFiles(directory=Path(__file__).resolve().parent / "webui" / "static" / "swagger-ui"),
@@ -318,6 +350,7 @@ async def related(body: RelatedIn) -> dict[str, Any]:
318
  return {
319
  "error": "所有传入的标签均不存在于标签表中",
320
  "invalid_tags": invalid_tags,
 
321
  }
322
  results = await tagger.get_related_async(
323
  corrected_tags,
@@ -357,13 +390,14 @@ async def artists(body: ArtistIn) -> dict[str, Any]:
357
  traffic_attribution.note_safe_parameters(limit=body.limit, min_cooc=body.min_cooc)
358
  tagger = await DanbooruTagger.get_instance()
359
  if not body.tags:
360
- return {"error": "tags 列表不能为空"}
361
 
362
  corrected_tags, invalid_tags, corrections = await _correct_tags(tagger, body.tags)
363
  if not corrected_tags:
364
  return {
365
  "error": "所有传入的标签均不存在于标签表中",
366
  "invalid_tags": invalid_tags,
 
367
  }
368
 
369
  results = await tagger.search_artists_by_tags_async(
@@ -391,4 +425,4 @@ async def artists(body: ArtistIn) -> dict[str, Any]:
391
  @app.get("/health")
392
  async def health():
393
  tagger = await DanbooruTagger.get_instance()
394
- return {"status": "ok", "loaded": tagger.is_loaded}
 
27
  from __future__ import annotations
28
 
29
  import asyncio
30
+ import json
31
  import time
32
  from pathlib import Path
33
  from typing import Any
34
  from typing import Literal
35
  from fastapi import FastAPI, HTTPException, Request
36
+ from fastapi.exception_handlers import http_exception_handler, request_validation_exception_handler
37
+ from fastapi.exceptions import RequestValidationError
38
+ from starlette.exceptions import HTTPException as StarletteHTTPException
39
  from fastapi.openapi.docs import get_swagger_ui_html, get_swagger_ui_oauth2_redirect_html
40
  from fastapi.staticfiles import StaticFiles
41
  from pydantic import BaseModel, ConfigDict, Field
 
53
  CategoryName = Literal['General', 'Artist', 'Copyright', 'Character', 'Meta']
54
  GroupMode = Literal['off', 'expand', 'diverse']
55
 
56
+ API_KEY_NOTICE = (
57
+ "即将上线 API Key 与限流政策,当前尚未生效,申请入口及生效时间将另行公告。"
58
+ "上线后每把 Key 默认 3000 点/日、60 点/分钟、并发 1,各 Key 独立;"
59
+ "无 Key 调用共享 15000 点/日、30 点/分钟、并发 1 的试用池。"
60
+ "search/related/artists/health 每次分别消耗 3/2/1/0 点,每日北京时间 00:00 重置。"
61
+ "入口开放后使用 Hugging Face 账号登录申请;首把且不超默认日额度可自动批准,"
62
+ "第二把及后续 Key、首把超默认额度或后续超默认额度增额需说明原因并人工审核。"
63
+ "超限请求届时将返回 429,各 Key 仍受服务整体容量保护。网页搜索无需申请 Key。"
64
+ )
65
+
66
 
67
  class SearchIn(BaseModel):
68
  model_config = ConfigDict(
 
130
 
131
 
132
  class SearchOut(BaseModel):
133
+ api_key_notice: str = Field(default=API_KEY_NOTICE, description="尚未生效的 API Key 与限流政策预告")
134
  tags_all: str
135
  tags_sfw: str
136
  results: list[TagOut]
 
173
 
174
  def _with_corrections(results: list[dict[str, Any]], corrections: dict[str, str]) -> dict[str, Any]:
175
  if not corrections:
176
+ return {"results": results, "api_key_notice": API_KEY_NOTICE}
177
  correction_notes = [f"{bad} → {good}" for bad, good in corrections.items()]
178
  return {
179
  "correction_note": "标签拼写错误,已经纠错: " + ", ".join(correction_notes),
180
  "corrections": corrections,
181
  "results": results,
182
+ "api_key_notice": API_KEY_NOTICE,
183
  }
184
 
185
 
 
198
  )
199
 
200
 
201
+ async def _policy_notice_error(request: Request, exc):
202
+ # Preserve FastAPI's error status, detail and headers; only append public copy.
203
+ handler = request_validation_exception_handler if isinstance(exc, RequestValidationError) else http_exception_handler
204
+ response = await handler(request, exc)
205
+ if response.body:
206
+ payload = json.loads(response.body)
207
+ payload["api_key_notice"] = API_KEY_NOTICE
208
+ response.body = json.dumps(payload, ensure_ascii=False, allow_nan=False).encode("utf-8")
209
+ response.headers["content-length"] = str(len(response.body))
210
+ return response
211
+
212
+
213
+ app.add_exception_handler(StarletteHTTPException, _policy_notice_error)
214
+ app.add_exception_handler(RequestValidationError, _policy_notice_error)
215
+
216
+
217
  app.mount(
218
  "/docs-assets",
219
  StaticFiles(directory=Path(__file__).resolve().parent / "webui" / "static" / "swagger-ui"),
 
350
  return {
351
  "error": "所有传入的标签均不存在于标签表中",
352
  "invalid_tags": invalid_tags,
353
+ "api_key_notice": API_KEY_NOTICE,
354
  }
355
  results = await tagger.get_related_async(
356
  corrected_tags,
 
390
  traffic_attribution.note_safe_parameters(limit=body.limit, min_cooc=body.min_cooc)
391
  tagger = await DanbooruTagger.get_instance()
392
  if not body.tags:
393
+ return {"error": "tags 列表不能为空", "api_key_notice": API_KEY_NOTICE}
394
 
395
  corrected_tags, invalid_tags, corrections = await _correct_tags(tagger, body.tags)
396
  if not corrected_tags:
397
  return {
398
  "error": "所有传入的标签均不存在于标签表中",
399
  "invalid_tags": invalid_tags,
400
+ "api_key_notice": API_KEY_NOTICE,
401
  }
402
 
403
  results = await tagger.search_artists_by_tags_async(
 
425
  @app.get("/health")
426
  async def health():
427
  tagger = await DanbooruTagger.get_instance()
428
+ return {"status": "ok", "loaded": tagger.is_loaded, "api_key_notice": API_KEY_NOTICE}
config/ui_text.yaml CHANGED
@@ -5,44 +5,41 @@ sponsor:
5
  如果你想继续折腾,也可以看看基于这个小工具的更多工具链
6
 
7
  help:
8
- update_title: 最近更新:REST API 来源声明
 
9
  update_summary: >-
10
- 近期 REST API 调用量明显增长。观察期内未声明来源不影响使用;未来未声明请求可能受到限流等流量治理措施影响。
11
  update_markdown: |-
12
- ### REST API 来源声明
13
 
14
- 为便于容量评估、服务优化和识别公开集成,建议 REST API 接入方主动声明客户端名称与公开服务地址:
 
15
 
16
- ```http
17
- X-DanbooruSearch-Client: example-service/1.0
18
- X-DanbooruSearch-Site: https://example.com
19
- ```
20
 
21
- 完整的搜索请求示例:
22
-
23
- ```bash
24
- curl --request POST \
25
- --url 'https://sakizuki-danboorusearch.hf.space/api/search' \
26
- --header 'Content-Type: application/json' \
27
- --header 'X-DanbooruSearch-Client: example-service/1.0' \
28
- --header 'X-DanbooruSearch-Site: https://example.com' \
29
- --data '{
30
- "query": "白色水手服的女孩",
31
- "top_k": 5,
32
- "limit": 80,
33
- "popularity_weight": 0.15,
34
- "show_nsfw": false,
35
- "use_segmentation": true,
36
- "target_layers": ["英文", "中文扩展词", "释义", "中文核心词", "artist"],
37
- "target_categories": ["General", "Character", "Copyright"],
38
- "group_mode": "off",
39
- "max_per_group": 2
40
- }'
41
- ```
42
 
43
- - 两个请求头在当前观察期内均为可选项;缺失、无效或无法确认时,**不影响 API 正常响应**。
44
- - 观察期结束后,未声明请求 **未来可能** 被纳入限流等流量治理措施;具体规则如需实施,将另行公布。
45
- - 归因仅记录小时级、服务级聚合信息,不保存 IP、查询内容、请求体、Cookie、Authorization、完整 User-Agent 或完整 Referer。
46
 
47
  tutorial:
48
  title: 使用教程
 
5
  如果你想继续折腾,也可以看看基于这个小工具的更多工具链
6
 
7
  help:
8
+ update_title: 即将上线:API Key 与调用限额
9
+ update_detail_label: 查看详情
10
  update_summary: >-
11
+ API 即将启用 Key 申请与限流:每把 Key 默认每天 3,000 点,无 Key 调用共享每天 15,000 点试用池。网页搜索和MCP继续无需登录使用。将于10月初生效。
12
  update_markdown: |-
13
+ ### API Key 与调用限额即将上线
14
 
15
+ 为保障大家的搜索体验,我们将为 API 调用引入 API Key 和使用限额。**目前申请入口尚未开放,以下额度与限流政策尚未生效;申请入口会另行公告。** 网页上的普通标签搜索继续无需登录,也无需申请 API Key。
16
+ 调用MCP接口也暂时无需申请Key。
17
 
18
+ **生效时间?**
19
+
20
+ 将于2026年10月01日 00:00(北京时间)左右正式生效。
 
21
 
22
+ **如何申请?**
23
+
24
+ - 申请入口开放后,使用 Hugging Face 账号登录,填写用途和预计每日用量即可提交。ModelScope因平台资源受限,暂无法提供 Key 申请;请使用 Hugging Face 账号申请。
25
+ - 第一把 Key 申请不超过默认 **3,000 点/日** 时可自动批准;申请第二把及后续 Key,或首把 Key 需要超过默认额度时,请填写申请原因,等待人工审核。
26
+ - 无统一收费计划,申请 Key 仅用于区分调用者、统计使用量和保护服务容量。
27
+
28
+ **调用如何计量?**
29
+
30
+ | 调用内容 | 每次消耗 |
31
+ | --- | --- |
32
+ | 标签搜索(/search) | 3 点 |
33
+ | 关联推荐(/related) | 2 点 |
34
+ | 画师推荐(/artists) | 1 点 |
35
+ | 健康检查(/health) | 0 点 |
36
+
37
+ - **有 Key:**每把 Key 默认每天 3,000 点,相当于 1,000 次纯标签搜索;混合调用按上表累加。每把 Key 默认每分钟 60 点,最多同时处理 1 个业务请求。同一账号的不同 Key 各自独立计算日额度、分钟额度和并发上限。
38
+ - **无 Key:**所有调用者共享每天 **15,000 点**的试用池,同时共享每分钟 30 点、最多 1 个业务请求的并发限制;公共池耗尽后,无 Key 调用需等待重置,建议长期集成申请自己的 Key。
39
+ - 每日额度在**北京时间 00:00**重置,剩余额度不结转。超出额度、短时速率或并发限制时,请稍后重试;上线后这类请求将返回 429。
40
+ - 不同 Key 的额度独立,但仍受服务整体容量保护,持有 Key 不保证随时能以最高速率调用。健康检查虽不扣点,也请避免频繁轮询。
 
 
41
 
42
+ 即日起,API 响应将提前附带政策提醒。
 
 
43
 
44
  tutorial:
45
  title: 使用教程
core/admin_metrics.py CHANGED
@@ -2,9 +2,12 @@
2
  from __future__ import annotations
3
 
4
  import asyncio
 
5
  import math
 
6
  from collections import Counter, defaultdict
7
  from datetime import datetime, timedelta, timezone
 
8
 
9
  LIMITS = (100, 250, 500, 1000, 2000, 5000, 10000, 30000, 60000, 120000)
10
  CST = timezone(timedelta(hours=8))
@@ -26,11 +29,135 @@ def timing_summary(raw: dict) -> dict:
26
  p95, overflow = 120000, True
27
  return {"count": count, "average_ms": round(raw.get("sum_ms", 0) / count, 1) if count else None,
28
  "p95_ms": p95, "p95_overflow": overflow,
 
29
  "buckets": [{"label": f"≤ {n / 1000:g} s", "count": int(buckets.get(f"le_{n}", 0))} for n in LIMITS]
30
  + [{"label": "> 120 s", "count": int(buckets.get("gt_120000", 0))}]}
31
 
32
 
33
- def build_dashboard(telemetry: dict, attribution: dict, now: datetime | None = None) -> dict:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  now = (now or datetime.now(CST)).astimezone(CST)
35
  earliest = now.date() - timedelta(days=13)
36
  rows = [row for row in attribution.get("records", [])
@@ -57,11 +184,22 @@ def build_dashboard(telemetry: dict, attribution: dict, now: datetime | None = N
57
  # A missing observation is not proof of zero traffic (restart/threshold).
58
  series.append({"hour": label, "count": hours.get(label)})
59
  cursor += timedelta(hours=1)
 
 
 
60
  return {
61
  "generated_at": now.isoformat(timespec="seconds"),
62
  "telemetry_since": telemetry.get("enabled_at"),
63
  "counters": telemetry.get("counters", {}),
64
  "ui_latency": timing_summary(telemetry.get("timings_ms", {}).get("ui_search_latency", {})),
 
 
 
 
 
 
 
 
65
  "rest": {"retention_days": 14, "first_hour": first_hour,
66
  "last_hour": max(hours) if hours else None,
67
  "count": total, "error_percent": round(100 * (statuses["4xx"] + statuses["5xx"]) / total, 2) if total else None,
@@ -76,4 +214,7 @@ async def read_dashboard() -> dict:
76
  from core import telemetry, traffic_attribution
77
  telemetry_snapshot = telemetry.get_snapshot()
78
  attribution_snapshot = traffic_attribution.get_admin_snapshot()
79
- return await asyncio.to_thread(build_dashboard, telemetry_snapshot, attribution_snapshot)
 
 
 
 
2
  from __future__ import annotations
3
 
4
  import asyncio
5
+ import json
6
  import math
7
+ import os
8
  from collections import Counter, defaultdict
9
  from datetime import datetime, timedelta, timezone
10
+ from pathlib import Path
11
 
12
  LIMITS = (100, 250, 500, 1000, 2000, 5000, 10000, 30000, 60000, 120000)
13
  CST = timezone(timedelta(hours=8))
 
29
  p95, overflow = 120000, True
30
  return {"count": count, "average_ms": round(raw.get("sum_ms", 0) / count, 1) if count else None,
31
  "p95_ms": p95, "p95_overflow": overflow,
32
+ "distribution_available": bool(count and sum(buckets.values()) == count),
33
  "buckets": [{"label": f"≤ {n / 1000:g} s", "count": int(buckets.get(f"le_{n}", 0))} for n in LIMITS]
34
  + [{"label": "> 120 s", "count": int(buckets.get("gt_120000", 0))}]}
35
 
36
 
37
+ def summarize_window(rows: list[dict], now: datetime, hours: int) -> dict:
38
+ cutoff = now.replace(minute=0, second=0, microsecond=0) - timedelta(hours=hours - 1)
39
+ selected = [row for row in rows if cutoff.strftime("%Y-%m-%dT%H") <= row["day"] + "T" + str(row["hour"]).zfill(2)
40
+ <= now.strftime("%Y-%m-%dT%H")]
41
+ endpoints = defaultdict(lambda: {"count": 0, "sum_ms": 0, "errors": 0, "buckets": Counter(), "statuses": Counter()})
42
+ hourly = defaultdict(lambda: {"count": 0, "endpoints": Counter(), "peak_in_flight": 0, "peak_per_minute": 0})
43
+ sources, clients, statuses = Counter(), Counter(), Counter()
44
+ for row in selected:
45
+ count = int(row["count"])
46
+ entry = endpoints[row["endpoint"]]
47
+ entry["count"] += count
48
+ entry["sum_ms"] += row["sum_ms"]
49
+ entry["buckets"][row["latency_bucket"]] += count
50
+ entry["statuses"][row["status_class"]] += count
51
+ entry["errors"] += count if row["status_class"] in {"4xx", "5xx"} else 0
52
+ hour = hourly[row["day"] + "T" + str(row["hour"]).zfill(2) + ":00"]
53
+ hour["count"] += count
54
+ hour["endpoints"][row["endpoint"]] += count
55
+ for peak in ("peak_in_flight", "peak_per_minute"):
56
+ hour[peak] = max(hour[peak], int(row.get(peak, 0)))
57
+ statuses[row["status_class"]] += count
58
+ clients[row.get("client_family", "unknown")] += count
59
+ kind = row.get("source_kind", "unavailable")
60
+ name, site = row.get("source_name", ""), row.get("source_site", "")
61
+ label = (f"未声明 · {name or 'unknown'}" if kind == "anonymous" else
62
+ f"声明 · {name or site or '未命名'}" if kind == "declared" else
63
+ f"{kind} · {site}" if kind in {"origin", "referer"} else
64
+ "其他合并来源" if kind == "other" else "无来源维度")
65
+ sources[label] += count
66
+ series = []
67
+ cursor = cutoff
68
+ while cursor <= now:
69
+ label = cursor.strftime("%Y-%m-%dT%H:00")
70
+ series.append({"hour": label, **hourly.get(label, {"count": None, "endpoints": {}, "peak_in_flight": None, "peak_per_minute": None})})
71
+ cursor += timedelta(hours=1)
72
+ total = sum(statuses.values())
73
+ slow = sum(sum(raw["buckets"][bucket] for bucket in ("le_10000", "le_30000", "le_60000", "le_120000", "gt_120000")) for raw in endpoints.values())
74
+ return {
75
+ "requested_hours": hours, "count": total, "observed_hours": len(hourly),
76
+ "first_hour": min(hourly) if hourly else None, "last_hour": max(hourly) if hourly else None,
77
+ "statuses": dict(statuses), "error_percent": round(100 * (statuses["4xx"] + statuses["5xx"]) / total, 2) if total else None,
78
+ "slow_count": slow, "slow_percent": round(100 * slow / total, 2) if total else None,
79
+ "peak_in_flight": max((item["peak_in_flight"] for item in hourly.values()), default=None),
80
+ "peak_per_minute": max((item["peak_per_minute"] for item in hourly.values()), default=None),
81
+ "hours": series,
82
+ "sources": [{"label": label, "count": count} for label, count in sources.most_common(8)]
83
+ + ([{"label": "其余来源合计", "count": sum(count for _, count in sources.most_common()[8:])}] if len(sources) > 8 else []),
84
+ "clients": [{"label": label, "count": count} for label, count in clients.most_common()],
85
+ "endpoints": [{"endpoint": name, **timing_summary(raw), "errors": raw["errors"],
86
+ "client_errors": raw["statuses"]["4xx"], "server_errors": raw["statuses"]["5xx"],
87
+ "slow_percent": round(100 * sum(raw["buckets"][bucket] for bucket in ("le_10000", "le_30000", "le_60000", "le_120000", "gt_120000")) / raw["count"], 2) if raw["count"] else None}
88
+ for name, raw in sorted(endpoints.items())],
89
+ }
90
+
91
+
92
+ def summarize_history(snapshots: list[dict], now: datetime) -> dict:
93
+ """Intervals between cumulative samples, never mislabeled as calendar days."""
94
+ parsed = {}
95
+ for snapshot in snapshots:
96
+ try:
97
+ at = datetime.fromisoformat(snapshot["updated_at"])
98
+ if at.tzinfo is None or at > now:
99
+ continue
100
+ parsed[at] = snapshot
101
+ except (KeyError, TypeError, ValueError):
102
+ continue
103
+ points = sorted(parsed.items())[-120:]
104
+ intervals, skipped = [], 0
105
+ for (start, before), (end, after) in zip(points, points[1:]):
106
+ elapsed = (end - start).total_seconds() / 3600
107
+ counters = after.get("counters", {})
108
+ previous = before.get("counters", {})
109
+ delta = {key: int(value) - int(previous[key]) for key, value in counters.items() if key in previous}
110
+ if any(value < 0 for value in delta.values()) or "ui_search" not in delta:
111
+ skipped += 1
112
+ continue
113
+ old = before.get("timings_ms", {}).get("ui_search_latency", {})
114
+ new = after.get("timings_ms", {}).get("ui_search_latency", {})
115
+ count, duration = new.get("count", 0) - old.get("count", 0), new.get("sum_ms", 0) - old.get("sum_ms", 0)
116
+ intervals.append({"start": start.isoformat(), "end": end.isoformat(), "hours": round(elapsed, 2),
117
+ "ui": delta["ui_search"], "rest": sum(v for k, v in delta.items() if k.startswith("rest_")),
118
+ "mcp": sum(v for k, v in delta.items() if k.startswith("mcp_")),
119
+ "ui_average_ms": round(duration / count, 2) if count > 0 and duration >= 0 else None,
120
+ "cold_failures": delta.get("engine_cold_start_failure", 0)})
121
+ latest = intervals[-1] if intervals else None
122
+ previous = intervals[-2] if len(intervals) > 1 else None
123
+ ratio = None
124
+ if latest and previous and latest["ui_average_ms"] is not None and previous["ui_average_ms"]:
125
+ ratio = round(latest["ui_average_ms"] / previous["ui_average_ms"], 2)
126
+ return {"intervals": intervals[-30:], "latest": latest, "latency_ratio": ratio,
127
+ "sample_count": len(points), "skipped_intervals": skipped,
128
+ "last_sample": points[-1][0].isoformat() if points else None,
129
+ "stale": bool(points and (now - points[-1][0]).total_seconds() > 36 * 3600)}
130
+
131
+
132
+ def load_history() -> tuple[list[dict], str]:
133
+ """Optional local input; never assume the developer's tempsave exists on HF."""
134
+ filename = os.environ.get("ADMIN_TELEMETRY_HISTORY_PATH", "")
135
+ if not filename:
136
+ return [], "not_configured"
137
+ try:
138
+ with Path(filename).open("rb") as stream:
139
+ raw = stream.read(5_000_001)
140
+ if len(raw) > 5_000_000:
141
+ return [], "unavailable"
142
+ data = json.loads(raw)
143
+ snapshots = data["snapshots"]
144
+ if data.get("schema_version") != 1 or not isinstance(snapshots, list) or len(snapshots) > 2000:
145
+ return [], "unavailable"
146
+ # Validate the numerical fields used by the presentation without exposing file paths.
147
+ for item in snapshots:
148
+ datetime.fromisoformat(item["updated_at"])
149
+ if any(not isinstance(v, int) or v < 0 for v in item["counters"].values()):
150
+ raise ValueError()
151
+ for value in item.get("timings_ms", {}).values():
152
+ if any(not isinstance(value.get(k), (int, float)) or not math.isfinite(value[k]) or value[k] < 0 for k in ("count", "sum_ms")):
153
+ raise ValueError()
154
+ return snapshots, "loaded"
155
+ except (OSError, ValueError, KeyError, TypeError, AttributeError):
156
+ return [], "unavailable"
157
+
158
+
159
+ def build_dashboard(telemetry: dict, attribution: dict, now: datetime | None = None,
160
+ history: list[dict] | None = None, history_status: str = "not_configured") -> dict:
161
  now = (now or datetime.now(CST)).astimezone(CST)
162
  earliest = now.date() - timedelta(days=13)
163
  rows = [row for row in attribution.get("records", [])
 
184
  # A missing observation is not proof of zero traffic (restart/threshold).
185
  series.append({"hour": label, "count": hours.get(label)})
186
  cursor += timedelta(hours=1)
187
+ counters = telemetry.get("counters", {})
188
+ ui_search = counters.get("ui_search", 0)
189
+ attempts = counters.get("engine_cold_start_attempt", 0)
190
  return {
191
  "generated_at": now.isoformat(timespec="seconds"),
192
  "telemetry_since": telemetry.get("enabled_at"),
193
  "counters": telemetry.get("counters", {}),
194
  "ui_latency": timing_summary(telemetry.get("timings_ms", {}).get("ui_search_latency", {})),
195
+ "history": {**summarize_history(history or [], now), "status": history_status},
196
+ "quality": {"selection_percent": round(100 * counters.get("ui_search_with_selection_session", 0) / ui_search, 2) if ui_search else None,
197
+ "copy_events_per_search": round(100 * (counters.get("ui_copy_all", 0) + counters.get("ui_copy_selected", 0)) / ui_search, 2) if ui_search else None,
198
+ "zero_percent": round(100 * counters.get("ui_zero_result", 0) / ui_search, 3) if ui_search else None,
199
+ "repeat_percent": round(100 * counters.get("ui_repeat_search_60s", 0) / ui_search, 2) if ui_search else None,
200
+ "cold_attempts": attempts, "cold_failures": counters.get("engine_cold_start_failure", 0),
201
+ "cold_successes": counters.get("engine_cold_start_success", 0)},
202
+ "rest_windows": {str(hours): summarize_window(rows, now, hours) for hours in (24, 168, 336)},
203
  "rest": {"retention_days": 14, "first_hour": first_hour,
204
  "last_hour": max(hours) if hours else None,
205
  "count": total, "error_percent": round(100 * (statuses["4xx"] + statuses["5xx"]) / total, 2) if total else None,
 
214
  from core import telemetry, traffic_attribution
215
  telemetry_snapshot = telemetry.get_snapshot()
216
  attribution_snapshot = traffic_attribution.get_admin_snapshot()
217
+ def aggregate():
218
+ history, status = load_history()
219
+ return build_dashboard(telemetry_snapshot, attribution_snapshot, history=history, history_status=status)
220
+ return await asyncio.to_thread(aggregate)
core/traffic_attribution.py CHANGED
@@ -742,7 +742,7 @@ def get_snapshot() -> dict[str, Any]:
742
 
743
 
744
  def get_admin_snapshot() -> dict[str, Any]:
745
- """Copy only overview fields on the event loop; no I/O or source identities.
746
 
747
  The detached snapshot can be aggregated in a worker without racing mutable
748
  request counters. Pending, sub-threshold records remain excluded.
@@ -750,7 +750,10 @@ def get_admin_snapshot() -> dict[str, Any]:
750
  return {"records": [
751
  {"day": key[0], "hour": key[1], "endpoint": key[5],
752
  "status_class": key[6], "latency_bucket": key[8],
753
- "count": metric["count"], "sum_ms": metric["sum_ms"]}
 
 
 
754
  for key, metric in _memory_records.items()
755
  ]}
756
 
 
742
 
743
 
744
  def get_admin_snapshot() -> dict[str, Any]:
745
+ """Copy existing safe aggregate fields on the event loop; no I/O or new tracking.
746
 
747
  The detached snapshot can be aggregated in a worker without racing mutable
748
  request counters. Pending, sub-threshold records remain excluded.
 
750
  return {"records": [
751
  {"day": key[0], "hour": key[1], "endpoint": key[5],
752
  "status_class": key[6], "latency_bucket": key[8],
753
+ "count": metric["count"], "sum_ms": metric["sum_ms"],
754
+ "source_kind": key[2], "source_name": key[3], "source_site": key[4],
755
+ "client_family": key[7], "peak_in_flight": metric.get("peak_in_flight", 0),
756
+ "peak_per_minute": metric.get("peak_per_minute", 0)}
757
  for key, metric in _memory_records.items()
758
  ]}
759
 
core/ui_performance.py CHANGED
@@ -7,6 +7,7 @@ import logging
7
  import math
8
  import os
9
  from collections import deque
 
10
  from contextlib import contextmanager
11
  from copy import deepcopy
12
  from datetime import datetime, timezone
@@ -21,6 +22,7 @@ METRICS = frozenset({
21
  'selected_render', 'history_render', 'favorites_render',
22
  'browser_roundtrip', 'event_loop_lag',
23
  'recommendation_wait', 'recommendation_compute',
 
24
  })
25
  _samples: dict[str, dict] = {}
26
  _probe_failures = 0
@@ -34,6 +36,23 @@ _gc_lock = RLock()
34
  _gc_started: dict[int, float] = {}
35
  _gc_samples: dict[int, dict] = {}
36
  _runtime_started: tuple[float, float] | None = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
 
39
  def _gc_callback(phase: str, info: dict) -> None:
@@ -51,11 +70,14 @@ def _gc_callback(phase: str, info: dict) -> None:
51
  duration = max(0.0, now - started) * 1000
52
  sample = _gc_samples.setdefault(generation, {
53
  'count': 0, 'sum_ms': 0.0, 'max_ms': 0.0, 'over_200ms': 0,
 
54
  })
55
  sample['count'] += 1
56
  sample['sum_ms'] += duration
57
  sample['max_ms'] = max(sample['max_ms'], duration)
58
  sample['over_200ms'] += duration > 200
 
 
59
 
60
 
61
  def _summarize(sample: dict) -> dict:
@@ -77,13 +99,26 @@ def _take_runtime() -> dict | None:
77
  _runtime_started = (now, cpu)
78
  with _gc_lock:
79
  samples, _gc_samples = _gc_samples, {}
80
- return {
81
  # 100% 表示消耗一个逻辑核;8 核满载可接近 800%,不是整机占用率。
82
  'process_cpu_percent': round(100 * used_cpu / wall, 1) if wall else 0.0,
83
  'wall_ms': round(wall * 1000, 1),
84
  'logical_cpus': os.cpu_count() or 1,
85
- 'gc': {str(gen): _summarize(sample) for gen, sample in sorted(samples.items())},
 
 
86
  }
 
 
 
 
 
 
 
 
 
 
 
87
 
88
 
89
  def record(name: str, duration_ms: float) -> None:
@@ -199,7 +234,18 @@ def _parse_runtime(runtime: dict) -> dict:
199
  if type(value) not in (int, float) or not math.isfinite(value) or value < 0:
200
  raise ValueError('invalid GC duration')
201
  clean_gc[generation] = {key: sample[key] for key in ('count', 'avg_ms', 'max_ms', 'over_200ms')}
202
- return {key: runtime[key] for key in ('process_cpu_percent', 'wall_ms', 'logical_cpus')} | {'gc': clean_gc}
 
 
 
 
 
 
 
 
 
 
 
203
 
204
 
205
  def _write_snapshot(snapshot: dict) -> None:
 
7
  import math
8
  import os
9
  from collections import deque
10
+ from collections.abc import Callable
11
  from contextlib import contextmanager
12
  from copy import deepcopy
13
  from datetime import datetime, timezone
 
22
  'selected_render', 'history_render', 'favorites_render',
23
  'browser_roundtrip', 'event_loop_lag',
24
  'recommendation_wait', 'recommendation_compute',
25
+ 'related_render', 'artist_render', 'group_render', 'group_page_render',
26
  })
27
  _samples: dict[str, dict] = {}
28
  _probe_failures = 0
 
36
  _gc_started: dict[int, float] = {}
37
  _gc_samples: dict[int, dict] = {}
38
  _runtime_started: tuple[float, float] | None = None
39
+ _ui_snapshot_provider: Callable[[], dict] | None = None
40
+
41
+
42
+ def set_ui_snapshot_provider(provider: Callable[[], dict]) -> None:
43
+ """UI 入口注册计数函数;采样模块不导入 UI 或保留页面对象。"""
44
+ global _ui_snapshot_provider
45
+ _ui_snapshot_provider = provider
46
+
47
+
48
+ def _read_rss_bytes() -> int | None:
49
+ """Linux 当前驻留内存;不可用时省略,不能用峰值冒充当前值。"""
50
+ try:
51
+ with open('/proc/self/statm', encoding='ascii') as source:
52
+ pages = int(source.read(256).split()[1])
53
+ return pages * os.sysconf('SC_PAGE_SIZE')
54
+ except (OSError, ValueError, IndexError, AttributeError):
55
+ return None
56
 
57
 
58
  def _gc_callback(phase: str, info: dict) -> None:
 
70
  duration = max(0.0, now - started) * 1000
71
  sample = _gc_samples.setdefault(generation, {
72
  'count': 0, 'sum_ms': 0.0, 'max_ms': 0.0, 'over_200ms': 0,
73
+ 'collected': 0, 'uncollectable': 0,
74
  })
75
  sample['count'] += 1
76
  sample['sum_ms'] += duration
77
  sample['max_ms'] = max(sample['max_ms'], duration)
78
  sample['over_200ms'] += duration > 200
79
+ sample['collected'] += info.get('collected', 0)
80
+ sample['uncollectable'] += info.get('uncollectable', 0)
81
 
82
 
83
  def _summarize(sample: dict) -> dict:
 
99
  _runtime_started = (now, cpu)
100
  with _gc_lock:
101
  samples, _gc_samples = _gc_samples, {}
102
+ runtime = {
103
  # 100% 表示消耗一个逻辑核;8 核满载可接近 800%,不是整机占用率。
104
  'process_cpu_percent': round(100 * used_cpu / wall, 1) if wall else 0.0,
105
  'wall_ms': round(wall * 1000, 1),
106
  'logical_cpus': os.cpu_count() or 1,
107
+ 'gc': {str(gen): _summarize(sample) | {
108
+ 'collected': sample['collected'], 'uncollectable': sample['uncollectable'],
109
+ } for gen, sample in sorted(samples.items())},
110
  }
111
+ rss = _read_rss_bytes()
112
+ if rss is not None:
113
+ runtime['rss_bytes'] = rss
114
+ if _ui_snapshot_provider is not None:
115
+ try:
116
+ values = _ui_snapshot_provider()
117
+ runtime.update({key: values[key] for key in ('ui_clients', 'ui_elements')
118
+ if type(values.get(key)) is int and values[key] >= 0})
119
+ except Exception:
120
+ pass # 页面计数不可用不影响其余采样。
121
+ return runtime
122
 
123
 
124
  def record(name: str, duration_ms: float) -> None:
 
234
  if type(value) not in (int, float) or not math.isfinite(value) or value < 0:
235
  raise ValueError('invalid GC duration')
236
  clean_gc[generation] = {key: sample[key] for key in ('count', 'avg_ms', 'max_ms', 'over_200ms')}
237
+ for key in ('collected', 'uncollectable'):
238
+ if key in sample:
239
+ if type(sample[key]) is not int or sample[key] < 0:
240
+ raise ValueError('invalid GC object counts')
241
+ clean_gc[generation][key] = sample[key]
242
+ result = {key: runtime[key] for key in ('process_cpu_percent', 'wall_ms', 'logical_cpus')} | {'gc': clean_gc}
243
+ for key in ('rss_bytes', 'ui_clients', 'ui_elements'):
244
+ if key in runtime:
245
+ if type(runtime[key]) is not int or runtime[key] < 0:
246
+ raise ValueError('invalid resource counts')
247
+ result[key] = runtime[key]
248
+ return result
249
 
250
 
251
  def _write_snapshot(snapshot: dict) -> None:
core/ui_text.py CHANGED
@@ -1,5 +1,7 @@
1
  from pathlib import Path
2
  from typing import Any
 
 
3
 
4
  import yaml
5
 
@@ -10,6 +12,7 @@ REQUIRED_TEXT_PATHS = (
10
  ("sponsor", "toolchain_prompt"),
11
  ("help", "update_title"),
12
  ("help", "update_summary"),
 
13
  ("help", "update_markdown"),
14
  ("tutorial", "title"),
15
  ("tutorial", "subtitle"),
@@ -27,6 +30,13 @@ REQUIRED_TEXT_PATHS = (
27
  )
28
 
29
 
 
 
 
 
 
 
 
30
  def load_ui_text(path: Path = DEFAULT_UI_TEXT_PATH) -> dict[str, Any]:
31
  """Load editable UI copy and fail with a clear startup error if it is invalid."""
32
  try:
 
1
  from pathlib import Path
2
  from typing import Any
3
+ import hashlib
4
+ import json
5
 
6
  import yaml
7
 
 
12
  ("sponsor", "toolchain_prompt"),
13
  ("help", "update_title"),
14
  ("help", "update_summary"),
15
+ ("help", "update_detail_label"),
16
  ("help", "update_markdown"),
17
  ("tutorial", "title"),
18
  ("tutorial", "subtitle"),
 
30
  )
31
 
32
 
33
+ def announcement_version(ui_text: dict[str, Any]) -> str:
34
+ """Invalidate dismissal only when the announcement or its details change."""
35
+ fields = ("update_title", "update_summary", "update_detail_label", "update_markdown")
36
+ content = json.dumps([ui_text["help"][key] for key in fields], ensure_ascii=False)
37
+ return "content-" + hashlib.sha256(content.encode("utf-8")).hexdigest()
38
+
39
+
40
  def load_ui_text(path: Path = DEFAULT_UI_TEXT_PATH) -> dict[str, Any]:
41
  """Load editable UI copy and fail with a clear startup error if it is invalid."""
42
  try:
ui_nicegui.py CHANGED
@@ -7,6 +7,7 @@ import traceback
7
 
8
  from fastapi.responses import PlainTextResponse
9
  from nicegui import app, ui
 
10
 
11
  from api_fastapi import app as api_app
12
  from core import counter, telemetry, traffic_attribution
@@ -54,6 +55,14 @@ if __name__ in {'__main__', '__mp_main__'}:
54
  host, port = get_host_port()
55
  app.include_router(create_admin_router())
56
  app.add_middleware(NiceGUIPollingDisconnectGuard)
 
 
 
 
 
 
 
 
57
  app.on_startup(ui_performance.start_monitor)
58
  app.on_shutdown(ui_performance.stop_monitor)
59
 
 
7
 
8
  from fastapi.responses import PlainTextResponse
9
  from nicegui import app, ui
10
+ from nicegui.client import Client
11
 
12
  from api_fastapi import app as api_app
13
  from core import counter, telemetry, traffic_attribution
 
55
  host, port = get_host_port()
56
  app.include_router(create_admin_router())
57
  app.add_middleware(NiceGUIPollingDisconnectGuard)
58
+
59
+ def ui_resource_counts():
60
+ return {
61
+ 'ui_clients': len(Client.instances),
62
+ 'ui_elements': sum(len(client.elements) for client in Client.instances.values()),
63
+ }
64
+
65
+ ui_performance.set_ui_snapshot_provider(ui_resource_counts)
66
  app.on_startup(ui_performance.start_monitor)
67
  app.on_shutdown(ui_performance.stop_monitor)
68
 
webui/constants.py CHANGED
@@ -2,7 +2,7 @@
2
 
3
  import os
4
 
5
- from core.ui_text import load_ui_text
6
  from core.workspace import (
7
  ARTIST_SELECTION_ORIGINS,
8
  FAVORITES_STORAGE_KEY,
@@ -29,7 +29,6 @@ OPTIONAL_COLS = {
29
 
30
  CONFIG_LS_KEY = 'danbooru_search_config'
31
  CONFIG_VERSION = 7
32
- ANNOUNCEMENT_VERSION = 'rest-attribution-2026-09'
33
  LOCAL_STORAGE_READ_CHUNK_CHARS = 200_000
34
  LOCAL_STORAGE_MAX_READ_CHARS = 4_000_000
35
  HISTORY_PRE_COMPACTION_BACKUP_KEY = f'{HISTORY_STORAGE_KEY}_pre_compaction_backup'
@@ -42,6 +41,7 @@ SPONSOR_TOOLCHAIN_URL = 'http://intro.sakizuki.site/index.html'
42
  SPONSOR_NOTICE_TEXT = '喜欢的话,可以请作者喝杯咖啡'
43
  SPONSOR_TITLE = '谢谢你愿意支持'
44
  UI_TEXT = load_ui_text()
 
45
 
46
 
47
  def resolve_group_render_limit(default: int = 80) -> int:
 
2
 
3
  import os
4
 
5
+ from core.ui_text import announcement_version, load_ui_text
6
  from core.workspace import (
7
  ARTIST_SELECTION_ORIGINS,
8
  FAVORITES_STORAGE_KEY,
 
29
 
30
  CONFIG_LS_KEY = 'danbooru_search_config'
31
  CONFIG_VERSION = 7
 
32
  LOCAL_STORAGE_READ_CHUNK_CHARS = 200_000
33
  LOCAL_STORAGE_MAX_READ_CHARS = 4_000_000
34
  HISTORY_PRE_COMPACTION_BACKUP_KEY = f'{HISTORY_STORAGE_KEY}_pre_compaction_backup'
 
41
  SPONSOR_NOTICE_TEXT = '喜欢的话,可以请作者喝杯咖啡'
42
  SPONSOR_TITLE = '谢谢你愿意支持'
43
  UI_TEXT = load_ui_text()
44
+ ANNOUNCEMENT_VERSION = announcement_version(UI_TEXT)
45
 
46
 
47
  def resolve_group_render_limit(default: int = 80) -> int:
webui/controller.py CHANGED
@@ -96,6 +96,8 @@ from webui.render.recommendations import (
96
  render_artist_page,
97
  render_artist_recommendations,
98
  render_group_expansion,
 
 
99
  render_related_list,
100
  render_related_page,
101
  )
@@ -547,7 +549,7 @@ class DanbooruSearchUI:
547
  confirm_delete_all_personal_data(self, storage_keys)
548
 
549
  def _build_release_announcement(self):
550
- build_release_announcement(self)
551
 
552
  def _dismiss_release_announcement(self):
553
  self.dismissed_announcement_version = _ANNOUNCEMENT_VERSION
@@ -1485,7 +1487,7 @@ class DanbooruSearchUI:
1485
  self._render_artist_rec([], {})
1486
  # 清空 Group 同类扩展
1487
  if self.group_expansion_container is not None:
1488
- self.group_expansion_container.clear()
1489
  with self.group_expansion_container:
1490
  ui.label('请先搜索并勾选标签…').classes('text-sm text-gray-400 italic p-4')
1491
  self._save_staged_tags()
@@ -1946,7 +1948,7 @@ class DanbooruSearchUI:
1946
  ui.notify('已触发同类标签更新', type='info', timeout=1500)
1947
  else:
1948
  if self.group_expansion_container is not None:
1949
- self.group_expansion_container.clear()
1950
  with self.group_expansion_container:
1951
  ui.label('请先搜索并勾选标签…').classes('text-sm text-gray-400 italic p-4')
1952
  ui.notify('暂未选中标签', type='info', timeout=1500)
@@ -2036,7 +2038,7 @@ class DanbooruSearchUI:
2036
  result['groups'], selected_tags, show_nsfw,
2037
  )
2038
  elif self.group_expansion_container is not None:
2039
- self.group_expansion_container.clear()
2040
  with self.group_expansion_container:
2041
  ui.label('请先搜索并勾选标签…').classes(
2042
  'text-sm text-gray-400 italic p-4'
@@ -2144,7 +2146,13 @@ class DanbooruSearchUI:
2144
  selected_tags: list[str],
2145
  show_nsfw: bool,
2146
  ):
 
 
2147
  await self._capture_group_scroll_positions(anchor_bottom=True)
 
 
 
 
2148
  current = self._group_render_limits.get(group_name, GROUP_RENDER_TAG_LIMIT)
2149
  self._group_render_limits[group_name] = _next_group_render_limit(
2150
  current,
@@ -2152,7 +2160,8 @@ class DanbooruSearchUI:
2152
  GROUP_RENDER_TAG_LIMIT,
2153
  )
2154
  self._group_expanded_names.add(group_name)
2155
- self._render_group_expansion(group_data, selected_tags, show_nsfw)
 
2156
 
2157
  # ── 表格列动态更新 ──────────────────────────────────────────────────
2158
 
 
96
  render_artist_page,
97
  render_artist_recommendations,
98
  render_group_expansion,
99
+ render_group_page,
100
+ clear_group_expansion,
101
  render_related_list,
102
  render_related_page,
103
  )
 
549
  confirm_delete_all_personal_data(self, storage_keys)
550
 
551
  def _build_release_announcement(self):
552
+ build_release_announcement(self, ui_text=UI_TEXT)
553
 
554
  def _dismiss_release_announcement(self):
555
  self.dismissed_announcement_version = _ANNOUNCEMENT_VERSION
 
1487
  self._render_artist_rec([], {})
1488
  # 清空 Group 同类扩展
1489
  if self.group_expansion_container is not None:
1490
+ clear_group_expansion(self)
1491
  with self.group_expansion_container:
1492
  ui.label('请先搜索并勾选标签…').classes('text-sm text-gray-400 italic p-4')
1493
  self._save_staged_tags()
 
1948
  ui.notify('已触发同类标签更新', type='info', timeout=1500)
1949
  else:
1950
  if self.group_expansion_container is not None:
1951
+ clear_group_expansion(self)
1952
  with self.group_expansion_container:
1953
  ui.label('请先搜索并勾选标签…').classes('text-sm text-gray-400 italic p-4')
1954
  ui.notify('暂未选中标签', type='info', timeout=1500)
 
2038
  result['groups'], selected_tags, show_nsfw,
2039
  )
2040
  elif self.group_expansion_container is not None:
2041
+ clear_group_expansion(self)
2042
  with self.group_expansion_container:
2043
  ui.label('请先搜索并勾选标签…').classes(
2044
  'text-sm text-gray-400 italic p-4'
 
2146
  selected_tags: list[str],
2147
  show_nsfw: bool,
2148
  ):
2149
+ view = getattr(self, '_group_views', {}).get(group_name)
2150
+ generation = self._recommendation_generation
2151
  await self._capture_group_scroll_positions(anchor_bottom=True)
2152
+ if (not self._client_alive() or generation != self._recommendation_generation
2153
+ or view is None or self._group_views.get(group_name) is not view):
2154
+ return
2155
+ total = len(view.info['tags'])
2156
  current = self._group_render_limits.get(group_name, GROUP_RENDER_TAG_LIMIT)
2157
  self._group_render_limits[group_name] = _next_group_render_limit(
2158
  current,
 
2160
  GROUP_RENDER_TAG_LIMIT,
2161
  )
2162
  self._group_expanded_names.add(group_name)
2163
+ render_group_page(self, group_name)
2164
+ self._restore_group_scroll_positions()
2165
 
2166
  # ── 表格列动态更新 ──────────────────────────────────────────────────
2167
 
webui/render/page.py CHANGED
@@ -385,7 +385,7 @@ def render_service_status(controller: Any, status: dict) -> None:
385
  ui.label(' · '.join(parts)).classes('font-medium')
386
 
387
 
388
- def build_release_announcement(controller: Any) -> None:
389
  controller.announcement_banner = ui.element('div').classes(
390
  'w-full release-notice section-surface px-3 py-2'
391
  )
@@ -395,11 +395,10 @@ def build_release_announcement(controller: Any) -> None:
395
  'release-notice-icon'
396
  )
397
  ui.label(
398
- '近期 REST API 调用量明显增长。建议接入方声明 X-DanbooruSearch-Client 与 '
399
- 'X-DanbooruSearch-Site;观察期内未声明不影响使用,未来可能受到限流。'
400
  ).classes('release-notice-copy')
401
  ui.button(
402
- '查看详情',
403
  ).on('click', js_handler=controller.help_dialog.browser_action(True)).props('outline dense no-caps').classes(
404
  'release-notice-detail'
405
  )
 
385
  ui.label(' · '.join(parts)).classes('font-medium')
386
 
387
 
388
+ def build_release_announcement(controller: Any, *, ui_text: dict) -> None:
389
  controller.announcement_banner = ui.element('div').classes(
390
  'w-full release-notice section-surface px-3 py-2'
391
  )
 
395
  'release-notice-icon'
396
  )
397
  ui.label(
398
+ ui_text['help']['update_summary']
 
399
  ).classes('release-notice-copy')
400
  ui.button(
401
+ ui_text['help']['update_detail_label'],
402
  ).on('click', js_handler=controller.help_dialog.browser_action(True)).props('outline dense no-caps').classes(
403
  'release-notice-detail'
404
  )
webui/render/recommendations.py CHANGED
@@ -1,6 +1,9 @@
1
  """推荐区域的 NiceGUI 容器与分页控件渲染。"""
2
 
3
  from typing import Any
 
 
 
4
 
5
  from nicegui import ui
6
 
@@ -16,18 +19,25 @@ from core.workspace_insights import (
16
  tag_group_candidate_reason,
17
  )
18
  from webui.helpers import (
19
- group_names_key,
20
  group_scroll_dom_id,
21
  limit_group_render_tags,
22
- should_group_start_expanded,
23
  )
24
  from webui.recommendations import page_count, page_items
25
 
26
 
 
27
  def render_related_list(controller: Any, related: list, show_nsfw: bool) -> None:
28
  """保存关联推荐快照,构建分页控件并渲染第一页。"""
29
  if controller.related_list_container is None or controller.related_pagination is None:
30
  return
 
 
 
 
 
 
 
 
31
  controller.related_list_container.clear()
32
  controller.related_pagination.clear()
33
  controller._related_checkboxes.clear()
@@ -35,10 +45,7 @@ def render_related_list(controller: Any, related: list, show_nsfw: bool) -> None
35
  controller._related_page_label = None
36
  controller._related_prev_button = None
37
  controller._related_next_button = None
38
- controller._related_results = [
39
- item for item in related
40
- if not (item.nsfw == '1' and not show_nsfw)
41
- ]
42
  controller._related_show_nsfw = show_nsfw
43
  controller._related_page_count = page_count(
44
  len(controller._related_results), RELATED_REC_PAGE_SIZE
@@ -49,6 +56,7 @@ def render_related_list(controller: Any, related: list, show_nsfw: bool) -> None
49
  controller._replay_motion(
50
  'danbooru-related-recommendations', 'motion-recommendation-enter-right'
51
  )
 
52
  return
53
 
54
  if controller._related_page_count > 1:
@@ -71,8 +79,10 @@ def render_related_list(controller: Any, related: list, show_nsfw: bool) -> None
71
  ).props('flat dense round color=grey-7')
72
 
73
  controller._set_related_page(1)
 
74
 
75
 
 
76
  def render_artist_recommendations(
77
  controller: Any,
78
  artist_results: list,
@@ -82,6 +92,15 @@ def render_artist_recommendations(
82
  """保存画师推荐快照,构建分页控件并渲染第一页。"""
83
  if controller.artist_rec_list is None or controller.artist_rec_pagination is None:
84
  return
 
 
 
 
 
 
 
 
 
85
  controller.artist_rec_list.clear()
86
  controller.artist_rec_pagination.clear()
87
  controller._artist_rec_checkboxes.clear()
@@ -109,6 +128,7 @@ def render_artist_recommendations(
109
  controller._replay_motion(
110
  'danbooru-artist-recommendations', 'motion-recommendation-enter-right'
111
  )
 
112
  return
113
 
114
  if controller._artist_rec_page_count > 1:
@@ -131,6 +151,7 @@ def render_artist_recommendations(
131
  ).props('flat dense round color=grey-7')
132
 
133
  controller._set_artist_rec_page(1)
 
134
 
135
 
136
  def render_related_page(controller: Any) -> None:
@@ -200,7 +221,7 @@ def render_related_page(controller: Any) -> None:
200
  ):
201
  cb = ui.checkbox(
202
  '', value=is_selected,
203
- on_change=lambda e, t=tag: controller._on_related_checkbox_change(t, e.value)
204
  ).props('dense').classes('flex-none')
205
  controller._related_checkboxes[tag] = cb
206
 
@@ -296,7 +317,7 @@ def render_artist_page(controller: Any) -> None:
296
  ):
297
  cb = ui.checkbox(
298
  '', value=is_selected,
299
- on_change=lambda e, t=artist: controller._on_artist_rec_checkbox_change(t, e.value)
300
  ).props('dense')
301
  controller._artist_rec_checkboxes[artist] = cb
302
 
@@ -324,140 +345,219 @@ def render_artist_page(controller: Any) -> None:
324
  f'text-sm font-bold text-{score_color}-600 whitespace-nowrap'
325
  )
326
 
327
- def render_group_expansion(controller: Any, group_data: list, selected_tags: list[str], show_nsfw: bool) -> None:
328
- """渲染 Group 同类扩展区域。"""
329
- if controller.group_expansion_container is None:
330
- return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
331
  controller.group_expansion_container.clear()
 
332
  controller._group_checkboxes.clear()
333
  controller._group_candidate_sources.clear()
334
- group_key = group_names_key(group_data)
335
- if group_key != controller._group_render_key:
336
- controller._group_render_key = group_key
337
- controller._group_render_limits.clear()
338
- controller._group_expanded_names.clear()
339
- controller._group_scroll_positions.clear()
340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  if not group_data:
342
- with controller.group_expansion_container:
343
  ui.label('已选标签无分组信息').classes('text-sm text-gray-400 italic p-2')
344
- controller._replay_motion('danbooru-group-expansion', 'motion-refresh-enter')
345
- return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
 
347
- # 行背景色按分类区分(与关联推荐一致)
348
- CAT_BG = {
349
- 'General': 'background-color: var(--general-bg);',
350
- 'Character': 'background-color: var(--character-bg);',
351
- 'Copyright': 'background-color: var(--copyright-bg);',
352
- }
353
- CAT_LABEL = {'General': '通用', 'Character': '角色', 'Copyright': '作品'}
354
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
355
  selected_now = set(controller._get_selected_tags())
356
-
357
- with controller.group_expansion_container:
358
- for group_info in group_data:
359
- group_name = group_info['group']
360
- group_cn = group_info.get('group_cn_name', group_name.replace('tag_group:', ''))
361
- group_sources = list(group_info.get('sources') or [])
362
- group_reason = tag_group_candidate_reason(group_cn, group_sources)
363
- group_source_detail = group_cn
364
- if group_sources:
365
- group_source_detail += f";触发标签:{'、'.join(group_sources[:3])}"
366
- tags = group_info['tags']
367
- visible_limit = controller._group_render_limits.get(group_name, GROUP_RENDER_TAG_LIMIT)
368
- visible_tags, hidden_count = limit_group_render_tags(tags, visible_limit)
369
- scroll_id = group_scroll_dom_id(group_name)
370
-
371
- expansion = ui.expansion(
372
- f'{group_cn} ({len(tags)} 个标签)',
373
- icon='label',
374
- value=should_group_start_expanded(group_name, controller._group_expanded_names),
375
- ).classes('w-full').props('dense')
376
- expansion.on(
377
- 'update:model-value',
378
- lambda e, g=group_name: controller._on_group_expansion_change(g, e),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
379
  )
380
- with expansion:
381
- with ui.element('div').props(
382
- f'id="{scroll_id}" data-danbooru-group-scroll="1"'
383
- ).classes('w-full grid grid-cols-2 gap-1 p-1').style('max-height: 600px; overflow-y: auto;'):
384
- for t in visible_tags:
385
- tag = t['tag']
386
- controller._group_candidate_sources.setdefault(tag, group_source_detail)
387
- cn_first = t['cn_name'].split(',')[0].strip() if t['cn_name'] else ''
388
- cn_full = t.get('cn_name', '')
389
- cat = t['category']
390
- wiki_text = str(t.get('wiki', ''))
391
- row_bg = CAT_BG.get(cat, '')
392
- is_selected = tag in selected_now
393
-
394
- cat_label = CAT_LABEL.get(cat, '')
395
- tooltip_html = ''
396
- if wiki_text:
397
- prefix = f'<span style="opacity:0.7;margin-right:4px;">[{cat_label}]</span>' if cat_label else ''
398
- tooltip_html += f'<div style="margin-bottom:6px;">{prefix}{wiki_text}</div>'
399
- if cn_full:
400
- tooltip_html += f'<div style="opacity:0.85;">{cn_full}</div>'
401
-
402
- with ui.row().classes(
403
- 'w-full min-w-0 flex-nowrap items-center gap-1.5 px-2 py-1.5 '
404
- 'rounded overflow-hidden related-item'
405
- ).style(row_bg):
406
- if tooltip_html:
407
- with ui.tooltip().props('content-class="bg-black text-white shadow-4" max-width="500px"'):
408
- ui.html(tooltip_html).style('font-size:14px;line-height:1.5;max-width:480px;')
409
-
410
- # 复选框
411
- cb = ui.checkbox(
412
- '', value=is_selected,
413
- on_change=lambda e, t=tag: controller._on_group_checkbox_change(t, e.value),
414
- ).props('dense').classes('flex-none')
415
- controller._group_checkboxes[tag] = cb
416
-
417
- # 标签名 + 中文名(与关联推荐对齐方式一致)
418
- with ui.column().classes('flex-1 gap-0 min-w-0 overflow-hidden'):
419
- link = ui.link(
420
- tag,
421
- f'https://danbooru.donmai.us/wiki_pages/{tag}',
422
- new_tab=True,
423
- ).classes(
424
- 'tag-link w-full min-w-0 text-primary font-bold text-xs truncate'
425
- )
426
- if cn_first:
427
- ui.label(cn_first).classes(
428
- 'w-full text-xs text-gray-500 truncate'
429
- )
430
- ui.label(group_reason).classes(
431
- 'w-full text-xs text-slate-500 truncate'
432
- )
433
 
434
- # 热度
435
- count = t['post_count']
436
- if count > 0:
437
- if count >= 10000:
438
- count_str = f'{count/1000:.0f}k'
439
- elif count >= 1000:
440
- count_str = f'{count/1000:.1f}k'
441
- else:
442
- count_str = str(count)
443
- ui.label(count_str).classes(
444
- 'flex-none ml-auto self-center text-sm font-bold '
445
- 'text-grey-600 whitespace-nowrap'
446
- )
447
- if hidden_count > 0:
448
- async def _load_more(
449
- g=group_name,
450
- total=len(tags),
451
- gd=group_data,
452
- st=list(selected_tags),
453
- sn=show_nsfw,
454
- ):
455
- await controller._load_more_group_tags(g, total, gd, st, sn)
456
-
457
- ui.button(
458
- f'加载更多(剩余 {hidden_count} 个)',
459
- icon='expand_more',
460
- on_click=_load_more,
461
- ).props('dense flat color=primary').classes('col-span-2 text-xs')
462
- controller._restore_group_scroll_positions()
463
- controller._replay_motion('danbooru-group-expansion', 'motion-refresh-enter')
 
1
  """推荐区域的 NiceGUI 容器与分页控件渲染。"""
2
 
3
  from typing import Any
4
+ from types import SimpleNamespace
5
+
6
+ from core.ui_performance import measure
7
 
8
  from nicegui import ui
9
 
 
19
  tag_group_candidate_reason,
20
  )
21
  from webui.helpers import (
 
22
  group_scroll_dom_id,
23
  limit_group_render_tags,
 
24
  )
25
  from webui.recommendations import page_count, page_items
26
 
27
 
28
+ @measure('related_render')
29
  def render_related_list(controller: Any, related: list, show_nsfw: bool) -> None:
30
  """保存关联推荐快照,构建分页控件并渲染第一页。"""
31
  if controller.related_list_container is None or controller.related_pagination is None:
32
  return
33
+ results = [item for item in related if not (item.nsfw == '1' and not show_nsfw)]
34
+ signature = tuple((r.tag, r.cn_name, r.category, r.nsfw, r.cooc_count,
35
+ r.cooc_score, tuple(r.sources), controller._lookup_tag_wiki(r.tag)) for r in results)
36
+ if (getattr(controller, '_related_signature', None) == signature
37
+ and controller.related_list_container.default_slot.children):
38
+ _sync_checks(controller, controller._related_checkboxes)
39
+ return
40
+ controller._related_signature = None
41
  controller.related_list_container.clear()
42
  controller.related_pagination.clear()
43
  controller._related_checkboxes.clear()
 
45
  controller._related_page_label = None
46
  controller._related_prev_button = None
47
  controller._related_next_button = None
48
+ controller._related_results = results
 
 
 
49
  controller._related_show_nsfw = show_nsfw
50
  controller._related_page_count = page_count(
51
  len(controller._related_results), RELATED_REC_PAGE_SIZE
 
56
  controller._replay_motion(
57
  'danbooru-related-recommendations', 'motion-recommendation-enter-right'
58
  )
59
+ controller._related_signature = signature
60
  return
61
 
62
  if controller._related_page_count > 1:
 
79
  ).props('flat dense round color=grey-7')
80
 
81
  controller._set_related_page(1)
82
+ controller._related_signature = signature
83
 
84
 
85
+ @measure('artist_render')
86
  def render_artist_recommendations(
87
  controller: Any,
88
  artist_results: list,
 
92
  """保存画师推荐快照,构建分页控件并渲染第一页。"""
93
  if controller.artist_rec_list is None or controller.artist_rec_pagination is None:
94
  return
95
+ signature = (tuple((r.artist, r.score, r.cooc_count, r.post_count, tuple(r.sources), r.hit_count)
96
+ for r in artist_results[:ARTIST_REC_LIMIT]),
97
+ tuple((r.artist, tuple((top_tags or {}).get(r.artist, [])[:10]))
98
+ for r in artist_results[:ARTIST_REC_LIMIT]), show_nsfw)
99
+ if (getattr(controller, '_artist_signature', None) == signature
100
+ and controller.artist_rec_list.default_slot.children):
101
+ _sync_checks(controller, controller._artist_rec_checkboxes)
102
+ return
103
+ controller._artist_signature = None
104
  controller.artist_rec_list.clear()
105
  controller.artist_rec_pagination.clear()
106
  controller._artist_rec_checkboxes.clear()
 
128
  controller._replay_motion(
129
  'danbooru-artist-recommendations', 'motion-recommendation-enter-right'
130
  )
131
+ controller._artist_signature = signature
132
  return
133
 
134
  if controller._artist_rec_page_count > 1:
 
151
  ).props('flat dense round color=grey-7')
152
 
153
  controller._set_artist_rec_page(1)
154
+ controller._artist_signature = signature
155
 
156
 
157
  def render_related_page(controller: Any) -> None:
 
221
  ):
222
  cb = ui.checkbox(
223
  '', value=is_selected,
224
+ on_change=lambda e, t=tag: _checkbox_changed(controller, '_on_related_checkbox_change', t, e.value)
225
  ).props('dense').classes('flex-none')
226
  controller._related_checkboxes[tag] = cb
227
 
 
317
  ):
318
  cb = ui.checkbox(
319
  '', value=is_selected,
320
+ on_change=lambda e, t=artist: _checkbox_changed(controller, '_on_artist_rec_checkbox_change', t, e.value)
321
  ).props('dense')
322
  controller._artist_rec_checkboxes[artist] = cb
323
 
 
345
  f'text-sm font-bold text-{score_color}-600 whitespace-nowrap'
346
  )
347
 
348
+ def _checkbox_changed(controller, method, tag, value):
349
+ if not getattr(controller, '_syncing_recommendation_checks', False):
350
+ getattr(controller, method)(tag, value)
351
+
352
+
353
+ def _sync_checks(controller, checks):
354
+ previous = getattr(controller, '_syncing_recommendation_checks', False)
355
+ controller._syncing_recommendation_checks = True
356
+ try:
357
+ selected = set(controller._get_selected_tags())
358
+ for tag, checkbox in checks.items():
359
+ if not checkbox.is_deleted and checkbox.value != (tag in selected):
360
+ checkbox.set_value(tag in selected)
361
+ finally:
362
+ controller._syncing_recommendation_checks = previous
363
+
364
+
365
+ def _group_reason(info):
366
+ name = info.get('group_cn_name', info['group'].replace('tag_group:', ''))
367
+ return tag_group_candidate_reason(name, list(info.get('sources') or []))
368
+
369
+
370
+ def _group_changed(controller, name, event):
371
+ controller._on_group_expansion_change(name, event)
372
+ view = getattr(controller, '_group_views', {}).get(name)
373
+ if view is not None and name in controller._group_expanded_names:
374
+ render_group_page(controller, name)
375
+
376
+
377
+ def clear_group_expansion(controller):
378
  controller.group_expansion_container.clear()
379
+ controller._group_views = {}
380
  controller._group_checkboxes.clear()
381
  controller._group_candidate_sources.clear()
382
+ controller._group_render_limits.clear()
383
+ controller._group_expanded_names.clear()
384
+ controller._group_scroll_positions.clear()
 
 
 
385
 
386
+
387
+ @measure('group_render')
388
+ def render_group_expansion(controller: Any, group_data: list, selected_tags: list[str], show_nsfw: bool) -> None:
389
+ root = controller.group_expansion_container
390
+ if root is None:
391
+ return
392
+ views = getattr(controller, '_group_views', {})
393
+ controller._group_views = views
394
+ names = {info['group'] for info in group_data}
395
+ for name in list(views):
396
+ if name not in names or views[name].root.is_deleted:
397
+ if not views[name].root.is_deleted:
398
+ views[name].root.delete()
399
+ del views[name]
400
+ controller._group_render_limits.pop(name, None)
401
+ controller._group_expanded_names.discard(name)
402
+ if not views:
403
+ root.clear()
404
  if not group_data:
405
+ with root:
406
  ui.label('已选标签无分组信息').classes('text-sm text-gray-400 italic p-2')
407
+ controller._group_checkboxes.clear()
408
+ controller._group_candidate_sources.clear()
409
+ for index, info in enumerate(group_data):
410
+ name = info['group']
411
+ view = views.get(name)
412
+ if view is None:
413
+ with root:
414
+ expansion = ui.expansion('', icon='label', value=False).classes('w-full').props('dense')
415
+ expansion.on('update:model-value', lambda e, g=name: _group_changed(controller, g, e))
416
+ view = SimpleNamespace(root=expansion, body=None, rows={}, more=None, info=info,
417
+ selected_tags=list(selected_tags), show_nsfw=show_nsfw)
418
+ views[name] = view
419
+ view.info, view.selected_tags, view.show_nsfw = info, list(selected_tags), show_nsfw
420
+ label = f"{info.get('group_cn_name', name.replace('tag_group:', ''))} ({len(info['tags'])} 个标签)"
421
+ if view.root.text != label:
422
+ view.root.set_text(label)
423
+ if root.default_slot.children[index] is not view.root:
424
+ view.root.move(root, index)
425
+ if view.body is not None or name in controller._group_expanded_names:
426
+ render_group_page(controller, name)
427
+ source = info.get('group_cn_name', name.replace('tag_group:', ''))
428
+ sources = list(info.get('sources') or [])
429
+ if sources:
430
+ source += f";触发标签:{'、'.join(sources[:3])}"
431
+ for tag in view.rows:
432
+ controller._group_candidate_sources.setdefault(tag, source)
433
+ for tag, (_, checkbox, _) in view.rows.items():
434
+ controller._group_checkboxes[tag] = checkbox
435
+ controller._restore_group_scroll_positions()
436
 
 
 
 
 
 
 
 
437
 
438
+ @measure('group_page_render')
439
+ def render_group_page(controller, name):
440
+ view = getattr(controller, '_group_views', {}).get(name)
441
+ if view is None or view.root.is_deleted:
442
+ return
443
+ if view.body is None:
444
+ with view.root:
445
+ view.body = ui.element('div').props(
446
+ f'id="{group_scroll_dom_id(name)}" data-danbooru-group-scroll="1"'
447
+ ).classes('w-full grid grid-cols-2 gap-1 p-1').style('max-height: 600px; overflow-y: auto;')
448
+ limit = controller._group_render_limits.get(name, GROUP_RENDER_TAG_LIMIT)
449
+ tags, hidden = limit_group_render_tags(view.info['tags'], limit)
450
+ reason = _group_reason(view.info)
451
+ desired = {t['tag'] for t in tags}
452
+ for tag in list(view.rows):
453
+ if tag not in desired:
454
+ row, checkbox, _ = view.rows.pop(tag)
455
+ row.delete()
456
+ if controller._group_checkboxes.get(tag) is checkbox:
457
+ controller._group_checkboxes.pop(tag, None)
458
+ for index, tag_info in enumerate(tags):
459
+ tag = tag_info['tag']
460
+ signature = (tag_info['cn_name'], tag_info['category'], tag_info['post_count'],
461
+ str(tag_info.get('wiki', '')), reason)
462
+ old = view.rows.get(tag)
463
+ if old is None or old[2] != signature:
464
+ if old is not None:
465
+ old[0].delete()
466
+ with view.body:
467
+ row, checkbox = _create_group_row(controller, tag_info, reason)
468
+ view.rows[tag] = (row, checkbox, signature)
469
+ row, checkbox, _ = view.rows[tag]
470
+ if view.body.default_slot.children[index] is not row:
471
+ row.move(view.body, index)
472
+ controller._group_checkboxes[tag] = checkbox
473
+ source = view.info.get('group_cn_name', name.replace('tag_group:', ''))
474
+ sources = list(view.info.get('sources') or [])
475
+ if sources:
476
+ source += f";触发标签:{'、'.join(sources[:3])}"
477
+ controller._group_candidate_sources.setdefault(tag, source)
478
+ _sync_checks(controller, {tag: item[1] for tag, item in view.rows.items()})
479
+ if hidden:
480
+ if view.more is None:
481
+ async def load_more():
482
+ await controller._load_more_group_tags(name, len(view.info['tags']),
483
+ [view.info], view.selected_tags, view.show_nsfw)
484
+ with view.body:
485
+ view.more = ui.button('', icon='expand_more', on_click=load_more).props(
486
+ 'dense flat color=primary').classes('col-span-2 text-xs')
487
+ text = f'加载更多(剩余 {hidden} 个)'
488
+ if view.more.text != text:
489
+ view.more.set_text(text)
490
+ if view.body.default_slot.children[-1] is not view.more:
491
+ view.more.move(view.body)
492
+ elif view.more is not None:
493
+ view.more.delete()
494
+ view.more = None
495
+
496
+
497
+ def _create_group_row(controller, t, group_reason):
498
+ CAT_BG = {'General': 'background-color: var(--general-bg);',
499
+ 'Character': 'background-color: var(--character-bg);',
500
+ 'Copyright': 'background-color: var(--copyright-bg);'}
501
+ CAT_LABEL = {'General': '通用', 'Character': '角色', 'Copyright': '作品'}
502
  selected_now = set(controller._get_selected_tags())
503
+ tag = t['tag']
504
+ cn_first = t['cn_name'].split(',')[0].strip() if t['cn_name'] else ''
505
+ cn_full = t.get('cn_name', '')
506
+ cat = t['category']
507
+ wiki_text = str(t.get('wiki', ''))
508
+ row_bg = CAT_BG.get(cat, '')
509
+ is_selected = tag in selected_now
510
+
511
+ cat_label = CAT_LABEL.get(cat, '')
512
+ tooltip_html = ''
513
+ if wiki_text:
514
+ prefix = f'<span style="opacity:0.7;margin-right:4px;">[{cat_label}]</span>' if cat_label else ''
515
+ tooltip_html += f'<div style="margin-bottom:6px;">{prefix}{wiki_text}</div>'
516
+ if cn_full:
517
+ tooltip_html += f'<div style="opacity:0.85;">{cn_full}</div>'
518
+
519
+ with ui.row().classes(
520
+ 'w-full min-w-0 flex-nowrap items-center gap-1.5 px-2 py-1.5 '
521
+ 'rounded overflow-hidden related-item'
522
+ ).style(row_bg) as row:
523
+ if tooltip_html:
524
+ with ui.tooltip().props('content-class="bg-black text-white shadow-4" max-width="500px"'):
525
+ ui.html(tooltip_html).style('font-size:14px;line-height:1.5;max-width:480px;')
526
+
527
+ # 复选框
528
+ cb = ui.checkbox(
529
+ '', value=is_selected,
530
+ on_change=lambda e, t=tag: _checkbox_changed(controller, '_on_group_checkbox_change', t, e.value),
531
+ ).props('dense').classes('flex-none')
532
+
533
+ # 标签名 + 中文名(与关联推荐对齐方式一致)
534
+ with ui.column().classes('flex-1 gap-0 min-w-0 overflow-hidden'):
535
+ link = ui.link(
536
+ tag,
537
+ f'https://danbooru.donmai.us/wiki_pages/{tag}',
538
+ new_tab=True,
539
+ ).classes(
540
+ 'tag-link w-full min-w-0 text-primary font-bold text-xs truncate'
541
+ )
542
+ if cn_first:
543
+ ui.label(cn_first).classes(
544
+ 'w-full text-xs text-gray-500 truncate'
545
+ )
546
+ ui.label(group_reason).classes(
547
+ 'w-full text-xs text-slate-500 truncate'
548
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
549
 
550
+ # 热度
551
+ count = t['post_count']
552
+ if count > 0:
553
+ if count >= 10000:
554
+ count_str = f'{count/1000:.0f}k'
555
+ elif count >= 1000:
556
+ count_str = f'{count/1000:.1f}k'
557
+ else:
558
+ count_str = str(count)
559
+ ui.label(count_str).classes(
560
+ 'flex-none ml-auto self-center text-sm font-bold '
561
+ 'text-grey-600 whitespace-nowrap'
562
+ )
563
+ return row, cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
webui/static/admin/admin.css CHANGED
@@ -11,6 +11,27 @@
11
  --amber:#896016;
12
  --focus:#4a90e2;
13
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  * {
15
  box-sizing:border-box;
16
  }
 
11
  --amber:#896016;
12
  --focus:#4a90e2;
13
  }
14
+ .signal-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(140px,1fr)); gap:18px; margin:12px 0 18px; }
15
+ .signal-grid span { display:block; color:var(--muted); font-size:12px; }
16
+ .signal-grid strong { display:block; font:500 23px/1.8 "Bahnschrift","Segoe UI",sans-serif; font-variant-numeric:tabular-nums; }
17
+ .history-panel { border-top:3px solid var(--blue); }
18
+ .quality-panel .signal-grid { grid-template-columns:repeat(3,minmax(0,1fr)); }
19
+ .chart:empty { display:none; }
20
+ .rest-toolbar { display:flex; align-items:center; justify-content:space-between; gap:15px; margin:30px 0 18px; }
21
+ .rest-toolbar p { font-size:12px; }
22
+ .chart-legend { display:flex; flex-wrap:wrap; gap:20px; font:12px Consolas,monospace; margin-bottom:10px; }
23
+ .chart-legend span::before { content:""; display:inline-block; width:8px; height:8px; border-radius:2px; margin-right:6px; }
24
+ .search-dot::before,.chart .endpoint-search { background:#2563a8; fill:#2563a8; }
25
+ .related-dot::before,.chart .endpoint-related { background:#137c80; fill:#137c80; }
26
+ .artists-dot::before,.chart .endpoint-artists { background:#7161a8; fill:#7161a8; }
27
+ .health-dot::before,.chart .endpoint-health { background:#9aa9b9; fill:#9aa9b9; }
28
+ .rank-list>div { display:grid; grid-template-columns:minmax(0,1fr) auto; gap:4px 12px; margin:12px 0; font-size:12px; }
29
+ .rank-list span { overflow-wrap:anywhere; }
30
+ .rank-list strong { font-variant-numeric:tabular-nums; font-weight:500; }
31
+ .rank-list meter { grid-column:1/-1; width:100%; height:9px; border:0; }
32
+ .rank-list meter::-webkit-meter-bar { background:var(--page); border:0; }
33
+ .rank-list meter::-webkit-meter-optimum-value { background:var(--blue); }
34
+ @media(max-width:700px) { .signal-grid,.quality-panel .signal-grid { grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; } .rest-toolbar { align-items:flex-start; } .rest-toolbar .range-label { font-size:0; } .rest-toolbar p { max-width:200px; } .rest-toolbar select { font-size:12px; } }
35
  * {
36
  box-sizing:border-box;
37
  }
webui/static/admin/admin.js CHANGED
@@ -18,6 +18,7 @@
18
  $("dashboard").hidden = true; $("account").hidden = true; $("login").hidden = false;
19
  for (const id of ["ui-count","rest-count","mcp-count","ui-detail","rest-detail","mcp-detail","ui-avg","ui-p95","window-count","window-errors","window-status","window-range","latency-note","since","updated","username"]) $(id).textContent = "—";
20
  for (const id of ["endpoints","latency-chart","trend-chart"]) $(id).replaceChildren();
 
21
  }
22
  async function session() {
23
  const response = await request("/admin/api/session", {cache:"no-store", credentials:"same-origin"});
@@ -51,8 +52,9 @@
51
  const top = 18, plot = height - bottom - top;
52
  const max = Math.max(...items.map((item) => item.count || 0), 1);
53
  const step = (width - left - 10) / items.length;
54
- const svg = svgNode("svg", {viewBox:`0 0 ${width} ${height}`, role:"img", "aria-label":trend ? "REST 每小时请求趋势" : "UI 搜索延迟分布"});
55
- svg.append(svgNode("title", {}, trend ? "每小时请求数,空白时段没有可用记录" : "每个延迟区间的样本数"));
 
56
  [0, .5, 1].forEach((ratio) => {
57
  const y = top + plot * (1 - ratio);
58
  svg.append(svgNode("line", {x1:left,y1:y,x2:width-10,y2:y,class:"gridline"}));
@@ -61,8 +63,17 @@
61
  items.forEach((item,i) => {
62
  const x = left + i * step, barHeight = plot * (item.count || 0) / max;
63
  if (item.count != null) {
64
- const rect = svgNode("rect", {x:x+1,y:top+plot-barHeight,width:Math.max(1,step-2),height:barHeight,rx:1,class:trend?"trend-bar":"latency-bar"});
65
- rect.append(svgNode("title", {}, `${item.label}: ${number(item.count)} 次`)); svg.append(rect);
 
 
 
 
 
 
 
 
 
66
  } else svg.append(svgNode("line", {x1:x+step/2,y1:top+plot-3,x2:x+step/2,y2:top+plot,class:"missing"}));
67
  const labelCount = width < 450 ? 3 : trend ? 5 : 6;
68
  if (i % Math.max(1,Math.ceil(items.length / labelCount)) === 0) svg.append(svgNode("text", {x:x+2,y:height-8}, item.short || item.label));
@@ -71,12 +82,53 @@
71
  }
72
  function trend() {
73
  if (!snapshot) return;
74
- const hours = Number($("range").value);
75
- const cutoff = new Date(snapshot.generated_at).getTime() - (hours - 1) * 3600000;
76
- const floor = Math.floor(cutoff / 3600000) * 3600000;
77
- const items = snapshot.rest.hours.filter((item) => new Date(`${item.hour}:00+08:00`).getTime() >= floor).map((item) => ({count:item.count,label:item.hour.replace("T"," "),short:item.hour.slice(5,10) + " " + item.hour.slice(11,13)+"时"}));
78
  chart("trend-chart", items, true);
79
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  function render(data) {
81
  snapshot = data;
82
  const c = data.counters, sum = (names) => names.reduce((total,key) => total + (c[key] || 0),0);
@@ -90,20 +142,11 @@
90
  $("mcp-detail").textContent = `标签搜索 ${number(c.mcp_search_tags)} · 相关标签 ${number(c.mcp_get_related_tags)}`;
91
  $("ui-avg").textContent = duration(data.ui_latency.average_ms);
92
  $("ui-p95").textContent = p95(data.ui_latency);
93
- $("latency-note").textContent = `${number(data.ui_latency.count)} 个延迟样本。分桶分别计数,P95 为区间估算;超过末档时显示 > 120 s。`;
94
  chart("latency-chart", data.ui_latency.buckets);
95
- const rest = data.rest;
96
- $("window-count").textContent = number(rest.count);
97
- $("window-errors").textContent = rest.error_percent == null ? "—" : `${rest.error_percent}%`;
98
- $("window-status").textContent = ["2xx","3xx","4xx","5xx"].map((key) => `${key} ${number(rest.statuses[key])}`).join(" / ");
99
- $("window-range").textContent = rest.first_hour ? `记录覆盖 ${rest.first_hour.replace("T"," ")} — ${rest.last_hour.replace("T"," ")}(北京时间)` : "目前尚无 REST 观测记录。";
100
- const tbody = $("endpoints"); tbody.replaceChildren();
101
- rest.endpoints.forEach((row) => {
102
- const tr = document.createElement("tr");
103
- [`/api/${row.endpoint}${row.endpoint === "health" ? "(健康检查)" : ""}`,number(row.count),duration(row.average_ms),p95(row),number(row.errors)].forEach((value) => {const td=document.createElement("td"); td.textContent=value; tr.append(td);}); tbody.append(tr);
104
- });
105
- if (!rest.endpoints.length) {const tr=document.createElement("tr"),td=document.createElement("td"); td.colSpan=5;td.textContent="暂无接口观测数据";tr.append(td);tbody.append(tr);}
106
- trend();
107
  }
108
  async function refresh() {
109
  if (loading || document.hidden) return;
@@ -119,7 +162,7 @@
119
  finally {loading=false;$("refresh").disabled=false;}
120
  }
121
  $("refresh").addEventListener("click", refresh);
122
- $("range").addEventListener("change", trend);
123
  $("logout").addEventListener("click", async () => {
124
  $("logout").disabled=true;
125
  try {
@@ -146,6 +189,6 @@
146
  document.addEventListener("visibilitychange", () => {if(!document.hidden) refresh();});
147
  setInterval(refresh, 30000);
148
  let resizeTimer;
149
- window.addEventListener("resize", () => {clearTimeout(resizeTimer);resizeTimer=setTimeout(() => {if(snapshot && !keysPage) {chart("latency-chart",snapshot.ui_latency.buckets);trend();}},100);});
150
  refresh();
151
  })();
 
18
  $("dashboard").hidden = true; $("account").hidden = true; $("login").hidden = false;
19
  for (const id of ["ui-count","rest-count","mcp-count","ui-detail","rest-detail","mcp-detail","ui-avg","ui-p95","window-count","window-errors","window-status","window-range","latency-note","since","updated","username"]) $(id).textContent = "—";
20
  for (const id of ["endpoints","latency-chart","trend-chart"]) $(id).replaceChildren();
21
+ for (const id of ["history-state","history-insight","history-stats","history-chart","history-note","quality-stats","rest-insight","window-slow","sources","clients","pressure-stats"]) $(id).replaceChildren();
22
  }
23
  async function session() {
24
  const response = await request("/admin/api/session", {cache:"no-store", credentials:"same-origin"});
 
52
  const top = 18, plot = height - bottom - top;
53
  const max = Math.max(...items.map((item) => item.count || 0), 1);
54
  const step = (width - left - 10) / items.length;
55
+ const chartTitle = id === "history-chart" ? "UI 区间平均延迟(毫秒)" : trend ? "REST 每小时请求趋势" : "UI 搜索延迟分布";
56
+ const svg = svgNode("svg", {viewBox:`0 0 ${width} ${height}`, role:"img", "aria-label":chartTitle});
57
+ svg.append(svgNode("title", {}, chartTitle));
58
  [0, .5, 1].forEach((ratio) => {
59
  const y = top + plot * (1 - ratio);
60
  svg.append(svgNode("line", {x1:left,y1:y,x2:width-10,y2:y,class:"gridline"}));
 
63
  items.forEach((item,i) => {
64
  const x = left + i * step, barHeight = plot * (item.count || 0) / max;
65
  if (item.count != null) {
66
+ if (trend && item.endpoints) {
67
+ let used = 0;
68
+ for (const endpoint of ["search","related","artists","health"]) {
69
+ const count = item.endpoints[endpoint] || 0, h = plot * count / max;
70
+ const rect = svgNode("rect", {x:x+1,y:top+plot-used-h,width:Math.max(.5,step-1),height:h,class:`endpoint-${endpoint}`});
71
+ rect.append(svgNode("title", {}, `${item.label} · ${endpoint}: ${number(count)} 次`));svg.append(rect);used+=h;
72
+ }
73
+ } else {
74
+ const rect = svgNode("rect", {x:x+1,y:top+plot-barHeight,width:Math.max(.5,step-2),height:barHeight,rx:1,class:trend?"trend-bar":"latency-bar"});
75
+ rect.append(svgNode("title", {}, item.tooltip || `${item.label}: ${number(item.count)} 次`)); svg.append(rect);
76
+ }
77
  } else svg.append(svgNode("line", {x1:x+step/2,y1:top+plot-3,x2:x+step/2,y2:top+plot,class:"missing"}));
78
  const labelCount = width < 450 ? 3 : trend ? 5 : 6;
79
  if (i % Math.max(1,Math.ceil(items.length / labelCount)) === 0) svg.append(svgNode("text", {x:x+2,y:height-8}, item.short || item.label));
 
82
  }
83
  function trend() {
84
  if (!snapshot) return;
85
+ const rest = snapshot.rest_windows[$("range").value];
86
+ const items = rest.hours.map((item) => ({count:item.count,endpoints:item.endpoints,label:item.hour.replace("T"," "),short:item.hour.slice(5,10) + " " + item.hour.slice(11,13)+"时"}));
 
 
87
  chart("trend-chart", items, true);
88
  }
89
+ const percent = (value) => value == null ? "—" : `${value}%`;
90
+ function signals(id, items) {
91
+ const root = $(id);root.replaceChildren();
92
+ items.forEach(([label,value]) => {const box=document.createElement("div"),caption=document.createElement("span"),amount=document.createElement("strong");caption.textContent=label;amount.textContent=value;box.append(caption,amount);root.append(box);});
93
+ }
94
+ function ranks(id, items, total) {
95
+ const root=$(id);root.replaceChildren();
96
+ if(!items.length){root.textContent="暂无观测记录";return;}
97
+ items.forEach((item) => {const row=document.createElement("div"),label=document.createElement("span"),value=document.createElement("strong"),meter=document.createElement("meter");label.textContent=item.label;value.textContent=`${number(item.count)} · ${total ? (100*item.count/total).toFixed(1) : 0}%`;meter.min=0;meter.max=total || 1;meter.value=item.count;meter.setAttribute("aria-label",`${item.label} 请求占比`);row.append(label,value,meter);root.append(row);});
98
+ }
99
+ function renderHistory() {
100
+ const h=snapshot.history;
101
+ $("history-state").textContent=h.stale?"历史已过期":`${h.sample_count} 个快照`;
102
+ if(!h.latest){
103
+ $("history-stats").replaceChildren();
104
+ $("history-chart").replaceChildren();
105
+ $("history-insight").textContent=h.status==="not_configured"?"尚未配置历史快照。累计统计及 REST 实时观测仍可使用。":"历史快照暂不可用,或不足两个有效快照。";
106
+ $("history-note").textContent="如需 UI / MCP 近期变化,请为部署配置 ADMIN_TELEMETRY_HISTORY_PATH,指向 telemetry_history.json;更新文件后下次刷新读取。";
107
+ return;
108
+ }
109
+ const latest=h.latest;
110
+ $("history-insight").textContent=`最近区间 UI 平均延迟 ${duration(latest.ui_average_ms)},累计平均 ${duration(snapshot.ui_latency.average_ms)}。${h.latency_ratio ? `相较上一采样区间为 ${h.latency_ratio.toFixed(2)} 倍。` : ""}${h.stale ? "历史文件已超过 36 小时未更新,不能代表当前表现。" : ""}`;
111
+ signals("history-stats",[["区间 UI 搜索",number(latest.ui)],["区间 REST 调用",number(latest.rest)],["区间 MCP 调用",number(latest.mcp)],["区间冷启动失败",number(latest.cold_failures)]]);
112
+ chart("history-chart",h.intervals.map((item)=>({count:item.ui_average_ms,label:date(item.end),short:date(item.end),tooltip:`${date(item.start)} → ${date(item.end)}(${item.hours} 小时)UI 平均延迟 ${duration(item.ui_average_ms)}`})),true);
113
+ $("history-note").textContent=`图表纵轴:UI 区间平均延迟(毫秒)。最近区间 ${date(latest.start)} — ${date(latest.end)},持续 ${latest.hours} 小时;区间不等同自然日,缺少分桶的历史不能计算区间 P95。${h.skipped_intervals ? `已跳过 ${h.skipped_intervals} 个计数回退或不可比区间。` : ""}`;
114
+ }
115
+ function renderRest() {
116
+ if(!snapshot)return;
117
+ const rest=snapshot.rest_windows[$("range").value], label=$("range").selectedOptions[0].textContent;
118
+ document.querySelectorAll(".window-label").forEach((node)=>{node.textContent=label;});
119
+ $("window-count").textContent=number(rest.count);
120
+ $("window-errors").textContent=`${number(rest.statuses["4xx"])} / ${number(rest.statuses["5xx"])}`;
121
+ $("window-slow").textContent=`${number(rest.slow_count)} · ${percent(rest.slow_percent)}`;
122
+ $("window-status").textContent=["2xx","3xx","4xx","5xx"].map((key)=>`${key} ${number(rest.statuses[key])}`).join(" / ");
123
+ $("window-range").textContent=rest.first_hour?`记录 ${rest.first_hour.replace("T"," ")} — ${rest.last_hour.replace("T"," ")} · ${rest.observed_hours} / ${rest.requested_hours} 个小时有记录` : "当前窗口没有 REST 观测记录。";
124
+ $("rest-insight").textContent=rest.count?`${label}:${percent(rest.slow_percent)} 的已记录请求耗时超过 5 秒;HTTP 在途峰值 ${number(rest.peak_in_flight)}。4xx ${number(rest.statuses["4xx"])} 次与 5xx ${number(rest.statuses["5xx"])} 次分别统计,不将全部错误视为服务器故障。`:"当前窗口没有记录;时间空白不等于零流量。";
125
+ const tbody=$("endpoints");tbody.replaceChildren();
126
+ rest.endpoints.forEach((row)=>{const tr=document.createElement("tr");[`/api/${row.endpoint}${row.endpoint==="health"?"(健康检查)":""}`,number(row.count),duration(row.average_ms),p95(row),percent(row.slow_percent),number(row.client_errors),number(row.server_errors)].forEach((value)=>{const td=document.createElement("td");td.textContent=value;tr.append(td);});tbody.append(tr);});
127
+ if(!rest.endpoints.length){const tr=document.createElement("tr"),td=document.createElement("td");td.colSpan=7;td.textContent="暂无接口观测数据";tr.append(td);tbody.append(tr);}
128
+ ranks("sources",rest.sources,rest.count);ranks("clients",rest.clients,rest.count);
129
+ signals("pressure-stats",[["HTTP 在途峰值",rest.peak_in_flight == null?"—":number(rest.peak_in_flight)],["分组分钟请求峰值",rest.peak_per_minute == null?"—":number(rest.peak_per_minute)],["有记录的小时",`${rest.observed_hours} / ${rest.requested_hours}`]]);
130
+ trend();
131
+ }
132
  function render(data) {
133
  snapshot = data;
134
  const c = data.counters, sum = (names) => names.reduce((total,key) => total + (c[key] || 0),0);
 
142
  $("mcp-detail").textContent = `标签搜索 ${number(c.mcp_search_tags)} · 相关标签 ${number(c.mcp_get_related_tags)}`;
143
  $("ui-avg").textContent = duration(data.ui_latency.average_ms);
144
  $("ui-p95").textContent = p95(data.ui_latency);
145
+ $("latency-note").textContent = `${number(data.ui_latency.count)} 个延迟样本。${data.ui_latency.distribution_available ? "分桶分别计数,P95 为区间估算;超过末档时显示 > 120 s。" : "当前数据未提供完整分桶,不能还原分布或估算 P95。"}`;
146
  chart("latency-chart", data.ui_latency.buckets);
147
+ const q=data.quality;
148
+ signals("quality-stats",[["发生选词的搜索会话",percent(q.selection_percent)],["复制操作 / 搜索",percent(q.copy_events_per_search)],["零结果率",percent(q.zero_percent)],["60 秒内重复搜索",percent(q.repeat_percent)],["冷启动成功 / 尝试",`${number(q.cold_successes)} / ${number(q.cold_attempts)}`],["冷启动失败",number(q.cold_failures)]]);
149
+ renderHistory();renderRest();
 
 
 
 
 
 
 
 
 
150
  }
151
  async function refresh() {
152
  if (loading || document.hidden) return;
 
162
  finally {loading=false;$("refresh").disabled=false;}
163
  }
164
  $("refresh").addEventListener("click", refresh);
165
+ $("range").addEventListener("change", renderRest);
166
  $("logout").addEventListener("click", async () => {
167
  $("logout").disabled=true;
168
  try {
 
189
  document.addEventListener("visibilitychange", () => {if(!document.hidden) refresh();});
190
  setInterval(refresh, 30000);
191
  let resizeTimer;
192
+ window.addEventListener("resize", () => {clearTimeout(resizeTimer);resizeTimer=setTimeout(() => {if(snapshot && !keysPage) {chart("latency-chart",snapshot.ui_latency.buckets);renderHistory();trend();}},100);});
193
  refresh();
194
  })();
webui/static/admin/index.html CHANGED
@@ -33,6 +33,13 @@
33
  <section id="overview">
34
  <div class="heading"><div><span class="eyebrow">服务运行</span><h1>运行概览</h1><p>按访问渠道查看用量与响应表现。</p></div><button id="refresh">刷新数据</button></div>
35
  <div class="meta"><span id="updated">读取数据中…</span><span>每 30 秒自动刷新 · 北京时间</span></div>
 
 
 
 
 
 
 
36
  <section class="panel"><div class="panel-heading"><h2>调用渠道</h2><span id="since" class="muted">累计统计</span></div>
37
  <div class="channels">
38
  <article class="channel"><span class="channel-tag">UI</span><h3>网页搜索</h3><strong class="big-number" id="ui-count">—</strong><span class="muted">次搜索</span><p id="ui-detail">—</p></article>
@@ -40,23 +47,28 @@
40
  <article class="channel"><span class="channel-tag">MCP</span><h3>工具调用</h3><strong class="big-number" id="mcp-count">—</strong><span class="muted">次工具调用</span><p id="mcp-detail">—</p></article>
41
  </div>
42
  </section>
 
 
 
43
  <div class="metrics-grid">
44
  <section class="panel"><div class="panel-heading"><h2>网页搜索延迟</h2><span class="muted">累计样本</span></div>
45
  <div class="latency-numbers"><div><span class="muted">平均延迟</span><strong id="ui-avg">—</strong></div><div><span class="muted">P95 所在区间上界</span><strong id="ui-p95">—</strong></div></div>
46
  <div id="latency-chart" class="chart" aria-label="网页搜索延迟分布"></div><p class="footnote" id="latency-note"></p>
47
  </section>
48
- <section class="panel"><div class="panel-heading"><h2>REST 观测窗口</h2><span class="badge">近 14 天</span></div>
49
- <dl class="window-stats"><div><dt>已记录请求</dt><dd id="window-count">—</dd></div><div><dt>4xx / 5xx 占比</dt><dd id="window-errors">—</dd></div><div><dt>状态码分布</dt><dd id="window-status">—</dd></div></dl>
50
  <p class="footnote" id="window-range"></p><p class="footnote">包含健康检查。按现有归因规则聚合,少量未达阈值的来源暂不展示;不等于全站累计调用量。</p>
51
  </section>
52
  </div>
53
- <section class="panel"><div class="panel-heading"><div><h2>REST 请求趋势</h2><p class="muted">每小时已记录请求数</p></div><label class="range-label">时间范围 <select id="range"><option value="24">近 24 小时</option><option value="168" selected>近 7 天</option><option value="336">近 14 天</option></select></label></div>
54
  <div id="trend-chart" class="chart trend"></div><p class="footnote">空白时段表示没有可用记录,不自动视为零请求。首尾小时可能不完整。</p>
55
  </section>
56
- <section class="panel"><div class="panel-heading"><h2>REST 接口表现</h2><span class="muted">近 14 天 · 完整观测窗口</span></div>
57
- <div class="table-scroll"><table><thead><tr><th scope="col">接口</th><th scope="col">请求数</th><th scope="col">平均延迟</th><th scope="col">P95 区间上界</th><th scope="col">4xx / 5xx</th></tr></thead><tbody id="endpoints"></tbody></table></div>
58
  <p class="footnote">延迟是现有观测链路的耗时,P95 由延迟分桶估算。MCP 尚无对应延迟数据,因此不展示推测值。</p>
59
  </section>
 
 
60
  </section>
61
  <section id="keys" hidden>
62
  <div class="heading"><div><span class="eyebrow">接入管理</span><h1>API Key</h1><p>申请、授权与操作记录的预留入口。</p></div><span class="badge">尚未启用</span></div>
@@ -64,7 +76,7 @@
64
  <div class="tabs" role="tablist" aria-label="API Key 管理"><button role="tab" aria-selected="true" aria-controls="key-panel" id="tab-applications" data-key-tab="applications">待审核申请</button><button role="tab" aria-selected="false" aria-controls="key-panel" id="tab-grants" data-key-tab="grants" tabindex="-1">授权与 Key</button><button role="tab" aria-selected="false" aria-controls="key-panel" id="tab-audit" data-key-tab="audit" tabindex="-1">操作记录</button></div>
65
  <section class="panel" id="key-panel" role="tabpanel" aria-labelledby="tab-applications"><div class="empty"><span class="empty-symbol" aria-hidden="true">⌘</span><h2 id="key-title">申请审核尚未启用</h2><p id="key-copy">后续在这里查看账号、服务名称、用途和预计用量,并批准或拒绝申请。</p><p class="footnote">尚未连接授权数据库,当前不生成或保存 API Key。</p></div></section>
66
  </section>
67
- <footer>运行数据来自当前服务的内存快照,OSS 按原有机制定期同步。<span>普通用户继续匿名使用标签搜索。</span></footer>
68
  </div>
69
  </main>
70
  </body>
 
33
  <section id="overview">
34
  <div class="heading"><div><span class="eyebrow">服务运行</span><h1>运行概览</h1><p>按访问渠道查看用量与响应表现。</p></div><button id="refresh">刷新数据</button></div>
35
  <div class="meta"><span id="updated">读取数据中…</span><span>每 30 秒自动刷新 · 北京时间</span></div>
36
+ <section class="panel history-panel">
37
+ <div class="panel-heading"><div><h2>近期变化</h2><p class="muted">相邻累计快照的增量,避免累计平均值掩盖近期变化</p></div><span id="history-state" class="badge">历史快照</span></div>
38
+ <div id="history-insight" class="notice neutral"></div>
39
+ <div id="history-stats" class="signal-grid"></div>
40
+ <div id="history-chart" class="chart trend"></div>
41
+ <p id="history-note" class="footnote"></p>
42
+ </section>
43
  <section class="panel"><div class="panel-heading"><h2>调用渠道</h2><span id="since" class="muted">累计统计</span></div>
44
  <div class="channels">
45
  <article class="channel"><span class="channel-tag">UI</span><h3>网页搜索</h3><strong class="big-number" id="ui-count">—</strong><span class="muted">次搜索</span><p id="ui-detail">—</p></article>
 
47
  <article class="channel"><span class="channel-tag">MCP</span><h3>工具调用</h3><strong class="big-number" id="mcp-count">—</strong><span class="muted">次工具调用</span><p id="mcp-detail">—</p></article>
48
  </div>
49
  </section>
50
+ <section class="panel quality-panel"><div class="panel-heading"><h2>使用质量与启动记录</h2><span class="muted">累计口径</span></div><div id="quality-stats" class="signal-grid"></div><p class="footnote">复制操作 / 搜索是事件比值,不是独立用户转化率。冷启动统计包含历史记录,不代表当前服务不可用。</p></section>
51
+ <div class="rest-toolbar"><div><h2>REST 运行窗口</h2><p class="muted">筛选同步应用于请求量、延迟、趋势、来源和峰值</p></div><label class="range-label">时间范围 <select id="range"><option value="24" selected>近 24 小时</option><option value="168">近 7 天</option><option value="336">近 14 天</option></select></label></div>
52
+ <p id="rest-insight" class="notice neutral"></p>
53
  <div class="metrics-grid">
54
  <section class="panel"><div class="panel-heading"><h2>网页搜索延迟</h2><span class="muted">累计样本</span></div>
55
  <div class="latency-numbers"><div><span class="muted">平均延迟</span><strong id="ui-avg">—</strong></div><div><span class="muted">P95 所在区间上界</span><strong id="ui-p95">—</strong></div></div>
56
  <div id="latency-chart" class="chart" aria-label="网页搜索延迟分布"></div><p class="footnote" id="latency-note"></p>
57
  </section>
58
+ <section class="panel"><div class="panel-heading"><h2>REST 观测窗口</h2><span class="badge window-label">近 24 小时</span></div>
59
+ <dl class="window-stats"><div><dt>已记录请求</dt><dd id="window-count">—</dd></div><div><dt>4xx 客户端错误 / 5xx 服务错误</dt><dd id="window-errors">—</dd></div><div><dt>耗时 &gt; 5 秒</dt><dd id="window-slow">—</dd></div><div><dt>状态码分布</dt><dd id="window-status">—</dd></div></dl>
60
  <p class="footnote" id="window-range"></p><p class="footnote">包含健康检查。按现有归因规则聚合,少量未达阈值的来源暂不展示;不等于全站累计调用量。</p>
61
  </section>
62
  </div>
63
+ <section class="panel"><div class="panel-heading"><div><h2>REST 请求趋势</h2><p class="muted">每小时已记录请求数 · 按接口区分</p></div><span class="window-label badge">近 24 小时</span></div><div class="chart-legend"><span class="search-dot">search</span><span class="related-dot">related</span><span class="artists-dot">artists</span><span class="health-dot">health</span></div>
64
  <div id="trend-chart" class="chart trend"></div><p class="footnote">空白时段表示没有可用记录,不自动视为零请求。首尾小时可能不完整。</p>
65
  </section>
66
+ <section class="panel"><div class="panel-heading"><h2>REST 接口表现</h2><span class="muted window-label">近 24 小时</span></div>
67
+ <div class="table-scroll"><table><thead><tr><th scope="col">接口</th><th scope="col">请求数</th><th scope="col">平均延迟</th><th scope="col">P95 区间上界</th><th scope="col">&gt; 5 秒</th><th scope="col">4xx</th><th scope="col">5xx</th></tr></thead><tbody id="endpoints"></tbody></table></div>
68
  <p class="footnote">延迟是现有观测链路的耗时,P95 由延迟分桶估算。MCP 尚无对应延迟数据,因此不展示推测值。</p>
69
  </section>
70
+ <div class="metrics-grid"><section class="panel"><div class="panel-heading"><h2>来源概览</h2><span class="muted window-label"></span></div><div id="sources" class="rank-list"></div><p class="footnote">来源为自声明或粗粒度归因,不是已验证用户。“未声明”不等于无 Key,也不能区分具体调用者。</p></section><section class="panel"><div class="panel-heading"><h2>客户端分布</h2><span class="muted window-label"></span></div><div id="clients" class="rank-list"></div><p class="footnote">客户端类别不是独立用户数,同一类别可能对应多个服务。</p></section></div>
71
+ <section class="panel"><div class="panel-heading"><h2>观测压力</h2><span class="muted window-label"></span></div><div id="pressure-stats" class="signal-grid"></div><p class="footnote">HTTP 在途峰值包含等待,不是同时运行的模型任务数。分钟峰值取来源 / 客户端 / 接口分组的最大值,不是全站 RPM;各组峰值不能相加。</p></section>
72
  </section>
73
  <section id="keys" hidden>
74
  <div class="heading"><div><span class="eyebrow">接入管理</span><h1>API Key</h1><p>申请、授权与操作记录的预留入口。</p></div><span class="badge">尚未启用</span></div>
 
76
  <div class="tabs" role="tablist" aria-label="API Key 管理"><button role="tab" aria-selected="true" aria-controls="key-panel" id="tab-applications" data-key-tab="applications">待审核申请</button><button role="tab" aria-selected="false" aria-controls="key-panel" id="tab-grants" data-key-tab="grants" tabindex="-1">授权与 Key</button><button role="tab" aria-selected="false" aria-controls="key-panel" id="tab-audit" data-key-tab="audit" tabindex="-1">操作记录</button></div>
77
  <section class="panel" id="key-panel" role="tabpanel" aria-labelledby="tab-applications"><div class="empty"><span class="empty-symbol" aria-hidden="true">⌘</span><h2 id="key-title">申请审核尚未启用</h2><p id="key-copy">后续在这里查看账号、服务名称、用途和预计用量,并批准或拒绝申请。</p><p class="footnote">尚未连接授权数据库,当前不生成或保存 API Key。</p></div></section>
78
  </section>
79
+ <footer>累计与 REST 数据来自服务内存快照;近期变化读取配置的历史文件,按各自时间范围展示。<span>普通用户继续匿名使用标签搜索。</span></footer>
80
  </div>
81
  </main>
82
  </body>