AZILS's picture
Create app.py
d9ccbf8 verified
raw
history blame
36.9 kB
import os
import re
import uuid
import json
import time
import random
import shutil
import requests
import asyncio
import gradio as gr
from pathlib import Path
import edge_tts
from gtts import gTTS
import numpy as np
import g4f
from g4f.client import Client
import assemblyai as aai
from moviepy.editor import *
from moviepy.video.fx.all import crop
from moviepy.audio.fx.all import volumex
from concurrent.futures import ThreadPoolExecutor
# Constants
TEMP_DIR = Path("temp")
OUTPUT_DIR = Path("output")
MUSIC_DIR = Path("music")
# Ensure directories exist
TEMP_DIR.mkdir(exist_ok=True)
OUTPUT_DIR.mkdir(exist_ok=True)
MUSIC_DIR.mkdir(exist_ok=True)
# Add a sample music file if none exists
if not list(MUSIC_DIR.glob("*.mp3")):
# Create a simple silent audio file as placeholder
silent_clip = AudioClip(lambda t: 0, duration=10)
silent_clip.write_audiofile(MUSIC_DIR / "silence.mp3", fps=44100)
# Utility functions
def info(msg):
return gr.Info(msg)
def warning(msg):
return gr.Warning(msg)
def error(msg):
return gr.Error(msg)
def generate_id():
return str(uuid.uuid4())
def choose_random_music():
music_files = list(MUSIC_DIR.glob("*.mp3"))
if not music_files:
return MUSIC_DIR / "silence.mp3"
return random.choice(music_files)
def parse_model(model_name):
"""Parse model name for g4f"""
if model_name == "gpt-4":
return g4f.models.gpt_4
elif model_name == "gpt-3.5-turbo":
return g4f.models.gpt_35_turbo
else:
return model_name
class YouTubeGenerator:
def __init__(self):
self.reset()
def reset(self):
"""Reset all generation state"""
self.subject = ""
self.script = ""
self.metadata = {"title": "", "description": ""}
self.image_prompts = []
self.images = []
self.tts_path = ""
self.video_path = ""
def clean_temp_files(self, keep_video=False):
"""Clean temporary files except final video if requested"""
for img in self.images:
if os.path.exists(img):
os.remove(img)
if self.tts_path and os.path.exists(self.tts_path):
os.remove(self.tts_path)
if not keep_video and self.video_path and os.path.exists(self.video_path):
os.remove(self.video_path)
def generate_response(self, prompt, model="gpt-4"):
"""Generate response using G4F"""
try:
response = g4f.ChatCompletion.create(
model=parse_model(model),
messages=[{"role": "user", "content": prompt}]
)
return response
except Exception as e:
error(f"Error generating response: {str(e)}")
return ""
def generate_topic(self, niche):
"""Generate a topic based on the niche"""
prompt = f"Please generate a specific video idea that takes about the following topic: {niche}. Make it exactly one sentence. Only return the topic, nothing else."
completion = self.generate_response(prompt)
if not completion:
raise ValueError("Failed to generate topic")
self.subject = completion
return completion
def generate_script(self, subject, language):
"""Generate video script based on subject"""
prompt = f"""
Generate a script for youtube shorts video, depending on the subject of the video.
The script is to be returned as a string with the specified number of paragraphs.
Here is an example of a string:
"This is an example string."
Do not under any circumstance reference this prompt in your response.
Get straight to the point, don't start with unnecessary things like, "welcome to this video".
Obviously, the script should be related to the subject of the video.
YOU MUST NOT INCLUDE ANY TYPE OF MARKDOWN OR FORMATTING IN THE SCRIPT, NEVER USE A TITLE.
YOU MUST WRITE THE SCRIPT IN THE LANGUAGE SPECIFIED IN [LANGUAGE].
ONLY RETURN THE RAW CONTENT OF THE SCRIPT. DO NOT INCLUDE "VOICEOVER", "NARRATOR" OR SIMILAR INDICATORS OF WHAT SHOULD BE SPOKEN AT THE BEGINNING OF EACH PARAGRAPH OR LINE. YOU MUST NOT MENTION THE PROMPT, OR ANYTHING ABOUT THE SCRIPT ITSELF. ALSO, NEVER TALK ABOUT THE AMOUNT OF PARAGRAPHS OR LINES. JUST WRITE THE SCRIPT
Subject: {subject}
Language: {language}
"""
completion = self.generate_response(prompt)
# Apply regex to remove *
completion = re.sub(r"\*", "", completion)
if not completion:
raise ValueError("The generated script is empty")
if len(completion) > 5000:
raise ValueError("Generated script is too long (>5000 chars)")
self.script = completion
return completion
def generate_metadata(self, subject):
"""Generate title and description"""
title_prompt = f"Please generate a YouTube Video Title for the following subject, including hashtags: {subject}. Only return the title, nothing else. Limit the title under 100 characters."
title = self.generate_response(title_prompt)
if len(title) > 100:
title = title[:97] + "..."
desc_prompt = f"Please generate a YouTube Video Description for the following script: {self.script}. Only return the description, nothing else."
description = self.generate_response(desc_prompt)
self.metadata = {
"title": title,
"description": description
}
return self.metadata
def generate_prompts(self, subject, script):
"""Generate image prompts for the script"""
n_prompts = 5
prompt = f"""
Generate {n_prompts} Image Prompts for AI Image Generation,
depending on the subject of a video.
Subject: {subject}
The image prompts are to be returned as
a JSON-Array of strings.
Each search term should consist of a full sentence,
always add the main subject of the video.
Be emotional and use interesting adjectives to make the
Image Prompt as detailed as possible.
YOU MUST ONLY RETURN THE JSON-ARRAY OF STRINGS.
YOU MUST NOT RETURN ANYTHING ELSE.
YOU MUST NOT RETURN THE SCRIPT.
The search terms must be related to the subject of the video.
Here is an example of a JSON-Array of strings:
["image prompt 1", "image prompt 2", "image prompt 3"]
For context, here is the full text:
{script}
"""
completion = str(self.generate_response(prompt, model="gpt-4"))
completion = completion.replace("```json", "").replace("```", "")
image_prompts = []
try:
# First try to parse as JSON directly
image_prompts = json.loads(completion)
if isinstance(image_prompts, dict) and "image_prompts" in image_prompts:
image_prompts = image_prompts["image_prompts"]
except Exception:
# If that fails, try to extract array from the text
try:
# Get everything between [ and ], and turn it into a list
r = re.compile(r"\[.*\]", re.DOTALL)
matches = r.findall(completion)
if matches:
image_prompts = json.loads(matches[0])
except Exception as e:
raise ValueError(f"Failed to parse image prompts: {str(e)}")
# Ensure we have prompts and they're in the right format
if not image_prompts or not isinstance(image_prompts, list):
raise ValueError("No valid image prompts were generated")
# Limit to 5 prompts
image_prompts = image_prompts[:5]
self.image_prompts = image_prompts
return image_prompts
def generate_image(self, prompt, provider="g4f", model="sdxl-turbo"):
"""Generate an image using the specified provider"""
try:
if provider == "g4f":
client = Client()
response = client.images.generate(
model=model,
prompt=prompt,
response_format="url"
)
if response and response.data and len(response.data) > 0:
image_url = response.data[0].url
image_response = requests.get(image_url)
if image_response.status_code == 200:
image_path = str(TEMP_DIR / f"{generate_id()}.png")
with open(image_path, "wb") as f:
f.write(image_response.content)
self.images.append(image_path)
return image_path
raise ValueError(f"Failed to download image from {image_url}")
elif provider == "prodia":
s = requests.Session()
headers = {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
# Generate job
resp = s.get(
"https://api.prodia.com/generate",
params={
"new": "true",
"prompt": prompt,
"model": model,
"negative_prompt": "verybadimagenegative_v1.3",
"steps": "20",
"cfg": "7",
"seed": random.randint(1, 10000),
"sample": "DPM++ 2M Karras",
"aspect_ratio": "square"
},
headers=headers
)
job_id = resp.json().get('job')
if not job_id:
raise ValueError("Failed to get job ID from Prodia")
# Wait for job to complete
for _ in range(30): # Timeout after 30 attempts (150 seconds)
time.sleep(5)
status = s.get(f"https://api.prodia.com/job/{job_id}", headers=headers).json()
if status.get("status") == "succeeded":
img_data = s.get(f"https://images.prodia.xyz/{job_id}.png?download=1", headers=headers).content
image_path = str(TEMP_DIR / f"{generate_id()}.png")
with open(image_path, "wb") as f:
f.write(img_data)
self.images.append(image_path)
return image_path
raise ValueError("Prodia image generation timed out")
elif provider == "pollinations":
response = requests.get(f"https://image.pollinations.ai/prompt/{prompt}{random.randint(1,10000)}")
if response.status_code == 200:
image_path = str(TEMP_DIR / f"{generate_id()}.png")
with open(image_path, "wb") as f:
f.write(response.content)
self.images.append(image_path)
return image_path
else:
raise ValueError(f"Pollinations request failed: {response.status_code}")
else:
raise ValueError(f"Unsupported image provider: {provider}")
except Exception as e:
raise ValueError(f"Image generation failed: {str(e)}")
async def generate_edge_tts(self, text, voice):
"""Generate speech using Edge TTS"""
try:
audio_path = str(TEMP_DIR / f"{generate_id()}.mp3")
communicate = edge_tts.Communicate(text, voice)
await communicate.save(audio_path)
self.tts_path = audio_path
return audio_path
except Exception as e:
# Try an alternative voice if the specified one fails
try:
fallback_voice = "en-US-ChristopherNeural"
communicate = edge_tts.Communicate(text, fallback_voice)
audio_path = str(TEMP_DIR / f"{generate_id()}.mp3")
await communicate.save(audio_path)
self.tts_path = audio_path
return audio_path
except Exception as nested_e:
raise ValueError(f"Edge TTS failed with both voices: {str(e)}, fallback: {str(nested_e)}")
def generate_gtts(self, text, lang='en'):
"""Generate speech using Google TTS"""
try:
audio_path = str(TEMP_DIR / f"{generate_id()}.mp3")
tts = gTTS(text=text, lang=lang, slow=False)
tts.save(audio_path)
self.tts_path = audio_path
return audio_path
except Exception as e:
raise ValueError(f"Google TTS failed: {str(e)}")
def generate_speech(self, text, engine="edge", voice="en-US-ChristopherNeural"):
"""Generate speech from text using selected engine"""
# Clean text
text = re.sub(r'[^\w\s.?!]', '', text)
if engine == "edge":
# Edge TTS is async, so we need to run it in an event loop
return asyncio.run(self.generate_edge_tts(text, voice))
elif engine == "gtts":
return self.generate_gtts(text, lang=voice)
else:
raise ValueError(f"Unsupported TTS engine: {engine}")
def generate_subtitles(self, audio_path, api_key):
"""Generate word-highlighted subtitles"""
try:
# Set API key
aai.settings.api_key = api_key
# Configure transcription
config = aai.TranscriptionConfig(
speaker_labels=False,
word_boost=[],
format_text=True
)
# Create transcriber and transcribe audio
transcriber = aai.Transcriber(config=config)
transcript = transcriber.transcribe(audio_path)
# Process word-level information
wordlevel_info = []
for word in transcript.words:
word_data = {
"word": word.text.strip(),
"start": word.start / 1000.0,
"end": word.end / 1000.0
}
wordlevel_info.append(word_data)
# Split text into lines based on character count and duration
MAX_CHARS = 30
MAX_DURATION = 3.0
MAX_GAP = 2.5
subtitles = []
line = []
line_duration = 0
for idx, word_data in enumerate(wordlevel_info):
word = word_data["word"]
start = word_data["start"]
end = word_data["end"]
line.append(word_data)
line_duration += end - start
temp = " ".join(item["word"] for item in line)
new_line_chars = len(temp)
duration_exceeded = line_duration > MAX_DURATION
chars_exceeded = new_line_chars > MAX_CHARS
if idx > 0:
gap = word_data['start'] - wordlevel_info[idx - 1]['end']
maxgap_exceeded = gap > MAX_GAP
else:
maxgap_exceeded = False
# Check if any condition is exceeded to finalize the current line
if duration_exceeded or chars_exceeded or maxgap_exceeded:
if line:
subtitle_line = {
"text": " ".join(item["word"] for item in line),
"start": line[0]["start"],
"end": line[-1]["end"],
"words": line
}
subtitles.append(subtitle_line)
line = []
line_duration = 0
# Add the remaining words as the last subtitle line if any
if line:
subtitle_line = {
"text": " ".join(item["word"] for item in line),
"start": line[0]["start"],
"end": line[-1]["end"],
"words": line
}
subtitles.append(subtitle_line)
# Create subtitle clips
all_subtitle_clips = []
# Define formatting constants
FONT = 'Helvetica-Bold'
FONTSIZE = 80
COLOR = 'white'
BG_COLOR = 'blue'
FRAME_SIZE = (1080, 1920)
for subtitle in subtitles:
full_duration = subtitle['end'] - subtitle['start']
word_clips = []
xy_textclips_positions = []
# Dynamic vertical positioning (moved to bottom)
frame_width, frame_height = FRAME_SIZE
x_pos = 0
y_pos = frame_height * 0.85 # Position at 85% of frame height
x_buffer = frame_width * 1 / 10
y_buffer = 10 # Small vertical buffer
line_height = 0
current_line_height = 0
for index, wordJSON in enumerate(subtitle['words']):
duration = wordJSON['end'] - wordJSON['start']
word_clip = TextClip(wordJSON['word'], font=FONT, fontsize=FONTSIZE, color=COLOR).set_start(subtitle['start']).set_duration(full_duration)
word_width, word_height = word_clip.size
# Track line height for multi-line support
line_height = max(line_height, word_height)
# Check if the current word exceeds the frame width, move to the next line
if x_pos + word_width > frame_width - 2 * x_buffer:
x_pos = 0
y_pos += line_height + y_buffer
current_line_height += line_height + y_buffer
# Store the position and other details for highlighting
xy_textclips_positions.append({
"x_pos": x_pos + x_buffer,
"y_pos": y_pos + y_buffer,
"width": word_width,
"height": word_height,
"word": wordJSON['word'],
"start": wordJSON['start'],
"end": wordJSON['end'],
"duration": duration
})
# Set the position of the word clip
word_clip = word_clip.set_position((x_pos + x_buffer, y_pos + y_buffer))
word_clips.append(word_clip)
x_pos = x_pos + word_width + 10
# Create highlighted word clips
for highlight_word in xy_textclips_positions:
word_clip_highlight = TextClip(highlight_word['word'], font=FONT, fontsize=FONTSIZE, color=COLOR, bg_color=BG_COLOR).set_start(highlight_word['start']).set_duration(highlight_word['duration'])
word_clip_highlight = word_clip_highlight.set_position((highlight_word['x_pos'], highlight_word['y_pos']))
word_clips.append(word_clip_highlight)
# Add all word clips to the list of subtitle clips
all_subtitle_clips.extend(word_clips)
return all_subtitle_clips
except Exception as e:
print(f"Subtitle generation error: {str(e)}")
return [] # Return empty list if subtitles fail
def combine_video(self, include_subtitles=True, subtitles_api_key=""):
"""Combine all elements into final video"""
try:
output_path = str(TEMP_DIR / f"{generate_id()}.mp4")
# Load audio
tts_clip = AudioFileClip(self.tts_path)
max_duration = tts_clip.duration
# Calculate duration per image
req_dur = max_duration / len(self.images)
# Create video clips from images
clips = []
tot_dur = 0
while tot_dur < max_duration:
for image_path in self.images:
clip = ImageClip(image_path)
clip.duration = req_dur
clip = clip.set_fps(30)
# Intelligent cropping for different aspect ratios
aspect_ratio = 9/16 # Standard vertical video ratio
if clip.w / clip.h < aspect_ratio:
clip = crop(
clip,
width=clip.w,
height=round(clip.w / aspect_ratio),
x_center=clip.w / 2,
y_center=clip.h / 2
)
else:
clip = crop(
clip,
width=round(aspect_ratio * clip.h),
height=clip.h,
x_center=clip.w / 2,
y_center=clip.h / 2
)
clip = clip.resize((1080, 1920)) # Hardcoded frame size for shorts
clips.append(clip)
tot_dur += clip.duration
# Break if we have enough duration
if tot_dur >= max_duration:
break
# Concatenate all clips
final_clip = concatenate_videoclips(clips)
final_clip = final_clip.set_fps(30)
# Add background music
random_music = choose_random_music()
random_music_clip = AudioFileClip(str(random_music))
random_music_clip = random_music_clip.fx(volumex, 0.1)
random_music_clip = random_music_clip.set_duration(max_duration)
# Generate subtitles if requested
word_highlighted_clips = []
if include_subtitles and subtitles_api_key:
word_highlighted_clips = self.generate_subtitles(self.tts_path, subtitles_api_key)
# Combine audio
comp_audio = CompositeAudioClip([
tts_clip,
random_music_clip
])
# Set audio and duration
final_clip = final_clip.set_audio(comp_audio)
final_clip = final_clip.set_duration(tts_clip.duration)
# Add subtitles if we have them
if word_highlighted_clips:
final_clip = CompositeVideoClip([final_clip] + word_highlighted_clips)
# Write video file
final_clip.write_videofile(output_path, threads=4)
# Save to output directory with a more descriptive name
safe_title = re.sub(r'[^\w\s-]', '', self.metadata["title"])
safe_title = re.sub(r'[-\s]+', '-', safe_title).strip('-_')
final_output = str(OUTPUT_DIR / f"{safe_title}_{int(time.time())}.mp4")
shutil.copy2(output_path, final_output)
self.video_path = final_output
return final_output
except Exception as e:
raise ValueError(f"Video generation failed: {str(e)}")
def generate_full_pipeline(
niche,
language,
img_provider,
img_model,
tts_engine,
tts_voice,
include_subtitles,
assemblyai_key,
progress=gr.Progress()
):
progress(0, desc="Initializing")
generator = YouTubeGenerator()
try:
# Step 1: Generate topic
progress(0.05, desc="Generating topic")
topic = generator.generate_topic(niche)
# Step 2: Generate script
progress(0.1, desc="Generating script")
script = generator.generate_script(topic, language)
# Step 3: Generate metadata
progress(0.15, desc="Generating metadata")
metadata = generator.generate_metadata(topic)
# Step 4: Generate image prompts
progress(0.2, desc="Generating image prompts")
image_prompts = generator.generate_prompts(topic, script)
# Step 5: Generate images
progress(0.3, desc="Generating images")
images = []
total_images = len(image_prompts)
for i, prompt in enumerate(image_prompts):
progress(0.3 + (0.3 * i/total_images), desc=f"Generating image {i+1}/{total_images}")
img_path = generator.generate_image(prompt, provider=img_provider, model=img_model)
images.append(img_path)
# Step 6: Generate speech
progress(0.6, desc="Generating speech")
tts_path = generator.generate_speech(script, engine=tts_engine, voice=tts_voice)
# Step 7: Combine into video
progress(0.8, desc="Creating video")
video_path = generator.combine_video(
include_subtitles=include_subtitles,
subtitles_api_key=assemblyai_key if include_subtitles else ""
)
progress(1.0, desc="Complete!")
return {
"topic": topic,
"script": script,
"title": metadata["title"],
"description": metadata["description"],
"image_prompts": "\n\n".join([f"{i+1}. {prompt}" for i, prompt in enumerate(image_prompts)]),
"images": images,
"audio": tts_path,
"video": video_path,
"video_html": f'
'
}
except Exception as e:
generator.clean_temp_files()
error_msg = str(e)
return {
"topic": f"ERROR: {error_msg}",
"script": "",
"title": "",
"description": "",
"image_prompts": "",
"images": [],
"audio": None,
"video": None,
"video_html": f'
Video generation failed: {error_msg}
'
}
def ui_component():
# Define UI components
with gr.Blocks(theme=gr.themes.Soft()) as app:
gr.Markdown("# YouTube Shorts Generator")
gr.Markdown("Generate complete YouTube Shorts videos with AI")
with gr.Tabs():
with gr.TabItem("Generate Video"):
with gr.Row():
with gr.Column():
# Input parameters
niche_input = gr.Textbox(label="Video Niche/Topic", placeholder="Historical Facts", value="Historical Facts")
language_input = gr.Dropdown(
label="Language",
choices=["English", "Spanish", "French", "German", "Italian", "Portuguese", "Russian", "Japanese", "Chinese", "Korean", "Arabic"],
value="English"
)
with gr.Accordion("Image Generation Settings", open=False):
img_provider = gr.Dropdown(
label="Image Provider",
choices=["g4f", "prodia", "pollinations"],
value="g4f"
)
img_model = gr.Dropdown(
label="Image Model",
choices=["sdxl-turbo", "sdxl", "stable-diffusion-3", "kandinsky-2.2", "midjourney"],
value="sdxl-turbo"
)
with gr.Accordion("TTS Settings", open=False):
tts_engine = gr.Dropdown(
label="TTS Engine",
choices=["edge", "gtts"],
value="edge"
)
tts_voice = gr.Dropdown(
label="TTS Voice",
choices=["en-US-ChristopherNeural", "en-US-GuyNeural", "en-US-JennyNeural", "en-US-AriaNeural", "en-GB-SoniaNeural", "en"],
value="en-US-ChristopherNeural"
)
with gr.Accordion("Subtitle Settings", open=False):
include_subtitles = gr.Checkbox(label="Generate Word-Level Subtitles", value=False)
assemblyai_key = gr.Textbox(
label="AssemblyAI API Key (required for subtitles)",
placeholder="Your AssemblyAI API Key",
type="password"
)
generate_btn = gr.Button("Generate Video", variant="primary")
with gr.Column():
# Output display
with gr.Accordion("Generated Content", open=True):
topic_output = gr.Textbox(label="Generated Topic")
script_output = gr.Textbox(label="Generated Script", lines=10)
title_output = gr.Textbox(label="Video Title")
description_output = gr.Textbox(label="Video Description", lines=5)
with gr.Accordion("Generated Assets", open=True):
prompts_output = gr.Textbox(label="Image Prompts", lines=5)
gallery_output = gr.Gallery(label="Generated Images")
audio_output = gr.Audio(label="Generated Speech")
video_output = gr.Video(label="Final Video")
video_html = gr.HTML(label="Video Player")
# Connect button to function
generate_btn.click(
generate_full_pipeline,
inputs=[
niche_input,
language_input,
img_provider,
img_model,
tts_engine,
tts_voice,
include_subtitles,
assemblyai_key
],
outputs={
"topic": topic_output,
"script": script_output,
"title": title_output,
"description": description_output,
"image_prompts": prompts_output,
"images": gallery_output,
"audio": audio_output,
"video": video_output,
"video_html": video_html
}
)
with gr.TabItem("Settings"):
gr.Markdown("## Advanced Settings")
with gr.Accordion("Storage Settings", open=True):
temp_dir = gr.Textbox(label="Temporary Directory", value=str(TEMP_DIR))
output_dir = gr.Textbox(label="Output Directory", value=str(OUTPUT_DIR))
music_dir = gr.Textbox(label="Music Directory", value=str(MUSIC_DIR))
def update_dirs(temp, output, music):
global TEMP_DIR, OUTPUT_DIR, MUSIC_DIR
TEMP_DIR = Path(temp)
OUTPUT_DIR = Path(output)
MUSIC_DIR = Path(music)
# Ensure directories exist
TEMP_DIR.mkdir(exist_ok=True)
OUTPUT_DIR.mkdir(exist_ok=True)
MUSIC_DIR.mkdir(exist_ok=True)
return f"Directories updated: {temp}, {output}, {music}"
update_dirs_btn = gr.Button("Update Directories")
dirs_status = gr.Textbox(label="Status")
update_dirs_btn.click(
update_dirs,
inputs=[temp_dir, output_dir, music_dir],
outputs=dirs_status
)
with gr.Accordion("Add Background Music", open=True):
music_file = gr.File(label="Upload Music File (MP3)")
def add_music(file):
if file is None:
return "No file selected"
try:
filename = os.path.basename(file.name)
dest_path = MUSIC_DIR / filename
shutil.copy2(file.name, dest_path)
return f"Music file added: {filename}"
except Exception as e:
return f"Error adding music: {str(e)}"
add_music_btn = gr.Button("Add Music")
music_status = gr.Textbox(label="Status")
add_music_btn.click(
add_music,
inputs=music_file,
outputs=music_status
)
with gr.Accordion("Cleanup", open=True):
def clean_temp():
try:
for file in TEMP_DIR.glob("*"):
file.unlink()
return "Temporary files cleaned successfully"
except Exception as e:
return f"Error cleaning files: {str(e)}"
clean_temp_btn = gr.Button("Clean Temporary Files")
clean_status = gr.Textbox(label="Status")
clean_temp_btn.click(
clean_temp,
outputs=clean_status
)
with gr.TabItem("Help"):
gr.Markdown("""
# Help & Troubleshooting
## Common Issues
### Image Generation
- **G4F Issues**: If image generation with G4F fails, try switching to "prodia" or "pollinations" provider
- **Model Compatibility**: Not all models work with all providers. If you get errors, try a different model/provider combination
### TTS Issues
- **Edge TTS Voice Error**: If you get "No audio was received" error, try a different voice like "en-US-ChristopherNeural"
- **Google TTS**: For simplicity, use Google TTS with language code "en" if Edge TTS isn't working
### Video Generation
- **Video Creation Errors**: Make sure all images were successfully generated before creating the video
- **Subtitle Issues**: Subtitles require an AssemblyAI API key. You can get a free one at [AssemblyAI](https://www.assemblyai.com/)
## Tips for Best Results
1. **Topics**: Be specific with your niche/topic for better results
2. **Images**: SDXL Turbo is fastest, but other models may give better quality
3. **TTS**: Edge TTS generally gives the best quality voice with "en-US-ChristopherNeural"
4. **Background Music**: Add your own music files for better video quality
""")
return app
if __name__ == "__main__":
app = ui_component()
app.launch()