Path: blob/master/video_creation/screenshot_downloader.py
494 views
import json1import re2from pathlib import Path3from typing import Dict, Final45import translators6from playwright.sync_api import ViewportSize, sync_playwright7from rich.progress import track89from utils import settings10from utils.console import print_step, print_substep11from utils.imagenarator import imagemaker12from utils.playwright import clear_cookie_by_name13from utils.videos import save_data1415__all__ = ["get_screenshots_of_reddit_posts"]161718def get_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: int):19"""Downloads screenshots of reddit posts as seen on the web. Downloads to assets/temp/png2021Args:22reddit_object (Dict): Reddit object received from reddit/subreddit.py23screenshot_num (int): Number of screenshots to download24"""25# settings values26W: Final[int] = int(settings.config["settings"]["resolution_w"])27H: Final[int] = int(settings.config["settings"]["resolution_h"])28lang: Final[str] = settings.config["reddit"]["thread"]["post_lang"]29storymode: Final[bool] = settings.config["settings"]["storymode"]3031print_step("Downloading screenshots of reddit posts...")32reddit_id = re.sub(r"[^\w\s-]", "", reddit_object["thread_id"])33# ! Make sure the reddit screenshots folder exists34Path(f"assets/temp/{reddit_id}/png").mkdir(parents=True, exist_ok=True)3536# set the theme and turn off non-essential cookies37if settings.config["settings"]["theme"] == "dark":38cookie_file = open("./video_creation/data/cookie-dark-mode.json", encoding="utf-8")39bgcolor = (33, 33, 36, 255)40txtcolor = (240, 240, 240)41transparent = False42elif settings.config["settings"]["theme"] == "transparent":43if storymode:44# Transparent theme45bgcolor = (0, 0, 0, 0)46txtcolor = (255, 255, 255)47transparent = True48cookie_file = open("./video_creation/data/cookie-dark-mode.json", encoding="utf-8")49else:50# Switch to dark theme51cookie_file = open("./video_creation/data/cookie-dark-mode.json", encoding="utf-8")52bgcolor = (33, 33, 36, 255)53txtcolor = (240, 240, 240)54transparent = False55else:56cookie_file = open("./video_creation/data/cookie-light-mode.json", encoding="utf-8")57bgcolor = (255, 255, 255, 255)58txtcolor = (0, 0, 0)59transparent = False6061if storymode and settings.config["settings"]["storymodemethod"] == 1:62print_substep("Generating images...")63return imagemaker(64theme=bgcolor,65reddit_obj=reddit_object,66txtclr=txtcolor,67transparent=transparent,68)6970screenshot_num: int71with sync_playwright() as p:72print_substep("Launching Headless Browser...")7374browser = p.chromium.launch(75headless=True76) # headless=False will show the browser for debugging purposes77# Device scale factor (or dsf for short) allows us to increase the resolution of the screenshots78# When the dsf is 1, the width of the screenshot is 600 pixels79# so we need a dsf such that the width of the screenshot is greater than the final resolution of the video80dsf = (W // 600) + 18182context = browser.new_context(83locale=lang or "en-CA,en;q=0.9",84color_scheme="dark",85viewport=ViewportSize(width=W, height=H),86device_scale_factor=dsf,87user_agent=f"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{browser.version}.0.0.0 Safari/537.36",88extra_http_headers={89"Dnt": "1",90"Sec-Ch-Ua": '"Not A(Brand";v="8", "Chromium";v="132", "Google Chrome";v="132"',91},92)93cookies = json.load(cookie_file)94cookie_file.close()9596context.add_cookies(cookies) # load preference cookies9798# Login to Reddit99print_substep("Logging in to Reddit...")100page = context.new_page()101page.goto("https://www.reddit.com/login", timeout=0)102page.set_viewport_size(ViewportSize(width=1920, height=1080))103page.wait_for_load_state()104105page.locator(f'input[name="username"]').fill(settings.config["reddit"]["creds"]["username"])106page.locator(f'input[name="password"]').fill(settings.config["reddit"]["creds"]["password"])107page.get_by_role("button", name="Log In").click()108page.wait_for_timeout(5000)109110login_error_div = page.locator(".AnimatedForm__errorMessage").first111if login_error_div.is_visible():112113print_substep(114"Your reddit credentials are incorrect! Please modify them accordingly in the config.toml file.",115style="red",116)117exit()118else:119pass120121page.wait_for_load_state()122# Handle the redesign123# Check if the redesign optout cookie is set124if page.locator("#redesign-beta-optin-btn").is_visible():125# Clear the redesign optout cookie126clear_cookie_by_name(context, "redesign_optout")127# Reload the page for the redesign to take effect128page.reload()129# Get the thread screenshot130page.goto(reddit_object["thread_url"], timeout=0)131page.set_viewport_size(ViewportSize(width=W, height=H))132page.wait_for_load_state()133page.wait_for_timeout(5000)134135if page.locator(136"#t3_12hmbug > div > div._3xX726aBn29LDbsDtzr_6E._1Ap4F5maDtT1E1YuCiaO0r.D3IL3FD0RFy_mkKLPwL4 > div > div > button"137).is_visible():138# This means the post is NSFW and requires to click the proceed button.139140print_substep("Post is NSFW. You are spicy...")141page.locator(142"#t3_12hmbug > div > div._3xX726aBn29LDbsDtzr_6E._1Ap4F5maDtT1E1YuCiaO0r.D3IL3FD0RFy_mkKLPwL4 > div > div > button"143).click()144page.wait_for_load_state() # Wait for page to fully load145146# translate code147if page.locator(148"#SHORTCUT_FOCUSABLE_DIV > div:nth-child(7) > div > div > div > header > div > div._1m0iFpls1wkPZJVo38-LSh > button > i"149).is_visible():150page.locator(151"#SHORTCUT_FOCUSABLE_DIV > div:nth-child(7) > div > div > div > header > div > div._1m0iFpls1wkPZJVo38-LSh > button > i"152).click() # Interest popup is showing, this code will close it153154if lang:155print_substep("Translating post...")156texts_in_tl = translators.translate_text(157reddit_object["thread_title"],158to_language=lang,159translator="google",160)161162page.evaluate(163"tl_content => document.querySelector('[data-adclicklocation=\"title\"] > div > div > h1').textContent = tl_content",164texts_in_tl,165)166else:167print_substep("Skipping translation...")168169postcontentpath = f"assets/temp/{reddit_id}/png/title.png"170try:171if settings.config["settings"]["zoom"] != 1:172# store zoom settings173zoom = settings.config["settings"]["zoom"]174# zoom the body of the page175page.evaluate("document.body.style.zoom=" + str(zoom))176# as zooming the body doesn't change the properties of the divs, we need to adjust for the zoom177location = page.locator('[data-test-id="post-content"]').bounding_box()178for i in location:179location[i] = float("{:.2f}".format(location[i] * zoom))180page.screenshot(clip=location, path=postcontentpath)181else:182page.locator('[data-test-id="post-content"]').screenshot(path=postcontentpath)183except Exception as e:184print_substep("Something went wrong!", style="red")185resp = input(186"Something went wrong with making the screenshots! Do you want to skip the post? (y/n) "187)188189if resp.casefold().startswith("y"):190save_data("", "", "skipped", reddit_id, "")191print_substep(192"The post is successfully skipped! You can now restart the program and this post will skipped.",193"green",194)195196resp = input("Do you want the error traceback for debugging purposes? (y/n)")197if not resp.casefold().startswith("y"):198exit()199200raise e201202if storymode:203page.locator('[data-click-id="text"]').first.screenshot(204path=f"assets/temp/{reddit_id}/png/story_content.png"205)206else:207for idx, comment in enumerate(208track(209reddit_object["comments"][:screenshot_num],210"Downloading screenshots...",211)212):213# Stop if we have reached the screenshot_num214if idx >= screenshot_num:215break216217if page.locator('[data-testid="content-gate"]').is_visible():218page.locator('[data-testid="content-gate"] button').click()219220page.goto(f"https://new.reddit.com/{comment['comment_url']}")221222# translate code223224if settings.config["reddit"]["thread"]["post_lang"]:225comment_tl = translators.translate_text(226comment["comment_body"],227translator="google",228to_language=settings.config["reddit"]["thread"]["post_lang"],229)230page.evaluate(231'([tl_content, tl_id]) => document.querySelector(`#t1_${tl_id} > div:nth-child(2) > div > div[data-testid="comment"] > div`).textContent = tl_content',232[comment_tl, comment["comment_id"]],233)234try:235if settings.config["settings"]["zoom"] != 1:236# store zoom settings237zoom = settings.config["settings"]["zoom"]238# zoom the body of the page239page.evaluate("document.body.style.zoom=" + str(zoom))240# scroll comment into view241page.locator(f"#t1_{comment['comment_id']}").scroll_into_view_if_needed()242# as zooming the body doesn't change the properties of the divs, we need to adjust for the zoom243location = page.locator(f"#t1_{comment['comment_id']}").bounding_box()244for i in location:245location[i] = float("{:.2f}".format(location[i] * zoom))246page.screenshot(247clip=location,248path=f"assets/temp/{reddit_id}/png/comment_{idx}.png",249)250else:251page.locator(f"#t1_{comment['comment_id']}").screenshot(252path=f"assets/temp/{reddit_id}/png/comment_{idx}.png"253)254except TimeoutError:255del reddit_object["comments"]256screenshot_num += 1257print("TimeoutError: Skipping screenshot...")258continue259260# close browser instance when we are done using it261browser.close()262263print_substep("Screenshots downloaded Successfully.", style="bold green")264265266