ComfyGen: shared generator tools (images, portraits, vintage, video, audio, voice)
Moved from YourlifeisGame/Spritegenerator; projects are found via _bootstrap.py (cwd or --project) and provide config.py plus list modules. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
122
generate_audio.py
Normal file
122
generate_audio.py
Normal file
@@ -0,0 +1,122 @@
|
||||
# Music + SFX generation via ComfyUI's Stable Audio pipeline (checkpoint
|
||||
# stable_audio_3_medium_base.safetensors). Same server as generate.py.
|
||||
# Results land in output/audio/. Usage:
|
||||
# python generate_audio.py # everything in audio_life.py
|
||||
# python generate_audio.py sfx_click # single entry
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen
|
||||
import config
|
||||
|
||||
HOST = "http://127.0.0.1:8188"
|
||||
OUT_DIR = os.path.join(config.OUTPUT_DIR, "audio")
|
||||
CLIP_NAME = "t5gemma_b_b_ul2.safetensors"
|
||||
|
||||
import importlib
|
||||
|
||||
|
||||
# Die Clip-Liste dieses Spiels: (name, prompt, seconds, negative) — siehe audio_life.py
|
||||
CLIPS = importlib.import_module(getattr(config, "AUDIO_MODULE", "audio_life")).CLIPS
|
||||
|
||||
|
||||
def build_graph(name, positive, negative, seconds, seed):
|
||||
return {
|
||||
"1": {"class_type": "CheckpointLoaderSimple",
|
||||
"inputs": {"ckpt_name": "stable_audio_3_medium_base.safetensors"}},
|
||||
"1c": {"class_type": "CLIPLoader",
|
||||
"inputs": {"clip_name": CLIP_NAME, "type": "stable_audio"}},
|
||||
"2": {"class_type": "CLIPTextEncode",
|
||||
"inputs": {"text": positive, "clip": ["1c", 0]}},
|
||||
"3": {"class_type": "CLIPTextEncode",
|
||||
"inputs": {"text": negative, "clip": ["1c", 0]}},
|
||||
"4": {"class_type": "ConditioningStableAudio",
|
||||
"inputs": {"positive": ["2", 0], "negative": ["3", 0],
|
||||
"seconds_start": 0.0, "seconds_total": seconds}},
|
||||
"5": {"class_type": "EmptyLatentAudio",
|
||||
"inputs": {"seconds": seconds, "batch_size": 1}},
|
||||
"6": {"class_type": "KSampler",
|
||||
"inputs": {"model": ["1", 0], "positive": ["4", 0], "negative": ["4", 1],
|
||||
"latent_image": ["5", 0], "seed": seed, "steps": 50,
|
||||
"cfg": 5.0, "sampler_name": "dpmpp_3m_sde",
|
||||
"scheduler": "exponential", "denoise": 1.0}},
|
||||
"7": {"class_type": "VAEDecodeAudio",
|
||||
"inputs": {"samples": ["6", 0], "vae": ["1", 2]}},
|
||||
"8": {"class_type": "SaveAudioMP3",
|
||||
"inputs": {"audio": ["7", 0], "filename_prefix": f"audio/{name}",
|
||||
"quality": "320k"}},
|
||||
}
|
||||
|
||||
|
||||
def submit(graph):
|
||||
req = urllib.request.Request(
|
||||
f"{HOST}/prompt",
|
||||
data=json.dumps({"prompt": graph}).encode(),
|
||||
headers={"Content-Type": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req) as res:
|
||||
return json.load(res)["prompt_id"]
|
||||
except urllib.error.HTTPError as error:
|
||||
# ComfyUI answers a bad graph with 400 and a body naming the node and
|
||||
# the field it did not like. Without printing it, every mistake in here
|
||||
# looks the same: "HTTP Error 400: Bad Request" and nothing to go on.
|
||||
body = error.read().decode("utf-8", "replace")
|
||||
print(f" rejected by ComfyUI: {body[:2000]}", flush=True)
|
||||
raise
|
||||
|
||||
|
||||
def wait_for(prompt_id, timeout=900):
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
with urllib.request.urlopen(f"{HOST}/history/{prompt_id}") as res:
|
||||
hist = json.load(res)
|
||||
if prompt_id in hist:
|
||||
entry = hist[prompt_id]
|
||||
status = entry.get("status", {})
|
||||
if status.get("status_str") == "error":
|
||||
for m in status.get("messages", []):
|
||||
if m[0] == "execution_error":
|
||||
raise RuntimeError(f"{m[1].get('node_type')}: {m[1].get('exception_message', '')[:400]}")
|
||||
raise RuntimeError("execution error")
|
||||
if status.get("completed") or entry.get("outputs"):
|
||||
return entry["outputs"]
|
||||
time.sleep(3)
|
||||
raise TimeoutError(prompt_id)
|
||||
|
||||
|
||||
def download(outputs):
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
saved = []
|
||||
for node_output in outputs.values():
|
||||
for audio in node_output.get("audio", []):
|
||||
params = urllib.parse.urlencode({
|
||||
"filename": audio["filename"],
|
||||
"subfolder": audio.get("subfolder", ""),
|
||||
"type": audio.get("type", "output"),
|
||||
})
|
||||
dest = os.path.join(OUT_DIR, audio["filename"].split("/")[-1])
|
||||
with urllib.request.urlopen(f"{HOST}/view?{params}") as res, open(dest, "wb") as f:
|
||||
f.write(res.read())
|
||||
saved.append(dest)
|
||||
return saved
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
only = set(sys.argv[1:])
|
||||
for name, positive, seconds, negative in CLIPS:
|
||||
if only and name not in only:
|
||||
continue
|
||||
seed = random.randint(0, 2**32 - 1)
|
||||
print(f"[{name}] queueing ({seconds:.0f}s, seed {seed})...", flush=True)
|
||||
pid = submit(build_graph(name, positive, negative, seconds, seed))
|
||||
outputs = wait_for(pid)
|
||||
for path in download(outputs):
|
||||
print(f"[{name}] saved -> {path}", flush=True)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user