Commit ·
b39ef30
1
Parent(s): 53b61f6
Add ASR diagnostic workflow and deployment guide
Browse filesFiles changed (4)
1 unmodified line234567188 unmodified lines19619719819920020167 unmodified lines2692702712722732743 unmodified lines27827928028128228328494 unmodified lines3793803813823833843853861 unmodified line3883893903913923931 unmodified line3953963973983994001 unmodified lineimport jsonimport mathimport subprocessimport sysimport time188 unmodified linesif output_files:lines.append("outputs:")lines.extend(output_files)return lines67 unmodified lines}def prepare_runtime() -> str:global PREPARE_PROCESS3 unmodified linesreturn "\n".join(lines)BOOTSTRAP_LOG.parent.mkdir(parents=True, exist_ok=True)log = BOOTSTRAP_LOG.open("ab")command = [sys.executable, str(ROOT / "scripts" / "bootstrap_comfy.py")]PREPARE_PROCESS = subprocess.Popen(command,cwd=ROOT,94 unmodified linesreturn "\n".join(lines)with gr.Blocks(title="VoiceGate") as demo:gr.Markdown("# VoiceGate")with gr.Row():prepare_run = gr.Button("Prepare")prepare_status_run = gr.Button("Prepare Status")1 unmodified linecomfy_run = gr.Button("ComfyUI")melband_run = gr.Button("MelBand")voxcpm_run = gr.Button("VoxCPM TTS")output = gr.Textbox(label="Status", lines=28)prepare_run.click(fn=prepare_runtime, outputs=output)prepare_status_run.click(fn=prepare_status, outputs=output)1 unmodified linecomfy_run.click(fn=comfy_runtime_test, outputs=output)melband_run.click(fn=melband_gpu_test, outputs=output)voxcpm_run.click(fn=voxcpm_tts_gpu_test, outputs=output)if __name__ == "__main__":1 unmodified line2345678188 unmodified lines19719819920020120220320420520620720820921021121221367 unmodified lines2812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463 unmodified lines35035135235335435535694 unmodified lines4514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824831 unmodified line4854864874884894904911 unmodified line4934944954964974984991 unmodified lineimport jsonimport mathimport shutilimport subprocessimport sysimport time188 unmodified linesif output_files:lines.append("outputs:")lines.extend(output_files)text_outputs = []for node_output in outputs.values():for key in ("text", "string"):values = node_output.get(key, []) or []if isinstance(values, str):values = [values]text_outputs.extend(str(value) for value in values)if text_outputs:lines.append("text_outputs:")for value in text_outputs:lines.append(value[:2000])return lines67 unmodified lines}def copy_audio_to_comfy_input(audio_path: str | Path, prefix: str) -> str:source = Path(audio_path)if not source.exists():raise FileNotFoundError(f"Uploaded audio does not exist: {source}")suffix = source.suffix or ".wav"filename = f"{prefix}_{uuid.uuid4().hex[:8]}{suffix}"COMFY_INPUT_DIR.mkdir(parents=True, exist_ok=True)shutil.copyfile(source, COMFY_INPUT_DIR / filename)return filenamedef asr_workflow(audio_filename: str, prefix: str) -> dict[str, Any]:return {"1": {"class_type": "LoadAudio","inputs": {"audio": audio_filename, "audioUI": ""},},"2": {"class_type": "VoiceBridgeASRLoader","inputs": {"repo_id": "Qwen/Qwen3-ASR-1.7B","source": "HuggingFace","precision": "bf16","attention": "sdpa","max_new_tokens": 256,"forced_aligner": "Qwen/Qwen3-ForcedAligner-0.6B","local_model_path_asr": "","local_model_path_fa": "",},},"3": {"class_type": "VoiceBridgeASRTranscribe","inputs": {"model_key": ["2", 0],"audio": ["1", 0],"language": "auto","context": "","return_timestamps": True,},},"4": {"class_type": "GenerateSRT","inputs": {"forced_aligns": ["3", 0],"text": ["3", 1],"language": ["3", 2],"save_srt": True,"filename_prefix": f"VoiceBridge/{prefix}",},},"5": {"class_type": "easy showAnything","inputs": {"text": "","anything": ["4", 0],},},}def prepare_runtime() -> str:global PREPARE_PROCESS3 unmodified linesreturn "\n".join(lines)BOOTSTRAP_LOG.parent.mkdir(parents=True, exist_ok=True)log = BOOTSTRAP_LOG.open("ab")command = [sys.executable, str(ROOT / "scripts" / "bootstrap_comfy.py"), "--with-models"]PREPARE_PROCESS = subprocess.Popen(command,cwd=ROOT,94 unmodified linesreturn "\n".join(lines)@spaces.GPU(duration=1800)def asr_gpu_test(audio_path: str | None) -> str:lines = gpu_status_lines()started = time.time()try:if not audio_path:raise ValueError("Please upload an audio file before running ASR.")ensure_comfy(lines)prefix = f"asr_gpu_{uuid.uuid4().hex[:8]}"audio_filename = copy_audio_to_comfy_input(audio_path, prefix)lines.append(f"input_audio={audio_filename}")prompt_id = submit_prompt(asr_workflow(audio_filename, prefix))lines.append(f"prompt_id={prompt_id}")history = wait_for_history(prompt_id, timeout=1800)lines.extend(history_summary(history))lines.append(f"elapsed_sec={time.time() - started:.1f}")except Exception as exc:lines.append(f"error={type(exc).__name__}: {exc}")if COMFY_LOG.exists():lines.append("comfy_log_tail:")lines.extend(COMFY_LOG.read_text(encoding="utf-8", errors="replace").splitlines()[-180:])return "\n".join(lines)with gr.Blocks(title="VoiceGate") as demo:gr.Markdown("# VoiceGate")asr_audio = gr.Audio(label="ASR test audio", type="filepath")with gr.Row():prepare_run = gr.Button("Prepare")prepare_status_run = gr.Button("Prepare Status")1 unmodified linecomfy_run = gr.Button("ComfyUI")melband_run = gr.Button("MelBand")voxcpm_run = gr.Button("VoxCPM TTS")asr_run = gr.Button("ASR")output = gr.Textbox(label="Status", lines=28)prepare_run.click(fn=prepare_runtime, outputs=output)prepare_status_run.click(fn=prepare_status, outputs=output)1 unmodified linecomfy_run.click(fn=comfy_runtime_test, outputs=output)melband_run.click(fn=melband_gpu_test, outputs=output)voxcpm_run.click(fn=voxcpm_tts_gpu_test, outputs=output)asr_run.click(fn=asr_gpu_test, inputs=asr_audio, outputs=output)if __name__ == "__main__":
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372# 从零部署 ComfyUI Workflow 到 Hugging Face Space 的操作指南
本文是 VoiceGate 部署过程沉淀出来的通用指南。目标是:从一个本地ComfyUI workflow 出发,快速构建一个 Hugging Face Space,用 Gradio 做前端,用 ComfyUI 做后端,并尽量避开已经踩过的坑。
## 1. 先确定部署形态
推荐形态:
- Space SDK:Gradio。- GPU:ZeroGPU,适合按需调用。- ComfyUI:不要直接提交整个 ComfyUI 目录到 git。- Custom nodes:用 bootstrap 脚本按 pinned commit 拉取。- 大模型:放在 Space persistent storage,例如 `/data/project_models`。- Secrets:只放 Hugging Face Space Secrets,不写进代码或 workflow JSON。
不推荐:
- 把模型权重提交到 Space git。- 把 API key 写进 workflow。- 依赖 Dev Mode 里的手动修改作为最终状态。- 假设 SSH 能看到 ZeroGPU CUDA。
## 2. 创建 Space
在 Hugging Face 创建 Space:
- SDK 选择 `Gradio`。- Hardware 选择 ZeroGPU,例如 `zero-a10g`。- 如果需要持久化模型,开启 persistent storage。- 如果 Space 是组织名下项目,确认 token 有该组织的 Space 写权限。
本地登录:
```powershellhuggingface-cli loginhuggingface-cli whoami```
添加 Space git remote:
```powershellgit remote add space https://huggingface.co/spaces/<org>/<space-name>git push space main```
## 3. 推荐目录结构
```textproject-hf/|-- app.py|-- README.md|-- requirements.txt|-- packages.txt|-- scripts/| |-- bootstrap_comfy.py| |-- run_comfy.py| `-- workflow_client.py|-- workflows/| |-- workflow_api.json| `-- workflow_ui.json|-- docs/| |-- deployment-plan.md| |-- dependency-inventory.md| |-- ssh-runbook.md| |-- todo.md| `-- work-log.md`-- assets/```
本地可以保留上游项目 checkout,例如 `VoiceGate/`,但要加入 `.gitignore`。它只作为参考,不作为 Space runtime 内容。
## 4. 先做 workflow 和依赖盘点
从 ComfyUI 导出两个文件:
- API workflow:用于 `/prompt` 调用。- UI workflow:用于人工参考节点布局。
检查 API workflow:
```powershellpython -m json.tool workflows\workflow_api.json > $null```
列出所有 `class_type`:
```powershellpython -c "import json; w=json.load(open('workflows/workflow_api.json',encoding='utf-8')); print('\n'.join(sorted({v['class_type'] for v in w.values()})))"```
为每个 custom node 找到:
- GitHub repo URL。- 可用 commit。- requirements.txt。- 额外系统包。- 模型路径约定。
把这些写进 `docs/dependency-inventory.md`。
## 5. 写 bootstrap 脚本
`scripts/bootstrap_comfy.py` 应该是幂等的:
- 如果 ComfyUI 不存在,clone。- 如果 custom node 不存在,clone。- 每个 repo checkout 到固定 commit。- 安装 ComfyUI requirements。- 安装 custom node requirements。- 创建模型目录和 symlink。- 可选下载模型。
模型不要默认每次下载。建议做成:
```bashpython scripts/bootstrap_comfy.pypython scripts/bootstrap_comfy.py --with-models```
持久化模型路径建议:
```text/data/project_models```
再 symlink 到 ComfyUI 需要的位置,例如:
```textComfyUI/models/voxcpm/VoxCPM2 -> /data/project_models/voxcpm/VoxCPM2```
## 6. 写最小 Gradio 入口
ZeroGPU Space 启动时必须能发现至少一个 `@spaces.GPU` 函数,否则可能报:
```textNo @spaces.GPU function detected during startup```
最小形式:
```pythonimport gradio as grimport spacesimport torch
@spaces.GPU(duration=60)def gpu_smoke_test(): return f"cuda_available={torch.cuda.is_available()}"
with gr.Blocks() as demo: button = gr.Button("GPU") output = gr.Textbox() button.click(gpu_smoke_test, outputs=output)
demo.launch()```
先推送这个版本,确认 Space 能运行。
## 7. 正确理解 ZeroGPU、SSH、Dev Mode
关键结论:
- SSH 只适合诊断容器文件和 CPU 模式。- SSH 里通常看不到 ZeroGPU CUDA。- 真正的 GPU 工作必须从 Gradio 的 `@spaces.GPU(...)` 函数触发。- Dev Mode 开启后,运行容器可能停留在旧 commit。
SSH 只在 Dev Mode 开启时可用:
```powershellssh -i "$env:USERPROFILE\.ssh\<key_name>" <space-user>@ssh.hf.space```
如果 Space 一直不更新到最新 commit:
- 关闭 Dev Mode。- push 一个新 commit 或 factory reboot。- 用 HF API 确认 runtime sha。
## 8. 不要在 Gradio 请求里同步做重 bootstrap
踩过的坑:
```textGradio click -> bootstrap_comfy.py -> clone -> pip install -> start ComfyUI```
这种请求可能在几分钟后被外层 queue 中断,只看到:
```textevent: errordata: {"error": null}```
推荐:
- `Prepare` 按钮:非 GPU,启动后台 bootstrap 进程。- `Prepare Status` 按钮:读取 `/tmp/bootstrap.log`。- GPU 按钮:只启动 ComfyUI、���交 workflow、等待结果。
这样不会把 ZeroGPU 时间浪费在安装依赖上,也更容易看到真实错误。
## 9. 启动 ComfyUI 并通过 API 测试
ComfyUI 启动命令:
```bashpython main.py --listen 127.0.0.1 --port 8188```
先测:
```textGET /system_stats```
再测最小 workflow:
```textLoadAudio -> SaveAudioMP3```
常用 API:
- `POST /upload/image`:上传 input 文件,音频也可用这个入口。- `POST /prompt`:提交 API workflow。- `GET /history/{prompt_id}`:取执行结果。
音频上传要注意二进制安全。不要用会破坏字节流的 PowerShell 文本管道。上传后最好校验 sha256 或至少确认 `file` 识别为音频。
## 10. 分阶段测试 workflow
不要一上来跑完整 workflow。推荐顺序:
1. GPU smoke test:确认 CUDA 可用。2. ComfyUI runtime test:确认 `@spaces.GPU -> ComfyUI -> /system_stats`。3. Load/Save audio:确认 ComfyUI API 和音频文件路径。4. LLM-only:确认 secret 和外部 API。5. MelBand-only:确认模型加载和音频输出。6. TTS-only:确认 TTS 模型能进 GPU。7. ASR-only:确认 ASR 模型、aligner、SRT 输出。8. SRT split/merge。9. 完整短音频 workflow。10. 最后再做正式 Gradio UI。
每一步都要记录:
- 输入文件。- prompt id。- status_str。- outputs。- elapsed_sec。- 错误日志尾部。
## 11. Secrets 的安全配置
API key 放在 HF Space Secrets,例如:
```textDEEPSEEK_API_KEY```
代码里只读环境变量:
```pythonimport osapi_key = os.environ.get("DEEPSEEK_API_KEY")```
不要打印 key。检查时只输出:
- 是否存在。- 长度。- 前后缀也尽量不要输出。
## 12. 常见坑和解决办法
### `No @spaces.GPU function detected`
原因:ZeroGPU Space 启动时没有发现 `@spaces.GPU`。
解决:在 `app.py` 保留至少一个 GPU 函数。
### SSH 里 `torch.cuda.is_available()` 是 False
这是正常的。SSH 不代表 ZeroGPU 执行环境。
解决:从 Gradio `@spaces.GPU` 函数里测 CUDA。
### Dev Mode 里代码不是最新
Dev Mode 容器可能停留在旧 commit。
解决:关闭 Dev Mode,重新 rebuild,或 push 新 commit。
### Custom node import failed
先看 ComfyUI 启动日志,通常是缺 Python 包或系统包。
VoiceGate 遇到过:
```textSoX could not be foundModuleNotFoundError: sounddeviceOSError: PortAudio library not foundModuleNotFoundError: easydictModuleNotFoundError: pytorch_lightning```
对应修复:
```textpackages.txt: sox, libportaudio2, portaudio19-devrequirements.txt: sounddevice, easydict, pytorch-lightning```
### Runtime pip install 改变 torch 版本
如果 Gradio 进程已经 import torch,再在运行时 pip install/upgrade torch,Gradio 进程和后续子进程可能看到不同 torch 版本。
解决:生产版本尽量把重依赖放进 build 阶段,并显式 pin 版本。
### 模型下载 CLI 不稳定
`huggingface-cli download` 或 `hf download` 可能因为版本兼容问题失败。
解决:用 `huggingface_hub` 的 Python API 下载模型。
### TTS/ASR 冷启动很慢
大模型第一次加载会非常慢。VoiceGate 的 VoxCPM2 TTS-only 冷启动约 766 秒。
解决方向:
- 缩短测试文本。- 避免每个 GPU 调用重复启动 ComfyUI。- 尽量复用模型进程。- 先做子流程验证,再优化 UX。
## 13. 最终正式化建议
诊断阶段可以把很多按钮放在 `app.py` 里。正式阶段建议拆分:
```textapp.pyscripts/bootstrap_comfy.pyvoicegate_runtime/|-- comfy_server.py|-- workflows.py|-- files.py`-- ui.py```
正式 Gradio UI 至少提供:
- 音频上传。- 目标语言。- 运行状态。- 生成音频下载。- SRT 下载。- 错误日志摘要。- 文件类型和时长限制。
先限制短音频,等完整链路稳定后再支持视频和更长输入。18 unmodified lines192021222324136 unmodified lines16116216316416516614 unmodified lines18118218318418518618 unmodified linesDo not commit API keys, model weights, uploaded media, generated outputs, or thelocal `VoiceGate/` upstream checkout.## Repository Setup Completed- Created and pushed the Space wrapper repository.136 unmodified lines...```### SSH Does Not Expose ZeroGPU CUDAStarting ComfyUI normally through SSH failed with:14 unmodified linespython scripts/run_comfy.py --cpu```## Dependency Pitfalls and Fixes`ComfyUI_AudioTools` initially failed to import.18 unmodified lines1920212223242526272829303132333435363738394041424344454647484950136 unmodified lines18718818919019119219319419519619719819920020120220320414 unmodified lines21922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927018 unmodified linesDo not commit API keys, model weights, uploaded media, generated outputs, or thelocal `VoiceGate/` upstream checkout.## Executive SummaryThe Space is no longer just a blank scaffold. It can now run Gradio, invokeZeroGPU, prepare a ComfyUI runtime, start ComfyUI from a GPU-backed Gradiofunction, and submit several segmented ComfyUI workflows.Confirmed working:- Hugging Face Space git push and normal rebuild flow.- Dev Mode SSH for CPU/container diagnostics.- ZeroGPU invocation from Gradio through `@spaces.GPU`.- ComfyUI startup from inside a `@spaces.GPU` function.- ComfyUI API calls from the Gradio process.- DeepSeek-compatible LLM node with the Space secret.- MelBand RoFormer smoke tests in CPU mode and ZeroGPU mode.- VoxCPM2 TTS-only smoke test in ZeroGPU mode.- Persistent model storage for VoxCPM2 and MelBand under `/data`.Not yet confirmed at the start of 2026-06-06:- VoiceBridge ASR-only workflow.- Qwen ASR and Qwen forced aligner model download/cache behavior in the Space.- SRT split -> VoxCPM -> SRT merge.- Full short-audio VoiceGate workflow.- Final user-facing Gradio upload/download UI.## Repository Setup Completed- Created and pushed the Space wrapper repository.136 unmodified lines...```Later this placeholder was replaced by real diagnostic functions:```python@spaces.GPU(duration=60)def gpu_smoke_test():...@spaces.GPU(duration=900)def comfy_runtime_test():...```### SSH Does Not Expose ZeroGPU CUDAStarting ComfyUI normally through SSH failed with:14 unmodified linespython scripts/run_comfy.py --cpu```### Gradio Request Timeout During BootstrapLong bootstrap work should not run synchronously inside a Gradio request. Thefirst attempt did this:```textGradio click -> bootstrap_comfy.py -> clone repos -> pip install -> start ComfyUI```The request was interrupted by Gradio/ZeroGPU's outer queue after roughly 2.5minutes and returned:```textevent: errordata: {"error": null}```Fix:- Add a non-GPU `Prepare` action that starts `scripts/bootstrap_comfy.py` as abackground process.- Add `Prepare Status` to poll `/tmp/voicegate_bootstrap.log`.- Keep GPU actions focused on starting ComfyUI and running actual CUDA work.This avoids wasting ZeroGPU time on clone/install steps and prevents the requestfrom being killed before diagnostics can return useful logs.### Runtime Pip Install PitfallThe background bootstrap installed a large dependency set and upgraded theon-disk Torch package. The already-running Gradio process continued to report:```texttorch=2.11.0+cu130```while the ComfyUI subprocess started afterwards reported:```textpytorch_version=2.12.0+cu130```This is workable for diagnostics, but final production should avoid heavyruntime `pip install` where possible. Prefer moving stable dependencies intoSpace build-time requirements or explicitly controlling pins.## Dependency Pitfalls and Fixes`ComfyUI_AudioTools` initially failed to import.
94 unmodified lines959697989910010110210310410591 unmodified lines1971981992002012029 unmodified lines21221321421521621794 unmodified linesMODEL_LINKS = {"voxcpm2": COMFY_DIR / "models" / "voxcpm" / "VoxCPM2","melband": COMFY_DIR / "models" / "diffusion_models" / "MelBandRoFormer_comfy",}MODEL_DIRS = {"voxcpm2": Path("voxcpm") / "VoxCPM2","melband": Path("diffusion_models") / "MelBandRoFormer_comfy",}91 unmodified lines"+ hf_hub_download "f"Kijai/MelBandRoFormer_comfy/MelBandRoformer_fp32.safetensors -> {model_target('melband')}")returnfrom huggingface_hub import hf_hub_download, snapshot_download9 unmodified lineslocal_dir=model_target("melband"),token=token,)def print_summary() -> None:94 unmodified lines959697989910010110210310410510610791 unmodified lines1992002012022032042052062072082099 unmodified lines21922022122222322422522622722822923023123223323494 unmodified linesMODEL_LINKS = {"voxcpm2": COMFY_DIR / "models" / "voxcpm" / "VoxCPM2","melband": COMFY_DIR / "models" / "diffusion_models" / "MelBandRoFormer_comfy","qwen3_asr": COMFY_DIR / "models" / "Qwen3-ASR",}MODEL_DIRS = {"voxcpm2": Path("voxcpm") / "VoxCPM2","melband": Path("diffusion_models") / "MelBandRoFormer_comfy","qwen3_asr": Path("Qwen3-ASR"),}91 unmodified lines"+ hf_hub_download "f"Kijai/MelBandRoFormer_comfy/MelBandRoformer_fp32.safetensors -> {model_target('melband')}")print(f"+ snapshot_download Qwen/Qwen3-ASR-1.7B -> {model_target('qwen3_asr') / 'Qwen3-ASR-1.7B'}")print("+ snapshot_download "f"Qwen/Qwen3-ForcedAligner-0.6B -> {model_target('qwen3_asr') / 'Qwen3-ForcedAligner-0.6B'}")returnfrom huggingface_hub import hf_hub_download, snapshot_download9 unmodified lineslocal_dir=model_target("melband"),token=token,)snapshot_download(repo_id="Qwen/Qwen3-ASR-1.7B",local_dir=model_target("qwen3_asr") / "Qwen3-ASR-1.7B",token=token,)snapshot_download(repo_id="Qwen/Qwen3-ForcedAligner-0.6B",local_dir=model_target("qwen3_asr") / "Qwen3-ForcedAligner-0.6B",token=token,)def print_summary() -> None:
app.py+100-1
docs/hf-space-comfyui-step-by-step.zh.mdAdded+372
docs/work-log.md+84
scripts/bootstrap_comfy.py+17