Skip to content

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

fix

增瑞 田cbf636507b17
diff --git a/backend/app/marketplace/drama_geometry.py b/backend/app/marketplace/drama_geometry.py
index 70fda5f..88a5281 100644
--- a/backend/app/marketplace/drama_geometry.py
+++ b/backend/app/marketplace/drama_geometry.py
@@ -4,6 +4,9 @@ from __future__ import annotations
from fractions import Fraction
import math
+# 模型返回的同画幅视频可能存在小幅尺寸偏差;最多接受整集 5% 的显示比例跨度。
+_MAX_ASPECT_SPREAD = Fraction(1, 20)
+
def _pixel_ratio(video: dict) -> Fraction:
"""缺失或无效的像素宽高比按方形像素解释。"""
@@ -48,18 +51,19 @@ def display_dimensions(info: dict) -> tuple[int, int]:
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)};请先统一画幅后发布")
+ low = min(range(len(ratios)), key=ratios.__getitem__)
+ high = max(range(len(ratios)), key=ratios.__getitem__)
+ if ratios[high] / ratios[low] - 1 > _MAX_ASPECT_SPREAD:
+ 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(low)}与{describe(high)};差异超过5%的自动补边范围,请先统一画幅后发布")
return [display_dimensions(info) for info in infos]
diff --git a/backend/app/marketplace/drama_media.py b/backend/app/marketplace/drama_media.py
index 0f656c0..0a70fa3 100644
--- a/backend/app/marketplace/drama_media.py
+++ b/backend/app/marketplace/drama_media.py
@@ -214,7 +214,7 @@ 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]
width = math.ceil(max(size[0] for size in sizes) / 2) * 2
height = math.ceil(max(size[1] for size in sizes) / 2) * 2
@@ -242,7 +242,7 @@ async def _encode(paths: list[Path], infos: list[dict], output: Path, timeout: f
args += ["-map", "0:a:0" if info["audio"] else "1:a:0", "-af",
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={fit_width}:{fit_height}:flags=lanczos,setsar=1,"
diff --git a/backend/tests/test_marketplace_drama_geometry.py b/backend/tests/test_marketplace_drama_geometry.py
index edd7f93..1479f47 100644
--- a/backend/tests/test_marketplace_drama_geometry.py
+++ b/backend/tests/test_marketplace_drama_geometry.py
@@ -28,6 +28,32 @@ def test_small_pixel_rounding_and_same_ratio_different_sizes_are_allowed():
assert validate_aspects(infos, [{"id": i} for i in (10, 11, 12)]) == [(1920, 1080), (1280, 720), (854, 480)]
[email protected]("rotation", [0, 90])
+def test_model_frame_size_variation_is_allowed_without_distortion(rotation):
+ """模型返回832或854宽时可等比补边,旋转后的同类竖屏也适用。"""
+ infos = [_info(832, 480, rotation=rotation), _info(854, 480, rotation=rotation)]
+ expected = [(480, 832), (480, 854)] if rotation else [(832, 480), (854, 480)]
+ sizes = validate_aspects(infos, [{"id": 18708}, {"id": 18711}])
+ assert sizes == expected
+ canvas = tuple(max(values) for values in zip(*sizes))
+ assert fit_dimensions(infos[0], *canvas) == expected[0]
+ assert fit_dimensions(infos[1], *canvas) == expected[1]
+
+
+def test_padding_limit_includes_five_percent_but_rejects_larger_difference():
+ infos = [_info(1600, 900), _info(1680, 900)]
+ assert validate_aspects(infos, [{"id": 10}, {"id": 11}]) == [(1600, 900), (1680, 900)]
+ with pytest.raises(ValueError, match="超过5%的自动补边范围"):
+ validate_aspects([infos[0], _info(1682, 900)], [{"id": 10}, {"id": 11}])
+
+
[email protected]("widths", [(880, 840, 920), (840, 920, 880), (920, 880, 840)])
+def test_total_aspect_spread_does_not_depend_on_which_shot_is_first(widths):
+ """中间尺寸不能掩盖首尾累计偏差,调整分镜顺序也不能绕过限制。"""
+ with pytest.raises(ValueError, match="MARKETPLACE_SOURCE_INCOMPATIBLE"):
+ validate_aspects([_info(width, 500) for width in widths], [{"id": i} for i in range(3)])
+
+
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)]
diff --git a/backend/tests/test_marketplace_drama_media.py b/backend/tests/test_marketplace_drama_media.py
index 4605215..28b9071 100644
--- a/backend/tests/test_marketplace_drama_media.py
+++ b/backend/tests/test_marketplace_drama_media.py
@@ -184,6 +184,54 @@ async def test_mixed_sizes_and_audio_use_highest_source_resolution(local_media):
assert not list(cache.iterdir())
+async def test_small_landscape_ratio_difference_pads_without_stretching_or_cropping(local_media):
+ """真实832/854宽度兼容:完整画面等比居中补边,镜序、时长及源文件不变。"""
+ static, cache, uploaded, settings = local_media
+ narrow, wide = static / "narrow.mp4", static / "wide.mp4"
+ # 图案和四边标记能检出拉伸或裁切,避免纯色测试误判画面保真。
+ pattern = (
+ "testsrc2=s=832x480:r=10:d=0.6,"
+ "drawbox=x=0:y=0:w=8:h=ih:color=yellow:t=fill,"
+ "drawbox=x=iw-8:y=0:w=8:h=ih:color=magenta:t=fill,"
+ "drawbox=x=0:y=0:w=iw:h=8:color=white:t=fill,"
+ "drawbox=x=0:y=ih-8:w=iw:h=8:color=cyan:t=fill"
+ )
+ await media.command(settings.ffmpeg_path, "-y", "-v", "error", "-f", "lavfi", "-i", pattern,
+ "-an", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-r", "10", "-g", "10", "-crf", "18",
+ "-video_track_timescale", "90000", str(narrow), timeout=30)
+ await _clip(settings, wide, "blue", size="854x480", duration=0.7)
+ originals = {path: media.fingerprint(path) for path in (narrow, wide)}
+
+ result = await media.prepare_drama_video(_snapshot(static, [narrow, wide]), "marketplace/test/padded.mp4")
+ info = await media._probe(uploaded)
+ assert (info["width"], info["height"]) == (854, 480)
+ assert info["video"]["sample_aspect_ratio"] == "1:1"
+ assert result["duration_seconds"] == pytest.approx(1.3, abs=0.15)
+
+ frames = []
+ for path in (narrow, uploaded):
+ frames.append(await media.command(settings.ffmpeg_path, "-v", "error", "-ss", "0.2", "-i", str(path),
+ "-frames:v", "1", "-pix_fmt", "rgb24", "-f", "rawvideo", "-", timeout=30))
+ original, composed = frames
+ assert len(original) == 832 * 480 * 3
+ assert len(composed) == 854 * 480 * 3
+ # 黑边左右差最多2px,兼容yuv420p对奇数居中坐标的色度对齐。
+ for x in (1, 852):
+ pixel = composed[(240 * 854 + x) * 3:(240 * 854 + x + 1) * 3]
+ assert max(pixel) < 20
+ errors = {}
+ for left in (10, 11, 12):
+ cropped = b"".join(composed[(row * 854 + left) * 3:(row * 854 + left + 832) * 3] for row in range(480))
+ errors[left] = sum(abs(a - b) for a, b in zip(original, cropped)) / len(original)
+ # 有效区与原始解码帧逐像素比对;仅允许高质量二次编码的小幅误差。
+ assert min(errors.values()) < 5, errors
+ blue = await _pixel(settings, uploaded, 0.9)
+ assert blue[2] > 180 and blue[0] < 60 and blue[1] < 60
+ assert {path: media.fingerprint(path) for path in (narrow, wide)} == originals
+ assert not list(cache.iterdir())
+
+
@pytest.mark.asyncio
async def test_single_clip_is_not_reencoded(local_media, monkeypatch):
static, _cache, uploaded, settings = local_media
@@ -212,6 +260,20 @@ async def test_different_aspect_ratios_fail_without_upload(local_media):
assert not list(cache.iterdir())
+async def test_four_by_three_and_widescreen_still_fail_without_upload(local_media):
+ """小偏差补边不能放行明显不同的4:3和16:9横屏画幅。"""
+ static, cache, uploaded, settings = local_media
+ paths = [static / "four-three.mp4", static / "widescreen.mp4"]
+ await _clip(settings, paths[0], "red", size="320x240")
+ await _clip(settings, paths[1], "blue", size="320x180")
+ with pytest.raises(ValueError, match="MARKETPLACE_SOURCE_INCOMPATIBLE") as error:
+ await media.prepare_drama_video(_snapshot(static, paths), "marketplace/test/incompatible.mp4")
+ assert "显示4:3" in str(error.value) and "显示16:9" in str(error.value)
+ assert not uploaded.exists()
+ assert not list(cache.iterdir())
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("rotation", [0, 90])
async def test_sar_sources_keep_display_aspect_without_extra_borders(local_media, rotation):
diff --git a/docs/MARKETPLACE.md b/docs/MARKETPLACE.md
index 6706c40..31ae2c7 100644
--- a/docs/MARKETPLACE.md
+++ b/docs/MARKETPLACE.md
@@ -217,7 +217,7 @@ cd C:\code\printfilm\backend
- `POST /api/marketplace/printfilm/dramas/{project_id}/publish`:提交选中编号、源版本、新建/已有目标、明确确认的更新及幂等键。独立 `marketplace_drama_publish_batches` 记录原子批次;同一账号的同一幂等键不能创建第二个系列。旧的分集导入 URL 也使用相同的整集逻辑。
- 原漫剧仅供读取。缺失任一分镜、视频生成或重新分镜尚未结束、跨账号选择均阻止发布。按 `(sort_order,id)` 冻结完整分镜清单、源文件指纹/ETag、标题、封面及源集号;不再把最后一个分镜当整集。
- 团队漫剧来源仍限原创建者导入,并在每次请求实时校验团队成员资格;已离队的旧创建者无法导入,也不会在来源列表中看到该项目。
-- 使用原有市场 Worker 及看门狗,不增加进程。阶段为排队、同步素材、拼接整集、校验、就绪/失败;兼容编码优先无损封装,不兼容时按最高来源画幅使用高质量编码。显示画幅先计算像素宽高比,再应用旋转;相同比例的不同分辨率可以合成,真实横竖画幅不一致时提示具体镜号、尺寸,要求先统一画幅,不自动裁切或拉伸。非公开临时目录只作缓存,视频写入私有 OSS `marketplace/series/` 并校验后才绑定。
+- 使用原有市场 Worker 及看门狗,不增加进程。阶段为排队、同步素材、拼接整集、校验、就绪/失败;兼容编码优先无损封装,不兼容时按最高来源画幅使用高质量编码。显示画幅先计算像素宽高比,再应用旋转;相同比例的不同分辨率可以合成。整集最大/最小显示比例之比减一不超过5%时,允许等比缩放并居中补边,例如832×480与854×480合成为854×480,不裁切、不拉伸、不降低源分辨率。超过范围(如16:9与4:3、横竖屏混用)仍提示具体镜号、尺寸,要求先统一画幅。非公开临时目录只作缓存,视频写入私有 OSS `marketplace/series/` 并校验后才绑定。
- 同步期间可以填写表单,保存与提交暂时禁用;失败提供原因和重试,源变化或目标冲突要求重新选择并确认。旧画幅失败任务需重新选择分集、确认来源后再次同步,不自动替换历史发布版本。租约丢失会取消处理;过期租约由同一个 Worker 恢复。源或目标已变化的旧任务不能回填新结果,未成功前保留旧资产。
- PrintFilm 分集统一引用账号当前有效授权函,可先同步及保存草稿,再签署一次并提交。自动关联只表示材料齐备;内容和版权仍由管理员一起审核,不自动批准。
- 明确更新使系列退回草稿并关闭所有历史发布版本的新销售;旧发布快照、HLS、价格及永久权益保留。已有买家通过 `GET /api/marketplace/platform/publications/{publication_id}/playback` 播放购买时版本,每次仍鉴权并检查封禁/权属限制。在途有效付款回调按冻结版本与金额确认,不因作者编辑或下架丢失权益。分成在提交时按单集、系列、后台默认优先顺序冻结。