diff --git a/TTS/TikTok.py b/TTS/TikTok.py index b370455..2bcbd6d 100644 --- a/TTS/TikTok.py +++ b/TTS/TikTok.py @@ -79,6 +79,8 @@ vocals: Final[tuple] = ( class TikTok: """TikTok Text-to-Speech Wrapper""" def __init__(self): + if not settings.config['settings']['tts']['tiktok_sessionid']: + raise TikTokTTSException(5) headers = { "User-Agent": "com.zhiliaoapp.musically/2022600030 (Linux; U; Android 7.1.2; es_ES; SM-G988N; " "Build/NRD90M;tt-ok/3.12.13.1)", @@ -140,7 +142,7 @@ class TikTok: return response.json() @staticmethod - def random_voice(): + def random_voice() -> str: return random.choice(eng_voices) @@ -158,5 +160,8 @@ class TikTokTTSException(Exception): if self._code == 4: return f"Code: {self._code}, reason: the speaker doesn't exist, message: {self._message}" + + if self._code == 5: + return f"You have to add session id in config to use titok TTS" return f"Code: {self._message}, reason: unknown, message: {self._message}" diff --git a/TTS/engine_wrapper.py b/TTS/engine_wrapper.py index 6ca63d5..d25b622 100644 --- a/TTS/engine_wrapper.py +++ b/TTS/engine_wrapper.py @@ -51,11 +51,18 @@ class TTSEngine: self.length = 0 self.last_clip_length = last_clip_length + def add_periods(self): # adds periods to the end of paragraphs (where people often forget to put them) so tts doesn't blend sentences + for comment in self.reddit_object["comments"]: + comment["comment_body"] = comment["comment_body"].replace('\n', '. ') + if comment["comment_body"][-1] != '.': + comment["comment_body"] += '.' + def run(self) -> Tuple[int, int]: Path(self.path).mkdir(parents=True, exist_ok=True) print_step("Saving Text to MP3 files...") - + + self.add_periods() self.call_tts("title", process_text(self.reddit_object["thread_title"])) # processed_text = ##self.reddit_object["thread_post"] != "" idx = None diff --git a/main.py b/main.py index dcb1861..4f2e442 100755 --- a/main.py +++ b/main.py @@ -23,7 +23,7 @@ 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.0" +__VERSION__ = "3.0.1" print( """ @@ -42,7 +42,7 @@ print_markdown( checkversion(__VERSION__) -def main(POST_ID=None): +def main(POST_ID=None) -> None: global redditid ,reddit_object reddit_object = get_subreddit_threads(POST_ID) redditid = id(reddit_object) @@ -55,7 +55,7 @@ def main(POST_ID=None): make_final_video(number_of_comments, length, reddit_object, bg_config) -def run_many(times): +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}' @@ -108,11 +108,8 @@ if __name__ == "__main__": shutdown() except Exception as err: - 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 - Version: {__VERSION__} \n - Story mode: {str(config["settings"]["storymode"])} \n - Story mode method: {str(config["settings"]["storymodemethod"])} - ''') + 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__},Story mode: {str(config["settings"]["storymode"])}, Story mode method: {str(config["settings"]["storymodemethod"])},\n' + f'Postid : {str(config["settings"])},allownsfw :{config["settings"]["allow_nsfw"]},is_nsfw : {str(reddit_object["is_nsfw"])}' + ) raise err - # todo error diff --git a/reddit/subreddit.py b/reddit/subreddit.py index 8fb9e9d..ed1e8cf 100644 --- a/reddit/subreddit.py +++ b/reddit/subreddit.py @@ -134,6 +134,7 @@ def get_subreddit_threads(POST_ID: str): content["thread_url"] = threadurl content["thread_title"] = submission.title content["thread_id"] = submission.id + content["is_nsfw"] = submission.over_18 content["comments"] = [] if settings.config["settings"]["storymode"]: if settings.config["settings"]["storymodemethod"] == 1: diff --git a/requirements.txt b/requirements.txt index a9564c0..6cf4689 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,7 +7,7 @@ praw==7.6.1 prawcore~=2.3.0 pytube==12.1.0 requests==2.28.1 -rich==12.5.1 +rich==13.3.1 toml==0.10.2 translators==5.3.1 pyttsx3==2.90 diff --git a/utils/backgrounds.json b/utils/backgrounds.json index 8cb01d1..6e00992 100644 --- a/utils/backgrounds.json +++ b/utils/backgrounds.json @@ -4,13 +4,13 @@ "https://www.youtube.com/watch?v=vw5L4xCPy9Q", "bike-parkour-gta.mp4", "Achy Gaming", - 480 + "center" ], "rocket-league": [ "https://www.youtube.com/watch?v=2X9QGY__0II", "rocket_league.mp4", "Orbital Gameplay", - 200 + "center" ], "minecraft": [ "https://www.youtube.com/watch?v=n_Dv4JMiwK8", @@ -22,7 +22,7 @@ "https://www.youtube.com/watch?v=qGa9kWREOnE", "gta-stunt-race.mp4", "Achy Gaming", - 480 + "center" ], "csgo-surf": [ "https://www.youtube.com/watch?v=E-8JlyO59Io", @@ -34,7 +34,7 @@ "https://www.youtube.com/watch?v=uVKxtdMgJVU", "cluster_truck.mp4", "No Copyright Gameplay", - 480 + "center" ], "minecraft-2": [ "https://www.youtube.com/watch?v=Pt5_GSKIWQM", diff --git a/utils/console.py b/utils/console.py index 3419f05..7ac8a70 100644 --- a/utils/console.py +++ b/utils/console.py @@ -10,28 +10,28 @@ from rich.text import Text console = Console() -def print_markdown(text): +def print_markdown(text) -> None: """Prints a rich info message. Support Markdown syntax.""" md = Padding(Markdown(text), 2) console.print(md) -def print_step(text): +def print_step(text) -> None: """Prints a rich info message.""" panel = Panel(Text(text, justify="left")) console.print(panel) -def print_table(items): +def print_table(items) -> None: """Prints items in a table.""" console.print(Columns([Panel(f"[yellow]{item}", expand=True) for item in items])) -def print_substep(text, style=""): - """Prints a rich info message without the panelling.""" +def print_substep(text, style="") -> None: + """Prints a rich colored info message without the panelling.""" console.print(text, style=style) diff --git a/utils/imagenarator.py b/utils/imagenarator.py index 8c6dc58..8e3789e 100644 --- a/utils/imagenarator.py +++ b/utils/imagenarator.py @@ -6,7 +6,7 @@ from PIL import Image, ImageDraw, ImageFont from rich.progress import track from TTS.engine_wrapper import process_text -def draw_multiple_line_text(image, text, font, text_color, padding, wrap=50): +def draw_multiple_line_text(image, text, font, text_color, padding, wrap=50) -> None: """ Draw multiline text over given image """ @@ -24,7 +24,7 @@ def draw_multiple_line_text(image, text, font, text_color, padding, wrap=50): # theme=bgcolor,reddit_obj=reddit_object,txtclr=txtcolor -def imagemaker(theme, reddit_obj: dict, txtclr, padding=5): +def imagemaker(theme, reddit_obj: dict, txtclr, padding=5) -> None: """ Render Images for video """ diff --git a/utils/voice.py b/utils/voice.py index a88c87d..76efc20 100644 --- a/utils/voice.py +++ b/utils/voice.py @@ -13,7 +13,7 @@ if sys.version_info[0] >= 3: from datetime import timezone -def check_ratelimit(response: Response): +def check_ratelimit(response: Response) -> bool: """ Checks if the response is a ratelimit response. If it is, it sleeps for the time specified in the response. @@ -30,7 +30,7 @@ def check_ratelimit(response: Response): return True -def sleep_until(time): +def sleep_until(time) -> None: """ Pause your program until a specific end time. 'time' is either a valid datetime object or unix timestamp in seconds (i.e. seconds since Unix epoch) diff --git a/video_creation/screenshot_downloader.py b/video_creation/screenshot_downloader.py index 3a76b5b..c98fb56 100644 --- a/video_creation/screenshot_downloader.py +++ b/video_creation/screenshot_downloader.py @@ -12,9 +12,11 @@ from utils import settings from utils.console import print_step, print_substep from utils.imagenarator import imagemaker +from utils.videos import save_data __all__ = ["download_screenshots_of_reddit_posts"] + def get_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: int): """Downloads screenshots of reddit posts as seen on the web. Downloads to assets/temp/png @@ -37,7 +39,7 @@ def get_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: int): with sync_playwright() as p: print_substep("Launching Headless Browser...") - browser = p.chromium.launch() # headless=False #to check for chrome view + browser = p.chromium.launch(headless=True) # headless=False will show the browser for debugging purposes context = browser.new_context() # Device scale factor (or dsf for short) allows us to increase the resolution of the screenshots # When the dsf is 1, the width of the screenshot is 600 pixels @@ -71,6 +73,20 @@ def get_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: int): context.add_cookies(cookies) # load preference cookies + # Login to Reddit + print_substep("Logging in to Reddit...") + page = context.new_page() + page.goto("https://www.reddit.com/login", timeout=0) + page.set_viewport_size(ViewportSize(width=1920, height=1080)) + page.wait_for_load_state() + + page.locator('[name="username"]').fill(settings.config["reddit"]["creds"]["username"]) + page.locator('[name="password"]').fill(settings.config["reddit"]["creds"]["password"]) + page.locator("button:has-text('Log In')").click() + + page.wait_for_load_state() # Wait for page to fully load and add 5 seconds + page.wait_for_timeout(5000) + # Get the thread screenshot page = context.new_page() page.goto(reddit_object["thread_url"], timeout=0) @@ -105,7 +121,21 @@ def get_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: int): print_substep("Skipping translation...") postcontentpath = f"assets/temp/{reddit_id}/png/title.png" - page.locator('[data-test-id="post-content"]').screenshot(path=postcontentpath) + try: + page.locator('[data-test-id="post-content"]').screenshot(path=postcontentpath) + except Exception as e: + print_substep("Something went wrong!",style="red") + resp = input("Something went wrong with making the screenshots! Do you want to skip the post? (y/n) ") + + if resp.casefold().startswith("y"): + save_data("", "", "skipped", reddit_id, "") + print_substep("The post is successfully skipped! You can now restart the program and this post will skipped.","green") + + resp = input("Do you want the error traceback for debugging purposes? (y/n)") + if not resp.casefold().startswith("y"): + exit() + + raise e if storymode: page.locator('[data-click-id="text"]').first.screenshot( @@ -151,6 +181,4 @@ def get_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: int): # close browser instance when we are done using it browser.close() - - - print_substep("Screenshots downloaded Successfully.", style="bold green") \ No newline at end of file + print_substep("Screenshots downloaded Successfully.", style="bold green")