nex_animation/backend/app/jobs/handlers.py

749 lines
39 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.

"""任务执行体:视频生成 / 配音 / 质检 / 合成 / 导入。
对应业务流程图(图2):任务队列调度 → 调用视频模型 → 生成成功?
 否 → 记录错误并重试(回到队列);是 → 下载并保存视频 → 质量检查 → 人工审核。
所有异常一律在本层收口:写入错误历史并按策略重试或终止,绝不向执行后端抛出,
这样 Celery 与 inline 两种执行后端的语义完全一致。
"""
from __future__ import annotations
import logging
import os
import socket
import threading
import time
from pathlib import Path
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import Session
from app.config import settings
from app.constants import ShotStatus, TaskKind, TaskStatus
from app.db import SessionLocal
from app.models import Asset, Character, Project, Scene, Shot, Task, Timeline, VoiceAsset, now_utc
from app.providers import registry as model_registry
from app.providers.base import ProviderError
from app.services import audio, compose, costing, dispatch, events, ffmpeg as ff
from app.services import prompt as prompt_service
from app.services import quality, status as status_service, storage, timbre
log = logging.getLogger("nex.jobs")
WORKER_ID = f"{socket.gethostname()}:{os.getpid()}"
# ---------------------------------------------------------------- 内部工具
def _load(task_id: int) -> tuple[Session | None, Task | None]:
db = SessionLocal()
task = db.get(Task, task_id)
if task is None:
db.close()
return None, None
return db, task
#: 抢写锁的退避重试:内联执行器同时跑关键帧/视频/配音/质检时,
#: begin_execution 是最早的一批写事务,撞锁概率最高、重试代价也最划算。
LOCK_RETRY_ATTEMPTS = 6
LOCK_RETRY_BASE_SECONDS = 0.25
def _is_lock_error(exc: BaseException) -> bool:
return "locked" in str(exc).lower()
def _begin(db: Session, task: Task) -> bool:
"""标记运行中;任务若已处于终态则跳过执行。
抢不到 SQLite 写锁时先退避重试:这条写事务发生在**还没调用任何模型**之前,
一次 database is locked 就能把一轮 4 分钟的出图整轮判成 runtime_error
(项目 9 镜头03 实测:task 463 白烧一次重试,多占两分钟 GPU)。
"""
if task.status in (TaskStatus.CANCELLED, TaskStatus.SUCCEEDED, TaskStatus.FAILED, TaskStatus.SKIPPED):
db.close()
return False
for attempt in range(LOCK_RETRY_ATTEMPTS):
try:
dispatch.begin_execution(db, task, worker=WORKER_ID)
db.commit()
return True
except OperationalError as exc:
db.rollback()
if not _is_lock_error(exc) or attempt == LOCK_RETRY_ATTEMPTS - 1:
raise
log.warning("任务 #%s 开始执行时数据库写锁冲突,退避后重试(第 %s 次)",
task.id, attempt + 1)
time.sleep(LOCK_RETRY_BASE_SECONDS * (attempt + 1))
return True
def _was_cancelled(db: Session, task_id: int) -> bool:
"""跨会话读取最新任务状态;长供应商调用期间任务可能被用户取消。"""
db.expire_all()
current = db.get(Task, task_id)
return current is None or current.status == TaskStatus.CANCELLED
class _Heartbeat:
"""执行期心跳:长任务(生成/合成动辄几分钟)必须持续续租,
否则「断点续跑」会把还在正常执行的任务误判成中断任务并重复排队,
造成同一个镜头被生成两次、成本翻倍。
"""
def __init__(self, task_id: int, interval: float | None = None):
self.task_id = task_id
stale = max(3, int(settings.stale_running_seconds or 120))
self.interval = float(interval or max(1.0, min(20.0, stale / 3.0)))
self._stop = threading.Event()
self._thread: threading.Thread | None = None
def _loop(self) -> None:
while not self._stop.wait(self.interval):
db = SessionLocal()
try:
dispatch.renew_lease(db, self.task_id)
except Exception: # 心跳失败不影响任务本身
db.rollback()
log.debug("任务心跳刷新失败 task=%s", self.task_id, exc_info=True)
finally:
db.close()
def __enter__(self) -> "_Heartbeat":
self._thread = threading.Thread(target=self._loop, name=f"nex-heartbeat-{self.task_id}",
daemon=True)
self._thread.start()
return self
def __exit__(self, *exc_info) -> None:
self._stop.set()
if self._thread is not None:
self._thread.join(timeout=max(1.0, self.interval))
self._thread = None
def _finish_failure(db: Session, task: Task, exc: BaseException, *, shot: Shot | None) -> dict:
db.rollback()
task = db.get(Task, task.id)
shot = db.get(Shot, shot.id) if shot is not None else None
dispatch.schedule_retry_or_fail(db, task, exc, shot=shot)
db.commit()
return {"failed": True, "code": task.error_code, "status": task.status}
def _output_for(project: Project, shot: Shot, task: Task) -> Path:
return storage.project_dir(project.id, "generated") / f"shot-{shot.order_index:02d}-task{task.id}.mp4"
# ---------------------------------------------------------------- 视频生成
def handle_generate_shot(task_id: int) -> dict:
db, task = _load(task_id)
if db is None or task is None:
return {"skipped": "任务不存在"}
shot = db.get(Shot, task.shot_id) if task.shot_id else None
project = db.get(Project, task.project_id)
if shot is None or project is None:
result = _finish_failure(db, task, ProviderError("任务对应的镜头或项目已不存在", code="missing_entity"),
shot=None)
db.close()
return result
if not _begin(db, task):
return {"skipped": "任务已处于终态"}
try:
# 1) 组装提示词 + 收集参考素材(关键帧 / 定妆图 / 场景图)
prompt_service.sync_prompt(db, project, shot, reason="生成前同步提示词", actor="worker", record=True)
request, used_paths = prompt_service.build_video_request(db, project, shot)
out = _output_for(project, shot, task)
request.output_path = out
spec, _adapter = model_registry.resolve_video(db, task.provider or None, task.model or None)
task.provider, task.model, task.mode = spec.provider, spec.model, request.mode
dispatch.heartbeat(db, task, progress=0.1, note=f"调用 {spec.provider}/{spec.model}")
db.commit()
# 2) 调用视频模型(异步供应商由适配器内部轮询,对上层保持阻塞语义)
def _report(ratio: float, note: str) -> None:
"""把供应商侧阶段(排队/出图/下载)写进任务表,长任务界面不再是一片空白。
ratio 为负数表示「只更新说明、进度保持原样」:断连重试这类事件既不该推进
进度条,也不该把它倒回去——倒回去看起来像任务被打回起点,用户会以为卡住了。
"""
value = float(ratio)
progress = None if value < 0 else 0.1 + 0.6 * max(0.0, min(1.0, value))
dispatch.heartbeat(db, task, progress=progress, note=note)
db.commit()
started = time.monotonic()
try:
result = model_registry.generate_video(db, request, spec.provider, spec.model,
on_progress=_report)
except TypeError: # 适配器不接受回调时退回原调用
result = model_registry.generate_video(db, request, spec.provider, spec.model)
elapsed = round(time.monotonic() - started, 3)
if _was_cancelled(db, task.id):
# 远端任务无法总是即时中止;返回后绝不能把已取消任务的结果写回镜头。
return {"cancelled": True}
task = db.get(Task, task.id)
shot = db.get(Shot, shot.id)
project = db.get(Project, project.id)
dispatch.heartbeat(db, task, progress=0.75, note="下载并校验产物")
db.commit()
# 3) 下载并保存视频:落盘 → 探测校验 → 校验和
produced = Path(result.file_path)
if not produced.exists():
raise ProviderError("供应商未返回可读取的产物文件", code="missing_output")
if out.resolve() != produced.resolve():
out.parent.mkdir(parents=True, exist_ok=True)
out.write_bytes(produced.read_bytes())
if out.stat().st_size < 512:
raise ProviderError("产物文件过小,疑似下载不完整", code="truncated_output")
if ff.available():
probe = ff.probe(out)
if probe.duration <= 0.2:
raise ProviderError("产物时长异常,无法进入合成环节", code="invalid_duration")
checksum = ff.checksum(out)
duration = float(result.duration_seconds or probe.duration or shot.duration)
else:
checksum, duration = "", float(result.duration_seconds or shot.duration)
rel = storage.to_relative(out)
# 4) 回写镜头产物
shot = db.get(Shot, shot.id)
shot.output_path = rel
shot.output_duration = round(duration, 3)
shot.output_checksum = checksum
shot.provider_job_id = result.provider_job_id or ""
shot.provider, shot.model = spec.provider, spec.model
shot.generated_at = now_utc()
shot.status = ShotStatus.GENERATED
shot.stage = "quality_check"
shot.error_code = ""
shot.error_message = ""
project.current_stage = "save_output"
# 5) 成本统计 + 生成记录
cost = float(result.cost or costing.estimate_video_cost(spec, duration))
if cost:
costing.record_cost(db, project_id=project.id, kind=TaskKind.GENERATE_SHOT, provider=spec.provider,
model=spec.model, shot_id=shot.id, task_id=task.id, quantity=duration,
unit="second", unit_price=float(spec.price_per_second or 0.0), cost=cost,
currency=spec.currency, note=f"镜头 {shot.order_index:02d} 视频生成")
task.cost = round(cost, 6)
costing.record_generation(db, project_id=project.id, shot_id=shot.id, task_id=task.id,
provider=spec.provider, model=spec.model, kind=TaskKind.GENERATE_SHOT,
prompt=request.prompt,
params_json={"duration": request.duration_seconds,
"resolution": request.resolution,
"aspect_ratio": request.aspect_ratio, "fps": request.fps,
"mode": request.mode,
# 结构化镜头参数进台账:出片与分镜必须逐项可核对(景别/机位/运镜)
"shot_size": (request.params or {}).get("shot_size"),
"camera_angle": (request.params or {}).get("camera_angle"),
"camera_movement": (request.params or {}).get("camera_movement"),
# 请求常不指定 seed(由适配器按幂等键派生),
# 只记 None 会让这条记录无法复现,优先落供应商实际用的 seed。
"seed": (result.metadata or {}).get("seed", request.seed),
"label": request.label,
"negative_prompt": request.negative_prompt},
provider_job_id=result.provider_job_id,
asset_paths=[storage.to_relative(p) for p in used_paths if p],
output_path=rel, duration_seconds=round(duration, 3), cost=cost,
currency=spec.currency, attempts=task.attempts,
metadata_json={"elapsed_seconds": elapsed,
"mock": bool((result.metadata or {}).get("mock")),
"provider_metadata": result.metadata or {}})
# 6) 质量检查任务入队(质量检查 → 人工审核)
qc_task = dispatch.new_qc_task(db, project, shot)
dispatch.mark_succeeded(db, task, output_path=rel,
result={"path": rel, "duration": round(duration, 3), "cost": round(cost, 6),
"checksum": checksum, "provider": spec.provider, "model": spec.model,
"qc_task_id": qc_task.id, "elapsed_seconds": elapsed})
events.log_event(db, "shot.generated", project_id=project.id, shot_id=shot.id, task_id=task.id,
message=f"镜头 {shot.order_index:02d} 生成完成并已保存({duration:.1f}s,"
f"{spec.provider}/{spec.model}),已排入质量检查",
entity_type="shot", entity_id=shot.id,
data={"path": rel, "provider": spec.provider, "model": spec.model,
"provider_job_id": result.provider_job_id, "cost": round(cost, 6)})
status_service.refresh(db, project, commit=False)
db.commit()
return {"ok": True, "path": rel, "duration": round(duration, 3), "qc_task_id": qc_task.id}
except Exception as exc:
log.warning("镜头生成失败 task=%s: %s", task_id, exc)
return _finish_failure(db, task, exc, shot=shot)
finally:
db.close()
# ---------------------------------------------------------------- 配音
def handle_voiceover(task_id: int) -> dict:
db, task = _load(task_id)
if db is None or task is None:
return {"skipped": "任务不存在"}
shot = db.get(Shot, task.shot_id) if task.shot_id else None
project = db.get(Project, task.project_id)
if shot is None or project is None:
dispatch.cancel_task(db, task, reason="镜头或项目已不存在,配音任务终止")
db.close()
return {"cancelled": True}
if not _begin(db, task):
return {"skipped": "任务已处于终态"}
try:
raw = (task.payload_json or {}).get("text")
text = shot.dialogue.strip() if raw is None else str(raw).strip()
if not text:
dispatch.mark_succeeded(db, task, result={"skipped": "镜头没有台词,无需配音"})
db.commit()
return {"skipped": "无台词"}
result = audio.generate_voiceover(db, project, shot, text=text, task_id=task.id, commit=False)
dispatch.mark_succeeded(db, task, output_path=result["path"], result=result)
db.commit()
return result
except Exception as exc:
log.warning("配音失败 task=%s: %s", task_id, exc)
return _finish_failure(db, task, exc, shot=None)
finally:
db.close()
# ---------------------------------------------------------------- 质量检查
def handle_qc_shot(task_id: int) -> dict:
db, task = _load(task_id)
if db is None or task is None:
return {"skipped": "任务不存在"}
shot = db.get(Shot, task.shot_id) if task.shot_id else None
project = db.get(Project, task.project_id)
if shot is None or project is None:
dispatch.cancel_task(db, task, reason="镜头或项目已不存在,质检任务终止")
db.close()
return {"cancelled": True}
if not _begin(db, task):
return {"skipped": "任务已处于终态"}
try:
report = quality.check_shot(db, project, shot, commit=False)
payload = {"passed": report.passed, "score": report.score, "issues": list(report.issues)[:10],
"checks": [c.as_dict() for c in report.checks]}
if report.passed:
dispatch.mark_succeeded(db, task, result=payload)
else:
# 产物仍在,流程交回人工「调整提示词或重新生成」,任务本身记录完成
dispatch.mark_succeeded(db, task, result=payload)
events.log_event(db, "qc.action_required", project_id=project.id, shot_id=shot.id, task_id=task.id,
level="warn", message=f"镜头 {shot.order_index:02d} 质检未通过,需要返工",
entity_type="shot", entity_id=shot.id, data=payload)
db.commit()
return payload
except Exception as exc:
log.warning("质检异常 task=%s: %s", task_id, exc)
return _finish_failure(db, task, exc, shot=None)
finally:
db.close()
# ---------------------------------------------------------------- 合成导出
def handle_compose(task_id: int) -> dict:
db, task = _load(task_id)
if db is None or task is None:
return {"skipped": "任务不存在"}
project = db.get(Project, task.project_id)
timeline = db.get(Timeline, task.timeline_id) if task.timeline_id else None
if project is None or timeline is None:
dispatch.cancel_task(db, task, reason="项目或时间线已不存在,合成任务终止")
db.close()
return {"cancelled": True}
if not _begin(db, task):
return {"skipped": "任务已处于终态"}
payload = task.payload_json or {}
try:
dispatch.heartbeat(db, task, progress=0.05, note="准备合成")
db.commit()
return compose.render(db, project, timeline, preset=str(payload.get("preset") or "web_1080p"),
name=str(payload.get("name") or task.name or ""),
burn_subtitle=payload.get("burn_subtitle"),
subtitle_mode=payload.get("subtitle_mode"), task=task)
except Exception as exc:
log.warning("合成失败 task=%s: %s", task_id, exc)
return _finish_failure(db, task, exc, shot=None)
finally:
db.close()
# ---------------------------------------------------------------- 分镜导入
def handle_import(task_id: int) -> dict:
from app.services import importer
db, task = _load(task_id)
if db is None or task is None:
return {"skipped": "任务不存在"}
project = db.get(Project, task.project_id)
if project is None:
db.close()
return {"cancelled": True}
if not _begin(db, task):
return {"skipped": "任务已处于终态"}
payload = task.payload_json or {}
try:
images: dict[str, bytes] = {}
for rel in payload.get("image_paths") or []:
abs_path = storage.to_absolute(rel)
if abs_path.exists():
images[Path(str(rel)).name] = abs_path.read_bytes()
result = importer.import_storyboard(db, project, script_text=str(payload.get("script_text") or ""),
script_name=str(payload.get("script_name") or ""), images=images,
default_duration=float(payload.get("default_duration") or 5.0),
replace=bool(payload.get("replace", False)), actor="worker")
dispatch.mark_succeeded(db, task, result={k: v for k, v in result.items() if k != "shots"})
db.commit()
return {k: v for k, v in result.items() if k != "shots"}
except Exception as exc:
return _finish_failure(db, task, exc, shot=None)
finally:
db.close()
# ---------------------------------------------------------------- 资产校验/衍生
def _asset_owner(db: Session, project: Project, owner_type: str, owner_id: int):
if owner_type == "human":
row = db.get(Character, owner_id)
elif owner_type == "scene":
row = db.get(Scene, owner_id)
elif owner_type == "voice":
row = db.get(VoiceAsset, owner_id)
elif owner_type == "shot":
row = db.get(Shot, owner_id)
else:
row = None
return row if row is not None and row.project_id == project.id else None
def _image_asset_prompt(db: Session, project: Project, owner, owner_type: str, kind: str,
custom: str) -> str:
# 有台词镜头的首帧必须多一句构图约束:**i2v 由谁来出声是首帧决定的**
# (详见 prompt_service.keyframe_speech_note)。页面上的关键帧生成会把
# shot.prompt 当「自定义提示词」传进来,所以这句话对自定义分支同样要生效。
speech_note = (prompt_service.keyframe_speech_note(owner)
if owner_type == "shot" and kind == "keyframe" else "")
if custom.strip():
return "。".join(x for x in (custom.strip().rstrip("。"), speech_note) if x)
if owner_type == "shot":
labels = {"keyframe": "分镜关键帧", "last_frame": "分镜尾帧",
"reference_image": "分镜参考图"}
# 首帧是 i2v 的视觉基准:这里必须现算提示词,不能用 shot.prompt 里那份缓存字符串。
# 旧实现读缓存,于是「换定妆照之后重画的关键帧」仍然带着描述卡里的衣着文字
# (白色短袖 + 黑丝袜),参考图被文字盖住,人物在成片里始终换不了装。
composed = prompt_service.compose_prompt(project, owner, db=db)
# compose_prompt 末尾已经并入了 shot.style_note,再拼一遍会让同一段
# 「日常真实场景 【返工要求第1轮】……」在关键帧提示词里出现两遍,
# 白白挤占上下文,还让模型以为返工要求被强调了两轮。
style_note = (owner.style_note or "").strip()
if style_note and style_note in composed:
style_note = ""
bits = [f"《{project.name}》镜头 {owner.order_index:02d},"
f"{labels.get(kind, '分镜画面')},电影级单帧构图",
composed or owner.description, speech_note, style_note,
"人物身份、服装、场景结构与美术风格保持一致;画面清晰,"
"只输出一张无文字、无水印的完整电影画面"]
return "。".join(str(value).strip() for value in bits if value)
if owner_type == "human":
labels = {"portrait": "角色定妆图", "turnaround": "角色三视图", "costume": "角色服装设定",
"expression": "角色表情参考"}
bits = [f"{owner.name},{labels.get(kind, '角色设定')},电影级人物概念设计",
owner.appearance, owner.persona_prompt, project.style_guide,
"五官、体型、发型、服装与配饰保持一致,正面清晰,材质细节可信"]
else:
bits = [f"{owner.name},电影级场景概念图", owner.prompt or owner.description,
owner.lighting, owner.time_of_day, owner.palette, project.style_guide,
"空间结构清晰,透视准确,同一场景在不同镜头中保持建筑与陈设一致"]
return "。".join(str(v).strip() for v in bits if v)
def _sync_owner_prompts(db: Session, project: Project, owner_type: str, owner_id: int) -> None:
for shot in project.shots or []:
used = ((owner_type == "human" and any(c.id == owner_id for c in (shot.characters or [])))
or (owner_type == "scene" and any(s.id == owner_id for s in (shot.scenes or []))))
if used:
prompt_service.sync_prompt(db, project, shot, reason="资产生成后重算提示词", record=False)
def _generate_image_asset(db: Session, task: Task, project: Project, payload: dict) -> dict:
owner_type = str(payload.get("target_type") or "")
owner_id = int(payload.get("target_id") or 0)
kind = str(payload.get("kind") or "portrait")
owner = _asset_owner(db, project, owner_type, owner_id)
if owner is None:
raise ProviderError("资产生成目标不存在", code="missing_asset_owner", retryable=False)
spec, _adapter = model_registry.resolve_asset(db, "image", task.provider or None, task.model or None)
task.provider, task.model = spec.provider, spec.model
prompt = _image_asset_prompt(db, project, owner, owner_type, kind,
str(payload.get("prompt") or ""))
width = max(256, min(4096, int(payload.get("width") or 1024)))
height = max(256, min(4096, int(payload.get("height") or 1024)))
suffix = ".png"
out = storage.project_dir(project.id, "generated-assets") / \
f"{owner_type}-{owner_id}-{kind}-task{task.id}{suffix}"
from app.providers.base import AssetGenRequest
gen_request = AssetGenRequest(
kind=kind, prompt=prompt, negative_prompt=str(payload.get("negative_prompt") or ""),
width=width, height=height, seed=payload.get("seed"),
reference_images=list(payload.get("reference_paths") or []),
params={"model": spec.model,
"asset_type": ("shot" if owner_type == "shot"
else "scene" if owner_type == "scene" else "character")},
idempotency_key=f"asset:{owner_type}:{owner_id}:{kind}:{task.id}",
label=f"{owner_type.upper()}-{owner_id}-{kind}", output_path=out,
)
dispatch.heartbeat(db, task, progress=0.25, note=f"调用 {spec.provider}/{spec.model} 生成图像")
db.commit()
result = model_registry.generate_asset(db, gen_request, "image", spec.provider, spec.model)
if _was_cancelled(db, task.id):
return {"cancelled": True}
task = db.get(Task, task.id)
project = db.get(Project, project.id)
produced = Path(result.file_path)
if not produced.exists() or produced.stat().st_size < 128:
raise ProviderError("图像模型未返回有效文件", code="missing_image_output", retryable=False)
info = storage.save_local_file(produced, project_id=project.id, kind=kind,
stem=f"{owner_type}-{owner_id}-{kind}-ai")
default_name = (f"镜头 {owner.order_index:02d} · AI {_asset_kind_label(kind)}"
if owner_type == "shot"
else f"{owner.name} · AI {_asset_kind_label(kind)}")
asset = storage.register_asset(
db, project_id=project.id, owner_type=owner_type, owner_id=owner_id, kind=kind,
path=info["path"], name=str(payload.get("name") or default_name),
note=f"模型生成:{spec.provider}/{spec.model}", source="provider", info=info,
metadata={"generated": True, "provider": spec.provider, "model": spec.model,
"prompt": prompt, "negative_prompt": payload.get("negative_prompt") or "",
"seed": (result.metadata or {}).get("seed", payload.get("seed")),
"reference_asset_ids": payload.get("reference_asset_ids") or [],
"task_id": task.id},
)
_sync_owner_prompts(db, project, owner_type, owner_id)
unit_price = float((spec.default_params or {}).get("price_per_image", 0.0) or 0.0)
cost = float(result.cost or unit_price)
if cost:
costing.record_cost(db, project_id=project.id, kind=TaskKind.ASSET, provider=spec.provider,
model=spec.model, task_id=task.id, quantity=1, unit="image",
unit_price=unit_price, cost=cost, currency=spec.currency,
note=f"{owner_type} {owner_id} 图像资产")
costing.record_generation(
db, project_id=project.id, task_id=task.id, provider=spec.provider, model=spec.model,
kind="asset_image", prompt=prompt,
params_json={"width": width, "height": height, "seed": payload.get("seed"), "kind": kind},
provider_job_id=result.provider_job_id, output_path=info["path"],
duration_seconds=0, cost=cost, currency=spec.currency, attempts=task.attempts,
metadata_json={"owner_type": owner_type, "owner_id": owner_id,
"provider_metadata": result.metadata or {}},
)
dispatch.mark_succeeded(db, task, output_path=info["path"], result={
"asset_id": asset.id, "asset": storage.asset_dict(asset), "provider": spec.provider,
"model": spec.model, "prompt": prompt,
})
events.log_event(db, "asset.generated", project_id=project.id, task_id=task.id,
message=f"使用 {spec.provider}/{spec.model} 生成{_asset_kind_label(kind)}:{asset.name}",
entity_type="asset", entity_id=asset.id,
data={"owner_type": owner_type, "owner_id": owner_id, "path": asset.path})
status_service.refresh(db, project, commit=False)
db.commit()
return {"asset": storage.asset_dict(asset), "provider": spec.provider, "model": spec.model}
def _asset_kind_label(kind: str) -> str:
from app.constants import AssetKind
return AssetKind.LABELS.get(kind, kind)
def _generate_voice_sample(db: Session, task: Task, project: Project, payload: dict) -> dict:
from app.providers.base import VoiceGenRequest
owner = _asset_owner(db, project, "voice", int(payload.get("target_id") or 0))
if not isinstance(owner, VoiceAsset):
raise ProviderError("声线资产不存在", code="missing_asset_owner", retryable=False)
spec, _adapter = model_registry.resolve_asset(db, "tts", task.provider or owner.provider or None,
task.model or None)
task.provider, task.model = spec.provider, spec.model
# 试听文本是「模型要念出来的台词」,不是声线设定。旧实现拿 owner.description 兜底,
# 于是「温和、语速中等」这种设定描述被当成台词念了出来。
text = str(payload.get("sample_text") or "").strip()
if not text:
raise ProviderError("请先填写试听文本:它是模型要朗读的台词,系统不会用「音色描述」代替",
code="missing_sample_text", retryable=False)
tuning = dict(owner.tuning or {})
reference_paths = [str(path) for path in (payload.get("reference_paths") or []) if path]
out = storage.project_dir(project.id, "generated-assets") / \
f"voice-{owner.id}-sample-task{task.id}.wav"
# 参考音频决定音色,「性别」对 zero-shot 克隆模型只是元数据:
# 缺参考时必须换成同性别参考或明确报错,不能让男声悄悄用上模型默认的女声底模。
clone = timbre.clone_model(spec)
reference = timbre.resolve_reference(
db, owner, explicit=reference_paths[0] if reference_paths else "", clone=clone)
if not reference["path"] and reference.get("source") == "none":
raise ProviderError(reference["note"], code="missing_reference_audio", retryable=False)
request = VoiceGenRequest(
text=text, voice_id=owner.name,
provider_voice_id=reference["path"] or owner.provider_voice_id,
language=owner.language, speed=float(tuning.get("speed", 1.0)),
pitch=float(tuning.get("pitch", 1.0)), volume=float(tuning.get("volume", 1.0)),
sample_rate=int(tuning.get("sample_rate", 24000)), seed=payload.get("seed"),
params=tuning.get("params") or {}, idempotency_key=f"asset-voice:{owner.id}",
label=f"VOICE-{owner.id}", output_path=out,
)
dispatch.heartbeat(db, task, progress=0.3, note=f"调用 {spec.provider}/{spec.model} 生成试听")
db.commit()
result = model_registry.generate_voice(db, request, spec.provider, spec.model)
if _was_cancelled(db, task.id):
return {"cancelled": True}
task = db.get(Task, task.id)
project = db.get(Project, project.id)
produced = Path(result.file_path)
if not produced.exists() or produced.stat().st_size < 256:
raise ProviderError("语音模型未返回有效音频", code="missing_audio_output", retryable=False)
info = storage.save_local_file(produced, project_id=project.id, kind="voice_sample",
stem=f"voice-{owner.id}-ai-sample")
info["duration_ms"] = int(result.duration_ms or ff.duration_ms(produced) or 0)
# 音色自检:量一遍实际基频,与声线设定的性别比对,结果进元数据供界面标注。
check = timbre.check_voice(produced, owner.gender)
if clone and reference["path"]:
# 把真正参与克隆的参考音频绑回声线:否则试听是 A 的嗓子,正式配音又落回模型默认参考。
owner.provider_voice_id = str(storage.to_relative(reference["path"]))
asset = storage.register_asset(
db, project_id=project.id, owner_type="voice", owner_id=owner.id, kind="voice_sample",
path=info["path"], name=f"{owner.name} · AI 音色样本", note=f"模型生成:{spec.provider}/{spec.model}",
source="provider", info=info,
metadata={"generated": True, "provider": spec.provider, "model": spec.model,
"text": text,
"reference_asset_ids": payload.get("reference_asset_ids") or [],
# 非克隆模型不拿本地参考定音色,但用户挂的参考仍要能回溯到具体文件
"reference_audio": reference["path"] or reference.get("attached") or "",
"reference_source": reference["source"],
"reference_note": reference["note"],
"timbre_check": check,
"task_id": task.id},
)
if check.get("matched") is False:
asset.note = f"{asset.note}|音色自检:{check['note']}"
cost = float(result.cost or 0.0)
if cost:
costing.record_cost(db, project_id=project.id, kind=TaskKind.ASSET, provider=spec.provider,
model=spec.model, task_id=task.id, quantity=len(text), unit="1k_chars",
unit_price=float(spec.price_per_1k_chars or 0.0), cost=cost,
currency=spec.currency, note=f"声线 {owner.id} 音色样本")
dispatch.mark_succeeded(db, task, output_path=info["path"], result={
"asset_id": asset.id, "asset": storage.asset_dict(asset), "provider": spec.provider,
"model": spec.model, "duration_ms": info["duration_ms"],
})
events.log_event(db, "asset.generated", project_id=project.id, task_id=task.id,
message=f"生成声线试听:{owner.name}({spec.provider}/{spec.model})",
entity_type="asset", entity_id=asset.id,
data={"owner_type": "voice", "owner_id": owner.id, "path": asset.path})
status_service.refresh(db, project, commit=False)
db.commit()
return {"asset": storage.asset_dict(asset), "provider": spec.provider, "model": spec.model}
def handle_asset(task_id: int) -> dict:
"""资产任务:校验已有素材,或调用图像/声音模型生成独立资产。"""
db, task = _load(task_id)
if db is None or task is None:
return {"skipped": "任务不存在"}
project = db.get(Project, task.project_id)
if project is None:
dispatch.cancel_task(db, task, reason="项目不存在,资产任务终止")
db.close()
return {"cancelled": True}
if not _begin(db, task):
return {"skipped": "任务已处于终态"}
try:
payload = task.payload_json or {}
operation = str(payload.get("operation") or "refresh")
if operation == "generate_image":
return _generate_image_asset(db, task, project, payload)
if operation == "generate_voice_sample":
return _generate_voice_sample(db, task, project, payload)
asset_id = int((task.payload_json or {}).get("asset_id") or 0)
asset = db.get(Asset, asset_id) if asset_id else None
if asset is None:
dispatch.cancel_task(db, task, reason="资产不存在,任务终止")
db.close()
return {"cancelled": True}
path = storage.to_absolute(asset.path)
if not path.exists():
raise ProviderError(f"资产文件缺失:{asset.path}", code="asset_missing")
asset.size_bytes = path.stat().st_size
asset.checksum = ff.checksum(path) or asset.checksum
if ff.available():
probe = ff.probe(path)
asset.width, asset.height = probe.width or asset.width, probe.height or asset.height
asset.duration_ms = int(probe.duration * 1000) if probe.duration else asset.duration_ms
dispatch.mark_succeeded(db, task, result={"asset_id": asset.id, "path": asset.path,
"size_bytes": asset.size_bytes})
db.commit()
return {"asset_id": asset.id, "path": asset.path}
except Exception as exc:
return _finish_failure(db, task, exc, shot=None)
finally:
db.close()
HANDLERS = {
TaskKind.GENERATE_SHOT: handle_generate_shot,
TaskKind.VOICEOVER: handle_voiceover,
TaskKind.QC_SHOT: handle_qc_shot,
TaskKind.COMPOSE: handle_compose,
TaskKind.IMPORT: handle_import,
TaskKind.ASSET: handle_asset,
}
def _reconcile_project(task_id: int) -> None:
"""任务进入终态后回写项目状态——所有任务类型统一收口。
过去只有 handle_generate_shot 会 refresh:质检、配音、合成、素材任务改完
镜头与任务就收工。守护线程那边的兜底也一起失效了(它只刷「队列里还有
活跃任务」的项目)。于是「项目最后一条任务正好是质检」时没人回写,
镜头早就出完了,项目却永远停在 generating/generate「调用视频模型」。
"""
db = SessionLocal()
try:
task = db.get(Task, task_id)
if task is None or task.project_id is None:
return
project = db.get(Project, task.project_id)
if project is None:
return
status_service.refresh(db, project, commit=False)
db.commit()
except Exception as exc: # 回写失败不得影响任务结果
db.rollback()
log.warning("任务 #%s 收口后回写项目状态失败:%s", task_id, exc)
finally:
db.close()
def run(kind: str, task_id: int) -> dict:
"""执行后端统一入口(Celery worker 与 inline 线程池都调用它)。"""
handler = HANDLERS.get(kind)
if handler is None:
log.error("未知任务类型 kind=%s task=%s", kind, task_id)
db, task = _load(task_id)
if db is not None and task is not None:
_finish_failure(db, task, ProviderError(f"未知任务类型:{kind}", code="unknown_kind"), shot=None)
db.close()
_reconcile_project(task_id)
return {"failed": True}
try:
with _Heartbeat(task_id):
return handler(task_id)
except Exception as exc: # handler 内部已收口,这里只做最后兜底
log.exception("任务执行未捕获异常 kind=%s task=%s", kind, task_id)
db, task = _load(task_id)
if db is not None and task is not None and task.status == TaskStatus.RUNNING:
_finish_failure(db, task, exc, shot=db.get(Shot, task.shot_id) if task.shot_id else None)
db.close()
return {"failed": True, "error": str(exc)}
finally:
_reconcile_project(task_id) # 队列动过,项目阶段就得跟上