nex_animation/backend/app/providers/mock.py

215 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""Mock 适配器:不依赖任何供应商即可跑通完整流水线(含配音)。
- 视频:以关键帧/定妆图为底图,按镜头运镜参数生成带真实运动的测试片段;无关键帧时生成色卡。
- 语音:按文本长度生成可播放的占位人声(WAV),用于验证字幕对齐与混音。
所有产物都是真实可播放的媒体文件,因此质检、时长对账、转场、混音逻辑都能被完整验证。
"""
from __future__ import annotations
import math
import random
import struct
import wave
from pathlib import Path
from app.config import settings
from app.providers.base import (FatalProviderError, RetryableProviderError, VideoGenRequest,
VideoGenResult, VoiceGenRequest, VoiceGenResult, VideoProviderAdapter,
VoiceProviderAdapter, Capabilities)
from app.services import ffmpeg as ff
_MOVE_MOTION = {
# crop 的 x/y 逐帧求值,因此平移/摇移类运镜可以直接用 t 做位移
"static": "x='(iw-{W})/2':y='(ih-{H})/2'",
"pan_left": "x='(iw-{W})*(0.9-0.6*t/{D})':y='(ih-{H})/2'",
"pan_right": "x='(iw-{W})*(0.1+0.6*t/{D})':y='(ih-{H})/2'",
"tilt_up": "x='(iw-{W})/2':y='(ih-{H})*(0.85-0.55*t/{D})'",
"tilt_down": "x='(iw-{W})/2':y='(ih-{H})*(0.15+0.55*t/{D})'",
"track": "x='(iw-{W})*(0.15+0.7*t/{D})':y='(ih-{H})*(0.5+0.12*sin(t))'",
"orbit": "x='(iw-{W})*(0.5+0.4*sin(t*0.9))':y='(ih-{H})*(0.5+0.25*cos(t*0.9))'",
"handheld": "x='(iw-{W})/2+8*sin(t*7.3)+5*sin(t*11.7)':y='(ih-{H})/2+6*cos(t*6.1)'",
"crane": "x='(iw-{W})/2':y='(ih-{H})*(0.1+0.7*t/{D})'",
}
# 推拉/变焦类运镜:crop 的 w/h 只在初始化求值一次(表达式里没有 t),
# 写成 w='iw/(1+0.04*t)' 会让整条滤镜链在 configure 阶段直接失败
# (Error when evaluating the expression),因此缩放统一交给 zoompan 逐帧推进。
_MOVE_ZOOM = {
"push_in": (1.00, 1.14, 0.0),
"zoom_in": (1.00, 1.20, 0.0),
"dolly_in": (1.02, 1.18, 0.03),
"pull_out": (1.34, 1.00, 0.0),
"zoom_out": (1.40, 1.00, 0.0),
"dolly_out": (1.36, 1.04, -0.03),
}
def _motion_filter(movement: str, width: int, height: int, duration: float, fps: int = 24) -> str:
"""按运镜生成滤镜链,产物必须是 width×height 且画面真的在动。"""
frames = max(1, int(round(duration * max(1, fps))))
zoom = _MOVE_ZOOM.get(movement)
if zoom:
z0, z1, drift = zoom
delta = (z1 - z0) / frames
sign = "-" if drift < 0 else "+"
big_w, big_h = width * 2 - (width * 2) % 2, height * 2 - (height * 2) % 2
# zoompan 的选项值里逗号是分隔符,表达式内的逗号必须转义成 \,
return (rf"scale=w={big_w}:h={big_h}:force_original_aspect_ratio=increase:force_divisible_by=2,"
rf"crop=w={big_w}:h={big_h}:x='(in_w-{big_w})/2':y='(in_h-{big_h})/2',"
rf"zoompan=z='min(max({z0:.4f}{delta:+.6f}*on\,{min(z0, z1):.4f})"
rf"\,{max(z0, z1):.4f})'"
rf":x='iw/2-(iw/zoom/2)'"
rf":y='max(0\,min(ih-(ih/zoom)\,ih/2-(ih/zoom/2){sign}"
rf"ih*{abs(drift):.3f}*on/{frames}))'"
rf":d=1:s={width}x{height}:fps={max(1, fps)}")
template = _MOVE_MOTION.get(movement, _MOVE_MOTION["static"])
expr = template.format(W=width, H=height, D=max(1.0, duration))
crop_args = expr if expr.startswith("w=") else f"w={width}:h={height}:" + expr
# 先放大 18%,保证裁切运动时画面不越界
return (f"scale=w={int(width * 1.18)}:h={int(height * 1.18)}:"
f"force_original_aspect_ratio=increase:force_divisible_by=2,"
f"crop={crop_args},crop=w={width}:h={height}:x='(in_w-{width})/2':y='(in_h-{height})/2'")
def _label_filter(label: str, height: int) -> str:
font = ff.find_font()
if not font or not ff.can_draw_text():
return ""
safe = label.replace("\\", "/").replace(":", "_").replace("'", "")[:80]
size = max(18, height // 22)
return (f",drawtext=fontfile='{font}':text='{safe}':x=28:y=28:fontsize={size}:"
f"fontcolor=white@0.9:box=1:boxcolor=black@0.35:boxborderw=12")
class MockVideoProvider(VideoProviderAdapter):
"""生成带运镜的测试片段,用于流水线自检。"""
_name = "mock"
@property
def name(self) -> str:
return self._name
def capabilities(self, config: dict | None = None) -> Capabilities:
return Capabilities(modes=("t2v", "i2v", "fl"), resolutions=("480p", "720p", "1080p", "4k"),
aspect_ratios=("16:9", "9:16", "1:1", "4:3", "3:4", "21:9"),
min_duration=1.0, max_duration=30.0, max_reference_images=4,
needs_public_media=False,
notes="测试用适配器:输出模拟运镜片段,不是真实 AI 视频")
def generate(self, request: VideoGenRequest, config: dict | None = None) -> VideoGenResult:
config = config or {}
if not ff.available():
raise FatalProviderError("本机缺少 ffmpeg/ffprobe,无法运行 mock 适配器")
failure_rate = float(config.get("failure_rate", 0.0))
if failure_rate > 0 and random.random() < failure_rate:
raise RetryableProviderError("mock 适配器按 failure_rate 注入的临时失败", code="mock_injected_failure")
out = Path(request.output_path or f"{settings.media_root}/mock/out.mp4")
out.parent.mkdir(parents=True, exist_ok=True)
from app.constants import canvas_for
width, height = canvas_for(request.resolution, request.aspect_ratio)
fps = max(1, int(request.fps or 24))
duration = max(0.4, min(float(request.duration_seconds), 30.0))
movement = str(request.params.get("camera_movement") or "static")
label = request.label or "MOCK SHOT"
base = None
if request.mode in ("i2v", "fl") and request.first_frame and Path(request.first_frame).exists():
base = request.first_frame
elif request.reference_images:
base = next((p for p in request.reference_images if Path(p).exists()), None)
chain = _motion_filter(movement, width, height, duration, fps) + _label_filter(f"{label} · MOCK", height)
chain += ",noise=alls=6:allf=t,format=yuv420p"
cmd = [ff.FFMPEG, "-v", "error", "-y"]
if base:
cmd += ["-loop", "1", "-i", str(base)]
else:
hue = int(abs(hash(request.prompt or label)) % 360)
cmd += ["-f", "lavfi", "-i", f"color=c=0x{20 + hue % 60:02x}{hue % 90:02x}{120 + hue % 100:02x}:s={width}x{height}:r={fps}"]
cmd += ["-t", f"{duration:.3f}", "-vf", chain, "-r", str(fps), "-an",
"-c:v", "libx264", "-preset", "veryfast", "-crf", "26", "-pix_fmt", "yuv420p", str(out)]
ff.run(cmd, timeout=900)
if not out.exists() or out.stat().st_size < 512:
raise RetryableProviderError("mock 适配器输出为空", code="empty_output")
probed = ff.probe(out)
return VideoGenResult(file_path=str(out), provider_job_id=f"mock-{abs(hash(str(out))) % 10**10}",
duration_seconds=probed.duration or duration, cost=0.0,
metadata={"mock": True, "base_image": base, "camera_movement": movement,
"canvas": [probed.width, probed.height]})
class MockVoiceProvider(VoiceProviderAdapter):
"""生成与文本长度成比例的占位人声,保证配音/字幕/混音链路可验证。"""
_name = "mock"
@property
def name(self) -> str:
return self._name
def synthesize(self, request: VoiceGenRequest, config: dict | None = None) -> VoiceGenResult:
config = config or {}
failure_rate = float(config.get("failure_rate", 0.0) or 0.0)
if failure_rate > 0 and random.random() < failure_rate:
raise RetryableProviderError("mock 适配器按 failure_rate 注入的临时失败",
code="mock_injected_failure")
out = Path(request.output_path or f"{settings.media_root}/mock/voice.wav")
out.parent.mkdir(parents=True, exist_ok=True)
text = (request.text or "").strip()
if not text:
raise FatalProviderError("配音文本为空")
speed = max(0.5, min(float(request.speed or 1.0), 2.0))
seed = request.seed if request.seed is not None else abs(hash(text)) % 10_000
rng = random.Random(seed)
# 中文按字符计,英文按词计:每音节 ~0.22s,句读停顿更长
units = max(1, sum(1 for ch in text if ch.isalnum()) if _has_cjk(text)
else max(1, len(text.split())))
base_freq = 110.0 + (abs(hash(request.provider_voice_id or request.voice_id)) % 90)
total = min(90.0, max(0.6, units * 0.235 / speed))
_write_speech_wav(out, total, base_freq * max(0.6, min(float(request.pitch or 1.0), 1.8)), rng,
sample_rate=int(request.sample_rate or 24000), gain=float(request.volume or 1.0))
duration_ms = int(round(total * 1000))
return VoiceGenResult(file_path=str(out), duration_ms=duration_ms,
provider_job_id=f"mock-tts-{seed}", cost=0.0,
metadata={"mock": True, "units": units, "voice": request.provider_voice_id})
def _has_cjk(text: str) -> bool:
return any("\u4e00" <= ch <= "\u9fff" for ch in text)
def _write_speech_wav(path: Path, duration: float, base_freq: float, rng: random.Random,
*, sample_rate: int, gain: float) -> None:
"""合成元音感占位音频:逐音节叠加基频+共振峰,带包络与停顿。"""
frames = bytearray()
t = 0.0
while t < duration:
syl = min(duration - t, rng.uniform(0.12, 0.26))
pause = 0.0 if rng.random() > 0.18 else rng.uniform(0.05, 0.16)
f0 = base_freq * rng.uniform(0.9, 1.15)
fmt = rng.uniform(1.6, 3.2)
n = int(syl * sample_rate)
for i in range(n):
x = i / sample_rate
env = math.sin(math.pi * (i / max(1, n))) ** 0.7
vib = 1.0 + 0.012 * math.sin(2 * math.pi * 5.2 * x)
v = (math.sin(2 * math.pi * f0 * vib * x) * 0.55
+ 0.28 * math.sin(2 * math.pi * f0 * fmt * x)
+ 0.12 * math.sin(2 * math.pi * f0 * 5.1 * x)
+ 0.05 * (rng.random() * 2 - 1))
sample = int(max(-1.0, min(1.0, v * env * gain * 0.6)) * 32767)
frames += struct.pack("<h", sample)
t += syl
for _ in range(int(pause * sample_rate)):
frames += struct.pack("<h", 0)
t += pause
with wave.open(str(path), "wb") as w:
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(sample_rate)
w.writeframes(bytes(frames))