Skip to content

PRINTFILM: AI short-video marketing and AI short-drama creation platform

fix

增瑞 田eb985f780127
diff --git a/backend/app/marketplace/drama_geometry.py b/backend/app/marketplace/drama_geometry.py
new file mode 100644
index 0000000..70fda5f
--- /dev/null
+++ b/backend/app/marketplace/drama_geometry.py
@@ -0,0 +1,71 @@
+"""统一解释分镜显示画幅,避免像素比例和旋转元数据导致误判或画面变形。"""
+from __future__ import annotations
+
+from fractions import Fraction
+import math
+
+
+def _pixel_ratio(video: dict) -> Fraction:
+ """缺失或无效的像素宽高比按方形像素解释。"""
+ try:
+ ratio = Fraction(str(video.get("sample_aspect_ratio") or "1:1").replace(":", "/"))
+ return ratio if ratio > 0 else Fraction(1)
+ except (ValueError, ZeroDivisionError):
+ return Fraction(1)
+
+
+def _quarter_turn(video: dict) -> bool:
+ """识别 FFmpeg 自动旋转使用的直角元数据,拒绝悄悄误算任意角度。"""
+ rotation = video.get("tags", {}).get("rotate") or 0
+ for side in video.get("side_data_list", []):
+ if "rotation" in side:
+ rotation = side["rotation"]
+ try:
+ angle = float(rotation)
+ turns = round(angle / 90)
+ if not math.isfinite(angle) or abs(angle - turns * 90) > 0.1:
+ raise ValueError("unsupported rotation")
+ except (ValueError, TypeError, OverflowError) as exc:
+ raise ValueError("MARKETPLACE_SOURCE_INCOMPATIBLE:分镜旋转角度不受支持,请先导出为标准横屏或竖屏视频") from exc
+ return bool(turns % 2)
+
+
+def display_ratio(info: dict) -> Fraction:
+ """先应用原始轴上的像素比例,再旋转;不让尺寸取整影响画幅判断。"""
+ ratio = Fraction(info["width"], info["height"]) * _pixel_ratio(info["video"])
+ return 1 / ratio if _quarter_turn(info["video"]) else ratio
+
+
+def display_dimensions(info: dict) -> tuple[int, int]:
+ """只扩大像素尺寸来还原显示画幅,最后应用旋转,不缩小源画面。"""
+ width, height = info["width"], info["height"]
+ ratio = _pixel_ratio(info["video"])
+ if ratio > 1:
+ width = math.ceil(width * ratio)
+ elif ratio < 1:
+ height = math.ceil(height / ratio)
+ return (height, width) if _quarter_turn(info["video"]) else (width, height)
+
+
+def validate_aspects(infos: list[dict], clips: list[dict]) -> list[tuple[int, int]]:
+ """允许同画幅不同清晰度;冲突时只报告镜号、尺寸等安全诊断信息。"""
+ ratios = [display_ratio(info) for info in infos]
+ for index, ratio in enumerate(ratios[1:], 1):
+ if abs(ratio / ratios[0] - 1) > Fraction(5, 1000):
+ def describe(position):
+ """把真实来源规格映射回发布时的分镜顺序。"""
+ info, clip = infos[position], clips[position]
+ value = ratios[position].limit_denominator(10000)
+ return (f"第{position + 1}镜(分镜编号{clip['id']},{info['width']}×{info['height']},"
+ f"显示{value.numerator}:{value.denominator})")
+ raise ValueError("MARKETPLACE_SOURCE_INCOMPATIBLE:分镜画幅比例不一致:"
+ f"{describe(0)}与{describe(index)};请先统一画幅后发布")
+ return [display_dimensions(info) for info in infos]
+
+
+def fit_dimensions(info: dict, width: int, height: int) -> tuple[int, int]:
+ """按显示画幅适配偶数像素画布,供方形像素编码使用,避免 SAR 被重置后压扁。"""
+ ratio = display_ratio(info)
+ if Fraction(width, height) > ratio:
+ return max(2, math.floor(height * ratio / 2) * 2), height
+ return width, max(2, math.floor(width / ratio / 2) * 2)
diff --git a/backend/app/marketplace/drama_media.py b/backend/app/marketplace/drama_media.py
index 962a20a..0f656c0 100644
--- a/backend/app/marketplace/drama_media.py
+++ b/backend/app/marketplace/drama_media.py
@@ -14,6 +14,7 @@ from app.config import get_settings
from app.services.storage import STATIC_ROOT
from . import storage
from .config import get_marketplace_settings
+from .drama_geometry import display_dimensions as _dimensions, fit_dimensions, validate_aspects
from .worker import cache_root, command, fingerprint
_FORMATS = "mov,mp4,matroska,webm"
@@ -204,28 +205,6 @@ def _signature(info: dict) -> tuple:
video.get("side_data_list", []), video.get("tags", {}).get("rotate"))
-def _dimensions(info: dict) -> tuple[int, int]:
- video = info["video"]
- rotation = float(video.get("tags", {}).get("rotate") or 0)
- for side in video.get("side_data_list", []):
- if "rotation" in side:
- rotation = float(side["rotation"])
- width, height = info["width"], info["height"]
- if round(rotation) % 180:
- width, height = height, width
- sar = video.get("sample_aspect_ratio") or "1:1"
- try:
- pixel_ratio = float(Fraction(sar.replace(":", "/"))) if sar not in ("N/A", "0:1") else 1.0
- except (ValueError, ZeroDivisionError):
- pixel_ratio = 1.0
- # 扩大显示尺寸以消除非方形像素,绝不缩小来源像素。
- if pixel_ratio > 1:
- width = math.ceil(width * pixel_ratio)
- elif 0 < pixel_ratio < 1:
- height = math.ceil(height / pixel_ratio)
- return width, height
-
-
async def _concat(paths: list[Path], output: Path, timeout: float) -> None:
listing = output.with_suffix(".txt")
listing.write_text("\n".join(f"file '{path.name}'" for path in paths), encoding="utf-8")
@@ -235,10 +214,8 @@ async def _concat(paths: list[Path], output: Path, timeout: float) -> None:
async def _encode(paths: list[Path], infos: list[dict], output: Path, timeout: float) -> None:
+ """保持显示比例与最大源尺寸,必要时补齐取整像素并统一编码。"""
sizes = [_dimensions(info) for info in infos]
- ratio = sizes[0][0] / sizes[0][1]
- if any(abs(width / height / ratio - 1) > 0.005 for width, height in sizes):
- raise _error("SOURCE_INCOMPATIBLE", "分镜画幅比例不一致,请先统一画幅后发布")
width = math.ceil(max(size[0] for size in sizes) / 2) * 2
height = math.ceil(max(size[1] for size in sizes) / 2) * 2
if width * height > 50_000_000:
@@ -266,9 +243,10 @@ async def _encode(paths: list[Path], infos: list[dict], output: Path, timeout: f
f"aresample=48000:async=1:first_pts=0,apad,atrim=duration={info['duration']}",
"-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2"]
# 同画幅因像素取整略有差异时补边,避免把人物画面拉伸。
+ fit_width, fit_height = fit_dimensions(info, width, height)
args += ["-sn", "-dn", "-t", str(info["duration"]), "-vf",
- f"scale={width}:{height}:force_original_aspect_ratio=decrease:flags=lanczos,"
- f"pad={width}:{height}:(ow-iw)/2:(oh-ih)/2,setsar=1,setpts=PTS-STARTPTS", "-r", str(fps),
+ f"scale={fit_width}:{fit_height}:flags=lanczos,setsar=1,"
+ f"pad={width}:{height}:(ow-iw)/2:(oh-ih)/2,setpts=PTS-STARTPTS", "-r", str(fps),
"-c:v", "libx264", "-preset", "fast", "-crf", "18", "-pix_fmt", "yuv420p",
"-threads", "2", "-video_track_timescale", "90000", "-movflags", "+faststart", str(dest)]
await command(*args, timeout=timeout)
@@ -315,10 +293,7 @@ async def prepare_drama_video(snapshot: dict, dest_key: str, progress=None) -> d
except ValueError as exc:
raise _error("SOURCE_INCOMPATIBLE", "分镜编码无法无损封装为市场视频") from exc
else:
- dimensions = [_dimensions(info) for info in infos]
- ratio = dimensions[0][0] / dimensions[0][1]
- if any(abs(width / height / ratio - 1) > 0.005 for width, height in dimensions):
- raise _error("SOURCE_INCOMPATIBLE", "分镜画幅比例不一致,请先统一画幅后发布")
+ validate_aspects(infos, clips)
compatible = all(_signature(info) == _signature(infos[0]) for info in infos[1:])
copied = False
if compatible:
@@ -346,27 +321,42 @@ async def prepare_drama_video(snapshot: dict, dest_key: str, progress=None) -> d
async def prepare_drama_cover(locator: str, dest_key: str, stamp: dict | None = None) -> dict:
- """安全复制可选封面,重编码为 PNG;失败由调用方提示用户补充封面。"""
+ """安全复制项目封面;卡片以视频展示时取首帧,统一保存为市场私有 PNG。"""
if not dest_key.startswith("marketplace/") or ".." in dest_key.split("/") or "\\" in dest_key:
raise _error("SOURCE_NOT_READY", "市场封面目标目录无效")
expected = stamp if stamp is not None else await _thread(source_stamp, locator)
- if not 0 < int(expected.get("size_bytes", 0)) <= get_marketplace_settings().max_document_bytes:
- raise _error("SOURCE_NOT_READY", "封面为空或超过图片大小限制")
+ limits = get_marketplace_settings()
+ if not 0 < int(expected.get("size_bytes", 0)) <= limits.max_video_bytes:
+ raise _error("SOURCE_NOT_READY", "源封面为空或超过媒体大小限制")
with tempfile.TemporaryDirectory(prefix="job-", dir=cache_root()) as directory:
root = Path(directory)
source, output = root / "cover-source", root / "cover.png"
await _thread(_copy_source, {"locator": locator, "stamp": expected}, source)
try:
+ formats = "png_pipe,jpeg_pipe,webp_pipe,image2," + _FORMATS
probe = json.loads(await command(get_settings().ffprobe_path, "-v", "error", "-protocol_whitelist", "file,pipe",
- "-format_whitelist", "png_pipe,jpeg_pipe,webp_pipe,image2", "-show_streams", "-of", "json", str(source), timeout=60))
- image = next(stream for stream in probe.get("streams", []) if stream.get("codec_type") == "video")
+ "-format_whitelist", formats, "-show_streams", "-show_format", "-of", "json", str(source), timeout=60))
+ image = next(stream for stream in probe.get("streams", []) if stream.get("codec_type") == "video"
+ and not stream.get("disposition", {}).get("attached_pic"))
width, height = int(image["width"]), int(image["height"])
- if image.get("codec_name") not in ("png", "mjpeg", "webp") or min(width, height) < 2 or width * height > 50_000_000:
+ video_source = bool(set(probe.get("format", {}).get("format_name", "").split(",")) & set(_FORMATS.split(",")))
+ if min(width, height) < 2 or width * height > 50_000_000:
+ raise ValueError("invalid image")
+ if not video_source and (image.get("codec_name") not in ("png", "mjpeg", "webp")
+ or expected["size_bytes"] > limits.max_document_bytes):
raise ValueError("invalid image")
+ if video_source:
+ duration = float(probe.get("format", {}).get("duration", 0))
+ if not math.isfinite(duration) or not 0 < duration <= limits.max_duration_seconds:
+ raise ValueError("invalid video")
+ width, height = _dimensions({"video": image, "width": width, "height": height})
+ if width * height > 50_000_000:
+ raise ValueError("invalid display size")
await command(get_settings().ffmpeg_path, "-y", "-v", "error", "-protocol_whitelist", "file,pipe",
- "-format_whitelist", "png_pipe,jpeg_pipe,webp_pipe,image2", "-i", str(source), "-frames:v", "1", str(output), timeout=60)
+ "-format_whitelist", formats, "-i", str(source), "-map", f"0:{image['index']}", "-an", "-sn", "-dn",
+ "-vf", f"scale={width}:{height}:flags=lanczos,setsar=1", "-frames:v", "1", str(output), timeout=60)
except (ValueError, KeyError, StopIteration) as exc:
- raise _error("SOURCE_NOT_READY", "源封面不是有效的 PNG、JPG 或 WebP 图片,请重新上传封面") from exc
+ raise _error("SOURCE_NOT_READY", "源封面不是有效图片或项目视频,请重新上传封面") from exc
size = output.stat().st_size
if not 0 < size <= get_marketplace_settings().max_document_bytes:
raise _error("SOURCE_NOT_READY", "处理后的封面超过图片大小限制")
diff --git a/backend/app/marketplace/drama_publish.py b/backend/app/marketplace/drama_publish.py
index 5f1df3d..f8725bd 100644
--- a/backend/app/marketplace/drama_publish.py
+++ b/backend/app/marketplace/drama_publish.py
@@ -7,10 +7,12 @@ import json
from fastapi import APIRouter, HTTPException
from sqlalchemy import func, or_, select, text, update
+from sqlalchemy.orm import selectinload
from app.models_drama import DramaEpisode, DramaEpisodeFragment, DramaProject
from app.models_tasks import TaskRun
from app.services.drama.access import require_drama_project_access
+from app.services.drama.project_cover import resolve_drama_project_cover
from .authorization import current as current_authorization
from .dependencies import Actor, DB, storage_ready
from .models import DramaPublishBatch, Handoff, Publication, Rights, Series, SeriesEpisode
@@ -46,9 +48,53 @@ async def owned_project(db, owner_id: int, project_id: int):
return project
+async def project_cover_snapshot(db, project_id: int, *, known_stamps=None) -> dict:
+ """沿用漫剧项目卡片的封面来源,并冻结真实文件身份供市场独立转存。"""
+ from .drama_media import source_stamp
+
+ project = (await db.execute(select(DramaProject).where(DramaProject.id == project_id).options(
+ selectinload(DramaProject.assets),
+ selectinload(DramaProject.episodes).selectinload(DramaEpisode.fragments),
+ ).execution_options(populate_existing=True))).scalar_one()
+ locator, _ = resolve_drama_project_cover(project)
+ if locator:
+ try:
+ stamp = (known_stamps or {}).get(locator)
+ if stamp is None:
+ stamp = await asyncio.to_thread(source_stamp, locator)
+ return {"project_cover_locator": locator, "project_cover_stamp": stamp}
+ except (HTTPException, ValueError, OSError):
+ pass
+ return {"project_cover_locator": "", "project_cover_stamp": None}
+
+
+def snapshot_source_version(snapshot: dict, *, include_project_cover: bool = True) -> str:
+ """按快照原协议计算来源版本,兼容升级前未包含项目封面的完整分集任务。"""
+ from .drama_media import stamp_version
+
+ cover_stamp = snapshot.get("cover_stamp")
+ if not include_project_cover and not any(clip.get("cover") for clip in snapshot["clips"]):
+ # 旧协议在没有分镜图片时留空,不将新增的视频首帧回退当作源文件变化。
+ cover_stamp = None
+ payload = {"episode": snapshot["drama_episode_id"], "title": snapshot["title"],
+ "episode_number": snapshot["episode_number"], "updated_at": snapshot["episode_updated_at"],
+ "cover_stamp": stamp_version(cover_stamp) if cover_stamp else None,
+ "clips": [{"id": clip["id"], "sort_order": clip["sort_order"], "updated_at": clip["updated_at"],
+ "stamp": stamp_version(clip["stamp"]), "cover": clip["cover"]} for clip in snapshot["clips"]]}
+ if include_project_cover:
+ project_stamp = snapshot.get("project_cover_stamp")
+ payload["project_cover_stamp"] = stamp_version(project_stamp) if project_stamp else None
+ return digest(payload)
+
+
+def source_matches(snapshot: dict, task: Handoff) -> bool:
+ """只放宽新增封面协议字段,真实分镜与原分镜封面发生变化仍拒绝复用。"""
+ return snapshot_source_version(snapshot, include_project_cover="project_cover_stamp" in (task.source_snapshot or {})) == task.source_version
+
+
async def episode_snapshot(db, owner_id: int, project_id: int, episode_id: int) -> dict:
"""服务端保存有序分镜与实际文件身份,不接受客户端传入视频地址。"""
- from .drama_media import source_stamp, stamp_version
+ from .drama_media import source_stamp
project = await owned_project(db, owner_id, project_id)
episode = await db.get(DramaEpisode, episode_id)
@@ -82,26 +128,30 @@ async def episode_snapshot(db, owner_id: int, project_id: int, episode_id: int)
clips.append({"id": fragment.id, "sort_order": fragment.sort_order, "locator": locator,
"stamp": stamp, "updated_at": fragment.updated_at.isoformat(),
"cover": fragment.cover or ""})
+ known_stamps = {clip["locator"]: clip["stamp"] for clip in clips}
+ project_cover = await project_cover_snapshot(db, project.id, known_stamps=known_stamps)
+ if project_cover["project_cover_stamp"]:
+ known_stamps[project_cover["project_cover_locator"]] = project_cover["project_cover_stamp"]
snapshot = {"schema_version": 2, "drama_project_id": project.id, "drama_episode_id": episode.id,
"episode_number": episode_number(episode), "title": episode.name,
"episode_updated_at": episode.updated_at.isoformat(), "clips": clips,
- "cover_locator": next((clip["cover"] for clip in clips if clip["cover"]), "")}
+ **project_cover,
+ "cover_locator": next((clip["cover"] for clip in clips if clip["cover"]), "")
+ or project_cover["project_cover_locator"]}
snapshot["cover_stamp"] = None
if snapshot["cover_locator"]:
try:
- snapshot["cover_stamp"] = await asyncio.to_thread(source_stamp, snapshot["cover_locator"])
+ snapshot["cover_stamp"] = known_stamps.get(snapshot["cover_locator"])
+ if snapshot["cover_stamp"] is None:
+ snapshot["cover_stamp"] = await asyncio.to_thread(source_stamp, snapshot["cover_locator"])
except (HTTPException, ValueError, OSError):
# A missing cover never selects an unrelated material. The editor asks for one.
snapshot["cover_locator"] = ""
- snapshot["source_version"] = digest({"episode": episode.id, "title": episode.name,
- "episode_number": snapshot["episode_number"], "updated_at": snapshot["episode_updated_at"],
- "cover_stamp": stamp_version(snapshot["cover_stamp"]) if snapshot["cover_stamp"] else None,
- "clips": [{"id": clip["id"], "sort_order": clip["sort_order"], "updated_at": clip["updated_at"],
- "stamp": stamp_version(clip["stamp"]), "cover": clip["cover"]} for clip in clips]})
+ snapshot["source_version"] = snapshot_source_version(snapshot)
return snapshot
-async def episode_context(db, owner_id: int, project_id: int, episode) -> dict:
+async def episode_context(db, owner_id: int, project_id: int, episode, *, source_versions=None) -> dict:
fragments = list((await db.execute(select(DramaEpisodeFragment).where(DramaEpisodeFragment.episode_id == episode.id))).scalars().all())
result = {"id": episode.id, "name": episode.name, "episode_number": episode_number(episode),
"fragment_count": len(fragments), "completed_count": sum(bool((f.video or "").strip()) for f in fragments),
@@ -109,6 +159,8 @@ async def episode_context(db, owner_id: int, project_id: int, episode) -> dict:
try:
snapshot = await episode_snapshot(db, owner_id, project_id, episode.id)
result.update(ready=True, source_version=snapshot["source_version"])
+ if source_versions is not None:
+ source_versions[episode.id] = (snapshot["source_version"], snapshot_source_version(snapshot, include_project_cover=False))
except HTTPException as exc:
result["reason"] = str(exc.detail)
return result
@@ -125,6 +177,8 @@ async def publish_context(project_id: int, db: DB, user: Actor):
project = await owned_project(db, user.id, project_id)
episodes = list((await db.execute(select(DramaEpisode).where(DramaEpisode.project_id == project.id))).scalars().all())
episodes.sort(key=lambda row: (episode_number(row), row.id))
+ source_versions = {}
+ episode_items = [await episode_context(db, user.id, project.id, episode, source_versions=source_versions) for episode in episodes]
targets = list((await db.execute(select(Series).where(Series.owner_id == user.id,
Series.deleted_at.is_(None), Series.blocked.is_(False)).order_by(Series.id.desc()))).scalars().all())
series_items = []
@@ -144,15 +198,21 @@ async def publish_context(project_id: int, db: DB, user: Actor):
(handoff.status == "ready" and handoff.asset_id == episode.asset_id and mapping.get("last_handoff_id") == handoff.id)
or (handoff.status in ("pending", "running", "failed") and mapping.get("pending_handoff_id") == handoff.id
and frozen.get("target_version") == episode.version and frozen.get("original_asset_id") == episode.asset_id)))
- mappings.append({"source_episode_id": mapping.get("drama_episode_id") or mapping.get("source_id"),
- "episode_id": episode.id, "source_version": handoff.source_version if handoff else mapping.get("imported_source_version", ""),
+ source_id = mapping.get("drama_episode_id") or mapping.get("source_id")
+ version = handoff.source_version if handoff else mapping.get("imported_source_version", "")
+ current_versions = source_versions.get(source_id)
+ if (reusable and current_versions and "project_cover_stamp" not in frozen and version == current_versions[1]):
+ # 向选择弹窗返回可比较的新协议版本,不改写原任务、源快照或已购买发布记录。
+ version = current_versions[0]
+ mappings.append({"source_episode_id": source_id,
+ "episode_id": episode.id, "source_version": version,
"status": handoff.status if handoff else "legacy", "handoff_id": handoff.id if handoff else None,
"requires_update": not reusable})
series_items.append({"id": target.id, "title": target.title, "version": target.version,
"series_version": target.version, "listed": target.listed,
"audit_status": target.audit_status, "imports": mappings})
return {"project": {"id": project.id, "title": project.title, "description": project.description or ""},
- "episodes": [await episode_context(db, user.id, project.id, episode) for episode in episodes],
+ "episodes": episode_items,
"series": series_items, "authorization_ready": bool(await current_authorization(db, user.id)),
"storage_configured": configured()}
@@ -257,7 +317,7 @@ async def publish_selected(project_id: int, body: DramaPublishInput, db, user):
and mapping.get("last_handoff_id") == previous.id)
or (previous.status in ("pending", "running", "failed") and previous_snapshot.get("target_version") == target.version
and previous_snapshot.get("original_asset_id") == target.asset_id and mapping.get("pending_handoff_id") == previous.id)))
- if previous_matches and previous.source_version == snapshot["source_version"] and previous_snapshot.get("schema_version") == 2:
+ if previous_matches and source_matches(snapshot, previous) and previous_snapshot.get("schema_version") == 2:
targets.append(target)
tasks.append(previous)
continue
@@ -286,7 +346,9 @@ async def publish_selected(project_id: int, body: DramaPublishInput, db, user):
source_kind="drama_episode", source_id=source_id, source_version=snapshot["source_version"],
target_kind="series_episode", target_id=target.id, series_id=series.id, status="pending",
source_snapshot={**snapshot, "phase": "queued", "target_version": target.version,
- "original_asset_id": target.asset_id})
+ "original_asset_id": target.asset_id,
+ "inherit_series_cover": not bool(body.series_id),
+ "series_cover_version": series.version + 1})
db.add(task)
await db.flush()
target.source = "printfilm"
diff --git a/backend/app/marketplace/handoff.py b/backend/app/marketplace/handoff.py
index b19d80b..a826ec9 100644
--- a/backend/app/marketplace/handoff.py
+++ b/backend/app/marketplace/handoff.py
@@ -24,7 +24,7 @@ from .authorization import current as current_authorization
from .categories import category_config
from .config import get_marketplace_settings
from .dependencies import Actor, DB, storage_ready
-from .models import Asset, Handoff, SeriesEpisode, Work
+from .models import Asset, Handoff, Series, SeriesEpisode, Work
from .schemas import PrintfilmEpisodeInput, PrintfilmWorkInput
from .service import data, fail, notify, now
@@ -516,7 +516,7 @@ async def _copy(handoff_id: int, token: str) -> None:
await db.commit()
-async def _bind(db, item: Handoff, asset_id: int, cover_id: int | None) -> None:
+async def _bind(db, item: Handoff, asset_id: int, cover_id: int | None, series_cover_id: int | None = None) -> None:
"""把就绪资产挂到草稿上;不改审核状态,也不生成水印。"""
if item.target_kind == "work":
work = await db.get(Work, item.target_id)
@@ -530,6 +530,11 @@ async def _bind(db, item: Handoff, asset_id: int, cover_id: int | None) -> None:
episode.asset_id = asset_id
if cover_id and not episode.cover_asset_id:
episode.cover_asset_id = cover_id
+ series = await db.get(Series, item.series_id)
+ snapshot = item.source_snapshot or {}
+ if (series_cover_id and snapshot.get("inherit_series_cover") and not series.cover_asset_id
+ and series.version == snapshot.get("series_cover_version")):
+ series.cover_asset_id = series_cover_id
episode.source_snapshot = {**(episode.source_snapshot or {}), "pending_handoff_id": None,
"last_handoff_id": item.id, "imported_source_version": item.source_version}
from .drama_publish import ensure_import_rights
@@ -559,7 +564,7 @@ async def _drama_target(db, item):
async def _validate_drama_source(db, item):
- from .drama_publish import episode_snapshot
+ from .drama_publish import episode_snapshot, source_matches
snapshot = item.source_snapshot or {}
if snapshot.get("schema_version") != 2:
fail("MARKETPLACE_SOURCE_CHANGED:旧导入未包含完整分镜,请重新选择分集并确认更新", 409)
@@ -569,7 +574,7 @@ async def _validate_drama_source(db, item):
if exc.status_code == 503:
raise
fail("MARKETPLACE_SOURCE_CHANGED:源分集已变化或正在重新生成,请重新选择分集", 409)
- if current["source_version"] != item.source_version:
+ if not source_matches(current, item):
fail("MARKETPLACE_SOURCE_CHANGED:源分集已更新,请重新选择分集", 409)
@@ -595,26 +600,27 @@ async def _copy_drama(handoff_id, token):
folder = f"marketplace/series/u{owner_id}/{target_id}"
dest = f"{folder}/{uuid.uuid4().hex}.mp4"
cover_key = f"{folder}/cover-{uuid.uuid4().hex}.png"
- bound = False
+ series_cover_key = (cover_key if snapshot.get("project_cover_locator") == snapshot.get("cover_locator")
+ else f"{folder}/series-cover-{uuid.uuid4().hex}.png")
+ object_keys = tuple(dict.fromkeys((dest, cover_key, series_cover_key)))
try:
- bound = await _finish_drama_copy(handoff_id, token, snapshot, owner_id, dest, cover_key)
+ await _finish_drama_copy(handoff_id, token, snapshot, owner_id, dest, cover_key, series_cover_key)
finally:
- if not bound:
- from .storage import discard_generated
- try:
- # A database commit error can have an uncertain outcome. Never
- # remove an object unless a fresh read confirms it is unbound.
- async with AsyncSessionLocal() as db:
- referenced = set((await db.execute(select(Asset.object_key).where(Asset.object_key.in_((dest, cover_key))))).scalars().all())
- for key in (dest, cover_key):
- if key in referenced:
- continue
+ from .storage import discard_generated
+ try:
+ # A commit error can have an uncertain outcome. Only discard objects
+ # confirmed unbound, including covers superseded by the author's edit.
+ async with AsyncSessionLocal() as db:
+ referenced = set((await db.execute(select(Asset.object_key).where(Asset.object_key.in_(object_keys)))).scalars().all())
+ for key in object_keys:
+ if key not in referenced:
await asyncio.to_thread(discard_generated, key)
- except Exception:
- logger.warning("未绑定的市场同步对象清理失败,任务 %s", handoff_id)
+ except Exception:
+ logger.warning("未绑定的市场同步对象清理失败,任务 %s", handoff_id)
-async def _finish_drama_copy(handoff_id, token, snapshot, owner_id, dest, cover_key):
+async def _finish_drama_copy(handoff_id, token, snapshot, owner_id, dest, cover_key, series_cover_key):
+ """独立转存分集与项目封面,仅为未被编辑的新系列回填项目封面。"""
from .drama_media import prepare_drama_video, prepare_drama_cover
result = await prepare_drama_video(snapshot, dest, lambda phase: _phase(handoff_id, token, phase))
cover = None
@@ -623,6 +629,16 @@ async def _finish_drama_copy(handoff_id, token, snapshot, owner_id, dest, cover_
cover = {**await prepare_drama_cover(snapshot["cover_locator"], cover_key, snapshot.get("cover_stamp")), "object_key": cover_key}
except (ValueError, HTTPException, OSError):
logger.info("漫剧来源封面不可用,保留为待上传封面")
+ series_cover = None
+ if snapshot.get("inherit_series_cover") and snapshot.get("project_cover_locator"):
+ if snapshot["project_cover_locator"] == snapshot.get("cover_locator"):
+ series_cover = cover
+ else:
+ try:
+ series_cover = {**await prepare_drama_cover(snapshot["project_cover_locator"], series_cover_key,
+ snapshot.get("project_cover_stamp")), "object_key": series_cover_key}
+ except (ValueError, HTTPException, OSError):
+ logger.info("漫剧项目封面不可用,保留为待上传系列封面")
async with AsyncSessionLocal() as db:
# Queue/update locks series -> episode -> handoff; use the same order.
candidate = await db.get(Handoff, handoff_id)
@@ -634,20 +650,32 @@ async def _finish_drama_copy(handoff_id, token, snapshot, owner_id, dest, cover_
if not item:
return False
await _validate_drama_source(db, item)
- await _drama_target(db, item)
+ episode = await _drama_target(db, item)
asset = Asset(owner_id=owner_id, kind="video", filename=f"{snapshot['title'][:180]}.mp4", object_key=dest,
status="ready", **{key: result[key] for key in ("size_bytes", "content_type", "fingerprint", "duration_seconds")})
db.add(asset)
await db.flush()
item.asset_id, item.source_fingerprint = asset.id, asset.fingerprint
cover_id = None
- if cover:
+ if cover and not episode.cover_asset_id:
cover_asset = Asset(owner_id=owner_id, kind="image", filename="cover" + Path(cover["object_key"]).suffix,
status="ready", **{key: cover[key] for key in ("object_key", "size_bytes", "content_type")})
db.add(cover_asset)
await db.flush()
cover_id = cover_asset.id
- await _bind(db, item, asset.id, cover_id)
+ series_cover_id = None
+ series = await db.get(Series, item.series_id)
+ if (series_cover and not series.cover_asset_id and snapshot.get("inherit_series_cover")
+ and series.version == snapshot.get("series_cover_version")):
+ if series_cover is cover and cover_id is not None:
+ series_cover_id = cover_id
+ else:
+ series_cover_asset = Asset(owner_id=owner_id, kind="image", filename="series-cover.png", status="ready",
+ **{key: series_cover[key] for key in ("object_key", "size_bytes", "content_type")})
+ db.add(series_cover_asset)
+ await db.flush()
+ series_cover_id = series_cover_asset.id
+ await _bind(db, item, asset.id, cover_id, series_cover_id)
item.status, item.error, item.lease_token, item.lease_until = "ready", "", None, None
item.source_snapshot = {**item.source_snapshot, "phase": "ready"}
await db.commit()
diff --git a/backend/tests/test_marketplace_drama_geometry.py b/backend/tests/test_marketplace_drama_geometry.py
new file mode 100644
index 0000000..edd7f93
--- /dev/null
+++ b/backend/tests/test_marketplace_drama_geometry.py
@@ -0,0 +1,44 @@
+"""验证显示画幅,不把编码尺寸、旋转和非方形像素混为一谈。"""
+from fractions import Fraction
+
+import pytest
+
+from app.marketplace.drama_geometry import display_dimensions, display_ratio, fit_dimensions, validate_aspects
+
+
+def _info(width, height, sar="1:1", rotation=0):
+ """构造 FFprobe 的几何相关字段。"""
+ return {"width": width, "height": height,
+ "video": {"sample_aspect_ratio": sar, "side_data_list": [{"rotation": rotation}]}}
+
+
[email protected]("rotation,dimensions,ratio", [
+ (0, (768, 576), Fraction(4, 3)), (90, (576, 768), Fraction(3, 4)),
+ (-90, (576, 768), Fraction(3, 4)), (180, (768, 576), Fraction(4, 3)),
+])
+def test_sar_is_applied_before_rotation(rotation, dimensions, ratio):
+ info = _info(720, 576, "16:15", rotation)
+ assert display_dimensions(info) == dimensions
+ assert display_ratio(info) == ratio
+ assert fit_dimensions(info, *dimensions) == dimensions
+
+
+def test_small_pixel_rounding_and_same_ratio_different_sizes_are_allowed():
+ infos = [_info(1920, 1080), _info(1280, 720), _info(854, 480)]
+ assert validate_aspects(infos, [{"id": i} for i in (10, 11, 12)]) == [(1920, 1080), (1280, 720), (854, 480)]
+
+
+def test_equivalent_sar_and_rotation_are_allowed():
+ infos = [_info(720, 576, "16:15", 90), _info(576, 768)]
+ assert validate_aspects(infos, [{"id": 10}, {"id": 11}]) == [(576, 768), (576, 768)]
+
+
+def test_unsupported_rotation_does_not_silently_become_portrait():
+ with pytest.raises(ValueError, match="MARKETPLACE_SOURCE_INCOMPATIBLE:分镜旋转角度不受支持"):
+ display_ratio(_info(1920, 1080, rotation=45))
+
+
+def test_subunit_sar_expands_height_without_lowering_source_resolution():
+ info = _info(720, 480, "8:9", 90)
+ assert display_dimensions(info) == (540, 720)
+ assert display_ratio(info) == Fraction(3, 4)
diff --git a/backend/tests/test_marketplace_drama_media.py b/backend/tests/test_marketplace_drama_media.py
index 6fd5dc3..4605215 100644
--- a/backend/tests/test_marketplace_drama_media.py
+++ b/backend/tests/test_marketplace_drama_media.py
@@ -110,7 +110,8 @@ async def test_source_change_is_rejected_before_upload(local_media):
assert not list(cache.iterdir())
-async def _clip(settings, path, color, size="160x90", duration=0.6, audio=False):
+async def _clip(settings, path, color, size="160x90", duration=0.6, audio=False, sar="1:1"):
+ """生成用于真实 FFmpeg 拼接回归的短分镜。"""
if not Path(settings.ffmpeg_path).is_file() and not shutil.which(settings.ffmpeg_path):
pytest.skip("FFmpeg is not available")
args = [settings.ffmpeg_path, "-y", "-v", "error", "-f", "lavfi", "-i", f"color=c={color}:s={size}:r=10:d={duration}"]
@@ -118,7 +119,7 @@ async def _clip(settings, path, color, size="160x90", duration=0.6, audio=False)
args += ["-f", "lavfi", "-i", f"sine=frequency=1000:sample_rate=48000:duration={duration}", "-c:a", "aac", "-ar", "48000", "-ac", "2"]
else:
args += ["-an"]
- await media.command(*args, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-r", "10", "-g", "10", "-crf", "18",
+ await media.command(*args, "-vf", f"setsar={sar.replace(':', '/')}", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-r", "10", "-g", "10", "-crf", "18",
"-video_track_timescale", "90000", "-t", str(duration), str(path), timeout=30)
@@ -203,12 +204,68 @@ async def test_different_aspect_ratios_fail_without_upload(local_media):
paths = [static / "portrait.mp4", static / "landscape.mp4"]
await _clip(settings, paths[0], "red", size="90x160")
await _clip(settings, paths[1], "blue", size="160x90")
- with pytest.raises(ValueError, match="MARKETPLACE_SOURCE_INCOMPATIBLE"):
+ with pytest.raises(ValueError, match="MARKETPLACE_SOURCE_INCOMPATIBLE") as error:
await media.prepare_drama_video(_snapshot(static, paths), "marketplace/test/invalid.mp4")
+ assert "第1镜(分镜编号1,90×160,显示9:16)" in str(error.value)
+ assert "第2镜(分镜编号2,160×90,显示16:9)" in str(error.value)
assert not uploaded.exists()
assert not list(cache.iterdir())
[email protected]("rotation", [0, 90])
+async def test_sar_sources_keep_display_aspect_without_extra_borders(local_media, rotation):
+ """真实编码验证:等效画幅可合成,非方形像素不会被压窄或额外补黑边。"""
+ static, cache, uploaded, settings = local_media
+ source = static / "sar.mp4"
+ await _clip(settings, source, "red", size="180x144", sar="16:15")
+ if rotation:
+ rotated = static / "rotated.mp4"
+ await media.command(settings.ffmpeg_path, "-y", "-v", "error", "-display_rotation", str(rotation),
+ "-i", str(source), "-c", "copy", str(rotated), timeout=30)
+ source = rotated
+ peer = static / "peer.mp4"
+ dimensions = (144, 192) if rotation else (192, 144)
+ await _clip(settings, peer, "blue", size=f"{dimensions[0]}x{dimensions[1]}")
+ before = media.fingerprint(source)
+ await media.prepare_drama_video(_snapshot(static, [source, peer]), "marketplace/test/sar-full.mp4")
+ output = await media._probe(uploaded)
+ assert media._dimensions(output) == dimensions
+ assert output["video"]["sample_aspect_ratio"] == "1:1"
+ raw = await media.command(settings.ffmpeg_path, "-v", "error", "-ss", "0.2", "-i", str(uploaded),
+ "-vf", "crop=2:2:0:0,scale=1:1", "-frames:v", "1", "-pix_fmt", "rgb24", "-f", "rawvideo", "-", timeout=30)
+ assert raw[0] > 180 and raw[1] < 60 and raw[2] < 60
+ assert media.fingerprint(source) == before
+ assert not list(cache.iterdir())
+
+
+async def test_project_video_cover_extracts_first_frame_and_normalizes_display_shape(local_media, monkeypatch, tmp_path):
+ """项目卡片以视频首帧展示时,生成相同画幅的独立 PNG,不返回源视频充当图片。"""
+ static, cache, _uploaded, settings = local_media
+ source = static / "cover-video.mp4"
+ await _clip(settings, source, "blue", size="180x144", sar="16:15")
+ captured = tmp_path / "cover.png"
+ def upload(key, path, content_type):
+ assert key == "marketplace/test/cover.png" and content_type == "image/png"
+ assert cache in path.parents
+ shutil.copyfile(path, captured)
+ monkeypatch.setattr(media.storage, "upload", upload)
+ # 模拟视频大于图片上传上限;来源仍按视频上限检查,输出按图片上限检查。
+ original_limits = media.get_marketplace_settings()
+ limits = original_limits.model_copy(update={"max_document_bytes": 1000})
+ monkeypatch.setattr(media, "get_marketplace_settings", lambda: limits)
+ assert source.stat().st_size > limits.max_document_bytes
+ before = media.fingerprint(source)
+ result = await media.prepare_drama_cover("/static/cover-video.mp4", "marketplace/test/cover.png")
+ assert (result["width"], result["height"]) == (192, 144)
+ assert result["fingerprint"] == media.fingerprint(captured)
+ pixel = await _pixel(settings, captured, 0)
+ assert pixel[2] > 180 and pixel[0] < 60 and pixel[1] < 60
+ assert media.fingerprint(source) == before
+ assert not list(cache.iterdir())
+
+
@pytest.mark.asyncio
async def test_cover_uses_private_copy_and_validates_image(local_media, monkeypatch):
static, cache, _uploaded, settings = local_media
diff --git a/backend/tests/test_marketplace_drama_publish.py b/backend/tests/test_marketplace_drama_publish.py
index ce49aa6..845f97a 100644
--- a/backend/tests/test_marketplace_drama_publish.py
+++ b/backend/tests/test_marketplace_drama_publish.py
@@ -253,6 +253,164 @@ async def test_atomic_publish_is_idempotent_orders_all_clips_and_keeps_upstream(
assert conflict.status_code == 409
+async def test_snapshots_keep_project_card_cover_and_episode_cover_distinct(drama_publish_ctx):
+ """选择第二集时保留该集图片,系列封面仍与项目卡片的第一集一致。"""
+ ctx = drama_publish_ctx
+ project, episodes, clips = await source(ctx, episodes=2)
+ snapshot = await drama_publish.episode_snapshot(ctx.db, ctx.owner.id, project.id, episodes[1].id)
+ assert snapshot["cover_locator"] == "/static/test/cover-2.png"
+ assert snapshot["project_cover_locator"] == "/static/test/cover-1.png"
+ assert snapshot["project_cover_stamp"]["locator"] == snapshot["project_cover_locator"]
+ # 没有独立图片的分镜在项目卡片上显示视频首帧;市场保存同一受控来源。
+ for clip in clips:
+ clip.cover = ""
+ await ctx.db.commit()
+ snapshot = await drama_publish.episode_snapshot(ctx.db, ctx.owner.id, project.id, episodes[1].id)
+ assert snapshot["project_cover_locator"] == "/static/test/episode-1-shot-0.mp4"
+ assert snapshot["cover_locator"] == snapshot["project_cover_locator"]
+
+
[email protected]("case", ["new_series", "existing_series", "series_edited", "episode_cover_selected"])
+async def test_project_cover_binding_only_fills_unchanged_new_series(drama_publish_ctx, case):
+ """异步回填带入新系列封面,保留现有系列、用户编辑及分集自选封面。"""
+ ctx = drama_publish_ctx
+ project, episodes, _ = await source(ctx)
+ series = None
+ if case == "existing_series":
+ series = Series(owner_id=ctx.owner.id, title="已有系列")
+ ctx.db.add(series)
+ await ctx.db.commit()
+ response = await post_publish(ctx, project, await publish_payload(ctx, project, episodes, series=series))
+ assert response.status_code == 200, response.text
+ result = response.json()
+ series = await ctx.db.get(Series, result["series_id"])
+ target = await ctx.db.get(SeriesEpisode, result["items"][0]["id"])
+ task = await ctx.db.get(Handoff, result["handoffs"][0]["id"])
+ video = Asset(owner_id=ctx.owner.id, kind="video", filename="video.mp4", content_type="video/mp4", size_bytes=100,
+ object_key="marketplace/video.mp4", status="ready")
+ cover = Asset(owner_id=ctx.owner.id, kind="image", filename="cover.png", content_type="image/png", size_bytes=10,
+ object_key="marketplace/cover.png", status="ready")
+ own_cover = Asset(owner_id=ctx.owner.id, kind="image", filename="chosen.png", content_type="image/png", size_bytes=10,
+ object_key="marketplace/chosen.png", status="ready")
+ ctx.db.add_all([video, cover, own_cover])
+ await ctx.db.flush()
+ if case == "series_edited":
+ # 包括用户明确移除封面的情形;旧任务不能重新填回。
+ series.version += 1
+ elif case == "episode_cover_selected":
+ target.cover_asset_id = own_cover.id
+ series.cover_asset_id = own_cover.id
+ task.asset_id = video.id
+ await handoff._bind(ctx.db, task, video.id, cover.id, cover.id)
+ assert target.cover_asset_id == (own_cover.id if case == "episode_cover_selected" else cover.id)
+ expected = cover.id if case == "new_series" else own_cover.id if case == "episode_cover_selected" else None
+ assert series.cover_asset_id == expected
+
+
+async def test_worker_copies_project_and_episode_covers_to_independent_market_assets(drama_publish_ctx, monkeypatch):
+ """从第二集发布时,项目封面和分集封面都经私有市场存储再独立绑定。"""
+ ctx = drama_publish_ctx
+ project, episodes, _ = await source(ctx, episodes=2)
+ response = await post_publish(ctx, project, await publish_payload(ctx, project, [episodes[1]]))
+ assert response.status_code == 200, response.text
+ body = response.json()
+ series = await ctx.db.get(Series, body["series_id"])
+ target = await ctx.db.get(SeriesEpisode, body["items"][0]["id"])
+ copies = []
+
+ @asynccontextmanager
+ async def sessions():
+ yield ctx.db
+
+ async def prepare_video(snapshot, destination, on_phase):
+ return {"size_bytes": 100, "content_type": "video/mp4", "fingerprint": "f" * 64, "duration_seconds": 9.0}
+
+ async def prepare_cover(locator, destination, stamp):
+ assert stamp["locator"] == locator
+ copies.append((locator, destination))
+ return {"size_bytes": 10, "content_type": "image/png"}
+
+ monkeypatch.setattr(handoff, "AsyncSessionLocal", sessions)
+ monkeypatch.setattr(drama_media, "prepare_drama_video", prepare_video)
+ monkeypatch.setattr(drama_media, "prepare_drama_cover", prepare_cover)
+ monkeypatch.setattr(storage, "discard_generated", lambda key: None)
+ assert await handoff.run_handoff_once() is True
+ assert [locator for locator, _ in copies] == ["/static/test/cover-2.png", "/static/test/cover-1.png"]
+ assert series.cover_asset_id != target.cover_asset_id
+ assert (await ctx.db.get(Asset, target.cover_asset_id)).object_key == copies[0][1]
+ assert (await ctx.db.get(Asset, series.cover_asset_id)).object_key == copies[1][1]
+ assert all(key.startswith("marketplace/series/") for _, key in copies)
+
+
[email protected]("case", ["episode_existing_shared", "both_existing_shared", "episode_existing_distinct", "series_existing_distinct"])
+async def test_worker_creates_only_attached_cover_assets_and_discards_unused_objects(drama_publish_ctx, monkeypatch, case):
+ """已有封面不产生孤立 Asset;共用对象仍可只挂给缺封面的新系列。"""
+ ctx = drama_publish_ctx
+ project, episodes, _ = await source(ctx, episodes=2 if case.endswith("distinct") else 1)
+ response = await post_publish(ctx, project, await publish_payload(ctx, project, [episodes[-1]]))
+ body = response.json()
+ series = await ctx.db.get(Series, body["series_id"])
+ episode = await ctx.db.get(SeriesEpisode, body["items"][0]["id"])
+ own = Asset(owner_id=ctx.owner.id, kind="image", filename="chosen.png", content_type="image/png", size_bytes=10,
+ object_key="marketplace/already-chosen.png", status="ready")
+ ctx.db.add(own)
+ await ctx.db.flush()
+ if case.startswith(("episode_", "both_")):
+ episode.cover_asset_id = own.id
+ if case.startswith(("series_", "both_")):
+ series.cover_asset_id = own.id
+ await ctx.db.commit()
+ produced, discarded = [], []
+
+ @asynccontextmanager
+ async def sessions():
+ yield ctx.db
+
+ async def prepare_video(snapshot, destination, on_phase):
+ return {"size_bytes": 100, "content_type": "video/mp4", "fingerprint": "f" * 64, "duration_seconds": 9.0}
+
+ async def prepare_cover(locator, destination, stamp):
+ produced.append(destination)
+ return {"size_bytes": 10, "content_type": "image/png"}
+
+ monkeypatch.setattr(handoff, "AsyncSessionLocal", sessions)
+ monkeypatch.setattr(drama_media, "prepare_drama_video", prepare_video)
+ monkeypatch.setattr(drama_media, "prepare_drama_cover", prepare_cover)
+ monkeypatch.setattr(storage, "discard_generated", discarded.append)
+ assert await handoff.run_handoff_once() is True
+ covers = list((await ctx.db.execute(select(Asset).where(Asset.kind == "image"))).scalars().all())
+ assert {cover.id for cover in covers} == {episode.cover_asset_id, series.cover_asset_id}
+ assert set(discarded) == set(produced) - {cover.object_key for cover in covers}
+ if case.startswith(("episode_", "both_")):
+ assert episode.cover_asset_id == own.id
+ if case.startswith(("series_", "both_")):
+ assert series.cover_asset_id == own.id
+ if case == "episode_existing_shared":
+ assert series.cover_asset_id != own.id and len(covers) == 2 and discarded == []
+
+
+async def test_snapshot_reuses_only_its_own_frozen_video_stamp_for_cover(drama_publish_ctx, monkeypatch):
+ """同一快照用视频首帧作封面时只算一次指纹,下一次快照仍重新校验源文件。"""
+ ctx = drama_publish_ctx
+ project, episodes, clips = await source(ctx)
+ for clip in clips:
+ clip.cover = ""
+ await ctx.db.commit()
+ calls = []
+ original = drama_media.source_stamp
+
+ def counted(locator):
+ calls.append(locator)
+ return original(locator)
+
+ monkeypatch.setattr(drama_media, "source_stamp", counted)
+ first = await drama_publish.episode_snapshot(ctx.db, ctx.owner.id, project.id, episodes[0].id)
+ assert len(calls) == 3 and len(set(calls)) == 3
+ ctx.source_revision += 1
+ second = await drama_publish.episode_snapshot(ctx.db, ctx.owner.id, project.id, episodes[0].id)
+ assert len(calls) == 6 and first["source_version"] != second["source_version"]
+
+
async def test_same_source_version_in_same_target_reuses_episode_across_batches(drama_publish_ctx):
ctx = drama_publish_ctx
existing = await published(ctx)
@@ -350,6 +508,70 @@ async def test_source_file_change_is_detected_before_worker_binding(drama_publis
assert existing.target.asset_id is None
+def legacy_v2_snapshot(task):
+ """构造升级前真实的完整分集协议,用原算法冻结版本以验证向后兼容。"""
+ frozen = {key: value for key, value in task.source_snapshot.items() if key not in (
+ "project_cover_locator", "project_cover_stamp", "inherit_series_cover", "series_cover_version")}
+ if not any(clip["cover"] for clip in frozen["clips"]):
+ frozen["cover_locator"], frozen["cover_stamp"] = "", None
+ frozen["source_version"] = drama_publish.digest({"episode": frozen["drama_episode_id"], "title": frozen["title"],
+ "episode_number": frozen["episode_number"], "updated_at": frozen["episode_updated_at"],
+ "cover_stamp": drama_media.stamp_version(frozen["cover_stamp"]) if frozen["cover_stamp"] else None,
+ "clips": [{"id": clip["id"], "sort_order": clip["sort_order"], "updated_at": clip["updated_at"],
+ "stamp": drama_media.stamp_version(clip["stamp"]), "cover": clip["cover"]} for clip in frozen["clips"]]})
+ return frozen
+
+
[email protected]("with_images", [True, False])
+async def test_legacy_complete_episode_task_remains_retryable_and_reusable(drama_publish_ctx, with_images):
+ """升级前的 schema2 完整任务不会仅因新增封面字段就被误判源视频更新。"""
+ ctx = drama_publish_ctx
+ project, episodes, clips = await source(ctx)
+ if not with_images:
+ for clip in clips:
+ clip.cover = ""
+ await ctx.db.commit()
+ response = await post_publish(ctx, project, await publish_payload(ctx, project, episodes))
+ result = response.json()
+ task = await ctx.db.get(Handoff, result["handoffs"][0]["id"])
+ series = await ctx.db.get(Series, result["series_id"])
+ task.source_snapshot = legacy_v2_snapshot(task)
+ task.source_version = task.source_snapshot["source_version"]
+ original_version = task.source_version
+ task.status, task.error = "failed", "复制成片失败,请稍后重试"
+ await ctx.db.commit()
+ await handoff._validate_drama_source(ctx.db, task)
+ retry = await ctx.client.post(f"/api/marketplace/handoffs/{task.id}/retry")
+ assert retry.status_code == 200, retry.text
+ assert retry.json()["status"] == "pending"
+ context = (await ctx.client.get(f"/api/marketplace/printfilm/dramas/{project.id}/publish-context")).json()
+ mapping = next(item for item in context["series"] if item["id"] == series.id)["imports"][0]
+ assert mapping["source_version"] == context["episodes"][0]["source_version"]
+ assert mapping["requires_update"] is False
+ repeated = await post_publish(ctx, project, await publish_payload(ctx, project, episodes, series=series))
+ assert repeated.status_code == 200, repeated.text
+ assert repeated.json()["handoffs"][0]["id"] == task.id
+ assert task.source_version == original_version and "project_cover_stamp" not in task.source_snapshot
+ assert await ctx.db.scalar(select(func.count()).select_from(Handoff)) == 1
+
+
[email protected]("changed", ["video_file", "cover_locator"])
+async def test_legacy_complete_episode_still_rejects_actual_source_changes(drama_publish_ctx, changed):
+ """旧协议兼容不跳过分镜视频文件身份及原有图片封面的真实变化。"""
+ ctx = drama_publish_ctx
+ existing = await published(ctx)
+ existing.task.source_snapshot = legacy_v2_snapshot(existing.task)
+ existing.task.source_version = existing.task.source_snapshot["source_version"]
+ await ctx.db.commit()
+ if changed == "video_file":
+ ctx.source_revision += 1
+ else:
+ existing.clips[-1].cover = "/static/test/replaced-cover.png"
+ await ctx.db.commit()
+ with pytest.raises(HTTPException, match="MARKETPLACE_SOURCE_CHANGED"):
+ await handoff._validate_drama_source(ctx.db, existing.task)
+
+
async def test_terminal_same_source_can_be_explicitly_resynced(drama_publish_ctx):
"""源恢复原状后仍能重新确认,不永远复用终止的旧任务。"""
ctx = drama_publish_ctx
@@ -420,6 +642,7 @@ async def test_worker_recovery_and_final_binding_guards(drama_publish_ctx, monke
assert existing.task.status == "ready" and existing.target.asset_id is not None
assert existing.task.lease_token is None and existing.task.lease_until is None
assert existing.target.cover_asset_id is not None
+ assert existing.series.cover_asset_id == existing.target.cover_asset_id
assert await ctx.db.scalar(select(func.count()).select_from(Asset)) == 2
assert discarded == []
else:
diff --git a/docs/MARKETPLACE.md b/docs/MARKETPLACE.md
index 50808b5..6706c40 100644
--- a/docs/MARKETPLACE.md
+++ b/docs/MARKETPLACE.md
@@ -211,14 +211,14 @@ cd C:\code\printfilm\backend
### 漫剧完整分集直接发布(2026-10-24)
-漫剧列表卡片菜单「发布到数字资产市场」、分集编辑页和市场编辑页使用同一个发布弹窗。选择当前项目的完整分集,新建或选择本人市场系列后同步并进入 `/marketplace/series/{id}/edit`。新系列带入项目名称和简介;已有系列保留介绍、封面及收费配置,按原集数排序后从下一集接续编号。没有可用封面时需补充上传。
+漫剧列表卡片菜单「发布到数字资产市场」、分集编辑页和市场编辑页使用同一个发布弹窗。选择当前项目的完整分集,新建或选择本人市场系列后同步并进入 `/marketplace/series/{id}/edit`。新系列带入项目名称、简介和项目卡片封面;已有系列保留介绍、封面及收费配置,按原集数排序后从下一集接续编号。分集优先使用自身封面,缺失时使用项目卡片封面;项目卡片使用视频时提取首帧。封面保存为市场独立副本,不覆盖用户随后选择的封面,没有可用来源时提示补充上传。
- `GET /api/marketplace/printfilm/dramas/{project_id}/publish-context`:完整度、不可发布原因、源版本、本人目标系列和既有同步关系,不返回来源地址或对象键。
- `POST /api/marketplace/printfilm/dramas/{project_id}/publish`:提交选中编号、源版本、新建/已有目标、明确确认的更新及幂等键。独立 `marketplace_drama_publish_batches` 记录原子批次;同一账号的同一幂等键不能创建第二个系列。旧的分集导入 URL 也使用相同的整集逻辑。
- 原漫剧仅供读取。缺失任一分镜、视频生成或重新分镜尚未结束、跨账号选择均阻止发布。按 `(sort_order,id)` 冻结完整分镜清单、源文件指纹/ETag、标题、封面及源集号;不再把最后一个分镜当整集。
- 团队漫剧来源仍限原创建者导入,并在每次请求实时校验团队成员资格;已离队的旧创建者无法导入,也不会在来源列表中看到该项目。
-- 使用原有市场 Worker 及看门狗,不增加进程。阶段为排队、同步素材、拼接整集、校验、就绪/失败;兼容编码优先无损封装,不兼容时按最高来源画幅使用高质量编码,比例不一致直接阻断。非公开临时目录只作缓存,视频写入私有 OSS `marketplace/series/` 并校验后才绑定。
-- 同步期间可以填写表单,保存与提交暂时禁用;失败提供原因和重试,源变化或目标冲突要求重新选择并确认。租约丢失会取消处理;过期租约由同一个 Worker 恢复。源或目标已变化的旧任务不能回填新结果,未成功前保留旧资产。
+- 使用原有市场 Worker 及看门狗,不增加进程。阶段为排队、同步素材、拼接整集、校验、就绪/失败;兼容编码优先无损封装,不兼容时按最高来源画幅使用高质量编码。显示画幅先计算像素宽高比,再应用旋转;相同比例的不同分辨率可以合成,真实横竖画幅不一致时提示具体镜号、尺寸,要求先统一画幅,不自动裁切或拉伸。非公开临时目录只作缓存,视频写入私有 OSS `marketplace/series/` 并校验后才绑定。
+- 同步期间可以填写表单,保存与提交暂时禁用;失败提供原因和重试,源变化或目标冲突要求重新选择并确认。旧画幅失败任务需重新选择分集、确认来源后再次同步,不自动替换历史发布版本。租约丢失会取消处理;过期租约由同一个 Worker 恢复。源或目标已变化的旧任务不能回填新结果,未成功前保留旧资产。
- PrintFilm 分集统一引用账号当前有效授权函,可先同步及保存草稿,再签署一次并提交。自动关联只表示材料齐备;内容和版权仍由管理员一起审核,不自动批准。
- 明确更新使系列退回草稿并关闭所有历史发布版本的新销售;旧发布快照、HLS、价格及永久权益保留。已有买家通过 `GET /api/marketplace/platform/publications/{publication_id}/playback` 播放购买时版本,每次仍鉴权并检查封禁/权属限制。在途有效付款回调按冻结版本与金额确认,不因作者编辑或下架丢失权益。分成在提交时按单集、系列、后台默认优先顺序冻结。
diff --git a/frontend/src/features/marketplace/SeriesEditor.tsx b/frontend/src/features/marketplace/SeriesEditor.tsx
index 01201fc..f279ec8 100644
--- a/frontend/src/features/marketplace/SeriesEditor.tsx
+++ b/frontend/src/features/marketplace/SeriesEditor.tsx
@@ -9,7 +9,7 @@ import { useCategories } from './useCategories'
import { dialog } from '../../lib/dialog'
import AuthorizationPanel from './AuthorizationPanel'
import DramaPublishModal from './DramaPublishModal'
-import { handoffLabel, isHandoffActive, latestEpisodeHandoffs, mergeSyncedEpisodes } from './dramaPublishing'
+import { handoffLabel, isHandoffActive, latestEpisodeHandoffs, mergeSyncedCover, mergeSyncedEpisodes } from './dramaPublishing'
import { isFreeEpisode, previewStatusLabel } from './playbackPolicy'
import { explainMarketplaceError } from './messages'
@@ -61,6 +61,8 @@ export default function SeriesEditor() {
const [message, setMessage] = useState('')
const [previewPollError, setPreviewPollError] = useState('')
const savedEpisodes = useRef<EpisodeDraft[]>([])
+ const savedCoverId = useRef<number | null>(null)
+ const coverEdited = useRef(false)
const [poll, setPoll] = useState(0)
const [busy, setBusy] = useState(false); const [error, setError] = useState('')
const [expanded, setExpanded] = useState<Set<number>>(() => new Set([0]))
@@ -72,10 +74,17 @@ export default function SeriesEditor() {
const previewFailed = Boolean(series?.episodes.some(episode => !isFreeEpisode(series, episode.episode_no) && episode.preview_status === 'failed'))
function acceptSaved(value: SeriesDraft) {
setSeries(value); setSaleType(value.sale_type); setFreeEpisodeCount(value.free_episode_count || 0); setCategory(value.category || '其他'); setCoverId(value.cover_asset_id ?? null)
+ savedCoverId.current = value.cover_asset_id ?? null; coverEdited.current = false
const normalized = value.episodes.map(item => ({ ...item, asset_id: item.asset_id ?? null, cover_asset_id: item.cover_asset_id ?? null }))
setEpisodes(normalized); savedEpisodes.current = normalized; setRemovedEpisodeIds([]); setDirty(false)
if (value.pending_handoffs) setHandoffs(current => [...value.pending_handoffs!, ...current.filter(item => !value.pending_handoffs!.some(pending => pending.id === item.id))])
}
+ // 同步封面以已加载的远端值为基线,避免保存草稿时把后台刚回填的封面清空。
+ function acceptSyncedCover(value: SeriesDraft) {
+ const previous = savedCoverId.current, remote = value.cover_asset_id ?? null, edited = coverEdited.current
+ setCoverId(current => mergeSyncedCover(current, remote, previous, edited))
+ savedCoverId.current = remote
+ }
useEffect(() => {
if (!id) { setEpisodes([{ episode_no: 1, title: '第1集', asset_id: null, cover_asset_id: null, copyright_price_fen: 0, unlock_price_fen: 0 }]); return }
let active = true
@@ -120,8 +129,9 @@ export default function SeriesEditor() {
const previous = savedEpisodes.current
setEpisodes(current => mergeSyncedEpisodes(current, fresh.episodes, previous))
savedEpisodes.current = fresh.episodes
- // Worker 也会推进父系列版本;仅合并状态,保留用户正在填写的标题、价格与封面。
- setSeries(current => current ? { ...current, version: fresh.version, audit_status: fresh.audit_status, listed: fresh.listed, authorization_ready: fresh.authorization_ready, sync_in_progress: fresh.sync_in_progress } : fresh)
+ acceptSyncedCover(fresh)
+ // Worker 也会推进父系列版本和封面;表单仍保留用户正在填写的内容。
+ setSeries(current => current ? { ...current, cover_asset_id: fresh.cover_asset_id, version: fresh.version, audit_status: fresh.audit_status, listed: fresh.listed, authorization_ready: fresh.authorization_ready, sync_in_progress: fresh.sync_in_progress } : fresh)
}
if (activeSync) timer = window.setTimeout(() => setPoll(value => value + 1), 3000)
} catch { if (!stop) { setHandoffError('同步进度暂时无法读取,正在重试。当前填写的内容已保留。'); timer = window.setTimeout(() => setPoll(value => value + 1), 5000) } }
@@ -208,7 +218,7 @@ export default function SeriesEditor() {
const current = series
if (id && !series && !error) return <p role="status">正在加载系列…</p>
return <><PageHeading title={id ? '编辑短剧' : '发布短剧'} description="短剧和单条视频一样出现在作品广场。在这一页添加分集,版权规则与单视频相同。" back="/marketplace" /><div className="pf-market-editor-layout"><form className="pf-market-editor-main pf-market-form" onSubmit={save} onChangeCapture={event => { if (!(event.target as HTMLElement).closest('.pf-market-authorization, [data-market-transient]')) setDirty(true) }}>
- <FormSection step="01" title="系列信息" description="先建立系列,再逐集上传或导入成片。"><label>系列标题<span className="pf-req-mark">必填</span><input name="title" required maxLength={200} placeholder="例如:城市里的光" defaultValue={current?.title} /></label><label>简介<textarea name="description" maxLength={5000} defaultValue={current?.description} placeholder="介绍整部短剧的主题和内容" /></label><div className="pf-market-field-row"><label>分类<span className="pf-req-mark">必填</span><select name="category" required value={category || current?.category || ''} onChange={event => setCategory(event.target.value)} disabled={!categories.length}><option value="" disabled>请选择系列分类</option>{current?.category && !categories.includes(current.category) && <option value={current.category}>{current.category}(历史分类)</option>}{categories.map(name => <option key={name} value={name}>{name}</option>)}</select>{categoryError && <span role="alert">{categoryError}</span>}</label><label>标签<input name="tags" defaultValue={current?.tags?.join(',')} placeholder="都市,短剧" /></label></div><AssetPicker kind="image" value={coverId} onChange={value => { setCoverId(value); setDirty(true) }} title="系列封面(与分集封面至少上传一处)" /></FormSection>
+ <FormSection step="01" title="系列信息" description="先建立系列,再逐集上传或导入成片。"><label>系列标题<span className="pf-req-mark">必填</span><input name="title" required maxLength={200} placeholder="例如:城市里的光" defaultValue={current?.title} /></label><label>简介<textarea name="description" maxLength={5000} defaultValue={current?.description} placeholder="介绍整部短剧的主题和内容" /></label><div className="pf-market-field-row"><label>分类<span className="pf-req-mark">必填</span><select name="category" required value={category || current?.category || ''} onChange={event => setCategory(event.target.value)} disabled={!categories.length}><option value="" disabled>请选择系列分类</option>{current?.category && !categories.includes(current.category) && <option value={current.category}>{current.category}(历史分类)</option>}{categories.map(name => <option key={name} value={name}>{name}</option>)}</select>{categoryError && <span role="alert">{categoryError}</span>}</label><label>标签<input name="tags" defaultValue={current?.tags?.join(',')} placeholder="都市,短剧" /></label></div><AssetPicker kind="image" value={coverId} onChange={value => { coverEdited.current = true; setCoverId(value); setDirty(true) }} title="系列封面(与分集封面至少上传一处)" /></FormSection>
<FormSection step="02" title="收益方式" description="免费公开供完整观看;版权出售通过客服洽谈;平台投放按集解锁并分成。"><select value={saleType} onChange={event => setSaleType(event.target.value as typeof saleType)}><option value="free">免费公开</option><option value="copyright_contact">版权出售收益</option><option value="platform_unlock">平台投放收益</option></select><label>参考价(元)<input name="copyright_price" type="number" min="0" step="0.01" defaultValue={current?.copyright_price_fen ? current.copyright_price_fen / 100 : ''} /></label><label>免费集数<span className="pf-req-mark">前几集免费</span><input type="number" min="0" max="10000" step="1" value={freeEpisodeCount} onChange={event => setFreeEpisodeCount(Math.max(0, Number(event.target.value) || 0))} /></label><p className="pf-market-notice">选择“免费公开”时全部分集播放原片,无需试看;其他收益方式可将前几集设为免费,其余分集提供最长15秒且不超过原片30%的无水印短试看。版权合作参考价不代表已包含版权转让手续等额外费用,具体事项请与客服确认。平台投放按集定价,观众解锁仅获得永久在线播放权益,不包含版权转让;需在平台启用分成后才能提交审核。修改收益方式或免费集数后,将重新检查播放准备状态。</p></FormSection>
<FormSection step="03" title="分集内容" description="每集一个完整视频和封面。同步期间可以填写信息,完成后再保存。">
<div className="pf-episode-tools"><button type="button" onClick={() => setExpanded(new Set(episodes.map((_, index) => index)))}>展开全部</button><button type="button" onClick={() => setExpanded(new Set())}>收起全部</button><span>共 {episodes.length} 集</span></div>
@@ -260,7 +270,8 @@ export default function SeriesEditor() {
const previous = savedEpisodes.current
setEpisodes(current => [...mergeSyncedEpisodes(current, fresh.episodes, previous), ...fresh.episodes.filter(item => !current.some(local => local.id === item.id))])
savedEpisodes.current = fresh.episodes
- setSeries(current => current ? { ...current, version: fresh.version, audit_status: fresh.audit_status, listed: fresh.listed, sync_in_progress: fresh.sync_in_progress } : fresh)
+ acceptSyncedCover(fresh)
+ setSeries(current => current ? { ...current, cover_asset_id: fresh.cover_asset_id, version: fresh.version, audit_status: fresh.audit_status, listed: fresh.listed, authorization_ready: fresh.authorization_ready, sync_in_progress: fresh.sync_in_progress } : fresh)
setPoll(value => value + 1); setExpanded(new Set(fresh.episodes.map((_, index) => index))); setMessage('同步任务已创建,完成后会自动填入完整视频。当前填写的内容已保留。')
}).catch(err => setError((err as Error).message)).finally(() => setBusy(false))
}} />}
diff --git a/frontend/src/features/marketplace/dramaPublishing.ts b/frontend/src/features/marketplace/dramaPublishing.ts
index 1aa43f4..21a73c6 100644
--- a/frontend/src/features/marketplace/dramaPublishing.ts
+++ b/frontend/src/features/marketplace/dramaPublishing.ts
@@ -50,6 +50,10 @@ export function latestEpisodeHandoffs(items: Handoff[]) {
}
type SyncEpisode = { id?: number; version?: number; asset_id: number | null; cover_asset_id: number | null; source?: string }
+// 接纳后台同步的系列封面;用户选过或主动清空后,后续轮询不能覆盖本地意图。
+export function mergeSyncedCover(current: number | null, remote: number | null, previous: number | null, edited = false) {
+ return !edited && current === previous ? remote : current
+}
// 只回填同步产物和版本;封面被用户编辑过时保留本地选择,标题和价格始终保留。
export function mergeSyncedEpisodes<T extends SyncEpisode>(current: T[], remote: T[], previous: T[]) {
return current.map(episode => {
diff --git a/frontend/tests/dramaPublishing.test.mjs b/frontend/tests/dramaPublishing.test.mjs
index 33d9025..6426df7 100644
--- a/frontend/tests/dramaPublishing.test.mjs
+++ b/frontend/tests/dramaPublishing.test.mjs
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict'
import test from 'node:test'
-import { latestEpisodeHandoffs, mergeSyncedEpisodes, publishSelection, sourceRelation } from '../src/features/marketplace/dramaPublishing.ts'
+import { latestEpisodeHandoffs, mergeSyncedCover, mergeSyncedEpisodes, publishSelection, sourceRelation } from '../src/features/marketplace/dramaPublishing.ts'
const episode = (id, episode_number, source_version = 'v1') => ({ id, name: `第${episode_number}集`, episode_number, source_version, ready: true, fragment_count: 3, completed_count: 3 })
@@ -54,3 +54,18 @@ test('后台第二次回填仍保留用户选择的封面和手动视频,新
const remote = [{ ...previous[0], version: 4, asset_id: 50, cover_asset_id: 51 }]
assert.deepEqual(mergeSyncedEpisodes(current, remote, previous), [{ ...current[0], version: 4 }, current[1]])
})
+
+test('后台补齐系列封面后,当前表单接纳封面并持续跟随未编辑的远端值', () => {
+ const first = mergeSyncedCover(null, 31, null)
+ assert.equal(first, 31)
+ assert.equal(mergeSyncedCover(first, 32, 31), 32)
+ assert.equal(mergeSyncedCover(32, 32, 32), 32)
+})
+
+test('系列封面同步保留本地新选、主动清空和选择后清空的意图', () => {
+ assert.equal(mergeSyncedCover(42, 31, null, true), 42)
+ assert.equal(mergeSyncedCover(null, 32, 31, true), null)
+ // 初始封面为空,用户选择后再清空;即使值与旧基线相同也不能被轮询覆盖。
+ assert.equal(mergeSyncedCover(null, 31, null, true), null)
+ assert.equal(mergeSyncedCover(42, 31, null), 42)
+})