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

class ComfyUIGenerator:
    def __init__(self, server_address="127.0.0.1:8188"):
        self.server_address = server_address
        self.client_id = str(uuid.uuid4())
        
        # 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()
    
    # 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

# ---------------------- Configuration ----------------------

# ImageMagick configuration (Ensure this path is correct for your system)
change_settings(
    {"IMAGEMAGICK_BINARY": r"C:\Program Files\ImageMagick-7.1.1-Q16-HDRI\magick.exe"}
)

# Paths for various components
BASE_DIR = os.path.abspath("would_you_rather_project")
TEXT_OUTPUT_FILE = os.path.join(BASE_DIR, "would_you_rather.txt")
GENERATED_IMAGES_DIR = os.path.join(BASE_DIR, "generate_images")
VOICE_OUTPUT_DIR = os.path.join(BASE_DIR, "generated_audio")
VIDEO_OUTPUT_FILE = os.path.join(BASE_DIR, "would_you_rather.mp4")

# Updated workflow path to home directory
COMFYUI_WORKFLOW_PATH = os.path.join("workflow.json")  # Updated path

F5_TTS_BASE_DIR = r"C:\Users\theod\Desktop\AI\text2voice\F5-TTS"  # Update as needed

# Ensure necessary directories exist
os.makedirs(BASE_DIR, exist_ok=True)
os.makedirs(GENERATED_IMAGES_DIR, exist_ok=True)
os.makedirs(VOICE_OUTPUT_DIR, exist_ok=True)

# ---------------------- Text Generation ----------------------

def generate_would_you_rather():
    import ollama

    prompt = """Generate 6 funny and weird 'Would You Rather' choices. 
Format each pair EXACTLY like this example:

1.
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

2.
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."""

    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

# ---------------------- Image Generation ----------------------

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 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

# ---------------------- Voice Generation ----------------------

def generate_tts(text, base_dir=F5_TTS_BASE_DIR, ref_audio=None, output_dir=VOICE_OUTPUT_DIR):
    """
    Generate TTS audio using F5-TTS model.
    
    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

        # 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)}")