diff --git a/TTS/TikTok.py b/TTS/TikTok.py index 807d6c7..7f79c81 100644 --- a/TTS/TikTok.py +++ b/TTS/TikTok.py @@ -64,9 +64,7 @@ noneng = [ class TikTok: # TikTok Text-to-Speech Wrapper def __init__(self): - self.URI_BASE = ( - "https://api16-normal-useast5.us.tiktokv.com/media/api/text/speech/invoke/?text_speaker=" - ) + self.URI_BASE = "https://api16-normal-useast5.us.tiktokv.com/media/api/text/speech/invoke/?text_speaker=" self.max_chars = 300 self.voices = {"human": human, "nonhuman": nonhuman, "noneng": noneng} @@ -77,10 +75,7 @@ class TikTok: # TikTok Text-to-Speech Wrapper voice = ( self.randomvoice() if random_voice - else ( - settings.config["settings"]["tts"]["tiktok_voice"] - or random.choice(self.voices["human"]) - ) + else (settings.config["settings"]["tts"]["tiktok_voice"] or random.choice(self.voices["human"])) ) try: r = requests.post(f"{self.URI_BASE}{voice}&req_text={text}&speaker_map_type=0") diff --git a/TTS/aws_polly.py b/TTS/aws_polly.py index 525da91..fa02079 100644 --- a/TTS/aws_polly.py +++ b/TTS/aws_polly.py @@ -39,15 +39,11 @@ class AWSPolly: voice = self.randomvoice() else: if not settings.config["settings"]["tts"]["aws_polly_voice"]: - raise ValueError( - f"Please set the TOML variable AWS_VOICE to a valid voice. options are: {voices}" - ) + raise ValueError(f"Please set the TOML variable AWS_VOICE to a valid voice. options are: {voices}") voice = str(settings.config["settings"]["tts"]["aws_polly_voice"]).capitalize() try: # Request speech synthesis - response = polly.synthesize_speech( - Text=text, OutputFormat="mp3", VoiceId=voice, Engine="neural" - ) + response = polly.synthesize_speech(Text=text, OutputFormat="mp3", VoiceId=voice, Engine="neural") except (BotoCoreError, ClientError) as error: # The service returned an error, exit gracefully print(error) diff --git a/TTS/engine_wrapper.py b/TTS/engine_wrapper.py index 52d95e5..00485b3 100644 --- a/TTS/engine_wrapper.py +++ b/TTS/engine_wrapper.py @@ -71,9 +71,7 @@ class TTSEngine: self.length -= self.last_clip_length idx -= 1 break - if ( - len(comment["comment_body"]) > self.tts_module.max_chars - ): # Split the comment if it is too long + if len(comment["comment_body"]) > self.tts_module.max_chars: # Split the comment if it is too long self.split_post(comment["comment_body"], idx) # Split the comment else: # If the comment is not too long, just call the tts engine self.call_tts(f"{idx}", process_text(comment["comment_body"])) @@ -84,10 +82,7 @@ class TTSEngine: def split_post(self, text: str, idx: int): split_files = [] split_text = [ - x.group().strip() - for x in re.finditer( - r" *(((.|\n){0," + str(self.tts_module.max_chars) + "})(\.|.$))", text - ) + x.group().strip() for x in re.finditer(r" *(((.|\n){0," + str(self.tts_module.max_chars) + "})(\.|.$))", text) ] offset = 0 for idy, text_cut in enumerate(split_text): diff --git a/TTS/pyttsx.py b/TTS/pyttsx.py index bf47601..874d573 100644 --- a/TTS/pyttsx.py +++ b/TTS/pyttsx.py @@ -32,9 +32,7 @@ class pyttsx: voice_id = self.randomvoice() engine = pyttsx3.init() voices = engine.getProperty("voices") - engine.setProperty( - "voice", voices[voice_id].id - ) # changing index changes voices but ony 0 and 1 are working here + engine.setProperty("voice", voices[voice_id].id) # changing index changes voices but ony 0 and 1 are working here engine.save_to_file(text, f"{filepath}") engine.runAndWait() diff --git a/TTS/streamlabs_polly.py b/TTS/streamlabs_polly.py index dc80dc9..ce2250b 100644 --- a/TTS/streamlabs_polly.py +++ b/TTS/streamlabs_polly.py @@ -39,9 +39,7 @@ class StreamlabsPolly: voice = self.randomvoice() else: if not settings.config["settings"]["tts"]["streamlabs_polly_voice"]: - raise ValueError( - f"Please set the config variable STREAMLABS_POLLY_VOICE to a valid voice. options are: {voices}" - ) + raise ValueError(f"Please set the config variable STREAMLABS_POLLY_VOICE to a valid voice. options are: {voices}") voice = str(settings.config["settings"]["tts"]["streamlabs_polly_voice"]).capitalize() body = {"voice": voice, "text": text, "service": "polly"} response = requests.post(self.url, data=body) diff --git a/main.py b/main.py index 3cf725f..cddcdb2 100755 --- a/main.py +++ b/main.py @@ -74,6 +74,7 @@ def shutdown(): print("Exiting...") exit() + if __name__ == "__main__": assert sys.version_info >= (3, 9), "Python 3.10 or higher is required" config = settings.check_toml("utils/.config.template.toml", "config.toml") diff --git a/reddit/subreddit.py b/reddit/subreddit.py index 1798654..5114d9a 100644 --- a/reddit/subreddit.py +++ b/reddit/subreddit.py @@ -103,12 +103,9 @@ def get_subreddit_threads(POST_ID: str): sanitised = sanitize_text(top_level_comment.body) if not sanitised or sanitised == " ": continue - if len(top_level_comment.body) <= int( - settings.config["reddit"]["thread"]["max_comment_length"] - ): + if len(top_level_comment.body) <= int(settings.config["reddit"]["thread"]["max_comment_length"]): if ( - top_level_comment.author is not None - and sanitize_text(top_level_comment.body) is not None + top_level_comment.author is not None and sanitize_text(top_level_comment.body) is not None ): # if errors occur with this change to if not. content["comments"].append( { diff --git a/utils/console.py b/utils/console.py index 11d299f..ce1b8a4 100644 --- a/utils/console.py +++ b/utils/console.py @@ -55,11 +55,7 @@ def handle_input( return default if default is not NotImplemented else "" if default is not NotImplemented: console.print( - "[green]" - + message - + '\n[blue bold]The default value is "' - + str(default) - + '"\nDo you want to use it?(y/n)' + "[green]" + message + '\n[blue bold]The default value is "' + str(default) + '"\nDo you want to use it?(y/n)' ) if input().casefold().startswith("y"): return default @@ -72,9 +68,7 @@ def handle_input( if check_type is not False: try: user_input = check_type(user_input) - if (nmin is not None and user_input < nmin) or ( - nmax is not None and user_input > nmax - ): + if (nmin is not None and user_input < nmin) or (nmax is not None and user_input > nmax): # FAILSTATE Input out of bounds console.print("[red]" + oob_error) continue @@ -90,9 +84,7 @@ def handle_input( continue else: # FAILSTATE Input STRING out of bounds - if (nmin is not None and len(user_input) < nmin) or ( - nmax is not None and len(user_input) > nmax - ): + if (nmin is not None and len(user_input) < nmin) or (nmax is not None and len(user_input) > nmax): console.print("[red bold]" + oob_error) continue break # SUCCESS Input STRING in bounds @@ -106,16 +98,8 @@ def handle_input( isinstance(eval(user_input), check_type) return check_type(user_input) except: - console.print( - "[red bold]" - + err_message - + "\nValid options are: " - + ", ".join(map(str, options)) - + "." - ) + console.print("[red bold]" + err_message + "\nValid options are: " + ", ".join(map(str, options)) + ".") continue if user_input in options: return user_input - console.print( - "[red bold]" + err_message + "\nValid options are: " + ", ".join(map(str, options)) + "." - ) + console.print("[red bold]" + err_message + "\nValid options are: " + ", ".join(map(str, options)) + ".") diff --git a/utils/settings.py b/utils/settings.py index a5d2a80..9f1f78b 100755 --- a/utils/settings.py +++ b/utils/settings.py @@ -34,17 +34,12 @@ def check(value, checks, name): except: incorrect = True - if ( - not incorrect and "options" in checks and value not in checks["options"] - ): # FAILSTATE Value is not one of the options + if not incorrect and "options" in checks and value not in checks["options"]: # FAILSTATE Value is not one of the options incorrect = True if ( not incorrect and "regex" in checks - and ( - (isinstance(value, str) and re.match(checks["regex"], value) is None) - or not isinstance(value, str) - ) + and ((isinstance(value, str) and re.match(checks["regex"], value) is None) or not isinstance(value, str)) ): # FAILSTATE Value doesn't match regex, or has regex but is not a string. incorrect = True @@ -84,9 +79,7 @@ def check(value, checks, name): err_message=get_check_value("input_error", "Incorrect input"), nmin=get_check_value("nmin", None), nmax=get_check_value("nmax", None), - oob_error=get_check_value( - "oob_error", "Input out of bounds(Value too high/low/long/short)" - ), + oob_error=get_check_value("oob_error", "Input out of bounds(Value too high/low/long/short)"), options=get_check_value("options", None), optional=get_check_value("optional", False), ) diff --git a/utils/subreddit.py b/utils/subreddit.py index c386868..b0b7ae5 100644 --- a/utils/subreddit.py +++ b/utils/subreddit.py @@ -54,9 +54,7 @@ def get_subreddit_undone(submissions: list, subreddit, times_checked=0): print("all time filters have been checked you absolute madlad ") return get_subreddit_undone( - subreddit.top( - time_filter=VALID_TIME_FILTERS[index], limit=(50 if int(index) == 0 else index + 1 * 50) - ), + subreddit.top(time_filter=VALID_TIME_FILTERS[index], limit=(50 if int(index) == 0 else index + 1 * 50)), subreddit, times_checked=index, ) # all the videos in hot have already been done diff --git a/utils/version.py b/utils/version.py index d39afa7..8cad1d8 100644 --- a/utils/version.py +++ b/utils/version.py @@ -4,9 +4,7 @@ from utils.console import print_step def checkversion(__VERSION__): - response = requests.get( - "https://api.github.com/repos/elebumm/RedditVideoMakerBot/releases/latest" - ) + response = requests.get("https://api.github.com/repos/elebumm/RedditVideoMakerBot/releases/latest") latestversion = response.json()["tag_name"] if __VERSION__ == latestversion: print_step(f"You are using the newest version ({__VERSION__}) of the bot") diff --git a/utils/video.py b/utils/video.py index d1b8218..2d212df 100644 --- a/utils/video.py +++ b/utils/video.py @@ -36,9 +36,7 @@ class Video: im.save(path) return ImageClip(path) - def add_watermark( - self, text, redditid, opacity=0.5, duration: int | float = 5, position: Tuple = (0.7, 0.9), fontsize=15 - ): + def add_watermark(self, text, redditid, opacity=0.5, duration: int | float = 5, position: Tuple = (0.7, 0.9), fontsize=15): compensation = round( (position[0] / ((len(text) * (fontsize / 5) / 1.5) / 100 + position[0] * position[0])), ndigits=2, diff --git a/video_creation/background.py b/video_creation/background.py index de330c7..f0f38d5 100644 --- a/video_creation/background.py +++ b/video_creation/background.py @@ -51,9 +51,7 @@ def download_background(background_config: Tuple[str, str, str, Any]): uri, filename, credit, _ = background_config if Path(f"assets/backgrounds/{credit}-{filename}").is_file(): return - print_step( - "We need to download the backgrounds videos. they are fairly large but it's only done once. 😎" - ) + print_step("We need to download the backgrounds videos. they are fairly large but it's only done once. 😎") print_substep("Downloading the backgrounds videos... please be patient 🙏 ") print_substep(f"Downloading {filename} from {uri}") YouTube(uri, on_progress_callback=on_progress).streams.filter(res="1080p").first().download( diff --git a/video_creation/data/videos.json b/video_creation/data/videos.json index 0637a08..41a71aa 100644 --- a/video_creation/data/videos.json +++ b/video_creation/data/videos.json @@ -1 +1,10 @@ -[] \ No newline at end of file +[ + { + "subreddit": "AskReddit", + "id": "w2orm0", + "time": "1658271429", + "background_credit": "No Copyright Gameplay", + "reddit_title": "What comedian has never ever made you laugh", + "filename": "What comedian has never ever made you laugh.mp4" + } +] diff --git a/video_creation/final_video.py b/video_creation/final_video.py index 37ef31d..ad675c5 100755 --- a/video_creation/final_video.py +++ b/video_creation/final_video.py @@ -119,9 +119,7 @@ def make_final_video( # ) # else: story mode stuff img_clip_pos = background_config[3] - image_concat = concatenate_videoclips(image_clips).set_position( - img_clip_pos - ) # note transition kwarg for delay in imgs + image_concat = concatenate_videoclips(image_clips).set_position(img_clip_pos) # note transition kwarg for delay in imgs image_concat.audio = audio_composite final = CompositeVideoClip([background_clip, image_concat]) title = re.sub(r"[^\w\s-]", "", reddit_obj["thread_title"]) @@ -141,9 +139,7 @@ def make_final_video( # # lowered_audio = audio_background.multiply_volume( # todo get this to work # # VOLUME_MULTIPLIER) # lower volume by background_audio_volume, use with fx # final.set_audio(final_audio) - final = Video(final).add_watermark( - text=f"Background credit: {background_config[2]}", opacity=0.4, redditid=reddit_obj - ) + final = Video(final).add_watermark(text=f"Background credit: {background_config[2]}", opacity=0.4, redditid=reddit_obj) final.write_videofile( f"assets/temp/{id}/temp.mp4", fps=30, @@ -164,6 +160,4 @@ def make_final_video( print_substep(f"Removed {cleanups} temporary files 🗑") print_substep("See result in the results folder!") - print_step( - f'Reddit title: {reddit_obj["thread_title"]} \n Background Credit: {background_config[2]}' - ) + print_step(f'Reddit title: {reddit_obj["thread_title"]} \n Background Credit: {background_config[2]}') diff --git a/video_creation/screenshot_downloader.py b/video_creation/screenshot_downloader.py index f85bd02..ba7835f 100644 --- a/video_creation/screenshot_downloader.py +++ b/video_creation/screenshot_downloader.py @@ -30,7 +30,7 @@ def download_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: in with sync_playwright() as p: print_substep("Launching Headless Browser...") - browser = p.chromium.launch(headless=True) # add headless=False for debug + browser = p.chromium.launch(headless=True) # add headless=False for debug context = browser.new_context() if settings.config["settings"]["theme"] == "dark": @@ -51,9 +51,7 @@ def download_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: in page.wait_for_load_state() # Wait for page to fully load if page.locator('[data-click-id="text"] button').is_visible(): - page.locator( - '[data-click-id="text"] button' - ).click() # Remove "Click to see nsfw" Button in Screenshot + page.locator('[data-click-id="text"] button').click() # Remove "Click to see nsfw" Button in Screenshot # translate code @@ -72,16 +70,12 @@ def download_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: in print_substep("Skipping translation...") postcontentpath = f"assets/temp/{id}/png/title.png" - page.locator('[data-test-id="post-content"]').screenshot(path= postcontentpath) + page.locator('[data-test-id="post-content"]').screenshot(path=postcontentpath) if storymode: - page.locator('[data-click-id="text"]').screenshot( - path=f"assets/temp/{id}/png/story_content.png" - ) + page.locator('[data-click-id="text"]').screenshot(path=f"assets/temp/{id}/png/story_content.png") else: - for idx, comment in enumerate( - track(reddit_object["comments"], "Downloading screenshots...") - ): + for idx, comment in enumerate(track(reddit_object["comments"], "Downloading screenshots...")): # Stop if we have reached the screenshot_num if idx >= screenshot_num: break @@ -103,9 +97,7 @@ def download_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: in [comment_tl, comment["comment_id"]], ) try: - page.locator(f"#t1_{comment['comment_id']}").screenshot( - path=f"assets/temp/{id}/png/comment_{idx}.png" - ) + page.locator(f"#t1_{comment['comment_id']}").screenshot(path=f"assets/temp/{id}/png/comment_{idx}.png") except TimeoutError: del reddit_object["comments"] screenshot_num += 1