The issues you're running into are likely due to misplaced indentation, incorrect function structure, or perhaps some typos. Let's integrate your updates and ensure the functions are correctly implemented. Below is the provided code with the updates incorporated as specified:
#!/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
import ctypes
from datetime import datetime
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"
# Windows path handling setup
if os.name == 'nt':
def enable_long_paths():
"""Enable long path support on Windows"""
try:
long_path_reg = ctypes.windll.kernel32.SetDllDirectoryW(None)
return long_path_reg != 0
except Exception:
return False
LONG_PATHS_ENABLED = enable_long_paths()
def sanitize_filename(filename: str) -> str:
"""Sanitize just the filename portion, not the full path"""
if os.name == 'nt':
# Remove invalid filename characters
filename = re.sub(r'[<>:"/\\|?*]', '_', filename)
# Limit filename length
if len(filename) > 240:
base, ext = os.path.splitext(filename)
filename = base[:240-len(ext)] + ext
return filename
def prepare_path(path: str) -> str:
"""Handle full paths while preserving structure"""
if os.name == 'nt':
abs_path = os.path.abspath(path)
if LONG_PATHS_ENABLED and len(abs_path) > 260:
return "\\\\?\\" + abs_path
return abs_path
return path
def build_path(base_dir: str, *parts) -> str:
"""Build a path preserving structure but sanitizing filenames"""
path = prepare_path(base_dir)
for part in parts:
if '.' in part:
part = sanitize_filename(part)
path = os.path.join(path, part)
return prepare_path(path)
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 find_latest_video(directory: str) -> str:
"""Find the latest video file in a directory, handling long paths"""
try:
directory = prepare_path(directory)
if not os.path.exists(directory):
print_substep(f"Directory not found: {directory}")
return None
mp4_files = []
for file in os.listdir(directory):
if file.endswith('.mp4') and not file.endswith('_out.mp4'):
try:
full_path = build_path(directory, file)
print_substep(f"Found video file: {full_path}")
if os.path.exists(full_path):
mp4_files.append((full_path, os.path.getctime(full_path)))
except Exception as e:
print_substep(f"Error processing file {file}: {str(e)}")
continue
if not mp4_files:
print_substep("No uncaptioned MP4 files found in directory")
if os.path.exists(directory):
print_substep("Files in directory:")
for file in os.listdir(directory):
print_substep(f"- {file}")
return None
latest_file = max(mp4_files, key=lambda x: x[1])[0]
print_substep(f"Selected latest video: {os.path.basename(latest_file)}")
return latest_file
except Exception as e:
print_substep(f"Error finding latest video: {str(e)}")
return None
def process_captions(video_path: str, iteration: int, total_iterations: int) -> bool:
"""Process captions for a video file"""
try:
print_substep(f"Starting caption process {iteration}/{total_iterations}")
print_substep(f"Processing: {os.path.basename(video_path)}")
if not os.path.exists(video_path):
print_substep(f"Video file not found: {video_path}")
return False
output_video = os.path.splitext(video_path)[0] + "_out.mp4"
if os.path.exists(output_video):
print_substep(f"Captioned version already exists: {os.path.basename(output_video)}")
return True
font_path = "fonts/Rubik-Black.ttf"
if not os.path.exists(font_path):
print_substep(f"Font file not found at: {font_path}")
return False
caption_cmd = f'python captionGen.py "{video_path}" --font "{font_path}"'
print_substep(f"Running caption command: {caption_cmd}")
result = subprocess.run(caption_cmd, shell=True, capture_output=True, text=True)
if result.returncode == 0:
if os.path.exists(output_video):
print_substep("Caption generation completed successfully")
return True
else:
print_substep("Caption generation failed: Output file not created")
return False
else:
print_substep(f"Caption generation failed: {result.stderr}")
return False
except Exception as e:
print_substep(f"Error in caption generation: {str(e)}")
return False
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("╰─────────────────────────────────────────────╯")
try:
base_dir = os.path.dirname(os.path.abspath(__file__))
subreddit = settings.config["reddit"]["thread"]["subreddit"]
results_dir = build_path(base_dir, "results", subreddit)
print_substep(f"Using results directory: {results_dir}")
video_path = None
if redditid:
id_path = build_path(results_dir, f"{redditid}.mp4")
if os.path.exists(id_path):
video_path = id_path
print_substep(f"Found video by ID: {redditid}")
if not video_path and reddit_object and 'thread_title' in reddit_object:
title_path = build_path(results_dir, f"{reddit_object['thread_title']}.mp4")
if os.path.exists(title_path):
video_path = title_path
print_substep(f"Found video by title")
if not video_path:
print_substep("Searching for most recent video...")
video_path = find_latest_video(results_dir)
if video_path and os.path.exists(video_path):
return video_path
else:
print_substep("Could not find video file!")
if os.path.exists(results_dir):
print_substep("Available files in results directory:")
for file in os.listdir(results_dir):
print_substep(f"- {file}")
return None
except Exception as e:
print_substep(f"Error in video processing: {str(e)}")
return None
def run_many(times) -> None:
processed_videos = []
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}'
)
try:
video_path = main()
if video_path:
processed_videos.append(video_path)
process_captions(video_path, x, times)
print("\n" + "="*80 + "\n")
except Exception as e:
print_substep(f"Error in iteration {x}: {str(e)}")
continue
print_step("Processing Summary:")
for idx, video in enumerate(processed_videos, 1):
print_substep(f"Video {idx}: {os.path.basename(video)}")
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)
elif config["settings"]["times_to_run"]:
run_many(config["settings"]["times_to_run"])
else:
video_path = main()
if video_path:
process_captions(video_path, 1, 1)
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
Key changes and updates:
- Indents & Syntax: Ensured correct indentation throughout the code and fixed any minor syntax issues.
- Updated Functions: Incorporated your provided updates into
run_many() and process_captions() functions, making sure they correctly execute your planned updates.
- Error Handling: Added error handling and more robust substep printing to assist in debugging runtime errors.
- Python Version Check: Adjusted the version check to allow for Python versions beyond just 3.10, since compatibility with versions like 3.11 and 3.12 might be planned, but ensure compatibility according to the requirements.
Please review the changes and test the code to ensure it addresses the syntax issues you initially faced.