nex_animation/backend/app/providers/comfy_assets.py

606 lines
30 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.

"""ComfyUI 本地图像与 TTS 适配器。
- 图像:Qwen-Image-2.1-Turbo GGUF,8 步固定 sigma,euler + CFG 1。
- 语音:IndexTTS2 Zero-shot 参考音频,模型文件复用 9200 实例。
两者与 H3 视频共用一张 GPU,所有请求通过 ``gpu_slot`` 串行。
"""
from __future__ import annotations
import hashlib
import json
import re
import threading
import time
import subprocess
import tempfile
from pathlib import Path
from typing import Any
from urllib.parse import quote
import httpx
from app.config import settings
from app.providers.base import (AssetGenRequest, AssetGenResult, Capabilities, FatalProviderError,
ImageProviderAdapter, RetryableProviderError, VoiceGenRequest,
VoiceGenResult, VoiceProviderAdapter)
from app.providers.comfy_common import client as comfy_client
from app.providers.comfy_common import diagnosis_message, is_network_error
from app.providers.comfy_common import (comfy_base, download_output, first_output, gpu_slot,
network_guard, object_candidates, raise_for,
require_reachable, stable_client_id, submit_graph,
upload_input, wait_history)
from app.services import ffmpeg as ff
# ------------------------------------------------------------------ 可用性探测
# /api/providers 是全站首屏都要打的接口,而这里两个适配器过去每次调用都现场
# 打 ComfyUI:图像 1 个请求、TTS 3 个请求,还都用 httpx.get/新建 Client,
# 等于每轮重新握手三次。实测 /api/providers 95% 的耗时都在这几个 socket.recv 上
# (p50 60ms、p95 150ms+),H3 视频适配器早就有 30s 探测缓存,这两个漏了。
# 现在同样缓存 30 秒,并复用一个带连接池的 Client;「模型中心 → 探测」按钮
# 走 invalidate_probes() 强制实探,语义不受影响。
PROBE_TTL_SECONDS = 30.0
_client: httpx.Client | None = None
_client_lock = threading.Lock()
def _probe_client() -> httpx.Client:
global _client
with _client_lock:
if _client is None or _client.is_closed:
_client = comfy_client(timeout=8.0)
return _client
class _ProbeCache:
"""按「适配器 + 服务地址」缓存探测结果;并发请求只让一个去打网络。"""
def __init__(self) -> None:
self._lock = threading.Lock()
self._hits: dict[str, tuple[float, bool]] = {}
def get(self, key: str) -> bool | None:
with self._lock:
hit = self._hits.get(key)
if hit and time.time() - hit[0] < PROBE_TTL_SECONDS:
return hit[1]
return None
def put(self, key: str, ok: bool) -> None:
with self._lock:
self._hits[key] = (time.time(), ok)
def invalidate(self, key: str | None = None) -> None:
with self._lock:
if key is None:
self._hits.clear()
else:
self._hits.pop(key, None)
QWEN_SIGMAS = "1.0, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568, 0"
QWEN_IMAGE_MARKER = re.compile(r"<image\s*\d+\s*>", re.IGNORECASE)
QWEN_COMPOSITION_LOCK = re.compile(
r"(?:保持|保留|沿用|维持|不要改变|不改变).{0,10}(?:构图|镜头|视角|机位)"
)
QWEN_INTERIOR_INTENT = re.compile(
r"(?:室内|内景|屋内|房间内部|客厅|卧室|厨房|餐厅|浴室|书房)"
)
QWEN_INTERIOR_DIRECTIVE = (
"将{reference}中的镜头移到建筑内部,生成全新的室内机位。"
"画面完全位于室内,展示房间的墙体、天花、地面、门窗、家具与陈设;"
"透过窗户可以保留原场景环境,但不要展示建筑外立面、屋顶或室外庭院。"
)
QWEN_NEW_FRAME_DIRECTIVE = (
"参考图只用于人物身份、空间结构、材质和美术风格的一致性,不代表最终构图。"
"必须重新组织画面,生成一张与参考图明显不同的新画面;"
"改变机位、景别或光线氛围,不要直接复刻、描摹或输出参考图本身。"
)
def _base(config: dict) -> str:
return comfy_base(config, settings.comfyui_base_url)
def _qwen_edit_prompt(prompt: str, reference_count: int) -> str:
"""Describe how the reference may be used, not merely that it exists.
A bare ``<imageN>`` mention is enough to activate Qwen Image 2.1 reference
conditioning, but short prompts still tend to reproduce the source image.
Interior requests need an explicit camera relocation; otherwise the model
keeps the exterior view from the reference.
"""
if reference_count <= 0:
return prompt
markers = "、".join(f"<image{idx}>" for idx in range(1, reference_count + 1))
has_marker = bool(QWEN_IMAGE_MARKER.search(prompt))
if QWEN_COMPOSITION_LOCK.search(prompt):
return f"以{markers}为参考,按以下要求生成或编辑:{prompt}"
if QWEN_INTERIOR_INTENT.search(prompt):
reference = "参考图" if has_marker else markers
return (
f"{QWEN_INTERIOR_DIRECTIVE.format(reference=reference)}"
f"{QWEN_NEW_FRAME_DIRECTIVE}{prompt}"
)
return f"以{markers}为参考。{QWEN_NEW_FRAME_DIRECTIVE}按以下要求生成:{prompt}"
def _image_seed(request: AssetGenRequest) -> int:
"""Keep requests deterministic without reusing a seed across different prompts/references."""
if request.seed is not None:
return int(request.seed)
material = json.dumps({
"idempotency_key": request.idempotency_key,
"prompt": request.prompt,
"negative_prompt": request.negative_prompt,
"reference_images": request.reference_images,
"width": request.width,
"height": request.height,
}, ensure_ascii=False, sort_keys=True)
return int(hashlib.sha256(material.encode("utf-8")).hexdigest()[:12], 16)
def _fit_reference_canvas(source: str | Path, width: int, height: int,
target: str | Path) -> Path:
"""Re-frame the latent-driving reference to the requested output canvas.
ComfyUI's Qwen reference encoder derives ``latent_image`` from reference
image 1. Without this step a 3:4 portrait turns a requested 9:16 keyframe
into 3:4, regardless of the width/height fields in the workflow.
"""
source_path = Path(source)
target_path = Path(target)
source_w, source_h = ff.image_size(source_path)
if source_w == width and source_h == height:
return source_path
vf = (
f"scale={width}:{height}:force_original_aspect_ratio=increase:flags=lanczos,"
f"crop={width}:{height},setsar=1"
)
ff.run([
ff.FFMPEG, "-hide_banner", "-loglevel", "error", "-y",
"-i", str(source_path), "-vf", vf, "-frames:v", "1", str(target_path),
], timeout=120)
return target_path
def _fit_generated_canvas(path: str | Path, width: int, height: int) -> None:
"""Normalize model output to the exact project canvas.
Qwen's reference encoder can round latent dimensions down to its internal
grid (for example 720px becomes 704px). The project contract still requires
exact delivery dimensions, so crop/scale the downloaded result once.
"""
output = Path(path)
if ff.image_size(output) == (width, height):
return
fitted = output.with_name(f"{output.stem}.canvas{output.suffix}")
try:
_fit_reference_canvas(output, width, height, fitted)
fitted.replace(output)
finally:
fitted.unlink(missing_ok=True)
class ComfyImageProvider(ImageProviderAdapter):
_name = "comfyui_image"
@property
def name(self) -> str:
return self._name
def capabilities(self, config: dict | None = None) -> Capabilities:
return Capabilities(modes=("t2i", "edit"), resolutions=("1024p", "2k"),
aspect_ratios=("1:1", "16:9", "9:16", "4:3", "3:4"),
min_duration=0, max_duration=0, max_reference_images=10,
notes="Qwen-Image-2.1-Turbo 本地 GGUF;8 步蒸馏采样,支持参考图编辑")
_probe = _ProbeCache()
def is_available(self, config: dict | None = None) -> bool:
try:
base = _base(config or {})
except FatalProviderError:
return False
key = f"image|{base}"
cached = self._probe.get(key)
if cached is not None:
return cached
try:
ok = _probe_client().get(f"{base}/system_stats", timeout=5).status_code < 400
except httpx.HTTPError:
ok = False
self._probe.put(key, ok)
return ok
@classmethod
def invalidate_probes(cls, config: dict | None = None) -> None:
"""强制实探(模型中心「探测」按钮):清掉这条地址的缓存。"""
try:
cls._probe.invalidate(f"image|{_base(config or {})}")
except FatalProviderError:
cls._probe.invalidate()
@staticmethod
def graph(request: AssetGenRequest, config: dict, seed: int,
references: list[str] | None = None) -> dict[str, Any]:
width = max(256, min(2048, int(request.width or 1024) // 32 * 32))
height = max(256, min(2048, int(request.height or 1024) // 32 * 32))
refs = list(references if references is not None else request.reference_images)
refs = refs[:max(0, min(16, int(config.get("max_reference_images") or 10)))]
prefixes = {
"unet": "qwen-image-2.1-turbo-Q4_K_M.gguf",
"clip": "qwen3vl_8b_int8_convrot.safetensors",
"vae": "qwen_image_2.1_vae_bf16.safetensors",
}
prefixes.update(config.get("models") or {})
graph = {
"1": {"class_type": "UnetLoaderGGUF", "inputs": {"unet_name": prefixes["unet"]}},
"2": {"class_type": "CLIPLoader", "inputs": {
"clip_name": prefixes["clip"], "type": "qwen_image",
"device": str(config.get("clip_device") or "default")}},
"3": {"class_type": "VAELoader", "inputs": {"vae_name": prefixes["vae"]}},
"4": {"class_type": "TextEncodeQwenImage21", "inputs": {
"clip": ["2", 0], "prompt": _qwen_edit_prompt(request.prompt, len(refs)),
"negative_prompt": request.negative_prompt or "",
"resolution": int(config.get("encoder_resolution") or 1024),
"images": {}}},
"5": {"class_type": "EmptyLatentImage", "inputs": {
"width": width, "height": height, "batch_size": 1}},
"6": {"class_type": "QwenImage21Cache", "inputs": {
"model": ["1", 0], "device": str(config.get("cache_device") or "auto"),
"dtype": str(config.get("cache_dtype") or "default")}},
"7": {"class_type": "CFGGuider", "inputs": {
"model": ["6", 0], "positive": ["4", 0], "negative": ["4", 1],
"cfg": float(config.get("cfg") or 1.0)}},
"8": {"class_type": "RandomNoise", "inputs": {"noise_seed": seed}},
"9": {"class_type": "KSamplerSelect", "inputs": {
"sampler_name": str(config.get("sampler") or "euler")}},
"10": {"class_type": "ManualSigmas", "inputs": {
"sigmas": str(config.get("sigmas") or QWEN_SIGMAS)}},
"11": {"class_type": "SamplerCustomAdvanced", "inputs": {
"noise": ["8", 0], "guider": ["7", 0], "sampler": ["9", 0],
"sigmas": ["10", 0], "latent_image": ["5", 0]}},
"12": {"class_type": "VAEDecode", "inputs": {"samples": ["11", 0], "vae": ["3", 0]}},
"13": {"class_type": "SaveImage", "inputs": {
"images": ["12", 0],
"filename_prefix": str(config.get("filename_prefix") or "nex/asset")}},
}
if refs:
# Qwen Image 2.1 的参考图是 COMFY_AUTOGROW_V3。ComfyUI 3.x API
# 使用“父输入.槽位”的扁平键;嵌套字典会被解析为空参考集。
# 同时使用编码器的 latent 输出,让画布严格跟随第一张参考图。
for idx, reference in enumerate(refs):
node_id = f"2{idx + 1}"
graph[node_id] = {"class_type": "LoadImage", "inputs": {"image": reference}}
graph["4"]["inputs"][f"images.image_{idx + 1}"] = [node_id, 0]
graph["4"]["inputs"].pop("images", None)
graph["4"]["inputs"]["vae"] = ["3", 0]
graph["11"]["inputs"]["latent_image"] = ["4", 2]
return graph
def generate(self, request: AssetGenRequest, config: dict | None = None) -> AssetGenResult:
cfg = dict(config or {})
base = _base(cfg)
out = Path(request.output_path or Path(settings.media_root) / "comfyui" / "asset.png")
# 开工前探活:定妆图/场景图/关键帧是一次一笔的付费生成,服务没起时要在
# 几秒内失败并说清原因,而不是排到 GPU 锁后面才在上传阶段撞墙。
require_reachable(base, stage="图像生成开工前")
seed = _image_seed(request)
requested_w = max(256, min(2048, int(request.width or 1024)))
requested_h = max(256, min(2048, int(request.height or 1024)))
with tempfile.TemporaryDirectory(prefix="nex-qwen-ref-") as temp_dir:
source_refs = list(request.reference_images or [])
if source_refs:
source_refs[0] = str(_fit_reference_canvas(
source_refs[0], requested_w, requested_h,
Path(temp_dir) / "reference-canvas.png",
))
with gpu_slot(cfg, base), comfy_client(timeout=float(cfg.get("request_timeout") or 120),
config=cfg) as client:
references = [
upload_input(client, base, path, str(cfg.get("input_subfolder") or "nex_animation"),
f"参考图{idx + 1}")
for idx, path in enumerate(source_refs)
]
graph = self.graph(request, cfg, seed, references)
prompt_id = submit_graph(client, base, graph,
stable_client_id(request.idempotency_key or request.label or request.prompt),
idempotency_key=request.idempotency_key)
entry = wait_history(client, base, prompt_id, cfg)
item = first_output(entry, keys=("images",), suffixes=(".png", ".jpg", ".jpeg", ".webp"))
if not item:
raise RetryableProviderError("Qwen-Image 完成但没有图像产物", code="no_output_file")
download_output(client, base, item, out)
_fit_generated_canvas(out, requested_w, requested_h)
return AssetGenResult(file_path=str(out), provider_job_id=prompt_id,
metadata={"provider": "comfyui_image", "base_url": base, "seed": seed,
"workflow": "qwen_image_2_1_turbo",
"reference_images": references,
"comfy_output": f"{item.get('subfolder', '')}/{item['filename']}".strip("/")})
def diagnose(self, config: dict | None = None) -> dict:
return _diagnose(config or {}, required_nodes=(
"UnetLoaderGGUF", "CLIPLoader", "TextEncodeQwenImage21", "QwenImage21Cache",
"CFGGuider", "ManualSigmas", "SamplerCustomAdvanced", "LoadImage",
))
def _sample_rate(path: Path, fallback: int = 0) -> int:
"""读音频真实采样率;``ff.probe`` 的结构里没有这一项,只能直接问 ffprobe。"""
try:
proc = ff.run([ff.FFPROBE, "-v", "error", "-select_streams", "a:0",
"-show_entries", "stream=sample_rate", "-of", "default=nw=1:nk=1", str(path)],
timeout=60, check=False)
text = (proc.stdout or "").strip()
return int(text.splitlines()[0]) if text else fallback
except Exception: # noqa: BLE001 - 拿不到采样率就不调音
return fallback
def _atempo_chain(speed: float) -> str:
"""ffmpeg 的 atempo 只接受 0.5~2.0,超出范围要拆成多段串联。"""
value = max(0.25, min(float(speed or 1.0), 4.0))
factors: list[float] = []
while value > 2.0:
factors.append(2.0)
value /= 2.0
while value < 0.5:
factors.append(0.5)
value /= 0.5
factors.append(value)
return ",".join(f"atempo={factor:.4f}" for factor in factors)
def apply_voice_tuning(path: Path, *, speed: float = 1.0, pitch: float = 1.0,
volume: float = 1.0, sample_rate: int = 0) -> dict[str, Any]:
"""把声线面板上的语速/音调/音量真正落到音频文件上。
ComfyUI 的 ``easy indexTTSGenerateSimple`` 只吃 model/text/seed/参考音频,
压根没有 speed / pitch / volume 输入。所以这三项过去只是写进声线记录的装饰品:
用户把语速调到 1.3,成片里仍然是 1.0,听起来就是「模型没调校好」。
模型产出的是定采样率 WAV,转码之后用 ffmpeg 补齐:
asetrate 改音高(顺带改时长)→ aresample 复原采样率 →
atempo 把时长拉回目标语速 → volume 调增益。
"""
requested = {"speed": round(float(speed or 1.0), 3), "pitch": round(float(pitch or 1.0), 3),
"volume": round(float(volume or 1.0), 3)}
if all(abs(value - 1.0) < 0.01 for value in requested.values()):
return {}
if not ff.available():
return {"requested": requested, "applied": {},
"warning": "本机缺少 ffmpeg,语速/音调/音量未能应用"}
speed_v, pitch_v, volume_v = requested["speed"], requested["pitch"], requested["volume"]
rate = _sample_rate(path, fallback=int(sample_rate or 0)) or 24000
filters: list[str] = []
shift_pitch = abs(pitch_v - 1.0) >= 0.01
if shift_pitch:
filters.append(f"asetrate={rate}*{pitch_v:.4f},aresample={rate}")
effective_speed = speed_v / pitch_v if shift_pitch else speed_v
if abs(effective_speed - 1.0) >= 0.01:
filters.append(_atempo_chain(effective_speed))
if abs(volume_v - 1.0) >= 0.01:
filters.append(f"volume={volume_v:.3f}")
if not filters:
return {"requested": requested, "applied": {}}
tmp = path.with_name(f"{path.stem}.tuning{path.suffix or '.wav'}")
try:
ff.run([ff.FFMPEG, "-hide_banner", "-loglevel", "error", "-y", "-i", str(path),
"-af", ",".join(filters), "-ar", str(rate), "-ac", "1", str(tmp)], timeout=180)
tmp.replace(path)
except Exception as exc: # noqa: BLE001 - 调音失败不能废掉整条配音
tmp.unlink(missing_ok=True)
return {"requested": requested, "applied": {}, "warning": f"ffmpeg 调音失败:{str(exc)[:160]}"}
return {"requested": requested, "applied": {"sample_rate": rate, "filter": ",".join(filters)}}
class ComfyTTSProvider(VoiceProviderAdapter):
_name = "comfyui_tts"
@property
def name(self) -> str:
return self._name
def capabilities(self, config: dict | None = None) -> Capabilities:
return Capabilities(modes=("voice", "voice_clone"), resolutions=(), aspect_ratios=(),
min_duration=0, max_duration=0, max_reference_images=1,
notes="IndexTTS2 本地推理;使用参考音频做 zero-shot 音色克隆")
_probe = _ProbeCache()
def is_available(self, config: dict | None = None) -> bool:
try:
base = _base(config or {})
except FatalProviderError:
return False
key = f"tts|{base}"
cached = self._probe.get(key)
if cached is not None:
return cached
try:
client = _probe_client()
stats = client.get(f"{base}/system_stats")
if stats.status_code >= 400:
ok = False
else:
ok = True
for node in ("easy downloadIndexTTSAndLoadModel", "easy indexTTSGenerateSimple"):
resp = client.get(f"{base}/object_info/{quote(node, safe='')}")
if resp.status_code >= 400 or not (resp.json() or {}).get(node):
ok = False
break
except (httpx.HTTPError, ValueError):
ok = False
self._probe.put(key, ok)
return ok
@classmethod
def invalidate_probes(cls, config: dict | None = None) -> None:
try:
cls._probe.invalidate(f"tts|{_base(config or {})}")
except FatalProviderError:
cls._probe.invalidate()
@staticmethod
def graph(request: VoiceGenRequest, config: dict, seed: int, reference: str) -> dict[str, Any]:
loader = str(config.get("load_node") or "easy downloadIndexTTSAndLoadModel")
generate = str(config.get("generate_node") or "easy indexTTSGenerateSimple")
model_name = str(config.get("model") or "IndexTTS-2")
load_inputs: dict[str, Any] = {
"model": model_name,
"download_from": str(config.get("download_from") or "modelscope"),
}
load_inputs.update(config.get("load_inputs") or {})
generate_inputs: dict[str, Any] = {
"indextts_model": ["1", 0],
"text": request.text,
"reference_audio": ["2", 0],
"unload_model": False,
"seed": seed,
}
generate_inputs.update(config.get("generate_inputs") or {})
return {
"1": {"class_type": loader, "inputs": load_inputs},
"2": {"class_type": "LoadAudio", "inputs": {"audio": reference}},
"3": {"class_type": generate, "inputs": generate_inputs},
"4": {"class_type": "SaveAudio", "inputs": {
"audio": ["3", 0],
"filename_prefix": str(config.get("filename_prefix") or "audio/nex")}},
}
def synthesize(self, request: VoiceGenRequest, config: dict | None = None) -> VoiceGenResult:
cfg = dict(config or {})
base = _base(cfg)
out = Path(request.output_path or Path(settings.media_root) / "comfyui" / "voice.wav")
# 配音卡死最常见的形态就是「ComfyUI 没了,任务还在 running」:先探活,
# 连不上立刻失败(可重试),别让整条配音队列挂在同一个死地址上。
require_reachable(base, stage="配音开工前")
candidate = str(request.provider_voice_id or "").strip()
configured_reference = str(cfg.get("reference_audio") or "").strip()
audio_suffixes = {".wav", ".mp3", ".m4a", ".aac", ".flac", ".ogg", ".opus"}
# 声线记录里的 provider_voice_id 可能是旧版 UI 写入的显示名(如“低沉男声”),
# 不能把它当成 ComfyUI 输入文件。只在确实是音频路径时才覆盖模型默认参考音频。
if candidate and not (
Path(candidate).suffix.lower() in audio_suffixes or "/" in candidate or "\\" in candidate
):
candidate = ""
reference = candidate or configured_reference
# reference_source 会进配音记录:排查「全片都是同一个陌生人音色」时,
# 必须能一眼看出这条配音用的是角色自己的参考音频还是模型默认参考。
reference_source = "voice_asset" if candidate else "model_default"
if not reference:
raise FatalProviderError("IndexTTS2 需要参考音频:请给声线填写 provider_voice_id"
" 或给模型配置 reference_audio", code="missing_reference_audio")
seed = request.seed if request.seed is not None else int(
hashlib.sha256((request.idempotency_key or request.text).encode()).hexdigest()[:12], 16
)
# IndexTTS2 的 seed 输入是 32 位整数;哈希派生值可能达到 48 位。
seed = int(seed) % (2 ** 32)
with gpu_slot(cfg, base), comfy_client(timeout=float(cfg.get("request_timeout") or 120),
config=cfg) as client:
with network_guard(base, "读取节点清单"):
nodes = client.get(f"{base}/object_info", timeout=60)
raise_for(nodes, context="读取 ComfyUI 节点清单")
available_nodes = set((nodes.json() or {}).keys())
required = {str(cfg.get("load_node") or "easy downloadIndexTTSAndLoadModel"),
str(cfg.get("generate_node") or "easy indexTTSGenerateSimple")}
missing = sorted(required - available_nodes)
if missing:
raise FatalProviderError(
"ComfyUI 缺少 IndexTTS2 节点:" + "、".join(missing)
+ "。请在 9200 实例安装并启用对应的 IndexTTS 自定义节点后重试",
code="missing_comfy_node",
)
local = Path(reference).expanduser()
if not local.is_absolute():
# 声线引入项目后 provider_voice_id 存的是 media_root 下的相对路径。
local = Path(settings.media_root) / local
if local.exists():
reference = upload_input(client, base, str(local), str(cfg.get("input_subfolder") or "nex_animation"),
"参考音频", "audio/wav")
elif candidate and reference == candidate and configured_reference:
# 媒体被单独删除后,声线记录可能仍保留旧路径。不要让这个失效路径
# 覆盖模型默认参考音频,否则每次生成都会在 LoadAudio 校验阶段失败。
reference = configured_reference
reference_source = "model_default"
graph = self.graph(request, cfg, int(seed), reference)
prompt_id = submit_graph(client, base, graph,
stable_client_id(request.idempotency_key or request.label or request.text),
idempotency_key=request.idempotency_key)
entry = wait_history(client, base, prompt_id, cfg)
item = first_output(entry, keys=("audio", "audios", "files"),
suffixes=(".wav", ".flac", ".mp3", ".ogg", ".m4a"))
if not item:
raise RetryableProviderError("IndexTTS2 完成但没有音频产物", code="no_output_file")
download_output(client, base, item, out)
if out.suffix.lower() == ".wav" and out.read_bytes()[:4] != b"RIFF":
if not ff.available():
raise FatalProviderError("IndexTTS2 返回非 WAV 音频,且本机缺少 ffmpeg 转码",
code="ffmpeg_missing")
tmp = out.with_suffix(".source")
out.replace(tmp)
try:
ff.run([ff.FFMPEG, "-hide_banner", "-loglevel", "error", "-y", "-i", str(tmp),
"-ar", str(request.sample_rate or 24000), "-ac", "1", str(out)], timeout=180)
finally:
tmp.unlink(missing_ok=True)
# 声线面板上的语速/音调/音量必须真的落到文件上,否则用户改的只是数据库里的数字。
tuning = apply_voice_tuning(
out, speed=request.speed, pitch=request.pitch, volume=request.volume,
sample_rate=int(request.sample_rate or 0))
duration_ms = int(ff.duration_ms(out)) if ff.available() else 0
return VoiceGenResult(file_path=str(out), duration_ms=duration_ms, provider_job_id=prompt_id,
metadata={"provider": "comfyui_tts", "base_url": base, "seed": seed,
"reference_audio": reference,
"reference_source": reference_source,
"tuning": tuning,
"comfy_output": f"{item.get('subfolder', '')}/{item['filename']}".strip("/")})
def diagnose(self, config: dict | None = None) -> dict:
return _diagnose(config or {}, required_nodes=(
"easy downloadIndexTTSAndLoadModel", "easy indexTTSGenerateSimple",
"LoadAudio", "SaveAudio",
))
def _diagnose(config: dict, *, required_nodes: tuple[str, ...]) -> dict:
try:
base = _base(config)
except FatalProviderError as exc:
return {"available": False, "reachable": False, "message": exc.message,
"nodes": {}, "files": {}}
info: dict[str, Any] = {"base_url": base, "available": False, "reachable": False,
"message": ""}
try:
with comfy_client(timeout=float(config.get("probe_timeout") or 12), config=config) as client:
stats = client.get(f"{base}/system_stats")
raise_for(stats, context="读取 ComfyUI 状态")
objects = client.get(f"{base}/object_info", timeout=60).json()
queue = client.get(f"{base}/queue", timeout=20).json()
nodes = {node: node in objects for node in required_nodes}
missing = [node for node, ok in nodes.items() if not ok]
version = (stats.json().get("system") or {}).get("comfyui_version", "?")
info.update({
"available": not missing,
"reachable": True,
"message": f"ComfyUI {version}" + (
f";缺少节点:{'、'.join(missing)}" if missing else ""
),
"missing_nodes": missing,
"nodes": nodes,
"files": {
"unet": object_candidates(objects, "UnetLoaderGGUF", "unet_name"),
"clip": object_candidates(objects, "CLIPLoader", "clip_name"),
"vae": [f for f in object_candidates(objects, "VAELoader", "vae_name") if f != "pixel_space"],
"input_audio": object_candidates(objects, "LoadAudio", "audio"),
},
"queue": {"running": len(queue.get("queue_running") or []),
"pending": len(queue.get("queue_pending") or [])},
})
except Exception as exc:
info["message"] = diagnosis_message(base, exc, stage="读取状态/节点清单")
if is_network_error(exc):
info["reachable"] = False
return info