From fc414b57b7784448653de522de3de1f3cbe5eff3 Mon Sep 17 00:00:00 2001 From: Jason Date: Wed, 6 Jul 2022 23:57:11 -0400 Subject: [PATCH] style: reformatted --- TTS/TikTok.py | 12 +++++------- TTS/aws_polly.py | 4 +--- TTS/engine_wrapper.py | 12 +++--------- TTS/streamlabs_polly.py | 4 +--- main.py | 10 ++++++---- reddit/subreddit.py | 16 ++++------------ utils/cleanup.py | 4 +--- utils/console.py | 17 +++-------------- utils/subreddit.py | 4 +--- utils/videos.py | 4 +--- video_creation/background.py | 20 ++++++++++---------- video_creation/screenshot_downloader.py | 12 +++--------- video_creation/voices.py | 14 +++----------- 13 files changed, 42 insertions(+), 91 deletions(-) diff --git a/TTS/TikTok.py b/TTS/TikTok.py index 6a116d7..743118c 100644 --- a/TTS/TikTok.py +++ b/TTS/TikTok.py @@ -62,7 +62,9 @@ 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} @@ -79,9 +81,7 @@ class TikTok: # TikTok Text-to-Speech Wrapper ) ) try: - r = requests.post( - f"{self.URI_BASE}{voice}&req_text={text}&speaker_map_type=0" - ) + r = requests.post(f"{self.URI_BASE}{voice}&req_text={text}&speaker_map_type=0") except requests.exceptions.SSLError: # https://stackoverflow.com/a/47475019/18516611 session = requests.Session() @@ -89,9 +89,7 @@ class TikTok: # TikTok Text-to-Speech Wrapper adapter = HTTPAdapter(max_retries=retry) session.mount("http://", adapter) session.mount("https://", adapter) - r = session.post( - f"{self.URI_BASE}{voice}&req_text={text}&speaker_map_type=0" - ) + r = session.post(f"{self.URI_BASE}{voice}&req_text={text}&speaker_map_type=0") # print(r.text) vstr = [r.json()["data"]["v_str"]][0] b64d = base64.b64decode(vstr) diff --git a/TTS/aws_polly.py b/TTS/aws_polly.py index 0ff0d74..13eaea1 100644 --- a/TTS/aws_polly.py +++ b/TTS/aws_polly.py @@ -39,9 +39,7 @@ class AWSPolly: return 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() + voice = str(settings.config["settings"]["tts"]["aws_polly_voice"]).capitalize() try: # Request speech synthesis response = polly.synthesize_speech( diff --git a/TTS/engine_wrapper.py b/TTS/engine_wrapper.py index e3cc04b..a171db7 100644 --- a/TTS/engine_wrapper.py +++ b/TTS/engine_wrapper.py @@ -63,9 +63,7 @@ class TTSEngine: self.call_tts("posttext", self.reddit_object["thread_post"]) idx = None - for idx, comment in track( - enumerate(self.reddit_object["comments"]), "Saving..." - ): + for idx, comment in track(enumerate(self.reddit_object["comments"]), "Saving..."): # ! Stop creating mp3 files if the length is greater than max length. if self.length > self.max_length: break @@ -81,9 +79,7 @@ class TTSEngine: split_files = [] split_text = [ x.group().strip() - for x in re.finditer( - rf" *((.{{0,{self.tts_module.max_chars}}})(\.|.$))", text - ) + for x in re.finditer(rf" *((.{{0,{self.tts_module.max_chars}}})(\.|.$))", text) ] idy = None @@ -106,9 +102,7 @@ class TTSEngine: # Path(f"{self.path}/{idx}-{i}.part.mp3").unlink() def call_tts(self, filename: str, text: str): - self.tts_module.run( - text=process_text(text), filepath=f"{self.path}/{filename}.mp3" - ) + self.tts_module.run(text=process_text(text), filepath=f"{self.path}/{filename}.mp3") # try: # self.length += MP3(f"{self.path}/{filename}.mp3").info.length # except (MutagenError, HeaderNotFoundError): diff --git a/TTS/streamlabs_polly.py b/TTS/streamlabs_polly.py index d4ddcb4..1f8a039 100644 --- a/TTS/streamlabs_polly.py +++ b/TTS/streamlabs_polly.py @@ -39,9 +39,7 @@ class StreamlabsPolly: return ValueError( f"Please set the config variable STREAMLABS_VOICE to a valid voice. options are: {voices}" ) - voice = str( - settings.config["settings"]["tts"]["streamlabs_polly_voice"] - ).capitalize() + voice = str(settings.config["settings"]["tts"]["streamlabs_polly_voice"]).capitalize() body = {"voice": voice, "text": text, "service": "polly"} response = requests.post(self.url, data=body) try: diff --git a/main.py b/main.py index cefb74d..8ce8725 100755 --- a/main.py +++ b/main.py @@ -8,7 +8,11 @@ from utils.console import print_markdown, print_step from utils import settings # from utils.checker import envUpdate -from video_creation.background import download_background, chop_background_video, get_background_config +from video_creation.background import ( + download_background, + chop_background_video, + get_background_config, +) from video_creation.final_video import make_final_video from video_creation.screenshot_downloader import download_screenshots_of_reddit_posts from video_creation.voices import save_text_to_mp3 @@ -60,9 +64,7 @@ if __name__ == "__main__": run_many(config["settings"]["times_to_run"]) elif len(config["reddit"]["thread"]["post_id"].split("+")) > 1: - for index, post_id in enumerate( - config["reddit"]["thread"]["post_id"].split("+") - ): + for index, post_id in enumerate(config["reddit"]["thread"]["post_id"].split("+")): index += 1 print_step( f'on the {index}{("st" if index%10 == 1 else ("nd" if index%10 == 2 else ("rd" if index%10 == 3 else "th")))} post of {len(config["reddit"]["thread"]["post_id"].split("+"))}' diff --git a/reddit/subreddit.py b/reddit/subreddit.py index 7583653..8365d04 100644 --- a/reddit/subreddit.py +++ b/reddit/subreddit.py @@ -18,9 +18,7 @@ def get_subreddit_threads(POST_ID: str): content = {} if settings.config["reddit"]["creds"]["2fa"] == True: - print( - "\nEnter your two-factor authentication code from your authenticator app.\n" - ) + print("\nEnter your two-factor authentication code from your authenticator app.\n") code = input("> ") print() pw = settings.config["reddit"]["creds"]["password"] @@ -46,9 +44,7 @@ def get_subreddit_threads(POST_ID: str): ]: # note to user. you can have multiple subreddits via reddit.subreddit("redditdev+learnpython") try: subreddit = reddit.subreddit( - re.sub( - r"r\/", "", input("What subreddit would you like to pull from? ") - ) + re.sub(r"r\/", "", input("What subreddit would you like to pull from? ")) # removes the r/ from the input ) except ValueError: @@ -58,9 +54,7 @@ def get_subreddit_threads(POST_ID: str): sub = settings.config["reddit"]["thread"]["subreddit"] print_substep(f"Using subreddit: r/{sub} from TOML config") subreddit_choice = sub - if subreddit_choice.casefold().startswith( - "r/" - ): # removes the r/ from the input + if subreddit_choice.casefold().startswith("r/"): # removes the r/ from the input subreddit_choice = subreddit_choice[2:] subreddit = reddit.subreddit( subreddit_choice @@ -72,9 +66,7 @@ def get_subreddit_threads(POST_ID: str): settings.config["reddit"]["thread"]["post_id"] and len(settings.config["reddit"]["thread"]["post_id"].split("+")) == 1 ): - submission = reddit.submission( - id=settings.config["reddit"]["thread"]["post_id"] - ) + submission = reddit.submission(id=settings.config["reddit"]["thread"]["post_id"]) else: threads = subreddit.hot(limit=25) diff --git a/utils/cleanup.py b/utils/cleanup.py index 44629a9..ef4fc44 100644 --- a/utils/cleanup.py +++ b/utils/cleanup.py @@ -10,9 +10,7 @@ def cleanup() -> int: """ if exists("./assets/temp"): count = 0 - files = [ - f for f in os.listdir(".") if f.endswith(".mp4") and "temp" in f.lower() - ] + 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) diff --git a/utils/console.py b/utils/console.py index 1ffa11c..6f99a41 100644 --- a/utils/console.py +++ b/utils/console.py @@ -49,10 +49,7 @@ def handle_input( optional=False, ): if optional: - console.print( - message - + "\n[green]This is an optional value. Do you want to skip it? (y/n)" - ) + console.print(message + "\n[green]This is an optional value. Do you want to skip it? (y/n)") if input().casefold().startswith("y"): return default if default is not NotImplemented else "" if default is not NotImplemented: @@ -86,11 +83,7 @@ def handle_input( console.print("[red]" + err_message) continue elif match != "" and re.match(match, user_input) is None: - console.print( - "[red]" - + err_message - + "\nAre you absolutely sure it's correct?(y/n)" - ) + console.print("[red]" + err_message + "\nAre you absolutely sure it's correct?(y/n)") if input().casefold().startswith("y"): break continue @@ -123,9 +116,5 @@ def handle_input( if user_input in options: return user_input console.print( - "[red bold]" - + err_message - + "\nValid options are: " - + ", ".join(map(str, options)) - + "." + "[red bold]" + err_message + "\nValid options are: " + ", ".join(map(str, options)) + "." ) diff --git a/utils/subreddit.py b/utils/subreddit.py index 7647454..140f4d3 100644 --- a/utils/subreddit.py +++ b/utils/subreddit.py @@ -15,9 +15,7 @@ def get_subreddit_undone(submissions: list, subreddit): """ # recursively checks if the top submission in the list was already done. - with open( - "./video_creation/data/videos.json", "r", encoding="utf-8" - ) as done_vids_raw: + with open("./video_creation/data/videos.json", "r", encoding="utf-8") as done_vids_raw: done_videos = json.load(done_vids_raw) for submission in submissions: if already_done(done_videos, submission): diff --git a/utils/videos.py b/utils/videos.py index 51143c3..d050ab8 100755 --- a/utils/videos.py +++ b/utils/videos.py @@ -20,9 +20,7 @@ def check_done( Returns: Submission|None: Reddit object in args """ - with open( - "./video_creation/data/videos.json", "r", encoding="utf-8" - ) as done_vids_raw: + with open("./video_creation/data/videos.json", "r", encoding="utf-8") as done_vids_raw: done_videos = json.load(done_vids_raw) for video in done_videos: if video["id"] == str(redditobj): diff --git a/video_creation/background.py b/video_creation/background.py index d9dc056..7ef4321 100644 --- a/video_creation/background.py +++ b/video_creation/background.py @@ -24,28 +24,29 @@ background_options = { "https://www.youtube.com/watch?v=vw5L4xCPy9Q", "bike-parkour-gta.mp4", "Achy Gaming", - lambda t: ('center', 480 + t) + lambda t: ("center", 480 + t), ), "rocket-league": ( # Rocket League "https://www.youtube.com/watch?v=2X9QGY__0II", "rocket_league.mp4", "Orbital Gameplay", - "top" + "top", ), "minecraft": ( # Minecraft parkour "https://www.youtube.com/watch?v=n_Dv4JMiwK8", "parkour.mp4", "bbswitzer", - "center" + "center", ), "gta": ( # GTA Stunt Race "https://www.youtube.com/watch?v=qGa9kWREOnE", "gta-stunt-race.mp4", "Achy Gaming", - lambda t: ('center', 480 + t) - ) + lambda t: ("center", 480 + t), + ), } + def get_start_and_end_times(video_length: int, length_of_clip: int) -> Tuple[int, int]: """Generates a random interval of time to be used as the background of the video. @@ -59,10 +60,11 @@ def get_start_and_end_times(video_length: int, length_of_clip: int) -> Tuple[int random_time = randrange(180, int(length_of_clip) - int(video_length)) return random_time, random_time + video_length + def get_background_config(): """Fetch the background/s configuration""" try: - choice = str(settings.config['settings']['background_choice']).casefold() + choice = str(settings.config["settings"]["background_choice"]).casefold() except AttributeError: print_substep("No background selected. Picking random background'") choice = None @@ -90,8 +92,7 @@ def download_background(background_config: Tuple[str, str, str, Any]): YouTube(uri, on_progress_callback=on_progress).streams.filter(res="1080p").first().download( "assets/backgrounds", filename=f"{credit}-{filename}" ) - print_substep("Background videos downloaded successfully! 🎉", - style="bold green") + print_substep("Background videos downloaded successfully! 🎉", style="bold green") def chop_background_video(background_config: Tuple[str, str, str, Any], video_length: int): @@ -107,8 +108,7 @@ def chop_background_video(background_config: Tuple[str, str, str, Any], video_le background = VideoFileClip(f"assets/backgrounds/{choice}") - start_time, end_time = get_start_and_end_times( - video_length, background.duration) + start_time, end_time = get_start_and_end_times(video_length, background.duration) try: ffmpeg_extract_subclip( f"assets/backgrounds/{choice}", diff --git a/video_creation/screenshot_downloader.py b/video_creation/screenshot_downloader.py index 9dbb3d8..6fb9ef4 100644 --- a/video_creation/screenshot_downloader.py +++ b/video_creation/screenshot_downloader.py @@ -35,13 +35,9 @@ def download_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: in context = browser.new_context() if settings.config["settings"]["theme"] == "dark": - cookie_file = open( - "./video_creation/data/cookie-dark-mode.json", encoding="utf-8" - ) + cookie_file = open("./video_creation/data/cookie-dark-mode.json", encoding="utf-8") else: - cookie_file = open( - "./video_creation/data/cookie-light-mode.json", encoding="utf-8" - ) + cookie_file = open("./video_creation/data/cookie-light-mode.json", encoding="utf-8") cookies = json.load(cookie_file) context.add_cookies(cookies) # load preference cookies # Get the thread screenshot @@ -73,9 +69,7 @@ def download_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: in else: print_substep("Skipping translation...") - page.locator('[data-test-id="post-content"]').screenshot( - path="assets/temp/png/title.png" - ) + page.locator('[data-test-id="post-content"]').screenshot(path="assets/temp/png/title.png") if storymode: page.locator('[data-click-id="text"]').screenshot( diff --git a/video_creation/voices.py b/video_creation/voices.py index e6e1045..ffc0898 100644 --- a/video_creation/voices.py +++ b/video_creation/voices.py @@ -35,9 +35,7 @@ def save_text_to_mp3(reddit_obj) -> Tuple[int, int]: voice = settings.config["settings"]["tts"]["choice"] if voice.casefold() in map(lambda _: _.casefold(), TTSProviders): - text_to_mp3 = TTSEngine( - get_case_insensitive_key_value(TTSProviders, voice), reddit_obj - ) + text_to_mp3 = TTSEngine(get_case_insensitive_key_value(TTSProviders, voice), reddit_obj) else: while True: print_step("Please choose one of the following TTS providers: ") @@ -46,19 +44,13 @@ def save_text_to_mp3(reddit_obj) -> Tuple[int, int]: if choice.casefold() in map(lambda _: _.casefold(), TTSProviders): break print("Unknown Choice") - text_to_mp3 = TTSEngine( - get_case_insensitive_key_value(TTSProviders, choice), reddit_obj - ) + text_to_mp3 = TTSEngine(get_case_insensitive_key_value(TTSProviders, choice), reddit_obj) return text_to_mp3.run() def get_case_insensitive_key_value(input_dict, key): return next( - ( - value - for dict_key, value in input_dict.items() - if dict_key.lower() == key.lower() - ), + (value for dict_key, value in input_dict.items() if dict_key.lower() == key.lower()), None, )