Peach: Local-first video metadata scraper and media manager.
refactor: consolidate media jobs and mature adapters
Peach local maintenancebaf3fa37ecfa
diff --git a/AGENTS.md b/AGENTS.mdindex 15b3b8cad..52fd4250c 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -7,8 +7,9 @@ Before changing the project, read these files in order:1. `README.md`2. `docs/STATUS.md`3. `docs/ARCHITECTURE.md`-4. `docs/HANDOFF.md`-5. Relevant ADRs under `docs/adr/`+4. `docs/REUSE.md`+5. `docs/HANDOFF.md`+6. Relevant ADRs under `docs/adr/`Working rules:@@ -20,4 +21,6 @@ Working rules:- Keep the architecture a FastAPI modular monolith with a separate web surface. Do not introduce microservices, PostgreSQL, a React rewrite, or a full multi-account system without a new ADR.- Ledger remains the core truth. Stash is a replaceable Media Engine adapter. AI results are candidates with provenance/confidence, not direct truth-field mutations.- Do not create dated handoff documents. Update `docs/STATUS.md` for current runtime/next work and `docs/HANDOFF.md` for durable operating knowledge as part of the same change.+- Before adding or restoring an implementation, check `docs/REUSE.md`, the current tree and Git history. A missing legacy filename does not prove the capability is missing. Update the reuse register when the decision changes.+- Never require the user to relay implementation details between agents. Put current facts in `docs/STATUS.md`, durable rules in `docs/HANDOFF.md`/`docs/REUSE.md`, and architecture decisions in an ADR.- Run the verification commands in `README.md` before committing relevant changes.diff --git a/README.md b/README.mdindex 84c23dcaa..78c0fde68 100644--- a/README.md+++ b/README.md@@ -55,6 +55,7 @@ cd R:\peach-app证书必须包含实际访问名(例如 `peach.local`)并被客户端信任;启用 TLS 时 mDNS 自动发布 HTTPS。当前运行态与下一任务只看 [`docs/STATUS.md`](docs/STATUS.md);跨 Codex/Claude 的固定接手方式只看 [`docs/HANDOFF.md`](docs/HANDOFF.md)。+准备新增、恢复或替换实现前,必须查 [`docs/REUSE.md`](docs/REUSE.md),避免按旧文件名重复造轮子。## 批处理安全边界diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex a2cbed277..d6c68e94a 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -8,11 +8,13 @@ Peach 是逻辑前后端分离、部署仍为一个进程的 FastAPI 模块化1. **Ledger**:资产、行为、来源和知识的唯一真相源。SQLite 适合当前单用户规模。2. **API/application**:FastAPI 承载页面、JSON、媒体响应和写入边界。-3. **Media Engine**:本地文件为原生 backend;Stash 先作为 adapter,再按扫描、元数据、预览、流媒体逐项替换。+3. **Media Engine**:FastAPI 只持有一个 `MediaEngine`。本地文件是原生 backend;Stash 是公开协议 adapter,再按扫描、元数据、预览、流媒体逐项替换。4. **Web**:当前是无构建步骤的单页,保持移动端优先;不做 React 重写。5. **AI providers**:`InferenceProvider` 与 `AgentProvider` 分离。AI 只产出带 provenance/confidence 的候选。6. **Profiles**:默认单用户,数据模型预留 user/profile,不引入完整账号体系。7. **Follow sources**:RSS/Atom 等成熟协议先归一化为只读候选;原始证据、review 和 ledger 写入分层。+8. **Jobs**:Peach 自己定义来源成本、磁盘闸门、进程归属、进度和 provenance;HTTP、调度、媒体探测、图片与协议解析使用成熟组件。+9. **HTTP/search**:网络 adapter 共用长生命周期 HTTPX transport;作品全文搜索使用 SQLite FTS5 trigram,短查询保留 LIKE fallback。## Data flow@@ -31,6 +33,7 @@ AI/external metadata -> reviewed candidates -> ledger- 将 Stash 私有目录或 GPL 构建作为 Peach 的稳定打包依赖关键取舍见 `docs/adr/`;Stash 的代码级证据见 `docs/STASH.md`。+复用/自研边界及旧脚本继任关系见 `docs/REUSE.md`。## Runtime data layoutdiff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex 8509be897..01cbf4018 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -9,13 +9,22 @@ This is durable operating knowledge, not a per-session transcript.- Both agents therefore receive the same contract and the same mandatory reading order.- Do not ask the outgoing agent to write a dated handoff. A task that changes reality must update `docs/STATUS.md`; a durable lesson changes this file or an ADR.- Start every new task with `R:\peach-app` as the working directory and say only: “接手 Peach,按项目入口文件继续 STATUS 中的下一任务。”+- The user is not the message bus. Do not ask the user to copy technical conclusions to another agent; update the shared documents in the same change.+- If the worktree is dirty, inspect and preserve every existing diff. One agent owns a file while actively changing it; work on non-overlapping files or wait for that write to finish, then integrate the diff instead of recreating it.++## Reuse before restore++- Read `docs/REUSE.md` before introducing a library, protocol implementation or restored legacy script.+- Search the current tree by capability and output contract, not only by the old filename. `scripts/scrape_codes.py` is the maintained successor to the removed `rm-javlookup.py`; restoring the old scraper is forbidden.+- The restructure was not a clean-room rewrite: probe, sheets, status, suggest, traffic watch, SHA1 sync, ledger and the web surface were migrated from legacy implementations. Treat them as inherited code until their behavior has been deliberately replaced and tested.+- Git history is recovery evidence, not an implementation catalog. Restore code only after proving no current successor or mature dependency covers the capability.## Data safety- Real ledger: `R:\peach-data\database\ledger.db`; WAL mode; normal browsing legitimately changes play/activity fields.- Tests must create temporary SQLite databases and temporary media files.- Before real migration: SQLite backup, asset/tag counts, `PRAGMA integrity_check`, migration version check, then service smoke test.-- Formal migrations `0000`–`0003` were applied to the real ledger on 2026-08-14. `0003` adds the local default profile, profile-scoped watch queue, typed entity links and entity search terms. The migration and studio-canonicalization backups from the 20:17 maintenance window supersede the older recovery point; retain both until a later verified migration.+- Formal migrations `0000`–`0004` were applied to the real ledger on 2026-08-14. `0003` adds the local default profile, profile-scoped watch queue, typed entity links and entity search terms. `0004` adds synchronized SQLite FTS5 trigram search over asset names/codes, canonical entities, aliases and private search terms. Its backup is `R:\peach-data\database\ledger.pre-migrate-20260814-213920.db`; retain it with the 20:17 recovery points until a later verified migration.- Media and runtime data remain under `R:\media` and `R:\peach-data`; they are not repository assets.## Operations@@ -26,6 +35,8 @@ This is durable operating knowledge, not a per-session transcript.- FastAPI is the only Web server. `web_contract.py` contains the stable JSON surface; do not recreate a parallel `http.server` or dynamic legacy loader.- FFmpeg/ffprobe resolve from explicit environment overrides, then `R:\peach-data\tools\ffmpeg\bin`, then `PATH`. No active code may fall back to the Stash private directory.- Long-running inventory helpers are under `scripts/`; their scheduled tasks use `R:\peach-app\.venv\Scripts\python.exe`. They use absolute data paths and may be interrupted/restarted where their own locking contract allows it.+- Probe, sheets, creator boards and traffic watch parse arguments only inside `main()`. They share `src/peach/jobs.py` for fail-closed disk checks, parameterized source policy and PID locks. Traffic watch stops only matching Peach Python process trees; never restore machine-wide ffmpeg termination.+- Stash, OpenCode Go, Feed, code scraping and performer-image imports use the shared HTTPX transport. Feed XML is parsed by feedparser, raster images by Pillow and source HTML by Beautiful Soup. New adapters must reuse these boundaries instead of adding urllib helpers, manual image headers or HTML regex parsing.- Importing operational scripts must have no filesystem/network/database side effects. `scrape_codes.py` sends only catalog codes to declared metadata sources, writes a resumable review CSV, and dual-writes provenance only with `--apply`. `clean_names.py` previews first and creates a SQLite backup before every apply run.- Check ports 80, 8900 and 9999 before starting or switching services.- 115/PikPak playback depends on CloudDrive mounts `B:`/`A:`. Drive-letter visibility differs by Windows execution token; CloudDrive and Peach must see the same mount namespace. A running process or a drive check from another token proves nothing—test one known `/stream` through Peach. Restart CloudDrive only after proving no copy task and no active I/O.@@ -47,6 +58,7 @@ This is durable operating knowledge, not a per-session transcript.- External sources and AI are supported only through explicit adapters and declared data boundaries.- `FeedAdapter` is the first online-follow connector. It performs explicit bounded RSS/Atom discovery; `FeedSnapshotStore` separates immutable evidence under `sources/follow` from conditional-request cursors under `state/follow`. Do not make it poll on application startup or write ledger rows directly.- AI provider layers are not equivalent: inference APIs and local coding/agent runtimes remain separate.+- Search terms of three or more characters use FTS5 trigram; shorter text falls back to LIKE because trigram cannot index shorter terms. FTS writes are maintained by migration triggers, not by Web startup repair.## Recoverydiff --git a/docs/REUSE.md b/docs/REUSE.mdnew file mode 100644index 000000000..256ed9804--- /dev/null+++ b/docs/REUSE.md@@ -0,0 +1,57 @@+# Reuse register++This file is the implementation lookup table shared by Codex and Claude. Check it before adding or restoring code.++## Peach-owned domain logic++These are product behavior and remain custom:++- canonical performer/studio/creator/tag identity, aliases and provenance;+- profile behavior, watch queue, taste and recommendation ranking;+- local/115/PikPak/Stash/online binding and fallback policy;+- metered-source authorization, privacy classification and reviewed candidate import;+- private acquisition/source references and discovery keywords;+- creator-level visual sampling semantics;+- inference-provider versus agent-provider capability contracts;+- job ownership, progress, cancellation, cost and evidence rules.++## Required reuse++| Capability | Reuse | Peach responsibility |+|---|---|---|+| HTTP | project-wide `httpx.Client`/transport | source policy, DTO and redaction |+| RSS/Atom | `feedparser` | bounded fetch, snapshots, review and import |+| HTML adapters | Beautiful Soup or selectolax | source-specific selectors and provenance |+| Raster images | Pillow | portrait/logo quality and source policy |+| Search | SQLite FTS5 | indexed fields, ranking and profile-aware filters |+| Media probe/transcode | managed FFmpeg/ffprobe | job policy and Media Engine orchestration |+| HLS/DASH playback | hls.js or Shaka Player | stream plan, authorization and fallback order |+| Icons | pinned local Lucide subset | labels, state and interaction design |+| Scheduled polling | APScheduler when persistent feed config exists | job definitions and safety policy |+| Local file events | watchdog plus periodic reconciliation | media identity and missed-event repair |+| Transitional metadata/media | Stash GraphQL, CommunityScrapers and Stash job system | adapter, reconciliation and exit gates |+| LAN discovery | Python zeroconf | service lifecycle and real-client acceptance |++Do not introduce a dependency until its first consumer and isolated tests land in the same change.++## Maintained successors++| Removed/old name | Current implementation | Rule |+|---|---|---|+| `rm-web.py` / `rm-web.html` | `src/peach/api.py`, `src/peach/web_contract.py`, `web/index.html` | never restore the HTTP server |+| `rm-javlookup.py` | `scripts/scrape_codes.py` | extend source adapters; do not fork another scraper |+| `rm-probe.py` | `scripts/probe.py` | move reusable policy into `src/peach`, preserve resume semantics |+| `rm-sheets.py` | `scripts/sheets.py` | share FFmpeg/job primitives; do not create another sheet pipeline |+| `rm-ledger.py` | `scripts/ledger.py` plus repository/migrations | new product reads belong in repositories, not this legacy CLI |+| `rm-status.py` | `scripts/status.py` | status is read-only |+| `rm-suggest.py` | `scripts/suggest.py` | ranking logic will move behind an application port |+| `rm-trafficwatch.py` | `scripts/traffic_watch.py` | stop only owned task process trees |+| `rm-sha1.py` | `scripts/sync_sha1_115.py` | reuse provider hashes; do not rehash cloud media blindly |++## Current replacement queue++Completed in the consolidation slice: shared Media/Job/HTTP boundaries, feedparser, Pillow, Beautiful Soup, FTS5, import-safe batch scripts and scoped task termination.++1. Add a Media Engine stream-plan API and a mature HLS/DASH player before using Stash transcodes in the browser.+2. Configure and evaluate Stash metadata providers before writing another source adapter.+3. Move remaining legacy status/suggest/ledger application logic behind repository/application ports, then delete obsolete CLI surfaces.diff --git a/docs/STATUS.md b/docs/STATUS.mdindex ab0f58481..47bc4f490 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -4,12 +4,12 @@ Last verified: 2026-08-14## Runtime-- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on `0.0.0.0:80`, listener PID observed as 52600; health mode is `fastapi`.+- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on `0.0.0.0:80`, listener PID observed as 3688; health mode is `fastapi`.- `peach.local` is again the single official LAN entry. The publisher restores the verified pre-migration behavior: Python zeroconf listens on all eligible interfaces and publishes `peach.local -> 192.168.50.162`. Production health reports `mdns_backend=zeroconf-all-interfaces`; same-host DNS-SD discovery and `getaddrinfo('peach.local')` both resolved the correct address after restart. A second LAN device remains the final external check; no firewall or router rule was changed.- Stash: `127.0.0.1:9999`, PID observed as 35332.- Traffic monitor: running through `RM-TrafficWatch` from `R:\peach-app\.venv`; all probe/sheets tasks use the same project environment.- Runtime Python: 3.14.7. The removed system Python 3.12 invalidated the old venv, which was rebuilt and reverified before production start.-- Real ledger migrations: `0000`–`0003` applied; zero pending. The 20:17 backups are `R:\peach-data\database\ledger.pre-migrate-20260814-201719.db` and `R:\peach-data\archive\ledger.pre-studio-canonicalize-20260814-201719.db`.+- Real ledger migrations: `0000`–`0004` applied; zero pending. FTS migration backup: `R:\peach-data\database\ledger.pre-migrate-20260814-213920.db`. The 20:17 backups remain `R:\peach-data\database\ledger.pre-migrate-20260814-201719.db` and `R:\peach-data\archive\ledger.pre-studio-canonicalize-20260814-201719.db`.- Current pre-0002 recovery point: `R:\peach-data\archive\ledger.pre-migrate-20260814-162004.db`.Runtime PIDs are observations, not configuration; always re-check them.@@ -31,7 +31,7 @@ Runtime PIDs are observations, not configuration; always re-check them.- Creator/studio top lists and related-item creator/tag/studio matching now read canonical entity relations. Real-ledger timings were 0.055 s for 28 top entries and 0.055 s for 24 related items.- Creator/studio filters, canonical-name search, creator index, facets and attribution stats now also read entity relations. Real-ledger timings were 0.040 s for a 1,545-item creator filter, 0.043 s for the first 60 creators, 0.132 s for facets and 0.394 s for stats.- Snapshot availability checks use the same strict legacy-prefix resolver as `/thumb`, so the front end requests migrated previews instead of displaying false “无预览” cards.-- 47 isolated tests, Python static compilation and JavaScript parse validation passed under Python 3.14/Node.+- 60 isolated tests, Python static compilation, dependency validation and JavaScript parse validation passed under Python 3.14/Node.- Real migration preserved 81,873 assets and 59,697 tag links; both live database and backup passed `integrity_check` and `foreign_key_check` before later metadata writes.- Desktop 1280×720 and mobile 390×844 browser checks passed on the same application candidate before the schema-only migration; visual checks were not rerun after migration because no browser instance was connected.- Restarted production port 80 passed health, home, public OpenCode Go model discovery (26 models at verification time), canonical filtered-list/item reads, thumbnail `200` and 1 KiB `206 Partial Content` Range smoke checks.@@ -44,12 +44,13 @@ Runtime PIDs are observations, not configuration; always re-check them.- `scripts/import_stash_entities.py` reconciled the Stash public performer contract into Peach without making Stash authoritative: 383 exact stable refs, 52 aliases/search terms and two explicitly declared X links were imported. Of 42 non-placeholder Stash images, 14 passed the 512 px short-side gate and were cached with provenance; 28 smaller images were rejected. Top entries including 一个ren、高桥千凛 and 小桃 now use 720 px-class cached portraits.- Static/unit/API production checks passed after restart: home/entity routes, FC2/Prestige logos, canonical aliases and a local-media 1 KiB `206 Partial Content` response. No browser instance was connected, so desktop and 390×844 visual verification remain pending.- The 20:36 Peach restart was launched only after verifying the port-80 command line in the host session. The replacement process can see CloudDrive: asset 4289 again passed `video/mp4` 1 KiB `206 Partial Content` and poster `200`; local asset 1 passed the same Range contract. A sandbox drive check is not authoritative.-- The mDNS regression fix was deployed after verifying the old port-80 command line. The replacement listener PID 52600 passed health, local DNS-SD discovery, Windows hostname resolution and CloudDrive asset 4289 with a 1 KiB `206 Partial Content` response. The active creator-board sampler and its FFmpeg children were not touched.+- The mDNS regression fix remains deployed. The current listener PID 3688 passed health, Windows hostname resolution and CloudDrive asset 4289 with a 1 KiB `206 Partial Content` response.- The original Peach process could not see CloudDrive `A:`/`B:` even though CloudDrive was running. After confirming zero copy tasks and no I/O, CloudDrive and Peach were restarted in the same execution context. Asset 4289 (`669.mp4`) then passed `video/mp4`, 1 KiB `206 Range`, thumbnail and generated-poster API checks. Drive-letter visibility differs by Windows token, so the HTTP stream check is the authoritative service test.## Batch jobs-- Active at the last observation: `scripts/creator_boards.py --from-video --allow-metered --top 60 --per 12 --workers 16` (nohup PID 46948, Python PIDs 51472/8508) is intentionally sampling A: videos into `generated/boards/_frames`. At 20:52 it had 299 frame files and 33 completed boards. The measured CloudDrive I/O belongs to this job; do not restart CloudDrive or terminate its FFmpeg children. The bounded run samples at most 12 frames per creator and has explicit metered authorization.+- The creator-board sampler completed before its implementation was changed; it left 86 boards and 598 cached frames. No `creator_boards.py` process was active at the final observation. The command now uses the shared source-access policy, disk guard, PID lock and Peach-managed FFmpeg resolver while preserving its prior arguments and output layout.+- `RM-TrafficWatch` is running from the project venv with the refactored watcher. It stops only matching Peach task trees and no longer terminates machine-wide FFmpeg/ffprobe processes.- `scripts/scrape_codes.py` — code scraping via r18 → avsox → javbus cascade, resumable from`R:\peach-data\generated\code-scrape.csv`. All 1,104 non-FC2 codes were processed; 715 rows carry@@ -80,11 +81,39 @@ Runtime PIDs are observations, not configuration; always re-check them.(3.7 GB + 1.2 GB) for a human disposal decision; nothing was deleted.- Two vocabulary gaps surfaced: 3D/CG animated content (`oscarkim123`, `Bewyx 2509`) has no medium tag,and video-frame advertising has no marker. Neither was forced into an existing term.+- `scripts/find_ads.py` — identifies promo videos bundled into pirate release packs and writes+ `R:\peach-data\generated\ad-candidates.csv`. Nothing is deleted. 82 candidates, 1.5 GB: 77 marked+ `确认` and 5 `存疑`. Nine sampled directories were visually confirmed as ads (QR code plus promo+ domain in every frame). The strongest signal is structural, not lexical: a group of files in one+ directory sharing an identical byte size and identical duration. Three false-positive classes were+ found and excluded by construction, each verified against a real file:+ `1024` as a substring ate `FC2-PPV-1381024` (970 MB feature); `成人游戏`/`加微信` appear in genuine+ titles (a 9.98 GB feature); and a bare domain with no ad copy is usually a pirate-site watermark on+ real content (`jitumi.pw(1).avi` sampled to an ordinary clothed scene), so those rows are `存疑` for+ human review rather than `确认`.+- Ad-detection recall is bounded: 9,480 of 24,980 videos (38%) have no usable duration, so the+ identical-size-and-duration test cannot run on them, and ads composited into a real video's frames are+ not detectable by metadata at all. `BNST033` is not entirely advertising as previously recorded — its+ directory holds a genuine 3.2 GB feature beside roughly 50 promo clips.- Remaining untagged videos are mostly creators whose PikPak sheets have not been generated, so visualtagging past this point is blocked on the metered PikPak sheet backlog.+## Deployed consolidation++- FastAPI now constructs one `MediaEngine`; filesystem access and the Stash public-protocol adapter are backends of that engine. Stash stream identity reads stable `media_binding` rows instead of using `asset.stash_scene_id` as the sole contract.+- Shared Job policy now owns parameterized source filtering, fail-closed disk-space checks and PID locks for probe, sheets and creator-board work. The traffic watcher targets only matching Python task trees and their descendants; it no longer kills every machine-wide ffmpeg/ffprobe process.+- Probe, sheets, creator boards and traffic watch are import-safe `main()` commands with existing scheduled arguments preserved; importing them for tests no longer opens the real database, log or lock file.+- Stash, OpenCode Go and Feed now share one HTTPX transport in the FastAPI process, including connection pooling, explicit timeouts and bounded response reads. Their protocol DTOs and privacy rules remain separate.+- Feed parsing uses feedparser 6.0.12, raster validation uses Pillow 12.3.0, and source HTML uses Beautiful Soup 4.15.0. `scripts/scrape_codes.py` and `scripts/import_stash_entities.py` also use the shared HTTPX boundary; source-specific selection, provenance and review policy remain Peach-owned.+- Migration `0004` is applied to the real ledger and maintains an FTS5 trigram row for every asset. Assets/entities/relations were unchanged at 81,873 / 8,590 / 131,877; FTS contains 81,873 rows, integrity is `ok`, foreign-key violations are zero, and an FC2 count took 0.0005 s. Production is running this query path; `q=FC2` returned 834 matching assets in the final API smoke test.+- `scripts/find_ads.py` was converted from a one-off hard-coded script into an import-safe, configurable, read-only candidate scanner with isolated tests. Its 82-row generated review result remains unchanged; it still deletes nothing.+- The reuse register and ADR-0010 record required mature dependencies, Peach-owned domain logic and old-to-current script successors. Production port 80 and the scheduled traffic watcher were both restarted onto the consolidated code.+- Final API smoke checks passed `/healthz`, FTS search, local asset 1 Range and CloudDrive asset 4289 Range. No real playback/feedback rows were written by verification.+- Desktop and 390×844 visual checks were attempted but remain unverified: the in-app browser blocks private LAN addresses and the local Firefox automation context could not start. This is a test-environment limitation, not a claimed visual pass.+## Next work-1. Add explicit feed configuration plus a reviewed candidate import without automatic ledger writes; only then consider a scheduler.-2. Add reviewed inference requests behind the OpenCode Go adapter; AI output must remain a candidate and cannot write ledger truth directly.-3. Replace remaining flattened creator/studio display projections only when the front end can consume canonical DTO fields without breaking compatibility.+1. Add a Media Engine stream-plan endpoint and integrate hls.js or Shaka Player before enabling Stash HLS/DASH fallback in the browser.+2. Configure/evaluate Stash CommunityScrapers and metadata providers before writing another source adapter.+3. Add explicit feed configuration and reviewed import; only then use APScheduler. Add reviewed inference requests afterward, with AI output remaining candidates.+4. Move remaining legacy status/suggest/ledger application logic behind repository/application ports, then delete obsolete CLI surfaces.diff --git a/docs/adr/0010-reuse-before-reimplementation.md b/docs/adr/0010-reuse-before-reimplementation.mdnew file mode 100644index 000000000..e89038300--- /dev/null+++ b/docs/adr/0010-reuse-before-reimplementation.md@@ -0,0 +1,27 @@+# ADR-0010:先复用、再重实现++- 状态:Accepted+- 日期:2026-08-14++## 背景++项目结构迁移删除了旧文件名,但多项实现实际以高相似度迁入 `scripts/`。按旧文件名查找导致现有 `scripts/scrape_codes.py` 被误判为缺失,并准备从 Git 恢复旧 scraper。迁移期间也出现过未对照已验证实现而重写 mDNS、重复媒体抽象、重复计费/磁盘闸门等问题。++## 决策++- 新增或恢复实现前,按能力、输入输出和数据副作用搜索当前树,再检查 `docs/REUSE.md` 和 Git 历史。+- Peach 只自研领域差异:实体身份、行为、跨来源绑定、成本/隐私、review/provenance 和任务语义。+- 协议、解析、媒体编解码、搜索基础设施、播放器、图标和调度优先使用成熟依赖;首个真实消费者、固定版本和隔离测试必须同批落地。+- 运行时只保留一个正式 abstraction。迁移 facade 若未接入生产,不得算作能力完成。+- 用户不承担代理间信息同步;事实、规则和决策分别写入 STATUS、HANDOFF/REUSE 和 ADR。++## 被否决的方案++- 因旧文件名消失就从 Git 恢复整份脚本。+- 为统一表面接口,把 Codex/Claude agent runtime 与普通 inference API 强行等同。+- 在没有首个消费者时提前堆积依赖。+- 保留两套生产 abstraction,依靠调用者自行选择。++## 后果++每项能力多一道短审计,但能避免迁移回归、重复维护和不必要的协议实现。`docs/REUSE.md` 成为可更新的实现索引,不替代具体 ADR 和测试证据。diff --git a/migrations/0004_asset_search_fts.sql b/migrations/0004_asset_search_fts.sqlnew file mode 100644index 000000000..3c1b5a1e3--- /dev/null+++ b/migrations/0004_asset_search_fts.sql@@ -0,0 +1,135 @@+CREATE VIRTUAL TABLE IF NOT EXISTS asset_search USING fts5(+ asset_id UNINDEXED,+ name,+ code,+ entities,+ search_terms,+ tokenize='trigram'+);++CREATE VIEW IF NOT EXISTS asset_search_source AS+SELECT+ a.id AS asset_id,+ COALESCE(a.name,'') AS name,+ COALESCE(a.code,'') AS code,+ COALESCE((+ SELECT group_concat(value,' ') FROM (+ SELECT DISTINCT e.canonical_name AS value+ FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id+ WHERE ae.asset_id=a.id+ UNION+ SELECT DISTINCT alias.alias AS value+ FROM asset_entity ae JOIN entity_alias alias ON alias.entity_id=ae.entity_id+ WHERE ae.asset_id=a.id+ )+ ),'') AS entities,+ COALESCE((+ SELECT group_concat(DISTINCT term.term)+ FROM asset_entity ae JOIN entity_search_term term ON term.entity_id=ae.entity_id+ WHERE ae.asset_id=a.id+ ),'') AS search_terms+FROM asset a;++INSERT INTO asset_search(asset_id,name,code,entities,search_terms)+SELECT asset_id,name,code,entities,search_terms FROM asset_search_source;++CREATE TRIGGER asset_search_asset_insert AFTER INSERT ON asset BEGIN+ INSERT INTO asset_search(asset_id,name,code,entities,search_terms)+ SELECT asset_id,name,code,entities,search_terms FROM asset_search_source WHERE asset_id=NEW.id;+END;++CREATE TRIGGER asset_search_asset_update AFTER UPDATE OF name,code ON asset BEGIN+ DELETE FROM asset_search WHERE asset_id=OLD.id;+ INSERT INTO asset_search(asset_id,name,code,entities,search_terms)+ SELECT asset_id,name,code,entities,search_terms FROM asset_search_source WHERE asset_id=NEW.id;+END;++CREATE TRIGGER asset_search_asset_delete AFTER DELETE ON asset BEGIN+ DELETE FROM asset_search WHERE asset_id=OLD.id;+END;++CREATE TRIGGER asset_search_relation_insert AFTER INSERT ON asset_entity BEGIN+ DELETE FROM asset_search WHERE asset_id=NEW.asset_id;+ INSERT INTO asset_search(asset_id,name,code,entities,search_terms)+ SELECT asset_id,name,code,entities,search_terms FROM asset_search_source WHERE asset_id=NEW.asset_id;+END;++CREATE TRIGGER asset_search_relation_delete AFTER DELETE ON asset_entity BEGIN+ DELETE FROM asset_search WHERE asset_id=OLD.asset_id;+ INSERT INTO asset_search(asset_id,name,code,entities,search_terms)+ SELECT asset_id,name,code,entities,search_terms FROM asset_search_source WHERE asset_id=OLD.asset_id;+END;++CREATE TRIGGER asset_search_relation_update AFTER UPDATE OF asset_id,entity_id ON asset_entity BEGIN+ DELETE FROM asset_search WHERE asset_id IN (OLD.asset_id,NEW.asset_id);+ INSERT INTO asset_search(asset_id,name,code,entities,search_terms)+ SELECT asset_id,name,code,entities,search_terms FROM asset_search_source+ WHERE asset_id IN (OLD.asset_id,NEW.asset_id);+END;++CREATE TRIGGER asset_search_entity_update AFTER UPDATE OF canonical_name ON entity BEGIN+ DELETE FROM asset_search WHERE asset_id IN (+ SELECT asset_id FROM asset_entity WHERE entity_id=NEW.id+ );+ INSERT INTO asset_search(asset_id,name,code,entities,search_terms)+ SELECT asset_id,name,code,entities,search_terms FROM asset_search_source+ WHERE asset_id IN (SELECT asset_id FROM asset_entity WHERE entity_id=NEW.id);+END;++CREATE TRIGGER asset_search_alias_insert AFTER INSERT ON entity_alias BEGIN+ DELETE FROM asset_search WHERE asset_id IN (+ SELECT asset_id FROM asset_entity WHERE entity_id=NEW.entity_id+ );+ INSERT INTO asset_search(asset_id,name,code,entities,search_terms)+ SELECT asset_id,name,code,entities,search_terms FROM asset_search_source+ WHERE asset_id IN (SELECT asset_id FROM asset_entity WHERE entity_id=NEW.entity_id);+END;++CREATE TRIGGER asset_search_alias_delete AFTER DELETE ON entity_alias BEGIN+ DELETE FROM asset_search WHERE asset_id IN (+ SELECT asset_id FROM asset_entity WHERE entity_id=OLD.entity_id+ );+ INSERT INTO asset_search(asset_id,name,code,entities,search_terms)+ SELECT asset_id,name,code,entities,search_terms FROM asset_search_source+ WHERE asset_id IN (SELECT asset_id FROM asset_entity WHERE entity_id=OLD.entity_id);+END;++CREATE TRIGGER asset_search_alias_update AFTER UPDATE OF alias,entity_id ON entity_alias BEGIN+ DELETE FROM asset_search WHERE asset_id IN (+ SELECT asset_id FROM asset_entity WHERE entity_id IN (OLD.entity_id,NEW.entity_id)+ );+ INSERT INTO asset_search(asset_id,name,code,entities,search_terms)+ SELECT asset_id,name,code,entities,search_terms FROM asset_search_source+ WHERE asset_id IN (+ SELECT asset_id FROM asset_entity WHERE entity_id IN (OLD.entity_id,NEW.entity_id)+ );+END;++CREATE TRIGGER asset_search_term_insert AFTER INSERT ON entity_search_term BEGIN+ DELETE FROM asset_search WHERE asset_id IN (+ SELECT asset_id FROM asset_entity WHERE entity_id=NEW.entity_id+ );+ INSERT INTO asset_search(asset_id,name,code,entities,search_terms)+ SELECT asset_id,name,code,entities,search_terms FROM asset_search_source+ WHERE asset_id IN (SELECT asset_id FROM asset_entity WHERE entity_id=NEW.entity_id);+END;++CREATE TRIGGER asset_search_term_delete AFTER DELETE ON entity_search_term BEGIN+ DELETE FROM asset_search WHERE asset_id IN (+ SELECT asset_id FROM asset_entity WHERE entity_id=OLD.entity_id+ );+ INSERT INTO asset_search(asset_id,name,code,entities,search_terms)+ SELECT asset_id,name,code,entities,search_terms FROM asset_search_source+ WHERE asset_id IN (SELECT asset_id FROM asset_entity WHERE entity_id=OLD.entity_id);+END;++CREATE TRIGGER asset_search_term_update AFTER UPDATE OF term,entity_id ON entity_search_term BEGIN+ DELETE FROM asset_search WHERE asset_id IN (+ SELECT asset_id FROM asset_entity WHERE entity_id IN (OLD.entity_id,NEW.entity_id)+ );+ INSERT INTO asset_search(asset_id,name,code,entities,search_terms)+ SELECT asset_id,name,code,entities,search_terms FROM asset_search_source+ WHERE asset_id IN (+ SELECT asset_id FROM asset_entity WHERE entity_id IN (OLD.entity_id,NEW.entity_id)+ );+END;diff --git a/pyproject.toml b/pyproject.tomlindex 5f0ae1492..69c6777fd 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -8,8 +8,11 @@ version = "0.2.0"description = "Local-first media library, behavior ledger, and discovery application"requires-python = ">=3.12"dependencies = [+ "beautifulsoup4==4.15.0","fastapi==0.116.1",+ "feedparser==6.0.12","httpx==0.28.1",+ "pillow==12.3.0","pydantic==2.13.4","starlette==0.47.3","uvicorn==0.35.0",diff --git a/scripts/creator_boards.py b/scripts/creator_boards.pyindex e26c0255f..71939a270 100644--- a/scripts/creator_boards.py+++ b/scripts/creator_boards.py@@ -1,73 +1,60 @@#!/usr/bin/env python3-# -*- coding: utf-8 -*--r"""-创作者风格板 —— 把一位创作者名下多个视频的抽帧图各取一格,拼成一张 3x3。--为什么不直接读单个视频的抽帧图:一位创作者动辄几百条视频,逐条读不现实;-读单张又只代表一个片子。风格板从 9 个不同视频各取首格,一张图就能看出这位-创作者的稳定风格(拍摄场景、人数、镜头语言),归属也不会串。--抽帧图版式:宽固定 1440,3 列。横屏片一行(高 ~810),竖屏片三行(高 ~2544)。-据此推算单格高度后裁首格。--两种取帧来源:- * 默认用已生成的抽帧图裁首格,不产生任何网络流量。- * --from-video 在没有抽帧图时直接从视频取 1 帧。给 PikPak 用的:实测那边- 单帧 seek 要 25~40 秒(115 只要 0.4~1.4 秒),全量抽帧 9 帧/条要 14 天,- 而打标只需要"每位创作者 9 个采样",直接取帧便宜三个数量级。计费来源,- 必须显式加 --allow-metered。延迟型瓶颈,并发接近线性,默认开 16 路。--用法:- python scripts/creator_boards.py [--top N] [--per 9]- python scripts/creator_boards.py --from-video --allow-metered [--workers 16]-输出:- R:\peach-data\generated\boards\<序号>_<创作者>.jpg-"""+"""按创作者跨作品抽样并生成 3×3 风格板。"""from __future__ import annotations+import argparseimport collections-import concurrent.futures as cf+import concurrent.futures as futuresimport hashlib-import osimport randomimport reimport sqlite3import subprocess-import sysimport time+from pathlib import Path++from peach.config import DATABASE_PATH, FFMPEG_DIR, GENERATED_DIR, STATE_DIR+from peach.ffmpeg import FFmpegResolver+from peach.jobs import JobPolicyError, PidFileLock, SourceAccessPolicy, require_free_space+from peach.media import remap_managed_path+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description="生成创作者跨作品视觉风格板")+ parser.add_argument("--top", type=int, default=40)+ parser.add_argument("--per", type=int, default=9)+ parser.add_argument("--workers", type=int, default=16)+ parser.add_argument("--from-video", action="store_true")+ parser.add_argument("--location")+ parser.add_argument("--allow-metered", action="store_true")+ parser.add_argument("--min-free", type=float, default=40.0)+ parser.add_argument("--db", type=Path, default=DATABASE_PATH)+ parser.add_argument("--output-dir", type=Path, default=GENERATED_DIR / "boards")+ parser.add_argument("--snapshot-root", type=Path, default=GENERATED_DIR / "snapshots")+ parser.add_argument(+ "--legacy-snapshot-root",+ type=Path,+ default=Path(r"R:\Resources\Intake\snapshots"),+ )+ parser.add_argument("--lock", type=Path, default=STATE_DIR / ".creator-boards.lock")+ return parser+++def safe_name(name: str) -> str:+ return re.sub(r"[^\w\u4e00-\u9fff-]", "_", name)[:40]-DB = r"R:\peach-data\database\ledger.db"-OUTDIR = r"R:\peach-data\generated\boards"-FFMPEG = r"R:\peach-data\tools\ffmpeg\bin\ffmpeg.exe"-FFPROBE = r"R:\peach-data\tools\ffmpeg\bin\ffprobe.exe"--ARGV = sys.argv[1:]-TOP = int(ARGV[ARGV.index("--top") + 1]) if "--top" in ARGV else 40-PER = int(ARGV[ARGV.index("--per") + 1]) if "--per" in ARGV else 9-WORKERS = int(ARGV[ARGV.index("--workers") + 1]) if "--workers" in ARGV else 16-FROM_VIDEO = "--from-video" in ARGV-ALLOW_METERED = "--allow-metered" in ARGV-FRAME_CACHE = r"R:\peach-data\generated\boards\_frames"--LEGACY = r"R:\Resources\Intake\snapshots"-CURRENT = r"R:\peach-data\generated\snapshots"---def rebase(path: str) -> str:- return CURRENT + path[len(LEGACY):] if path.startswith(LEGACY) else path---def cell_height(path: str) -> int | None:- """抽帧图宽固定 1440 / 3 列;高 <1000 视为单行,否则按三行推算格高。- 返回 None 表示这张不是接触表(比如直接从视频取的单帧),整张用即可。- """- out = subprocess.run(- [FFPROBE, "-v", "error", "-select_streams", "v",- "-show_entries", "stream=width,height", "-of", "csv=p=0", path],- capture_output=True, text=True)+def cell_height(ffprobe: str, path: Path) -> int | None:+ result = subprocess.run(+ [+ ffprobe, "-v", "error", "-select_streams", "v",+ "-show_entries", "stream=width,height", "-of", "csv=p=0", str(path),+ ],+ capture_output=True,+ text=True,+ )try:- width, height = (int(x) for x in out.stdout.strip().split(","))+ width, height = (int(value) for value in result.stdout.strip().split(","))except ValueError:return Noneif width != 1440:@@ -75,154 +62,185 @@ def cell_height(path: str) -> int | None:return height if height < 1000 else height // 3-def safe(name: str) -> str:- return re.sub(r"[^\w\u4e00-\u9fff-]", "_", name)[:40]---def grab_frame(job: tuple[str, float]) -> str | None:- """\u4ece\u89c6\u9891\u53d6\u4e00\u5e27\u5b58\u8fdb\u7f13\u5b58\uff0c\u8fd4\u56de\u56fe\u7247\u8def\u5f84\u3002\u5df2\u7f13\u5b58\u5219\u76f4\u63a5\u8fd4\u56de\uff0c\u4e0d\u91cd\u590d\u8d70\u7f51\u7edc\u3002"""+def grab_frame(ffmpeg: str, cache: Path, job: tuple[str, float]) -> Path | None:path, duration = job- dst = os.path.join(FRAME_CACHE, hashlib.sha1(path.encode("utf-8", "ignore")).hexdigest()[:16] + ".jpg")- if os.path.exists(dst):- return dst+ destination = cache / (+ hashlib.sha1(path.encode("utf-8", "ignore")).hexdigest()[:16] + ".jpg"+ )+ if destination.is_file() and destination.stat().st_size > 0:+ return destinationseek = int((duration or 60) * 0.3)try:subprocess.run(- [FFMPEG, "-y", "-v", "error", "-ss", str(seek), "-i", path,- "-frames:v", "1", "-vf", "scale=480:-1", dst],- capture_output=True, timeout=240)+ [+ ffmpeg, "-y", "-v", "error", "-ss", str(seek), "-i", path,+ "-frames:v", "1", "-vf", "scale=480:-1", str(destination),+ ],+ capture_output=True,+ timeout=240,+ )except subprocess.TimeoutExpired:return None- return dst if os.path.exists(dst) and os.path.getsize(dst) > 0 else None---def build(paths: list[str], dst: str) -> bool:- """每张裁首格 → 统一装进 360x360 → 拼 3x3。"""- inputs, filters, labels = [], [], []- for src in paths:- ch = cell_height(src)- idx = len(labels)- inputs += ["-i", src]- # 接触表裁首格;直接取的单帧整张用- crop = f"crop=480:{ch}:0:0," if ch else ""+ return destination if destination.is_file() and destination.stat().st_size > 0 else None+++def build_board(ffmpeg: str, ffprobe: str, paths: list[Path], destination: Path) -> bool:+ inputs: list[str] = []+ filters: list[str] = []+ labels: list[str] = []+ for source in paths[:9]:+ height = cell_height(ffprobe, source)+ index = len(labels)+ inputs.extend(("-i", str(source)))+ crop = f"crop=480:{height}:0:0," if height else ""filters.append(- f"[{idx}:v]{crop}"- f"scale=360:360:force_original_aspect_ratio=decrease,"- f"pad=360:360:(ow-iw)/2:(oh-ih)/2:color=black[v{idx}]")- labels.append(f"[v{idx}]")- if len(labels) == 9:- break+ f"[{index}:v]{crop}scale=360:360:force_original_aspect_ratio=decrease,"+ f"pad=360:360:(ow-iw)/2:(oh-ih)/2:color=black[v{index}]"+ )+ labels.append(f"[v{index}]")if len(labels) < 4:return False- while len(labels) < 9: # 不足九格补黑,保持 3x3+ while len(labels) < 9:filters.append(f"color=c=black:s=360x360:d=1[v{len(labels)}]")labels.append(f"[v{len(labels)}]")- chain = ";".join(filters) + ";" + "".join(labels) + "xstack=inputs=9:layout=" + \- "|".join(f"{c*360}_{r*360}" for r in range(3) for c in range(3)) + "[out]"- run = subprocess.run(- [FFMPEG, "-y", "-v", "error", *inputs, "-filter_complex", chain,- "-map", "[out]", "-frames:v", "1", "-q:v", "4", dst],- capture_output=True, text=True)- if run.returncode != 0:- print(" ffmpeg:", run.stderr.strip()[:160])+ layout = "|".join(f"{column*360}_{row*360}" for row in range(3) for column in range(3))+ chain = ";".join(filters) + ";" + "".join(labels) + f"xstack=inputs=9:layout={layout}[out]"+ result = subprocess.run(+ [+ ffmpeg, "-y", "-v", "error", *inputs, "-filter_complex", chain,+ "-map", "[out]", "-frames:v", "1", "-q:v", "4", str(destination),+ ],+ capture_output=True,+ text=True,+ )+ if result.returncode != 0:+ print(" ffmpeg:", result.stderr.strip()[:160])return False- return os.path.exists(dst)---def from_video() -> int:- """给还没有抽帧图的创作者出板:每人抽 9 个视频各取 1 帧。"""- if not ALLOW_METERED:- print("拒绝:--from-video 会读云端视频,PikPak 是计费来源。确认要花流量再加 --allow-metered")- return 1- os.makedirs(OUTDIR, exist_ok=True)- os.makedirs(FRAME_CACHE, exist_ok=True)- conn = sqlite3.connect(f"file:{DB}?mode=ro", uri=True)- rows = conn.execute(- "SELECT creator, path, duration FROM asset WHERE medium='video' "+ return destination.is_file()+++def _readonly(db_path: Path) -> sqlite3.Connection:+ return sqlite3.connect(db_path.resolve().as_uri() + "?mode=ro", uri=True)+++def _existing_video_boards(output_dir: Path) -> set[str]:+ names = set()+ for path in output_dir.glob("v*_*.jpg"):+ match = re.match(r"^v\d+_(.+)_\d+\.jpg$", path.name)+ if match:+ names.add(match.group(1))+ return names+++def build_from_videos(args: argparse.Namespace, ffmpeg: str, ffprobe: str) -> int:+ require_free_space(Path("C:/"), args.min_free)+ source_sql, source_parameters = SourceAccessPolicy().sql_filter(+ args.location, args.allow_metered+ )+ frame_cache = args.output_dir / "_frames"+ frame_cache.mkdir(parents=True, exist_ok=True)+ connection = _readonly(args.db)+ rows = connection.execute(+ "SELECT creator,path,duration FROM asset WHERE medium='video' ""AND creator IS NOT NULL AND creator<>'' "- "AND id NOT IN (SELECT asset_id FROM asset_tag)").fetchall()- conn.close()+ "AND id NOT IN (SELECT asset_id FROM asset_tag)" + source_sql,+ source_parameters,+ ).fetchall()+ connection.close()by_creator: dict[str, list[tuple[str, float]]] = collections.defaultdict(list)for creator, path, duration in rows:by_creator[creator].append((path, duration or 60))+ ranked = sorted(by_creator.items(), key=lambda item: -len(item[1]))[:args.top]+ existing = _existing_video_boards(args.output_dir)+ ranked = [(creator, items) for creator, items in ranked if safe_name(creator) not in existing]+ print(f"待出板 {len(ranked)} 位;并发 {args.workers}")- ranked = sorted(by_creator.items(), key=lambda kv: -len(kv[1]))[:TOP]- done = {f.split("_", 1)[1].rsplit("_", 1)[0] for f in os.listdir(OUTDIR)- if f.endswith(".jpg")}- ranked = [(c, v) for c, v in ranked if safe(c) not in done]- print(f"待出板 {len(ranked)} 位,覆盖 {sum(len(v) for _, v in ranked)} 条待打标视频;"- f"并发 {WORKERS}")-- # 先把所有需要的帧一次性并发抓完 —— 逐个创作者串行会浪费掉并发jobs: list[tuple[str, float]] = []for creator, items in ranked:random.Random(creator).shuffle(items)- jobs += items[:PER]- print(f"需要 {len(jobs)} 帧,单帧实测 25~40 秒,预计 {len(jobs)*32/WORKERS/60:.0f} 分钟")-- got: dict[tuple[str, float], str] = {}- t0 = time.time()- with cf.ThreadPoolExecutor(WORKERS) as pool:- for i, (job, out) in enumerate(zip(jobs, pool.map(grab_frame, jobs)), 1):- if out:- got[job] = out- if i % 25 == 0:- rate = i / max(time.time() - t0, 1) * 60- print(f" {i}/{len(jobs)} 帧 成功 {len(got)} {rate:.1f} 帧/分 "- f"剩 {(len(jobs)-i)/max(rate,0.1):.0f} 分钟", flush=True)+ jobs.extend(items[:args.per])+ captured: dict[tuple[str, float], Path] = {}+ started = time.time()+ with futures.ThreadPoolExecutor(args.workers) as pool:+ outputs = pool.map(lambda job: grab_frame(ffmpeg, frame_cache, job), jobs)+ for index, (job, output) in enumerate(zip(jobs, outputs), 1):+ if output:+ captured[job] = output+ if index % 25 == 0:+ rate = index / max(time.time() - started, 1) * 60+ print(f" {index}/{len(jobs)} 帧 成功 {len(captured)} {rate:.1f} 帧/分", flush=True)made = 0for rank, (creator, items) in enumerate(ranked, 1):- frames = [got[j] for j in items[:PER] if j in got]+ frames = [captured[job] for job in items[:args.per] if job in captured]if len(frames) < 4:print(f" {rank:>2}. {creator[:26]:<26} 可用帧仅 {len(frames)},跳过")continue- dst = os.path.join(OUTDIR, f"v{rank:02d}_{safe(creator)}_{len(items)}.jpg")- if build(frames, dst):+ destination = args.output_dir / f"v{rank:02d}_{safe_name(creator)}_{len(items)}.jpg"+ if build_board(ffmpeg, ffprobe, frames, destination):made += 1- print(f" {rank:>2}. {creator[:26]:<26} 视频{len(items):>4} 帧{len(frames)} → {os.path.basename(dst)}")- print(f"\n生成 {made} 张 → {OUTDIR}")+ print(f" {rank:>2}. {creator[:26]:<26} 视频{len(items):>4} 帧{len(frames)} → {destination.name}")+ print(f"生成 {made} 张 → {args.output_dir}")return 0-def main() -> int:- if FROM_VIDEO:- return from_video()- os.makedirs(OUTDIR, exist_ok=True)- conn = sqlite3.connect(f"file:{DB}?mode=ro", uri=True)- rows = conn.execute(- "SELECT creator, snapshot_path FROM asset WHERE medium='video' "+def build_from_snapshots(args: argparse.Namespace, ffmpeg: str, ffprobe: str) -> int:+ connection = _readonly(args.db)+ rows = connection.execute(+ "SELECT creator,snapshot_path FROM asset WHERE medium='video' ""AND creator IS NOT NULL AND creator<>'' AND snapshot_path IS NOT NULL "- "AND id NOT IN (SELECT asset_id FROM asset_tag)").fetchall()+ "AND id NOT IN (SELECT asset_id FROM asset_tag)"+ ).fetchall()counts = collections.Counter(- r[0] for r in conn.execute(+ row[0] for row in connection.execute("SELECT creator FROM asset WHERE medium='video' AND creator IS NOT NULL "- "AND creator<>'' AND id NOT IN (SELECT asset_id FROM asset_tag)"))- conn.close()-- by_creator: dict[str, list[str]] = collections.defaultdict(list)- for creator, snap in rows:- path = rebase(snap)- if os.path.exists(path):+ "AND creator<>'' AND id NOT IN (SELECT asset_id FROM asset_tag)"+ )+ )+ connection.close()+ by_creator: dict[str, list[Path]] = collections.defaultdict(list)+ for creator, snapshot in rows:+ path = remap_managed_path(snapshot, args.snapshot_root, (args.legacy_snapshot_root,))+ if path.is_file():by_creator[creator].append(path)-- ranked = [(c, n) for c, n in counts.most_common() if len(by_creator.get(c, [])) >= 4][:TOP]- print(f"可出板创作者 {len(ranked)} 位,覆盖无标签视频 {sum(n for _, n in ranked)} 条")-+ ranked = [(creator, count) for creator, count in counts.most_common() if len(by_creator.get(creator, [])) >= 4][:args.top]+ print(f"可出板创作者 {len(ranked)} 位,覆盖无标签视频 {sum(count for _, count in ranked)} 条")made = 0- for rank, (creator, n) in enumerate(ranked, 1):- pool = by_creator[creator]- random.Random(creator).shuffle(pool)- dst = os.path.join(OUTDIR, f"{rank:02d}_{safe(creator)}_{n}.jpg")- if build(pool[:PER], dst):+ for rank, (creator, count) in enumerate(ranked, 1):+ candidates = by_creator[creator]+ random.Random(creator).shuffle(candidates)+ destination = args.output_dir / f"{rank:02d}_{safe_name(creator)}_{count}.jpg"+ if build_board(ffmpeg, ffprobe, candidates[:args.per], destination):made += 1- print(f" {rank:>2}. {creator[:26]:<26} 视频{n:>4} 取样{min(len(pool), PER)} → {os.path.basename(dst)}")- else:- print(f" {rank:>2}. {creator[:26]:<26} 视频{n:>4} 失败")- print(f"\n生成 {made} 张 → {OUTDIR}")+ print(f" {rank:>2}. {creator[:26]:<26} 视频{count:>4} 取样{min(len(candidates), args.per)} → {destination.name}")+ print(f"生成 {made} 张 → {args.output_dir}")return 0+def run(args: argparse.Namespace) -> int:+ if args.top < 1 or args.per < 4 or args.workers < 1:+ raise SystemExit("top/workers 必须大于 0,per 至少为 4")+ resolver = FFmpegResolver(FFMPEG_DIR)+ ffmpeg = resolver.ffmpeg()+ ffprobe = resolver.ffprobe()+ if ffmpeg is None or ffprobe is None:+ raise RuntimeError("ffmpeg/ffprobe unavailable")+ args.output_dir.mkdir(parents=True, exist_ok=True)+ if args.from_video:+ return build_from_videos(args, str(ffmpeg.path), str(ffprobe.path))+ return build_from_snapshots(args, str(ffmpeg.path), str(ffprobe.path))+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ try:+ with PidFileLock(args.lock):+ return run(args)+ except JobPolicyError as exc:+ print(f"[stop] {exc}")+ return exc.exit_code++if __name__ == "__main__":raise SystemExit(main())diff --git a/scripts/find_ads.py b/scripts/find_ads.pynew file mode 100644index 000000000..e70ffe018--- /dev/null+++ b/scripts/find_ads.py@@ -0,0 +1,164 @@+#!/usr/bin/env python3+# -*- coding: utf-8 -*-+r"""+广告文件识别 —— 找出盗版组塞进资源包里的推广视频,出清单供人工处置。++不删任何东西,只出 CSV。判据来自实际样本 B:\创作者\BNST033\aaxv.xyz-BNST033\:+正片 BNST033.mp4 有 3.2 GB,旁边躺着一堆 10.9 MB / 37.40 秒**逐字节等长等时**的+"催眠(1..N).mp4",外加 論壇文宣\ 和 1024\ 两个子目录。++三条判据,各自独立记分,命中越多越可信:+ A 目录名自曝:文宣 / 宣傳 / 廣告 / 1024 / 論壇 等+ B 同目录内体积与时长完全相同的一组小短片(正片不会出现这种整齐的重复)+ C 文件名里的手游推广词与推广站域名++B 是主力:它不依赖任何关键词,纯靠"广告是同一个文件复制多份"的结构特征。+故意不把"短"或"小"单独当判据 —— 库里 8710 条 20 秒内的视频绝大多数是正常短片。++用法:+ python scripts/find_ads.py [--min-group 3]+输出:+ R:\peach-data\generated\ad-candidates.csv+"""+from __future__ import annotations++import collections+import argparse+import csv+import os+import re+import sqlite3+from pathlib import Path++from peach.config import DATABASE_PATH, GENERATED_DIR++DEFAULT_OUTPUT = GENERATED_DIR / "ad-candidates.csv"++# A:目录名自曝。整段路径分量匹配,不做子串 ——+# "1024" 当子串会吃掉 FC2-PPV-1381024 这种正片番号(实测误伤 970 MB 一条)。+RE_ADDIR = re.compile(r"(論壇文宣|论坛文宣|文宣|宣傳|宣传|廣告|广告|推廣|推广|"+ r"發佈頁|发布页|禮包碼|礼包码|地址发布|免费预览)", re.I)+RE_ADDIR_EXACT = re.compile(r"^(1024|論壇|论坛|廣告|广告|文宣)$", re.I)++# C:只认推广站域名。"成人游戏""加微信"这类词单独出现不算 ——+# 实测正片标题里就有("兄妹成人游戏" 9.98 GB、"花了三萬加微信約出來的女主播"),+# 拿它当判据会把正片当广告删掉。+RE_ADNAME = re.compile(+ r"([0-9a-z]{1,8}\.(?:18my|gm\d?|gg\d?|hgame\d?)\.(?:cc|xyz|com|net|app)|"+ r"\b(?:18my|hgame\d?|[0-9a-z]{2,6}(?:gm|gg))\.(?:cc|xyz|com|net|app)|"+ r"(?:全網最火爆|全网最火爆|開後宮|开后宫)[^.]{0,12}(?:遊戲|游戏|手遊|手游))", re.I)++# D:文件名里带任意站点域名。单靠这个不能判 —— 库里 73 条带域名的视频里,+# legalporno.com / hhd800.com@259LUXU / nyap2p.com / fuckbe.com 那些是 0.8~6.4 GB+# 的正片,域名只是片源水印。真广告全是又小又短的,所以必须叠加体积时长门槛。+RE_ANYDOMAIN = re.compile(+ r"\b[0-9a-z][-0-9a-z]{1,20}\.(?:cc|xyz|com|net|la|me|top|vip|club|app|cn|pw|tv|gg)\b", re.I)+# 域名旁边有没有推广文案,是"广告"和"正片被打了站点水印"的分界线。+# 实测 jitumi.pw(1).avi 抽帧是体操服正片,光有裸域名不能判广告。+RE_ADCOPY = re.compile(+ r"(手遊|手游|遊戲大全|游戏大全|在線觀看|在线观看|在線視頻|在线视频|賭場|赌场|"+ r"約炮|约炮|女神檔案|女神档案|精彩直播|大秀直播|禮包碼|礼包码|"+ r"最新地址|開車地址|开车地址|徵信|征信|借貸|借贷)", re.I)++# B 的边界:只有"小且短"的整齐重复才算广告,避免误伤分集正片+MAX_AD_MB = 80+MAX_AD_SEC = 180+# D 的边界:正片再短也很少低于这个量级+DOMAIN_AD_SEC = 150+DOMAIN_AD_MB = 220++FIELDS = ["id", "location", "dir", "name", "size_mb", "duration",+ "confidence", "score", "hits", "group_n"]+++def find_candidates(db_path: Path | str, min_group: int = 3) -> tuple[list[dict], int]:+ """只读 ledger 并返回复核候选;不写数据库或文件。"""+ db_path = Path(db_path)+ conn = sqlite3.connect(db_path.resolve().as_uri() + "?mode=ro", uri=True)+ rows = conn.execute(+ "SELECT id, location, path, name, size, duration FROM asset "+ "WHERE medium='video'").fetchall()+ conn.close()+ # B:同目录内 (size, duration) 完全相同的成组小短片+ buckets: dict[tuple[str, int, str], list] = collections.defaultdict(list)+ for aid, loc, path, name, size, duration in rows:+ if not size or not duration:+ continue+ if size > MAX_AD_MB * 1048576 or duration > MAX_AD_SEC:+ continue+ key = (os.path.dirname(path).lower(), size, f"{duration:.3f}")+ buckets[key].append((aid, loc, path, name, size, duration))+ grouped = {}+ for items in buckets.values():+ if len(items) >= min_group:+ for it in items:+ grouped[it[0]] = len(items)++ plan = []+ for aid, loc, path, name, size, duration in rows:+ directory = os.path.dirname(path)+ parts = directory.split(os.sep)+ hits = []+ if RE_ADDIR.search(directory) or any(RE_ADDIR_EXACT.match(p) for p in parts):+ hits.append("目录名")+ if RE_ADNAME.search(name) or RE_ADNAME.search(directory):+ hits.append("推广词")+ if aid in grouped:+ hits.append(f"等长重复x{grouped[aid]}")+ small = (size or 0) <= DOMAIN_AD_MB * 1048576+ short = duration is not None and 0 < duration <= DOMAIN_AD_SEC+ if RE_ANYDOMAIN.search(name) and small and short:+ hits.append("域名+文案" if RE_ADCOPY.search(name) else "裸域名")+ if not hits:+ continue+ # 只有裸域名、没有任何其它佐证的,交人工看一眼再定+ solid = [h for h in hits if h != "裸域名"]+ plan.append({+ "id": aid, "location": loc, "dir": directory, "name": name,+ "size_mb": round((size or 0) / 1048576, 1),+ "duration": round(duration, 1) if duration else "",+ "confidence": "确认" if solid else "存疑",+ "score": len(hits), "hits": "+".join(hits),+ "group_n": grouped.get(aid, ""),+ })++ plan.sort(key=lambda r: (r["confidence"] != "确认", -r["score"], r["dir"]))+ return plan, len(rows)+++def write_candidates(output: Path | str, plan: list[dict]) -> None:+ output = Path(output)+ output.parent.mkdir(parents=True, exist_ok=True)+ with output.open("w", encoding="utf-8-sig", newline="") as fh:+ writer = csv.DictWriter(fh, fieldnames=FIELDS)+ writer.writeheader()+ writer.writerows(plan)+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description="生成广告文件人工复核清单")+ parser.add_argument("--db", type=Path, default=DATABASE_PATH)+ parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)+ parser.add_argument("--min-group", type=int, default=3)+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ if args.min_group < 2:+ raise SystemExit("--min-group 必须至少为 2")+ plan, scanned = find_candidates(args.db, args.min_group)+ print(f"扫描 {scanned} 条视频")+ write_candidates(args.output, plan)++ print(f"命中 {len(plan)} 条,合计 {sum(r['size_mb'] for r in plan)/1024:.1f} GB")+ for level in ("确认", "存疑"):+ sub = [r for r in plan if r["confidence"] == level]+ print(f" {level}: {len(sub):>4} 条 {sum(r['size_mb'] for r in sub)/1024:>6.2f} GB")+ print(f"\n判据分布: {collections.Counter(r['hits'] for r in plan).most_common(6)}")+ print(f"→ {args.output}(仅清单,未删任何文件)")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/import_stash_entities.py b/scripts/import_stash_entities.pyindex ae3c0d77d..adee36288 100644--- a/scripts/import_stash_entities.py+++ b/scripts/import_stash_entities.py@@ -7,16 +7,19 @@ Dry-run is the default and applying requires a SQLite backup.from __future__ import annotationsimport argparse+import ioimport jsonimport reimport sqlite3-import struct-import urllib.requestfrom datetime import datetime, timezonefrom pathlib import Pathfrom urllib.parse import urlsplit+import httpx+from PIL import Image, UnidentifiedImageError+from peach.config import DATABASE_PATH, GENERATED_DIR+from peach.http import HttpRequest, HttpTransport, HttpxTransportfrom peach.migrations import sqlite_backupfrom peach.stash import StashClient@@ -134,67 +137,71 @@ def apply(connection: sqlite3.Connection, rows: list[dict]) -> dict:return counts+def inspect_image(data: bytes) -> tuple[tuple[int, int], str] | None:+ """由 Pillow 验证完整 raster,并从解码格式确定 MIME;SVG/损坏数据拒绝。"""+ try:+ with Image.open(io.BytesIO(data)) as image:+ size = image.size+ image_format = (image.format or "").upper()+ image.verify()+ except (OSError, UnidentifiedImageError, Image.DecompressionBombError):+ return None+ content_type = {"JPEG": "image/jpeg", "PNG": "image/png"}.get(image_format)+ return (size, content_type) if content_type else None++def image_size(data: bytes) -> tuple[int, int] | None:- if data.startswith(b"\x89PNG\r\n\x1a\n") and len(data) >= 24:- return struct.unpack(">II", data[16:24])- if data.startswith(b"\xff\xd8"):- offset = 2- while offset + 9 < len(data):- if data[offset] != 0xFF:- offset += 1- continue- marker = data[offset + 1]- offset += 2- if marker in {0xD8, 0xD9}:- continue- if offset + 2 > len(data):- break- length = int.from_bytes(data[offset:offset + 2], "big")- if marker in {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7,- 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF} and offset + 7 <= len(data):- return (int.from_bytes(data[offset + 5:offset + 7], "big"),- int.from_bytes(data[offset + 3:offset + 5], "big"))- offset += max(length, 2)- return None---def cache_images(rows: list[dict], destination: Path, minimum_short_side: int = 512) -> dict:+ inspected = inspect_image(data)+ return inspected[0] if inspected else None+++def cache_images(+ rows: list[dict],+ destination: Path,+ minimum_short_side: int = 512,+ transport: HttpTransport | None = None,+) -> dict:destination.mkdir(parents=True, exist_ok=True)result = {"cached": 0, "too_small": 0, "placeholder_or_invalid": 0, "failed": 0}- for row in rows:- if not row["has_real_image"]:- continue- url = row["image_url"]- parsed = urlsplit(url)- if parsed.hostname not in {"127.0.0.1", "localhost", "::1"}:- result["failed"] += 1- continue- try:- with urllib.request.urlopen(url, timeout=20) as response:- content_type = response.headers.get_content_type()- data = response.read(10 * 1024 * 1024 + 1)- size = image_size(data)- if content_type not in {"image/jpeg", "image/png"} or not size or len(data) > 10 * 1024 * 1024:- result["placeholder_or_invalid"] += 1+ owns_transport = transport is None+ http = transport or HttpxTransport()+ try:+ for row in rows:+ if not row["has_real_image"]:continue- if min(size) < minimum_short_side:- result["too_small"] += 1+ url = row["image_url"]+ parsed = urlsplit(url)+ if parsed.hostname not in {"127.0.0.1", "localhost", "::1"}:+ result["failed"] += 1continue- target = destination / f"performer-{row['entity_id']}.img"- temporary = target.with_suffix(".tmp")- temporary.write_bytes(data)- temporary.replace(target)- Path(str(target) + ".ct").write_text(content_type + "\n", encoding="utf-8", newline="\n")- Path(str(target) + ".provenance.json").write_text(json.dumps({- "source": "Stash public performer adapter",- "stash_performer_id": row["stash_id"],- "cached_at": datetime.now(timezone.utc).isoformat(),- "width": size[0], "height": size[1],- "upstream_url": "local-stash-performer-endpoint",- }, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", newline="\n")- result["cached"] += 1- except (OSError, ValueError):- result["failed"] += 1+ try:+ response = http(HttpRequest("GET", url, {"Accept": "image/*"}), 20, 10 * 1024 * 1024)+ inspected = inspect_image(response.body)+ if response.status != 200 or not inspected or len(response.body) > 10 * 1024 * 1024:+ result["placeholder_or_invalid"] += 1+ continue+ size, content_type = inspected+ if min(size) < minimum_short_side:+ result["too_small"] += 1+ continue+ target = destination / f"performer-{row['entity_id']}.img"+ temporary = target.with_suffix(".tmp")+ temporary.write_bytes(response.body)+ temporary.replace(target)+ Path(str(target) + ".ct").write_text(content_type + "\n", encoding="utf-8", newline="\n")+ Path(str(target) + ".provenance.json").write_text(json.dumps({+ "source": "Stash public performer adapter",+ "stash_performer_id": row["stash_id"],+ "cached_at": datetime.now(timezone.utc).isoformat(),+ "width": size[0], "height": size[1],+ "upstream_url": "local-stash-performer-endpoint",+ }, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", newline="\n")+ result["cached"] += 1+ except (httpx.HTTPError, OSError, ValueError):+ result["failed"] += 1+ finally:+ if owns_transport and isinstance(http, HttpxTransport):+ http.close()return resultdiff --git a/scripts/probe.py b/scripts/probe.pyindex 80e64df27..fe5d8449c 100644--- a/scripts/probe.py+++ b/scripts/probe.py@@ -1,229 +1,189 @@#!/usr/bin/env python3-# -*- coding: utf-8 -*--"""-全库 ffprobe —— 无人值守。给 ledger 里的视频补事实层与情境层。--设计成可以关掉终端、跑几个小时、随时中断重启:- * 只处理 duration IS NULL 的记录,所以重启即续跑,不重复劳动- * 多线程(默认 6),每完成一批就提交,进程被杀也不丢进度- * 全部输出写日志文件,不依赖终端- * 对网盘限速(每个请求间隔 workers*interval),避免触发 115 风控- * 单个文件超时 60s 直接跳过并标记,不卡住整体--用法(双击 run-probe.cmd 即可,或):- python scripts/probe.py [--workers 6] [--location 115] [--interval 0.15] [--limit N]-"""-import os, sys, time, json, sqlite3, subprocess, threading, queue--from peach.config import FFMPEG_DIR+"""全库 ffprobe:可续跑、单写者、显式计费授权。"""+from __future__ import annotations++import argparse+import json+import queue+import sqlite3+import subprocess+import threading+import time+from pathlib import Path++from peach.config import DATABASE_PATH, FFMPEG_DIR, LOG_DIR, STATE_DIRfrom peach.ffmpeg import FFmpegResolver--DB = r"R:\peach-data\database\ledger.db"-_FFPROBE_CHOICE = FFmpegResolver(FFMPEG_DIR).ffprobe()-if _FFPROBE_CHOICE is None:- raise RuntimeError("ffprobe is unavailable; install it under Peach data tools or PATH")-FFPROBE = str(_FFPROBE_CHOICE.path)-LOG = r"R:\peach-data\logs\probe-{}.log".format(time.strftime("%Y%m%d-%H%M%S"))--a = sys.argv[1:]-def opt(name, default, cast=str):- return cast(a[a.index(name) + 1]) if name in a else default-WORKERS = opt("--workers", 6, int)-LOCATION = opt("--location", None)-INTERVAL = opt("--interval", 0.15, float)-LIMIT = opt("--limit", 0, int)--# ---------- 单实例保护 -----------# 多个实例同时跑会互抢 SQLite 写锁,全部卡死(实测踩过:三个实例并存时 ffprobe 数归零)-LOCKFILE = r"R:\peach-data\state\.probe.lock"-try:- _lock = open(LOCKFILE, "x")- _lock.write(str(os.getpid()))- _lock.flush()-except FileExistsError:- try:- old = open(LOCKFILE).read().strip()- alive = subprocess.run(["tasklist", "/FI", f"PID eq {old}"],- capture_output=True, text=True, errors="ignore").stdout- if old and old in alive:- print(f"已有实例在跑(PID {old}),退出。要强制重来请删除 {LOCKFILE}")- sys.exit(0)- except Exception:- pass- os.remove(LOCKFILE)- _lock = open(LOCKFILE, "x"); _lock.write(str(os.getpid())); _lock.flush()--import atexit-def _unlock():- try:- _lock.close()- except Exception:- pass- try:- os.remove(LOCKFILE)- except OSError:- pass-atexit.register(_unlock)--logf = open(LOG, "w", encoding="utf-8", buffering=1)-# 必须是 RLock:worker 在持有锁的情况下调用 log(),而 log() 内部还要再拿一次锁。-# 普通 Lock 不可重入,会让第一个触发日志的 worker 自锁死,其余 worker 全部堵在同一把锁上,-# 表现为「进程活着、CPU 接近 0、ffprobe 子进程数为 0、日志不推进」—— 排查了很久才定位。-lock = threading.RLock()-def log(s):- with lock:- line = f"[{time.strftime('%H:%M:%S')}] {s}"- print(line, flush=True); logf.write(line + "\n")--def ctx_of(w, h, dur):- orient = quality = length = None- if w and h:- orient = "竖屏" if h > w else "横屏"- m = max(w, h)- quality = ("4K" if m >= 3000 else "2K" if m >= 1900 else "1080P" if m >= 1300- else "720P" if m >= 900 else "低画质")- if dur:- length = "速食" if dur < 300 else "短" if dur < 900 else "中" if dur < 2400 else "长"- return length, orient, quality--def probe(path):- """只读第一条视频流的指定字段。- 实测:不加 -select_streams 的完整 -show_streams 要 0.6~9.6 秒(ffprobe 会深度探测所有流),- 限定后降到 0.04~0.07 秒,快 20~160 倍。音轨检测另算约 1 秒/文件,不值得,留空后续按需补。"""- # -rw_timeout:网络读卡住时提前放弃(微秒)。坏文件卡满超时是吞吐的头号杀手:- # 实测 50 个里 4 个坏文件各占满 60 秒,12 个 worker 长期有几个被占着,整体降到 16 个/分钟。- r = subprocess.run(- [FFPROBE, "-v", "error", "-rw_timeout", "8000000",- "-select_streams", "v:0",- "-show_entries", "format=duration:stream=width,height,codec_name,avg_frame_rate",- "-of", "json", path],- capture_output=True, timeout=20)- j = json.loads(r.stdout or b"{}")- dur = float((j.get("format") or {}).get("duration") or 0)- st = (j.get("streams") or [{}])[0]+from peach.jobs import JobPolicyError, PidFileLock, SourceAccessPolicy, require_free_space+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description="补全视频事实层和情境层")+ parser.add_argument("--workers", type=int, default=6)+ parser.add_argument("--location")+ parser.add_argument("--interval", type=float, default=0.15)+ parser.add_argument("--limit", type=int, default=0)+ parser.add_argument("--min-free", type=float, default=40.0)+ parser.add_argument("--allow-metered", action="store_true")+ parser.add_argument("--db", type=Path, default=DATABASE_PATH)+ parser.add_argument("--log-dir", type=Path, default=LOG_DIR)+ parser.add_argument("--lock", type=Path, default=STATE_DIR / ".probe.lock")+ return parser+++def context_fields(width: int, height: int, duration: float) -> tuple[str | None, str | None, str | None]:+ orientation = quality = length = None+ if width and height:+ orientation = "竖屏" if height > width else "横屏"+ longest = max(width, height)+ quality = (+ "4K" if longest >= 3000 else "2K" if longest >= 1900+ else "1080P" if longest >= 1300 else "720P" if longest >= 900+ else "低画质"+ )+ if duration:+ length = "速食" if duration < 300 else "短" if duration < 900 else "中" if duration < 2400 else "长"+ return length, orientation, quality+++def probe_file(ffprobe: str, path: str) -> tuple:+ result = subprocess.run(+ [+ ffprobe, "-v", "error", "-rw_timeout", "8000000",+ "-select_streams", "v:0", "-show_entries",+ "format=duration:stream=width,height,codec_name,avg_frame_rate",+ "-of", "json", path,+ ],+ capture_output=True,+ timeout=20,+ )+ payload = json.loads(result.stdout or b"{}")+ duration = float((payload.get("format") or {}).get("duration") or 0)+ stream = (payload.get("streams") or [{}])[0]fps = 0.0try:- n, d = (st.get("avg_frame_rate") or "0/1").split("/")- fps = float(n) / float(d) if float(d) else 0.0- except Exception:+ numerator, denominator = (stream.get("avg_frame_rate") or "0/1").split("/")+ fps = float(numerator) / float(denominator) if float(denominator) else 0.0+ except (TypeError, ValueError, ZeroDivisionError):pass- return dur, int(st.get("width") or 0), int(st.get("height") or 0), st.get("codec_name"), fps, None--# ---------- 取任务 -----------c = sqlite3.connect(DB)-# -- 磁盘闸门(2026-08-14 加)---------------------------------# 教训:这些任务读网盘会把块缓存写到 CloudDrive.WinUI\file_buffer_cache。-# 跑了一整天后该目录涨到 910 GB(配置上限写的 32 GB,LRU 没拦住),-# C 盘从 22 GB 可用掉到 0.1 GB,我全程没发现,是用户报错才查出来。-# 所以:启动前检查,低于阈值直接拒绝。-import shutil as _sh-MIN_FREE_GB = float(sys.argv[sys.argv.index("--min-free") + 1]) if "--min-free" in sys.argv else 40.0-def _free_gb(drive="C:" + chr(92)):- try:- return _sh.disk_usage(drive).free / 1024**3- except Exception:- return 999.0-def disk_guard():- f = _free_gb()- if f < MIN_FREE_GB:- print("[stop] C 盘仅剩 %.1f GB(阈值 %.0f GB)—— 拒绝启动。"- "先清 CloudDrive 的 file_buffer_cache" % (f, MIN_FREE_GB))- return False- return True-if not disk_guard():- sys.exit(3)-# -------------------------------------------------------------# ── 计费来源闸门(2026-08-14 加)──────────────────────────────-# 教训:这两个脚本不带 --location 启动了一次,覆盖到 PikPak,-# 11 小时烧掉 677 GB 代理流量。知道要限制、脚本也支持,就是启动时没加。-# 所以把限制写死:默认拒绝计费来源,要跑必须显式 --allow-metered。-METERED = {"pikpak", "online"}-ALLOW_METERED = "--allow-metered" in sys.argv-if not LOCATION:- LOCATION = None-if not ALLOW_METERED:- _excl = " AND location NOT IN ('" + "','".join(sorted(METERED)) + "')"- if LOCATION in METERED:- print(f"拒绝:{LOCATION} 是计费来源。确认要花流量再加 --allow-metered")- sys.exit(2)-else:- _excl = ""- print("⚠️ 已开启 --allow-metered:将读取 PikPak,产生计费流量")-# ─────────────────────────────────────────────────────────────--sql = ("SELECT id,path FROM asset WHERE medium='video' AND duration IS NULL "- "AND location != 'online'")-if LOCATION:- sql += f" AND location='{LOCATION}'"-sql += _excl-# 从小到大:大文件的 moov 常在末尾,要多一次网络往返;小文件先做能更快出成果。-# 实测这是延迟受限而非带宽受限的任务(115 单次 0.87s / PikPak 1.56s),所以并发几乎线性加速。-sql += " ORDER BY size ASC"-if LIMIT:- sql += f" LIMIT {LIMIT}"-tasks = c.execute(sql).fetchall()-c.close()-total = len(tasks)-log(f"待处理 {total:,} 个视频 workers={WORKERS} interval={INTERVAL}s 日志={LOG}")-if not total:- log("没有待处理项,退出"); sys.exit(0)--q = queue.Queue()-for t in tasks: q.put(t)-results = queue.Queue()-done = [0]; failed = [0]; t0 = time.time()--def worker():- while True:- try:- aid, path = q.get_nowait()- except queue.Empty:- return- try:- dur, w, h, vc, fps, au = probe(path)- L, O, Q = ctx_of(w, h, dur)- results.put((dur, w, h, vc, fps, au, L, O, Q, aid))- except Exception as e:- results.put((-1, 0, 0, None, 0, 0, None, None, None, aid))- with lock: failed[0] += 1- finally:+ return (+ duration,+ int(stream.get("width") or 0),+ int(stream.get("height") or 0),+ stream.get("codec_name"),+ fps,+ None,+ )+++def run(args: argparse.Namespace) -> int:+ if args.workers < 1 or args.interval < 0 or args.limit < 0:+ raise SystemExit("workers 必须大于 0;interval/limit 不能为负数")+ choice = FFmpegResolver(FFMPEG_DIR).ffprobe()+ if choice is None:+ raise RuntimeError("ffprobe unavailable")+ require_free_space(Path("C:/"), args.min_free)+ source_sql, source_parameters = SourceAccessPolicy().sql_filter(+ args.location, args.allow_metered+ )++ args.log_dir.mkdir(parents=True, exist_ok=True)+ log_path = args.log_dir / f"probe-{time.strftime('%Y%m%d-%H%M%S')}.log"+ lock = threading.RLock()+ with log_path.open("w", encoding="utf-8", buffering=1) as log_file:+ def log(message: str) -> None:with lock:- done[0] += 1- if done[0] % 50 == 0:- el = time.time() - t0- rate = done[0] / el if el else 0- eta = (total - done[0]) / rate / 60 if rate else 0- log(f"{done[0]:,}/{total:,} 失败 {failed[0]} "- f"{rate:.1f} 个/秒 预计剩余 {eta:.0f} 分钟")- time.sleep(INTERVAL)--threads = [threading.Thread(target=worker, daemon=True) for _ in range(WORKERS)]-for t in threads: t.start()--# 主线程负责写库(sqlite 单写者)-conn = sqlite3.connect(DB, timeout=120)-conn.execute("PRAGMA journal_mode=WAL") # 允许读者与写者并存,status/suggest 可随时查-conn.execute("PRAGMA busy_timeout=120000")-buf = []-UP = """UPDATE asset SET duration=?,width=?,height=?,vcodec=?,fps=?,has_audio=?,- ctx_length=?,ctx_orient=?,ctx_quality=? WHERE id=?"""-while any(t.is_alive() for t in threads) or not results.empty():+ line = f"[{time.strftime('%H:%M:%S')}] {message}"+ print(line, flush=True)+ log_file.write(line + "\n")++ if args.allow_metered:+ log("已显式允许计费来源")+ connection = sqlite3.connect(args.db)+ sql = (+ "SELECT id,path FROM asset WHERE medium='video' AND duration IS NULL "+ "AND location != 'online'" + source_sql + " ORDER BY size ASC"+ )+ parameters: tuple[object, ...] = source_parameters+ if args.limit:+ sql += " LIMIT ?"+ parameters += (args.limit,)+ tasks = connection.execute(sql, parameters).fetchall()+ connection.close()+ total = len(tasks)+ log(f"待处理 {total:,} 个视频 workers={args.workers} interval={args.interval}s 日志={log_path}")+ if not total:+ return 0++ pending: queue.Queue = queue.Queue()+ results: queue.Queue = queue.Queue()+ for task in tasks:+ pending.put(task)+ counters = {"done": 0, "failed": 0}+ started = time.time()++ def worker() -> None:+ while True:+ try:+ asset_id, path = pending.get_nowait()+ except queue.Empty:+ return+ try:+ duration, width, height, codec, fps, audio = probe_file(str(choice.path), path)+ length, orientation, quality = context_fields(width, height, duration)+ results.put((duration, width, height, codec, fps, audio, length, orientation, quality, asset_id))+ except Exception:+ results.put((-1, 0, 0, None, 0, 0, None, None, None, asset_id))+ with lock:+ counters["failed"] += 1+ finally:+ with lock:+ counters["done"] += 1+ if counters["done"] % 50 == 0:+ elapsed = time.time() - started+ rate = counters["done"] / elapsed if elapsed else 0+ eta = (total - counters["done"]) / rate / 60 if rate else 0+ log(f"{counters['done']:,}/{total:,} 失败 {counters['failed']} {rate:.1f} 个/秒 剩余 {eta:.0f} 分钟")+ time.sleep(args.interval)++ threads = [threading.Thread(target=worker, daemon=True) for _ in range(args.workers)]+ for thread in threads:+ thread.start()++ connection = sqlite3.connect(args.db, timeout=120)+ connection.execute("PRAGMA journal_mode=WAL")+ connection.execute("PRAGMA busy_timeout=120000")+ update = (+ "UPDATE asset SET duration=?,width=?,height=?,vcodec=?,fps=?,has_audio=?,"+ "ctx_length=?,ctx_orient=?,ctx_quality=? WHERE id=?"+ )+ buffer = []+ while any(thread.is_alive() for thread in threads) or not results.empty():+ try:+ buffer.append(results.get(timeout=2))+ except queue.Empty:+ pass+ if len(buffer) >= 25:+ connection.executemany(update, buffer)+ connection.commit()+ buffer.clear()+ if buffer:+ connection.executemany(update, buffer)+ connection.commit()+ elapsed = time.time() - started+ log(f"完成 {counters['done']:,} 个,失败 {counters['failed']},耗时 {elapsed/60:.1f} 分钟")+ connection.close()+ return 0+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)try:- buf.append(results.get(timeout=2))- except queue.Empty:- pass- if len(buf) >= 25: # 批次小一点,进度可见,也降低写锁持有时间- conn.executemany(UP, buf); conn.commit(); buf.clear()-if buf:- conn.executemany(UP, buf); conn.commit()--el = time.time() - t0-log(f"完成 {done[0]:,} 个,失败 {failed[0]},耗时 {el/60:.1f} 分钟")-row = conn.execute("""SELECT ctx_length,COUNT(*) FROM asset WHERE ctx_length IS NOT NULL- GROUP BY 1 ORDER BY 2 DESC""").fetchall()-log("时长档分布: " + " ".join(f"{k}={v:,}" for k, v in row))-row = conn.execute("""SELECT ctx_orient,COUNT(*) FROM asset WHERE ctx_orient IS NOT NULL- GROUP BY 1""").fetchall()-log("屏向分布: " + " ".join(f"{k}={v:,}" for k, v in row))-conn.close(); logf.close()+ with PidFileLock(args.lock):+ return run(args)+ except JobPolicyError as exc:+ print(f"[stop] {exc}")+ return exc.exit_code+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/scrape_codes.py b/scripts/scrape_codes.pyindex c3436ff92..7be62f7fe 100644--- a/scripts/scrape_codes.py+++ b/scripts/scrape_codes.py@@ -29,11 +29,12 @@ import randomimport reimport sqlite3import time-import urllib.errorimport urllib.parse-import urllib.request++from bs4 import BeautifulSoupfrom peach.entities import upsert_asset_entity+from peach.http import HttpRequest, HttpTransport, HttpxTransportDEFAULT_DB = r"R:\peach-data\database\ledger.db"DEFAULT_OUT = r"R:\peach-data\generated\code-scrape.csv"@@ -59,18 +60,30 @@ UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ""(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")-def _get(url: str, headers: dict | None = None, timeout: int = 25) -> str:- hdrs = {"User-Agent": UA, "Accept-Language": "zh-TW,zh;q=0.9,ja;q=0.8"}- hdrs.update(headers or {})- with urllib.request.urlopen(urllib.request.Request(url, headers=hdrs), timeout=timeout) as resp:- return resp.read().decode("utf-8", "ignore")---_TAG_RE = re.compile(r"<[^>]+>")+class SourceHttpError(RuntimeError):+ def __init__(self, status: int):+ super().__init__(f"source returned HTTP {status}")+ self.status = status-def _text(fragment: str) -> str:- return re.sub(r"\s+", " ", _TAG_RE.sub("", fragment)).strip()+def _get(+ url: str,+ headers: dict | None = None,+ timeout: int = 25,+ transport: HttpTransport | None = None,+) -> str:+ hdrs = {"User-Agent": UA, "Accept-Language": "zh-TW,zh;q=0.9,ja;q=0.8"}+ hdrs.update(headers or {})+ owns_transport = transport is None+ http = transport or HttpxTransport()+ try:+ response = http(HttpRequest("GET", url, hdrs), timeout, 8 * 1024 * 1024)+ if response.status < 200 or response.status >= 300:+ raise SourceHttpError(response.status)+ return response.body.decode("utf-8", "ignore")+ finally:+ if owns_transport and isinstance(http, HttpxTransport):+ http.close()def _name_of(value) -> str:@@ -83,10 +96,10 @@ BLANK = {"performers": "", "studio": "", "label": "", "series": "","title": "", "categories": "", "source": ""}-def from_r18(code: str) -> dict | None:+def from_r18(code: str, transport: HttpTransport | None = None) -> dict | None:payload = json.loads(_get("https://r18.dev/videos/vod/movies/detail/-/dvd_id="- f"{urllib.parse.quote(code)}/json"))+ f"{urllib.parse.quote(code)}/json", transport=transport))actors = [a.get("name", "").strip() for a in (payload.get("actresses") or []) if a.get("name")]if not actors and not payload.get("maker"):return None@@ -101,48 +114,76 @@ def from_r18(code: str) -> dict | None:}-def from_avsox(code: str) -> dict | None:- search = _get("https://avsox.click/cn/search/" + urllib.parse.quote(code))- hit = re.search(r'href="(https?://[^"]*/cn/movie/[^"]+)"', search)- if not hit:- return None- page = _get(hit.group(1))- actors = [_text(x) for x in re.findall(- r'class="avatar-box"[^>]*>.{0,400}?<span>([^<]{1,30})</span>', page, re.S)]- maker = re.search(r"制作商.{0,300}?<a[^>]*>([^<]{1,60})</a>", page, re.S)- title = re.search(r"<h3>(.*?)</h3>", page, re.S)+def _linked_value(soup: BeautifulSoup, labels: tuple[str, ...]) -> str:+ label = soup.find(string=lambda value: bool(value) and any(name in value for name in labels))+ if label is None:+ return ""+ for parent in label.parents:+ link = parent.find("a", href=True)+ if link is not None:+ return link.get_text(" ", strip=True)+ if parent.name in {"body", "html"}:+ break+ return ""+++def avsox_movie_url(html: str, base_url: str = "https://avsox.click") -> str:+ soup = BeautifulSoup(html, "html.parser")+ link = soup.select_one('a[href*="/cn/movie/"]')+ return urllib.parse.urljoin(base_url, link.get("href", "")) if link else ""+++def parse_avsox(html: str) -> dict | None:+ soup = BeautifulSoup(html, "html.parser")+ actors = [node.get_text(" ", strip=True) for node in soup.select(".avatar-box span")]+ maker = _linked_value(soup, ("制作商", "製作商"))+ title = soup.find("h3")if not (actors or maker):return Noneout = dict(BLANK)out.update({"performers": "|".join(dict.fromkeys(a for a in actors if a)),- "studio": maker.group(1).strip() if maker else "",- "title": _text(title.group(1))[:200] if title else "",+ "studio": maker,+ "title": title.get_text(" ", strip=True)[:200] if title else "","source": "avsox",})return out-def from_javbus(code: str) -> dict | None:- page = _get("https://www.javbus.com/" + urllib.parse.quote(code),- headers={"Cookie": "existmag=all"})- actors = [_text(b) for b in re.findall(r'class="star-name"[^>]*>(.*?)</span>', page, re.S)]+def from_avsox(code: str, transport: HttpTransport | None = None) -> dict | None:+ search = _get(+ "https://avsox.click/cn/search/" + urllib.parse.quote(code), transport=transport,+ )+ url = avsox_movie_url(search)+ return parse_avsox(_get(url, transport=transport)) if url else None+++def parse_javbus(html: str) -> dict | None:+ soup = BeautifulSoup(html, "html.parser")+ actors = [node.get_text(" ", strip=True) for node in soup.select(".star-name")]if not actors:- actors = [x.strip() for x in re.findall(- r'href="[^"]*/star/[^"]*"[^>]*>([^<]{1,30})</a>', page)]+ actors = [node.get_text(" ", strip=True) for node in soup.select('a[href*="/star/"]')]out = dict(BLANK)out["performers"] = "|".join(dict.fromkeys(a for a in actors if a))- for key, field in (("製作商", "studio"), ("發行商", "label"), ("系列", "series")):- hit = re.search(key + r'.{0,200}?href="[^"]*"[^>]*>([^<]{1,60})</a>', page, re.S)- if hit:- out[field] = hit.group(1).strip()- title = re.search(r"<h3>(.*?)</h3>", page, re.S)+ out["studio"] = _linked_value(soup, ("製作商", "制作商"))+ out["label"] = _linked_value(soup, ("發行商", "发行商"))+ out["series"] = _linked_value(soup, ("系列",))+ title = soup.find("h3")if title:- out["title"] = _text(title.group(1))[:200]+ out["title"] = title.get_text(" ", strip=True)[:200]out["source"] = "javbus"return out if (out["performers"] or out["studio"]) else None+def from_javbus(code: str, transport: HttpTransport | None = None) -> dict | None:+ page = _get(+ "https://www.javbus.com/" + urllib.parse.quote(code),+ headers={"Cookie": "existmag=all"},+ transport=transport,+ )+ return parse_javbus(page)++def normalise(code: str) -> str:"""FC2PPV-1234567 → FC2-PPV-1234567 ; ABW123 → ABW-123 ; IPVR00296 → IPVR-296"""value = code.upper().replace("_", "-").replace(" ", "-")@@ -238,41 +279,45 @@ def main(argv: list[str] | None = None) -> int:by_source: dict[str, int] = {}started = time.time()- for index, (code, size_gb, videos) in enumerate(todo, 1):- query = normalise(code)- record = dict(BLANK)- record.update({"code": code, "query": query, "status": "",- "size_gb": round(size_gb, 2), "videos": videos})- for source_name, fetch in chain(query):- if time.time() < cooldown.get(source_name, 0):- continue- try:- found = fetch(query)- except urllib.error.HTTPError as exc:- if exc.code in (403, 429, 503):- cooldown[source_name] = time.time() + 300- log(f" {source_name} 限流 {exc.code},冷却 5 分钟")- continue- except Exception:- continue- if found:- record.update(found)- record["status"] = "ok" if found["performers"] else "no_actress"- by_source[source_name] = by_source.get(source_name, 0) + 1- break- time.sleep(0.4)- if record["performers"]:- hit += 1- else:- miss += 1- record["status"] = record["status"] or "not_found"- writer.writerow(record)- handle.flush()- if index % 25 == 0:- elapsed = time.time() - started- log(f"{index}/{len(todo)} 命中 {hit} 未果 {miss} "- f"剩余 {(len(todo) - index) * elapsed / index / 60:.0f} 分钟 源:{by_source}")- time.sleep(args.delay + random.uniform(0, 0.5))+ http = HttpxTransport()+ try:+ for index, (code, size_gb, videos) in enumerate(todo, 1):+ query = normalise(code)+ record = dict(BLANK)+ record.update({"code": code, "query": query, "status": "",+ "size_gb": round(size_gb, 2), "videos": videos})+ for source_name, fetch in chain(query):+ if time.time() < cooldown.get(source_name, 0):+ continue+ try:+ found = fetch(query, http)+ except SourceHttpError as exc:+ if exc.status in (403, 429, 503):+ cooldown[source_name] = time.time() + 300+ log(f" {source_name} 限流 {exc.status},冷却 5 分钟")+ continue+ except Exception:+ continue+ if found:+ record.update(found)+ record["status"] = "ok" if found["performers"] else "no_actress"+ by_source[source_name] = by_source.get(source_name, 0) + 1+ break+ time.sleep(0.4)+ if record["performers"]:+ hit += 1+ else:+ miss += 1+ record["status"] = record["status"] or "not_found"+ writer.writerow(record)+ handle.flush()+ if index % 25 == 0:+ elapsed = time.time() - started+ log(f"{index}/{len(todo)} 命中 {hit} 未果 {miss} "+ f"剩余 {(len(todo) - index) * elapsed / index / 60:.0f} 分钟 源:{by_source}")+ time.sleep(args.delay + random.uniform(0, 0.5))+ finally:+ http.close()handle.close()total = hit + missdiff --git a/scripts/sheets.py b/scripts/sheets.pyindex 1c43b97cf..40d5001cd 100644--- a/scripts/sheets.py+++ b/scripts/sheets.py@@ -1,197 +1,200 @@#!/usr/bin/env python3-# -*- coding: utf-8 -*--"""-全库关键帧接触表 —— 无人值守。给 ledger 里每个视频抽 9 帧拼成一张图。--用途:日后不打开文件就能认内容;识别创作者水印;判定行为标签。-成本:实测 seek 抽帧 0.37–1.36 秒/帧且与文件大小无关,一个视频 6–14 秒。--与 scripts/probe.py 一样设计成可随时中断重启:- * 只处理 snapshot_path IS NULL 的记录- * 产物落地后才写库,进程被杀不会留下"记了但没图"的空档- * 图已存在则直接补登记,不重复抽帧--用法(双击 run-sheets.cmd,或):- python scripts/sheets.py [--workers 4] [--location 115] [--frames 9] [--limit N]-"""-import os, sys, time, hashlib, sqlite3, subprocess, threading, queue, tempfile, shutil--from peach.config import FFMPEG_DIR+"""全库关键帧接触表:可续跑、显式计费授权、产物落地后登记。"""+from __future__ import annotations++import argparse+import hashlib+import os+import queue+import shutil+import sqlite3+import subprocess+import tempfile+import threading+import time+from pathlib import Path++from peach.config import DATABASE_PATH, FFMPEG_DIR, GENERATED_DIR, LOG_DIR, STATE_DIRfrom peach.ffmpeg import FFmpegResolver--DB = r"R:\peach-data\database\ledger.db"-_FFMPEG_RESOLVER = FFmpegResolver(FFMPEG_DIR)-_FFMPEG_CHOICE = _FFMPEG_RESOLVER.ffmpeg()-_FFPROBE_CHOICE = _FFMPEG_RESOLVER.ffprobe()-if _FFMPEG_CHOICE is None or _FFPROBE_CHOICE is None:- raise RuntimeError("ffmpeg/ffprobe are unavailable; install them under Peach data tools or PATH")-FFMPEG, FFPROBE = str(_FFMPEG_CHOICE.path), str(_FFPROBE_CHOICE.path)-OUTROOT = r"R:\peach-data\generated\snapshots\cloud"-LOG = r"R:\peach-data\logs\sheets-{}.log".format(time.strftime("%Y%m%d-%H%M%S"))--a = sys.argv[1:]-def opt(n, d, cast=str): return cast(a[a.index(n) + 1]) if n in a else d-WORKERS = opt("--workers", 4, int)-LOCATION = opt("--location", None)-FRAMES = opt("--frames", 9, int)-LIMIT = opt("--limit", 0, int)-COLS = 3-TILE_W = 480--os.makedirs(OUTROOT, exist_ok=True)-logf = open(LOG, "w", encoding="utf-8", buffering=1)-lock = threading.RLock() # 必须可重入:worker 持锁时会调 log(),而 log() 内部还要再拿一次锁-def log(s):- with lock:- line = f"[{time.strftime('%H:%M:%S')}] {s}"- print(line, flush=True); logf.write(line + "\n")--def outpath(location, path):- h = hashlib.sha1(path.encode("utf-8", "ignore")).hexdigest()[:16]- d = os.path.join(OUTROOT, location, h[:2])- os.makedirs(d, exist_ok=True)- return os.path.join(d, h + ".jpg")--def make_sheet(path, dur, dst):- """抽 N 帧拼接成接触表。-- ⚠ 不能用 select 滤镜按时间戳挑帧 —— 那会**线性解码整个视频**,实测 4 分钟只出 3 张图。- 必须用 -ss 放在 -i 之前做输入端 seek:ffmpeg 只读 moov atom + 目标 GOP,- 实测 0.37~1.36 秒/帧且与文件大小无关(8.5 GB 和 0.36 GB 一样快)。- """- if not dur or dur < 2:+from peach.jobs import JobPolicyError, PidFileLock, SourceAccessPolicy, require_free_space+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description="生成视频关键帧接触表")+ parser.add_argument("--workers", type=int, default=4)+ parser.add_argument("--location")+ parser.add_argument("--frames", type=int, default=9)+ parser.add_argument("--limit", type=int, default=0)+ parser.add_argument("--min-free", type=float, default=40.0)+ parser.add_argument("--allow-metered", action="store_true")+ parser.add_argument("--db", type=Path, default=DATABASE_PATH)+ parser.add_argument("--output-root", type=Path, default=GENERATED_DIR / "snapshots" / "cloud")+ parser.add_argument("--log-dir", type=Path, default=LOG_DIR)+ parser.add_argument("--lock", type=Path, default=STATE_DIR / ".sheets.lock")+ return parser+++def output_path(output_root: Path, location: str, path: str) -> Path:+ digest = hashlib.sha1(path.encode("utf-8", "ignore")).hexdigest()[:16]+ directory = output_root / location / digest[:2]+ directory.mkdir(parents=True, exist_ok=True)+ return directory / f"{digest}.jpg"+++def make_sheet(ffmpeg: str, path: str, duration: float, destination: Path, frames: int) -> bool:+ """输入端 seek 抽帧后调用 FFmpeg tile;不线性解码整片。"""+ if not duration or duration < 2:return False- tmpd = tempfile.mkdtemp(prefix="sheet_")+ temporary = Path(tempfile.mkdtemp(prefix="sheet_"))try:- got = []- for i in range(FRAMES):- ts = dur * (0.03 + 0.94 * (i + 0.5) / FRAMES)- f = os.path.join(tmpd, f"{i:02d}.jpg")- r = subprocess.run(- [FFMPEG, "-y", "-v", "error", "-rw_timeout", "8000000",- "-ss", f"{ts:.2f}", "-i", path,- "-frames:v", "1", "-vf", f"scale={TILE_W}:-1", "-q:v", "4", f],- capture_output=True, timeout=45)- if os.path.exists(f) and os.path.getsize(f) > 1024:- got.append(f)- if len(got) < 2:+ captured: list[Path] = []+ for index in range(frames):+ timestamp = duration * (0.03 + 0.94 * (index + 0.5) / frames)+ frame = temporary / f"{index:02d}.jpg"+ subprocess.run(+ [+ ffmpeg, "-y", "-v", "error", "-rw_timeout", "8000000",+ "-ss", f"{timestamp:.2f}", "-i", path, "-frames:v", "1",+ "-vf", "scale=480:-1", "-q:v", "4", str(frame),+ ],+ capture_output=True,+ timeout=45,+ )+ if frame.is_file() and frame.stat().st_size > 1024:+ captured.append(frame)+ if len(captured) < 2:return False- # 重排成连续编号供 image2 读取- for n, f in enumerate(got):- tgt = os.path.join(tmpd, f"s{n:02d}.jpg")- if f != tgt:- os.replace(f, tgt)- rows = (len(got) + COLS - 1) // COLS+ for index, frame in enumerate(captured):+ target = temporary / f"s{index:02d}.jpg"+ if frame != target:+ frame.replace(target)+ rows = (len(captured) + 2) // 3+ destination.parent.mkdir(parents=True, exist_ok=True)subprocess.run(- [FFMPEG, "-y", "-v", "error", "-i", os.path.join(tmpd, "s%02d.jpg"),- "-filter_complex", f"tile={COLS}x{rows}", "-q:v", "4", dst],- capture_output=True, timeout=60)- return os.path.exists(dst) and os.path.getsize(dst) > 4096+ [+ ffmpeg, "-y", "-v", "error", "-i", str(temporary / "s%02d.jpg"),+ "-filter_complex", f"tile=3x{rows}", "-q:v", "4", str(destination),+ ],+ capture_output=True,+ timeout=60,+ )+ return destination.is_file() and destination.stat().st_size > 4096finally:- shutil.rmtree(tmpd, ignore_errors=True)--# ---------- 取任务 -----------c = sqlite3.connect(DB)-# -- 磁盘闸门(2026-08-14 加)---------------------------------# 教训:这些任务读网盘会把块缓存写到 CloudDrive.WinUI\file_buffer_cache。-# 跑了一整天后该目录涨到 910 GB(配置上限写的 32 GB,LRU 没拦住),-# C 盘从 22 GB 可用掉到 0.1 GB,我全程没发现,是用户报错才查出来。-# 所以:启动前检查,低于阈值直接拒绝。-import shutil as _sh-MIN_FREE_GB = float(sys.argv[sys.argv.index("--min-free") + 1]) if "--min-free" in sys.argv else 40.0-def _free_gb(drive="C:" + chr(92)):- try:- return _sh.disk_usage(drive).free / 1024**3- except Exception:- return 999.0-def disk_guard():- f = _free_gb()- if f < MIN_FREE_GB:- print("[stop] C 盘仅剩 %.1f GB(阈值 %.0f GB)—— 拒绝启动。"- "先清 CloudDrive 的 file_buffer_cache" % (f, MIN_FREE_GB))- return False- return True-if not disk_guard():- sys.exit(3)-# -------------------------------------------------------------# ── 计费来源闸门(2026-08-14 加)──────────────────────────────-# 教训:这两个脚本不带 --location 启动了一次,覆盖到 PikPak,-# 11 小时烧掉 677 GB 代理流量。知道要限制、脚本也支持,就是启动时没加。-# 所以把限制写死:默认拒绝计费来源,要跑必须显式 --allow-metered。-METERED = {"pikpak", "online"}-ALLOW_METERED = "--allow-metered" in sys.argv-if not LOCATION:- LOCATION = None-if not ALLOW_METERED:- _excl = " AND location NOT IN ('" + "','".join(sorted(METERED)) + "')"- if LOCATION in METERED:- print(f"拒绝:{LOCATION} 是计费来源。确认要花流量再加 --allow-metered")- sys.exit(2)-else:- _excl = ""- print("⚠️ 已开启 --allow-metered:将读取 PikPak,产生计费流量")-# ─────────────────────────────────────────────────────────────--sql = ("SELECT id,location,path,duration FROM asset WHERE medium='video' "- "AND snapshot_path IS NULL AND location != 'online' AND duration > 2")-if LOCATION: sql += f" AND location='{LOCATION}'"-sql += _excl-sql += " ORDER BY size DESC"-if LIMIT: sql += f" LIMIT {LIMIT}"-tasks = c.execute(sql).fetchall()-c.close()-total = len(tasks)-log(f"待处理 {total:,} 个视频 workers={WORKERS} frames={FRAMES} 日志={LOG}")-if not total:- log("没有待处理项(可能需要先跑 scripts/probe.py 拿到 duration)"); sys.exit(0)--q = queue.Queue()-for t in tasks: q.put(t)-results = queue.Queue()-done = [0]; failed = [0]; skipped = [0]; t0 = time.time()--def worker():- while True:- try:- aid, loc, path, dur = q.get_nowait()- except queue.Empty:- return- dst = outpath(loc, path)- try:- if os.path.exists(dst) and os.path.getsize(dst) > 4096:- results.put((dst, aid));- with lock: skipped[0] += 1- elif make_sheet(path, dur, dst):- results.put((dst, aid))- else:- with lock: failed[0] += 1- except Exception:- with lock: failed[0] += 1- finally:+ shutil.rmtree(temporary, ignore_errors=True)+++def run(args: argparse.Namespace) -> int:+ if args.workers < 1 or args.frames < 2 or args.limit < 0:+ raise SystemExit("workers 必须大于 0,frames 至少为 2,limit 不能为负数")+ resolver = FFmpegResolver(FFMPEG_DIR)+ ffmpeg = resolver.ffmpeg()+ if ffmpeg is None:+ raise RuntimeError("ffmpeg unavailable")+ require_free_space(Path("C:/"), args.min_free)+ source_sql, source_parameters = SourceAccessPolicy().sql_filter(+ args.location, args.allow_metered+ )+ args.output_root.mkdir(parents=True, exist_ok=True)+ args.log_dir.mkdir(parents=True, exist_ok=True)+ log_path = args.log_dir / f"sheets-{time.strftime('%Y%m%d-%H%M%S')}.log"+ lock = threading.RLock()++ with log_path.open("w", encoding="utf-8", buffering=1) as log_file:+ def log(message: str) -> None:with lock:- done[0] += 1- if done[0] % 100 == 0:- el = time.time() - t0- rate = done[0] / el if el else 0- log(f"{done[0]:,}/{total:,} 失败 {failed[0]} 已存在 {skipped[0]} "- f"{rate*60:.0f} 个/分 预计剩余 {(total-done[0])/rate/3600 if rate else 0:.1f} 小时")--threads = [threading.Thread(target=worker, daemon=True) for _ in range(WORKERS)]-for t in threads: t.start()--conn = sqlite3.connect(DB, timeout=60)-buf = []-while any(t.is_alive() for t in threads) or not results.empty():- try: buf.append(results.get(timeout=2))- except queue.Empty: pass- if len(buf) >= 50:- conn.executemany("UPDATE asset SET snapshot_path=? WHERE id=?", buf); conn.commit(); buf.clear()-if buf:- conn.executemany("UPDATE asset SET snapshot_path=? WHERE id=?", buf); conn.commit()--el = time.time() - t0-log(f"完成 {done[0]:,} 失败 {failed[0]} 已存在 {skipped[0]} 耗时 {el/3600:.2f} 小时")-n = conn.execute("SELECT COUNT(*) FROM asset WHERE snapshot_path IS NOT NULL").fetchone()[0]-log(f"账本中已有接触表的资产: {n:,}")-conn.close(); logf.close()+ line = f"[{time.strftime('%H:%M:%S')}] {message}"+ print(line, flush=True)+ log_file.write(line + "\n")++ if args.allow_metered:+ log("已显式允许计费来源")+ connection = sqlite3.connect(args.db)+ sql = (+ "SELECT id,location,path,duration FROM asset WHERE medium='video' "+ "AND snapshot_path IS NULL AND location != 'online' AND duration > 2"+ + source_sql + " ORDER BY size DESC"+ )+ parameters: tuple[object, ...] = source_parameters+ if args.limit:+ sql += " LIMIT ?"+ parameters += (args.limit,)+ tasks = connection.execute(sql, parameters).fetchall()+ connection.close()+ total = len(tasks)+ log(f"待处理 {total:,} 个视频 workers={args.workers} frames={args.frames} 日志={log_path}")+ if not total:+ log("没有待处理项;可能需要先运行 probe")+ return 0++ pending: queue.Queue = queue.Queue()+ results: queue.Queue = queue.Queue()+ for task in tasks:+ pending.put(task)+ counters = {"done": 0, "failed": 0, "existing": 0}+ started = time.time()++ def worker() -> None:+ while True:+ try:+ asset_id, location, path, duration = pending.get_nowait()+ except queue.Empty:+ return+ destination = output_path(args.output_root, location, path)+ try:+ if destination.is_file() and destination.stat().st_size > 4096:+ results.put((str(destination), asset_id))+ with lock:+ counters["existing"] += 1+ elif make_sheet(str(ffmpeg.path), path, duration, destination, args.frames):+ results.put((str(destination), asset_id))+ else:+ with lock:+ counters["failed"] += 1+ except Exception:+ with lock:+ counters["failed"] += 1+ finally:+ with lock:+ counters["done"] += 1+ if counters["done"] % 100 == 0:+ elapsed = time.time() - started+ rate = counters["done"] / elapsed if elapsed else 0+ eta = (total - counters["done"]) / rate / 3600 if rate else 0+ log(f"{counters['done']:,}/{total:,} 失败 {counters['failed']} 已存在 {counters['existing']} 剩余 {eta:.1f} 小时")++ threads = [threading.Thread(target=worker, daemon=True) for _ in range(args.workers)]+ for thread in threads:+ thread.start()++ connection = sqlite3.connect(args.db, timeout=60)+ buffer = []+ while any(thread.is_alive() for thread in threads) or not results.empty():+ try:+ buffer.append(results.get(timeout=2))+ except queue.Empty:+ pass+ if len(buffer) >= 50:+ connection.executemany("UPDATE asset SET snapshot_path=? WHERE id=?", buffer)+ connection.commit()+ buffer.clear()+ if buffer:+ connection.executemany("UPDATE asset SET snapshot_path=? WHERE id=?", buffer)+ connection.commit()+ elapsed = time.time() - started+ log(f"完成 {counters['done']:,},失败 {counters['failed']},已存在 {counters['existing']},耗时 {elapsed/3600:.2f} 小时")+ connection.close()+ return 0+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ try:+ with PidFileLock(args.lock):+ return run(args)+ except JobPolicyError as exc:+ print(f"[stop] {exc}")+ return exc.exit_code+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/traffic_watch.py b/scripts/traffic_watch.pyindex 1792ac786..9b016f7b5 100644--- a/scripts/traffic_watch.py+++ b/scripts/traffic_watch.py@@ -1,203 +1,227 @@#!/usr/bin/env python3-# -*- coding: utf-8 -*--r"""-流量哨兵 —— 代理下载增量超阈值就**停机报警**,不是提示后继续。--用户 2026-08-14 定的策略:构建期允许较大量用流量,短时大量消耗须停机报警;-阈值现场定(当晚 200 GB),50 GB 只是「值得警惕」的量级不是死上限。--背景:08-13 15:30 → 08-14 02:40 的 11 小时里代理下载 677 GB,- 89% 是 CloudDrive.exe 拉 PikPak。全是执行疏漏(脚本漏加 --location、- 测流量的脚本自己去拉、前端 bug 反复缓冲同一个 12.6 GB 文件),- 所以闸门必须自动执行,不能靠记性。--数据源:Clash Verge 的 external-controller 是空的、只开命名管道- \\.\pipe\verge-mihomo,curl 打不到,直接对管道说 HTTP。- ⚠️ downloadTotal **含 DIRECT**,不是代理用量(实测 60s 内 0.697 GB- 里有 0.531 GB 是 115 直连)。本脚本改为逐连接只累计非 DIRECT。--注意:115 走 GEOIP,CN,DIRECT 不计入代理量,所以这个哨兵只会因 PikPak 之类的出网触发。--用法:- python scripts/traffic_watch.py 阈值 50 GB,每 30 秒查一次- python scripts/traffic_watch.py --limit 30 --interval 20- python scripts/traffic_watch.py --once 查一次当前用量就退出-"""-import os, re, sys, json, time, subprocess--PIPE = r"\\.\pipe\verge-mihomo"-SECRET = "set-your-secret"-LOG = r"R:\peach-data\logs\trafficwatch-{}.log".format(time.strftime("%Y%m%d-%H%M%S"))-ALERT = r"R:\peach-data\logs\流量警报.txt"--A = sys.argv[1:]-def _o(n, d, c=str): return c(A[A.index(n) + 1]) if n in A else d-LIMIT_GB = _o("--limit", 50.0, float)-WARN_GB = _o("--warn", LIMIT_GB * 0.6, float)-INTERVAL = _o("--interval", 2, int)-ONCE = "--once" in A-# 触发时要杀掉的任务(读网盘的那些)-KILL_PATTERNS = ["scripts\\probe.py", "scripts\\sheets.py", "rm-probe.py", "rm-sheets.py"]--logf = open(LOG, "a", encoding="utf-8", buffering=1)-def log(s):- line = f"[{time.strftime('%H:%M:%S')}] {s}"- print(line, flush=True); logf.write(line + "\n")--def clash(path="/connections"):- req = (f"GET {path} HTTP/1.1\r\nHost: localhost\r\n"- f"Authorization: Bearer {SECRET}\r\n"- f"Accept: application/json\r\nConnection: close\r\n\r\n").encode()- # 读到「响应真正结束」为止。- # 上一版用 buf.endswith('}'/']'/'0') 判断结束 —— 在分块边界上会误判,- # 连接数一多响应变大就必然在中途截断(Unterminated string)。- with open(PIPE, "r+b", buffering=0) as f:- f.write(req)- buf = b""- clen = None- hdr_end = -1+r"""代理下载流量哨兵:按连接增量计量,只停止 Peach 所属任务树。"""+from __future__ import annotations++import argparse+import json+import os+import re+import subprocess+import time+from pathlib import Path++from peach.config import LOG_DIR+++DEFAULT_PIPE = r"\\.\pipe\verge-mihomo"+KILL_PATTERNS = (+ "scripts\\probe.py",+ "scripts\\sheets.py",+ "scripts\\creator_boards.py",+)+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description="Peach 代理流量停机哨兵")+ parser.add_argument("--limit", type=float, default=50.0)+ parser.add_argument("--warn", type=float)+ parser.add_argument("--interval", type=int, default=2)+ parser.add_argument("--once", action="store_true")+ parser.add_argument("--pipe", default=DEFAULT_PIPE)+ parser.add_argument("--secret", default=os.environ.get("PEACH_CLASH_SECRET", "set-your-secret"))+ parser.add_argument("--log-dir", type=Path, default=LOG_DIR)+ parser.add_argument("--alert", type=Path, default=LOG_DIR / "流量警报.txt")+ return parser+++def clash(pipe: str, secret: str, path: str = "/connections") -> dict:+ request = (+ f"GET {path} HTTP/1.1\r\nHost: localhost\r\n"+ f"Authorization: Bearer {secret}\r\nAccept: application/json\r\n"+ "Connection: close\r\n\r\n"+ ).encode()+ with open(pipe, "r+b", buffering=0) as handle:+ handle.write(request)+ buffer = b""+ content_length = None+ header_end = -1+ chunked = Falsewhile True:try:- chunk = f.read(65536)- except Exception:+ chunk = handle.read(65536)+ except OSError:breakif not chunk:break- buf += chunk- if hdr_end < 0:- hdr_end = buf.find(b"\r\n\r\n")- if hdr_end >= 0:- head = buf[:hdr_end].lower()- m = re.search(rb"content-length:\s*(\d+)", head)- if m:- clen = int(m.group(1))- chunked = b"transfer-encoding: chunked" in head- if hdr_end >= 0:- body_len = len(buf) - hdr_end - 4- if clen is not None and body_len >= clen:+ buffer += chunk+ if header_end < 0:+ header_end = buffer.find(b"\r\n\r\n")+ if header_end >= 0:+ header = buffer[:header_end].lower()+ match = re.search(rb"content-length:\s*(\d+)", header)+ if match:+ content_length = int(match.group(1))+ chunked = b"transfer-encoding: chunked" in header+ if header_end >= 0:+ body_length = len(buffer) - header_end - 4+ if content_length is not None and body_length >= content_length:break- if clen is None and buf.endswith(b"\r\n0\r\n\r\n"):+ if content_length is None and buffer.endswith(b"\r\n0\r\n\r\n"):break- head, _, body = buf.partition(b"\r\n\r\n")- if b"chunked" in head.lower():- out, rest = b"", body- while rest:- ln, _, rest = rest.partition(b"\r\n")- try: n = int(ln.strip().split(b";")[0], 16)- except Exception: break- if n == 0: break- out += rest[:n]; rest = rest[n + 2:]- body = out- elif clen is not None:- body = body[:clen]+ header, _, body = buffer.partition(b"\r\n\r\n")+ if chunked or b"chunked" in header.lower():+ decoded = b""+ remaining = body+ while remaining:+ line, _, remaining = remaining.partition(b"\r\n")+ try:+ size = int(line.strip().split(b";")[0], 16)+ except ValueError:+ break+ if size == 0:+ break+ decoded += remaining[:size]+ remaining = remaining[size + 2:]+ body = decoded+ elif content_length is not None:+ body = body[:content_length]return json.loads(body)-def _is_direct(c):- ch = c.get("chains") or []- return len(ch) == 1 and ch[0] == "DIRECT"--def snapshot():- """返回 {连接id: (已下载字节, 是否直连, 目标)} 以及 downloadTotal。-- ⚠️ 不能拿 downloadTotal 当代理用量 —— 实测它**把 DIRECT 也算进去**:- 60 秒内 downloadTotal +0.697 GB,其中 0.531 GB 来自 cdnfhnfile.115cdn.net- (115 的 CDN,走 GEOIP,CN,DIRECT,免费),代理只占 0.010 GB。- 照这个比例,按 downloadTotal 设 200 GB 的闸门会在几小时内被免费流量撑爆,- 然后把不该停的 115 任务一起杀掉。- 所以改成:逐连接记账,只累计 chain 非纯 DIRECT 的增量。"""- d = clash()- per = {}- for c in d.get("connections") or []:- m = c.get("metadata") or {}- per[c.get("id")] = (c.get("download", 0), _is_direct(c),- m.get("host") or m.get("destinationIP") or "?")- return d.get("downloadTotal", 0), per--def kill_jobs():- killed = []- try:- out = subprocess.run(["powershell", "-NoProfile", "-Command",++def is_direct(connection: dict) -> bool:+ chains = connection.get("chains") or []+ return len(chains) == 1 and chains[0] == "DIRECT"+++def snapshot(pipe: str, secret: str) -> tuple[int, dict]:+ payload = clash(pipe, secret)+ per_connection = {}+ for connection in payload.get("connections") or []:+ metadata = connection.get("metadata") or {}+ per_connection[connection.get("id")] = (+ connection.get("download", 0),+ is_direct(connection),+ metadata.get("host") or metadata.get("destinationIP") or "?",+ )+ return payload.get("downloadTotal", 0), per_connection+++def owned_python_jobs() -> list[tuple[str, str]]:+ result = subprocess.run(+ [+ "powershell", "-NoProfile", "-Command","Get-CimInstance Win32_Process -Filter \"Name='python.exe'\" | "- "ForEach-Object { \"$($_.ProcessId)|$($_.CommandLine)\" }"],- capture_output=True, text=True, timeout=60).stdout- for ln in out.splitlines():- pid, _, cmd = ln.partition("|")- if any(p in cmd for p in KILL_PATTERNS):- subprocess.run(["powershell", "-NoProfile", "-Command",- f"Stop-Process -Id {pid.strip()} -Force"],- capture_output=True, timeout=30)- killed.append(f"{pid.strip()} {cmd.strip()[:80]}")- subprocess.run(["powershell", "-NoProfile", "-Command",- "Get-Process ffmpeg,ffprobe -ErrorAction SilentlyContinue | "- "Stop-Process -Force -ErrorAction SilentlyContinue"],- capture_output=True, timeout=30)- except Exception as e:- log(f"杀进程失败: {e}")- return killed--try:- total0, prev = snapshot()-except Exception as e:- print("连不上 Clash 管道:", e); sys.exit(1)--proxy_bytes = 0.0 # 只累计走代理的-direct_bytes = 0.0 # 直连另记一笔,方便对照-hosts_proxy = {}--log(f"哨兵启动。mihomo 累计(含直连){total0/1024**3:,.1f} GB,活跃连接 {len(prev)}")-log("计量口径:只累计非 DIRECT 连接的下载增量(115 直连不计入)")-log("⚠️ 这是**下界**:两次轮询之间开启又关闭的连接会整段漏掉。")-log(" CloudDrive 用大量短连接,30s 轮询曾比机场面板少算一半以上;已降到 2s,仍只是近似。")-log(" 准确用量以机场面板为准。")-log(f"阈值:增量 {LIMIT_GB:.0f} GB 触发停机({WARN_GB:.0f} GB 预警),每 {INTERVAL}s 查一次")--if ONCE:- agg = {}- for cid, (dl, dr, host) in prev.items():- if not dr:- agg[host] = agg.get(host, 0) + dl- print("\n活跃**代理**连接按目标(下载字节,不含直连):")- for h, v in sorted(agg.items(), key=lambda x: -x[1])[:12]:- print(f" {v/1024**3:>8.3f} GB {h}")- print("\n注:mihomo 的 downloadTotal 含 DIRECT,不能当代理用量。")- sys.exit(0)--warned = False-while True:- time.sleep(INTERVAL)+ "ForEach-Object { \"$($_.ProcessId)|$($_.CommandLine)\" }",+ ],+ capture_output=True,+ text=True,+ timeout=60,+ )+ jobs = []+ for line in result.stdout.splitlines():+ pid, separator, command = line.partition("|")+ normalized = command.lower().replace("/", "\\")+ if separator and pid.strip().isdigit() and any(pattern in normalized for pattern in KILL_PATTERNS):+ jobs.append((pid.strip(), command.strip()))+ return jobs+++def stop_owned_jobs(log) -> list[str]:+ stopped = []+ try:+ for pid, command in owned_python_jobs():+ result = subprocess.run(+ ["taskkill", "/PID", pid, "/T", "/F"],+ capture_output=True,+ timeout=30,+ )+ if result.returncode == 0:+ stopped.append(f"{pid} {command[:80]}")+ except Exception as exc:+ log(f"停止任务失败: {exc}")+ return stopped+++def run(args: argparse.Namespace, log) -> int:+ if args.limit <= 0 or args.interval < 1:+ raise SystemExit("limit 必须大于 0,interval 至少为 1 秒")+ warn_gb = args.warn if args.warn is not None else args.limit * 0.6try:- total, cur = snapshot()- except Exception as e:- log(f"读取失败({e}),跳过本轮"); continue- # 逐连接算增量:连接关闭后会从列表消失,最后一次增量在消失前那轮已计入- for cid, (dl, dr, host) in cur.items():- old = prev.get(cid, (0, dr, host))[0]- delta = max(dl - old, 0)- if dr:- direct_bytes += delta- else:- proxy_bytes += delta- hosts_proxy[host] = hosts_proxy.get(host, 0) + delta- prev = cur- nconn = len(cur)- hosts = hosts_proxy- used = proxy_bytes / 1024**3- if used >= LIMIT_GB:- top = sorted(hosts.items(), key=lambda x: -x[1])[:5]- log(f"⛔ 增量 {used:.1f} GB 超过阈值 {LIMIT_GB:.0f} GB —— 停机")- killed = kill_jobs()- msg = [f"流量警报 {time.strftime('%Y-%m-%d %H:%M:%S')}",- f"代理下载增量 {used:.1f} GB(阈值 {LIMIT_GB:.0f} GB)",- f"(同期直连 {direct_bytes/1024**3:.1f} GB,不计入)",- f"活跃连接 {nconn}", "", "活跃连接 Top:"]- msg += [f" {v/1024**3:>8.3f} GB {h}" for h, v in top]- msg += ["", "已杀掉的任务:"] + ([f" {k}" for k in killed] or [" (无匹配任务)"])- open(ALERT, "w", encoding="utf-8").write("\n".join(msg))- log("警报已写入 " + ALERT)- for ln in msg: log(" " + ln)- sys.exit(10)- if used >= WARN_GB and not warned:- warned = True- log(f"⚠️ 增量已达 {used:.1f} GB(阈值 {LIMIT_GB:.0f} GB),接近停机线")- log(f"代理 {used:>7.2f} GB / {LIMIT_GB:.0f} GB "- f"(直连 {direct_bytes/1024**3:>7.2f} GB 不计) 连接 {nconn}")+ total_start, previous = snapshot(args.pipe, args.secret)+ except Exception as exc:+ print("连不上 Clash 管道:", exc)+ return 1++ proxy_bytes = 0.0+ direct_bytes = 0.0+ proxy_hosts: dict[str, float] = {}+ log(f"哨兵启动。mihomo 累计(含直连){total_start/1024**3:,.1f} GB,活跃连接 {len(previous)}")+ log("计量口径:只累计非 DIRECT 连接下载增量;这是轮询下界")+ log(f"阈值 {args.limit:.0f} GB,预警 {warn_gb:.0f} GB,每 {args.interval}s 检查")++ if args.once:+ aggregate: dict[str, int] = {}+ for downloaded, direct, host in previous.values():+ if not direct:+ aggregate[host] = aggregate.get(host, 0) + downloaded+ for host, value in sorted(aggregate.items(), key=lambda item: -item[1])[:12]:+ print(f"{value/1024**3:>8.3f} GB {host}")+ return 0++ warned = False+ while True:+ time.sleep(args.interval)+ try:+ _total, current = snapshot(args.pipe, args.secret)+ except Exception as exc:+ log(f"读取失败({exc}),跳过本轮")+ continue+ for connection_id, (downloaded, direct, host) in current.items():+ old = previous.get(connection_id, (0, direct, host))[0]+ delta = max(downloaded - old, 0)+ if direct:+ direct_bytes += delta+ else:+ proxy_bytes += delta+ proxy_hosts[host] = proxy_hosts.get(host, 0) + delta+ previous = current+ used_gb = proxy_bytes / 1024**3+ if used_gb >= args.limit:+ log(f"增量 {used_gb:.1f} GB 超过阈值 {args.limit:.0f} GB——停止所属任务")+ stopped = stop_owned_jobs(log)+ top = sorted(proxy_hosts.items(), key=lambda item: -item[1])[:5]+ lines = [+ f"流量警报 {time.strftime('%Y-%m-%d %H:%M:%S')}",+ f"代理下载增量 {used_gb:.1f} GB(阈值 {args.limit:.0f} GB)",+ f"同期直连 {direct_bytes/1024**3:.1f} GB(不计入)",+ "", "代理目标 Top:",+ *[f" {value/1024**3:>8.3f} GB {host}" for host, value in top],+ "", "已停止的 Peach 任务:",+ *([f" {item}" for item in stopped] or [" (无匹配任务)"]),+ ]+ args.alert.parent.mkdir(parents=True, exist_ok=True)+ args.alert.write_text("\n".join(lines) + "\n", encoding="utf-8")+ for line in lines:+ log(line)+ return 10+ if used_gb >= warn_gb and not warned:+ warned = True+ log(f"增量已达 {used_gb:.1f} GB,接近停机线")+ log(f"代理 {used_gb:>7.2f}/{args.limit:.0f} GB(直连 {direct_bytes/1024**3:>7.2f} GB 不计)连接 {len(current)}")+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ args.log_dir.mkdir(parents=True, exist_ok=True)+ log_path = args.log_dir / f"trafficwatch-{time.strftime('%Y%m%d-%H%M%S')}.log"+ with log_path.open("a", encoding="utf-8", buffering=1) as log_file:+ def log(message: str) -> None:+ line = f"[{time.strftime('%H:%M:%S')}] {message}"+ print(line, flush=True)+ log_file.write(line + "\n")++ return run(args, log)+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/src/peach/api.py b/src/peach/api.pyindex 2e1f0d097..e9346cc02 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -10,11 +10,19 @@ from fastapi.responses import FileResponse, JSONResponse, PlainTextResponse, Resfrom . import web_contractfrom .config import PeachSettingsfrom .ffmpeg import FFmpegResolver-from .media import FilesystemMediaService, MediaNotFound, MediaUnavailable+from .http import HttpxTransport+from .media import (+ FilesystemBackend,+ MediaEngine,+ MediaNotFound,+ MediaUnavailable,+ StashAdapter,+)from .mdns import create_mdns_publisherfrom .previews import PreviewService, PreviewUnavailablefrom .providers import OpenCodeGoClient, ProviderUnavailable, default_registryfrom .repository import LedgerRepository+from .stash import StashClientdef _first_query_values(request: Request) -> dict[str, str]:@@ -40,10 +48,17 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:)repository = LedgerRepository(settings.db_path)resolver = FFmpegResolver(settings.ffmpeg_root)- media_service = FilesystemMediaService(- repository, settings.allowed_media_roots, settings.snapshot_root,+ http_transport = HttpxTransport()+ filesystem = FilesystemBackend(+ settings.allowed_media_roots,+ settings.snapshot_root,settings.legacy_snapshot_roots,)+ media_engine = MediaEngine(+ repository,+ filesystem,+ (StashAdapter(StashClient(transport=http_transport)),),+ )preview_service = PreviewService(repository, resolver, settings.snapshot_root, settings.poster_root,settings.avatar_root, settings.logo_root, settings.legacy_snapshot_roots,@@ -52,7 +67,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:settings.mdns_name, settings.mdns_port, secure=settings.tls_enabled) if settings.mdns_enabled else Noneproviders = default_registry()- opencode_go = OpenCodeGoClient()+ opencode_go = OpenCodeGoClient(transport=http_transport)@asynccontextmanagerasync def lifespan(_app: FastAPI):@@ -67,6 +82,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:finally:if mdns is not None:await asyncio.to_thread(mdns.stop)+ http_transport.close()app = FastAPI(title="Peach API",@@ -79,11 +95,12 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:app.state.settings = settingsapp.state.web_contract = contractapp.state.repository = repository- app.state.media_service = media_service+ app.state.media_engine = media_engineapp.state.preview_service = preview_serviceapp.state.mdns = mdnsapp.state.providers = providersapp.state.opencode_go = opencode_go+ app.state.http_transport = http_transport@app.middleware("http")async def no_store(request: Request, call_next):@@ -136,7 +153,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:if not _authorized(request, settings.token, args):return JSONResponse({"error": "unauthorized"}, status_code=401)try:- path = media_service.file_for(id, thumbnail=False)+ path = media_engine.file_for(id, thumbnail=False)except MediaNotFound:return JSONResponse({"error": "no such id"}, status_code=404)except MediaUnavailable:@@ -151,7 +168,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:if not _authorized(request, settings.token, args):return JSONResponse({"error": "unauthorized"}, status_code=401)try:- path = media_service.file_for(id, thumbnail=True)+ path = media_engine.file_for(id, thumbnail=True)except MediaNotFound:return JSONResponse({"error": "no such id"}, status_code=404)except MediaUnavailable:diff --git a/src/peach/follow.py b/src/peach/follow.pyindex aca067321..35ff52c09 100644--- a/src/peach/follow.py+++ b/src/peach/follow.py@@ -6,17 +6,19 @@ persist raw evidence and submit normalized entries through a review boundary.from __future__ import annotationsimport hashlib-import htmlimport jsonimport re-import urllib.errorimport urllib.parse-import urllib.request-import xml.etree.ElementTree as ETfrom dataclasses import asdict, dataclass, fieldfrom datetime import datetime, timezonefrom pathlib import Path-from typing import Callable, Mapping, Protocol+from typing import Protocol++import httpx+import feedparser+from bs4 import BeautifulSoup++from .http import HttpRequest, HttpResponse, HttpTransport, HttpxTransportDEFAULT_MAX_BYTES = 5 * 1024 * 1024@@ -26,13 +28,6 @@ class FollowSourceError(RuntimeError):pass-@dataclass(frozen=True)-class HttpResponse:- status: int- headers: Mapping[str, str]- body: bytes--@dataclass(frozen=True)class FollowEntry:external_id: str@@ -59,42 +54,10 @@ class FollowSource(Protocol):last_modified: str | None = None) -> FollowResult: ...-def _read_http(request: urllib.request.Request, timeout: float, max_bytes: int) -> HttpResponse:- try:- with urllib.request.urlopen(request, timeout=timeout) as response:- return HttpResponse(- status=response.status,- headers=dict(response.headers.items()),- body=response.read(max_bytes + 1),- )- except urllib.error.HTTPError as exc:- if exc.code == 304:- return HttpResponse(304, dict(exc.headers.items()), b"")- raise---def _local_name(tag: str) -> str:- return tag.rsplit("}", 1)[-1].lower()---def _children(element: ET.Element, name: str) -> list[ET.Element]:- return [child for child in element if _local_name(child.tag) == name]---def _child_text(element: ET.Element, *names: str) -> str | None:- wanted = set(names)- for child in element:- if _local_name(child.tag) in wanted:- value = "".join(child.itertext()).strip()- if value:- return value- return None--def _plain_text(value: str | None) -> str | None:if not value:return None- cleaned = html.unescape(re.sub(r"<[^>]+>", " ", value))+ cleaned = BeautifulSoup(value, "html.parser").get_text(" ")cleaned = re.sub(r"\s+", " ", cleaned).strip()return cleaned or None@@ -117,10 +80,10 @@ class FeedAdapter:"""RSS 2.0 and Atom discovery using mature public feed protocols."""def __init__(self, *, timeout: float = 15.0, max_bytes: int = DEFAULT_MAX_BYTES,- transport: Callable[[urllib.request.Request, float, int], HttpResponse] = _read_http):+ transport: HttpTransport | None = None):self.timeout = timeoutself.max_bytes = max_bytes- self.transport = transport+ self.transport = transport or HttpxTransport()def fetch(self, url: str, *, etag: str | None = None,last_modified: str | None = None) -> FollowResult:@@ -133,10 +96,10 @@ class FeedAdapter:headers["If-None-Match"] = etagif last_modified:headers["If-Modified-Since"] = last_modified- request = urllib.request.Request(source_url, headers=headers)+ request = HttpRequest("GET", source_url, headers)try:response = self.transport(request, self.timeout, self.max_bytes)- except (OSError, urllib.error.URLError) as exc:+ except (OSError, httpx.HTTPError) as exc:raise FollowSourceError("follow source request failed") from excresponse_headers = {key.lower(): value for key, value in response.headers.items()}common = {@@ -150,61 +113,45 @@ class FeedAdapter:raise FollowSourceError(f"follow source returned HTTP {response.status}")if len(response.body) > self.max_bytes:raise FollowSourceError("follow source exceeded response size limit")- try:- root = ET.fromstring(response.body)- except ET.ParseError as exc:- raise FollowSourceError("follow source returned invalid XML") from exc- root_name = _local_name(root.tag)- if root_name == "rss":- entries = self._parse_rss(root)- elif root_name == "feed":- entries = self._parse_atom(root)- else:+ parsed = feedparser.parse(response.body)+ if not parsed.version or not (+ parsed.version.startswith("rss")+ or parsed.version.startswith("atom")+ or parsed.version.startswith("cdf")+ ):raise FollowSourceError("unsupported feed format")+ if parsed.bozo and not parsed.entries:+ raise FollowSourceError("follow source returned an invalid feed")+ entries = [self._normalize_entry(entry) for entry in parsed.entries]return FollowResult(entries=tuple(entries), raw_body=response.body, **common)@staticmethod- def _parse_rss(root: ET.Element) -> list[FollowEntry]:- channel = next((node for node in root if _local_name(node.tag) == "channel"), None)- if channel is None:- raise FollowSourceError("RSS feed has no channel")- entries = []- for item in _children(channel, "item"):- title = _child_text(item, "title") or "(untitled)"- url = _child_text(item, "link")- published = _child_text(item, "pubdate", "date")- author = _child_text(item, "author", "creator")- summary = _plain_text(_child_text(item, "description", "summary"))- guid = _child_text(item, "guid")- enclosure = next((node for node in item if _local_name(node.tag) == "enclosure"), None)- media_url = enclosure.get("url") if enclosure is not None else None- entries.append(FollowEntry(- external_id=guid or url or _stable_id(title, published, media_url),- title=title, url=url, media_url=media_url, published=published,- author=author, summary=summary,- ))- return entries-- @staticmethod- def _parse_atom(root: ET.Element) -> list[FollowEntry]:- entries = []- for item in _children(root, "entry"):- title = _child_text(item, "title") or "(untitled)"- links = _children(item, "link")- alternate = next((node for node in links if node.get("rel", "alternate") == "alternate"), None)- enclosure = next((node for node in links if node.get("rel") == "enclosure"), None)- author_node = next((node for node in item if _local_name(node.tag) == "author"), None)- author = _child_text(author_node, "name") if author_node is not None else None- url = alternate.get("href") if alternate is not None else None- media_url = enclosure.get("href") if enclosure is not None else None- published = _child_text(item, "published", "updated")- external_id = _child_text(item, "id") or url or _stable_id(title, published, media_url)- entries.append(FollowEntry(- external_id=external_id, title=title, url=url, media_url=media_url,- published=published, author=author,- summary=_plain_text(_child_text(item, "summary", "content")),- ))- return entries+ def _normalize_entry(entry) -> FollowEntry:+ title = _plain_text(entry.get("title")) or "(untitled)"+ url = entry.get("link") or None+ published = entry.get("published") or entry.get("updated") or None+ author = _plain_text(entry.get("author"))+ summary_value = entry.get("summary") or entry.get("description")+ if not summary_value and entry.get("content"):+ summary_value = entry.content[0].get("value")+ media_url = None+ for enclosure in entry.get("enclosures") or ():+ media_url = enclosure.get("href") or enclosure.get("url")+ if media_url:+ break+ external_id = (+ entry.get("id") or entry.get("guid") or url+ or _stable_id(title, published, media_url)+ )+ return FollowEntry(+ external_id=str(external_id),+ title=title,+ url=str(url) if url else None,+ media_url=str(media_url) if media_url else None,+ published=str(published) if published else None,+ author=author,+ summary=_plain_text(summary_value),+ )@dataclass(frozen=True)diff --git a/src/peach/http.py b/src/peach/http.pynew file mode 100644index 000000000..c1de52aec--- /dev/null+++ b/src/peach/http.py@@ -0,0 +1,76 @@+"""共享 HTTP transport:连接池、超时、有界读取与可注入测试边界。"""+from __future__ import annotations++from dataclasses import dataclass+from typing import Mapping, Protocol++import httpx+++@dataclass(frozen=True)+class HttpRequest:+ method: str+ url: str+ headers: Mapping[str, str]+ body: bytes | None = None+++@dataclass(frozen=True)+class HttpResponse:+ status: int+ headers: Mapping[str, str]+ body: bytes+++class HttpTransport(Protocol):+ def __call__(+ self,+ request: HttpRequest,+ timeout: float,+ max_bytes: int,+ ) -> HttpResponse: ...+++class HttpxTransport:+ """可跨请求复用的同步 HTTPX client;不会自动重试或持久化响应。"""++ def __init__(self, client: httpx.Client | None = None):+ self.client = client or httpx.Client(+ follow_redirects=True,+ limits=httpx.Limits(max_connections=32, max_keepalive_connections=16),+ headers={"User-Agent": "Peach/0.2"},+ )+ self._owns_client = client is None++ def __call__(+ self,+ request: HttpRequest,+ timeout: float,+ max_bytes: int,+ ) -> HttpResponse:+ chunks: list[bytes] = []+ total = 0+ with self.client.stream(+ request.method,+ request.url,+ headers=dict(request.headers),+ content=request.body,+ timeout=timeout,+ ) as response:+ for chunk in response.iter_bytes():+ remaining = max_bytes + 1 - total+ if remaining <= 0:+ break+ chunks.append(chunk[:remaining])+ total += min(len(chunk), remaining)+ if total > max_bytes:+ break+ return HttpResponse(+ response.status_code,+ dict(response.headers),+ b"".join(chunks),+ )++ def close(self) -> None:+ if self._owns_client:+ self.client.close()diff --git a/src/peach/jobs.py b/src/peach/jobs.pynew file mode 100644index 000000000..4060876be--- /dev/null+++ b/src/peach/jobs.py@@ -0,0 +1,120 @@+"""Peach 批处理任务共享的安全与成本策略。"""+from __future__ import annotations++import shutil+import os+from dataclasses import dataclass+from pathlib import Path+++class JobPolicyError(RuntimeError):+ exit_code = 1+++class MeteredSourceDenied(JobPolicyError):+ exit_code = 2+++class DiskSpaceDenied(JobPolicyError):+ exit_code = 3+++class JobAlreadyRunning(JobPolicyError):+ exit_code = 0+++@dataclass(frozen=True)+class SourceAccessPolicy:+ metered_locations: frozenset[str] = frozenset({"pikpak", "online"})++ def sql_filter(+ self,+ location: str | None,+ allow_metered: bool,+ column: str = "location",+ ) -> tuple[str, tuple[str, ...]]:+ """返回参数化 location 条件;显式计费授权是唯一放行入口。"""+ if location in self.metered_locations and not allow_metered:+ raise MeteredSourceDenied(+ f"{location} 是计费来源;确认预算后显式加 --allow-metered"+ )++ clauses: list[str] = []+ parameters: list[str] = []+ if location:+ clauses.append(f"{column}=?")+ parameters.append(location)+ if not allow_metered:+ metered = tuple(sorted(self.metered_locations))+ placeholders = ",".join("?" for _ in metered)+ clauses.append(f"{column} NOT IN ({placeholders})")+ parameters.extend(metered)+ if not clauses:+ return "", ()+ return " AND " + " AND ".join(clauses), tuple(parameters)+++def require_free_space(path: Path | str, minimum_gb: float) -> float:+ """返回可用 GiB;无法读取或低于阈值都拒绝启动,避免静默失去磁盘闸门。"""+ try:+ free_gb = shutil.disk_usage(path).free / 1024**3+ except OSError as exc:+ raise DiskSpaceDenied(f"无法读取 {path} 的磁盘余量") from exc+ if free_gb < minimum_gb:+ raise DiskSpaceDenied(+ f"{path} 仅剩 {free_gb:.1f} GiB(阈值 {minimum_gb:.1f} GiB)"+ )+ return free_gb+++class PidFileLock:+ """进程级独占锁;只清理确认已经不存在的旧 PID。"""++ def __init__(self, path: Path | str):+ self.path = Path(path)+ self._acquired = False++ @staticmethod+ def _running(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ return True++ def acquire(self) -> None:+ self.path.parent.mkdir(parents=True, exist_ok=True)+ try:+ descriptor = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)+ except FileExistsError:+ try:+ old_pid = int(self.path.read_text(encoding="ascii").strip())+ except (OSError, ValueError):+ old_pid = 0+ if old_pid and self._running(old_pid):+ raise JobAlreadyRunning(f"已有实例在跑(PID {old_pid})")+ try:+ self.path.unlink()+ except FileNotFoundError:+ pass+ descriptor = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)+ with os.fdopen(descriptor, "w", encoding="ascii") as handle:+ handle.write(str(os.getpid()))+ self._acquired = True++ def release(self) -> None:+ if self._acquired:+ try:+ self.path.unlink()+ except FileNotFoundError:+ pass+ self._acquired = False++ def __enter__(self) -> "PidFileLock":+ self.acquire()+ return self++ def __exit__(self, *_exc: object) -> None:+ self.release()diff --git a/src/peach/media.py b/src/peach/media.pyindex 6718c5901..64b23b444 100644--- a/src/peach/media.py+++ b/src/peach/media.py@@ -1,17 +1,17 @@-"""可替换 Media Engine 契约。"""+"""Peach 的唯一 Media Engine 与可替换 backend 契约。"""from __future__ import annotationsimport osfrom dataclasses import dataclassfrom pathlib import Path-from typing import Mapping, Protocol, Sequence+from typing import Protocol, Sequence-from .repository import LedgerRepository+from .repository import LedgerRepository, MediaAssetfrom .stash import StashClientdef normalized_path(path: Path | str) -> Path:- """Windows 离线/云盘可能让 realpath 失败;启动时仍需保留安全的绝对路径边界。"""+ """Windows 离线/云盘可能让 realpath 失败;仍保留绝对路径安全边界。"""candidate = Path(path)try:return candidate.resolve()@@ -19,9 +19,12 @@ def normalized_path(path: Path | str) -> Path:return Path(os.path.abspath(os.fspath(candidate)))-def remap_managed_path(path: Path | str, current_root: Path,- legacy_roots: Sequence[Path] = ()) -> Path:- """将数据迁移前的受控根路径映射到当前根,不接受任意 basename 搜索。"""+def remap_managed_path(+ path: Path | str,+ current_root: Path,+ legacy_roots: Sequence[Path] = (),+) -> Path:+ """将拆分前的受控根映射到当前根,不接受 basename 搜索。"""candidate = normalized_path(path)current = normalized_path(current_root)if candidate == current or current in candidate.parents:@@ -62,55 +65,54 @@ class MediaUnavailable(RuntimeError):pass-class FilesystemMediaService:- def __init__(self, repository: LedgerRepository, allowed_roots: Sequence[Path],- snapshot_root: Path, legacy_snapshot_roots: Sequence[Path] = ()):- self.repository = repository- self.allowed_roots = tuple(normalized_path(root) for root in allowed_roots)- self.snapshot_root = normalized_path(snapshot_root)- self.legacy_snapshot_roots = tuple(- normalized_path(root) for root in legacy_snapshot_roots- )-- 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 = (remap_managed_path(raw, self.snapshot_root, self.legacy_snapshot_roots)- if thumbnail else 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: strdef capabilities(self) -> MediaCapabilities: ...- def stream_candidates(self, asset: Mapping[str, object]) -> Sequence[StreamCandidate]: ...++ def stream_candidates(self, asset: MediaAsset) -> Sequence[StreamCandidate]: ...class FilesystemBackend:+ """原生文件 backend;路径授权、旧快照映射和存在性检查集中在这里。"""+name = "filesystem"- def __init__(self, allowed_roots: Sequence[Path]):+ def __init__(+ self,+ allowed_roots: Sequence[Path],+ snapshot_root: Path,+ legacy_snapshot_roots: Sequence[Path] = (),+ ):self.allowed_roots = tuple(normalized_path(root) for root in allowed_roots)+ self.snapshot_root = normalized_path(snapshot_root)+ self.legacy_snapshot_roots = tuple(+ normalized_path(root) for root in legacy_snapshot_roots+ )def capabilities(self) -> MediaCapabilities:return MediaCapabilities(probe=True, preview=True, direct_stream=True)- def stream_candidates(self, asset: Mapping[str, object]) -> Sequence[StreamCandidate]:- raw = asset.get("path")+ def file_for(self, asset: MediaAsset, thumbnail: bool = False) -> Path:+ raw = asset.snapshot_path if thumbnail else asset.pathif not raw:- return ()- path = normalized_path(str(raw))- if not any(path == root or root in path.parents for root in self.allowed_roots):+ raise MediaUnavailable(asset.id)+ path = (+ remap_managed_path(raw, self.snapshot_root, self.legacy_snapshot_roots)+ if thumbnail+ else 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++ def stream_candidates(self, asset: MediaAsset) -> Sequence[StreamCandidate]:+ try:+ path = self.file_for(asset)+ except MediaUnavailable:return ()return (StreamCandidate(self.name, "file", str(path)),)@@ -124,29 +126,63 @@ class StashAdapter:self.client = client or StashClient()def capabilities(self) -> MediaCapabilities:- return MediaCapabilities(probe=True, preview=True, direct_stream=True,- transcode=True, search=True)+ return MediaCapabilities(+ probe=True,+ preview=True,+ direct_stream=True,+ transcode=True,+ search=True,+ )- def stream_candidates(self, asset: Mapping[str, object]) -> Sequence[StreamCandidate]:- scene_id = asset.get("stash_scene_id")+ def stream_candidates(self, asset: MediaAsset) -> Sequence[StreamCandidate]:+ scene_id = asset.external_id("stash")if not scene_id:return ()payload = self.client.graphql("query($id:ID!){sceneStreams(id:$id){url mime_type label}}",- {"id": str(scene_id)},+ {"id": scene_id},)streams = payload.get("sceneStreams") or []return tuple(- StreamCandidate(self.name, "http", str(item["url"]),- item.get("mime_type"), item.get("label"))- for item in streams if item.get("url")+ StreamCandidate(+ self.name,+ "http",+ str(item["url"]),+ item.get("mime_type"),+ item.get("label"),+ )+ for item in streams+ if item.get("url"))+class MediaEngine:- def __init__(self, backends: Sequence[MediaBackend]):- self.backends = tuple(backends)+ """按 asset id 统一解析原生文件与外部媒体 backend。"""++ def __init__(+ self,+ repository: LedgerRepository,+ filesystem: FilesystemBackend,+ adapters: Sequence[MediaBackend] = (),+ ):+ self.repository = repository+ self.filesystem = filesystem+ self.backends: tuple[MediaBackend, ...] = (filesystem, *adapters)++ def capabilities(self) -> dict[str, MediaCapabilities]:+ return {backend.name: backend.capabilities() for backend in self.backends}++ def asset(self, asset_id: int) -> MediaAsset:+ asset = self.repository.media_asset(asset_id)+ if asset is None:+ raise MediaNotFound(asset_id)+ return asset++ def file_for(self, asset_id: int, thumbnail: bool = False) -> Path:+ return self.filesystem.file_for(self.asset(asset_id), thumbnail=thumbnail)- def stream_candidates(self, asset: Mapping[str, object]) -> tuple[StreamCandidate, ...]:+ def stream_candidates(self, asset_id: int) -> tuple[StreamCandidate, ...]:+ asset = self.asset(asset_id)candidates: list[StreamCandidate] = []for backend in self.backends:candidates.extend(backend.stream_candidates(asset))diff --git a/src/peach/providers.py b/src/peach/providers.pyindex 1cc428ab3..1643d30a6 100644--- a/src/peach/providers.py+++ b/src/peach/providers.py@@ -5,12 +5,14 @@ import shutilimport jsonimport threadingimport time-import urllib.error-import urllib.requestfrom dataclasses import asdict, dataclassfrom enum import Enumfrom typing import Callable, Protocol+import httpx++from .http import HttpRequest, HttpTransport, HttpxTransport+OPENCODE_GO_BASE_URL = "https://opencode.ai/zen/go/v1"@@ -19,22 +21,17 @@ class ProviderUnavailable(RuntimeError):pass-def _read_http(request: urllib.request.Request, timeout: float) -> bytes:- with urllib.request.urlopen(request, timeout=timeout) as response:- return response.read()--class OpenCodeGoClient:"""OpenCode Go public model discovery; completion protocols remain separate."""def __init__(self, api_key: str | None = None, *, base_url: str = OPENCODE_GO_BASE_URL,timeout: float = 10.0,- transport: Callable[[urllib.request.Request, float], bytes] = _read_http,+ transport: HttpTransport | None = None,cache_ttl: float = 300.0):self._api_key = api_keyself.base_url = base_url.rstrip("/")self.timeout = timeout- self.transport = transport+ self.transport = transport or HttpxTransport()self.cache_ttl = cache_ttlself._cache: tuple[float, list[dict]] | None = Noneself._lock = threading.Lock()@@ -51,11 +48,15 @@ class OpenCodeGoClient:headers = {"Accept": "application/json", "User-Agent": "Peach/0.2"}if self._api_key:headers["Authorization"] = "Bearer " + self._api_key- request = urllib.request.Request(self.base_url + "/models", headers=headers)+ request = HttpRequest("GET", self.base_url + "/models", headers)try:- raw = self.transport(request, self.timeout)- payload = json.loads(raw.decode("utf-8"))- except (OSError, UnicodeError, json.JSONDecodeError, urllib.error.URLError) as exc:+ response = self.transport(request, self.timeout, 1024 * 1024)+ if response.status != 200:+ raise ProviderUnavailable(+ f"OpenCode Go returned HTTP {response.status}"+ )+ payload = json.loads(response.body.decode("utf-8"))+ except (OSError, UnicodeError, json.JSONDecodeError, httpx.HTTPError) as exc:raise ProviderUnavailable("OpenCode Go model discovery failed") from excdata = payload.get("data") if isinstance(payload, dict) else Noneif not isinstance(data, list):diff --git a/src/peach/repository.py b/src/peach/repository.pyindex 2532a36e7..e6ca8699d 100644--- a/src/peach/repository.py+++ b/src/peach/repository.py@@ -10,7 +10,10 @@ class MediaAsset:id: intpath: str | Nonesnapshot_path: str | None- stash_scene_id: int | None+ bindings: tuple[tuple[str, str], ...] = ()++ def external_id(self, backend: str) -> str | None:+ return next((value for name, value in self.bindings if name == backend), None)class LedgerRepository:@@ -22,11 +25,21 @@ class LedgerRepository:connection.row_factory = sqlite3.Rowtry:row = connection.execute(- "SELECT id,path,snapshot_path,stash_scene_id FROM asset WHERE id=?",+ "SELECT id,path,snapshot_path FROM asset WHERE id=?",(asset_id,),).fetchone()+ bindings = connection.execute(+ "SELECT backend,external_id FROM media_binding WHERE asset_id=? "+ "ORDER BY backend,external_id",+ (asset_id,),+ ).fetchall() if row is not None else ()finally:connection.close()if row is None:return None- return MediaAsset(row["id"], row["path"], row["snapshot_path"], row["stash_scene_id"])+ return MediaAsset(+ row["id"],+ row["path"],+ row["snapshot_path"],+ tuple((item["backend"], item["external_id"]) for item in bindings),+ )diff --git a/src/peach/stash.py b/src/peach/stash.pyindex 24e712894..8eab0a55f 100644--- a/src/peach/stash.py+++ b/src/peach/stash.py@@ -1,10 +1,13 @@from __future__ import annotationsimport json-import urllib.requestfrom dataclasses import dataclassfrom typing import Mapping+import httpx++from .http import HttpRequest, HttpTransport, HttpxTransport+class StashError(RuntimeError):pass@@ -15,17 +18,21 @@ class StashClient:graphql_url: str = "http://127.0.0.1:9999/graphql"timeout: float = 10.0api_key: str | None = None+ transport: HttpTransport | None = Nonedef 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")+ transport = self.transport or HttpxTransport()+ request = HttpRequest("POST", self.graphql_url, headers, body)try:- with urllib.request.urlopen(request, timeout=self.timeout) as response:- result = json.load(response)- except Exception as exc:+ response = transport(request, self.timeout, 5 * 1024 * 1024)+ if response.status != 200:+ raise StashError(f"Stash returned HTTP {response.status}")+ result = json.loads(response.body)+ except (OSError, UnicodeError, json.JSONDecodeError, httpx.HTTPError) as exc:raise StashError(f"Stash request failed: {type(exc).__name__}") from excif result.get("errors"):raise StashError(str(result["errors"]))diff --git a/src/peach/web_contract.py b/src/peach/web_contract.pyindex 3cb7dc518..c73b24d0c 100644--- a/src/peach/web_contract.py+++ b/src/peach/web_contract.py@@ -35,6 +35,7 @@ class WebContract:self.write_lock = threading.Lock()self.cache: dict[str, tuple[float, object]] = {}self.cache_lock = threading.Lock()+ self._fts_available: bool | None = Nonedef cached(self, key, fn):now = time.time()@@ -68,6 +69,17 @@ class WebContract:) if self.snapshot_root is not None else Path(raw_path))return path.is_file()+ def has_fts(self) -> bool:+ if self._fts_available is None:+ connection = self.db()+ try:+ self._fts_available = connection.execute(+ "SELECT 1 FROM sqlite_schema WHERE type='table' AND name='asset_search'"+ ).fetchone() is not None+ finally:+ connection.close()+ return self._fts_available+# ────────────────────────────── 查询 ──────────────────────────────def q_items(contract: WebContract, args):@@ -109,13 +121,21 @@ def q_items(contract: WebContract, args):if args.get("orient"):where.append("a.ctx_orient = ?"); par.append(args["orient"])if args.get("q"):- where.append(- "(a.name LIKE ? OR a.code LIKE ? OR EXISTS("- "SELECT 1 FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "- "WHERE ae.asset_id=a.id AND e.kind IN ('creator','performer','studio') "- "AND e.canonical_name LIKE ?))"- )- s = f"%{args['q']}%"; par += [s, s, s]+ query = args["q"].strip()+ if len(query) >= 3 and contract.has_fts():+ where.append(+ "a.id IN (SELECT asset_id FROM asset_search WHERE asset_search MATCH ?)"+ )+ par.append('"' + query.replace('"', '""') + '"')+ else:+ where.append(+ "(a.name LIKE ? OR a.code LIKE ? OR EXISTS("+ "SELECT 1 FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "+ "WHERE ae.asset_id=a.id AND e.kind IN ('creator','performer','studio') "+ "AND e.canonical_name LIKE ?))"+ )+ pattern = f"%{query}%"+ par += [pattern, pattern, pattern]if args.get("state") == "fresh":where.append("(a.play_count IS NULL OR a.play_count=0) AND a.feedback IS NULL")elif args.get("state") == "played":diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex 65d6216fa..e05a50e9f 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -35,6 +35,9 @@ CREATE TABLE asset_entity(UNIQUE(asset_id,entity_id,role,source));CREATE TABLE watch_queue(profile_id TEXT,asset_id INTEGER,added_at TEXT,source TEXT,PRIMARY KEY(profile_id,asset_id));+CREATE TABLE media_binding(+ asset_id INTEGER,backend TEXT,external_id TEXT,metadata_json TEXT,last_synced_at TEXT,+ PRIMARY KEY(asset_id,backend),UNIQUE(backend,external_id));"""diff --git a/tests/test_follow.py b/tests/test_follow.pyindex e759f2278..3fddc91ab 100644--- a/tests/test_follow.py+++ b/tests/test_follow.py@@ -3,7 +3,8 @@ import tempfilefrom datetime import datetime, timezonefrom pathlib import Path-from peach.follow import FeedAdapter, FeedSnapshotStore, FollowSourceError, HttpResponse+from peach.follow import FeedAdapter, FeedSnapshotStore, FollowSourceError+from peach.http import HttpResponseclass FeedAdapterTests(unittest.TestCase):@@ -31,8 +32,8 @@ class FeedAdapterTests(unittest.TestCase):self.assertEqual(result.entries[0].external_id, "post-1")self.assertEqual(result.entries[0].summary, "Hello world")self.assertEqual(result.entries[0].media_url, "https://cdn.example.test/1.mp4")- self.assertEqual(calls[0][0].get_header("If-none-match"), '"v0"')- self.assertEqual(calls[0][0].get_header("If-modified-since"),+ self.assertEqual(calls[0][0].headers.get("If-None-Match"), '"v0"')+ self.assertEqual(calls[0][0].headers.get("If-Modified-Since"),"Wed, 13 Aug 2026 08:00:00 GMT")def test_atom_discovery_and_not_modified(self):@@ -54,6 +55,20 @@ class FeedAdapterTests(unittest.TestCase):self.assertTrue(cached.not_modified)self.assertEqual(cached.entries, ())+ def test_rss_one_namespace_is_supported_by_mature_parser(self):+ rdf = b"""<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'+ xmlns='http://purl.org/rss/1.0/' xmlns:dc='http://purl.org/dc/elements/1.1/'>+ <channel rdf:about='https://example.test/'><title>Example</title>+ <link>https://example.test/</link><description>Feed</description></channel>+ <item rdf:about='https://example.test/one'><title>One</title>+ <link>https://example.test/one</link><dc:creator>Alice</dc:creator></item>+ </rdf:RDF>"""+ result = FeedAdapter(transport=lambda *_: HttpResponse(200, {}, rdf)).fetch(+ "https://example.test/rss1"+ )+ self.assertEqual(result.entries[0].title, "One")+ self.assertEqual(result.entries[0].author, "Alice")+def test_rejects_unsafe_urls_oversized_and_invalid_feeds(self):adapter = FeedAdapter(transport=lambda *_: HttpResponse(200, {}, b"x" * 5), max_bytes=4)with self.assertRaisesRegex(FollowSourceError, "size limit"):diff --git a/tests/test_http.py b/tests/test_http.pynew file mode 100644index 000000000..ec90bdedd--- /dev/null+++ b/tests/test_http.py@@ -0,0 +1,26 @@+import unittest++import httpx++from peach.http import HttpRequest, HttpxTransport+++class HttpTransportTests(unittest.TestCase):+ def test_shared_transport_bounds_response_without_hiding_status(self):+ def handler(request: httpx.Request) -> httpx.Response:+ self.assertEqual(request.headers["X-Test"], "yes")+ return httpx.Response(304, headers={"ETag": '"v1"'}, content=b"abcdef")++ with httpx.Client(transport=httpx.MockTransport(handler)) as client:+ response = HttpxTransport(client)(+ HttpRequest("GET", "https://example.test/feed", {"X-Test": "yes"}),+ timeout=2,+ max_bytes=4,+ )+ self.assertEqual(response.status, 304)+ self.assertEqual(response.body, b"abcde")+ self.assertEqual(response.headers["etag"], '"v1"')+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_jobs.py b/tests/test_jobs.pynew file mode 100644index 000000000..7cc6b5589--- /dev/null+++ b/tests/test_jobs.py@@ -0,0 +1,52 @@+import tempfile+import unittest+from pathlib import Path+from unittest.mock import patch++from peach.jobs import (+ DiskSpaceDenied,+ JobAlreadyRunning,+ MeteredSourceDenied,+ PidFileLock,+ SourceAccessPolicy,+ require_free_space,+)+++class JobPolicyTests(unittest.TestCase):+ def test_metered_source_requires_explicit_authorization(self):+ policy = SourceAccessPolicy()+ with self.assertRaises(MeteredSourceDenied):+ policy.sql_filter("pikpak", allow_metered=False)++ def test_unmetered_query_uses_parameters_and_excludes_metered_sources(self):+ sql, parameters = SourceAccessPolicy().sql_filter("115", allow_metered=False)+ self.assertEqual(sql, " AND location=? AND location NOT IN (?,?)")+ self.assertEqual(parameters, ("115", "online", "pikpak"))++ def test_authorized_metered_query_is_scoped_to_requested_source(self):+ sql, parameters = SourceAccessPolicy().sql_filter("pikpak", allow_metered=True)+ self.assertEqual(sql, " AND location=?")+ self.assertEqual(parameters, ("pikpak",))++ def test_disk_guard_fails_closed_when_usage_is_unavailable(self):+ with patch("peach.jobs.shutil.disk_usage", side_effect=OSError("offline")):+ with self.assertRaises(DiskSpaceDenied):+ require_free_space(Path("C:/"), 40)++ def test_disk_guard_accepts_real_temporary_volume(self):+ with tempfile.TemporaryDirectory() as tmp:+ self.assertGreaterEqual(require_free_space(tmp, 0), 0)++ def test_pid_lock_rejects_live_owner_and_cleans_up(self):+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / "job.lock"+ with PidFileLock(path):+ self.assertTrue(path.is_file())+ with self.assertRaises(JobAlreadyRunning):+ PidFileLock(path).acquire()+ self.assertFalse(path.exists())+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_media.py b/tests/test_media.pyindex 3e11b9e10..013dc5769 100644--- a/tests/test_media.py+++ b/tests/test_media.py@@ -7,6 +7,7 @@ from peach.ffmpeg import FFmpegResolverfrom peach.media import (FilesystemBackend, MediaEngine, StashAdapter, normalized_path, remap_managed_path,)+from peach.repository import MediaAssetfrom peach.stash import StashClient@@ -16,10 +17,14 @@ class MediaEngineTests(unittest.TestCase):root = Path(tmp)inside = root / "media" / "one.mp4"outside = root.parent / "outside.mp4"- backend = FilesystemBackend([root])- result = backend.stream_candidates({"path": str(inside)})+ inside.parent.mkdir()+ inside.write_bytes(b"test")+ backend = FilesystemBackend([root], root / "snapshots")+ result = backend.stream_candidates(MediaAsset(1, str(inside), None))self.assertEqual(result[0].backend, "filesystem")- self.assertEqual(backend.stream_candidates({"path": str(outside)}), ())+ self.assertEqual(+ backend.stream_candidates(MediaAsset(2, str(outside), None)), ()+ )def test_stash_adapter_uses_public_stream_contract(self):client = StashClient()@@ -31,21 +36,42 @@ class MediaEngineTests(unittest.TestCase):"label": "HLS"},]}with patch.object(client, "graphql", return_value=payload) as graphql:- result = adapter.stream_candidates({"stash_scene_id": 42})+ result = adapter.stream_candidates(+ MediaAsset(1, None, None, (("stash", "42"),))+ )self.assertEqual([x.label for x in result], ["Direct", "HLS"])self.assertEqual(graphql.call_args.args[1], {"id": "42"})def test_engine_composes_backends_without_hidden_fallback(self):with tempfile.TemporaryDirectory() as tmp:- filesystem = FilesystemBackend([Path(tmp)])+ root = Path(tmp)+ media = root / "one.mp4"+ media.write_bytes(b"test")+ filesystem = FilesystemBackend([root], root / "snapshots")client = StashClient()stash = StashAdapter(client)+ repository = unittest.mock.Mock()+ repository.media_asset.return_value = MediaAsset(+ 1, str(media), None, (("stash", "42"),)+ )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})+ engine = MediaEngine(repository, filesystem, (stash,))+ result = engine.stream_candidates(1)self.assertEqual([x.backend for x in result], ["filesystem"])+ def test_engine_raises_for_unknown_asset(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ repository = unittest.mock.Mock()+ repository.media_asset.return_value = None+ engine = MediaEngine(+ repository,+ FilesystemBackend([root], root / "snapshots"),+ )+ with self.assertRaises(Exception) as raised:+ engine.file_for(404)+ self.assertEqual(type(raised.exception).__name__, "MediaNotFound")+def test_ffmpeg_resolver_prefers_explicit_environment(self):with tempfile.TemporaryDirectory() as tmp:root = Path(tmp)diff --git a/tests/test_migrations.py b/tests/test_migrations.pyindex 2fbdf9eca..a9add835c 100644--- a/tests/test_migrations.py+++ b/tests/test_migrations.py@@ -23,7 +23,7 @@ class MigrationTests(unittest.TestCase):sqlite3.connect(self.db).close()backup = self.root / "before.db"done = upgrade(self.db, MIGRATIONS, backup)- self.assertEqual([m.version for m in done], ["0000", "0001", "0002", "0003"])+ self.assertEqual([m.version for m in done], ["0000", "0001", "0002", "0003", "0004"])self.assertTrue(backup.exists())con = sqlite3.connect(self.db)tables = {row[0] for row in con.execute(@@ -36,8 +36,9 @@ class MigrationTests(unittest.TestCase):self.assertTrue({"asset", "profile", "media_binding", "activity_event","provider_profile", "entity", "entity_alias","entity_external_ref", "asset_entity", "entity_link",- "entity_search_term", "watch_queue", "schema_migration"} <= tables)- self.assertEqual(versions, ["0000", "0001", "0002", "0003"])+ "entity_search_term", "watch_queue", "asset_search",+ "schema_migration"} <= tables)+ self.assertEqual(versions, ["0000", "0001", "0002", "0003", "0004"])self.assertEqual(upgrade(self.db, MIGRATIONS), [])self.assertEqual(plan(self.db, MIGRATIONS)[1], [])@@ -108,6 +109,35 @@ class MigrationTests(unittest.TestCase):('creator','creator','legacy:asset'),('series','series','legacy:asset')} <= relations)+ def test_fts_tracks_asset_entity_alias_and_search_term_changes(self):+ sqlite3.connect(self.db).close()+ upgrade(self.db, MIGRATIONS)+ connection = sqlite3.connect(self.db)+ connection.executescript("""+ INSERT INTO asset(id,location,path,name,medium,code)+ VALUES(1,'local','one.mp4','Prestige sample.mp4','video','ABW-001');+ INSERT INTO entity(id,kind,canonical_name,normalized_name,created_at,updated_at)+ VALUES(1,'performer','高桥千凛','高桥千凛','now','now');+ INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence)+ VALUES(1,1,'performer','test',1.0);+ INSERT INTO entity_alias(entity_id,alias,normalized_alias,source,confidence)+ VALUES(1,'Takachi Chisato','takachi chisato','test',1.0);+ INSERT INTO entity_search_term(entity_id,term,purpose,source,created_at)+ VALUES(1,'private release keyword','source_lookup','test','now');+ """)+ for query in ('"Prestige"', '"高桥千"', '"Takachi"', '"release keyword"'):+ self.assertEqual(connection.execute(+ "SELECT asset_id FROM asset_search WHERE asset_search MATCH ?", (query,)+ ).fetchall(), [(1,)])+ connection.execute("UPDATE asset SET name='Renamed title.mp4' WHERE id=1")+ self.assertEqual(connection.execute(+ "SELECT asset_id FROM asset_search WHERE asset_search MATCH ?", ('"Renamed"',)+ ).fetchall(), [(1,)])+ self.assertEqual(connection.execute(+ "SELECT asset_id FROM asset_search WHERE asset_search MATCH ?", ('"Prestige"',)+ ).fetchall(), [])+ connection.close()+if __name__ == "__main__":unittest.main()diff --git a/tests/test_providers.py b/tests/test_providers.pyindex ca9e8e20b..4b04bed42 100644--- a/tests/test_providers.py+++ b/tests/test_providers.py@@ -42,12 +42,13 @@ class ProviderRegistryTests(unittest.TestCase):def test_opencode_model_discovery_is_normalized_and_cached(self):calls = []- def transport(request, timeout):- calls.append((request.full_url, request.get_header("Authorization"), timeout))- return json.dumps({"object": "list", "data": [+ def transport(request, timeout, max_bytes):+ calls.append((request.url, request.headers.get("Authorization"), timeout, max_bytes))+ from peach.http import HttpResponse+ return HttpResponse(200, {}, json.dumps({"object": "list", "data": [{"id": "kimi-k3", "object": "model", "owned_by": "opencode", "extra": "drop"},{"missing": "id"},- ]}).encode()+ ]}).encode())client = OpenCodeGoClient("test-secret", transport=transport, cache_ttl=300, timeout=3,@@ -62,12 +63,15 @@ class ProviderRegistryTests(unittest.TestCase):self.assertEqual(second, first)self.assertEqual(len(calls), 1)self.assertEqual(calls[0], (- "https://opencode.ai/zen/go/v1/models", "Bearer test-secret", 3,+ "https://opencode.ai/zen/go/v1/models", "Bearer test-secret", 3, 1024 * 1024,))self.assertNotIn("test-secret", repr(first))def test_opencode_invalid_payload_is_provider_error(self):- client = OpenCodeGoClient(transport=lambda *_: b'{"unexpected":true}')+ from peach.http import HttpResponse+ client = OpenCodeGoClient(+ transport=lambda *_: HttpResponse(200, {}, b'{"unexpected":true}')+ )with self.assertRaises(ProviderUnavailable):client.list_models()diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex ca4648673..a9ca9d263 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -27,11 +27,47 @@ class OperationalScriptTests(unittest.TestCase):def setUpClass(cls):cls.clean_names = load_script("clean_names")cls.scrape_codes = load_script("scrape_codes")+ cls.find_ads = load_script("find_ads")+ cls.probe = load_script("probe")+ cls.sheets = load_script("sheets")+ cls.traffic_watch = load_script("traffic_watch")+ cls.creator_boards = load_script("creator_boards")def test_import_has_no_filesystem_or_log_side_effect(self):self.assertIsNone(self.clean_names._logf)self.assertIsNone(self.scrape_codes._logf)+ def test_ad_candidate_scan_is_isolated_and_review_only(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ db = root / "ledger.db"+ connection = sqlite3.connect(db)+ connection.execute(+ "CREATE TABLE asset(id INTEGER,location TEXT,path TEXT,name TEXT,"+ "size INTEGER,duration REAL,medium TEXT)"+ )+ for asset_id in range(1, 4):+ connection.execute(+ "INSERT INTO asset VALUES(?,?,?,?,?,?,?)",+ (+ asset_id,+ "local",+ str(root / "pack" / f"promo-{asset_id}.mp4"),+ f"promo-{asset_id}.mp4",+ 10 * 1024**2,+ 37.4,+ "video",+ ),+ )+ connection.commit()+ connection.close()++ plan, scanned = self.find_ads.find_candidates(db, min_group=3)+ self.assertEqual(scanned, 3)+ self.assertEqual(len(plan), 3)+ self.assertTrue(all("等长重复x3" in row["hits"] for row in plan))+ self.assertFalse((root / "ad-candidates.csv").exists())+def test_filename_cleanup_is_conservative(self):propose = self.clean_names.proposeself.assertEqual(propose("[email protected]"), "sample.mp4")@@ -39,12 +75,50 @@ class OperationalScriptTests(unittest.TestCase):self.assertEqual(propose("sample.mp4.jpg"), "sample.mp4.jpg")self.assertEqual(propose("(3).mp4"), "(3).mp4")+ def test_media_batch_scripts_are_import_safe_and_keep_context_rules(self):+ self.assertEqual(self.probe.context_fields(1920, 1080, 180), ("速食", "横屏", "2K"))+ with tempfile.TemporaryDirectory() as tmp:+ output = self.sheets.output_path(Path(tmp), "local", "R:/media/one.mp4")+ self.assertFalse(output.exists())+ self.assertTrue(output.parent.is_dir())+ self.assertTrue(self.traffic_watch.is_direct({"chains": ["DIRECT"]}))+ self.assertFalse(self.traffic_watch.is_direct({"chains": ["Proxy", "Relay"]}))+ self.assertEqual(self.creator_boards.safe_name("A/B:C"), "A_B_C")+def test_code_normalization(self):normalise = self.scrape_codes.normaliseself.assertEqual(normalise("fc2ppv-1234567"), "FC2-PPV-1234567")self.assertEqual(normalise("abw123"), "ABW-123")self.assertEqual(normalise("ipvr00296"), "IPVR-296")+ def test_scrape_html_adapters_use_structured_parsing(self):+ avsox_search = '<a href="/cn/movie/abc123">result</a>'+ self.assertEqual(+ self.scrape_codes.avsox_movie_url(avsox_search),+ "https://avsox.click/cn/movie/abc123",+ )+ avsox = self.scrape_codes.parse_avsox("""+ <h3>Example <b>Title</b></h3>+ <p><span>制作商:</span><a href="/studio/a">Studio A</a></p>+ <a class="avatar-box"><span>Alice</span></a>+ <a class="avatar-box"><span>Bob</span></a>+ """)+ self.assertEqual(avsox["performers"], "Alice|Bob")+ self.assertEqual(avsox["studio"], "Studio A")+ self.assertEqual(avsox["title"], "Example Title")++ javbus = self.scrape_codes.parse_javbus("""+ <h3>Bus <em>Title</em></h3>+ <p><span>製作商:</span><a href="/studio/p">Prestige</a></p>+ <p><span>發行商:</span><a href="/label/l">Label A</a></p>+ <p><span>系列:</span><a href="/series/s">Series A</a></p>+ <a href="/star/alice"><span class="star-name">Alice</span></a>+ """)+ self.assertEqual(javbus["performers"], "Alice")+ self.assertEqual(javbus["studio"], "Prestige")+ self.assertEqual(javbus["label"], "Label A")+ self.assertEqual(javbus["series"], "Series A")+def test_scrape_writeback_dual_writes_projection_and_entities(self):with tempfile.TemporaryDirectory() as tmp:root = Path(tmp)diff --git a/tests/test_stash_entity_import.py b/tests/test_stash_entity_import.pyindex 29453713e..18b8df466 100644--- a/tests/test_stash_entity_import.py+++ b/tests/test_stash_entity_import.py@@ -1,9 +1,12 @@import importlib.util+import ioimport sqlite3import tempfileimport unittestfrom pathlib import Path+from PIL import Image+ROOT = Path(__file__).resolve().parents[1]SPEC = importlib.util.spec_from_file_location(@@ -61,11 +64,13 @@ class StashEntityImportTests(unittest.TestCase):self.assertIn("Performer summary", metadata)def test_reads_png_and_jpeg_dimensions(self):- png = b"\x89PNG\r\n\x1a\n" + b"\x00" * 8 + (600).to_bytes(4, "big") + (800).to_bytes(4, "big")- jpeg = (b"\xff\xd8\xff\xc0\x00\x11\x08" + (700).to_bytes(2, "big")- + (500).to_bytes(2, "big") + b"\x03" + b"\x00" * 20)- self.assertEqual(MODULE.image_size(png), (600, 800))- self.assertEqual(MODULE.image_size(jpeg), (500, 700))+ png_buffer = io.BytesIO()+ jpeg_buffer = io.BytesIO()+ Image.new("RGB", (600, 800)).save(png_buffer, format="PNG")+ Image.new("RGB", (500, 700)).save(jpeg_buffer, format="JPEG")+ self.assertEqual(MODULE.image_size(png_buffer.getvalue()), (600, 800))+ self.assertEqual(MODULE.image_size(jpeg_buffer.getvalue()), (500, 700))+ self.assertIsNone(MODULE.image_size(b"\x89PNG\r\n\x1a\n" + b"broken"))if __name__ == "__main__":