I want a full ready would you rather generator. for that combind all the files I made.
here is the first file I made, its called 16.py and its for the video generation:
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from moviepy.editor import (
TextClip,
ColorClip,
CompositeVideoClip,
ImageClip,
)
from moviepy.config import change_settings
import numpy as np
from PIL import Image, ImageDraw
import os
Configure ImageMagick (Ensure this path is correct for your system)
class WouldYouRatherGenerator:
def init(self):
self.window = tk.Tk()
self.window.title("Would You Rather Generator")
self.window.geometry("800x700") # Increased height to accommodate new field
code
Assistant
# Video dimensions (9:16 ratio)
self.width = 1080
self.height = 1920
self.middle_y = self.height // 2
# Store image paths
self.image1_path = None # Top image (Black socks)
self.image2_path = None # Bottom image (White socks)
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)
# Option 1 Section (Top Half - Black Socks)
option1_frame = ttk.LabelFrame(main_frame, text="Option 1 (Black Socks)", padding="10")
option1_frame.grid(row=0, column=0, columnspan=4, sticky=(tk.W, tk.E), pady=10)
ttk.Label(option1_frame, text="Text:").grid(row=0, column=0, sticky=tk.W, pady=5)
self.option1_text = ttk.Entry(option1_frame, width=50)
self.option1_text.grid(row=0, column=1, columnspan=2, sticky=(tk.W, tk.E), pady=5)
self.option1_text.insert(0, "SCHWARZE SOCKEN") # Default text
ttk.Label(option1_frame, text="Image:").grid(row=1, column=0, sticky=tk.W, pady=5)
self.image1_label = ttk.Label(option1_frame, text="No image selected")
self.image1_label.grid(row=1, column=1, sticky=tk.W, pady=5)
ttk.Button(
option1_frame, text="Browse...", command=lambda: self.select_image(1)
).grid(row=1, column=2, padx=5, pady=5)
ttk.Label(option1_frame, text="Percentage:").grid(row=2, column=0, sticky=tk.W, pady=5)
self.percent1 = ttk.Entry(option1_frame, width=10)
self.percent1.grid(row=2, column=1, sticky=tk.W, pady=5)
self.percent1.insert(0, "1,02%") # Default percentage
# Option 2 Section (Bottom Half - White Socks)
option2_frame = ttk.LabelFrame(main_frame, text="Option 2 (White Socks)", padding="10")
option2_frame.grid(row=1, column=0, columnspan=4, sticky=(tk.W, tk.E), pady=10)
ttk.Label(option2_frame, text="Text:").grid(row=0, column=0, sticky=tk.W, pady=5)
self.option2_text = ttk.Entry(option2_frame, width=50)
self.option2_text.grid(row=0, column=1, columnspan=2, sticky=(tk.W, tk.E), pady=5)
self.option2_text.insert(0, "WEIßE SOCKEN") # Default text
ttk.Label(option2_frame, text="Image:").grid(row=1, column=0, sticky=tk.W, pady=5)
self.image2_label = ttk.Label(option2_frame, text="No image selected")
self.image2_label.grid(row=1, column=1, sticky=tk.W, pady=5)
ttk.Button(
option2_frame, text="Browse...", command=lambda: self.select_image(2)
).grid(row=1, column=2, padx=5, pady=5)
ttk.Label(option2_frame, text="Percentage:").grid(row=2, column=0, sticky=tk.W, pady=5)
self.percent2 = ttk.Entry(option2_frame, width=10)
self.percent2.grid(row=2, column=1, sticky=tk.W, pady=5)
self.percent2.insert(0, "999,72%") # Default percentage
# Timing Controls Section
timing_frame = ttk.LabelFrame(main_frame, text="Timing Controls", padding="10")
timing_frame.grid(row=2, column=0, columnspan=4, sticky=(tk.W, tk.E), pady=10)
ttk.Label(timing_frame, text="Initial Pause (seconds):").grid(
row=0, column=0, sticky=tk.W, pady=5
)
self.initial_pause = ttk.Entry(timing_frame, width=10)
self.initial_pause.grid(row=0, column=1, sticky=tk.W, pady=5)
self.initial_pause.insert(0, "2") # Default 2 seconds
ttk.Label(timing_frame, text="Timer Delay Before Second Image (seconds):").grid(
row=1, column=0, sticky=tk.W, pady=5
)
self.timer_delay = ttk.Entry(timing_frame, width=10)
self.timer_delay.grid(row=1, column=1, sticky=tk.W, pady=5)
self.timer_delay.insert(0, "1") # Default 1 second
ttk.Label(timing_frame, text="Wait Before Countdown (seconds):").grid(
row=2, column=0, sticky=tk.W, pady=5
)
self.wait_before_countdown = ttk.Entry(timing_frame, width=10)
self.wait_before_countdown.grid(row=2, column=1, sticky=tk.W, pady=5)
self.wait_before_countdown.insert(0, "1") # Default 1 second
ttk.Label(timing_frame, text="Countdown (seconds):").grid(
row=3, column=0, sticky=tk.W, pady=5
)
self.countdown_duration = ttk.Entry(timing_frame, width=10)
self.countdown_duration.grid(row=3, column=1, sticky=tk.W, pady=5)
self.countdown_duration.insert(0, "5") # Default 5 seconds
# Generate Button
generate_button = ttk.Button(
main_frame, text="Generate Video", command=self.generate_video
)
generate_button.grid(row=4, column=0, columnspan=4, pady=20)
def select_image(self, option_num):
"""
Open a file dialog to select an image and update the corresponding label.
"""
file_path = filedialog.askopenfilename(
filetypes=[("Image files", "*.png *.jpg *.jpeg *.gif *.bmp")]
)
if file_path:
if option_num == 1:
self.image1_path = file_path
self.image1_label.config(text=os.path.basename(file_path))
elif option_num == 2:
self.image2_path = file_path
self.image2_label.config(text=os.path.basename(file_path))
def process_image(self, image_path, size=(500, 500), start_time=0, duration=0):
"""
Process the image by converting mode and resizing proportionally without warping.
:param image_path: Path to the image file.
:param size: Maximum width and height as a tuple. Increased to (500, 500).
:param start_time: Time at which the image should appear in the video.
:param duration: Duration of the image clip.
:return: An ImageClip object.
"""
img = Image.open(image_path)
if img.mode != "RGBA":
img = img.convert("RGBA")
# Resize image proportionally if size is provided
if size:
img.thumbnail(size, Image.LANCZOS) # In-place resizing
img_array = np.array(img)
clip_duration = duration if duration > 0 else self.total_duration
clip = ImageClip(img_array).set_duration(clip_duration)
if start_time > 0:
clip = clip.set_start(start_time)
return clip
def create_styled_text(
self, text, y_position, duration, start_time=0, fontsize=70, color="yellow",
stroke_color="black", stroke_width=2
):
"""
Create a styled TextClip.
:param text: Text content.
:param y_position: Vertical position of the text.
:param duration: Duration for which the text is visible.
:param start_time: Time at which the text appears.
:param fontsize: Font size of the text.
:param color: Text color.
:param stroke_color: Stroke (outline) color.
:param stroke_width: Width of the stroke.
:return: A TextClip object.
"""
text_clip = TextClip(
text,
font="Arial-Bold",
color=color,
fontsize=fontsize,
method="label", # Changed to 'label' for better positioning
stroke_color=stroke_color,
stroke_width=stroke_width,
).set_duration(duration)
if start_time > 0:
text_clip = text_clip.set_start(start_time)
return text_clip.set_position(("center", y_position))
def create_timer_clips(self, start_time, countdown_seconds, total_duration):
"""
Create countdown timer clips from countdown_seconds to 1 (excluding 0).
:param start_time: The time at which the countdown starts.
:param countdown_seconds: Number of seconds to count down from.
:param total_duration: Total duration of the video.
:return: A list of TextClip objects for the countdown.
"""
timer_clips = []
for i in range(countdown_seconds, 0, -1): # Excludes 0
current_time = countdown_seconds - i
timer_text = str(i)
timer_duration = 1 # Each number shows for 1 second
timer_clip = self.create_styled_text(
timer_text,
self.middle_y - 100, # Positioned slightly above the center
timer_duration,
start_time + current_time,
fontsize=150,
color="white",
stroke_color="black",
stroke_width=3
)
timer_clips.append(timer_clip)
return timer_clips
def generate_video(self):
"""
Generate the 'Would You Rather' video based on user inputs.
"""
# Validate inputs
if not self.image1_path or not self.image2_path:
messagebox.showerror("Input Error", "Please select both images (Option 1 and Option 2).")
return
option1_text = self.option1_text.get().strip()
option2_text = self.option2_text.get().strip()
if not option1_text or not option2_text:
messagebox.showerror(
"Input Error", "Please enter text for both options."
)
return
# Validate timing inputs
try:
initial_pause = float(self.initial_pause.get())
timer_delay = float(self.timer_delay.get())
countdown_wait = float(self.wait_before_countdown.get())
countdown_seconds = int(self.countdown_duration.get())
except ValueError:
messagebox.showerror(
"Input Error", "Please enter valid numeric values for timings."
)
return
if countdown_wait < 0:
messagebox.showerror(
"Input Error", "Wait Before Countdown cannot be negative."
)
return
# Validate percentage inputs
try:
# Replace comma with dot for decimal conversion if used
percent1_val = self.percent1.get().strip().replace(',', '.').replace('%', '')
percent2_val = self.percent2.get().strip().replace(',', '.').replace('%', '')
percent1 = float(percent1_val)
percent2 = float(percent2_val)
except ValueError:
messagebox.showerror(
"Input Error", "Please enter valid numeric values for percentages (e.g., 1.02%)."
)
return
# Define percentage display duration and desired extra time
percentage_duration = 3 # seconds (increased from 2)
desired_extra_time = 0 # seconds (no extra buffer after percentages)
# Calculate buffer_time as the sum of percentage_duration and desired_extra_time
buffer_time = percentage_duration + desired_extra_time # 3 + 0 = 3 seconds
# Calculate total_duration
self.total_duration = (
initial_pause
+ timer_delay
+ countdown_wait
+ countdown_seconds
+ buffer_time
) # e.g., 2 + 1 + 1 + 5 + 3 = 12 seconds
# Create background clips
red_clip = ColorClip((self.width, self.middle_y), color=(255, 0, 0)).set_duration(
self.total_duration
)
blue_clip = ColorClip((self.width, self.middle_y), color=(0, 0, 255)).set_duration(
self.total_duration
)
clips = [
red_clip.set_position((0, 0)),
blue_clip.set_position((0, self.middle_y)),
]
# Fixed Positions
# Top Half
top_image_y = 250 # Moved further down from 200 to 250
top_text_y = 650 # Moved up by 50 pixels from 700 to 650
top_percentage_y = 750 # Moved up by 50 pixels from 800 to 750
# Bottom Half
bottom_image_y = self.middle_y + 350 # Moved further down from self.middle_y + 300 to +350
bottom_text_y = 1200 # Fixed position for bottom text
bottom_percentage_y = 1100 # Changed from 1300 to 1100 to place above the bottom text
# Add top image (Black Socks) with initial_pause delay
img1_clip = self.process_image(
self.image1_path,
size=(500, 500), # Increased size to 500x500
start_time=initial_pause, # Starts after initial_pause
duration=self.total_duration - initial_pause # Adjust duration accordingly
)
if img1_clip:
clips.append(img1_clip.set_position(("center", top_image_y)))
# Add top text with initial_pause delay
option1_txt = self.create_styled_text(
option1_text.upper(),
y_position=top_text_y,
duration=self.total_duration - initial_pause, # Duration until end
start_time=initial_pause, # Starts after initial_pause
fontsize=80,
color="white",
stroke_color="black",
stroke_width=3
)
clips.append(option1_txt)
# Add bottom image (White Socks) after initial_pause + timer_delay
img2_start_time = initial_pause + timer_delay
img2_clip = self.process_image(
self.image2_path,
size=(500, 500), # Increased size to 500x500
start_time=img2_start_time,
duration=self.total_duration - img2_start_time # Adjust duration accordingly
)
if img2_clip:
clips.append(img2_clip.set_position(("center", bottom_image_y)).set_start(img2_start_time))
# Add bottom text below the bottom image after initial_pause + timer_delay
option2_txt = self.create_styled_text(
option2_text.upper(),
y_position=bottom_text_y,
duration=self.total_duration - img2_start_time, # Duration until the end
start_time=img2_start_time,
fontsize=80,
color="white",
stroke_color="black",
stroke_width=3
)
clips.append(option2_txt)
# Add dividing line
line_thickness = 8
black_line = ColorClip((self.width, line_thickness), color=(0, 0, 0)).set_duration(self.total_duration)
black_line = black_line.set_position((0, self.middle_y - line_thickness // 2))
clips.append(black_line)
# Add small black circle in the middle of the dividing line
circle_diameter = 50 # Adjust size as needed
circle_size = (circle_diameter, circle_diameter)
# Create a transparent image with a black circle
circle_img = Image.new("RGBA", circle_size, (0, 0, 0, 0))
draw = ImageDraw.Draw(circle_img)
draw.ellipse((0, 0, circle_diameter, circle_diameter), fill=(0, 0, 0, 255))
circle_array = np.array(circle_img)
# Create ImageClip for the circle
circle_clip = ImageClip(circle_array).set_duration(self.total_duration)
# Position the circle in the middle of the dividing line
circle_position = (self.width // 2 - circle_diameter // 2, self.middle_y - circle_diameter // 2)
clips.append(circle_clip.set_position(circle_position))
# Add countdown timer after initial_pause + timer_delay + countdown_wait
countdown_start_time = initial_pause + timer_delay + countdown_wait
timer_clips = self.create_timer_clips(countdown_start_time, countdown_seconds, self.total_duration)
clips.extend(timer_clips)
# Add Percentage 1 Text ("1.02%") in Yellow after countdown
percent1_txt = self.create_styled_text(
f"{percent1:.2f}%",
y_position=top_percentage_y,
duration=percentage_duration, # 3 seconds
start_time=countdown_start_time + countdown_seconds,
fontsize=100, # Increased font size
color="yellow",
stroke_color="black",
stroke_width=2
)
clips.append(percent1_txt)
# Add Percentage 2 Text ("999.72%") in Yellow above the bottom text after countdown
percent2_txt = self.create_styled_text(
f"{percent2:.2f}%",
y_position=bottom_percentage_y,
duration=percentage_duration, # 3 seconds
start_time=countdown_start_time + countdown_seconds,
fontsize=100, # Increased font size
color="yellow",
stroke_color="black",
stroke_width=2
)
clips.append(percent2_txt)
# No additional buffer_time; video will end after percentages are hidden
# Create final video
final_clip = CompositeVideoClip(clips, size=(self.width, self.height))
# Render the video
final_clip.write_videofile(
"would_you_rather.mp4",
fps=30,
codec="libx264",
audio=False,
threads=4,
preset="medium",
)
messagebox.showinfo("Success", "Video generated successfully!")
def run(self):
self.window.mainloop()
if name == "main":
app = WouldYouRatherGenerator()
app.run()
and here is the code I made for the idea and text generatoin.
text_generation.py:
import ollama
def generate_would_you_rather():
prompt = """Generate 6 funny and weird 'Would You Rather' choices.
Format each pair EXACTLY like this example:
code
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."""
try:
response = ollama.chat(model='llama3.2', messages=[
{'role': 'user', 'content': prompt}
])
return response['message']['content'].strip()
except Exception as e:
print(f"Error: {str(e)}")
raise
def main():
print("Generating Would You Rather pairs...")
print("\n" + "="*50 + "\n")
code
result = generate_would_you_rather()
print(result)
# Save to file
with open('would_you_rather.txt', 'w', encoding='utf-8') as f:
f.write(result)
print("\n" + "="*50)
print("\nResults have been saved to would_you_rather.txt")
if name == "main":
main()
and here for the image you can use this:
image_generation.py:
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 please use this for the voice generation.
voice_generation.py:
import os
import subprocess
from pathlib import Path
import shutil
import datetime
import argparse
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
"""
if base_dir is None:
base_dir = r"C:\Users\theod\Desktop\AI\text2voice\F5-TTS"
if ref_audio is None:
ref_audio = os.path.join(base_dir, "tests", "ref_audio", "tiktok.mp3")
if output_dir is None:
output_dir = os.path.join(r"C:\Users\theod\Desktop\Coding\AI\wouldyourather\generated_audio")
# Create output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
# 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 with proper quoting
cmd = [
"python", "inference-cli.py",
"--model", "F5-TTS",
"--ref_audio", f'"{ref_audio}"',
"--ref_text", f'"{ref_text}"',
"--gen_text", f'"{text}"'
]
try:
# Change to the base directory
original_dir = os.getcwd()
os.chdir(base_dir)
# Combine command with proper quoting
command_str = " ".join(cmd)
# Activate virtual environment and run command
if os.name == 'nt': # Windows
activate_cmd = os.path.join(base_dir, "venv", "Scripts", "activate")
full_command = f'call "{activate_cmd}" && {command_str}'
subprocess.run(full_command, shell=True, check=True)
else: # Linux/Mac
activate_cmd = os.path.join(base_dir, "venv", "bin", "activate")
full_command = f'source "{activate_cmd}" && {command_str}'
subprocess.run(full_command, shell=True, check=True)
# Copy the output file to our designated output directory
output_file = os.path.join(base_dir, "tests", "out.wav")
if os.path.exists(output_file):
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
new_filename = f"tts_output_{timestamp}.wav"
new_filepath = os.path.join(output_dir, new_filename)
shutil.copy2(output_file, new_filepath)
print(f"Audio generated successfully: {new_filepath}")
return new_filepath
else:
print("Error: Output file not found")
return None
except subprocess.CalledProcessError as e:
print(f"Command execution failed: {str(e)}")
return None
except Exception as e:
print(f"Error occurred: {str(e)}")
return None
finally:
# Return to original directory
os.chdir(original_dir)
def main():
parser = argparse.ArgumentParser(description='Generate TTS audio using F5-TTS')
parser.add_argument('--text', type=str, required=True, help='Text to convert to speech')
args = parser.parse_args()
code
output_path = generate_tts(args.text)
if output_path:
print(f"Generated audio saved to: {output_path}")
if name == "main":
# Example usage:
text_to_generate = "This is a test of the TTS system"
generate_tts(text_to_generate)
code
# Or you can run it with multiple texts:
texts = [
"Welcome to my TikTok channel!",
"Don't forget to like and subscribe",
"Check out this amazing trick"
]
for text in texts:
generate_tts(text)
so make it automatically generation a video.
make sure to change the timings of the video to match the time of the audio recordings that were generated.
please import the functions from the python files I have
Certainly! I understand you want to integrate all your existing Python scripts (16.py, text_generation.py, image_generation.py, and voice_generation.py) into a single, cohesive "Would You Rather" generator. This integrated generator will automate the entire process—from generating funny "Would You Rather" pairs, creating corresponding images and voiceovers, to compiling everything into a synchronized video.
Below is a comprehensive guide and a combined Python script that accomplishes this integration. Before proceeding, ensure that all your individual scripts (text_generation.py, image_generation.py, voice_generation.py, and 16.py) are properly modularized to allow importing their respective functions and classes.
Step 1: Refactor Existing Scripts for Modularity
To seamlessly import functions and classes from your existing scripts, we'll need to refactor them slightly. Here's how you can modify each script:
# text_generation.py
import ollama
def generate_would_you_rather():
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
# ... Continues for other pairs ...
Make each pair unique, weird, and entertaining. Write detailed image descriptions that would help create a clear visual."""
try:
response = ollama.chat(model='llama3.2', messages=[
{'role': 'user', 'content': prompt}
])
return response['message']['content'].strip()
except Exception as e:
print(f"Error: {str(e)}")
raise
def parse_would_you_rather(text):
"""
Parses the generated 'Would You Rather' text into structured data.
Returns:
List of dictionaries with 'choice1', 'image1', 'choice2', 'image2'.
"""
pairs = []
entries = text.strip().split('\n\n')
for entry in entries:
lines = entry.strip().split('\n')
if len(lines) >= 6:
pair = {
'choice1': lines[1].replace("CHOICE: ", "").strip(),
'image1': lines[2].replace("IMAGE: ", "").strip(),
'choice2': lines[4].replace("CHOICE: ", "").strip(),
'image2': lines[5].replace("IMAGE: ", "").strip(),
}
pairs.append(pair)
return pairs
1.2 image_generation.py
Refactored Structure:
python
1.3 voice_generation.py
Refactored Structure:
python
1.4 16.py (Video Generation)
We'll transform the WouldYouRatherGenerator class into a modular class that can be imported and utilized by our main script.
python
Step 2: Create the Main Integrated Script
Now, we'll create a new Python script (complete_generator.py) that brings together all the functionalities: text generation, image creation, voiceover generation, and video compilation.
python
Step 3: Ensure Proper Workflow Configuration
Ensure that your workflow.json for ComfyUI is correctly configured to accept prompts and generate images based on the provided descriptions. The script assumes that this file exists in the same directory as image_generation.py. Adjust the workflow_path variable if it's located elsewhere.
Step 4: Install Necessary Dependencies
Ensure you have all the required Python packages installed. You can install them using pip:
Additionally, ensure that external dependencies like ImageMagick and ComfyUI are correctly installed and configured on your system.
Step 5: Run the Integrated Generator
Place All Scripts Together: Ensure that complete_generator.py, text_generation.py, image_generation.py, voice_generation.py, and video_generation.py are in the same directory.
Ensure External Services are Running:
ComfyUI Server: Make sure the ComfyUI server is running at 127.0.0.1:8188. Adjust the server_address in ComfyUIGenerator if it's different.
F5-TTS: Ensure that the F5-TTS environment is set up correctly, and the paths in voice_generation.py are accurate.
Execute the Script:
bash
python complete_generator.py
This will:
Generate 6 "Would You Rather" pairs.
Generate images for each choice using ComfyUI.
Generate a voiceover audio narration for all pairs.
Compile everything into a synchronized video named would_you_rather_video.mp4.
Additional Enhancements
Error Handling: The provided scripts include basic error handling. You can enhance this by adding more granular checks and fallback mechanisms.
Parallel Processing: Image and audio generation can be time-consuming. Consider implementing parallel processing (using multiprocessing or asyncio) to speed up the process.
GUI Integration: If you prefer a GUI interface (as in your original 16.py), you can integrate the main() function's logic into the GUI's event handlers. This allows users to trigger the entire generation process with button clicks and monitor progress.
Dynamic Timing Adjustment: Currently, the video durations are based on a default total duration. To make timings dynamically match the generated audio durations:
Retrieve the duration of the generated audio.
Adjust self.total_duration in WouldYouRatherVideoGenerator based on the audio duration.
Ensure that all video elements (images, texts) are synchronized with the audio timeline.
Here's how you can modify the generate_video method in video_generation.py to accommodate dynamic audio durations:
python
from moviepy.editor import AudioFileClip
# Inside the WouldYouRatherVideoGenerator class
def generate_video(self, pairs, images_dict, audio_path, output_path="would_you_rather.mp4"):
"""
... [existing docstring] ...
"""
from moviepy.editor import AudioFileClip # Ensure this import is at the top
# Reset clips
self.clips = []
# Add background
self.add_background()
# Add dividing line
self.add_dividing_line()
# Load audio and set total_duration based on audio length
audio_clip = AudioFileClip(audio_path)
self.total_duration = audio_clip.duration
duration_per_pair = self.total_duration / len(pairs)
# Iterate over each pair and add to the video
current_time = 0
for pair in pairs:
# Add choice 1
img1_clip = self.process_image(
images_dict[pair['image1']],
size=(500, 500),
start_time=current_time,
duration=duration_per_pair
)
self.clips.append(img1_clip.set_position(("center", 250)))
option1_txt = self.create_styled_text(
pair['choice1'].upper(),
y_position=650,
duration=duration_per_pair,
start_time=current_time,
fontsize=80,
color="white",
stroke_color="black",
stroke_width=3
)
self.clips.append(option1_txt)
# Add choice 2
img2_clip = self.process_image(
images_dict[pair['image2']],
size=(500, 500),
start_time=current_time + (duration_per_pair / 2),
duration=duration_per_pair / 2
)
self.clips.append(img2_clip.set_position(("center", 350))) # Adjust y_position as needed
option2_txt = self.create_styled_text(
pair['choice2'].upper(),
y_position=1200,
duration=duration_per_pair / 2,
start_time=current_time + (duration_per_pair / 2),
fontsize=80,
color="white",
stroke_color="black",
stroke_width=3
)
self.clips.append(option2_txt)
current_time += duration_per_pair
# Add audio to the final clip
final_clip = CompositeVideoClip(self.clips, size=(self.width, self.height)).set_audio(audio_clip)
# Render the video
final_clip.write_videofile(
output_path,
fps=30,
codec="libx264",
audio_codec="aac",
threads=4,
preset="medium",
)
This modification ensures that the video duration matches the audio duration, providing a seamless viewing experience.
Conclusion
By following the above steps and utilizing the integrated complete_generator.py script, you can automate the entire process of generating a "Would You Rather" video—from creating quirky choices and corresponding visuals to producing voiceovers and compiling everything into a polished video. Ensure that all external dependencies are correctly configured and that paths within the scripts are accurately set according to your system.
Feel free to further customize and enhance the generator to better fit your specific requirements!
# image_generation.py
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
# Serialize the modified workflow back to JSON
modified_workflow_path = "modified_workflow.json"
with open(modified_workflow_path, 'w') as f:
json.dump(workflow, f)
# 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, modified_workflow_path)
# Save all generated images
saved_filenames = []
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)
saved_filenames.append(filename)
finally:
ws.close()
return saved_filenames
# voice_generation.py
import os
import subprocess
from pathlib import Path
import shutil
import datetime
import argparse
def generate_tts(text, base_dir=None, ref_audio=None, output_dir=None):
"""
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
"""
if base_dir is None:
base_dir = r"C:\Users\theod\Desktop\AI\text2voice\F5-TTS"
if ref_audio is None:
ref_audio = os.path.join(base_dir, "tests", "ref_audio", "tiktok.mp3")
if output_dir is None:
output_dir = os.path.join(r"C:\Users\theod\Desktop\Coding\AI\wouldyourather\generated_audio")
# Create output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
# 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 with proper quoting
cmd = [
"python", "inference-cli.py",
"--model", "F5-TTS",
"--ref_audio", f'"{ref_audio}"',
"--ref_text", f'"{ref_text}"',
"--gen_text", f'"{text}"'
]
try:
# Change to the base directory
original_dir = os.getcwd()
os.chdir(base_dir)
# Combine command with proper quoting
command_str = " ".join(cmd)
# Activate virtual environment and run command
if os.name == 'nt': # Windows
activate_cmd = os.path.join(base_dir, "venv", "Scripts", "activate")
full_command = f'call "{activate_cmd}" && {command_str}'
subprocess.run(full_command, shell=True, check=True)
else: # Linux/Mac
activate_cmd = os.path.join(base_dir, "venv", "bin", "activate")
full_command = f'source "{activate_cmd}" && {command_str}'
subprocess.run(full_command, shell=True, check=True)
# Copy the output file to our designated output directory
output_file = os.path.join(base_dir, "tests", "out.wav")
if os.path.exists(output_file):
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
new_filename = f"tts_output_{timestamp}.wav"
new_filepath = os.path.join(output_dir, new_filename)
shutil.copy2(output_file, new_filepath)
print(f"Audio generated successfully: {new_filepath}")
return new_filepath
else:
print("Error: Output file not found")
return None
except subprocess.CalledProcessError as e:
print(f"Command execution failed: {str(e)}")
return None
except Exception as e:
print(f"Error occurred: {str(e)}")
return None
finally:
# Return to original directory
os.chdir(original_dir)
# video_generation.py
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from moviepy.editor import (
TextClip,
ColorClip,
CompositeVideoClip,
ImageClip,
)
from moviepy.config import change_settings
import numpy as np
from PIL import Image, ImageDraw
import os
# Configure ImageMagick (Ensure this path is correct for your system)
change_settings(
{"IMAGEMAGICK_BINARY": r"C:\Program Files\ImageMagick-7.1.1-Q16-HDRI\magick.exe"}
)
class WouldYouRatherVideoGenerator:
def __init__(self, width=1080, height=1920):
self.width = width
self.height = height
self.middle_y = self.height // 2
self.total_duration = 12 # Default duration, can be updated based on audio
self.clips = []
def process_image(self, image_path, size=(500, 500), start_time=0, duration=0):
"""
Process the image by converting mode and resizing proportionally without warping.
:param image_path: Path to the image file.
:param size: Maximum width and height as a tuple.
:param start_time: Time at which the image should appear in the video.
:param duration: Duration of the image clip.
:return: An ImageClip object.
"""
img = Image.open(image_path)
if img.mode != "RGBA":
img = img.convert("RGBA")
# Resize image proportionally if size is provided
if size:
img.thumbnail(size, Image.LANCZOS) # In-place resizing
img_array = np.array(img)
clip_duration = duration if duration > 0 else self.total_duration
clip = ImageClip(img_array).set_duration(clip_duration)
if start_time > 0:
clip = clip.set_start(start_time)
return clip
def create_styled_text(
self, text, y_position, duration, start_time=0, fontsize=70, color="yellow",
stroke_color="black", stroke_width=2
):
"""
Create a styled TextClip.
:param text: Text content.
:param y_position: Vertical position of the text.
:param duration: Duration for which the text is visible.
:param start_time: Time at which the text appears.
:param fontsize: Font size of the text.
:param color: Text color.
:param stroke_color: Stroke (outline) color.
:param stroke_width: Width of the stroke.
:return: A TextClip object.
"""
text_clip = TextClip(
text,
font="Arial-Bold",
color=color,
fontsize=fontsize,
method="label", # Changed to 'label' for better positioning
stroke_color=stroke_color,
stroke_width=stroke_width,
).set_duration(duration)
if start_time > 0:
text_clip = text_clip.set_start(start_time)
return text_clip.set_position(("center", y_position))
def create_timer_clips(self, start_time, countdown_seconds, total_duration):
"""
Create countdown timer clips from countdown_seconds to 1 (excluding 0).
:param start_time: The time at which the countdown starts.
:param countdown_seconds: Number of seconds to count down from.
:param total_duration: Total duration of the video.
:return: A list of TextClip objects for the countdown.
"""
timer_clips = []
for i in range(countdown_seconds, 0, -1): # Excludes 0
current_time = countdown_seconds - i
timer_text = str(i)
timer_duration = 1 # Each number shows for 1 second
timer_clip = self.create_styled_text(
timer_text,
self.middle_y - 100, # Positioned slightly above the center
timer_duration,
start_time + current_time,
fontsize=150,
color="white",
stroke_color="black",
stroke_width=3
)
timer_clips.append(timer_clip)
return timer_clips
def add_background(self, color1=(255, 0, 0), color2=(0, 0, 255)):
"""
Add background color clips.
:param color1: RGB color for the top half.
:param color2: RGB color for the bottom half.
"""
red_clip = ColorClip((self.width, self.middle_y), color=color1).set_duration(self.total_duration)
blue_clip = ColorClip((self.width, self.middle_y), color=color2).set_duration(self.total_duration)
self.clips.append(red_clip.set_position((0, 0)))
self.clips.append(blue_clip.set_position((0, self.middle_y)))
def add_dividing_line(self, thickness=8, color=(0,0,0), diameter=50):
"""
Add a dividing line with a circle in the middle.
"""
# Add dividing line
black_line = ColorClip((self.width, thickness), color=color).set_duration(self.total_duration)
black_line = black_line.set_position((0, self.middle_y - thickness // 2))
self.clips.append(black_line)
# Add small black circle in the middle of the dividing line
circle_diameter = diameter # Adjust size as needed
circle_size = (circle_diameter, circle_diameter)
# Create a transparent image with a black circle
circle_img = Image.new("RGBA", circle_size, (0, 0, 0, 0))
draw = ImageDraw.Draw(circle_img)
draw.ellipse((0, 0, circle_diameter, circle_diameter), fill=color)
circle_array = np.array(circle_img)
# Create ImageClip for the circle
circle_clip = ImageClip(circle_array).set_duration(self.total_duration)
# Position the circle in the middle of the dividing line
circle_position = (self.width // 2 - circle_diameter // 2, self.middle_y - circle_diameter // 2)
self.clips.append(circle_clip.set_position(circle_position))
def generate_video(self, pairs, images_dict, audio_path, output_path="would_you_rather.mp4"):
"""
Generate the 'Would You Rather' video based on provided pairs, images, and audio.
:param pairs: List of 'Would You Rather' pairs.
:param images_dict: Dictionary mapping image descriptions to file paths.
:param audio_path: Path to the audio file.
:param output_path: Path to save the final video.
"""
# Reset clips
self.clips = []
# Add background
self.add_background()
# Add dividing line
self.add_dividing_line()
# Iterate over each pair and add to the video
current_time = 0
duration_per_pair = self.total_duration / len(pairs)
for pair in pairs:
# Add choice 1
img1_clip = self.process_image(
images_dict[pair['image1']],
size=(500, 500),
start_time=current_time,
duration=duration_per_pair
)
self.clips.append(img1_clip.set_position(("center", 250)))
option1_txt = self.create_styled_text(
pair['choice1'].upper(),
y_position=650,
duration=duration_per_pair,
start_time=current_time,
fontsize=80,
color="white",
stroke_color="black",
stroke_width=3
)
self.clips.append(option1_txt)
# Add choice 2
img2_clip = self.process_image(
images_dict[pair['image2']],
size=(500, 500),
start_time=current_time + (duration_per_pair / 2),
duration=duration_per_pair / 2
)
self.clips.append(img2_clip.set_position(("center", 350))) # Adjust y_position as needed
option2_txt = self.create_styled_text(
pair['choice2'].upper(),
y_position=1200,
duration=duration_per_pair / 2,
start_time=current_time + (duration_per_pair / 2),
fontsize=80,
color="white",
stroke_color="black",
stroke_width=3
)
self.clips.append(option2_txt)
current_time += duration_per_pair
# Add audio
audio_clip = AudioFileClip(audio_path)
final_duration = audio_clip.duration
self.total_duration = final_duration
# Update the durations of all clips based on final_duration
for clip in self.clips:
clip = clip.set_duration(final_duration)
# Combine all clips
final_clip = CompositeVideoClip(self.clips, size=(self.width, self.height)).set_audio(audio_clip)
# Render the video
final_clip.write_videofile(
output_path,
fps=30,
codec="libx264",
audio_codec="aac",
threads=4,
preset="medium",
)
# complete_generator.py
import os
import time
import shutil
from pathlib import Path
# Import the necessary classes and functions
from text_generation import generate_would_you_rather, parse_would_you_rather
from image_generation import ComfyUIGenerator
from voice_generation import generate_tts
from video_generation import WouldYouRatherVideoGenerator
def main():
# Step 1: Generate "Would You Rather" pairs
print("Generating 'Would You Rather' pairs...")
raw_text = generate_would_you_rather()
pairs = parse_would_you_rather(raw_text)
print(f"Generated {len(pairs)} pairs.")
# Step 2: Generate images for each choice
generator = ComfyUIGenerator(server_address="127.0.0.1:8188")
workflow_path = "workflow.json" # Ensure this file exists and is correctly configured
images_dict = {}
for idx, pair in enumerate(pairs, start=1):
print(f"Generating images for pair {idx}:")
# Generate image for choice 1
image1_description = pair['image1']
print(f" - Choice 1 Image: {image1_description}")
image1_filenames = generator.generate_image(workflow_path, image1_description)
if image1_filenames:
images_dict[image1_description] = image1_filenames[0] # Taking the first image
print(f" Saved: {image1_filenames[0]}")
else:
print(" Failed to generate image for choice 1.")
continue # Skip this pair if image generation failed
# Generate image for choice 2
image2_description = pair['image2']
print(f" - Choice 2 Image: {image2_description}")
image2_filenames = generator.generate_image(workflow_path, image2_description)
if image2_filenames:
images_dict[image2_description] = image2_filenames[0]
print(f" Saved: {image2_filenames[0]}")
else:
print(" Failed to generate image for choice 2.")
continue # Skip this pair if image generation failed
# Step 3: Generate voiceover audio
print("Generating voiceover audio...")
# Combine all choices into a single text for TTS
tts_text = ""
for idx, pair in enumerate(pairs, start=1):
tts_text += f"Would you rather {pair['choice1']} or {pair['choice2']}?\n"
# Generate TTS audio
audio_path = generate_tts(tts_text)
if not audio_path:
print("Failed to generate TTS audio. Exiting.")
return
# Step 4: Generate the video
print("Compiling the video...")
video_generator = WouldYouRatherVideoGenerator()
output_video_path = "would_you_rather_video.mp4"
video_generator.generate_video(pairs, images_dict, audio_path, output_path=output_video_path)
print(f"Video generated successfully: {output_video_path}")
# Optional: Clean up generated images and audio
cleanup = False
if cleanup:
# Remove generated images
shutil.rmtree("generate_images", ignore_errors=True)
# Remove generated audio
audio_dir = Path(audio_path).parent
shutil.rmtree(audio_dir, ignore_errors=True)
print("Cleaned up generated images and audio.")
if __name__ == "__main__":
main()