From 08f2a646be4434208e43ecf4eb394bcc2089ff91 Mon Sep 17 00:00:00 2001 From: John Toniutti Date: Sat, 1 Oct 2022 17:40:11 +0200 Subject: [PATCH] Reformat using black --- video_creation/background.py | 18 ++++++++---- video_creation/final_video.py | 32 +++++++++++++++----- video_creation/screenshot_downloader.py | 39 +++++++++++++++++-------- video_creation/voices.py | 14 +++++++-- 4 files changed, 74 insertions(+), 29 deletions(-) diff --git a/video_creation/background.py b/video_creation/background.py index c451025..0405e66 100644 --- a/video_creation/background.py +++ b/video_creation/background.py @@ -45,7 +45,9 @@ def get_start_and_end_times(video_length: int, length_of_clip: int) -> Tuple[int def get_background_config(): """Fetch the background/s configuration""" try: - choice = str(settings.config["settings"]["background"]["background_choice"]).casefold() + choice = str( + settings.config["settings"]["background"]["background_choice"] + ).casefold() except AttributeError: print_substep("No background selected. Picking random background'") choice = None @@ -65,16 +67,20 @@ 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( - "assets/backgrounds", filename=f"{credit}-{filename}" - ) + YouTube(uri, on_progress_callback=on_progress).streams.filter( + res="1080p" + ).first().download("assets/backgrounds", filename=f"{credit}-{filename}") print_substep("Background video downloaded successfully! 🎉", style="bold green") -def chop_background_video(background_config: Tuple[str, str, str, Any], video_length: int, reddit_object: dict): +def chop_background_video( + background_config: Tuple[str, str, str, Any], video_length: int, reddit_object: dict +): """Generates the background footage to be used in the video and writes it to assets/temp/background.mp4 Args: diff --git a/video_creation/final_video.py b/video_creation/final_video.py index 3db4e6d..28c9ff6 100755 --- a/video_creation/final_video.py +++ b/video_creation/final_video.py @@ -45,7 +45,11 @@ def name_normalize(name: str) -> str: def prepare_background(id: str, W: int, H: int) -> VideoFileClip: - clip = VideoFileClip(f"assets/temp/{id}/background.mp4").without_audio().resize(height=H) + clip = ( + VideoFileClip(f"assets/temp/{id}/background.mp4") + .without_audio() + .resize(height=H) + ) # calculate the center of the background clip c = clip.w // 2 @@ -83,7 +87,7 @@ def make_final_video( id = re.sub(r"[^\w\s-]", "", reddit_obj["thread_id"]) print_step("Creating the final video 🎥") - + VideoFileClip.reW = lambda clip: clip.resize(width=W) VideoFileClip.reH = lambda clip: clip.resize(width=H) @@ -93,7 +97,9 @@ def make_final_video( background_clip = prepare_background(id, W=W, H=H) # Gather all audio clips - audio_clips = [AudioFileClip(f"assets/temp/{id}/mp3/{i}.mp3") for i in range(number_of_clips)] + audio_clips = [ + AudioFileClip(f"assets/temp/{id}/mp3/{i}.mp3") for i in range(number_of_clips) + ] audio_clips.insert(0, AudioFileClip(f"assets/temp/{id}/mp3/title.mp3")) audio_concat = concatenate_audioclips(audio_clips) audio_composite = CompositeAudioClip([audio_concat]) @@ -103,8 +109,10 @@ def make_final_video( image_clips = [] # Gather all images new_opacity = 1 if opacity is None or float(opacity) >= 1 else float(opacity) - new_transition = 0 if transition is None or float(transition) > 2 else float(transition) - screenshow_width = int((W*90)//100) + new_transition = ( + 0 if transition is None or float(transition) > 2 else float(transition) + ) + screenshow_width = int((W * 90) // 100) image_clips.insert( 0, ImageClip(f"assets/temp/{id}/png/title.png") @@ -137,7 +145,9 @@ 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"]) @@ -158,7 +168,11 @@ def make_final_video( # # 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, @@ -179,4 +193,6 @@ 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 01da49a..ea655a0 100644 --- a/video_creation/screenshot_downloader.py +++ b/video_creation/screenshot_downloader.py @@ -24,7 +24,7 @@ def download_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: in # settings values W: Final[int] = int(settings.config["settings"]["resolution_w"]) H: Final[int] = int(settings.config["settings"]["resolution_h"]) - lang: Final[str] = settings.config["reddit"]["thread"]["post_lang"] + lang: Final[str] = settings.config["reddit"]["thread"]["post_lang"] storymode: Final[bool] = settings.config["settings"]["storymode"] print_step("Downloading screenshots of reddit posts...") @@ -35,25 +35,29 @@ 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 # 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 # so we need a dsf such that the width of the screenshot is greater than the final resolution of the video - dsf = (W // 600)+1 + dsf = (W // 600) + 1 context = browser.new_context( locale=lang or "en-us", color_scheme="dark", viewport=ViewportSize(width=W, height=H), - device_scale_factor=dsf - ) + device_scale_factor=dsf, + ) # set the theme and disable non-essential cookies 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 @@ -70,7 +74,9 @@ 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 @@ -92,9 +98,16 @@ def download_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: in 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"][:screenshot_num], "Downloading screenshots...")): + for idx, comment in enumerate( + track( + reddit_object["comments"][:screenshot_num], + "Downloading screenshots...", + ) + ): # Stop if we have reached the screenshot_num if idx >= screenshot_num: break @@ -116,7 +129,9 @@ 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 @@ -125,5 +140,5 @@ def download_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: in # close browser instance when we are done using it browser.close() - + print_substep("Screenshots downloaded Successfully.", style="bold green") diff --git a/video_creation/voices.py b/video_creation/voices.py index 511b7ff..68d5085 100644 --- a/video_creation/voices.py +++ b/video_creation/voices.py @@ -36,7 +36,9 @@ def save_text_to_mp3(reddit_obj) -> Tuple[int, int]: voice = settings.config["settings"]["tts"]["voice_choice"] if str(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: ") @@ -45,12 +47,18 @@ 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, )