better err handle and run.bat

pull/1671/head
electro199 2 years ago
parent 7486e04b26
commit 4a83cd0f6f

@ -77,7 +77,7 @@ class TTSEngine:
self.add_periods() self.add_periods()
self.call_tts("title", process_text(self.reddit_object["thread_title"])) self.call_tts("title", process_text(self.reddit_object["thread_title"]))
# processed_text = ##self.reddit_object["thread_post"] != "" # processed_text = ##self.reddit_object["thread_post"] != ""
idx = None idx = 0
if settings.config["settings"]["storymode"]: if settings.config["settings"]["storymode"]:
if settings.config["settings"]["storymodemethod"] == 0: if settings.config["settings"]["storymodemethod"] == 0:

@ -1,10 +1,10 @@
#!/usr/bin/env python #!/usr/bin/env python
import math import math
import sys import sys
from logging import error
from os import name from os import name
from pathlib import Path from pathlib import Path
from subprocess import Popen from subprocess import Popen
from typing import NoReturn
import ffmpeg import ffmpeg
from prawcore import ResponseException from prawcore import ResponseException
@ -59,11 +59,8 @@ def main(POST_ID=None) -> None:
download_background_video(bg_config["video"]) download_background_video(bg_config["video"])
download_background_audio(bg_config["audio"]) download_background_audio(bg_config["audio"])
chop_background(bg_config, length, reddit_object) chop_background(bg_config, length, reddit_object)
try:
make_final_video(number_of_comments, length, reddit_object, bg_config) make_final_video(number_of_comments, length, reddit_object, bg_config)
except ffmpeg.Error as e:
print(e.stderr.decode("utf8"))
exit(1)
def run_many(times) -> None: def run_many(times) -> None:
@ -75,29 +72,31 @@ def run_many(times) -> None:
Popen("cls" if name == "nt" else "clear", shell=True).wait() Popen("cls" if name == "nt" else "clear", shell=True).wait()
def shutdown(): def shutdown() -> NoReturn:
try:
redditid if "redditid" in globals :
except NameError:
print("Exiting...")
exit()
else:
print_markdown("## Clearing temp files") print_markdown("## Clearing temp files")
cleanup(redditid) cleanup(redditid)
print("Exiting...") print("Exiting...")
exit() sys.exit()
print("Exiting...")
sys.exit()
if __name__ == "__main__": if __name__ == "__main__":
if sys.version_info.major != 3 or sys.version_info.minor != 10: 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.") 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 ffmpeg_install() # install ffmpeg if not installed
directory = Path().absolute() directory = Path().absolute()
config = settings.check_toml( 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 ( if (
not settings.config["settings"]["tts"]["tiktok_sessionid"] not settings.config["settings"]["tts"]["tiktok_sessionid"]
or 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.", "TikTok voice requires a sessionid! Check our documentation on how to obtain one.",
"bold red", "bold red",
) )
exit() sys.exit()
try: try:
if config["reddit"]["thread"]["post_id"]: if config["reddit"]["thread"]["post_id"]:
for index, post_id in enumerate( for index, post_id in enumerate(

@ -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"
)

@ -1,31 +1,20 @@
import os import os
from os.path import exists from os.path import exists
import shutil
def _listdir(d): # listdir with full path def _listdir(d): # listdir with full path
return [os.path.join(d, f) for f in os.listdir(d)] 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 """Deletes all temporary assets in assets/temp
Returns: Returns:
int: How many files were deleted int: How many files were deleted
""" """
if exists(f"../assets/temp/{id}/"): directory = f"../assets/temp/{reddit_id}/"
count = 0 if exists(directory):
files = [ shutil.rmtree(directory)
f for f in os.listdir(".") if f.endswith(".mp4") and "temp" in f.lower()
] return 1
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

@ -17,13 +17,11 @@ def ffmpeg_install_windows():
os.rename("ffmpeg-master-latest-win64-gpl", "ffmpeg") os.rename("ffmpeg-master-latest-win64-gpl", "ffmpeg")
# Move the files inside bin to the root # Move the files inside bin to the root
for file in os.listdir("ffmpeg/bin"): 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") os.rmdir("ffmpeg/bin")
for file in os.listdir("ffmpeg/doc"): for file in os.listdir("ffmpeg/doc"):
os.remove(f"ffmpeg/doc/{file}") os.remove(f"ffmpeg/doc/{file}")
os.rmdir("ffmpeg/doc") 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.") print("FFmpeg installed successfully! Please restart your computer and then re-run the program.")
exit() exit()
except Exception as e: except Exception as e:
@ -60,6 +58,7 @@ def ffmpeg_install():
try: try:
# Try to run the FFmpeg command # Try to run the FFmpeg command
subprocess.run(['ffmpeg', '-version'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) subprocess.run(['ffmpeg', '-version'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
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.') print('FFmpeg is installed on this system! If you are seeing this error for the second time, restart your computer.')
except FileNotFoundError as e: except FileNotFoundError as e:
print('FFmpeg is not installed on this system.') print('FFmpeg is not installed on this system.')

@ -1,4 +1,6 @@
import os
import re import re
from typing import List
import spacy import spacy
@ -7,25 +9,25 @@ from utils.voice import sanitize_text
# working good # working good
def posttextparser(obj): def posttextparser(obj,*,tried:bool=False) -> List[str]:
text = re.sub("\n", "", obj) text:str = re.sub("\n", " ", obj)
try: try:
nlp = spacy.load("en_core_web_sm") nlp = spacy.load("en_core_web_sm")
except OSError: except OSError as e:
print_step( if not tried:
"The spacy model can't load. You need to install it with the command \npython -m spacy download en_core_web_sm" os.system("python -m spacy download en_core_web_sm")
) return posttextparser(obj,tried)
exit()
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) doc = nlp(text)
newtext: list = [] newtext: list = []
# to check for space str
for line in doc.sents: for line in doc.sents:
if sanitize_text(line.text): if sanitize_text(line.text):
newtext.append(line.text) newtext.append(line.text)
# print(line)
return newtext return newtext

@ -25,8 +25,6 @@ def load_background_options():
del background_options["video"]["__comment"] del background_options["video"]["__comment"]
del background_options["audio"]["__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()): for name in list(background_options["video"].keys()):
pos = background_options["video"][name][3] pos = background_options["video"][name][3]

@ -98,9 +98,9 @@ def prepare_background(reddit_id: str, W: int, H: int) -> str:
) )
try: try:
output.run(quiet=True) output.run(quiet=True)
except Exception as e: except ffmpeg.Error as e:
print(e) print(e.stderr.decode("utf8"))
exit() exit(1)
return output_path return output_path
def merge_background_audio(audio: ffmpeg, reddit_id: str): def merge_background_audio(audio: ffmpeg, reddit_id: str):
@ -337,7 +337,7 @@ def make_final_video(
text=text, text=text,
x=f"(w-text_w)", x=f"(w-text_w)",
y=f"(h-text_h)", y=f"(h-text_h)",
fontsize=12, fontsize=5,
fontcolor="White", fontcolor="White",
fontfile=os.path.join("fonts", "Roboto-Regular.ttf"), 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=" %") 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) status = round(progress * 100, 2)
old_percentage = pbar.n old_percentage = pbar.n
pbar.update(status - old_percentage) pbar.update(status - old_percentage)
@ -379,6 +379,7 @@ def make_final_video(
path = path[:251] + ".mp4" #Prevent a error by limiting the path length, do not change this. path = path[:251] + ".mp4" #Prevent a error by limiting the path length, do not change this.
print_step("Rendering the Only TTS Video 🎥") print_step("Rendering the Only TTS Video 🎥")
with ProgressFfmpeg(length, on_update_example) as progress: with ProgressFfmpeg(length, on_update_example) as progress:
try:
ffmpeg.output( ffmpeg.output(
background_clip, background_clip,
audio, audio,
@ -396,6 +397,9 @@ def make_final_video(
capture_stdout=False, capture_stdout=False,
capture_stderr=False, capture_stderr=False,
) )
except ffmpeg.Error as e:
print(e.stderr.decode("utf8"))
exit(1)
old_percentage = pbar.n old_percentage = pbar.n
pbar.update(100 - old_percentage) pbar.update(100 - old_percentage)
pbar.close() pbar.close()

Loading…
Cancel
Save