cmvr-visual/backend/app/adapters/provider/editor_media.py

213 lines
8.9 KiB
Python
Raw Normal View History

"""自动文案和单音轨装配;模型只通过已有Qwen HTTP边界调用。"""
from __future__ import annotations
import json
import os
import re
import uuid
import wave
from app.adapters.media import input_options, run_process
from app.adapters.storage import file_thread
from app.domain.execution import CpuResult, enter_phase
from app.domain.errors import MediaError
from app.domain.timeline import Subtitle
from .contracts import _invalid, _int, _keys, _string
def validate(task_type, inputs, parameters):
if task_type == "text.script.generate":
_keys(inputs, {"shots", "context"})
_keys(parameters, {"model"})
if "model" in parameters:
_string(parameters["model"], 256)
shots = inputs.get("shots")
if not isinstance(shots, list) or not 1 <= len(shots) <= 1000:
raise _invalid("文案需要1–1000个镜头")
ids = []
for shot in shots:
_keys(shot, {"shot_id", "name", "visual_prompt", "motion_prompt", "duration_frames"})
sid = shot.get("shot_id")
if not isinstance(sid, str) or not re.fullmatch("[a-f0-9]{32}", sid):
raise _invalid("镜头ID无效")
ids.append(sid)
for field in ("name", "visual_prompt", "motion_prompt"):
_string(shot.get(field, ""), 8000, required=False)
_int(shot.get("duration_frames", 120), 24, 360)
if len(ids) != len(set(ids)):
raise _invalid("文案镜头ID不能重复")
if "context" in inputs and not isinstance(inputs["context"], dict):
raise _invalid("故事设定无效")
if len(json.dumps(inputs, ensure_ascii=False)) > 200000:
raise _invalid("文案输入过长,请减少镜头或描述")
elif task_type == "audio.assemble":
_keys(inputs, {"segments", "total_frames"})
_keys(parameters, {"fps"})
if parameters.get("fps", 24) != 24:
raise _invalid("音轨装配仅支持24fps")
_int(inputs.get("total_frames"), 1, 360000)
segments = inputs.get("segments")
if not isinstance(segments, list) or not 1 <= len(segments) <= 1000:
raise _invalid("音轨需要1–1000个片段")
for segment in segments:
_keys(segment, {"asset_id", "offset_frame"})
asset_id = _string(segment.get("asset_id"), 64)
if not re.fullmatch("[A-Za-z0-9_.-]+", asset_id):
raise _invalid("音轨只接受素材编号")
_int(segment.get("offset_frame"), 0, inputs["total_frames"] - 1)
async def script(provider, inputs, parameters, work):
validate("text.script.generate", inputs, parameters)
if parameters.get("model", provider.settings.qwen_model) != provider.settings.qwen_model:
raise MediaError("capability_changed", "文案模型配置已变化,请重新生成执行计划")
# 大故事按有界小组调用,避免一次输出截断;已返回组只有在整个步骤成功后发布。
segments = []
for index in range(0, len(inputs["shots"]), 8):
shots = inputs["shots"][index : index + 8]
# 已开始的响应自然完成;下一组调用仍须重新检查窗口和手动控制。
await enter_phase("script", "qwen_http")
content = await provider._chat(
[
{
"role": "system",
"content": '根据故事和镜头生成简短中文旁白。只返回JSON对象,格式为{"segments":[{"shot_id":"原ID","text":"旁白"}]}。每镜头恰好一条,ID原样返回。旁白字数必须适合给定duration_frames/24秒,建议每秒不超过3个汉字。不要把运镜、参数或提示词写入旁白,不要输出Markdown。',
},
{
"role": "user",
"content": json.dumps(
{"context": inputs.get("context", {}), "shots": shots}, ensure_ascii=False
),
},
],
max_tokens=4096,
thinking=False,
)
try:
text = content.strip()
if text.startswith("```"):
text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text)
value = json.loads(text)
_keys(value, {"segments"})
rows = value["segments"]
if not isinstance(rows, list) or len(rows) != len(shots):
raise ValueError
by_id = {}
for row in rows:
_keys(row, {"shot_id", "text"})
if row["shot_id"] in by_id:
raise ValueError
Subtitle(start_frame=0, end_frame=24, text=row["text"])
if len(row["text"]) > 2000:
raise ValueError
by_id[row["shot_id"]] = row
if set(by_id) != {s["shot_id"] for s in shots}:
raise ValueError
segments.extend(by_id[s["shot_id"]] for s in shots)
except (ValueError, TypeError, KeyError, MediaError) as exc:
raise MediaError(
"invalid_script", "文案服务返回了无效、缺失或不匹配的镜头内容"
) from exc
result = {"segments": segments}
path = provider._json_file(work, "script.json", result)
return CpuResult(
[path],
result,
{"provider": "qwen", "model": provider.settings.qwen_model, "recipe": "shot-script-v1"},
)
async def assemble(provider, inputs, parameters, assets, work):
validate("audio.assemble", inputs, parameters)
total_samples = inputs["total_frames"] * 2000
if total_samples * 4 + 44 > provider.settings.max_output_bytes:
raise MediaError("output_too_large", "装配音轨超出输出大小限制")
normalized, positions = [], []
target = work / ("narration-" + uuid.uuid4().hex + ".wav")
temporary = target.with_suffix(".part.wav")
try:
for segment in sorted(inputs["segments"], key=lambda s: s["offset_frame"]):
source = provider._asset(segment["asset_id"], assets)
start = segment["offset_frame"] * 2000
path = work / ("segment-" + uuid.uuid4().hex + ".wav")
normalized.append(path)
await run_process(
[
provider.settings.ffmpeg_bin,
"-v",
"error",
"-nostdin",
*input_options(),
"-i",
str(source),
"-vn",
"-t",
str((total_samples - start + 2000) / 48000),
"-ar",
"48000",
"-ac",
"2",
"-c:a",
"pcm_s16le",
"-y",
str(path),
],
timeout=300,
)
with wave.open(str(path), "rb") as audio:
count = audio.getnframes()
if (
count <= 0
or start + count > total_samples
or (positions and start < positions[-1]["end_sample"])
):
raise MediaError("invalid_timeline", "配音片段重叠或超出成片,原音频已保留")
positions.append(
{
**segment,
"start_sample": start,
"end_sample": start + count,
"sample_count": count,
}
)
def write_track():
cursor = 0
silence = bytes(65536)
with wave.open(str(temporary), "wb") as output:
output.setparams((2, 2, 48000, 0, "NONE", "not compressed"))
def pad(count):
remaining = count * 4
while remaining:
chunk = silence[: min(remaining, len(silence))]
output.writeframesraw(chunk)
remaining -= len(chunk)
for path, position in zip(normalized, positions, strict=True):
pad(position["start_sample"] - cursor)
with wave.open(str(path), "rb") as source:
while chunk := source.readframes(16384):
output.writeframesraw(chunk)
cursor = position["end_sample"]
pad(total_samples - cursor)
os.replace(temporary, target)
await file_thread(write_track)
result = {
"segments": positions,
"sample_rate": 48000,
"sample_count": total_samples,
"total_frames": inputs["total_frames"],
}
return CpuResult(
[target, provider._json_file(work, "narration.json", result)],
result,
{"provider": "ffmpeg-cpu", "recipe": "narration-assemble-v1"},
)
finally:
temporary.unlink(missing_ok=True)
for path in normalized:
path.unlink(missing_ok=True)