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.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:

@ -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(

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

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

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

@ -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]

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

Loading…
Cancel
Save