Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat: add reviewed JAV release dates and source priority

longmeidao25ba2c01cc00
diff --git a/README.md b/README.md
index 075fa2ac2..d059e1b25 100644
--- a/README.md
+++ b/README.md
@@ -355,7 +355,7 @@ Per-Monitor V2 DPI,单击打开 `https://peach-win.local/`;右键可同步 L
## 批处理安全边界
-`scripts/scrape_codes.py` 只把规范化番号交给固定版本 Javinizer-Go,逐来源保存原始 JSON 并生成字段候选 CSV;它没有整批 `--apply`,只有 `/review` 中明确选中某个来源值并批准才写 ledger。`scripts/clean_names.py` 默认只生成改名计划;`--apply` 会先备份 SQLite,并在数据库更新失败时把文件名回滚。两者导入模块时均无副作用,测试不得使用真实路径。
+`scripts/scrape_codes.py` 只把规范化番号交给固定版本 Javinizer-Go,逐来源保存原始 JSON,并为演员、厂牌、系列、发行日期和内容标签生成字段候选;官方/官方镜像标签来源优先。它没有整批 `--apply`,只有 `/review` 中明确选中某个来源值并批准才写 ledger。`scripts/clean_names.py` 默认只生成改名计划;`--apply` 会先备份 SQLite,并在数据库更新失败时把文件名回滚。两者导入模块时均无副作用,测试不得使用真实路径。
历史创作者投影使用逐项只读审计,不再把目录名直接当身份:
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index 5f8c14551..c1fb4f0a9 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -123,7 +123,7 @@ Claude 的 `.claude/settings.json` 已配置 Stop、StopFailure、SessionEnd hoo
- **标签添加弹窗(2026-08-15)**:用户提供 macOS 标签管理弹窗截图,未提供产品名或可访问 URL,源码证据为 `未取得`。Peach 只复用截图可证实的交互层级:搜索、最近使用、全部标签、已选状态和键盘上下/Enter/Escape;不声称像素或源码级复刻。
- **YouTube 详情参考(2026-08-17)**:实时取得 `https://www.youtube.com/watch?v=dQw4w9WgXcQ` 当前页面 HTML;页面使用 `Roboto`、暗色详情播放器与高对比控制条,播放器资源预加载 `hqdefault.jpg`,当前页面 bundle 版本由 WIZ 配置标识为 `youtube.web-front-end-critical_20260811.08_p0`。用户同时提供详情/卡片截图。Peach 只复用可复现的层级原则:详情操作采用连续圆角操作组、hover 提亮、active 使用蓝色语义;播放区 ambient 使用模糊画面并向上下渐隐。未复制 YouTube 品牌、播放器源码或登录能力。
- **YouTube Shorts 播放/动作栏参考(2026-08-17)**:实时取得 `https://www.youtube.com/shorts/BJynPKgwfyA`,页面 `INNERTUBE_CLIENT_VERSION=2.20260813.05.00`;协作浏览器快照未取得,但运行时 DOM/CSS 可复核。`#shorts-player` 为 `396×704`,视频 `object-fit:cover`;右侧动作容器宽 `72px`、左右内边距 `12px`;动作按钮为 `48×48px`、`rgba(255,255,255,.1)`、圆角 `24px`,文字位于独立的垂直标签容器;全屏按钮同为 `48px` 圆形。Peach 复用全视口 cover、48px tonal 圆形和克制的动作层级,保留自己的 Lucide 图标、色彩 token、横竖屏混流和业务反馈语义。
-- **Javinizer-Go 元数据 Provider(2026-08-22)**:取得官方仓库 `https://github.com/javinizer/javinizer-go`、v1.5.1 release 与 tag commit `f57985c8c98a0ad7283f72854c249b8612300637`;本机 `javinizer-darwin-arm64` SHA-256 `6197d78c561a05a42c9ef0e3896991d6f5e46d863595d25ed13de0139d0f179d` 与发布清单一致,并用 `IPX-535` 验证单来源 JSON。Peach 复用 query-only `scrape --output json --scrapers <source>` 和结构化错误;主动差异是仅发送规范番号、自己逐源留原始证据和形成字段候选,批准后才写 ledger,且不使用其 DB/organizer。
+- **Javinizer-Go 元数据 Provider(2026-08-22)**:取得官方仓库 `https://github.com/javinizer/javinizer-go`、v1.5.1 release 与 tag commit `f57985c8c98a0ad7283f72854c249b8612300637`;macOS arm64 SHA-256 `6197d78c…f179d`、Windows amd64 SHA-256 `4d5b0bc6…1abca` 均与发布值一致。Windows 必须锁定 subprocess UTF-8,且 r18dev 要显式绑定 `scrapers.r18dev.proxy.profile` 才走 7897。`IPX-535` 已验证真实单来源 JSON;Peach 只发送规范番号、逐源留原始证据,并为演员/厂牌/系列/发行日期/内容标签形成字段候选,官方 tag 优先,批准后才写 ledger,不使用其 organizer。
## 智能体用量与任务路由
- 调度看官方配额窗口,不看 API 等价美元估算。Codex 使用 App Server `account/rateLimits/read`;Claude 使用 Claude Code 已登录用量界面。不得打印、复制或保存 OAuth token。
diff --git a/docs/REUSE.md b/docs/REUSE.md
index b1f7ce1d4..2834421d9 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -25,7 +25,7 @@
| 位图 | Pillow | 头像/Logo 质量和来源策略 |
| 搜索 | SQLite FTS5 | 索引字段、排序、profile 感知筛选 |
| 女优姓名对照 | `li-peifeng/Jav-Actors-Mapping` 的固定 revision,仅作私有输入(仓库未声明许可证,不随 Peach 分发) | 精确匹配、冲突复核、别名、来源与真实 ledger 写入 |
-| JAV 元数据查询 | Javinizer-Go v1.5.1 单来源 JSON CLI(MIT) | 只发送规范番号;逐源原始证据、字段候选、重复值硬门槛、人工批准和 ledger 投影 |
+| JAV 元数据查询 | Javinizer-Go v1.5.1 单来源 JSON CLI(MIT) | 只发送规范番号;逐源原始证据、发行日期/实体/标签字段候选、官方 tag 优先、重复值硬门槛、人工批准和 ledger 投影 |
| 媒体探测/转码 | Peach 管理的 FFmpeg/ffprobe | 任务策略和 Media Engine 编排 |
| HTML5/HLS/DASH 播放 | Video.js 8.23.9 + 内置 VHS(Apache-2.0,本地固定版本) | 流方案、授权、稳定时长、回退顺序和统计面板 |
| 图标 | 固定版本的本地 Lucide 子集;Health Icons 24 px outline(CC0)用于领域图标 | 标签、状态和交互设计 |
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 828b7442f..ec455f186 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -81,7 +81,7 @@
- 回收站有独立入口 `peach.local/trash`(后端 `/trash` 走 SPA,前端 `restoreRoute` 直接进 `state=trash`)。
- 疑似广告是处置队列:队列说明行随页面正常滚走,不复用普通作品列表的 sticky 排序栏。批量或详情加入回收站后会立即刷新队列;Ledger 冲突等非 2xx 写入会明确报错,不再把错误 JSON 当成功后让条目原样出现。
- 回收站的两条删除路径此前从未真正执行过,已修复:`media.py` 漏 `from functools import lru_cache` 导致整个包 import 失败;`ASSET_REFERENCE_TABLES` 从未定义,`/api/batch` 的 `delete` 必然 `NameError`;`/api/trash/empty` 只加了 dispatch 分支、`w_empty_trash` 没有函数体。现已统一到 `purge_assets()` 并补齐数据层测试。之前「API 写读删已复核」的说法不成立,属于未验证即结论。
-- 管理界面 `/review` 已覆盖元数据字段、创作者标签、厂牌 Logo、女优头像、西方身份、番号目录、封面来源、FC2 评论标记和媒体失败。Javinizer-Go 元数据按「番号 × 字段」并列来源候选,批准必须选中具体来源值;服务端从当前 CSV 重取权威值并留下 candidate/source provenance。演员只写 performer 与兼容标签,不写 `asset.creator`;所有实体名在候选生成和批准写入两层拦截重复片段。
+- 管理界面 `/review` 已覆盖元数据字段、创作者标签、厂牌 Logo、女优头像、西方身份、番号目录、封面来源、FC2 评论标记和媒体失败。Javinizer-Go 元数据按「番号 × 字段」并列演员、厂牌、系列、发行日期和标签候选,官方/官方镜像 tag 优先;批准必须选中具体来源值,服务端从当前 CSV 重取权威值并留下 candidate/source provenance。演员只写 performer 与兼容标签,不写 `asset.creator`;所有实体名在候选生成和批准写入两层拦截重复片段。
- HLS 除开头一两段外全部失败过,2026-08-18 已修复。`-copyts` 保留原始时间轴后,FFmpeg 把 `-t` 当成绝对结束时刻而不是片段时长,每段的 `-t` 都约等于一个片段长,起点超过它的片段一律「已经过期」,FFmpeg 以退出码 0、空 stderr 写出 0 字节,服务端只能报一句没有内容的 `ffmpeg failed`。实测 asset 6562(6,332 秒):片段 0、1 返回 200,片段 2 与 300 都是 503;片段缓存目录里 6562、29914、19490 三个资产也都只留下 `0.ts` 与 `1.ts`。所以症状不只是拖不动,播到约 20 秒就会断。修法是保留 `-copyts`、把 `-t 时长` 换成绝对终点 `-to 起点+时长`;删掉 `-copyts` 同样能出片,但首个 PTS 会退回 0.069,每段都自称从 0 开始,正是当初引入 `-copyts` 要解决的拖动跳位。隔离实例实测片段 2、300、633 全部返回 200(47.2 MB、41.1 MB、69.3 MB),手工核验片段 300 首个 PTS 为 2997.995,绝对位置与跨段连续性都对。生产托盘已于 2026-08-18 重启并复验:asset 6562 的片段 2、300 与 asset 29914 的片段 5 均返回 200。
- 同批把静默失败改为自陈:FFmpeg 退出码 0、stderr 全空却写出 0 字节时,错误信息带上 `returncode`、字节数与 `ss`/`to`,不再只说 `ffmpeg failed`。上面那个缺陷能藏这么久,正是因为日志里那句话什么都没说。
- 远端 MP4 已改为默认标准 Range,HLS 转为按需(`/api/stream-plan?mode=hls`),见 ADR-0016。起因是 asset 22716(115 的 HEVC 重制 MP4)在详情页黑屏:分片全部 200、数据进了缓冲、时间轴照走,但 `videoWidth=0`、解码 0 帧、无 error 事件。`-c copy` 把 HEVC 原样装进 MPEG-TS,而 Chromium 的 MSE 不支持 TS 里的 HEVC;同一浏览器实测 `video/mp2t; codecs="hvc1…"` 为 `false`、`video/mp4; codecs="hvc1…"` 为 `true`,直接 Range 播同一文件解码 997 帧、拖动后继续出帧。文件名含 `HEVC` 的 115 视频有 248 条、PikPak 2 条,此前全部受影响。生产重启后复验 22716:默认计划为 `range`,`mode=hls` 仍给出 76 段计划,播放列表返回 200;详情页取到 `/stream?id=22716`、`readyState=4`、`1920×1080`,当前帧平均亮度 147.1、非黑像素 99.3%。
@@ -154,7 +154,7 @@
- 2026-08-21 macOS 最新基线:`./scripts/test.sh` 全量 468 项通过、3 项跳过;Windows 当前状态提交
`& .\scripts\test.ps1` 全量 460 项通过、12 项按平台跳过;上下文预算检查通过。
-- 2026-08-22 Javinizer-Go P0 在 macOS 隔离 worktree 通过 `./scripts/test.sh` 全量 490 项(3 项按平台跳过);固定 v1.5.1 arm64 二进制校验和与官方一致,公开番号 `IPX-535` 的真实单来源 JSON、临时 ledger 候选生成、1440×1000 与 390×844 复核页均通过。Windows 二进制、Windows 测试、真实 ledger 批次、人工批准和生产服务重启均未执行,不能描述为已部署。
+- 2026-08-22 Javinizer-Go P0 已完成 Windows 接续:e390 与 5fcc 的整合提交 `47d6b84` 保留字段候选与全入口 person 门槛;Windows amd64 v1.5.1 安装于 `peach-data/tools/javinizer/v1.5.1/windows-amd64/javinizer.exe`,SHA-256 `4d5b0bc6a655f765325e55a6638795ac39cd01f11a7c3c40066e5fac79f1abca`。Windows 全量测试 495 项通过、12 项跳过;`IPX-535` 临时库真实 r18dev 生成 5 个字段组。真实 ledger 的 limit=10 联网批生成 43 组(演员10、厂牌10、系列4、发行日期10、标签9),10 份 raw JSON、错误0;紧窗口只读重放 generation 29→29,asset 81,657、asset_entity 155,894、asset_tag 88,049、entity 8,185、review_decision 14 均未变,完整性 `ok`。隔离迁移副本的 `/review` 在 1280×720 与 390×844 无横向溢出、控制台零错误,未批准候选。生产因 PikPak `probe.py --workers 6` 夜跑仍在进行而未应用 `0016`、未重启,不能描述为已部署。
- Windows 无外置盘生产验收:HTTP 与严格 CA HTTPS `/healthz` 返回 200,账本、FFmpeg、115 和
PikPak 可用,只有 `local` 来源离线;115 HTTP 与 PikPak 严格 HTTPS 各完成 1 KiB `206` Range。
- 双机同时在线时账本世代 18、状态 `in-sync`;`peach-win.local` 与 `peach.local` 分别只由
@@ -175,7 +175,7 @@ artifact 拆分、生成资产的跨机同步,以及 macOS 拔盘后的完整
6. Windows writer 执行 PikPak 视觉夜跑:先用 `probe.py --redo all` 重探当前 5,445 条失败/零时长,再只跑官方封套与九帧缩略图。generation 29 的 Mac 副本基线为可直接抽 4,740、需重探 5,445、短于等于 2 秒 11;Windows 起跑前重算。第一晚以 200 GB 流量守卫与 40 GiB 系统盘闸门为硬上限,允许安全中止和续跑,不承诺一夜全量完成。
7. 115 抽帧失败的大小写部分已修复:`peach.media.resolve_case_insensitive` 与 `FilesystemBackend.file_for`、`scripts/sheets.py`、`scripts/probe.py` 的 worker 均已接入;2026-08-17 重跑 33 条九帧,31 成功、2 失败。这 2 条的原因已查清(见上一节):`18349` 是 ledger 时长记错、`12510` 是片源头损坏。2026-08-18 已全部收尾:`sheets.py` 区分失败原因、`probe.py`/`sheets.py` 新增 `--asset`、`18349` 重探重抽成功、`12510` 判为坏片源并留痕,详见上一节。`sheets.py` 遇 `prim:reserved` 非法色彩元数据的重试已完成并有测试。
8. HLS `stream-plan` 和按需 TS 片段已接入现有 Video.js 内置 VHS。片段时间窗的绝对终点问题已修并已切生产(见上节);自适应码率、多路清单、首帧/seek 的桌面与手机验收仍未完成。CloudDrive 约 100 MiB 固定块预取仍是来源层成本,服务端分片只能避免整部 MP4 Range,不会消除来源层块预取。
-9. 在 Windows 数据工具目录安装并校验 Javinizer-Go v1.5.1 amd64,跑 `r18dev` 小批真实候选后从 `/review` 人工批准;确认来源质量再逐个启用 Javinizer 已有 scraper,不新增 Peach 私有站点解析器。
+9. PikPak 夜跑结束后按迁移门槛应用 `0016`、重启生产,再从 `/review` 人工批准 Windows r18dev 小批候选;确认来源质量后逐个启用 Javinizer 已有 scraper,不新增 Peach 私有站点解析器。
10. 配置可复核的真实追更源,之后再接 APScheduler;AI 结果继续只作为候选。
11. Codex 侧封装技能:`.claude/skills/` 下的六个技能目前只有 Claude 会按 description 自动触发,
Codex 只能靠 `AGENTS.md` 索引表主动读。由 Codex 接手时确认当前版本的技能机制与目录约定,
diff --git a/docs/adr/0006-external-metadata-batch-boundary.md b/docs/adr/0006-external-metadata-batch-boundary.md
index 1b949fbc9..16a070d79 100644
--- a/docs/adr/0006-external-metadata-batch-boundary.md
+++ b/docs/adr/0006-external-metadata-batch-boundary.md
@@ -14,6 +14,7 @@ Peach 需要在线补充番号的 performer、studio、series 和内容分类,
- 抓取先写逐来源原始 JSON 和可续跑的字段候选 CSV;只有 `/review` 对具体来源值的显式批准才写 ledger,不保留整批 `--apply` 后门。
- 写入同时包含 source/confidence/provenance,并双写规范 `entity`/`asset_entity` 与当前 UI 兼容投影。
- 默认查询适配器固定为 Javinizer-Go v1.5.1 的单来源 JSON CLI;Peach 自己聚合来源、规范化字段、保存证据和执行批准,绝不调用其 organizer 或让其持有 Peach 数据库。
+- P0 字段覆盖演员、厂牌、系列、发行日期和内容标签;发行时间只落 `YYYY-MM-DD`,官方/官方镜像 tag 来源排在社区来源前,仍须逐项批准。
- 对 403/429/503 做来源级冷却;HTML 来源视为易变 adapter,失败不得阻塞 Peach。
- 导入脚本本身无副作用,网络和真实数据库操作只发生在 `main()` 的显式命令路径。
diff --git a/migrations/0016_asset_release_date.sql b/migrations/0016_asset_release_date.sql
new file mode 100644
index 000000000..133b57ed3
--- /dev/null
+++ b/migrations/0016_asset_release_date.sql
@@ -0,0 +1 @@
+ALTER TABLE asset ADD COLUMN release_date TEXT;
diff --git a/scripts/ledger.py b/scripts/ledger.py
index de10614f3..a2ea662da 100644
--- a/scripts/ledger.py
+++ b/scripts/ledger.py
@@ -39,7 +39,7 @@ CREATE TABLE IF NOT EXISTS asset(
name TEXT, medium TEXT, -- video/image/audio/archive/game/illustration/account
size INTEGER, mtime TEXT,
hash_kind TEXT, hash TEXT,
- creator TEXT, studio TEXT, series TEXT, code TEXT,
+ creator TEXT, studio TEXT, series TEXT, code TEXT, release_date TEXT,
duration REAL, width INTEGER, height INTEGER, vcodec TEXT, fps REAL, has_audio INTEGER,
ctx_length TEXT, ctx_orient TEXT, ctx_quality TEXT, ctx_pace TEXT, ctx_people TEXT,
play_count INTEGER DEFAULT 0, last_played TEXT, rating INTEGER, o_count INTEGER, watch_ratio REAL,
diff --git a/scripts/scrape_codes.py b/scripts/scrape_codes.py
index b280c970b..da6f9eac6 100644
--- a/scripts/scrape_codes.py
+++ b/scripts/scrape_codes.py
@@ -29,12 +29,21 @@ from peach.metadata import (
_logf = None
-FIELD_LABELS = {"performers": "演员", "studio": "厂牌", "series": "系列", "tags": "内容标签"}
+FIELD_LABELS = {
+ "performers": "演员", "studio": "厂牌", "series": "系列",
+ "release_date": "发行日期", "tags": "内容标签",
+}
FIELDS = [
"item_key", "code", "query", "field", "field_label", "current_value",
"candidates_json", "source_count", "status", "size_gb", "videos", "fetched_at",
]
ERROR_FIELDS = ["code", "query", "source", "kind", "status_code", "retryable", "message"]
+TAG_SOURCE_PRIORITY = {
+ "dmm": 100, "mgstage": 100, "tokyohot": 100, "aventertainment": 100,
+ "caribbeancom": 100, "fc2": 100, "r18dev": 90, "libredmm": 90,
+ "javstash": 70, "javdb": 50, "javbus": 40, "javlibrary": 40,
+ "jav321": 30, "dlgetchu": 30,
+}
# Javinizer r18dev genre -> Peach's reviewed content taxonomy. Unknown source values
@@ -112,7 +121,11 @@ def _candidate_key(code: str, field: str, source: str, value: object) -> str:
def _current_values(connection: sqlite3.Connection, code: str, field: str) -> list[str]:
- if field in {"studio", "series"}:
+ if field in {"studio", "series", "release_date"}:
+ if field == "release_date" and field not in {
+ str(row[1]) for row in connection.execute("PRAGMA table_info(asset)")
+ }:
+ return []
rows = connection.execute(
f"SELECT DISTINCT trim({field}) FROM asset WHERE medium='video' "
f"AND upper(trim(code))=upper(?) AND {field} IS NOT NULL AND trim({field})<>''",
@@ -251,11 +264,14 @@ def main(argv: list[str] | None = None, *, provider: JavinizerGoProvider | None
log(f"{source} 暂时不可用,本批后续番号进入来源级冷却:{error}")
continue
for field, extracted in extract_peach_fields(payload, CATEGORY_MAP).items():
+ tag_priority = TAG_SOURCE_PRIORITY.get(source, 10) if field == "tags" else 0
candidate = {
"candidate_key": _candidate_key(query, field, source, extracted["value"]),
"source": source,
"source_url": str(payload.get("source_url") or ""),
"confidence": 0.9 if source == "r18dev" else 0.75,
+ "priority": tag_priority,
+ "official": bool(field == "tags" and tag_priority >= 90),
"value": extracted["value"],
"display_value": extracted["display_value"],
"warnings": extracted["warnings"],
@@ -265,6 +281,12 @@ def main(argv: list[str] | None = None, *, provider: JavinizerGoProvider | None
if args.delay > 0:
time.sleep(args.delay + random.uniform(0, min(0.4, args.delay / 3)))
for field, candidates in by_field.items():
+ if field == "tags":
+ candidates.sort(key=lambda item: (
+ -int(item.get("priority") or 0),
+ -float(item.get("confidence") or 0),
+ str(item.get("source") or ""),
+ ))
candidate_writer.writerow({
"item_key": f"{query}:{field}", "code": code, "query": query,
"field": field, "field_label": FIELD_LABELS[field],
diff --git a/src/peach/metadata.py b/src/peach/metadata.py
index a6624fe8e..83f362774 100644
--- a/src/peach/metadata.py
+++ b/src/peach/metadata.py
@@ -9,6 +9,7 @@ import shutil
import subprocess
import sys
from dataclasses import dataclass
+from datetime import date
from pathlib import Path
from typing import Callable
@@ -94,7 +95,7 @@ class JavinizerGoProvider:
try:
version = runner(
[str(resolved), "version", "--short"], capture_output=True, text=True,
- timeout=10, check=False, shell=False,
+ encoding="utf-8", errors="strict", timeout=10, check=False, shell=False,
)
except OSError as exc:
raise MetadataProviderError(f"无法验证 Javinizer-Go 版本:{exc}") from exc
@@ -123,7 +124,7 @@ class JavinizerGoProvider:
try:
completed = self.runner(
command, capture_output=True, text=True, timeout=self.timeout,
- check=False, shell=False,
+ encoding="utf-8", errors="strict", check=False, shell=False,
)
except subprocess.TimeoutExpired as exc:
raise MetadataProviderError(
@@ -190,8 +191,21 @@ def normalized_performers(raw: object) -> tuple[list[dict], list[str]]:
return performers, warnings
+def normalized_release_date(raw: object) -> tuple[str, list[str]]:
+ value = str(raw or "").strip()
+ if not value:
+ return "", []
+ candidate = value[:10]
+ try:
+ normalized = date.fromisoformat(candidate).isoformat()
+ except ValueError:
+ return "", [f"来源发行日期无效,已忽略:{value}"]
+ warnings = [] if value == normalized else [f"来源发行时间已规范化为日期:{value} → {normalized}"]
+ return normalized, warnings
+
+
def extract_peach_fields(payload: dict, category_map: dict[str, str]) -> dict[str, dict]:
- """Map raw provider data to the four Peach truth fields supported by P0."""
+ """Map raw provider data to the Peach truth fields supported by P0."""
out: dict[str, dict] = {}
performers, warnings = normalized_performers(payload.get("actresses"))
if performers:
@@ -210,6 +224,13 @@ def extract_peach_fields(payload: dict, category_map: dict[str, str]) -> dict[st
"warnings": ([f"来源值含重复片段,已规范化:{raw_name} → {name}"]
if repeated else []),
}
+ release_date, date_warnings = normalized_release_date(payload.get("release_date"))
+ if release_date:
+ out["release_date"] = {
+ "value": release_date,
+ "display_value": release_date,
+ "warnings": date_warnings,
+ }
mapped = [category_map[name] for name in payload.get("genres") or [] if name in category_map]
mapped = list(dict.fromkeys(mapped))
if mapped:
diff --git a/src/peach/web_contract.py b/src/peach/web_contract.py
index 47eb01d71..ac8f866bb 100644
--- a/src/peach/web_contract.py
+++ b/src/peach/web_contract.py
@@ -306,7 +306,7 @@ def q_items(contract: WebContract, args):
off = int(args.get("offset", 0))
include_total = args.get("count", "1") != "0"
fetch_limit = lim if include_total else lim + 1
- sql = ("SELECT a.id,a.location,a.path,a.name,a.creator,a.studio,a.code,a.size,"
+ sql = ("SELECT a.id,a.location,a.path,a.name,a.creator,a.studio,a.code,a.release_date,a.size,"
"a.duration,a.width,a.height,a.ctx_length,a.ctx_orient,a.snapshot_path,"
"a.play_count,a.leave_ratio,a.feedback,a.disposal,a.rating,a.o_count,"
"a.play_seconds,a.max_reached,a.seek_count,"
@@ -450,7 +450,7 @@ def q_item(contract: WebContract, aid):
既显示错条目,又反复拉计费流量。教训:按 id 取就按 id 取。"""
c = contract.db()
r = c.execute(
- "SELECT id,location,path,name,creator,studio,code,size,duration,width,height,"
+ "SELECT id,location,path,name,creator,studio,code,release_date,size,duration,width,height,"
"ctx_length,ctx_orient,snapshot_path,play_count,leave_ratio,feedback,disposal,"
"rating,o_count,play_seconds,max_reached,seek_count,"
"COALESCE((SELECT p.liked FROM asset_preference p WHERE p.asset_id=asset.id "
@@ -1145,7 +1145,7 @@ def _approved_entity_name(value: object, kind: str) -> str:
def _apply_metadata_candidate(connection, group: dict, candidate: dict, now: str) -> int:
field = str(group.get("field") or "").strip()
- if field not in {"performers", "studio", "series", "tags"}:
+ if field not in {"performers", "studio", "series", "release_date", "tags"}:
raise ValueError("该元数据字段没有 Peach 写入映射")
code = str(group.get("code") or "").strip()
query = str(group.get("query") or code).strip()
@@ -1176,6 +1176,19 @@ def _apply_metadata_candidate(connection, group: dict, candidate: dict, now: str
}
marks = ",".join("?" * len(asset_ids))
+ if field == "release_date":
+ value = str(candidate.get("value") or "").strip()
+ if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", value):
+ raise ValueError("发行日期候选必须是 YYYY-MM-DD")
+ try:
+ time.strptime(value, "%Y-%m-%d")
+ except ValueError as exc:
+ raise ValueError("发行日期候选无效") from exc
+ connection.execute(
+ f"UPDATE asset SET release_date=? WHERE id IN ({marks})", (value, *asset_ids),
+ )
+ return len(asset_ids)
+
if field in {"studio", "series"}:
name = _approved_entity_name(candidate.get("value"), field)
connection.execute(
diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.py
index 5972a15e3..a47cb3cc9 100644
--- a/tests/test_fastapi_api.py
+++ b/tests/test_fastapi_api.py
@@ -21,7 +21,7 @@ if HAS_DEPS:
BASE_SCHEMA = """
CREATE TABLE asset(
id INTEGER PRIMARY KEY, location TEXT NOT NULL, path TEXT NOT NULL, name TEXT,
- medium TEXT, size INTEGER, creator TEXT, studio TEXT, series TEXT, code TEXT,
+ medium TEXT, size INTEGER, creator TEXT, studio TEXT, series TEXT, code TEXT, release_date TEXT,
duration REAL, width INTEGER, height INTEGER, ctx_length TEXT, ctx_orient TEXT,
ctx_quality TEXT, play_count INTEGER DEFAULT 0, last_played TEXT, rating INTEGER,
o_count INTEGER, watch_ratio REAL, stash_scene_id INTEGER, snapshot_path TEXT, first_seen TEXT,
diff --git a/tests/test_metadata.py b/tests/test_metadata.py
index 39e7d0d1a..3eed87d65 100644
--- a/tests/test_metadata.py
+++ b/tests/test_metadata.py
@@ -40,6 +40,8 @@ class MetadataProviderTests(unittest.TestCase):
command, options = calls[0]
self.assertEqual(command[-5:], ["IPX-535", "--output", "json", "--scrapers", "r18dev"])
self.assertFalse(options["shell"])
+ self.assertEqual(options["encoding"], "utf-8")
+ self.assertEqual(options["errors"], "strict")
def test_provider_rejects_paths_and_urls_before_subprocess(self):
for unsafe in ("/media/IPX-535.mp4", r"R:\media\IPX-535.mp4", "https://x/IPX-535"):
@@ -69,12 +71,15 @@ class MetadataProviderTests(unittest.TestCase):
{"dmm_id": 7, "japanese_name": "木村さん"},
{"dmm_id": 8, "japanese_name": "画像を拡大する 画像を拡大する"},
],
- "maker": "Studio Studio", "series": "Series A", "genres": ["Anal"],
+ "maker": "Studio Studio", "series": "Series A",
+ "release_date": "2020-09-13T00:00:00Z", "genres": ["Anal"],
}, {"Anal": "肛交"})
self.assertEqual(fields["performers"]["value"], [
{"name": "木村さん", "external_id": "7", "thumb_url": ""},
])
self.assertEqual(fields["studio"]["value"], "Studio")
+ self.assertEqual(fields["release_date"]["value"], "2020-09-13")
+ self.assertIn("已规范化", fields["release_date"]["warnings"][0])
self.assertEqual(fields["tags"]["value"], ["肛交"])
diff --git a/tests/test_migrations.py b/tests/test_migrations.py
index 0e8eeee5a..6e918b7eb 100644
--- a/tests/test_migrations.py
+++ b/tests/test_migrations.py
@@ -24,7 +24,7 @@ class MigrationTests(unittest.TestCase):
backup = self.root / "before.db"
done = upgrade(self.db, MIGRATIONS, backup)
self.assertEqual([m.version for m in done],
- ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015"])
+ ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016"])
self.assertTrue(backup.exists())
con = sqlite3.connect(self.db)
tables = {row[0] for row in con.execute(
@@ -40,7 +40,7 @@ class MigrationTests(unittest.TestCase):
"entity_search_term", "watch_queue", "asset_preference", "asset_quality_goal",
"asset_tag_preference", "asset_search",
"schema_migration"} <= tables)
- self.assertEqual(versions, ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015"])
+ self.assertEqual(versions, ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016"])
self.assertEqual(upgrade(self.db, MIGRATIONS), [])
self.assertEqual(plan(self.db, MIGRATIONS)[1], [])
@@ -67,7 +67,7 @@ class MigrationTests(unittest.TestCase):
columns = {row[1] for row in con.execute("PRAGMA table_info(asset)")}
con.close()
self.assertTrue({"studio", "feedback", "disposal", "leave_ratio", "play_seconds",
- "feedback_at", "seek_count", "max_reached"} <= columns)
+ "feedback_at", "seek_count", "max_reached", "release_date"} <= columns)
def test_checksum_change_is_rejected(self):
sqlite3.connect(self.db).close()
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index ad28298ac..5dc8a7d6f 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -22,6 +22,7 @@ CREATE TABLE asset(
studio TEXT,
series TEXT,
code TEXT,
+ release_date TEXT,
duration REAL,
width INTEGER,
height INTEGER,
@@ -569,7 +570,8 @@ class WebDataTests(unittest.TestCase):
REVIEW_SCHEMA = """
CREATE TABLE asset(id INTEGER PRIMARY KEY,location TEXT,path TEXT,name TEXT,medium TEXT,
- duration REAL,creator TEXT,studio TEXT,series TEXT,code TEXT,snapshot_path TEXT,disposal TEXT);
+ duration REAL,creator TEXT,studio TEXT,series TEXT,code TEXT,release_date TEXT,
+ snapshot_path TEXT,disposal TEXT);
CREATE TABLE asset_tag(asset_id INTEGER,tag TEXT,confidence REAL DEFAULT 1.0,source TEXT,
PRIMARY KEY(asset_id,tag,source));
CREATE TABLE entity(id INTEGER PRIMARY KEY,kind TEXT,canonical_name TEXT,normalized_name TEXT,
@@ -669,6 +671,32 @@ class ReviewQueueTests(unittest.TestCase):
con.close()
self.assertEqual(json.loads(note)["candidate_key"], candidate["candidate_key"])
+ def test_metadata_release_date_approval_writes_the_date_field(self):
+ con = sqlite3.connect(self.db_path)
+ con.execute("UPDATE asset SET code='ABC-001' WHERE id=1")
+ con.commit(); con.close()
+ candidate = {
+ "candidate_key": "ABC-001:release_date:r18dev:abc", "source": "r18dev",
+ "source_url": "https://r18.dev/example", "confidence": 0.9,
+ "value": "2020-09-13", "display_value": "2020-09-13", "warnings": [],
+ "raw_snapshot": "/evidence.json",
+ }
+ self.write_metadata_candidates([{
+ "item_key": "ABC-001:release_date", "code": "ABC-001", "query": "ABC-001",
+ "field": "release_date", "field_label": "发行日期", "current_value": "",
+ "candidates_json": json.dumps([candidate]), "source_count": "1",
+ "status": "candidate", "size_gb": "1", "videos": "1", "fetched_at": "now",
+ }])
+ result = rm_web.w_review_decision(self.contract, {
+ "category": "metadata_fields", "item_key": "ABC-001:release_date",
+ "candidate_key": candidate["candidate_key"], "status": "approved",
+ })
+ self.assertEqual(result["applied_assets"], 1)
+ con = sqlite3.connect(self.db_path)
+ self.assertEqual(con.execute(
+ "SELECT release_date FROM asset WHERE id=1").fetchone()[0], "2020-09-13")
+ con.close()
+
def test_metadata_approval_rejects_repeated_name_even_if_csv_is_tampered(self):
con = sqlite3.connect(self.db_path)
con.execute("UPDATE asset SET code='ABC-001' WHERE id=1")
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index 2f85d720f..c3cf1c17e 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -580,7 +580,7 @@ class OperationalScriptTests(unittest.TestCase):
return {
"source": source, "source_url": "https://r18.dev/example",
"maker": "Studio A" if source == "r18dev" else "Studio B",
- "series": "Series A",
+ "series": "Series A", "release_date": "2020-09-13T00:00:00Z",
"actresses": [{"dmm_id": 7, "japanese_name": "木村さん 木村さん"}],
"genres": ["Foot Fetish", "Anal", "Unknown"],
}
@@ -589,19 +589,28 @@ class OperationalScriptTests(unittest.TestCase):
result = self.scrape_codes.main([
"--db", str(db), "--out", str(output), "--raw-dir", str(raw),
"--log-dir", str(root / "logs"), "--delay", "0",
- "--sources", "r18dev,javbus",
+ "--sources", "javbus,r18dev",
], provider=provider)
self.assertEqual(result, 0)
- self.assertEqual(provider.calls, [("ABC-001", "r18dev"), ("ABC-001", "javbus")])
+ self.assertEqual(provider.calls, [("ABC-001", "javbus"), ("ABC-001", "r18dev")])
with output.open(encoding="utf-8-sig") as handle:
rows = list(csv.DictReader(handle))
- self.assertEqual({row["field"] for row in rows}, {"performers", "studio", "series", "tags"})
+ self.assertEqual({row["field"] for row in rows},
+ {"performers", "studio", "series", "release_date", "tags"})
performer = next(row for row in rows if row["field"] == "performers")
candidates = __import__("json").loads(performer["candidates_json"])
self.assertEqual({candidate["source"] for candidate in candidates}, {"r18dev", "javbus"})
self.assertEqual(candidates[0]["display_value"], "木村さん")
self.assertIn("已规范化", candidates[0]["warnings"][0])
+ release = next(row for row in rows if row["field"] == "release_date")
+ self.assertEqual(__import__("json").loads(release["candidates_json"])[0]["value"],
+ "2020-09-13")
+ tag_candidates = __import__("json").loads(
+ next(row for row in rows if row["field"] == "tags")["candidates_json"])
+ self.assertEqual([candidate["source"] for candidate in tag_candidates],
+ ["r18dev", "javbus"], "官方 tag 来源必须排在社区来源前")
+ self.assertTrue(tag_candidates[0]["official"])
self.assertTrue((raw / "ABC-001" / "r18dev.json").is_file())
self.assertTrue((raw / "ABC-001" / "javbus.json").is_file())
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index aaa7a4804..943af44bc 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -781,9 +781,13 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("const REVIEW_LABELS={metadata_fields:'元数据字段',creator_tags:'创作者标签'")
self.assertPageContains("candidate_key:candidateKey")
self.assertPageContains("class=\"metadatacandidate\"")
+ self.assertPageContains("candidate.official?' · 官方优先':''")
self.assertPageContains("/api/review/decision")
self.assertPageContains("if(path==='/review')")
+ def test_jav_release_date_is_visible_in_detail(self):
+ self.assertPageContains("发行 ${esc(it.release_date)}")
+
def test_duplicates_page_is_a_management_section(self):
self.assertPageContains("['dupes','重复文件','hard-drive']")
self.assertPageContains("if(path==='/duplicates')return 'dupes'")
diff --git a/web/app.js b/web/app.js
index 4d0699093..107d702dc 100644
--- a/web/app.js
+++ b/web/app.js
@@ -972,7 +972,7 @@ async function openReview(push=true){
const approveLabel=canApprove?'通过':'已跳过';
const assets=row.preview_assets||[];
const preview=metadata
- ? `<div class="metadatacandidates">${candidates.map((candidate,index)=>`<label class="metadatacandidate"><input type="radio" name="metadata-${esc(key)}" value="${esc(candidate.candidate_key)}"${index===0?' checked':''}><span><b>${esc(candidate.source)}</b><span>${esc(candidate.display_value||'')}</span>${(candidate.warnings||[]).map(warning=>`<i>${esc(warning)}</i>`).join('')}</span></label>`).join('')}</div>`
+ ? `<div class="metadatacandidates">${candidates.map((candidate,index)=>`<label class="metadatacandidate"><input type="radio" name="metadata-${esc(key)}" value="${esc(candidate.candidate_key)}"${index===0?' checked':''}><span><b>${esc(candidate.source)}${candidate.official?' · 官方优先':''}</b><span>${esc(candidate.display_value||'')}</span>${(candidate.warnings||[]).map(warning=>`<i>${esc(warning)}</i>`).join('')}</span></label>`).join('')}</div>`
: reviewCategory==='creator_tags'
? (assets.length?`<div class="reviewpick"><div class="reviewpickhead"><span class="mono" data-picked-count></span>
<button type="button" data-pick-all>全选</button><button type="button" data-pick-none>清空</button></div>
@@ -1677,7 +1677,8 @@ async function openItem(id,push=true,mixContext=null){
<div class="stitle">${esc(it.name)}</div>
<div class="smeta mono">${srcBadge(it.location,it.cost,'srcbig')}
<span style="align-self:center">${it.width||'?'}×${it.height||'?'}</span>
- <span style="align-self:center">${fmtSize(it.size||0)}</span></div>
+ <span style="align-self:center">${fmtSize(it.size||0)}</span>
+ ${it.release_date?`<span style="align-self:center">发行 ${esc(it.release_date)}</span>`:''}</div>
<div class="detailidentity">${identityRows||`<div class="identityrow"><span></span><span class="ilabel">归属</span><span>${esc(who)}</span></div>`}</div>
<div class="stags" id="detailTags"></div>
<div class="trace"><div class="lab mono"><span>离开位置 / 全片</span><span id="ratioTxt">—</span></div>