Skip to content

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

fix: 加固 Seedance 宽高比钳制(偶数字对齐 + 漫剧路径 + 失败上抛)

yi3958b3f75f6b
diff --git a/backend/app/services/ark.py b/backend/app/services/ark.py
index 76e4ffa..4cd4f01 100644
--- a/backend/app/services/ark.py
+++ b/backend/app/services/ark.py
@@ -1295,8 +1295,11 @@ class ArkGateway:
copy = dict(item)
if item.get("type") == "image_url":
raw_url = (item.get("image_url") or {}).get("url") or ""
+ from app.services.seedance_image_aspect import ensure_seedance_compatible_image_url
+
+ safe_url = await ensure_seedance_compatible_image_url(str(raw_url))
copy["image_url"] = {
- "url": await self._resolve_media_ref(str(raw_url), prefer_https=True)
+ "url": await self._resolve_media_ref(safe_url, prefer_https=True)
}
elif item.get("type") == "audio_url":
raw_url = (item.get("audio_url") or {}).get("url") or ""
diff --git a/backend/app/services/seedance_image_aspect.py b/backend/app/services/seedance_image_aspect.py
index c6d5e75..45726c4 100644
--- a/backend/app/services/seedance_image_aspect.py
+++ b/backend/app/services/seedance_image_aspect.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import asyncio
import logging
import math
import struct
@@ -37,15 +38,29 @@ def target_canvas_for_seedance_ar(
if ar_min <= ar <= ar_max:
return None
if ar > ar_max:
- canvas_h = max(h, int(math.ceil(w / ar_max)))
- canvas_w = w
+ canvas_w, canvas_h = w, max(h, int(math.ceil(w / ar_max)))
else:
- canvas_w = max(w, int(math.ceil(h * ar_min)))
- canvas_h = h
- if canvas_w % 2:
- canvas_w += 1
- if canvas_h % 2:
- canvas_h += 1
+ canvas_w, canvas_h = max(w, int(math.ceil(h * ar_min))), h
+ # 偶数字对齐后可能把 AR 推回 2.50/0.40 边界,循环微调直到落在安全区
+ for _ in range(16):
+ if canvas_w % 2:
+ canvas_w += 1
+ if canvas_h % 2:
+ canvas_h += 1
+ out_ar = canvas_w / canvas_h
+ if ar_min <= out_ar <= ar_max:
+ break
+ if out_ar > ar_max:
+ canvas_h += 2
+ else:
+ canvas_w += 2
+ else:
+ logger.warning(
+ "seedance ar: cannot stabilize canvas for %sx%s",
+ w,
+ h,
+ )
+ return None
if canvas_w == w and canvas_h == h:
return None
return canvas_w, canvas_h
@@ -105,33 +120,36 @@ def _webp_size(data: bytes) -> tuple[int, int] | None:
return None
+def _run_ffmpeg_pad(src: Path, dest: Path, cw: int, ch: int) -> None:
+ ffmpeg = _which("ffmpeg")
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ vf = f"pad={cw}:{ch}:(ow-iw)/2:(oh-ih)/2:black"
+ cmd = [ffmpeg, "-y", "-i", str(src), "-vf", vf, str(dest)]
+ proc = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
+ if proc.returncode != 0 or not dest.exists() or dest.stat().st_size <= 0:
+ raise RuntimeError(
+ f"seedance ar pad failed: {(proc.stderr or '')[-400:] or 'empty output'}"
+ )
+
+
# 本地图若超 Seedance 比例,FFmpeg 居中垫黑边写出新文件
def pad_image_to_seedance_ar(src: Path, dest: Path) -> Path | None:
- """需要钳制时写出 dest 并返回路径;无需改动或失败返回 None。"""
+ """需要钳制时写出 dest 并返回路径;无需改动返回 None;失败抛 RuntimeError。"""
dims = read_image_size(src)
if not dims:
- logger.warning("seedance ar: cannot read size path=%s", src)
- return None
+ raise RuntimeError(f"无法读取参考图尺寸:{src.name}")
canvas = target_canvas_for_seedance_ar(*dims)
if not canvas:
return None
cw, ch = canvas
- try:
- ffmpeg = _which("ffmpeg")
- except RuntimeError:
- logger.warning("seedance ar: ffmpeg missing, skip pad path=%s", src)
- return None
- dest.parent.mkdir(parents=True, exist_ok=True)
- vf = f"pad={cw}:{ch}:(ow-iw)/2:(oh-ih)/2:black"
- cmd = [ffmpeg, "-y", "-i", str(src), "-vf", vf, str(dest)]
- proc = subprocess.run(cmd, capture_output=True, text=True)
- if proc.returncode != 0 or not dest.exists() or dest.stat().st_size <= 0:
- logger.warning(
- "seedance ar pad failed src=%s stderr=%s",
- src,
- (proc.stderr or "")[-400:],
- )
- return None
+ _run_ffmpeg_pad(src, dest, cw, ch)
+ out_dims = read_image_size(dest)
+ if out_dims:
+ out_ar = out_dims[0] / out_dims[1]
+ if not (SEEDANCE_AR_SAFE_MIN <= out_ar <= SEEDANCE_AR_SAFE_MAX):
+ raise RuntimeError(
+ f"垫边后宽高比仍超限:{out_dims[0]}x{out_dims[1]} ar={out_ar:.4f}"
+ )
logger.info(
"seedance ar padded %sx%s -> %sx%s src=%s",
dims[0],
@@ -163,16 +181,22 @@ async def ensure_seedance_compatible_image_url(image_url: str) -> str:
local = work_dir / f"dl_{uuid.uuid4().hex[:12]}{suffix}"
try:
await storage.download_to(raw, local)
- except Exception: # noqa: BLE001
- logger.exception("seedance ar: download failed url=%s", raw[:160])
- return raw
+ except Exception as exc: # noqa: BLE001
+ raise RuntimeError(f"下载参考图失败,无法校验宽高比:{exc}") from exc
dims = read_image_size(local)
- if not dims or target_canvas_for_seedance_ar(*dims) is None:
+ if not dims:
+ # 读不出尺寸时不硬失败(SVG/少见格式),交给上游
+ logger.warning("seedance ar: cannot read size, pass-through path=%s", local)
+ return raw
+ if target_canvas_for_seedance_ar(*dims) is None:
return raw
out = local.parent / f"{local.stem}_ar{uuid.uuid4().hex[:8]}{local.suffix or '.png'}"
- padded = pad_image_to_seedance_ar(local, out)
+ try:
+ padded = await asyncio.to_thread(pad_image_to_seedance_ar, local, out)
+ except Exception as exc: # noqa: BLE001
+ raise RuntimeError(f"参考图宽高比超限且垫边失败:{exc}") from exc
if not padded:
return raw
diff --git a/backend/tests/test_seedance_image_aspect.py b/backend/tests/test_seedance_image_aspect.py
index 8d0a335..40bd0be 100644
--- a/backend/tests/test_seedance_image_aspect.py
+++ b/backend/tests/test_seedance_image_aspect.py
@@ -35,4 +35,13 @@ def test_target_canvas_boundary_exactly_2_5_gets_padded():
canvas = target_canvas_for_seedance_ar(2500, 1000)
assert canvas is not None
cw, ch = canvas
- assert cw / ch <= 2.49
+ assert 0.41 <= cw / ch <= 2.49
+
+
+def test_target_canvas_even_align_stays_safe():
+ # 偶数字对齐不得把 AR 推回 2.50
+ canvas = target_canvas_for_seedance_ar(249, 99)
+ assert canvas is not None
+ cw, ch = canvas
+ assert cw % 2 == 0 and ch % 2 == 0
+ assert 0.41 <= cw / ch <= 2.49