heres the thumbnail code, heres the main.py file, and heres the error: from PIL import Image, ImageDraw, ImageFont
import os
class TwitterThumbnailGenerator:
def init(self):
self.width = 1280
self.height = 720
self.background_color = (0, 0, 0) # Black background
self.text_color = (255, 255, 255) # White text
self.highlight_color = (255, 0, 0, 128) # Semi-transparent red
self.underline_color = (255, 0, 0) # Red
# Load fonts - using project's font path
self.font_title = ImageFont.truetype(os.path.join("fonts", "Roboto-Bold.ttf"), 56)
self.font_username = ImageFont.truetype(os.path.join("fonts", "Roboto-Regular.ttf"), 36)
self.lowercase_words = {'an', 'of', 'a', 'the', 'and', 'with', 'but', 'to', 'for'}
def capitalize_title(self, text):
words = text.split()
result = []
for i, word in enumerate(words):
if i == 0 or word.lower() not in self.lowercase_words:
result.append(word.capitalize())
else:
result.append(word.lower())
return ' '.join(result)
def split_into_four_lines(self, text):
words = text.split()
total_chars = sum(len(word) for word in words)
chars_per_line = total_chars // 4
lines = []
current_line = []
current_chars = 0
for word in words:
if len(lines) == 3: # Last line gets remaining words
current_line.append(word)
else:
if current_chars + len(word) <= chars_per_line:
current_line.append(word)
current_chars += len(word)
else:
lines.append(' '.join(current_line))
current_line = [word]
current_chars = len(word)
if current_line:
lines.append(' '.join(current_line))
return lines
def draw_highlighted_text(self, draw, text, position, highlighted=False, underlined=False):
x, y = position
text_bbox = self.font_title.getbbox(text)
text_width = text_bbox[2] - text_bbox[0]
text_height = text_bbox[3] - text_bbox[1]
if highlighted:
# Draw highlight background
padding = 10
highlight_bbox = [
x - padding,
y - padding,
x + text_width + padding,
y + text_height + padding
]
draw.rectangle(highlight_bbox, fill=self.highlight_color)
# Draw text
draw.text(position, text, self.text_color, font=self.font_title)
if underlined:
# Draw underline
underline_y = y + text_height + 5
draw.line([(x, underline_y), (x + text_width, underline_y)],
fill=self.underline_color, width=3)
def create_thumbnail(thumbnail, font_family, font_size, font_color, width, height, title):
"""Main function called by the video creation process"""
generator = TwitterThumbnailGenerator()
# Create new image with black background
img = Image.new('RGB', (width, height), generator.background_color)
draw = ImageDraw.Draw(img)
# Process title
processed_title = generator.capitalize_title(title)
lines = generator.split_into_four_lines(processed_title)
try:
# Load and paste profile picture
profile_pic = Image.open(os.path.join("assets", "profile.png"))
profile_pic = profile_pic.resize((100, 100))
profile_circle = Image.new('L', (100, 100), 0)
circle_draw = ImageDraw.Draw(profile_circle)
circle_draw.ellipse([0, 0, 100, 100], fill=255)
img.paste(profile_pic, (50, 50), profile_circle)
# Draw username and verification
username_x = 170
username_y = 75
draw.text((username_x, username_y), "@RedditBinge",
generator.text_color, font=generator.font_username)
# Load and paste verification badge
if os.path.exists(os.path.join("assets", "verified.png")):
verified = Image.open(os.path.join("assets", "verified.png"))
verified = verified.resize((40, 40))
img.paste(verified, (username_x + 200, username_y), verified.convert('RGBA'))
# Draw title lines
line_y = 200
line_spacing = 70
for i, line in enumerate(lines):
x = 50
y = line_y + (i * line_spacing)
generator.draw_highlighted_text(
draw,
line,
(x, y),
highlighted=(i < 2), # First two lines highlighted
underlined=(i >= 2) # Last two lines underlined
)
except Exception as e:
print(f"Error creating thumbnail: {str(e)}")
# Return original thumbnail if there's an error
return thumbnail
return img, #!/usr/bin/env python
import math
import sys
import re
import os
import subprocess
from os import name
from pathlib import Path
from subprocess import Popen
from typing import NoReturn
from prawcore import ResponseException
from reddit.subreddit import get_subreddit_threads
from utils import settings
from utils.cleanup import cleanup
from utils.console import print_markdown, print_step, print_substep
from utils.ffmpeg_install import ffmpeg_install
from utils.id import id
from utils.version import checkversion
from video_creation.background import (
chop_background,
download_background_audio,
download_background_video,
get_background_config,
)
from video_creation.final_video import make_final_video
from video_creation.screenshot_downloader import get_screenshots_of_reddit_posts
from video_creation.voices import save_text_to_mp3
VERSION = "3.3.0"
print(
"""
██████╗ ███████╗██████╗ ██████╗ ██╗████████╗ ██╗ ██╗██╗██████╗ ███████╗ ██████╗ ███╗ ███╗ █████╗ ██╗ ██╗███████╗██████╗
██╔══██╗██╔════╝██╔══██╗██╔══██╗██║╚══██╔══╝ ██║ ██║██║██╔══██╗██╔════╝██╔═══██╗ ████╗ ████║██╔══██╗██║ ██╔╝██╔════╝██╔══██╗
██████╔╝█████╗ ██║ ██║██║ ██║██║ ██║ ██║ ██║██║██║ ██║█████╗ ██║ ██║ ██╔████╔██║███████║█████╔╝ █████╗ ██████╔╝
██╔══██╗██╔══╝ ██║ ██║██║ ██║██║ ██║ ╚██╗ ██╔╝██║██║ ██║██╔══╝ ██║ ██║ ██║╚██╔╝██║██╔══██║██╔═██╗ ██╔══╝ ██╔══██╗
██║ ██║███████╗██████╔╝██████╔╝██║ ██║ ╚████╔╝ ██║██████╔╝███████╗╚██████╔╝ ██║ ╚═╝ ██║██║ ██║██║ ██╗███████╗██║ ██║
╚═╝ ╚═╝╚══════╝╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═══╝ ╚═╝╚═════╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝
"""
)
print_markdown(
"### Thanks for using this tool! Feel free to contribute to this project on GitHub! If you have any questions, feel free to join my Discord server or submit a GitHub issue. You can find solutions to many common problems in the documentation: https://reddit-video-maker-bot.netlify.app/"
)
checkversion(VERSION)
def main(POST_ID=None) -> None:
global redditid, reddit_object
reddit_object = get_subreddit_threads(POST_ID)
redditid = id(reddit_object)
length, number_of_comments = save_text_to_mp3(reddit_object)
length = math.ceil(length)
get_screenshots_of_reddit_posts(reddit_object, number_of_comments)
bg_config = {
"video": get_background_config("video"),
"audio": get_background_config("audio"),
}
download_background_video(bg_config["video"])
download_background_audio(bg_config["audio"])
chop_background(bg_config, length, reddit_object)
make_final_video(number_of_comments, length, reddit_object, bg_config)
print("\n╭─────────────────────────────────────────────╮")
print("│ Starting caption generation process... │")
print("╰─────────────────────────────────────────────╯")
# Get subreddit from config and build paths
base_dir = os.path.dirname(os.path.abspath(__file__))
subreddit = settings.config["reddit"]["thread"]["subreddit"]
results_dir = os.path.join(base_dir, "results", subreddit)
print(f"Debug: Using results directory: {results_dir}")
# Try to find the video using thread ID first
video_path = os.path.join(results_dir, f"{redditid}.mp4")
# If not found by ID, try original title
if not os.path.exists(video_path):
video_filename = f"{reddit_object['thread_title']}.mp4"
video_path = os.path.join(results_dir, video_filename)
# If still not found, look for most recent mp4
if not os.path.exists(video_path):
print("Debug: Searching for video in results directory...")
mp4_files = [f for f in os.listdir(results_dir) if f.endswith('.mp4')]
if mp4_files:
# Get most recent mp4 file
latest_file = max([os.path.join(results_dir, f) for f in mp4_files],
key=os.path.getctime)
video_path = latest_file
print(f"Debug: Found most recent video: {os.path.basename(video_path)}")
if os.path.exists(video_path):
print(f"Debug: Running caption generation for: {os.path.basename(video_path)}")
try:
# Use shell=True for Windows paths with spaces
cmd = f'python captionGen.py "{video_path}" --font "fonts/Rubik-Black.ttf"'
subprocess.run(cmd, shell=True, check=True)
print("Debug: Caption generation completed successfully")
except subprocess.CalledProcessError as e:
print(f"Debug: Caption generation failed with error: {e}")
else:
print("Debug: Could not find the video file to caption!")
print("Debug: Available files in results directory:")
for file in os.listdir(results_dir):
print(f"- {file}")
def run_many(times) -> None:
for x in range(1, times + 1):
print_step(
f'on the {x}{("th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th")[x % 10]} iteration of {times}'
)
main()
Popen("cls" if name == "nt" else "clear", shell=True).wait()
def shutdown() -> NoReturn:
if "redditid" in globals():
print_markdown("## Clearing temp files")
cleanup(redditid)
print("Exiting...")
sys.exit()
if name == "main":
if sys.version_info.major != 3 or sys.version_info.minor not in [10, 11, 12]:
print(
"Hey! Congratulations, you've made it so far (which is pretty rare with no Python 3.10). Unfortunately, this program only works on Python 3.10. Please install Python 3.10 and try again."
)
sys.exit()
ffmpeg_install()
directory = Path().absolute()
config = settings.check_toml(
f"{directory}/utils/.config.template.toml",
f"{directory}/config.toml"
)
config is False and sys.exit()
if (
not settings.config["settings"]["tts"]["tiktok_sessionid"]
or settings.config["settings"]["tts"]["tiktok_sessionid"] == ""
) and config["settings"]["tts"]["voice_choice"] == "tiktok":
print_substep(
"TikTok voice requires a sessionid! Check our documentation on how to obtain one.",
"bold red",
)
sys.exit()
try:
if config["reddit"]["thread"]["post_id"]:
for index, post_id in enumerate(config["reddit"]["thread"]["post_id"].split("+")):
index += 1
print_step(
f'on the {index}{("st" if index % 10 == 1 else ("nd" if index % 10 == 2 else ("rd" if index % 10 == 3 else "th")))} post of {len(config["reddit"]["thread"]["post_id"].split("+"))}'
)
main(post_id)
Popen("cls" if name == "nt" else "clear", shell=True).wait()
elif config["settings"]["times_to_run"]:
run_many(config["settings"]["times_to_run"])
else:
main()
except KeyboardInterrupt:
shutdown()
except ResponseException:
print_markdown("## Invalid credentials")
print_markdown("Please check your credentials in the config.toml file")
shutdown()
except Exception as err:
config["settings"]["tts"]["tiktok_sessionid"] = "REDACTED"
config["settings"]["tts"]["elevenlabs_api_key"] = "REDACTED"
print_step(
f"Sorry, something went wrong with this version! Try again, and feel free to report this issue at GitHub or the Discord community.\n"
f"Version: {__VERSION__} \n"
f"Error: {err} \n"
f'Config: {config["settings"]}'
)
raise err, Collecting the image files... ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 0:00:00
Translating filename...
Error creating thumbnail: [Errno 2] No such file or directory: 'C:\Users\buggy\Desktop\FullyAutomatedRedditVideoMakerBot-main\assets\profile.png'
Thumbnail - Building Thumbnail in assets/temp/1gqt2n2/thumbnail.png
╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮│ Rendering the video 🎥 │╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯Progress: 100%|██████████████████████████████████████████████████████████