feat: themes

refactor:acess browser 

less duration of brower usage
pull/1288/head
Syed Aman Raza 2 years ago committed by GitHub
parent c6f7295948
commit d48d24422e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,7 +1,6 @@
from PIL import Image, ImageDraw,ImageFont from PIL import Image, ImageDraw,ImageFont
import textwrap import textwrap
import re import re
def draw_multiple_line_text(image, text, font, text_color,padding): def draw_multiple_line_text(image, text, font, text_color,padding):
''' '''
Draw multiline text over given image Draw multiline text over given image
@ -10,7 +9,7 @@ def draw_multiple_line_text(image, text, font, text_color,padding):
Fontperm= font.getsize(text) Fontperm= font.getsize(text)
image_width, image_height = image.size image_width, image_height = image.size
lines = textwrap.wrap(text, width=50) lines = textwrap.wrap(text, width=50)
y=(image_height/2)-(((Fontperm[1]+(len(lines)*padding)/len(lines))*len(lines))/2) #dont touch it y=(image_height/2)-(((Fontperm[1]+(len(lines)*padding)/len(lines))*len(lines))/2)
for line in lines: for line in lines:
line_width, line_height = font.getsize(line) line_width, line_height = font.getsize(line)
draw.text(((image_width - line_width) / 2, y), draw.text(((image_width - line_width) / 2, y),
@ -18,24 +17,24 @@ def draw_multiple_line_text(image, text, font, text_color,padding):
y += line_height + padding y += line_height + padding
def imagemaker(text, def imagemaker( theme,reddit_obj,
reddit_obj, txtclr,
idx='NoName',
padding=5 padding=5
): ):
texts=reddit_obj['thread_post']
id = re.sub(r"[^\w\s-]", "", reddit_obj["thread_id"]) id = re.sub(r"[^\w\s-]", "", reddit_obj["thread_id"])
font=ImageFont.truetype("arial.ttf", 20) font=ImageFont.truetype("arial.ttf", 20)
Fontperm= font.getsize(text)
# print(Fontperm[1])
size=(500,176) size=(500,176)
textcolor=txtclr
textcolor=(240,240,240)
image =Image.new('RGBA',size,(33,33,36,255)) for idx,text in enumerate(texts):
image =Image.new('RGBA',size,theme)
draw = ImageDraw.Draw(image) draw = ImageDraw.Draw(image)
if len(text)>50: if len(text)>50:
draw_multiple_line_text(image, text,font, textcolor,padding) draw_multiple_line_text(image, text,font, textcolor,padding)
else: else:
draw.text(((image.size[0]-Fontperm[0])/2,(image.size[1]-Fontperm[1])/2),font=font,text=text,align='center') #(image.size[1]/2)-(Fontperm[1]/2) image =Image.new('RGBA',size,theme)
image.save(f'assets/temp/{id}/png/img{idx}.png') draw = ImageDraw.Draw(image)
Fontperm= font.getsize(text)
draw.text((((image.size[0]-Fontperm[0])/2),((image.size[1]-Fontperm[1])/2)),font=font,text=text,align='center')
image.save(f'assets/temp/{id}/png/img{idx}.png')

@ -1,16 +1,21 @@
import json import json
import re
from pathlib import Path from pathlib import Path
import re
from typing import Dict from typing import Dict
from utils import settings
from playwright.async_api import async_playwright # pylint: disable=unused-import
# do not remove the above line
import translators as ts
from playwright.sync_api import sync_playwright, ViewportSize from playwright.sync_api import sync_playwright, ViewportSize
from rich.progress import track from rich.progress import track
import translators as ts import translators as ts
from utils import settings
from utils.imagenarator import imagemaker from utils.imagenarator import imagemaker
from utils.console import print_step, print_substep from utils.console import print_step, print_substep
def download_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: int): 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 """Downloads screenshots of reddit posts as seen on the web. Downloads to assets/temp/png
@ -22,94 +27,108 @@ def download_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: in
id = re.sub(r"[^\w\s-]", "", reddit_object["thread_id"]) id = re.sub(r"[^\w\s-]", "", reddit_object["thread_id"])
# ! Make sure the reddit screenshots folder exists # ! Make sure the reddit screenshots folder exists
Path(f"assets/temp/{id}/png").mkdir(parents=True, exist_ok=True) Path(f"assets/temp/{id}/png").mkdir(parents=True, exist_ok=True)
def download(cookie_file):
with sync_playwright() as p: with sync_playwright() as p:
print_substep("Launching Headless Browser...") print_substep("Launching Headless Browser...")
browser = p.chromium.launch() # add headless=False for debug browser = p.chromium.launch(headless=False) # #to check for chrome view
context = browser.new_context()
context = browser.new_context()
if settings.config["settings"]["theme"] == "dark": cookies = json.load(cookie_file)
cookie_file = open("./video_creation/data/cookie-dark-mode.json", encoding="utf-8")
else: context.add_cookies(cookies) # load preference cookies
cookie_file = open("./video_creation/data/cookie-light-mode.json", encoding="utf-8") # Get the thread screenshot
cookies = json.load(cookie_file) page = context.new_page()
context.add_cookies(cookies) # load preference cookies page.goto(reddit_object["thread_url"], timeout=0)
# Get the thread screenshot page.set_viewport_size(ViewportSize(width=1920, height=1080))
page = context.new_page() if page.locator('[data-testid="content-gate"]').is_visible():
page.goto(reddit_object["thread_url"], timeout=0) # This means the post is NSFW and requires to click the proceed button.
page.set_viewport_size(ViewportSize(width=1920, height=1080))
if page.locator('[data-testid="content-gate"]').is_visible(): print_substep("Post is NSFW. You are spicy...")
# This means the post is NSFW and requires to click the proceed button. page.locator('[data-testid="content-gate"] button').click()
page.wait_for_load_state() # Wait for page to fully load
print_substep("Post is NSFW. You are spicy...")
page.locator('[data-testid="content-gate"] button').click() if page.locator('[data-click-id="text"] button').is_visible():
page.wait_for_load_state() # Wait for page to fully load page.locator(
'[data-click-id="text"] button'
if page.locator('[data-click-id="text"] button').is_visible(): ).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
# translate code
if settings.config["reddit"]["thread"]["post_lang"]:
if settings.config["reddit"]["thread"]["post_lang"]: print_substep("Translating post...")
print_substep("Translating post...") texts_in_tl = ts.google(
texts_in_tl = ts.google( reddit_object["thread_title"],
reddit_object["thread_title"], to_language=settings.config["reddit"]["thread"]["post_lang"],
to_language=settings.config["reddit"]["thread"]["post_lang"], )
)
page.evaluate(
page.evaluate( "tl_content => document.querySelector('[data-test-id=\"post-content\"] > div:nth-child(3) > div > div').textContent = tl_content",
"tl_content => document.querySelector('[data-test-id=\"post-content\"] > div:nth-child(3) > div > div').textContent = tl_content", texts_in_tl,
texts_in_tl, )
) else:
else: print_substep("Skipping translation...")
print_substep("Skipping translation...") postcontentpath = f"assets/temp/{id}/png/title.png"
page.locator('[data-test-id="post-content"]').screenshot(path=postcontentpath)
postcontentpath = f"assets/temp/{id}/png/title.png"
page.locator('[data-test-id="post-content"]').screenshot(path=postcontentpath) if not settings.config["settings"]["storymodemethode"]and settings.config["settings"]["storymode"]:
if settings.config["settings"]["storymode"] :
if settings.config["settings"]["storymodemethod"] == 0:
try : #new change try : #new change
page.locator('[data-click-id="text"]').first.screenshot( page.locator('[data-click-id="text"]').first.screenshot(
path=f"assets/temp/{id}/png/story_content.png" path=f"assets/temp/{id}/png/story_content.png"
) )
except: except:
exit exit
elif settings.config["settings"]["storymodemethod"] == 1: if not settings.config["settings"]["storymode"] :
for idx,item in enumerate(reddit_object["thread_post"]): for idx, comment in enumerate(
imagemaker(item,idx=idx,reddit_obj=reddit_object) track(reddit_object["comments"], "Downloading screenshots...")
):
# Stop if we have reached the screenshot_num
if idx >= screenshot_num:
else: break
for idx, comment in enumerate(track(reddit_object["comments"], "Downloading screenshots...")):
# Stop if we have reached the screenshot_num if page.locator('[data-testid="content-gate"]').is_visible():
if idx >= screenshot_num: page.locator('[data-testid="content-gate"] button').click()
break
page.goto(f'https://reddit.com{comment["comment_url"]}', timeout=0)
if page.locator('[data-testid="content-gate"]').is_visible():
page.locator('[data-testid="content-gate"] button').click() # translate code
page.goto(f'https://reddit.com{comment["comment_url"]}', timeout=0) if settings.config["reddit"]["thread"]["post_lang"]:
comment_tl = ts.google(
# translate code comment["comment_body"],
to_language=settings.config["reddit"]["thread"]["post_lang"],
if settings.config["reddit"]["thread"]["post_lang"]: )
comment_tl = ts.google( page.evaluate(
comment["comment_body"], '([tl_content, tl_id]) => document.querySelector(`#t1_${tl_id} > div:nth-child(2) > div > div[data-testid="comment"] > div`).textContent = tl_content',
to_language=settings.config["reddit"]["thread"]["post_lang"], [comment_tl, comment["comment_id"]],
) )
page.evaluate( try:
'([tl_content, tl_id]) => document.querySelector(`#t1_${tl_id} > div:nth-child(2) > div > div[data-testid="comment"] > div`).textContent = tl_content', page.locator(f"#t1_{comment['comment_id']}").screenshot(
[comment_tl, comment["comment_id"]], path=f"assets/temp/{id}/png/comment_{idx}.png"
) )
try: except TimeoutError:
page.locator(f"#t1_{comment['comment_id']}").screenshot(path=f"assets/temp/{id}/png/comment_{idx}.png") del reddit_object["comments"]
except TimeoutError: screenshot_num += 1
del reddit_object["comments"] print("TimeoutError: Skipping screenshot...")
screenshot_num += 1 continue
print("TimeoutError: Skipping screenshot...")
continue
print_substep("Screenshots downloaded Successfully.", style="bold green") print_substep("Screenshots downloaded Successfully.", style="bold green")
theme=settings.config["settings"]["theme"]
if theme == "dark":
cookie_file = open("./video_creation/data/cookie-dark-mode.json", encoding="utf-8")
bgcolor=(33,33,36,255)
txtcolor=(240,240,240)
else:
cookie_file = open("./video_creation/data/cookie-light-mode.json", encoding="utf-8")
bgcolor=(255,255,255,255)
txtcolor=(0,0,0)
if settings.config["settings"]["storymode"] :
# if settings.config["settings"]["storymodemethode"] == 0:
# story=True
if settings.config["settings"]["storymodemethode"] :
# for idx,item in enumerate(reddit_object["thread_post"]):
imagemaker(theme=bgcolor,reddit_obj=reddit_object,txtclr=txtcolor)
download(cookie_file)
Loading…
Cancel
Save