I have a image generation program I made:
import websocket
import uuid
import json
import urllib.request
import urllib.parse
import random
import os
from pathlib import Path
from io import BytesIO
# Create generate_images folder if it doesn't exist
Path("generate_images").mkdir(exist_ok=True)
def load_workflow(self, workflow_path):
"""Load workflow JSON from file"""
with open(workflow_path, 'r') as f:
return json.load(f)
def queue_prompt(self, prompt):
"""Queue a prompt on the ComfyUI server"""
p = {"prompt": prompt, "client_id": self.client_id}
data = json.dumps(p).encode('utf-8')
req = urllib.request.Request(f"http://{self.server_address}/prompt", data=data)
return json.loads(urllib.request.urlopen(req).read())
def get_image(self, filename, subfolder, folder_type):
"""Get image data from the server"""
data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
url_values = urllib.parse.urlencode(data)
with urllib.request.urlopen(f"http://{self.server_address}/view?{url_values}") as response:
return response.read()
def get_history(self, prompt_id):
"""Get history data for a prompt"""
with urllib.request.urlopen(f"http://{self.server_address}/history/{prompt_id}") as response:
return json.loads(response.read())
def save_image(self, image_data, filename):
"""Save image data to file"""
output_path = Path("generate_images") / filename
with open(output_path, 'wb') as f:
f.write(image_data)
print(f"Image saved to: {output_path}")
def get_images(self, ws, prompt):
"""Get images using the history endpoint"""
prompt_id = self.queue_prompt(prompt)['prompt_id']
# Wait for execution to complete
while True:
out = ws.recv()
if isinstance(out, str):
message = json.loads(out)
if message['type'] == 'executing':
data = message['data']
if data['node'] is None and data['prompt_id'] == prompt_id:
break
else:
continue # Skip binary messages (previews)
# Get the images from history
history = self.get_history(prompt_id)[prompt_id]
output_images = {}
for node_id in history['outputs']:
node_output = history['outputs'][node_id]
images_output = []
if 'images' in node_output:
for image in node_output['images']:
image_data = self.get_image(
image['filename'],
image['subfolder'],
image['type']
)
images_output.append(image_data)
output_images[node_id] = images_output
return output_images, prompt_id
def generate_image(self, workflow_path, prompt_text, seed=None):
"""Generate an image using the workflow"""
# Load the workflow
workflow = self.load_workflow(workflow_path)
# Generate random seed if none provided
if seed is None:
seed = random.randint(0, 1000000000)
# Find the CLIPTextEncode node for positive prompt
for node_id, node in workflow.items():
if node.get("class_type") == "CLIPTextEncode" and \
"_meta" in node and \
"title" in node["_meta"] and \
"Positive" in node["_meta"]["title"]:
node["inputs"]["text"] = prompt_text
# Find the KSampler node to update the seed
for node_id, node in workflow.items():
if node.get("class_type") == "KSampler":
node["inputs"]["seed"] = seed
# Connect to websocket
ws = websocket.WebSocket()
ws.connect(f"ws://{self.server_address}/ws?clientId={self.client_id}")
try:
# Get images using history endpoint
images, prompt_id = self.get_images(ws, workflow)
# Save all generated images
for node_id, image_list in images.items():
for i, image_data in enumerate(image_list):
filename = f"generated_{seed}_{node_id}_{i}.png"
self.save_image(image_data, filename)
finally:
ws.close()
return seed
def main():
# Initialize the generator
generator = ComfyUIGenerator()
code
# Example prompts
prompts = [
"a beautiful landscape with mountains",
"a cyberpunk city at night",
"a serene beach at sunset",
"an enchanted forest with magical creatures"
]
# Generate multiple images with different prompts
workflow_path = "workflow.json" # Make sure this file exists
for prompt in prompts:
print(f"\nGenerating image for prompt: {prompt}")
try:
seed = generator.generate_image(workflow_path, prompt)
print(f"Generated image with seed: {seed}")
except Exception as e:
print(f"Error generating image for prompt '{prompt}': {str(e)}")
if name == "main":
main()
and I tried to implelment it here, but it get some issues:
[DEBUG] Updated CLIPTextEncode node (129) with prompt: A slender, shimmering snake wrapped around a miniature harmonica, its body glowing with an ethereal blue light as it blows out soulful blues riffs. The snake's eyes gleam with a mischievous spark, and it occasionally blows raspberries to punctuate its performances.
[DEBUG] Updated KSampler node (71) with seed: 373329289
[DEBUG] Connecting to websocket at ws://127.0.0.1:8188/ws?clientId=18467366-7df0-43a0-b2f7-c41d59716617
[DEBUG] Websocket connection established.
[DEBUG] Queuing prompt to http://127.0.0.1:8188/prompt: A slender, shimmering snake wrapped around a miniature harmonica, its body glowing with an ethereal blue light as it blows out soulful blues riffs. The snake's eyes gleam with a mischievous spark, and it occasionally blows raspberries to punctuate its performances.
[ERROR] Failed to queue prompt: HTTP Error 500: Internal Server Error
[ERROR] Error during image generation: HTTP Error 500: Internal Server Error
[DEBUG] Websocket connection closed.
[ERROR] Failed to generate images: Failed to generate image for prompt: A slender, shimmering snake wrapped around a miniature harmonica, its body glowing with an ethereal blue light as it blows out soulful blues riffs. The snake's eyes gleam with a mischievous spark, and it occasionally blows raspberries to punctuate its performances.
[DEBUG] Image generation task completed successfully.
can you help me find the issues and fix them:
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from moviepy.editor import (
TextClip,
ColorClip,
CompositeVideoClip,
ImageClip,
AudioFileClip,
concatenate_videoclips,
CompositeAudioClip
)
from moviepy.config import change_settings
import numpy as np
from PIL import Image, ImageDraw
import os
import subprocess
from pathlib import Path
import json
import urllib.request
import urllib.parse
import uuid
import random
import shutil
import datetime
import websocket
import re
import threading
import sys
---------------------- Text Generation ----------------------
def generate_would_you_rather():
import ollama
code
prompt = """Generate 6 funny and weird 'Would You Rather' choices.
Format each pair EXACTLY like this example:
CHOICE: eat a glowing mushroom
IMAGE: A luminescent blue mushroom radiating soft light in the darkness, sitting on a bed of moss with tiny sparkles emanating from its cap
VERSUS
CHOICE: drink liquid rainbow
IMAGE: A crystal glass filled with swirling, iridescent liquid that shifts through all colors of the spectrum, leaving trails of light as it moves
CHOICE: have clouds for shoes
IMAGE: Fluffy white cumulus clouds shaped like sneakers, floating inches above the ground, leaving behind small rainbows with each step
VERSUS
CHOICE: wear a hat made of living butterflies
IMAGE: A graceful arrangement of vibrant butterflies forming a crown-like hat, their wings gently fluttering in unison
Make each pair unique, weird, and entertaining. Write detailed image descriptions that would help create a clear visual."""
code
print("[DEBUG] Starting text generation using Ollama...")
try:
response = ollama.chat(model='llama3.2', messages=[
{'role': 'user', 'content': prompt}
])
generated_text = response['message']['content'].strip()
print("[DEBUG] Text generation successful.")
return generated_text
except Exception as e:
print(f"[ERROR] Text generation failed: {str(e)}")
raise
class ComfyUIGenerator:
def init(self, server_address="127.0.0.1:8188"):
self.server_address = server_address
self.client_id = str(uuid.uuid4())
print(f"[DEBUG] Initialized ComfyUIGenerator with client_id: {self.client_id}")
code
# Create generate_images folder if it doesn't exist
Path(GENERATED_IMAGES_DIR).mkdir(exist_ok=True)
print("[DEBUG] Ensured Generated Images Directory exists.")
def load_workflow(self, workflow_path):
"""Load workflow JSON from file"""
try:
with open(workflow_path, 'r') as f:
workflow = json.load(f)
print(f"[DEBUG] Loaded workflow from {workflow_path}")
return workflow
except Exception as e:
print(f"[ERROR] Failed to load workflow: {str(e)}")
raise
def queue_prompt(self, prompt):
"""Queue a prompt on the ComfyUI server"""
p = {"prompt": prompt, "client_id": self.client_id}
data = json.dumps(p).encode('utf-8')
req_url = f"http://{self.server_address}/prompt"
print(f"[DEBUG] Queuing prompt to {req_url}: {prompt}")
try:
req = urllib.request.Request(req_url, data=data, headers={'Content-Type':'application/json'})
response = urllib.request.urlopen(req).read()
response_json = json.loads(response)
print(f"[DEBUG] Prompt queued successfully with prompt_id: {response_json.get('prompt_id')}")
return response_json
except Exception as e:
print(f"[ERROR] Failed to queue prompt: {str(e)}")
raise
def get_image(self, filename, subfolder, folder_type):
"""Get image data from the server"""
data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
url_values = urllib.parse.urlencode(data)
url = f"http://{self.server_address}/view?{url_values}"
print(f"[DEBUG] Fetching image from URL: {url}")
try:
with urllib.request.urlopen(url) as response:
image_data = response.read()
print(f"[DEBUG] Image fetched successfully: {filename}")
return image_data
except Exception as e:
print(f"[ERROR] Failed to fetch image {filename}: {str(e)}")
raise
def get_history(self, prompt_id):
"""Get history data for a prompt"""
url = f"http://{self.server_address}/history/{prompt_id}"
print(f"[DEBUG] Fetching history from URL: {url}")
try:
with urllib.request.urlopen(url) as response:
history = json.loads(response.read())
print(f"[DEBUG] History fetched successfully for prompt_id: {prompt_id}")
return history
except Exception as e:
print(f"[ERROR] Failed to fetch history for prompt_id {prompt_id}: {str(e)}")
raise
def save_image(self, image_data, filename):
"""Save image data to file"""
output_path = Path(GENERATED_IMAGES_DIR) / filename
try:
with open(output_path, 'wb') as f:
f.write(image_data)
print(f"[DEBUG] Image saved to: {output_path}")
return str(output_path)
except Exception as e:
print(f"[ERROR] Failed to save image {filename}: {str(e)}")
raise
def get_images(self, ws, prompt_id):
"""Get images using the history endpoint"""
try:
history_response = self.get_history(prompt_id)
history = history_response.get(str(prompt_id))
if not history:
raise ValueError(f"No history found for prompt_id: {prompt_id}")
print(f"[DEBUG] Processing history for prompt_id: {prompt_id}")
output_images = {}
for node_id, node_output in history['outputs'].items():
images_output = []
if 'images' in node_output:
for image in node_output['images']:
image_data = self.get_image(
image['filename'],
image['subfolder'],
image['type']
)
images_output.append(image_data)
output_images[node_id] = images_output
return output_images, prompt_id
except Exception as e:
print(f"[ERROR] Failed to get images for prompt_id {prompt_id}: {str(e)}")
raise
def generate_image(self, workflow_path, prompt_text, seed=None):
"""Generate an image using the workflow"""
print("[DEBUG] Starting image generation...")
try:
# Load the workflow
workflow = self.load_workflow(workflow_path)
# Generate random seed if none provided
if seed is None:
seed = random.randint(0, 1000000000)
print(f"[DEBUG] Using seed: {seed}")
# Find the CLIPTextEncode node for positive prompt
for node_id, node in workflow.items():
if node.get("class_type") == "CLIPTextEncode" and \
"_meta" in node and \
"title" in node["_meta"] and \
"Positive" in node["_meta"]["title"]:
node["inputs"]["text"] = prompt_text
print(f"[DEBUG] Updated CLIPTextEncode node ({node_id}) with prompt: {prompt_text}")
# Find the KSampler node to update the seed
for node_id, node in workflow.items():
if node.get("class_type") == "KSampler":
node["inputs"]["seed"] = seed
print(f"[DEBUG] Updated KSampler node ({node_id}) with seed: {seed}")
# Connect to websocket
ws_url = f"ws://{self.server_address}/ws?clientId={self.client_id}"
print(f"[DEBUG] Connecting to websocket at {ws_url}")
ws = websocket.WebSocket()
ws.connect(ws_url)
print("[DEBUG] Websocket connection established.")
try:
# Queue the prompt and get prompt_id
response = self.queue_prompt(prompt_text)
prompt_id = response.get('prompt_id')
print(f"[DEBUG] Received prompt_id: {prompt_id}")
# Wait for the server to process the prompt and get images
images, prompt_id = self.get_images(ws, prompt_id)
# Save all generated images and collect paths
saved_image_paths = []
for node_id, image_list in images.items():
for i, image_data in enumerate(image_list):
filename = f"generated_{seed}_{node_id}_{i}.png"
image_path = self.save_image(image_data, filename)
saved_image_paths.append(image_path)
print(f"[DEBUG] Image generation completed successfully. Saved images: {saved_image_paths}")
return saved_image_paths
except Exception as e:
print(f"[ERROR] Error during image generation: {str(e)}")
return None
finally:
ws.close()
print("[DEBUG] Websocket connection closed.")
except Exception as e:
print(f"[ERROR] Failed to generate image: {str(e)}")
return None
Args:
text (str): Text to convert to speech
base_dir (str): Base directory where F5-TTS is installed
ref_audio (str): Path to reference audio file
output_dir (str): Directory to save output files
"""
print(f"[DEBUG] Starting TTS generation for text: {text}")
if ref_audio is None:
ref_audio = os.path.join(base_dir, "tests", "ref_audio", "tiktok.mp3")
print(f"[DEBUG] Using default reference audio: {ref_audio}")
# Create output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
print(f"[DEBUG] Ensured Voice Output Directory exists: {output_dir}")
# Reference text that matches your sample
ref_text = "Never go to school again. Or, Get paid to go to school. Be able to fly like a bird or be able to swim like a fish. Have a long but ordinary life or have a short but extraordinary life I love God or reject the offer have a ferrari."
# Build the command without extra quotes
cmd = [
"python", "inference-cli.py",
"--model", "F5-TTS",
"--ref_audio", ref_audio,
"--ref_text", ref_text,
"--gen_text", text,
"--output", "out.wav" # Ensures the output file is named consistently
]
print(f"[DEBUG] TTS Command: {' '.join(cmd)}")
try:
# Change to the base directory
original_dir = os.getcwd()
os.chdir(base_dir)
print(f"[DEBUG] Changed working directory to: {base_dir}")
# Path to the Python executable in the virtual environment
if os.name == 'nt': # Windows
python_executable = os.path.join(base_dir, "venv", "Scripts", "python.exe")
else: # Linux/Mac
python_executable = os.path.join(base_dir, "venv", "bin", "python")
print(f"[DEBUG] Python executable path: {python_executable}")
# Replace "python" with the virtual environment's Python
cmd[0] = python_executable
print(f"[DEBUG] Updated TTS Command with Python executable: {' '.join(cmd)}")
# Run the subprocess and capture output
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=False)
print(f"[DEBUG] TTS Subprocess completed with return code: {result.returncode}")
print(f"[DEBUG] Subprocess STDOUT: {result.stdout}")
print(f"[DEBUG] Subprocess STDERR: {result.stderr}")
if result.returncode != 0:
print(f"[ERROR] Error in TTS generation:\n{result.stderr}")
return None
# Path to the output file
output_file = os.path.join(base_dir, "out.wav")
if os.path.exists(output_file):
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
sanitized_text = "_".join(text.split())
sanitized_text = re.sub(r'[^a-zA-Z0-9_]', '', sanitized_text) # Remove invalid characters
new_filename = f"tts_output_{sanitized_text[:30]}_{timestamp}.wav" # Limit filename length
new_filepath = os.path.join(output_dir, new_filename)
shutil.move(output_file, new_filepath) # Use move to ensure the file is relocated
print(f"[DEBUG] Audio generated successfully: {new_filepath}")
return new_filepath
else:
print("[ERROR] Output file not found after TTS generation.")
print(f"[DEBUG] Subprocess Output:\n{result.stdout}\n{result.stderr}")
return None
except subprocess.CalledProcessError as e:
print(f"[ERROR] Command execution failed: {str(e)}")
return None
except Exception as e:
print(f"[ERROR] Error occurred during TTS generation: {str(e)}")
return None
finally:
# Return to original directory
os.chdir(original_dir)
print(f"[DEBUG] Returned to original directory: {original_dir}")
---------------------- Video Generation ----------------------
class WouldYouRatherGeneratorApp:
def init(self):
self.window = tk.Tk()
self.window.title("Would You Rather - All-in-One Generator")
self.window.geometry("800x900") # Increased height to accommodate all fields
code
# Video dimensions (9:16 ratio)
self.width = 1080
self.height = 1920
self.middle_y = self.height // 2
# Initialize ComfyUI Generator
self.comfyui = ComfyUIGenerator()
# Store generated media paths
self.choice_media = [] # List of dictionaries with 'choice1', 'image1', 'audio1', 'choice2', 'image2', 'audio2'
self.setup_ui()
def setup_ui(self):
main_frame = ttk.Frame(self.window, padding="20")
main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# Configure grid columns for consistent alignment
for i in range(4):
main_frame.columnconfigure(i, weight=1, pad=5)
# Text Generation Section
text_frame = ttk.LabelFrame(main_frame, text="Text Generation", padding="10")
text_frame.grid(row=0, column=0, columnspan=4, sticky=(tk.W, tk.E), pady=10)
self.generate_text_button = ttk.Button(
text_frame, text="Generate 'Would You Rather' Text", command=self.generate_text
)
self.generate_text_button.grid(row=0, column=0, padx=5, pady=5, sticky=tk.W)
self.text_output = tk.Text(text_frame, width=80, height=10, wrap=tk.WORD)
self.text_output.grid(row=1, column=0, padx=5, pady=5)
# Image Generation Section (Auto-generated)
image_frame = ttk.LabelFrame(main_frame, text="Image Generation", padding="10")
image_frame.grid(row=1, column=0, columnspan=4, sticky=(tk.W, tk.E), pady=10)
ttk.Label(image_frame, text="Choose Workflow File:").grid(row=0, column=0, sticky=tk.W, pady=5)
self.workflow_path_entry = ttk.Entry(image_frame, width=50)
self.workflow_path_entry.grid(row=0, column=1, padx=5, pady=5)
self.workflow_path_entry.insert(0, COMFYUI_WORKFLOW_PATH) # Updated path to home directory
ttk.Label(image_frame, text="Prompt File:").grid(row=1, column=0, sticky=tk.W, pady=5)
self.prompt_file_entry = ttk.Entry(image_frame, width=50)
self.prompt_file_entry.grid(row=1, column=1, padx=5, pady=5)
self.prompt_file_entry.insert(0, TEXT_OUTPUT_FILE) # Default path
self.generate_images_button = ttk.Button(
image_frame, text="Generate Images", command=self.generate_images
)
self.generate_images_button.grid(row=2, column=0, columnspan=2, pady=10)
# Voice Generation Section
voice_frame = ttk.LabelFrame(main_frame, text="Voice Generation", padding="10")
voice_frame.grid(row=2, column=0, columnspan=4, sticky=(tk.W, tk.E), pady=10)
ttk.Label(voice_frame, text="Text File:").grid(row=0, column=0, sticky=tk.W, pady=5)
self.voice_text_file_entry = ttk.Entry(voice_frame, width=50)
self.voice_text_file_entry.grid(row=0, column=1, padx=5, pady=5)
self.voice_text_file_entry.insert(0, TEXT_OUTPUT_FILE) # Default path
self.generate_voice_button = ttk.Button(
voice_frame, text="Generate Voice", command=self.generate_voice
)
self.generate_voice_button.grid(row=1, column=0, columnspan=2, pady=10)
# Video Generation Section
video_frame = ttk.LabelFrame(main_frame, text="Video Generation", padding="10")
video_frame.grid(row=3, column=0, columnspan=4, sticky=(tk.W, tk.E), pady=10)
# Removed Audio Files Directory Entry as it's redundant with choice_media mapping
self.generate_video_button = ttk.Button(
video_frame, text="Generate Video", command=self.generate_video
)
self.generate_video_button.grid(row=0, column=0, columnspan=2, pady=10)
def generate_text(self):
"""Generate 'Would You Rather' text pairs and display them."""
def task():
try:
self.generate_text_button.config(state=tk.DISABLED)
print("[DEBUG] Text generation started.")
text = generate_would_you_rather()
self.text_output.delete('1.0', tk.END)
self.text_output.insert(tk.END, text)
# Save to file
with open(TEXT_OUTPUT_FILE, 'w', encoding='utf-8') as f:
f.write(text)
print(f"[DEBUG] Generated text saved to {TEXT_OUTPUT_FILE}")
messagebox.showinfo("Success", "Text generation completed and saved.")
except Exception as e:
print(f"[ERROR] Failed to generate text: {str(e)}")
messagebox.showerror("Error", f"Failed to generate text: {str(e)}")
finally:
self.generate_text_button.config(state=tk.NORMAL)
print("[DEBUG] Text generation task completed.")
threading.Thread(target=task).start()
def generate_images(self):
"""Generate images based on the generated text."""
def task():
try:
self.generate_images_button.config(state=tk.DISABLED)
print("[DEBUG] Image generation started.")
# Read the text file and extract image descriptions
with open(self.prompt_file_entry.get(), 'r', encoding='utf-8') as f:
content = f.read()
print("[DEBUG] Read generated text for image prompts.")
# Parse the content to extract image descriptions
pattern = re.compile(
r'\d+\.\s+CHOICE:\s*(.*?)\s+IMAGE:\s*(.*?)\s+VERSUS\s+CHOICE:\s*(.*?)\s+IMAGE:\s*(.*?)\s*',
re.DOTALL
)
matches = pattern.findall(content)
if not matches:
raise ValueError("No valid 'Would You Rather' pairs found in the text file.")
print(f"[DEBUG] Found {len(matches)} 'Would You Rather' pairs for image generation.")
# Clear existing media mappings
self.choice_media.clear()
# Generate images for each pair's choices
for pair_idx, match in enumerate(matches):
choice1, image1_desc, choice2, image2_desc = match
print(f"[DEBUG] Generating image for Pair {pair_idx + 1}, Choice 1: {choice1}")
# List existing files before generation
before_files = set(os.listdir(GENERATED_IMAGES_DIR))
# Generate image for Choice 1
generated_paths1 = self.comfyui.generate_image(COMFYUI_WORKFLOW_PATH, image1_desc)
if generated_paths1:
seed1 = generated_paths1[0].split('_')[1] # Extract seed based on filename pattern
print(f"[DEBUG] Image generated for Choice 1 with seed: {seed1}")
else:
raise ValueError(f"Failed to generate image for prompt: {image1_desc}")
# List files after generation and find the new image
after_files = set(os.listdir(GENERATED_IMAGES_DIR))
new_files = after_files - before_files
image1_file = None
for file in new_files:
if f"generated_{seed1}_" in file:
image1_file = os.path.join(GENERATED_IMAGES_DIR, file)
break
if not image1_file:
raise ValueError(f"No image file found for Choice 1 with seed: {seed1}")
print(f"[DEBUG] Mapped image for Choice 1: {image1_file}")
print(f"[DEBUG] Generating image for Pair {pair_idx + 1}, Choice 2: {choice2}")
# List existing files before generation
before_files = set(os.listdir(GENERATED_IMAGES_DIR))
# Generate image for Choice 2
generated_paths2 = self.comfyui.generate_image(COMFYUI_WORKFLOW_PATH, image2_desc)
if generated_paths2:
seed2 = generated_paths2[0].split('_')[1] # Extract seed based on filename pattern
print(f"[DEBUG] Image generated for Choice 2 with seed: {seed2}")
else:
raise ValueError(f"Failed to generate image for prompt: {image2_desc}")
# List files after generation and find the new image
after_files = set(os.listdir(GENERATED_IMAGES_DIR))
new_files = after_files - before_files
image2_file = None
for file in new_files:
if f"generated_{seed2}_" in file:
image2_file = os.path.join(GENERATED_IMAGES_DIR, file)
break
if not image2_file:
raise ValueError(f"No image file found for Choice 2 with seed: {seed2}")
print(f"[DEBUG] Mapped image for Choice 2: {image2_file}")
# Append to choice_media with placeholders for audio
self.choice_media.append({
'choice1': choice1.strip(),
'image1': image1_file,
'audio1': None, # To be filled in generate_voice
'choice2': choice2.strip(),
'image2': image2_file,
'audio2': None # To be filled in generate_voice
})
print(f"[DEBUG] Image generation completed. Total pairs: {len(self.choice_media)}")
messagebox.showinfo("Success", "Image generation completed and saved.")
except Exception as e:
print(f"[ERROR] Failed to generate images: {str(e)}")
messagebox.showerror("Error", f"Failed to generate images: {str(e)}")
finally:
self.generate_images_button.config(state=tk.NORMAL)
print("[DEBUG] Image generation task completed successfully.")
threading.Thread(target=task).start()
def generate_voice(self):
"""Generate voice recordings for the choices."""
def task():
try:
self.generate_voice_button.config(state=tk.DISABLED)
print("[DEBUG] Voice generation started.")
# Ensure media mappings are present
if not self.choice_media:
raise ValueError("No choices available. Please generate images first.")
print(f"[DEBUG] Found {len(self.choice_media)} pairs in choice_media for voice generation.")
# Generate TTS for each choice and update choice_media
for pair_idx, media in enumerate(self.choice_media):
choice1 = media['choice1']
print(f"[DEBUG] Generating TTS for Pair {pair_idx + 1}, Choice 1: {choice1}")
audio1 = generate_tts(choice1)
if audio1:
media['audio1'] = audio1
print(f"[DEBUG] TTS generated and saved to: {audio1}")
else:
raise ValueError(f"Failed to generate audio for choice: {choice1}")
choice2 = media['choice2']
print(f"[DEBUG] Generating TTS for Pair {pair_idx + 1}, Choice 2: {choice2}")
audio2 = generate_tts(choice2)
if audio2:
media['audio2'] = audio2
print(f"[DEBUG] TTS generated and saved to: {audio2}")
else:
raise ValueError(f"Failed to generate audio for choice: {choice2}")
# Verify that all audio paths are filled
for idx, media in enumerate(self.choice_media):
if not media['audio1'] or not media['audio2']:
raise ValueError(f"Audio paths missing for Pair {idx + 1}")
print(f"[DEBUG] Voice generation completed for all choices.")
messagebox.showinfo("Success", "Voice generation completed and saved.")
except Exception as e:
print(f"[ERROR] Failed to generate voice: {str(e)}")
messagebox.showerror("Error", f"Failed to generate voice: {str(e)}")
finally:
self.generate_voice_button.config(state=tk.NORMAL)
print("[DEBUG] Voice generation task completed successfully.")
threading.Thread(target=task).start()
def generate_video(self):
"""Assemble the video with generated images and audio."""
def task():
try:
self.generate_video_button.config(state=tk.DISABLED)
print("[DEBUG] Video generation started.")
# Ensure that media has been generated
if not self.choice_media:
raise ValueError("No media available. Please generate images and voice first.")
print(f"[DEBUG] Found {len(self.choice_media)} pairs in choice_media.")
# Define desired duration for each video segment (in seconds)
desired_segment_duration = 5 # You can adjust this as needed
print(f"[DEBUG] Desired segment duration set to: {desired_segment_duration} seconds.")
# Start assembling video clips
clips = []
total_duration = 0
for idx, media in enumerate(self.choice_media):
print(f"[DEBUG] Creating video segment for Pair {idx + 1}.")
# Load images
img1_clip = ImageClip(media['image1']).resize(width=500).set_position(("center", self.height * 0.3))
img2_clip = ImageClip(media['image2']).resize(width=500).set_position(("center", self.height * 0.7))
# Load audio
audio1 = AudioFileClip(media['audio1']).volumex(0.5)
audio2 = AudioFileClip(media['audio2']).volumex(0.5)
# Pad audio to the desired duration
audio1 = audio1.set_duration(desired_segment_duration)
audio2 = audio2.set_duration(desired_segment_duration)
# Combine audio using CompositeAudioClip
combined_audio = CompositeAudioClip([audio1, audio2]).set_duration(desired_segment_duration)
# Create text clips
txt1 = TextClip(
media['choice1'].upper(),
fontsize=80,
color='white',
stroke_color='black',
stroke_width=2
).set_position(("center", self.height * 0.2)).set_duration(desired_segment_duration)
txt2 = TextClip(
media['choice2'].upper(),
fontsize=80,
color='white',
stroke_color='black',
stroke_width=2
).set_position(("center", self.height * 0.6)).set_duration(desired_segment_duration)
# Combine image and text
composite = CompositeVideoClip([img1_clip, img2_clip, txt1, txt2]).set_duration(desired_segment_duration)
# Set combined audio
composite = composite.set_audio(combined_audio)
clips.append(composite)
total_duration += desired_segment_duration
print(f"[DEBUG] Video segment {idx + 1} created successfully.")
# Concatenate all clips
final_clip = concatenate_videoclips(clips, method="compose")
final_clip = final_clip.set_duration(total_duration)
print("[DEBUG] All video segments concatenated successfully.")
# Export the video
print(f"[DEBUG] Exporting final video to: {VIDEO_OUTPUT_FILE}")
final_clip.write_videofile(
VIDEO_OUTPUT_FILE,
fps=30,
codec="libx264",
audio_codec="aac",
remove_temp=True,
threads=4,
preset="medium",
)
print("[DEBUG] Video exported successfully.")
messagebox.showinfo("Success", f"Video generated successfully!\nSaved to: {VIDEO_OUTPUT_FILE}")
print("[DEBUG] Video generation task completed successfully.")
except Exception as e:
print(f"[ERROR] Failed to generate video: {str(e)}")
messagebox.showerror("Error", f"Failed to generate video: {str(e)}")
finally:
self.generate_video_button.config(state=tk.NORMAL)
print("[DEBUG] Video generation task completed.")
threading.Thread(target=task).start()
def run(self):
self.window.mainloop()
---------------------- Main Execution ----------------------
if name == "main":
try:
app = WouldYouRatherGeneratorApp()
print("[DEBUG] Starting WouldYouRatherGenerator application.")
app.run()
except Exception as e:
print(f"[CRITICAL ERROR] Application failed to start: {str(e)}")
The HTTP 500 Internal Server Error you're encountering when queuing a prompt indicates that something is going wrong on the ComfyUI server side. This error typically means that the server encountered an unexpected condition that prevented it from fulfilling the request. Let's systematically identify and resolve the issues in your implementation.
1. Understanding the Core Issue
From your logs, the critical error is:
code
[ERROR] Failed to queue prompt: HTTP Error 500: Internal Server Error
This error occurs when your client attempts to send a prompt to the ComfyUI server via the /prompt endpoint. The underlying cause is likely related to how the workflow is being managed and sent to the server. Specifically:
Workflow Synchronization: Your client modifies the workflow locally but does not ensure that the ComfyUI server is aware of these changes.
Payload Structure: The JSON payload sent to the /prompt endpoint might not align with what the server expects.
Workflow Validity: The modified workflow may be invalid or incompatible with the server's processing logic.
2. Step-by-Step Troubleshooting and Fixes
A. Ensure Workflow is Properly Loaded on the Server
Issue: Your client modifies the workflow (workflow.json) locally but doesn't send this updated workflow to the ComfyUI server. The server likely operates with its own workflow configuration, unaware of the client's modifications, leading to inconsistencies and errors.
Solution:
Update the Server's Workflow: After modifying the workflow in your client, you need to ensure that the ComfyUI server is using this updated workflow.
ComfyUI's Workflow API: Check if ComfyUI provides an API endpoint to upload or update workflows. If such an endpoint exists, you can modify your ComfyUIGenerator class to upload the modified workflow before queuing the prompt.
Manual Workflow Update: If no API exists, consider manually updating the server's workflow.json with the modified workflow or configuring your setup so that both the client and server share the same workflow file (e.g., via a shared directory).
Implementation Example:
Assuming ComfyUI has an endpoint like /workflow to upload workflows, you can add a method to your ComfyUIGenerator to handle this:
python
def upload_workflow(self, workflow_path):
"""Upload modified workflow to the ComfyUI server."""
try:
with open(workflow_path, 'r') as f:
workflow_data = json.load(f)
data = json.dumps(workflow_data).encode('utf-8')
req_url = f"http://{self.server_address}/workflow"
print(f"[DEBUG] Uploading workflow to {req_url}")
req = urllib.request.Request(req_url, data=data, headers={'Content-Type':'application/json'})
response = urllib.request.urlopen(req).read()
response_json = json.loads(response)
print(f"[DEBUG] Workflow uploaded successfully.")
return response_json
except Exception as e:
print(f"[ERROR] Failed to upload workflow: {str(e)}")
raise
Then, modify your generate_image method to upload the workflow before queuing the prompt:
python
def generate_image(self, workflow_path, prompt_text, seed=None):
"""Generate an image using the workflow"""
print("[DEBUG] Starting image generation...")
try:
# Load the workflow
workflow = self.load_workflow(workflow_path)
# Generate random seed if none provided
if seed is None:
seed = random.randint(0, 1000000000)
print(f"[DEBUG] Using seed: {seed}")
# Update workflow nodes
for node_id, node in workflow.items():
if node.get("class_type") == "CLIPTextEncode" and \
"_meta" in node and \
"title" in node["_meta"] and \
"Positive" in node["_meta"]["title"]:
node["inputs"]["text"] = prompt_text
print(f"[DEBUG] Updated CLIPTextEncode node ({node_id}) with prompt: {prompt_text}")
for node_id, node in workflow.items():
if node.get("class_type") == "KSampler":
node["inputs"]["seed"] = seed
print(f"[DEBUG] Updated KSampler node ({node_id}) with seed: {seed}")
# Save the modified workflow temporarily
temp_workflow_path = "temp_workflow.json"
with open(temp_workflow_path, 'w') as f:
json.dump(workflow, f)
print(f"[DEBUG] Saved modified workflow to {temp_workflow_path}")
# Upload the modified workflow to the server
self.upload_workflow(temp_workflow_path)
# Connect to websocket
ws_url = f"ws://{self.server_address}/ws?clientId={self.client_id}"
print(f"[DEBUG] Connecting to websocket at {ws_url}")
ws = websocket.WebSocket()
ws.connect(ws_url)
print("[DEBUG] Websocket connection established.")
try:
# Queue the prompt and get prompt_id
response = self.queue_prompt(prompt_text)
prompt_id = response.get('prompt_id')
print(f"[DEBUG] Received prompt_id: {prompt_id}")
# Wait for the server to process the prompt and get images
images, prompt_id = self.get_images(ws, prompt_id)
# Save all generated images and collect paths
saved_image_paths = []
for node_id, image_list in images.items():
for i, image_data in enumerate(image_list):
filename = f"generated_{seed}_{node_id}_{i}.png"
image_path = self.save_image(image_data, filename)
saved_image_paths.append(image_path)
print(f"[DEBUG] Image generation completed successfully. Saved images: {saved_image_paths}")
return saved_image_paths
except Exception as e:
print(f"[ERROR] Error during image generation: {str(e)}")
return None
finally:
ws.close()
print("[DEBUG] Websocket connection closed.")
except Exception as e:
print(f"[ERROR] Failed to generate image: {str(e)}")
return None
Note: Replace "/workflow" with the actual endpoint provided by ComfyUI for uploading workflows. If such an endpoint doesn't exist, you may need to explore other methods to synchronize workflows between the client and server.
B. Validate the JSON Payload Structure
Issue: The JSON payload sent to the /prompt endpoint may not align with what ComfyUI expects, leading to server errors.
Solution:
Refer to ComfyUI Documentation: Ensure that the payload structure in the queue_prompt method matches the expected format as per ComfyUI's API documentation.
Validate JSON Fields: Confirm that all required fields are included and correctly named. For instance, some APIs might expect client_id, prompt, workflow, etc.
Test with Minimal Payload: Start by sending minimal valid payloads to ensure basic communication works, then incrementally add complexity.
Example Adjustment:
Suppose ComfyUI expects both prompt and workflow in the payload:
python
def queue_prompt(self, prompt):
"""Queue a prompt on the ComfyUI server"""
p = {
"prompt": prompt,
"client_id": self.client_id,
"workflow": "temp_workflow.json" # Or the actual workflow data
}
data = json.dumps(p).encode('utf-8')
req_url = f"http://{self.server_address}/prompt"
print(f"[DEBUG] Queuing prompt to {req_url}: {prompt}")
try:
req = urllib.request.Request(req_url, data=data, headers={'Content-Type':'application/json'})
response = urllib.request.urlopen(req).read()
response_json = json.loads(response)
print(f"[DEBUG] Prompt queued successfully with prompt_id: {response_json.get('prompt_id')}")
return response_json
except Exception as e:
print(f"[ERROR] Failed to queue prompt: {str(e)}")
raise
Action:
Verify Expected Fields: Check which fields ComfyUI expects in the /prompt API and ensure your payload includes them.
C. Check and Handle Server Logs
Issue: The HTTP 500 error could be due to a variety of internal server issues, and without detailed logs, it's challenging to pinpoint the exact cause.
Solution:
Access Server Logs: Look into the ComfyUI server's logs to identify the precise error message corresponding to the HTTP 500 response. This will provide insights into what went wrong.
Enable Verbose Logging: If the server supports it, increase the verbosity of the logs to capture more detailed information during the error.
Action:
Example Log Inspection:
If you're running the server locally, check the terminal or log files where ComfyUI outputs logs.
Look for stack traces or error messages that occur when the /prompt endpoint is hit.
D. Ensure Workflow Validity
Issue: The modified workflow may have inconsistencies, missing nodes, or incorrect configurations, causing the server to fail when processing the prompt.
Solution:
Validate JSON Syntax: Ensure that the workflow.json (or temp_workflow.json) is correctly formatted and free of syntax errors.
Check Node Configurations: Verify that all required nodes are present and correctly configured. For example, ensure that nodes like CLIPTextEncode and KSampler are correctly set up with all necessary inputs.
Test Workflow Independently: Before integrating with your application, test the workflow manually in ComfyUI to ensure it behaves as expected.
Action:
Use JSON Validators: Tools like JSONLint can help validate the structure of your JSON files.
Manual Testing: Load the modified workflow into ComfyUI manually and attempt to generate an image using the same prompts to see if it works without the client.
E. Refine get_images Method
Issue: The get_images method in your revised code might not correctly handle the interaction with the WebSocket, especially if the server's message structure has changed.
Solution:
Validate WebSocket Messages: Ensure that the messages received from the WebSocket are correctly parsed and that your method correctly identifies when the image generation is complete.
Handle Different Message Types: The server might send various types of messages. Ensure that your client gracefully handles unexpected message types.
Example Adjustment:
python
def get_images(self, ws, prompt_id):
"""Get images using the history endpoint"""
try:
# Queue the prompt via WebSocket
while True:
out = ws.recv()
if isinstance(out, str):
message = json.loads(out)
if message.get('type') == 'executing':
data = message.get('data', {})
if data.get('node') is None and data.get('prompt_id') == prompt_id:
break
# Optionally, add a timeout or max retries to prevent infinite loops
# Get the images from history
history = self.get_history(prompt_id)
output_images = {}
for node_id, node_output in history.get('outputs', {}).items():
images_output = []
if 'images' in node_output:
for image in node_output['images']:
image_data = self.get_image(
image['filename'],
image['subfolder'],
image['type']
)
images_output.append(image_data)
output_images[node_id] = images_output
return output_images, prompt_id
except Exception as e:
print(f"[ERROR] Failed to get images for prompt_id {prompt_id}: {str(e)}")
raise
Action:
Implement Timeouts: To prevent the client from hanging indefinitely if the server doesn't respond as expected, implement timeouts or maximum retry limits.
Debug Messages: Add more debug statements to capture the flow of messages received from the WebSocket.
F. Comprehensive Testing
After implementing the above fixes, perform comprehensive testing:
Unit Tests: Test individual components like workflow loading, prompt queuing, image fetching, etc., to ensure each part functions correctly.
Integration Tests: Test the complete flow from text generation to video creation to ensure all components work seamlessly together.
Error Handling: Intentionally induce errors (like invalid workflows or malformed prompts) to ensure your application gracefully handles them without crashing.
3. Enhanced Code with Fixes Applied
Below is the enhanced version of your ComfyUIGenerator class incorporating the discussed fixes:
python
4. Additional Recommendations
A. Use Robust Error Handling and Retries
Retries on Failures: Implement retry mechanisms for network requests in case of transient issues.
Graceful Degradation: Ensure that your application can handle partial failures without crashing.
B. Logging Enhancements
Detailed Logs: Incorporate more detailed logging, especially around network requests and responses.
Log Levels: Use different log levels (DEBUG, INFO, WARNING, ERROR, CRITICAL) to manage log verbosity effectively.
C. Configuration Management
Centralize Configurations: Manage server address, endpoints, and other configurations centrally, possibly using environment variables or a configuration file.
Validation: Validate configurations at startup to ensure all necessary parameters are set correctly.
D. Security Considerations
Input Sanitization: Ensure that all inputs, especially those that modify workflows or execute commands, are sanitized to prevent injection attacks.
Error Disclosure: Avoid exposing sensitive error details to end-users. Use logs for debugging while displaying user-friendly messages in the UI.
5. Conclusion
The primary issue stems from the workflow synchronization between the client and the ComfyUI server. By ensuring that the server is aware of any modifications made to the workflow and validating the structure of the JSON payloads, you can resolve the HTTP 500 error and achieve successful image generation. Additionally, enhancing your error handling, logging, and configuration management will lead to a more robust and maintainable application.
If after implementing these fixes you still encounter issues, please provide the specific error messages from the ComfyUI server logs. This information will be invaluable in diagnosing and resolving further issues.
import websocket
import uuid
import json
import urllib.request
import urllib.parse
import random
import os
from pathlib import Path
from io import BytesIO
class ComfyUIGenerator:
def __init__(self, server_address="127.0.0.1:8188"):
self.server_address = server_address
self.client_id = str(uuid.uuid4())
print(f"[DEBUG] Initialized ComfyUIGenerator with client_id: {self.client_id}")
# Create generate_images folder if it doesn't exist
Path(GENERATED_IMAGES_DIR).mkdir(exist_ok=True)
print("[DEBUG] Ensured Generated Images Directory exists.")
def load_workflow(self, workflow_path):
"""Load workflow JSON from file"""
try:
with open(workflow_path, 'r') as f:
workflow = json.load(f)
print(f"[DEBUG] Loaded workflow from {workflow_path}")
return workflow
except Exception as e:
print(f"[ERROR] Failed to load workflow: {str(e)}")
raise
def upload_workflow(self, workflow_path):
"""Upload modified workflow to the ComfyUI server."""
try:
with open(workflow_path, 'r') as f:
workflow_data = json.load(f)
data = json.dumps(workflow_data).encode('utf-8')
req_url = f"http://{self.server_address}/workflow" # Adjust endpoint as needed
print(f"[DEBUG] Uploading workflow to {req_url}")
req = urllib.request.Request(req_url, data=data, headers={'Content-Type':'application/json'})
response = urllib.request.urlopen(req).read()
response_json = json.loads(response)
print(f"[DEBUG] Workflow uploaded successfully.")
return response_json
except Exception as e:
print(f"[ERROR] Failed to upload workflow: {str(e)}")
raise
def queue_prompt(self, prompt):
"""Queue a prompt on the ComfyUI server"""
p = {"prompt": prompt, "client_id": self.client_id}
data = json.dumps(p).encode('utf-8')
req_url = f"http://{self.server_address}/prompt"
print(f"[DEBUG] Queuing prompt to {req_url}: {prompt}")
try:
req = urllib.request.Request(req_url, data=data, headers={'Content-Type':'application/json'})
response = urllib.request.urlopen(req).read()
response_json = json.loads(response)
print(f"[DEBUG] Prompt queued successfully with prompt_id: {response_json.get('prompt_id')}")
return response_json
except Exception as e:
print(f"[ERROR] Failed to queue prompt: {str(e)}")
raise
def get_image(self, filename, subfolder, folder_type):
"""Get image data from the server"""
data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
url_values = urllib.parse.urlencode(data)
url = f"http://{self.server_address}/view?{url_values}"
print(f"[DEBUG] Fetching image from URL: {url}")
try:
with urllib.request.urlopen(url) as response:
image_data = response.read()
print(f"[DEBUG] Image fetched successfully: {filename}")
return image_data
except Exception as e:
print(f"[ERROR] Failed to fetch image {filename}: {str(e)}")
raise
def get_history(self, prompt_id):
"""Get history data for a prompt"""
url = f"http://{self.server_address}/history/{prompt_id}"
print(f"[DEBUG] Fetching history from URL: {url}")
try:
with urllib.request.urlopen(url) as response:
history = json.loads(response.read())
print(f"[DEBUG] History fetched successfully for prompt_id: {prompt_id}")
return history
except Exception as e:
print(f"[ERROR] Failed to fetch history for prompt_id {prompt_id}: {str(e)}")
raise
def save_image(self, image_data, filename):
"""Save image data to file"""
output_path = Path(GENERATED_IMAGES_DIR) / filename
try:
with open(output_path, 'wb') as f:
f.write(image_data)
print(f"[DEBUG] Image saved to: {output_path}")
return str(output_path)
except Exception as e:
print(f"[ERROR] Failed to save image {filename}: {str(e)}")
raise
def get_images(self, ws, prompt_id):
"""Get images using the history endpoint"""
try:
# Wait for the server to process the prompt via WebSocket
while True:
out = ws.recv()
if isinstance(out, str):
message = json.loads(out)
if message.get('type') == 'executing':
data = message.get('data', {})
if data.get('node') is None and data.get('prompt_id') == prompt_id:
break
# Optionally, handle other message types or add a timeout
# Get the images from history
history = self.get_history(prompt_id)
output_images = {}
for node_id, node_output in history.get('outputs', {}).items():
images_output = []
if 'images' in node_output:
for image in node_output['images']:
image_data = self.get_image(
image['filename'],
image['subfolder'],
image['type']
)
images_output.append(image_data)
output_images[node_id] = images_output
return output_images, prompt_id
except Exception as e:
print(f"[ERROR] Failed to get images for prompt_id {prompt_id}: {str(e)}")
raise
def generate_image(self, workflow_path, prompt_text, seed=None):
"""Generate an image using the workflow"""
print("[DEBUG] Starting image generation...")
try:
# Load the workflow
workflow = self.load_workflow(workflow_path)
# Generate random seed if none provided
if seed is None:
seed = random.randint(0, 1000000000)
print(f"[DEBUG] Using seed: {seed}")
# Update workflow nodes
for node_id, node in workflow.items():
if node.get("class_type") == "CLIPTextEncode" and \
"_meta" in node and \
"title" in node["_meta"] and \
"Positive" in node["_meta"]["title"]:
node["inputs"]["text"] = prompt_text
print(f"[DEBUG] Updated CLIPTextEncode node ({node_id}) with prompt: {prompt_text}")
for node_id, node in workflow.items():
if node.get("class_type") == "KSampler":
node["inputs"]["seed"] = seed
print(f"[DEBUG] Updated KSampler node ({node_id}) with seed: {seed}")
# Save the modified workflow temporarily
temp_workflow_path = "temp_workflow.json"
with open(temp_workflow_path, 'w') as f:
json.dump(workflow, f)
print(f"[DEBUG] Saved modified workflow to {temp_workflow_path}")
# Upload the modified workflow to the server
self.upload_workflow(temp_workflow_path)
# Connect to websocket
ws_url = f"ws://{self.server_address}/ws?clientId={self.client_id}"
print(f"[DEBUG] Connecting to websocket at {ws_url}")
ws = websocket.WebSocket()
ws.connect(ws_url)
print("[DEBUG] Websocket connection established.")
try:
# Queue the prompt and get prompt_id
response = self.queue_prompt(prompt_text)
prompt_id = response.get('prompt_id')
print(f"[DEBUG] Received prompt_id: {prompt_id}")
# Wait for the server to process the prompt and get images
images, prompt_id = self.get_images(ws, prompt_id)
# Save all generated images and collect paths
saved_image_paths = []
for node_id, image_list in images.items():
for i, image_data in enumerate(image_list):
filename = f"generated_{seed}_{node_id}_{i}.png"
image_path = self.save_image(image_data, filename)
saved_image_paths.append(image_path)
print(f"[DEBUG] Image generation completed successfully. Saved images: {saved_image_paths}")
return saved_image_paths
except Exception as e:
print(f"[ERROR] Error during image generation: {str(e)}")
return None
finally:
ws.close()
print("[DEBUG] Websocket connection closed.")
except Exception as e:
print(f"[ERROR] Failed to generate image: {str(e)}")
return None