parent
b1663f3381
commit
27577d0da6
@ -0,0 +1,67 @@
|
||||
from attr import attrs, attrib
|
||||
from typing import TypeVar, Optional, Callable, Union
|
||||
|
||||
|
||||
_function = TypeVar("_function", bound=Callable[..., object])
|
||||
_exceptions = TypeVar("_exceptions", bound=Optional[Union[type, tuple, list]])
|
||||
|
||||
|
||||
@attrs
|
||||
class ExceptionDecorator:
|
||||
"""
|
||||
Decorator factory for catching exceptions and writing logs
|
||||
"""
|
||||
exception: Optional[_exceptions] = attrib(default=None)
|
||||
_default_exception: Optional[_exceptions] = attrib(
|
||||
kw_only=True,
|
||||
default=None
|
||||
)
|
||||
|
||||
def __attrs_post_init__(self):
|
||||
if not self.exception:
|
||||
self.exception = self._default_exception
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
func: _function,
|
||||
):
|
||||
async def wrapper(*args, **kwargs):
|
||||
try:
|
||||
obj_to_return = await func(*args, **kwargs)
|
||||
return obj_to_return
|
||||
except Exception as caughtException:
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger("webdriver_log")
|
||||
logger.setLevel(logging.ERROR)
|
||||
handler = logging.FileHandler(".webdriver.log", mode="a+", encoding="utf-8")
|
||||
logger.addHandler(handler)
|
||||
|
||||
if isinstance(self.exception, type):
|
||||
if not type(caughtException) == self.exception:
|
||||
logger.error(f"unexpected error - {caughtException}")
|
||||
else:
|
||||
if not type(caughtException) in self.exception:
|
||||
logger.error(f"unexpected error - {caughtException}")
|
||||
|
||||
return wrapper
|
||||
|
||||
@classmethod
|
||||
def catch_exception(
|
||||
cls,
|
||||
func: Optional[_function],
|
||||
exception: Optional[_exceptions] = None,
|
||||
) -> Union[object, _function]:
|
||||
"""
|
||||
Decorator for catching exceptions and writing logs
|
||||
|
||||
Args:
|
||||
func: Function to be decorated
|
||||
exception: Expected exception(s)
|
||||
Returns:
|
||||
Decorated function
|
||||
"""
|
||||
exceptor = cls(exception)
|
||||
if func:
|
||||
exceptor = exceptor(func)
|
||||
return exceptor
|
@ -0,0 +1,202 @@
|
||||
from playwright.async_api import async_playwright, ViewportSize
|
||||
from playwright.async_api import Browser, Playwright
|
||||
from rich.progress import track
|
||||
|
||||
from pathlib import Path
|
||||
import translators as ts
|
||||
from utils import settings
|
||||
from utils.console import print_step, print_substep
|
||||
from attr import attrs, attrib
|
||||
from attr.validators import instance_of, optional
|
||||
|
||||
from typing import Dict, Optional, Union
|
||||
|
||||
|
||||
@attrs
|
||||
class Browser:
|
||||
"""
|
||||
Args:
|
||||
default_Viewport (dict):Pyppeteer Browser default_Viewport options
|
||||
browser (BrowserCls): Pyppeteer Browser instance
|
||||
"""
|
||||
default_Viewport: dict = attrib(
|
||||
validator=instance_of(dict),
|
||||
default={
|
||||
# 9x21 to see long posts
|
||||
"defaultViewport": {
|
||||
"width": 500,
|
||||
"height": 1200,
|
||||
},
|
||||
},
|
||||
kw_only=True,
|
||||
)
|
||||
playwright: Playwright
|
||||
browser: Browser
|
||||
|
||||
async def get_browser(
|
||||
self,
|
||||
) -> None:
|
||||
"""
|
||||
Creates Playwright instance & browser
|
||||
"""
|
||||
self.playwright = await async_playwright().start()
|
||||
self.browser = await self.playwright.chromium.launch()
|
||||
|
||||
async def close_browser(
|
||||
self,
|
||||
) -> None:
|
||||
"""
|
||||
Closes Pyppeteer browser
|
||||
"""
|
||||
await self.browser.close()
|
||||
await self.playwright.stop()
|
||||
|
||||
|
||||
@attrs(auto_attribs=True)
|
||||
class RedditScreenshot(Browser):
|
||||
"""
|
||||
Args:
|
||||
reddit_object (Dict): Reddit object received from reddit/subreddit.py
|
||||
screenshot_idx (int): List with indexes of voiced comments
|
||||
"""
|
||||
reddit_object: dict
|
||||
screenshot_idx: list
|
||||
|
||||
async def __dark_theme(
|
||||
self,
|
||||
page_instance: PageCls,
|
||||
) -> None:
|
||||
"""
|
||||
Enables dark theme in Reddit
|
||||
|
||||
Args:
|
||||
page_instance: Pyppeteer page instance with reddit page opened
|
||||
"""
|
||||
|
||||
await self.click(
|
||||
page_instance,
|
||||
"//*[contains(@class, 'header-user-dropdown')]",
|
||||
{"timeout": 5000},
|
||||
)
|
||||
|
||||
# It's normal not to find it, sometimes there is none :shrug:
|
||||
await self.click(
|
||||
page_instance,
|
||||
"//*[contains(text(), 'Settings')]/ancestor::button[1]",
|
||||
{"timeout": 5000},
|
||||
)
|
||||
|
||||
await self.click(
|
||||
page_instance,
|
||||
"//*[contains(text(), 'Dark Mode')]/ancestor::button[1]",
|
||||
{"timeout": 5000},
|
||||
)
|
||||
|
||||
# Closes settings
|
||||
await self.click(
|
||||
page_instance,
|
||||
"//*[contains(@class, 'header-user-dropdown')]",
|
||||
{"timeout": 5000},
|
||||
)
|
||||
|
||||
|
||||
|
||||
storymode = False
|
||||
|
||||
|
||||
def download_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
|
||||
|
||||
Args:
|
||||
reddit_object (Dict): Reddit object received from reddit/subreddit.py
|
||||
screenshot_num (int): Number of screenshots to download
|
||||
"""
|
||||
print_step("Downloading screenshots of reddit posts...")
|
||||
|
||||
# ! Make sure the reddit screenshots folder exists
|
||||
Path("assets/temp/png").mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with sync_playwright() as p:
|
||||
print_substep("Launching Headless Browser...")
|
||||
|
||||
browser = p.chromium.launch()
|
||||
context = browser.new_context()
|
||||
|
||||
if settings.config["settings"]["theme"] == "dark":
|
||||
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")
|
||||
cookies = json.load(cookie_file)
|
||||
context.add_cookies(cookies) # load preference cookies
|
||||
# Get the thread screenshot
|
||||
page = context.new_page()
|
||||
page.goto(reddit_object["thread_url"], timeout=0)
|
||||
page.set_viewport_size(ViewportSize(width=1920, height=1080))
|
||||
if page.locator('[data-testid="content-gate"]').is_visible():
|
||||
# This means the post is NSFW and requires to click the proceed button.
|
||||
|
||||
print_substep("Post is NSFW. You are spicy...")
|
||||
page.locator('[data-testid="content-gate"] button').click()
|
||||
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
|
||||
|
||||
# translate code
|
||||
|
||||
if settings.config["reddit"]["thread"]["post_lang"]:
|
||||
print_substep("Translating post...")
|
||||
texts_in_tl = ts.google(
|
||||
reddit_object["thread_title"],
|
||||
to_language=settings.config["reddit"]["thread"]["post_lang"],
|
||||
)
|
||||
|
||||
page.evaluate(
|
||||
"tl_content => document.querySelector('[data-test-id=\"post-content\"] > div:nth-child(3) > div > div').textContent = tl_content",
|
||||
texts_in_tl,
|
||||
)
|
||||
else:
|
||||
print_substep("Skipping translation...")
|
||||
|
||||
page.locator('[data-test-id="post-content"]').screenshot(path="assets/temp/png/title.png")
|
||||
|
||||
if storymode:
|
||||
page.locator('[data-click-id="text"]').screenshot(
|
||||
path="assets/temp/png/story_content.png"
|
||||
)
|
||||
else:
|
||||
for idx, comment in enumerate(
|
||||
track(reddit_object["comments"], "Downloading screenshots...")
|
||||
):
|
||||
# Stop if we have reached the screenshot_num
|
||||
if idx >= screenshot_num:
|
||||
break
|
||||
|
||||
if page.locator('[data-testid="content-gate"]').is_visible():
|
||||
page.locator('[data-testid="content-gate"] button').click()
|
||||
|
||||
page.goto(f'https://reddit.com{comment["comment_url"]}', timeout=0)
|
||||
|
||||
# translate code
|
||||
|
||||
if settings.config["reddit"]["thread"]["post_lang"]:
|
||||
comment_tl = ts.google(
|
||||
comment["comment_body"],
|
||||
to_language=settings.config["reddit"]["thread"]["post_lang"],
|
||||
)
|
||||
page.evaluate(
|
||||
'([tl_content, tl_id]) => document.querySelector(`#t1_${tl_id} > div:nth-child(2) > div > div[data-testid="comment"] > div`).textContent = tl_content',
|
||||
[comment_tl, comment["comment_id"]],
|
||||
)
|
||||
try:
|
||||
page.locator(f"#t1_{comment['comment_id']}").screenshot(
|
||||
path=f"assets/temp/png/comment_{idx}.png"
|
||||
)
|
||||
except TimeoutError:
|
||||
del reddit_object["comments"]
|
||||
screenshot_num += 1
|
||||
print("TimeoutError: Skipping screenshot...")
|
||||
continue
|
||||
print_substep("Screenshots downloaded Successfully.", style="bold green")
|
@ -0,0 +1,22 @@
|
||||
from typing import Union
|
||||
|
||||
from webdriver.pyppeteer import RedditScreenshot as Pyppeteer
|
||||
|
||||
|
||||
def screenshot_factory(
|
||||
driver: str,
|
||||
) -> Union[Pyppeteer]:
|
||||
"""
|
||||
Factory for webdriver
|
||||
Args:
|
||||
driver: (str) Name of a driver
|
||||
|
||||
Returns:
|
||||
Webdriver instance
|
||||
"""
|
||||
web_drivers = {
|
||||
"pyppeteer": Pyppeteer,
|
||||
"playwright": None,
|
||||
}
|
||||
|
||||
return web_drivers[driver]
|
Loading…
Reference in new issue