Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(media): 按时间点预抽视频缩略图并经接口下发

longmeidaof8b90674bf83
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 83bd14e39..96dbd2541 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -51,6 +51,8 @@ SCOPES: dict[str, tuple[str, ...]] = {
# 接线的两端,改哪一端都要两边一起验。
"media": ("test_runtime_consistency.py", "test_endcard.py", "test_fastapi_api.py", "test_jobs.py",
"test_task_runs.py", "test_task_center_integration.py",
+ "test_frame_capture.py", "test_timeline_sheets.py",
+ "test_web_timeline_thumbnails.py",
"test_interaction.py", "test_media.py", "test_previews.py",
"test_providers.py", "test_segments.py", "test_streaming.py",
"test_subtitles.py", "test_transcodes.py"),
diff --git a/src/peach/api.py b/src/peach/api.py
index c7e37f02b..5fd0539dd 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -112,6 +112,7 @@ def create_app(
avatar_root=settings.avatar_root,
logo_root=settings.logo_root,
poster_root=settings.poster_root,
+ timeline_root=settings.timeline_root,
photo_root=settings.photo_root,
transcode_root=settings.transcode_root,
stream_root=settings.stream_root,
diff --git a/src/peach/config.py b/src/peach/config.py
index 58b2fe1a4..4e7d0d516 100644
--- a/src/peach/config.py
+++ b/src/peach/config.py
@@ -102,6 +102,8 @@ class PeachSettings:
allowed_media_roots: tuple[Path, ...] = translate_roots(MEDIA_ROOT_DECLARATIONS)
snapshot_root: Path = GENERATED_DIR / "snapshots"
poster_root: Path = GENERATED_DIR / "posters"
+ # 时间轴预览的接触印相,由采集任务铺,悬停时整张取回来按格子换位置。
+ timeline_root: Path = GENERATED_DIR / "timeline"
avatar_root: Path = GENERATED_DIR / "avatars"
logo_root: Path = GENERATED_DIR / "logos"
# 图片资产的缓存缩略图。云盘原图一张就有几 MB,回源一次之后图片墙只读这里。
diff --git a/src/peach/routes_media.py b/src/peach/routes_media.py
index 3fdbab55a..a5d86a925 100644
--- a/src/peach/routes_media.py
+++ b/src/peach/routes_media.py
@@ -29,8 +29,8 @@ from starlette.staticfiles import StaticFiles
from . import (
avatar_face, avatar_picker, avatar_provider, follow_assets, link_marks,
- scraping_access, site_icons, subtitles, taste_history, web_follow,
- web_settings,
+ scraping_access, site_icons, subtitles, taste_history, timeline_sheets,
+ web_follow, web_settings,
)
from .config import GENERATED_DIR
from .follow import FollowSourceError
@@ -424,6 +424,20 @@ def poster(request: Request, id: int, c: int = 4, args: dict[str, str] = Depends
return _image_response(request, path, media_type="image/jpeg")
[email protected]_route("/timeline", methods=["GET", "HEAD"])
+def timeline(request: Request, id: int, s: int = 0, args: dict[str, str] = Depends(require_auth)):
+ """时间轴预览的一张接触印相。只发已经铺好的,这里不现抽。
+
+ `/poster` 那条取不到会当场抽一帧,因为九宫格只要九张。这里一张图是一百帧,现抽要
+ 几分钟,悬停的人早走了;没铺到就回 404,页面退回九宫格。
+ """
+ contract = request.app.state.web_contract
+ path = timeline_sheets.sheet_path(contract.timeline_root, id, s)
+ if id <= 0 or s < 0 or not path.is_file():
+ return JSONResponse({"error": "unavailable"}, status_code=404)
+ return _image_response(request, path, media_type="image/jpeg")
+
+
@router.api_route("/cover", methods=["GET", "HEAD"])
def cover(request: Request, code: str = "", args: dict[str, str] = Depends(require_auth)):
"""官方封套原图。存原图不裁:4:3 与 16:9 两种版式在界面上按比例取景。"""
diff --git a/src/peach/timeline_sheets.py b/src/peach/timeline_sheets.py
new file mode 100644
index 000000000..73781042d
--- /dev/null
+++ b/src/peach/timeline_sheets.py
@@ -0,0 +1,256 @@
+"""时间轴预览:每隔固定秒数一帧,按 10×10 拼成接触印相,供悬停扫画面用。
+
+悬停扫的九宫格取的是全片九个等分点:一部两小时的片子,格与格之间隔着十几分钟,
+想看某一段里有什么,扫过去的九张都对不上。这里换成按时间取——每 10 秒或 30 秒一帧,
+帧在图上的位置就是它在片子里的位置。
+
+两个口径都固定,前端据此换算格子位置,不必为每部片子多取一份索引:一张图 10 列
+10 行共 100 帧,帧宽 320。间隔由用户在设置里选,和图一起写进 `meta.json`。
+
+只对本机磁盘上的片子预生成。网盘上的每抽一帧都要拉一次远端读取,实测 115 单文件抽
+九帧约 285 MB;两万部按每 10 秒一帧算,流量按 TB 计,与流量策略冲突。
+"""
+from __future__ import annotations
+
+import json
+import shutil
+import sqlite3
+import tempfile
+import time
+from pathlib import Path
+
+from .frame_capture import capture_with_retry, tile_frames
+from .fsutil import atomic_path
+from .jobs import DiskSpaceDenied
+from .media import resolve_case_insensitive
+
+#: 两档密度,值就是秒数。名字进接口也进设置页,改这里就是改契约。
+INTERVALS = {"precise": 10, "coarse": 30}
+OFF = "off"
+MODES = (OFF, *INTERVALS)
+
+#: 一张图的格子数与帧宽。换算在前端也有一份,这三个数是两边的共同约定。
+COLUMNS = 10
+ROWS = 10
+FRAMES_PER_SHEET = COLUMNS * ROWS
+FRAME_WIDTH = 320
+
+#: 头尾各让开一点:片头的黑场和片尾的字幕板扫过去什么都看不出来。
+EDGE_MARGIN = 0.01
+
+
+class _TileFailed(RuntimeError):
+ """拼图这一步没出成图。只在本模块内部用来跳出 `atomic_path`。"""
+
+
+def _fill_gaps(directory: Path, count: int) -> int:
+ """把抽失败的格子用邻近那一帧补上,返回补完后连续的帧数。
+
+ 两件事都要这么做才成立。一是 `image2` 按连续序号读,中间缺一号它就在那里停下;
+ 二是这套图的全部意义在于「第 n 格就是第 n 个采样点」,缺一帧让后面全体前移一格,
+ 图还是满的,位置却整体错开——而错开多少取决于哪几帧解不出来,事后看不出来。
+ 补进去的是旁边那一帧,画面重复一格,位置不动。
+ """
+ slots = [directory / f"s{index:03d}.jpg" for index in range(count)]
+ present = [index for index, path in enumerate(slots) if path.is_file()]
+ if not present:
+ return 0
+ for index, path in enumerate(slots):
+ if path.is_file():
+ continue
+ nearest = min(present, key=lambda good: (abs(good - index), good))
+ shutil.copyfile(slots[nearest], path)
+ return count
+
+
+def sheet_dir(root: Path, asset_id: int) -> Path:
+ """按 id 末两位分桶。一层平铺的话,本机这三千部就是几千个文件挤在一个目录里,
+ Windows 上列目录会变慢,而这个目录正好是清理产物时要逐个看的那个。"""
+ return Path(root) / f"{int(asset_id) % 100:02d}" / str(int(asset_id))
+
+
+def meta_path(root: Path, asset_id: int) -> Path:
+ return sheet_dir(root, asset_id) / "meta.json"
+
+
+def sheet_path(root: Path, asset_id: int, index: int) -> Path:
+ return sheet_dir(root, asset_id) / f"{int(index):03d}.jpg"
+
+
+def frame_count(duration: float, interval: int) -> int:
+ """这部片子按这个间隔有多少帧。至少两帧才谈得上扫。"""
+ if not duration or duration <= 0 or interval <= 0:
+ return 0
+ return max(0, min(FRAMES_PER_SHEET * 999, int(duration // interval)))
+
+
+def read_meta(root: Path, asset_id: int) -> dict | None:
+ """已经生成过什么。读不出来当作没有:坏掉的 meta 重生成一次就好,
+ 比让整条链在一个残缺的 JSON 上崩掉划算。"""
+ path = meta_path(root, asset_id)
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ return data if isinstance(data, dict) and data.get("frames") else None
+
+
+def is_current(root: Path, asset_id: int, interval: int) -> bool:
+ """这部片子已经按这个间隔做好了,且每一张图都还在。
+
+ 只看 meta 不看图的话,用户手工清过产物目录之后,任务会把它们全部当成做好的跳过,
+ 页面上则是一片取不到的图。
+ """
+ meta = read_meta(root, asset_id)
+ if not meta or int(meta.get("interval") or 0) != int(interval):
+ return False
+ return all(sheet_path(root, asset_id, index).is_file()
+ for index in range(int(meta.get("sheets") or 0)))
+
+
+def build(ffmpeg: str, source: str, duration: float, root: Path, asset_id: int,
+ interval: int, *, active=lambda: True) -> dict:
+ """给一部片子生成整套时间轴图,返回写进 `meta.json` 的那份。
+
+ `active` 每帧问一次:一部三小时的片子有上千帧,中途按停就该停在这里,而不是
+ 等这一部跑完。半路停下不写 meta——没有 meta 就是没做过,下一趟从头来,不会
+ 留下一份「说有 700 帧、实际只有 300 帧」的索引。
+ """
+ total = frame_count(duration, interval)
+ if total < 2:
+ return {}
+ sheets = (total + FRAMES_PER_SHEET - 1) // FRAMES_PER_SHEET
+ directory = sheet_dir(root, asset_id)
+ # 整套重做,所以先清干净。换档位时新的一套通常比旧的少几张,只覆盖不清理的话,
+ # 多出来的那几张留在盘上,`is_current` 又不看它们,于是永远没人删。
+ discard(root, asset_id)
+ directory.mkdir(parents=True, exist_ok=True)
+ made = 0
+ produced = 0
+ for index in range(sheets):
+ first = index * FRAMES_PER_SHEET
+ count = min(FRAMES_PER_SHEET, total - first)
+ temporary = Path(tempfile.mkdtemp(prefix="timeline_"))
+ try:
+ slots = 0
+ for offset in range(count):
+ if not active():
+ return {}
+ # 帧号乘间隔就是它在片子里的秒数,前端按同一条式子反算。头尾各让开
+ # 一点,靠 EDGE_MARGIN 把采样点往里推,不改这条对应关系的斜率。
+ timestamp = (first + offset) * interval + duration * EDGE_MARGIN
+ if timestamp >= duration:
+ break
+ slots = offset + 1
+ capture_with_retry(ffmpeg, source, timestamp,
+ temporary / f"s{offset:03d}.jpg",
+ width=FRAME_WIDTH, timeout=20)
+ captured = _fill_gaps(temporary, slots)
+ if captured < 2:
+ # 末张可能一格都排不进(`EDGE_MARGIN` 把最后一个采样点推过了片尾)。
+ # 前面已经出了图就到此为止,别把整套连同已成的几十张一起作废。
+ if produced:
+ break
+ return {}
+ rows = (captured + COLUMNS - 1) // COLUMNS
+ try:
+ with atomic_path(sheet_path(root, asset_id, index)) as destination:
+ if not tile_frames(ffmpeg, str(temporary / "s%03d.jpg"),
+ COLUMNS, rows, destination):
+ # 拼不出来就让 `atomic_path` 按异常路径收尾:正常退出它会去
+ # 替换目标,而这时那个临时文件要么不存在要么是半张。
+ raise _TileFailed
+ except _TileFailed:
+ return {}
+ made += captured
+ produced += 1
+ finally:
+ shutil.rmtree(temporary, ignore_errors=True)
+ # `frames` 是连续的格子数,末张的行数由它反算(`ceil(余数 / columns)`):那一张
+ # 通常不满 10 行,按 `rows` 去算格子位置会在图外面取到空白。
+ meta = {"interval": int(interval), "frames": made, "sheets": produced,
+ "columns": COLUMNS, "rows": ROWS, "frame_width": FRAME_WIDTH,
+ "made_at": time.time()}
+ with atomic_path(meta_path(root, asset_id)) as destination:
+ destination.write_text(json.dumps(meta, ensure_ascii=False), encoding="utf-8")
+ return meta
+
+
+#: 本机磁盘上的片子才预生成。这个清单是判据也是文案依据,改它就是改功能范围。
+LOCAL_LOCATIONS = ("local",)
+
+#: 用户按停时写进 `stopped` 的那句话。调用方按它区分「人停的」和「机器停的」:
+#: 前者不是故障,后者要把原因摆到页面上。
+STOPPED_BY_USER = "已按停"
+
+
+def pending(db_path: Path | str, interval: int, *, limit: int = 0) -> list[tuple]:
+ """待办队列:本机磁盘上、时长够两帧的视频,最近看过的排前面。
+
+ 排序不是装饰。这条链随时可能被磁盘闸门或用户按停,跑到哪算哪,所以先做的必须是
+ 最可能被悬停扫到的那些。
+ """
+ placeholders = ",".join("?" for _ in LOCAL_LOCATIONS)
+ # 回收站里的不做:那一批等着被删,为它们各抽一百帧是白花的时间和磁盘。
+ sql = ("SELECT id, path, duration FROM asset WHERE medium='video' "
+ f"AND location IN ({placeholders}) AND duration >= ? "
+ "AND (disposal IS NULL OR disposal <> 'trash') "
+ "ORDER BY (last_played IS NULL), last_played DESC, id")
+ parameters: tuple = (*LOCAL_LOCATIONS, float(interval) * 2)
+ if limit:
+ sql += " LIMIT ?"
+ parameters += (int(limit),)
+ connection = sqlite3.connect(f"file:{Path(db_path)}?mode=ro", uri=True)
+ try:
+ return connection.execute(sql, parameters).fetchall()
+ finally:
+ connection.close()
+
+
+def generate_library(db_path: Path | str, root: Path, interval: int, *, ffmpeg: str,
+ report=lambda **fields: None, active=lambda: True,
+ guard=None, limit: int = 0) -> dict:
+ """按队列逐部生成,返回这一趟的计数。
+
+ 失败不中断:一部片子解不出来(源坏了、时长记错、编码器不认)是它自己的事,
+ 队列后面还有几千部。磁盘触线是另一回事——那说明整台机器写不下了,立刻停手并
+ 把原因带出去,不能继续跑成「完成」。
+ """
+ tasks = pending(db_path, interval, limit=limit)
+ state = {"total": len(tasks), "done": 0, "made": 0, "skipped": 0,
+ "failed": 0, "stopped": ""}
+ report(**state)
+ for asset_id, path, duration in tasks:
+ if not active():
+ state["stopped"] = STOPPED_BY_USER
+ break
+ if guard is not None:
+ try:
+ guard.check()
+ except DiskSpaceDenied as exc:
+ state["stopped"] = str(exc)
+ break
+ state["done"] += 1
+ if is_current(root, asset_id, interval):
+ state["skipped"] += 1
+ report(**state)
+ continue
+ # 账本路径是 Windows 形态,而挂载层可能是大小写敏感的:这一步同时管翻译和
+ # 大小写救回,和抽帧脚本走的是同一份判据。
+ source = Path(resolve_case_insensitive(path))
+ if not source.is_file():
+ state["failed"] += 1
+ report(**state)
+ continue
+ if build(ffmpeg, str(source), float(duration or 0), root, int(asset_id),
+ interval, active=active):
+ state["made"] += 1
+ else:
+ state["failed"] += 1
+ report(**state)
+ return state
+
+
+def discard(root: Path, asset_id: int) -> None:
+ """删掉一部片子的整套图。关掉采集时按它清退,产物不留在盘上。"""
+ shutil.rmtree(sheet_dir(root, asset_id), ignore_errors=True)
diff --git a/src/peach/web_resource_sync.py b/src/peach/web_resource_sync.py
index 25aedf07f..5a8878c4d 100644
--- a/src/peach/web_resource_sync.py
+++ b/src/peach/web_resource_sync.py
@@ -33,6 +33,7 @@ class ResourceSyncContract(Protocol):
poster_root: Path
avatar_root: Path
photo_root: Path
+ timeline_root: Path
stream_root: Path
transcode_root: Path
resource_cleanup_enabled: bool
@@ -246,6 +247,24 @@ def _resource_orphan_plan(contract: ResourceSyncContract, excluded_ids: Sequence
if path.is_file():
_cache_file(path, "stream-segments", files)
+ # 时间轴预览按 `<id 末两位>/<id>/` 分桶,一部片子一个目录、里面几十张图。判据和
+ # 分片一样是目录名,只是外面多一层桶:一部三小时的片子按 10 秒一帧就是 1080 张,
+ # 片子没了而这些还留着,是本机产物里单部占得最多的一类。
+ if (_managed_cache_root(contract, contract.timeline_root)
+ and contract.timeline_root.is_dir()):
+ for bucket in contract.timeline_root.iterdir():
+ if not bucket.is_dir():
+ continue
+ for directory in bucket.iterdir():
+ if not directory.is_dir() or not directory.name.isdigit():
+ continue
+ if int(directory.name) in active_ids:
+ continue
+ cleanup_dirs.add(directory)
+ for path in directory.rglob("*"):
+ if path.is_file():
+ _cache_file(path, "timeline", files)
+
if (_managed_cache_root(contract, contract.avatar_root)
and contract.avatar_root.is_dir()):
for path in contract.avatar_root.iterdir():
diff --git a/src/peach/web_router.py b/src/peach/web_router.py
index 67ef1c132..940f4ed19 100644
--- a/src/peach/web_router.py
+++ b/src/peach/web_router.py
@@ -68,6 +68,7 @@ from .web_settings import q_settings, w_settings
from .web_scraping import q_scraping, w_scraping_settings, w_scraping_check, w_scraping_cover
from .web_state import WebContract
from .web_tasks import q_tasks
+from .web_timeline_thumbnails import q_thumbnail_jobs, q_timeline, w_thumbnail_jobs
from .web_stats import (
q_quality_goals,
q_search_history,
@@ -226,6 +227,8 @@ GET_HANDLERS = {
"/api/tasks": q_tasks,
"/api/library-processing": q_library_processing,
"/api/library-processing/issues": q_library_processing_issues,
+ "/api/thumbnail-jobs": q_thumbnail_jobs,
+ "/api/timeline": q_timeline,
"/api/scraping": q_scraping,
"/api/scraping/cover": lambda contract, args: contract.scraping_cover_job.snapshot() or {"status": "idle"},
"/api/settings": q_settings,
@@ -266,6 +269,7 @@ GET_HANDLERS = {
POST_HANDLERS = {
"/api/library-processing": w_library_processing,
+ "/api/thumbnail-jobs": w_thumbnail_jobs,
"/api/scraping/settings": w_scraping_settings,
"/api/scraping/cover": w_scraping_cover,
"/api/scraping/check": w_scraping_check,
diff --git a/src/peach/web_state.py b/src/peach/web_state.py
index 766e30061..1940d8b56 100644
--- a/src/peach/web_state.py
+++ b/src/peach/web_state.py
@@ -73,6 +73,7 @@ class WebContract:
logo_root: Path | None = None,
marks_root: Path | None = None,
poster_root: Path | None = None,
+ timeline_root: Path | None = None,
photo_root: Path | None = None,
transcode_root: Path | None = None,
stream_root: Path | None = None,
@@ -96,6 +97,10 @@ class WebContract:
self.marks_root = (Path(marks_root) if marks_root is not None
else brand_marks.STUDIOS_DIR)
self.poster_root = Path(poster_root) if poster_root is not None else GENERATED_DIR / "posters"
+ # 时间轴预览的接触印相。和上面几个不一样,它不是取不到就现做的缓存:一张图要抽
+ # 一百帧,只能靠采集任务提前铺好,没铺到的片子悬停时退回九宫格。
+ self.timeline_root = (Path(timeline_root) if timeline_root is not None
+ else GENERATED_DIR / "timeline")
self.photo_root = Path(photo_root) if photo_root is not None else GENERATED_DIR / "photo-thumbs"
self.transcode_root = (Path(transcode_root) if transcode_root is not None
else GENERATED_DIR / "transcodes")
@@ -149,6 +154,8 @@ class WebContract:
self.scraping_cover_job = self._job("PeachScrapingCoverJob", "scraping-cover")
self.library_processing_job = self._job(
"PeachLibraryProcessingJob", "library-processing")
+ self.thumbnail_job = self._job(
+ "PeachTimelineThumbnailJob", "timeline-thumbnails")
self.resource_apply_job = self._job("PeachResourceApplyJob", "resource-apply")
self.follow_scheduler = None
# 两块后台任务的锁、状态和线程都归 BackgroundJob 管,契约上只留这两个字段。
@@ -223,6 +230,7 @@ class WebContract:
self.follow_job.stop()
self.scraping_cover_job.stop()
self.library_processing_job.stop()
+ self.thumbnail_job.stop()
self.follow_resolve_job.stop()
self.taste_refresh_job.stop()
self.link_prune_job.stop()
diff --git a/src/peach/web_timeline_thumbnails.py b/src/peach/web_timeline_thumbnails.py
new file mode 100644
index 000000000..78fe42bd4
--- /dev/null
+++ b/src/peach/web_timeline_thumbnails.py
@@ -0,0 +1,103 @@
+"""时间轴预览的采集任务:选一档密度、后台跑、页面轮询。
+
+档位存在服务端而不是浏览器里:跑的是这台机器上的一条长任务,从另一台设备打开设置
+时要看到的是「这台机器正在按 10 秒一帧采集」,不是那台设备自己的上一次选择。
+"""
+import json
+import time
+from pathlib import Path
+
+from . import timeline_sheets
+from .config import FFMPEG_DIR, STATE_DIR
+from .ffmpeg import FFmpegResolver
+from .fsutil import atomic_path
+from .jobs import DiskGuard
+from .platform import system_volume
+
+#: 采集期间系统盘至少留这么多 GiB。数字和抽帧脚本的默认值同一个:真正会把系统盘写满的
+#: 是网盘缓存那一类第三方消耗方,与产物落在哪块盘无关。
+MIN_FREE_GB = 40.0
+
+MODE_PATH = STATE_DIR / 'timeline-thumbnails.json'
+
+
+def _mode_file(path: Path | None = None) -> Path:
+ return Path(path) if path is not None else MODE_PATH
+
+
+def read_mode(path: Path | None = None) -> str:
+ """当前档位。读不出来就是关着——这条链会写盘也会读片子,不能靠猜来开。"""
+ try:
+ data = json.loads(_mode_file(path).read_text(encoding='utf-8'))
+ except (OSError, ValueError):
+ return timeline_sheets.OFF
+ mode = str((data or {}).get('mode') or timeline_sheets.OFF)
+ return mode if mode in timeline_sheets.MODES else timeline_sheets.OFF
+
+
+def write_mode(mode: str, path: Path | None = None) -> None:
+ with atomic_path(_mode_file(path)) as destination:
+ destination.write_text(json.dumps({'mode': mode, 'saved_at': time.time()}),
+ encoding='utf-8')
+
+
+def q_timeline(contract, args):
+ """一部片子的时间轴索引。没铺到就回空对象,页面据此决定要不要画这一层。
+
+ 单独一条而不是随列表下发:一页六十张卡里真正被悬停的是个位数,为此每行多读一份
+ `meta.json` 是把六十次文件读摊到每一次翻页上。
+ """
+ asset_id = int((args or {}).get('id') or 0)
+ if asset_id <= 0:
+ return {}
+ return timeline_sheets.read_meta(contract.timeline_root, asset_id) or {}
+
+
+def q_thumbnail_jobs(contract, _args):
+ state = contract.thumbnail_job.snapshot() or {}
+ return {'mode': read_mode(), 'modes': list(timeline_sheets.MODES),
+ 'intervals': dict(timeline_sheets.INTERVALS),
+ 'status': state.get('status') or 'idle',
+ 'job_id': state.get('job_id') or '',
+ 'total': state.get('total') or 0, 'done': state.get('done') or 0,
+ 'made': state.get('made') or 0, 'skipped': state.get('skipped') or 0,
+ 'failed': state.get('failed') or 0, 'stopped': state.get('stopped') or ''}
+
+
+def w_thumbnail_jobs(contract, body):
+ """选档位。选 `off` 只是停手,已经生成的图留在盘上——几 GB 的产物删不删是另一件
+ 事,走数据管理页那条清理链,不在切换开关时顺手做掉。"""
+ mode = str((body or {}).get('mode') or timeline_sheets.OFF)
+ if mode not in timeline_sheets.MODES:
+ raise ValueError('采集密度无效')
+ write_mode(mode)
+ if mode == timeline_sheets.OFF:
+ contract.thumbnail_job.stop()
+ return q_thumbnail_jobs(contract, {})
+ choice = FFmpegResolver(FFMPEG_DIR).ffmpeg()
+ if choice is None:
+ raise ValueError('未找到 ffmpeg,无法采集缩略图')
+ interval = timeline_sheets.INTERVALS[mode]
+ root = contract.timeline_root
+
+ def work(job_id):
+ guard = DiskGuard(system_volume(), MIN_FREE_GB)
+ result = timeline_sheets.generate_library(
+ contract.db_path, root, interval, ffmpeg=str(choice.path),
+ active=lambda: (contract.thumbnail_job.snapshot() or {}).get('job_id') == job_id,
+ report=lambda **fields: contract.thumbnail_job.update(job_id, **fields),
+ guard=guard)
+ # 磁盘触线停下来的那一轮不能记成完成:队列后面还剩几千部,而页面上「完成」
+ # 和「跑完了」是同一个意思。按停是用户自己做的,不算故障。
+ stopped = str(result.get('stopped') or '')
+ failed = bool(stopped) and stopped != timeline_sheets.STOPPED_BY_USER
+ contract.thumbnail_job.update(
+ job_id, **result, completed_at=time.time(),
+ status='failed' if failed else 'complete',
+ error=stopped if failed else '')
+
+ contract.thumbnail_job.start(work, restart=True,
+ initial={'mode': mode, 'interval': interval,
+ 'total': 0, 'done': 0, 'made': 0,
+ 'skipped': 0, 'failed': 0, 'stopped': ''})
+ return q_thumbnail_jobs(contract, {})
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index 56be36c80..10761341a 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -889,6 +889,7 @@ class WebDataTests(unittest.TestCase):
"/api/tasks",
"/api/library-processing",
"/api/library-processing/issues",
+ "/api/thumbnail-jobs", "/api/timeline",
"/api/scraping", "/api/scraping/cover",
"/api/items", "/api/item", "/api/entity", "/api/photos", "/api/photo-set",
"/api/index", "/api/parts", "/api/editions", "/api/duplicates", "/api/quality-goals",
@@ -903,7 +904,7 @@ class WebDataTests(unittest.TestCase):
"/api/taste", "/api/settings", "/api/links",
})
self.assertEqual(set(rm_web.POST_HANDLERS), {
- "/api/library-processing",
+ "/api/library-processing", "/api/thumbnail-jobs",
"/api/scraping/settings", "/api/scraping/check", "/api/scraping/cover",
"/api/activity", "/api/play", "/api/feedback", "/api/watch-later",
"/api/playlist",
diff --git a/tests/test_timeline_sheets.py b/tests/test_timeline_sheets.py
new file mode 100644
index 000000000..dcbb66114
--- /dev/null
+++ b/tests/test_timeline_sheets.py
@@ -0,0 +1,206 @@
+"""时间轴预览的接触印相:格子几何、整套生成、队列取舍与整库跑法。"""
+from __future__ import annotations
+
+import json
+import shutil
+import sqlite3
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+from peach import timeline_sheets
+from peach.jobs import DiskSpaceDenied
+from support.ledger import fresh_ledger
+
+
+class SheetGeometryTests(unittest.TestCase):
+ def setUp(self):
+ self.root = Path(tempfile.mkdtemp(prefix="timeline-geometry-"))
+ self.addCleanup(lambda: shutil.rmtree(self.root, ignore_errors=True))
+
+ def test_sheets_of_one_video_live_under_one_bucket(self):
+ """产物按 id 末两位分桶。本机三千部一层平铺就是三千个目录挤在一处。"""
+ self.assertEqual(timeline_sheets.sheet_dir(self.root, 1234),
+ self.root / "34" / "1234")
+ self.assertEqual(timeline_sheets.sheet_path(self.root, 1234, 7).name, "007.jpg")
+
+ def test_a_video_too_short_to_scan_gets_no_sheet(self):
+ """两帧以下没有可扫的东西,一张图也不该出。"""
+ self.assertEqual(timeline_sheets.frame_count(15, 10), 1)
+ self.assertEqual(timeline_sheets.frame_count(0, 10), 0)
+ self.assertEqual(timeline_sheets.frame_count(3600, 10), 360)
+
+ def test_a_missing_sheet_file_sends_the_video_back_through(self):
+ """只认 meta 不看图的话,手工清过产物目录之后整批被当成做好的跳过,
+ 页面上则是一片取不到的图。"""
+ directory = timeline_sheets.sheet_dir(self.root, 5)
+ directory.mkdir(parents=True)
+ (directory / "meta.json").write_text(
+ json.dumps({"interval": 10, "frames": 120, "sheets": 2}), encoding="utf-8")
+ (directory / "000.jpg").write_bytes(b"x")
+ self.assertFalse(timeline_sheets.is_current(self.root, 5, 10))
+ (directory / "001.jpg").write_bytes(b"x")
+ self.assertTrue(timeline_sheets.is_current(self.root, 5, 10))
+ self.assertFalse(timeline_sheets.is_current(self.root, 5, 30))
+
+ def test_a_frame_that_would_not_decode_keeps_its_own_slot(self):
+ """抽失败的格子用邻近那一帧补上。少一帧让后面全体前移一格,图还是满的,
+ 位置整体错开,而错开多少取决于哪几帧解不出来。"""
+ for index in (0, 3):
+ (self.root / f"s{index:03d}.jpg").write_bytes(bytes([index]))
+ self.assertEqual(timeline_sheets._fill_gaps(self.root, 4), 4)
+ self.assertEqual((self.root / "s001.jpg").read_bytes(), bytes([0]))
+ self.assertEqual((self.root / "s002.jpg").read_bytes(), bytes([3]))
+
+ def test_nothing_decoded_means_no_sheet_at_all(self):
+ self.assertEqual(timeline_sheets._fill_gaps(self.root, 3), 0)
+
+
+class BuildTests(unittest.TestCase):
+ def setUp(self):
+ self.root = Path(tempfile.mkdtemp(prefix="timeline-build-"))
+ self.addCleanup(lambda: shutil.rmtree(self.root, ignore_errors=True))
+ self.stamps: list[float] = []
+
+ def _capture(self, _ffmpeg, _path, timestamp, destination, **_kw):
+ self.stamps.append(timestamp)
+ destination.write_bytes(b"frame")
+ return True
+
+ def _tile(self, _ffmpeg, _pattern, _columns, _rows, destination, **_kw):
+ destination.write_bytes(b"sheet")
+ return True
+
+ def _build(self, duration, interval, **kwargs):
+ with patch.object(timeline_sheets, "capture_with_retry", self._capture), \
+ patch.object(timeline_sheets, "tile_frames", self._tile):
+ return timeline_sheets.build("ffmpeg", "movie.mp4", duration, self.root,
+ 9, interval, **kwargs)
+
+ def test_the_frame_number_times_the_interval_is_where_it_came_from(self):
+ """前端按同一条式子从时间反算格子。采样点只被 `EDGE_MARGIN` 整体推进一点,
+ 不改这条对应关系的斜率。"""
+ meta = self._build(100, 10)
+ self.assertEqual(meta["frames"], 10)
+ self.assertEqual(meta["interval"], 10)
+ self.assertAlmostEqual(self.stamps[0], 1.0)
+ self.assertAlmostEqual(self.stamps[3] - self.stamps[2], 10.0)
+
+ def test_a_long_video_is_split_into_full_sheets_plus_a_remainder(self):
+ meta = self._build(10 * 1000, 10)
+ self.assertEqual(meta["sheets"], 10)
+ self.assertEqual(meta["frames"], 990)
+ self.assertTrue(timeline_sheets.sheet_path(self.root, 9, 9).is_file())
+
+ def test_stopping_midway_leaves_no_index_behind(self):
+ """半路停下不写 meta。留一份「说有 700 帧、实际只有 300 帧」的索引,
+ 下一趟会把它当成做好的跳过。"""
+ calls = {"n": 0}
+
+ def active():
+ calls["n"] += 1
+ return calls["n"] < 5
+
+ self.assertEqual(self._build(1000, 10, active=active), {})
+ self.assertIsNone(timeline_sheets.read_meta(self.root, 9))
+
+ def test_switching_density_does_not_leave_the_old_sheets_behind(self):
+ """换档位是整套重做,新的一套通常比旧的少几张。多出来的那几张 `is_current`
+ 又不看,只覆盖不清理就永远没人删。"""
+ self._build(10 * 1000, 10)
+ self._build(400, 30)
+ self.assertFalse(timeline_sheets.sheet_path(self.root, 9, 1).exists())
+ self.assertTrue(timeline_sheets.sheet_path(self.root, 9, 0).is_file())
+
+ def test_a_sheet_that_will_not_tile_produces_nothing(self):
+ with patch.object(timeline_sheets, "capture_with_retry", self._capture), \
+ patch.object(timeline_sheets, "tile_frames", lambda *a, **k: False):
+ self.assertEqual(timeline_sheets.build("ffmpeg", "movie.mp4", 100, self.root,
+ 9, 10), {})
+ self.assertFalse(timeline_sheets.sheet_path(self.root, 9, 0).exists())
+
+
+class QueueTests(unittest.TestCase):
+ def setUp(self):
+ self.root = Path(tempfile.mkdtemp(prefix="timeline-queue-"))
+ self.addCleanup(lambda: shutil.rmtree(self.root, ignore_errors=True))
+ self.db = fresh_ledger(self.root)
+ rows = [
+ (1, "local", r"R:\a.mp4", 3600, "2026-09-01", None),
+ (2, "pikpak", r"R:\b.mp4", 3600, "2026-09-02", None),
+ (3, "local", r"R:\c.mp4", 3600, None, None),
+ (4, "local", r"R:\d.mp4", 5, "2026-09-03", None),
+ (5, "local", r"R:\e.mp4", 3600, "2026-09-04", "trash"),
+ (6, "local", r"R:\f.mp4", 3600, "2026-09-05", None),
+ ]
+ connection = sqlite3.connect(self.db)
+ with connection:
+ connection.executemany(
+ "INSERT INTO asset(id,medium,location,path,duration,last_played,disposal) "
+ "VALUES(?,'video',?,?,?,?,?)", rows)
+ connection.close()
+
+ def test_the_queue_is_local_only_and_starts_with_what_was_played_last(self):
+ """这条链随时会被磁盘闸门或用户按停,跑到哪算哪,所以先做的必须是最可能被
+ 扫到的那些。网盘上的每抽一帧都要回源拉一次,不进队列。"""
+ self.assertEqual([row[0] for row in timeline_sheets.pending(self.db, 10)],
+ [6, 1, 3])
+
+ def test_the_queue_can_be_cut_short(self):
+ self.assertEqual([row[0] for row in timeline_sheets.pending(self.db, 10, limit=1)],
+ [6])
+
+
+class GenerateLibraryTests(unittest.TestCase):
+ def setUp(self):
+ self.root = Path(tempfile.mkdtemp(prefix="timeline-run-"))
+ self.addCleanup(lambda: shutil.rmtree(self.root, ignore_errors=True))
+ self.db = fresh_ledger(self.root)
+ self.media = self.root / "media"
+ self.media.mkdir()
+ connection = sqlite3.connect(self.db)
+ with connection:
+ for index in (1, 2, 3):
+ path = self.media / f"{index}.mp4"
+ if index != 3:
+ path.write_bytes(b"movie")
+ connection.execute(
+ "INSERT INTO asset(id,medium,location,path,duration,last_played) "
+ "VALUES(?,'video','local',?,3600,?)",
+ (index, str(path), f"2026-09-0{4 - index}"))
+ connection.close()
+ self.sheets = self.root / "sheets"
+
+ def _run(self, **kwargs):
+ with patch.object(timeline_sheets, "resolve_case_insensitive", lambda path: path):
+ return timeline_sheets.generate_library(
+ self.db, self.sheets, 10, ffmpeg="ffmpeg", **kwargs)
+
+ def test_a_video_that_will_not_open_does_not_take_the_queue_down_with_it(self):
+ """源坏了、时长记错、编码器不认,都是它自己的事;队列后面还有几千部。"""
+ with patch.object(timeline_sheets, "build", lambda *a, **k: {"frames": 1}):
+ state = self._run()
+ self.assertEqual((state["total"], state["made"], state["failed"]), (3, 2, 1))
+ self.assertEqual(state["stopped"], "")
+
+ def test_a_video_already_done_is_counted_as_skipped(self):
+ with patch.object(timeline_sheets, "is_current", lambda *a: True):
+ state = self._run()
+ self.assertEqual((state["skipped"], state["made"]), (3, 0))
+
+ def test_a_full_disk_stops_the_run_and_says_so(self):
+ """磁盘触线说明整台机器写不下了,立刻停手并把原因带出去,不能跑成「完成」。"""
+ guard = MagicMock()
+ guard.check.side_effect = DiskSpaceDenied("系统盘只剩 3 GB")
+ state = self._run(guard=guard)
+ self.assertEqual(state["stopped"], "系统盘只剩 3 GB")
+ self.assertEqual(state["done"], 0)
+
+ def test_pressing_stop_is_recorded_as_the_user_stopping_it(self):
+ state = self._run(active=lambda: False)
+ self.assertEqual(state["stopped"], timeline_sheets.STOPPED_BY_USER)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_web_resource_sync.py b/tests/test_web_resource_sync.py
index 732462472..c0d30e7be 100644
--- a/tests/test_web_resource_sync.py
+++ b/tests/test_web_resource_sync.py
@@ -113,7 +113,7 @@ class PurgeMissingTests(unittest.TestCase):
def test_full_sync_scans_all_online_assets_and_cleans_only_rebuildable_caches(self):
roots = {}
for name in ("snapshots", "posters", "photo-thumbs", "transcodes",
- "stream-segments", "avatars", "covers"):
+ "stream-segments", "timeline", "avatars", "covers"):
roots[name] = self.root / name
roots[name].mkdir()
cache_files = [
@@ -122,12 +122,19 @@ class PurgeMissingTests(unittest.TestCase):
roots["photo-thumbs"] / "2.jpg",
roots["transcodes"] / "2-10-20.mp4",
roots["stream-segments"] / "2" / "10-20-6" / "0.ts",
+ # 时间轴预览按 `<id 末两位>/<id>/` 分桶。一部三小时的片子按 10 秒一帧是
+ # 1080 张,片子没了还留着的话,是本机产物里单部占得最多的一类。
+ roots["timeline"] / "02" / "2" / "000.jpg",
+ roots["timeline"] / "02" / "2" / "meta.json",
roots["avatars"] / "2.jpg",
roots["covers"] / "hey-002.jpg",
]
for path in cache_files:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b"cache")
+ kept = roots["timeline"] / "04" / "4" / "000.jpg"
+ kept.parent.mkdir(parents=True)
+ kept.write_bytes(b"cache")
evidence = self.root / "candidate.csv"
evidence.write_text("review evidence", encoding="utf-8")
con = sqlite3.connect(self.db_path)
@@ -139,6 +146,7 @@ class PurgeMissingTests(unittest.TestCase):
self.contract.photo_root = roots["photo-thumbs"]
self.contract.transcode_root = roots["transcodes"]
self.contract.stream_root = roots["stream-segments"]
+ self.contract.timeline_root = roots["timeline"]
self.contract.avatar_root = roots["avatars"]
self.contract.cover_root = roots["covers"]
self.contract.resource_cleanup_enabled = True
@@ -156,6 +164,7 @@ class PurgeMissingTests(unittest.TestCase):
self.assertEqual(result["moved_to_trash"], 2)
self.assertEqual(result["cache_removed"], len(cache_files))
self.assertTrue(all(not path.exists() for path in cache_files))
+ self.assertTrue(kept.is_file(), "账本里还在的片子,它那套时间轴图不算孤儿")
self.assertTrue(evidence.is_file(), "候选证据不属于可删除缓存")
con = sqlite3.connect(self.db_path)
try:
diff --git a/tests/test_web_timeline_thumbnails.py b/tests/test_web_timeline_thumbnails.py
new file mode 100644
index 000000000..53dcd0171
--- /dev/null
+++ b/tests/test_web_timeline_thumbnails.py
@@ -0,0 +1,98 @@
+"""时间轴预览的档位与采集任务端点。"""
+from __future__ import annotations
+
+import json
+import shutil
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+from peach import timeline_sheets, web_timeline_thumbnails
+
+
+class ModeFileTests(unittest.TestCase):
+ def setUp(self):
+ self.root = Path(tempfile.mkdtemp(prefix="timeline-mode-"))
+ self.addCleanup(lambda: shutil.rmtree(self.root, ignore_errors=True))
+ self.path = self.root / "timeline-thumbnails.json"
+
+ def test_an_unreadable_setting_means_the_job_stays_off(self):
+ """这条链会写盘也会读片子,不能靠猜来开。"""
+ self.assertEqual(web_timeline_thumbnails.read_mode(self.path), "off")
+ self.path.write_text("{", encoding="utf-8")
+ self.assertEqual(web_timeline_thumbnails.read_mode(self.path), "off")
+ self.path.write_text(json.dumps({"mode": "hourly"}), encoding="utf-8")
+ self.assertEqual(web_timeline_thumbnails.read_mode(self.path), "off")
+
+ def test_the_chosen_density_survives_a_restart(self):
+ web_timeline_thumbnails.write_mode("coarse", self.path)
+ self.assertEqual(web_timeline_thumbnails.read_mode(self.path), "coarse")
+
+
+class ThumbnailJobEndpointTests(unittest.TestCase):
+ def setUp(self):
+ self.root = Path(tempfile.mkdtemp(prefix="timeline-endpoint-"))
+ self.addCleanup(lambda: shutil.rmtree(self.root, ignore_errors=True))
+ self.contract = MagicMock()
+ self.contract.timeline_root = self.root / "sheets"
+ self.contract.db_path = self.root / "ledger.db"
+ self.contract.thumbnail_job.snapshot.return_value = {}
+ patcher = patch.object(web_timeline_thumbnails, "MODE_PATH",
+ self.root / "timeline-thumbnails.json")
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def test_an_unknown_density_is_refused_before_anything_starts(self):
+ with self.assertRaises(ValueError):
+ web_timeline_thumbnails.w_thumbnail_jobs(self.contract, {"mode": "every-second"})
+ self.contract.thumbnail_job.start.assert_not_called()
+ self.assertEqual(web_timeline_thumbnails.read_mode(), "off")
+
+ def test_turning_it_off_stops_the_run_and_keeps_the_sheets(self):
+ """几 GB 的产物删不删是另一件事,走数据管理页那条清理链。"""
+ web_timeline_thumbnails.write_mode("precise")
+ made = timeline_sheets.sheet_path(self.contract.timeline_root, 3, 0)
+ made.parent.mkdir(parents=True)
+ made.write_bytes(b"sheet")
+ state = web_timeline_thumbnails.w_thumbnail_jobs(self.contract, {"mode": "off"})
+ self.contract.thumbnail_job.stop.assert_called_once_with()
+ self.assertEqual(state["mode"], "off")
+ self.assertTrue(made.is_file())
+
+ def test_choosing_a_density_starts_the_run_and_reports_it(self):
+ resolver = MagicMock()
+ resolver.return_value.ffmpeg.return_value.path = "ffmpeg"
+ with patch.object(web_timeline_thumbnails, "FFmpegResolver", resolver):
+ state = web_timeline_thumbnails.w_thumbnail_jobs(self.contract, {"mode": "coarse"})
+ self.assertEqual(state["mode"], "coarse")
+ self.assertEqual(state["intervals"]["coarse"], 30)
+ started = self.contract.thumbnail_job.start.call_args
+ self.assertTrue(started.kwargs["restart"])
+ self.assertEqual(started.kwargs["initial"]["interval"], 30)
+
+ def test_without_ffmpeg_the_density_cannot_be_turned_on(self):
+ resolver = MagicMock()
+ resolver.return_value.ffmpeg.return_value = None
+ with patch.object(web_timeline_thumbnails, "FFmpegResolver", resolver):
+ with self.assertRaises(ValueError):
+ web_timeline_thumbnails.w_thumbnail_jobs(self.contract, {"mode": "precise"})
+ self.contract.thumbnail_job.start.assert_not_called()
+
+ def test_a_video_with_no_sheets_reports_an_empty_index(self):
+ """页面据此决定要不要画这一层;空对象就是退回九宫格。"""
+ self.assertEqual(web_timeline_thumbnails.q_timeline(self.contract, {"id": "7"}), {})
+ self.assertEqual(web_timeline_thumbnails.q_timeline(self.contract, {}), {})
+
+ def test_a_video_with_sheets_reports_the_interval_and_frame_count(self):
+ directory = timeline_sheets.sheet_dir(self.contract.timeline_root, 7)
+ directory.mkdir(parents=True)
+ (directory / "meta.json").write_text(
+ json.dumps({"interval": 30, "frames": 120, "sheets": 2, "columns": 10}),
+ encoding="utf-8")
+ index = web_timeline_thumbnails.q_timeline(self.contract, {"id": "7"})
+ self.assertEqual((index["interval"], index["frames"]), (30, 120))
+
+
+if __name__ == "__main__":
+ unittest.main()