Peach: Local-first video metadata scraper and media manager.
feat: complete FastAPI media candidate
Peach local maintenance429a222cc364
diff --git a/Resources/Tools/README.md b/Resources/Tools/README.mdindex 8a0c359f6..7b607c85e 100644--- a/Resources/Tools/README.md+++ b/Resources/Tools/README.md@@ -6,8 +6,11 @@## 当前架构(2026-08-14)- `ledger.db`:资产、行为和知识的真相源。-- Peach Web:当前生产仍由 `rm-web.py` 提供;新 `rm-web-fastapi.py` 已具备 JSON API 兼容入口。+- Peach Web:当前生产仍由 `rm-web.py` 提供;`rm-web-fastapi.py` 已能完整承载首页、JSON API、+ 标准 Range/HEAD 媒体流、缩略图、poster/avatar/logo,待维护窗口切换。- Media Engine:`peach/media.py` 定义 backend 边界;Stash 先是 adapter,之后逐项 native 化。+- 媒体运行时:`peach/ffmpeg.py` 按环境变量、Peach 托管目录、PATH、临时 Stash fallback+ 的顺序定位二进制;新代码不再散落硬编码路径。- 数据库迁移:`rm-migrate.py status` 默认只读,`upgrade` 显式执行且先 SQLite backup。- AI:`peach/providers.py` 分 Inference/Agent;第一阶段不发送真实模型请求、不保存 OAuth token。- 部署:继续模块化单体;不引入微服务、PostgreSQL、React 重写或完整多账号系统。@@ -27,10 +30,13 @@ cd R:\Resources\Tools& .\.venv\Scripts\python.exe -m unittest discover -s .\tests -p 'test_*.py' -v& .\.venv\Scripts\python.exe .\rm-migrate.py status-# 实验性 FastAPI JSON API;默认 127.0.0.1:8900,不替换 80 端口旧服务+# FastAPI 完整候选入口;默认 127.0.0.1:8900,不替换 80 端口旧服务& .\.venv\Scripts\python.exe .\rm-web-fastapi.py --port 8900```+切换生产前至少验证:23 项隔离测试、真实库副本 migration、桌面、390×844、普通/开放尾端/+suffix/越界 Range、HEAD、poster/avatar 和回退启动。当前 80 端口尚未切换。+## 目录约定```diff --git "a/Resources/Tools/Stash\344\270\223\351\241\271\345\256\241\350\256\241-2026-08-14.md" "b/Resources/Tools/Stash\344\270\223\351\241\271\345\256\241\350\256\241-2026-08-14.md"index 63b62ce39..49f4f0566 100644--- "a/Resources/Tools/Stash\344\270\223\351\241\271\345\256\241\350\256\241-2026-08-14.md"+++ "b/Resources/Tools/Stash\344\270\223\351\241\271\345\256\241\350\256\241-2026-08-14.md"@@ -40,6 +40,14 @@ Peach 最终可以完全去 Stash,但现在不能直接卸载。Web 主链已5. 同批资产影子对比并关闭 adapter;保留备份与回退期。6. 依赖归零后才卸载 Stash 和 generated 数据。+## 2026-08-14 第二阶段进展++- 新增集中 `StashClient`,FastAPI/Media Engine 新代码不再各自实现 GraphQL transport。+- 新增独立 `FFmpegResolver`:环境变量/Peach 托管目录/PATH 优先,Stash 私有目录只作可关闭 fallback。+- FastAPI 已用 Starlette `FileResponse` 替换候选入口的手写 Range,并验证普通、指定区间、suffix、+ 越界 416、HEAD、ETag、Last-Modified。+- 旧 19 个脚本直连和 11 个硬编码依赖尚未归零;不能因此宣称已经去 Stash。+## 验收门槛关闭 Stash 前必须完成:2,551 Scene 全关联;842 Performer、126 Tag、140 Studio 与全部关系、别名、hash 有 external ID/provenance;24,980 视频探测覆盖不回退;10,714 个账本 snapshot 仍可访问;常用和异常 Range、seek、两路并发及不兼容编码转码通过;关键别名/Studio/组合标签/云资产搜索一致;19/11 个依赖计数归零;关闭和回退均演练。diff --git a/Resources/Tools/docs/adr/0001-fastapi-modular-monolith.md b/Resources/Tools/docs/adr/0001-fastapi-modular-monolith.mdindex 7e712c276..2f5e8f387 100644--- a/Resources/Tools/docs/adr/0001-fastapi-modular-monolith.md+++ b/Resources/Tools/docs/adr/0001-fastapi-modular-monolith.md@@ -10,7 +10,8 @@ Peach 已有可运行的 `rm-web.py`,数据查询和写入函数大体独立## 决策- 后端渐进迁移到 FastAPI;前端与后端在代码职责上拆分,但继续单进程、单体部署。-- 第一阶段只提供 `/healthz` 与现有 `/api/*` JSON 兼容入口,旧 `rm-web.py` 继续作为生产入口。+- 第一阶段先提供 `/healthz` 与现有 `/api/*` JSON 兼容入口;第二阶段已补齐首页、标准媒体响应、+ 缩略图和 preview/logo 路由。旧 `rm-web.py` 在生产切换前继续作为回退入口。- 不引入微服务、PostgreSQL、React 重写或完整账号系统。- Uvicorn 只允许单 worker,直到进程内缓存、写锁和后台任务状态移出全局变量。- schema 升级必须由显式迁移器完成;应用导入和健康检查不得自动改真实数据库。@@ -23,4 +24,5 @@ Peach 已有可运行的 `rm-web.py`,数据查询和写入函数大体独立## 后果-迁移期会同时存在 legacy adapter 与 FastAPI 入口,但每一步都可独立验证和回退。待 JSON、媒体 Range、页面与 mDNS 全部通过契约测试及双视口验收后,才切换生产入口。+迁移期会同时存在 legacy JSON adapter 与 FastAPI 入口,但每一步都可独立验证和回退。JSON、+媒体 Range、页面和双视口已通过;生产切换前仍需真实迁移备份、端口切换与 mDNS/回退演练。diff --git a/Resources/Tools/peach/api.py b/Resources/Tools/peach/api.pyindex e801cfd07..2dd811716 100644--- a/Resources/Tools/peach/api.py+++ b/Resources/Tools/peach/api.py@@ -2,10 +2,14 @@ import hmacfrom typing import Anyfrom fastapi import Body, FastAPI, Request-from fastapi.responses import JSONResponse+from fastapi.responses import FileResponse, JSONResponse, PlainTextResponse, Response-from .config import PeachSettings+from .config import TOOLS_DIR, PeachSettings+from .ffmpeg import FFmpegResolverfrom .legacy_web import load_legacy+from .media import FilesystemMediaService, MediaNotFound, MediaUnavailable+from .previews import PreviewService, PreviewUnavailable+from .repository import LedgerRepositorydef _first_query_values(request: Request) -> dict[str, str]:@@ -27,6 +31,15 @@ def _authorized(request: Request, token: str, args: dict[str, str]) -> bool:def create_app(settings: PeachSettings | None = None) -> FastAPI:settings = settings or PeachSettings()legacy = load_legacy(settings.legacy_module_path, settings.db_path, settings.token)+ repository = LedgerRepository(settings.db_path)+ resolver = FFmpegResolver(TOOLS_DIR, settings.allow_legacy_stash_ffmpeg)+ media_service = FilesystemMediaService(+ repository, settings.allowed_media_roots, settings.snapshot_root,+ )+ preview_service = PreviewService(+ repository, resolver, settings.snapshot_root, settings.poster_root,+ settings.avatar_root, settings.logo_root,+ )app = FastAPI(title="Peach API",version="0.1.0",@@ -36,17 +49,117 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:)app.state.settings = settingsapp.state.legacy = legacy+ app.state.repository = repository+ app.state.media_service = media_service+ app.state.preview_service = preview_service@app.middleware("http")async def no_store(request: Request, call_next):response = await call_next(request)- response.headers["Cache-Control"] = "no-store"+ if "cache-control" not in response.headers:+ response.headers["Cache-Control"] = "no-store"+ response.headers["X-Content-Type-Options"] = "nosniff"+ response.headers["Referrer-Policy"] = "same-origin"return response@app.get("/healthz")def healthz() -> dict[str, Any]:# 不探测/迁移数据库;健康检查必须无副作用。- return {"ok": True, "service": "peach-api", "mode": "compat"}+ ffmpeg = resolver.ffmpeg()+ return {"ok": True, "service": "peach-api", "mode": "candidate",+ "db": "available" if settings.db_path.is_file() else "missing",+ "ffmpeg": ffmpeg.source if ffmpeg else "unavailable"}++ @app.api_route("/", methods=["GET", "HEAD"])+ def index(request: Request):+ args = _first_query_values(request)+ if not _authorized(request, settings.token, args):+ return PlainTextResponse("需要 ?t=口令", status_code=401)+ if not settings.page_path.is_file():+ return PlainTextResponse("Peach page missing", status_code=500)+ response = FileResponse(settings.page_path, media_type="text/html")+ response.headers["Cache-Control"] = "no-store"+ if settings.token:+ response.set_cookie(+ "tok", settings.token, max_age=31536000, path="/", httponly=True,+ samesite="lax", secure=request.url.scheme == "https",+ )+ return response++ @app.api_route("/favicon.svg", methods=["GET", "HEAD"])+ def favicon():+ response = Response(legacy.FAVICON, media_type="image/svg+xml")+ response.headers["Cache-Control"] = "no-store"+ return response++ @app.api_route("/stream", methods=["GET", "HEAD"])+ def stream(request: Request, id: int):+ args = _first_query_values(request)+ if not _authorized(request, settings.token, args):+ return JSONResponse({"error": "unauthorized"}, status_code=401)+ try:+ path = media_service.file_for(id, thumbnail=False)+ except MediaNotFound:+ return JSONResponse({"error": "no such id"}, status_code=404)+ except MediaUnavailable:+ return JSONResponse({"error": "unavailable"}, status_code=404)+ response = FileResponse(path)+ response.headers["Cache-Control"] = "no-store"+ return response++ @app.api_route("/thumb", methods=["GET", "HEAD"])+ def thumbnail(request: Request, id: int):+ args = _first_query_values(request)+ if not _authorized(request, settings.token, args):+ return JSONResponse({"error": "unauthorized"}, status_code=401)+ try:+ path = media_service.file_for(id, thumbnail=True)+ except MediaNotFound:+ return JSONResponse({"error": "no such id"}, status_code=404)+ except MediaUnavailable:+ return JSONResponse({"error": "unavailable"}, status_code=404)+ response = FileResponse(path)+ response.headers["Cache-Control"] = "public, max-age=86400"+ return response++ @app.api_route("/poster", methods=["GET", "HEAD"])+ def poster(request: Request, id: int, c: int = 4):+ args = _first_query_values(request)+ if not _authorized(request, settings.token, args):+ return JSONResponse({"error": "unauthorized"}, status_code=401)+ try:+ path = preview_service.poster(id, c)+ except PreviewUnavailable:+ return JSONResponse({"error": "unavailable"}, status_code=404)+ response = FileResponse(path, media_type="image/jpeg")+ response.headers["Cache-Control"] = "public, max-age=86400"+ return response++ @app.api_route("/avatar", methods=["GET", "HEAD"])+ def avatar(request: Request, id: int):+ args = _first_query_values(request)+ if not _authorized(request, settings.token, args):+ return JSONResponse({"error": "unauthorized"}, status_code=401)+ try:+ path = preview_service.avatar(id)+ except PreviewUnavailable:+ return JSONResponse({"error": "unavailable"}, status_code=404)+ response = FileResponse(path, media_type="image/jpeg")+ response.headers["Cache-Control"] = "public, max-age=86400"+ return response++ @app.api_route("/logo", methods=["GET", "HEAD"])+ def logo(request: Request, studio: str = ""):+ args = _first_query_values(request)+ if not _authorized(request, settings.token, args):+ return JSONResponse({"error": "unauthorized"}, status_code=401)+ try:+ path, content_type = preview_service.logo(studio)+ except PreviewUnavailable:+ return JSONResponse({"error": "unavailable"}, status_code=404)+ response = FileResponse(path, media_type=content_type)+ response.headers["Cache-Control"] = "public, max-age=86400"+ return response@app.get("/api/{route:path}")def api_get(route: str, request: Request):diff --git a/Resources/Tools/peach/config.py b/Resources/Tools/peach/config.pyindex d5986b142..e16fd9094 100644--- a/Resources/Tools/peach/config.py+++ b/Resources/Tools/peach/config.py@@ -12,3 +12,9 @@ class PeachSettings:token: str = ""legacy_module_path: Path = TOOLS_DIR / "rm-web.py"docs_enabled: bool = False+ allowed_media_roots: tuple[Path, ...] = (Path("R:/"), Path("B:/"), Path("A:/"))+ snapshot_root: Path = Path(r"R:\Resources\Intake\snapshots")+ poster_root: Path = Path(r"R:\Resources\Intake\posters")+ avatar_root: Path = Path(r"R:\Resources\Intake\avatars")+ logo_root: Path = Path(r"R:\Resources\Intake\logos")+ allow_legacy_stash_ffmpeg: bool = Truediff --git a/Resources/Tools/peach/ffmpeg.py b/Resources/Tools/peach/ffmpeg.pynew file mode 100644index 000000000..01f4541a7--- /dev/null+++ b/Resources/Tools/peach/ffmpeg.py@@ -0,0 +1,50 @@+from __future__ import annotations++import os+import shutil+from dataclasses import dataclass+from pathlib import Path+++@dataclass(frozen=True)+class BinaryChoice:+ path: Path+ source: str+++class FFmpegResolver:+ """统一二进制定位;Stash 私有目录只是显式、可关闭的迁移 fallback。"""++ def __init__(self, tools_dir: Path, allow_legacy_stash: bool = True):+ self.tools_dir = tools_dir+ self.allow_legacy_stash = allow_legacy_stash++ def ffmpeg(self) -> BinaryChoice | None:+ return self._resolve("ffmpeg", "PEACH_FFMPEG")++ def ffprobe(self) -> BinaryChoice | None:+ return self._resolve("ffprobe", "PEACH_FFPROBE")++ def _resolve(self, executable: str, env_name: str) -> BinaryChoice | None:+ suffix = ".exe" if os.name == "nt" else ""+ configured = os.environ.get(env_name)+ if configured:+ path = Path(configured).expanduser()+ if path.is_file():+ return BinaryChoice(path.resolve(), "environment")++ managed = self.tools_dir / "bin" / f"{executable}{suffix}"+ if managed.is_file():+ return BinaryChoice(managed.resolve(), "peach-managed")++ found = shutil.which(executable)+ if found:+ return BinaryChoice(Path(found).resolve(), "path")++ if self.allow_legacy_stash:+ local = Path(os.environ.get("LOCALAPPDATA", ""))+ root = local / "Stash" / "ffmpeg-btbn"+ matches = sorted(root.glob(f"*/bin/{executable}.exe"), reverse=True)+ if matches:+ return BinaryChoice(matches[0].resolve(), "legacy-stash")+ return Nonediff --git a/Resources/Tools/peach/media.py b/Resources/Tools/peach/media.pyindex 95f4ff0d5..fadb5340a 100644--- a/Resources/Tools/peach/media.py+++ b/Resources/Tools/peach/media.py@@ -1,15 +1,23 @@-"""渐进式 Media Engine 契约。--阶段一只建立独立边界;现有生产串流仍由 rm-web.py 提供,避免半迁移。-"""+"""可替换 Media Engine 契约。"""from __future__ import annotations-import json-import urllib.request+import osfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Mapping, Protocol, Sequence+from .repository import LedgerRepository+from .stash import StashClient+++def normalized_path(path: Path | str) -> Path:+ """Windows 离线/云盘可能让 realpath 失败;启动时仍需保留安全的绝对路径边界。"""+ candidate = Path(path)+ try:+ return candidate.resolve()+ except OSError:+ return Path(os.path.abspath(os.fspath(candidate)))+@dataclass(frozen=True)class MediaCapabilities:@@ -29,6 +37,37 @@ class StreamCandidate:label: str | None = None+class MediaNotFound(RuntimeError):+ pass+++class MediaUnavailable(RuntimeError):+ pass+++class FilesystemMediaService:+ def __init__(self, repository: LedgerRepository, allowed_roots: Sequence[Path],+ snapshot_root: Path):+ self.repository = repository+ self.allowed_roots = tuple(normalized_path(root) for root in allowed_roots)+ self.snapshot_root = normalized_path(snapshot_root)++ def file_for(self, asset_id: int, thumbnail: bool = False) -> Path:+ asset = self.repository.media_asset(asset_id)+ if asset is None:+ raise MediaNotFound(asset_id)+ raw = asset.snapshot_path if thumbnail else asset.path+ if not raw:+ raise MediaUnavailable(asset_id)+ path = normalized_path(raw)+ roots = (self.snapshot_root,) if thumbnail else self.allowed_roots+ if not any(path == root or root in path.parents for root in roots):+ raise MediaUnavailable(asset_id)+ if not path.is_file():+ raise MediaUnavailable(asset_id)+ return path++class MediaBackend(Protocol):name: str@@ -40,7 +79,7 @@ class FilesystemBackend:name = "filesystem"def __init__(self, allowed_roots: Sequence[Path]):- self.allowed_roots = tuple(root.resolve() for root in allowed_roots)+ self.allowed_roots = tuple(normalized_path(root) for root in allowed_roots)def capabilities(self) -> MediaCapabilities:return MediaCapabilities(probe=True, preview=True, direct_stream=True)@@ -49,7 +88,7 @@ class FilesystemBackend:raw = asset.get("path")if not raw:return ()- path = Path(str(raw)).resolve()+ path = normalized_path(str(raw))if not any(path == root or root in path.parents for root in self.allowed_roots):return ()return (StreamCandidate(self.name, "file", str(path)),)@@ -60,9 +99,8 @@ class StashAdapter:name = "stash"- def __init__(self, graphql_url: str = "http://127.0.0.1:9999/graphql", timeout: float = 10.0):- self.graphql_url = graphql_url- self.timeout = timeout+ def __init__(self, client: StashClient | None = None):+ self.client = client or StashClient()def capabilities(self) -> MediaCapabilities:return MediaCapabilities(probe=True, preview=True, direct_stream=True,@@ -72,7 +110,7 @@ class StashAdapter:scene_id = asset.get("stash_scene_id")if not scene_id:return ()- payload = self._graphql(+ payload = self.client.graphql("query($id:ID!){sceneStreams(id:$id){url mime_type label}}",{"id": str(scene_id)},)@@ -83,19 +121,6 @@ class StashAdapter:for item in streams if item.get("url"))- def _graphql(self, query: str, variables: Mapping[str, object]) -> dict:- body = json.dumps({"query": query, "variables": variables}).encode("utf-8")- request = urllib.request.Request(- self.graphql_url, data=body,- headers={"Content-Type": "application/json"}, method="POST",- )- with urllib.request.urlopen(request, timeout=self.timeout) as response:- result = json.load(response)- if result.get("errors"):- raise RuntimeError(result["errors"])- return result.get("data") or {}--class MediaEngine:def __init__(self, backends: Sequence[MediaBackend]):self.backends = tuple(backends)diff --git a/Resources/Tools/peach/previews.py b/Resources/Tools/peach/previews.pynew file mode 100644index 000000000..d650b1c38--- /dev/null+++ b/Resources/Tools/peach/previews.py@@ -0,0 +1,137 @@+from __future__ import annotations++import os+import re+import subprocess+import threading+from pathlib import Path++from .ffmpeg import FFmpegResolver+from .repository import LedgerRepository+++class PreviewUnavailable(RuntimeError):+ pass+++_GENERATE_LOCK = threading.Lock()+++class PreviewService:+ def __init__(self, repository: LedgerRepository, resolver: FFmpegResolver,+ snapshot_root: Path, poster_root: Path, avatar_root: Path, logo_root: Path):+ self.repository = repository+ self.resolver = resolver+ self.snapshot_root = snapshot_root.resolve()+ self.poster_root = poster_root.resolve()+ self.avatar_root = avatar_root.resolve()+ self.logo_root = logo_root.resolve()++ def poster(self, asset_id: int, cell: int = 4) -> Path:+ cell = max(0, min(8, cell))+ destination = self.poster_root / f"{asset_id}_{cell}.jpg"+ if destination.is_file():+ return destination+ source = self._snapshot(asset_id)+ ffmpeg = self._ffmpeg()+ col, row = cell % 3, cell // 3+ self.poster_root.mkdir(parents=True, exist_ok=True)+ temporary = destination.with_name(destination.stem + ".tmp.jpg")+ with _GENERATE_LOCK:+ if destination.is_file():+ return destination+ self._run([+ str(ffmpeg), "-y", "-v", "error", "-i", str(source),+ "-vf", f"crop=iw/3:ih/3:iw/3*{col}:ih/3*{row},scale='min(640,iw)':-2",+ "-q:v", "4", str(temporary),+ ])+ os.replace(temporary, destination)+ return destination++ def avatar(self, asset_id: int) -> Path:+ destination = self.avatar_root / f"{asset_id}.jpg"+ if destination.is_file():+ return destination+ source = self._snapshot(asset_id)+ ffmpeg = self._ffmpeg()+ self.avatar_root.mkdir(parents=True, exist_ok=True)+ candidates: list[tuple[Path, float]] = []+ with _GENERATE_LOCK:+ if destination.is_file():+ return destination+ try:+ for col, row in ((1, 1), (0, 0), (1, 2), (2, 0), (0, 2), (2, 2)):+ temporary = destination.with_name(f"{destination.stem}.{col}{row}.tmp.jpg")+ self._run([+ str(ffmpeg), "-y", "-v", "error", "-i", str(source),+ "-vf", f"crop=iw/3:ih/3:iw/3*{col}:ih/3*{row},"+ "scale=160:160:force_original_aspect_ratio=increase,crop=160:160",+ "-q:v", "4", str(temporary),+ ])+ try:+ raw = subprocess.run(+ [str(ffmpeg), "-v", "error", "-i", str(temporary), "-vf", "scale=1:1",+ "-f", "rawvideo", "-pix_fmt", "gray", "-"],+ capture_output=True, timeout=20, check=False,+ ).stdout+ except (OSError, subprocess.TimeoutExpired):+ raw = b""+ brightness = float(raw[0]) if raw else 0.0+ candidates.append((temporary, brightness))+ if brightness >= 60:+ break+ if not candidates:+ raise PreviewUnavailable("avatar generation failed")+ best, brightness = max(candidates, key=lambda item: item[1])+ if brightness < 12:+ raise PreviewUnavailable("snapshot is too dark")+ os.replace(best, destination)+ finally:+ for path, _ in candidates:+ if path.exists() and path != destination:+ path.unlink(missing_ok=True)+ return destination++ def logo(self, studio: str) -> tuple[Path, str]:+ safe = re.sub(r"[^A-Za-z0-9_-]", "_", studio)[:60]+ if not safe:+ raise PreviewUnavailable("empty studio")+ candidates = [self.logo_root / f"{safe}.img"]+ if self.logo_root.is_dir():+ target = f"{safe}.img".lower()+ candidates.extend(path for path in self.logo_root.iterdir() if path.name.lower() == target)+ for path in candidates:+ if path.is_file():+ content_type = "image/x-icon"+ sidecar = Path(str(path) + ".ct")+ if sidecar.is_file():+ detected = sidecar.read_text(encoding="utf-8").strip().split(";")[0]+ content_type = detected or content_type+ return path, content_type+ raise PreviewUnavailable("logo unavailable")++ def _snapshot(self, asset_id: int) -> Path:+ asset = self.repository.media_asset(asset_id)+ if asset is None or not asset.snapshot_path:+ raise PreviewUnavailable("snapshot unavailable")+ path = Path(asset.snapshot_path).resolve()+ if not (path == self.snapshot_root or self.snapshot_root in path.parents) or not path.is_file():+ raise PreviewUnavailable("snapshot unavailable")+ return path++ def _ffmpeg(self) -> Path:+ choice = self.resolver.ffmpeg()+ if choice is None:+ raise PreviewUnavailable("ffmpeg unavailable")+ return choice.path++ @staticmethod+ def _run(command: list[str]) -> None:+ try:+ result = subprocess.run(command, capture_output=True, timeout=30, check=False)+ except (OSError, subprocess.TimeoutExpired) as exc:+ Path(command[-1]).unlink(missing_ok=True)+ raise PreviewUnavailable("ffmpeg generation failed") from exc+ if result.returncode != 0 or not Path(command[-1]).is_file():+ Path(command[-1]).unlink(missing_ok=True)+ raise PreviewUnavailable("ffmpeg generation failed")diff --git a/Resources/Tools/peach/repository.py b/Resources/Tools/peach/repository.pynew file mode 100644index 000000000..2532a36e7--- /dev/null+++ b/Resources/Tools/peach/repository.py@@ -0,0 +1,32 @@+from __future__ import annotations++import sqlite3+from dataclasses import dataclass+from pathlib import Path+++@dataclass(frozen=True)+class MediaAsset:+ id: int+ path: str | None+ snapshot_path: str | None+ stash_scene_id: int | None+++class LedgerRepository:+ def __init__(self, db_path: Path):+ self.db_path = db_path++ def media_asset(self, asset_id: int) -> MediaAsset | None:+ connection = sqlite3.connect(self.db_path.resolve().as_uri() + "?mode=ro", uri=True)+ connection.row_factory = sqlite3.Row+ try:+ row = connection.execute(+ "SELECT id,path,snapshot_path,stash_scene_id FROM asset WHERE id=?",+ (asset_id,),+ ).fetchone()+ finally:+ connection.close()+ if row is None:+ return None+ return MediaAsset(row["id"], row["path"], row["snapshot_path"], row["stash_scene_id"])diff --git a/Resources/Tools/peach/stash.py b/Resources/Tools/peach/stash.pynew file mode 100644index 000000000..24e712894--- /dev/null+++ b/Resources/Tools/peach/stash.py@@ -0,0 +1,32 @@+from __future__ import annotations++import json+import urllib.request+from dataclasses import dataclass+from typing import Mapping+++class StashError(RuntimeError):+ pass+++@dataclass+class StashClient:+ graphql_url: str = "http://127.0.0.1:9999/graphql"+ timeout: float = 10.0+ api_key: str | None = None++ def graphql(self, query: str, variables: Mapping[str, object] | None = None) -> dict:+ body = json.dumps({"query": query, "variables": variables or {}}).encode("utf-8")+ headers = {"Content-Type": "application/json"}+ if self.api_key:+ headers["ApiKey"] = self.api_key+ request = urllib.request.Request(self.graphql_url, data=body, headers=headers, method="POST")+ try:+ with urllib.request.urlopen(request, timeout=self.timeout) as response:+ result = json.load(response)+ except Exception as exc:+ raise StashError(f"Stash request failed: {type(exc).__name__}") from exc+ if result.get("errors"):+ raise StashError(str(result["errors"]))+ return result.get("data") or {}diff --git a/Resources/Tools/rm-web.py b/Resources/Tools/rm-web.pyindex 8885c43c9..edb83c7a2 100644--- a/Resources/Tools/rm-web.py+++ b/Resources/Tools/rm-web.py@@ -24,6 +24,7 @@ ledger 有全部 24,980 个(本地 + 115 + PikPak)。import os, re, sys, json, time, html, hmac, sqlite3, mimetypes, threading, subprocess, urllib.parsefrom http.server import ThreadingHTTPServer, BaseHTTPRequestHandlerfrom http.cookies import SimpleCookie+from pathlib import PathDB = r"R:\Resources\Intake\ledger.db"HERE = os.path.dirname(os.path.abspath(__file__))@@ -88,14 +89,15 @@ def cache_bust():with _CACHE_LOCK:_CACHE.clear()-def db():- c = sqlite3.connect(DB, timeout=30, check_same_thread=False)+def db(write=False):+ target = DB if write else Path(DB).resolve().as_uri() + "?mode=ro"+ c = sqlite3.connect(target, timeout=30, check_same_thread=False, uri=not write)c.row_factory = sqlite3.Rowreturn cdef ensure_columns():"""仅供旧库兼容/测试;生产启动不再自动调用。"""- c = db()+ c = db(write=True)have = {r[1] for r in c.execute("PRAGMA table_info(asset)")}for col, decl in (("feedback", "TEXT"), # dislike / seen (见方案 §5.4)("disposal", "TEXT"), # pending 待删@@ -491,7 +493,7 @@ def w_activity(body):dur = float(body.get("duration", 0)); add = float(body.get("delta", 0))ended = bool(body.get("ended")); seeks = int(body.get("seeks", 0))with _lock:- c = db()+ c = db(write=True)row = c.execute("SELECT play_seconds,max_reached,seek_count FROM asset WHERE id=?",(aid,)).fetchone()secs = (row["play_seconds"] or 0) + max(add, 0)@@ -510,7 +512,7 @@ def w_play(body):cache_bust()aid = int(body["id"])with _lock:- c = db()+ c = db(write=True)c.execute("UPDATE asset SET play_count=COALESCE(play_count,0)+1, last_played=? ""WHERE id=?", (time.time(), aid))c.commit(); c.close()@@ -521,7 +523,7 @@ def w_feedback(body):"""四级反馈,前三级只打标记(见方案 §5.4)。第四级删除不在本服务里。"""aid = int(body["id"]); kind = body.get("kind")with _lock:- c = db()+ c = db(write=True)if kind in ("dislike", "seen"):cur = c.execute("SELECT feedback FROM asset WHERE id=?", (aid,)).fetchone()["feedback"]c.execute("UPDATE asset SET feedback=?, feedback_at=? WHERE id=?",diff --git a/Resources/Tools/scripts/audit-ledger-readonly.py b/Resources/Tools/scripts/audit-ledger-readonly.pynew file mode 100644index 000000000..c2e19260b--- /dev/null+++ b/Resources/Tools/scripts/audit-ledger-readonly.py@@ -0,0 +1,43 @@+#!/usr/bin/env python3+"""只读核对真实账本的 schema 与行为水位,不执行 PRAGMA 或写操作。"""+import json+import sqlite3+from pathlib import Path+++DB = Path(r"R:\Resources\Intake\ledger.db")+++def main():+ connection = sqlite3.connect(DB.resolve().as_uri() + "?mode=ro", uri=True)+ try:+ scalar = lambda sql: connection.execute(sql).fetchone()[0]+ has_events = scalar(+ "SELECT COUNT(*) FROM sqlite_schema WHERE type='table' AND name='activity_event'"+ )+ result = {+ "schema_migration": scalar(+ "SELECT COUNT(*) FROM sqlite_schema WHERE type='table' AND name='schema_migration'"+ ),+ "assets": scalar("SELECT COUNT(*) FROM asset"),+ "played": scalar("SELECT COUNT(*) FROM asset WHERE COALESCE(play_count,0)>0"),+ "feedback": scalar("SELECT COUNT(*) FROM asset WHERE feedback IS NOT NULL"),+ "latest_feedback_at": scalar("SELECT MAX(feedback_at) FROM asset"),+ "latest_last_played_numeric": scalar("SELECT MAX(CAST(last_played AS REAL)) FROM asset"),+ "activity_events": scalar("SELECT COUNT(*) FROM activity_event") if has_events else None,+ "recent_play_rows": [+ {"id": row[0], "play_count": row[1], "last_played": row[2], "name": row[3]}+ for row in connection.execute(+ """SELECT id,play_count,last_played,name FROM asset+ WHERE CAST(last_played AS REAL)>0+ ORDER BY CAST(last_played AS REAL) DESC LIMIT 10"""+ )+ ],+ }+ finally:+ connection.close()+ print(json.dumps(result, ensure_ascii=True, sort_keys=True))+++if __name__ == "__main__":+ main()diff --git a/Resources/Tools/tests/test_fastapi_api.py b/Resources/Tools/tests/test_fastapi_api.pyindex de90a4f08..3e041c4c9 100644--- a/Resources/Tools/tests/test_fastapi_api.py+++ b/Resources/Tools/tests/test_fastapi_api.py@@ -18,7 +18,7 @@ CREATE TABLE asset(medium TEXT, size INTEGER, creator TEXT, studio TEXT, series TEXT, code TEXT,duration REAL, width INTEGER, height INTEGER, ctx_length TEXT, ctx_orient TEXT,ctx_quality TEXT, play_count INTEGER DEFAULT 0, last_played TEXT, rating INTEGER,- o_count INTEGER, watch_ratio REAL, snapshot_path TEXT, first_seen TEXT,+ o_count INTEGER, watch_ratio REAL, stash_scene_id INTEGER, snapshot_path TEXT, first_seen TEXT,feedback TEXT, disposal TEXT, leave_ratio REAL, play_seconds REAL,feedback_at REAL, seek_count INTEGER, max_reached REAL,UNIQUE(location,path));@@ -31,19 +31,44 @@ CREATE TABLE asset_tag(asset_id INTEGER,tag TEXT,confidence REAL DEFAULT 1.0,souclass FastApiContractTests(unittest.IsolatedAsyncioTestCase):async def asyncSetUp(self):self.tmp = tempfile.TemporaryDirectory()- self.db = Path(self.tmp.name) / "ledger.db"+ self.root = Path(self.tmp.name)+ self.db = self.root / "ledger.db"+ self.media_root = self.root / "media"+ self.snapshot_root = self.root / "snapshots"+ self.poster_root = self.root / "posters"+ self.avatar_root = self.root / "avatars"+ self.logo_root = self.root / "logos"+ for path in (self.media_root, self.snapshot_root, self.poster_root,+ self.avatar_root, self.logo_root):+ path.mkdir()+ self.media_file = self.media_root / "one.mp4"+ self.media_file.write_bytes(b"0123456789")+ self.snapshot_file = self.snapshot_root / "one.jpg"+ self.snapshot_file.write_bytes(b"snapshot")+ (self.poster_root / "1_4.jpg").write_bytes(b"poster")+ (self.avatar_root / "1.jpg").write_bytes(b"avatar")+ (self.logo_root / "Studio_A.img").write_bytes(b"logo")+ (self.logo_root / "Studio_A.img.ct").write_text("image/png", encoding="utf-8")+ self.page = self.root / "index.html"+ self.page.write_text("<!doctype html><title>Peach test</title><main>ready</main>", encoding="utf-8")con = sqlite3.connect(self.db)con.executescript(BASE_SCHEMA)con.execute("""INSERT INTO asset(id,location,path,name,medium,size,creator,studio,duration,- width,height,first_seen)- VALUES(1,'local','R:\\Media\\one.mp4','one.mp4','video',100,- 'Alice','Studio A',100,1920,1080,'2026-08-14')"""+ width,height,snapshot_path,first_seen)+ VALUES(1,'local',?,'one.mp4','video',100,+ 'Alice','Studio A',100,1920,1080,?,'2026-08-14')""",+ (str(self.media_file), str(self.snapshot_file)),)con.execute("INSERT INTO asset_tag(asset_id,tag,source) VALUES(1,'Tag A','test')")con.commit()con.close()- app = create_app(PeachSettings(db_path=self.db, token="secret"))+ app = create_app(PeachSettings(+ db_path=self.db, token="secret", page_path=self.page,+ allowed_media_roots=(self.media_root,), snapshot_root=self.snapshot_root,+ poster_root=self.poster_root, avatar_root=self.avatar_root, logo_root=self.logo_root,+ allow_legacy_stash_ffmpeg=False,+ ))self.client = httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test")@@ -55,7 +80,7 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):async def test_health_is_side_effect_free(self):response = await self.client.get("/healthz")self.assertEqual(response.status_code, 200)- self.assertEqual(response.json()["mode"], "compat")+ self.assertEqual(response.json()["mode"], "candidate")async def test_auth_and_items_contract(self):denied = await self.client.get("/api/items")@@ -78,6 +103,59 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):con.close()self.assertEqual(row, (7.0, 1, 0.5))+ async def test_home_sets_exact_http_only_cookie(self):+ denied = await self.client.get("/")+ self.assertEqual(denied.status_code, 401)+ response = await self.client.get("/?t=secret")+ self.assertEqual(response.status_code, 200)+ self.assertIn("ready", response.text)+ cookie = response.headers["set-cookie"]+ self.assertIn("tok=secret", cookie)+ self.assertIn("HttpOnly", cookie)++ async def test_standard_range_and_head_contract(self):+ headers = {"X-Token": "secret"}+ full = await self.client.get("/stream?id=1", headers=headers)+ self.assertEqual(full.status_code, 200)+ self.assertEqual(full.content, b"0123456789")+ self.assertIn("etag", full.headers)+ self.assertIn("last-modified", full.headers)++ partial = await self.client.get(+ "/stream?id=1", headers={**headers, "Range": "bytes=2-5"}+ )+ self.assertEqual(partial.status_code, 206)+ self.assertEqual(partial.content, b"2345")+ self.assertEqual(partial.headers["content-range"], "bytes 2-5/10")++ suffix = await self.client.get(+ "/stream?id=1", headers={**headers, "Range": "bytes=-4"}+ )+ self.assertEqual(suffix.status_code, 206)+ self.assertEqual(suffix.content, b"6789")++ invalid = await self.client.get(+ "/stream?id=1", headers={**headers, "Range": "bytes=99-"}+ )+ self.assertEqual(invalid.status_code, 416)+ self.assertEqual(invalid.headers["content-range"], "*/10")++ head = await self.client.head("/stream?id=1", headers=headers)+ self.assertEqual(head.status_code, 200)+ self.assertEqual(head.content, b"")+ self.assertEqual(head.headers["content-length"], "10")++ async def test_cached_visual_assets_and_thumbnail(self):+ headers = {"X-Token": "secret"}+ poster = await self.client.get("/poster?id=1&c=4", headers=headers)+ avatar = await self.client.get("/avatar?id=1", headers=headers)+ logo = await self.client.get("/logo?studio=Studio_A", headers=headers)+ thumb = await self.client.get("/thumb?id=1", headers=headers)+ self.assertEqual((poster.content, avatar.content, logo.content, thumb.content),+ (b"poster", b"avatar", b"logo", b"snapshot"))+ self.assertEqual(logo.headers["content-type"], "image/png")+ self.assertEqual(poster.headers["cache-control"], "public, max-age=86400")+if __name__ == "__main__":unittest.main()diff --git a/Resources/Tools/tests/test_media.py b/Resources/Tools/tests/test_media.pyindex 2ec377af0..f419ea39f 100644--- a/Resources/Tools/tests/test_media.py+++ b/Resources/Tools/tests/test_media.py@@ -3,7 +3,9 @@ import unittestfrom pathlib import Pathfrom unittest.mock import patch-from peach.media import FilesystemBackend, MediaEngine, StashAdapter+from peach.ffmpeg import FFmpegResolver+from peach.media import FilesystemBackend, MediaEngine, StashAdapter, normalized_path+from peach.stash import StashClientclass MediaEngineTests(unittest.TestCase):@@ -18,14 +20,15 @@ class MediaEngineTests(unittest.TestCase):self.assertEqual(backend.stream_candidates({"path": str(outside)}), ())def test_stash_adapter_uses_public_stream_contract(self):- adapter = StashAdapter()+ client = StashClient()+ adapter = StashAdapter(client)payload = {"sceneStreams": [{"url": "http://127.0.0.1:9999/scene/42/stream", "mime_type": "video/mp4","label": "Direct"},{"url": "http://127.0.0.1:9999/scene/42/hls", "mime_type": "application/x-mpegURL","label": "HLS"},]}- with patch.object(adapter, "_graphql", return_value=payload) as graphql:+ with patch.object(client, "graphql", return_value=payload) as graphql:result = adapter.stream_candidates({"stash_scene_id": 42})self.assertEqual([x.label for x in result], ["Direct", "HLS"])self.assertEqual(graphql.call_args.args[1], {"id": "42"})@@ -33,13 +36,29 @@ class MediaEngineTests(unittest.TestCase):def test_engine_composes_backends_without_hidden_fallback(self):with tempfile.TemporaryDirectory() as tmp:filesystem = FilesystemBackend([Path(tmp)])- stash = StashAdapter()- with patch.object(stash, "_graphql", return_value={"sceneStreams": []}):+ client = StashClient()+ stash = StashAdapter(client)+ with patch.object(client, "graphql", return_value={"sceneStreams": []}):engine = MediaEngine([filesystem, stash])result = engine.stream_candidates({"path": str(Path(tmp) / "one.mp4"),"stash_scene_id": 42})self.assertEqual([x.backend for x in result], ["filesystem"])+ def test_ffmpeg_resolver_prefers_explicit_environment(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ binary = root / "ffmpeg.exe"+ binary.write_bytes(b"test")+ resolver = FFmpegResolver(root, allow_legacy_stash=False)+ with patch.dict("os.environ", {"PEACH_FFMPEG": str(binary)}, clear=False):+ choice = resolver.ffmpeg()+ self.assertEqual(choice.source, "environment")++ def test_offline_windows_root_does_not_block_startup(self):+ with patch.object(Path, "resolve", side_effect=OSError("offline")):+ path = normalized_path(Path("B:/"))+ self.assertTrue(path.is_absolute())+if __name__ == "__main__":unittest.main()diff --git a/Resources/Tools/tests/test_rm_web.py b/Resources/Tools/tests/test_rm_web.pyindex b33a011f6..0c9fb05bd 100644--- a/Resources/Tools/tests/test_rm_web.py+++ b/Resources/Tools/tests/test_rm_web.py@@ -96,6 +96,12 @@ class WebDataTests(unittest.TestCase):self.assertTrue({"feedback", "disposal", "leave_ratio", "play_seconds","feedback_at", "seek_count", "max_reached"} <= columns)+ def test_default_database_connection_is_readonly(self):+ con = rm_web.db()+ with self.assertRaises(sqlite3.OperationalError):+ con.execute("UPDATE asset SET name='must-not-write' WHERE id=1")+ con.close()+def test_items_are_filtered_and_do_not_expose_paths(self):result = rm_web.q_items({"loc": "local", "sort": "new", "limit": "10"})self.assertEqual(result["total"], 1)diff --git "a/Resources/Tools/\344\272\244\346\216\245\346\226\207\346\241\243-2026-08-13.md" "b/Resources/Tools/\344\272\244\346\216\245\346\226\207\346\241\243-2026-08-13.md"index af25b8e31..fc3b11538 100644--- "a/Resources/Tools/\344\272\244\346\216\245\346\226\207\346\241\243-2026-08-13.md"+++ "b/Resources/Tools/\344\272\244\346\216\245\346\226\207\346\241\243-2026-08-13.md"@@ -7,8 +7,10 @@> - Peach 80 端口和 Stash 9999 均仍运行;本轮新后端代码尚未重启到生产实例。> - 默认本地自托管,但在线追更/外部数据源是正式能力;未来支持安全远程访问。> - ledger 是真相源;Stash 是可替换 adapter,不是 Peach Web 后端。-> - 已建立 Git 基线 `cc293c7`、正式迁移器、FastAPI JSON 兼容入口、Media/AI Provider 边界及-> 17 项隔离测试。真实 `ledger.db` 未应用新迁移。+> - 已建立 Git 基线 `cc293c7`、正式迁移器、FastAPI 完整候选入口、Media/AI Provider 边界及+> 23 项隔离测试。真实 `ledger.db` 未应用新迁移。+> - FastAPI 已在临时 `127.0.0.1:8900` 通过桌面/390×844/真实媒体 HEAD/缓存预览验证,+> 测试进程已关闭;80 端口仍是旧服务。> - 项目早期允许破坏性重构未发布代码/接口;不得把这种授权扩大到真实媒体、账本或公网配置。>> 接手先读:`架构接手审计-2026-08-14.md`、`Stash专项审计-2026-08-14.md`、`docs/adr/`。diff --git "a/Resources/Tools/\346\236\266\346\236\204\346\216\245\346\211\213\345\256\241\350\256\241-2026-08-14.md" "b/Resources/Tools/\346\236\266\346\236\204\346\216\245\346\211\213\345\256\241\350\256\241-2026-08-14.md"index 2c4e0f5c9..bc338d0a3 100644--- "a/Resources/Tools/\346\236\266\346\236\204\346\216\245\346\211\213\345\256\241\350\256\241-2026-08-14.md"+++ "b/Resources/Tools/\346\236\266\346\236\204\346\216\245\346\211\213\345\256\241\350\256\241-2026-08-14.md"@@ -67,7 +67,9 @@ CLI 使用 `rating=5/1` 表示喜欢/不喜欢,Web 使用 `feedback=dislike/se### P1:缺少工程基线(已建立)-已建立 Git 基线 `cc293c7`,排除媒体、ledger、密码和生成物;测试增至 17 项。允许更积极拆模块,但每个切片仍必须用临时库和契约测试证明不会破坏真实数据。+已建立 Git 基线 `cc293c7`,排除媒体、ledger、密码和生成物;测试增至 23 项。FastAPI 候选入口+已完整覆盖页面、JSON、标准 Range/HEAD、缩略图和预览资产,并在临时 8900 端口完成双视口+验证。允许更积极拆模块,但每个切片仍必须用临时库和契约测试证明不会破坏真实数据。### P2:首屏性能与查询模型diff --git "a/Resources/Tools/\351\241\271\347\233\256\350\277\233\345\272\246\346\200\273\350\247\210.md" "b/Resources/Tools/\351\241\271\347\233\256\350\277\233\345\272\246\346\200\273\350\247\210.md"index 648b1f193..53f70dd6d 100644--- "a/Resources/Tools/\351\241\271\347\233\256\350\277\233\345\272\246\346\200\273\350\247\210.md"+++ "b/Resources/Tools/\351\241\271\347\233\256\350\277\233\345\272\246\346\200\273\350\247\210.md"@@ -12,6 +12,9 @@> “只在本地/局域网、绝不联网”不再是产品边界。当前实现继续模块化单体,后端渐进 FastAPI,> ledger 是真相源,Stash 是可替换 adapter。详见 `docs/adr/` 与> [《Stash 专项审计》](Stash专项审计-2026-08-14.md)。+>+> **第二阶段代码态**:FastAPI 候选入口已覆盖完整页面、JSON、标准媒体 Range/HEAD 与预览资产,+> 23 项隔离测试和临时 8900 双视口验证通过;生产 80 端口尚未切换,真实 schema 迁移尚未应用。---