diff --git a/TTS/engine_wrapper.py b/TTS/engine_wrapper.py index c1d3bf6..f30330a 100644 --- a/TTS/engine_wrapper.py +++ b/TTS/engine_wrapper.py @@ -77,7 +77,7 @@ class TTSEngine: self.add_periods() self.call_tts("title", process_text(self.reddit_object["thread_title"])) # processed_text = ##self.reddit_object["thread_post"] != "" - idx = None + idx = 0 if settings.config["settings"]["storymode"]: if settings.config["settings"]["storymodemethod"] == 0: diff --git a/main.py b/main.py index 5624d87..654f22f 100755 --- a/main.py +++ b/main.py @@ -1,10 +1,10 @@ #!/usr/bin/env python import math import sys -from logging import error from os import name from pathlib import Path from subprocess import Popen +from typing import NoReturn import ffmpeg from prawcore import ResponseException @@ -59,11 +59,8 @@ def main(POST_ID=None) -> None: download_background_video(bg_config["video"]) download_background_audio(bg_config["audio"]) chop_background(bg_config, length, reddit_object) - try: - make_final_video(number_of_comments, length, reddit_object, bg_config) - except ffmpeg.Error as e: - print(e.stderr.decode("utf8")) - exit(1) + make_final_video(number_of_comments, length, reddit_object, bg_config) + def run_many(times) -> None: @@ -75,29 +72,31 @@ def run_many(times) -> None: Popen("cls" if name == "nt" else "clear", shell=True).wait() -def shutdown(): - try: - redditid - except NameError: - print("Exiting...") - exit() - else: +def shutdown() -> NoReturn: + + if "redditid" in globals : print_markdown("## Clearing temp files") cleanup(redditid) print("Exiting...") - exit() + sys.exit() + + print("Exiting...") + sys.exit() + + if __name__ == "__main__": if sys.version_info.major != 3 or sys.version_info.minor != 10: 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.") - exit() + sys.exit() ffmpeg_install() # install ffmpeg if not installed directory = Path().absolute() config = settings.check_toml( - f"{directory}/utils/.config.template.toml", "config.toml" + f"{directory}/utils/.config.template.toml", f"{directory}/config.toml" ) - config is False and exit() + if not config : + sys.exit() if ( not settings.config["settings"]["tts"]["tiktok_sessionid"] or settings.config["settings"]["tts"]["tiktok_sessionid"] == "" @@ -106,7 +105,7 @@ if __name__ == "__main__": "TikTok voice requires a sessionid! Check our documentation on how to obtain one.", "bold red", ) - exit() + sys.exit() try: if config["reddit"]["thread"]["post_id"]: for index, post_id in enumerate( diff --git a/run.bat b/run.bat new file mode 100644 index 0000000..b37ea3b --- /dev/null +++ b/run.bat @@ -0,0 +1,20 @@ +@echo off +set VENV_DIR=.venv + +if exist "%VENV_DIR%" ( + echo Activating virtual environment... + call "%VENV_DIR%\Scripts\activate.bat" +) + +echo Running Python script... +python main.py + +if errorlevel 1 ( + echo An error occurred. Press any key to exit. + pause >nul +) + +if exist "%VENV_DIR%" ( + echo Deactivating virtual environment... + call "%VENV_DIR%\Scripts\deactivate.bat" +) diff --git a/utils/cleanup.py b/utils/cleanup.py index 65b59b0..6e00d4c 100644 --- a/utils/cleanup.py +++ b/utils/cleanup.py @@ -1,31 +1,20 @@ import os from os.path import exists +import shutil def _listdir(d): # listdir with full path return [os.path.join(d, f) for f in os.listdir(d)] -def cleanup(id) -> int: +def cleanup(reddit_id) -> int: """Deletes all temporary assets in assets/temp Returns: int: How many files were deleted """ - if exists(f"../assets/temp/{id}/"): - count = 0 - files = [ - f for f in os.listdir(".") if f.endswith(".mp4") and "temp" in f.lower() - ] - count += len(files) - for f in files: - os.remove(f"../assets/temp/{id}/{f}") - REMOVE_DIRS = [f"../assets/temp/{id}/mp3/", f"../assets/temp/{id}/png/"] - for d in REMOVE_DIRS: - if exists(d): - count += len(_listdir(d)) - for f in _listdir(d): - os.remove(f) - os.rmdir(d) - os.rmdir(f"../assets/temp/{id}/") - return count + directory = f"../assets/temp/{reddit_id}/" + if exists(directory): + shutil.rmtree(directory) + + return 1 diff --git a/utils/ffmpeg_install.py b/utils/ffmpeg_install.py index 5522028..87a6a98 100644 --- a/utils/ffmpeg_install.py +++ b/utils/ffmpeg_install.py @@ -17,13 +17,11 @@ def ffmpeg_install_windows(): os.rename("ffmpeg-master-latest-win64-gpl", "ffmpeg") # Move the files inside bin to the root for file in os.listdir("ffmpeg/bin"): - os.rename(f"ffmpeg/bin/{file}", f"ffmpeg/{file}") + os.rename(f"ffmpeg/bin/{file}", f"./{file}") os.rmdir("ffmpeg/bin") for file in os.listdir("ffmpeg/doc"): os.remove(f"ffmpeg/doc/{file}") os.rmdir("ffmpeg/doc") - # Add to the path - subprocess.run("setx /M PATH \"%PATH%;%CD%\\ffmpeg\"", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print("FFmpeg installed successfully! Please restart your computer and then re-run the program.") exit() except Exception as e: @@ -60,7 +58,8 @@ def ffmpeg_install(): try: # Try to run the FFmpeg command subprocess.run(['ffmpeg', '-version'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - print('FFmpeg is installed on this system! If you are seeing this error for the second time, restart your computer.') + if not os.path.exists("./results") : + print('FFmpeg is installed on this system! If you are seeing this error for the second time, restart your computer.') except FileNotFoundError as e: print('FFmpeg is not installed on this system.') resp = input("We can try to automatically install it for you. Would you like to do that? (y/n): ") diff --git a/utils/posttextparser.py b/utils/posttextparser.py index 9b1e306..e7f6840 100644 --- a/utils/posttextparser.py +++ b/utils/posttextparser.py @@ -1,4 +1,6 @@ +import os import re +from typing import List import spacy @@ -7,25 +9,25 @@ from utils.voice import sanitize_text # working good -def posttextparser(obj): - text = re.sub("\n", "", obj) +def posttextparser(obj,*,tried:bool=False) -> List[str]: + text:str = re.sub("\n", " ", obj) try: nlp = spacy.load("en_core_web_sm") - except OSError: - print_step( - "The spacy model can't load. You need to install it with the command \npython -m spacy download en_core_web_sm" - ) - exit() - + except OSError as e: + if not tried: + os.system("python -m spacy download en_core_web_sm") + return posttextparser(obj,tried) + + print_step(" The spacy model can't load. You need to install it with the command \npython -m spacy download en_core_web_sm ") + raise e + doc = nlp(text) newtext: list = [] - # to check for space str for line in doc.sents: if sanitize_text(line.text): newtext.append(line.text) - # print(line) return newtext diff --git a/video_creation/background.py b/video_creation/background.py index 010f15e..6f83f4c 100644 --- a/video_creation/background.py +++ b/video_creation/background.py @@ -25,8 +25,6 @@ def load_background_options(): del background_options["video"]["__comment"] del background_options["audio"]["__comment"] - # Add position lambda function - # (https://zulko.github.io/moviepy/ref/VideoClip/VideoClip.html#moviepy.video.VideoClip.VideoClip.set_position) for name in list(background_options["video"].keys()): pos = background_options["video"][name][3] diff --git a/video_creation/final_video.py b/video_creation/final_video.py index a74fec4..2fdc4a8 100644 --- a/video_creation/final_video.py +++ b/video_creation/final_video.py @@ -98,9 +98,9 @@ def prepare_background(reddit_id: str, W: int, H: int) -> str: ) try: output.run(quiet=True) - except Exception as e: - print(e) - exit() + except ffmpeg.Error as e: + print(e.stderr.decode("utf8")) + exit(1) return output_path def merge_background_audio(audio: ffmpeg, reddit_id: str): @@ -337,7 +337,7 @@ def make_final_video( text=text, x=f"(w-text_w)", y=f"(h-text_h)", - fontsize=12, + fontsize=5, fontcolor="White", fontfile=os.path.join("fonts", "Roboto-Regular.ttf"), ) @@ -346,7 +346,7 @@ def make_final_video( pbar = tqdm(total=100, desc="Progress: ", bar_format="{l_bar}{bar}", unit=" %") - def on_update_example(progress): + def on_update_example(progress) -> None: status = round(progress * 100, 2) old_percentage = pbar.n pbar.update(status - old_percentage) @@ -379,23 +379,27 @@ def make_final_video( path = path[:251] + ".mp4" #Prevent a error by limiting the path length, do not change this. print_step("Rendering the Only TTS Video 🎥") with ProgressFfmpeg(length, on_update_example) as progress: - ffmpeg.output( - background_clip, - audio, - path, - f="mp4", - **{ - "c:v": "h264", - "b:v": "20M", - "b:a": "192k", - "threads": multiprocessing.cpu_count(), - }, - ).overwrite_output().global_args("-progress", progress.output_file.name).run( - quiet=True, - overwrite_output=True, - capture_stdout=False, - capture_stderr=False, - ) + try: + ffmpeg.output( + background_clip, + audio, + path, + f="mp4", + **{ + "c:v": "h264", + "b:v": "20M", + "b:a": "192k", + "threads": multiprocessing.cpu_count(), + }, + ).overwrite_output().global_args("-progress", progress.output_file.name).run( + quiet=True, + overwrite_output=True, + capture_stdout=False, + capture_stderr=False, + ) + except ffmpeg.Error as e: + print(e.stderr.decode("utf8")) + exit(1) old_percentage = pbar.n pbar.update(100 - old_percentage) pbar.close()