source_scripts_data_aya / utils_sel.py
Gabrui's picture
Varied Exams
896aea1
"""Utilities Function for dealing with Selenium and generating PDF output"""
from io import BytesIO
from PyPDF2 import PdfMerger
from PIL import Image, ImageDraw, ImageFont
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
def get_driver(production=True, width=1080, height=3840):
"""Initializes the driver with a tall headless window in production"""
chrome_options = Options()
if production:
chrome_options.add_argument("--headless")
chrome_options.add_argument(f"--window-size={width},{height}")
return webdriver.Chrome(options=chrome_options)
def find_links_names(driver, partial_text):
"""Return all urls and full names of links that partially have the text"""
links = driver.find_elements(By.PARTIAL_LINK_TEXT, partial_text)
urls = [elem.get_attribute('href') for elem in links]
names = [elem.text for elem in links]
return urls, names
def click_button(driver, button_name):
"""Click the first button with the name attribute"""
button = driver.find_element(By.NAME, button_name)
button.click()
def click_link(driver, partial_text):
"""Click the first link that partially have the text"""
link = driver.find_element(By.PARTIAL_LINK_TEXT, partial_text)
link.click()
def get_html(driver, element):
"""Get an string of the innerHTML"""
script = """
var div = arguments[0];
return div.innerHTML;
"""
return driver.execute_script(script, element)
def get_html_with_images(driver, element):
"""Get an string of the innerHTML of the elements with embedded images"""
script = """
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
return canvas.toDataURL("image/png");
}
var div = arguments[0];
var images = div.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
var img = images[i];
var src = img.src;
if (src.startsWith('http')) {
img.src = getBase64Image(img);
}
}
return div.innerHTML;
"""
return driver.execute_script(script, element)
def bytes_to_image(img_bytes: bytes) -> Image:
"""Reads the bytes and returns a PIL.Image"""
return Image.open(BytesIO(img_bytes))
def image_to_bytes(img, f_type='JPEG', quality=95):
"""Convert a PIL Image to its bytes representation"""
bytesio = BytesIO()
img.save(bytesio, format=f_type, quality=quality)
bytesio.seek(0)
return bytesio.getvalue()
def take_full_div_screenshot(driver, div):
"""Takes the screenshot of the whole div, uses zoom,
resolution may be bad if too big"""
div_h = driver.execute_script("return arguments[0].offsetHeight;", div)
div_w = driver.execute_script("return arguments[0].offsetWidth;", div)
window_height = driver.execute_script("return window.innerHeight;")
window_width = driver.execute_script("return window.innerWidth;")
zoom_level = min(window_height / div_h, window_width / div_w, 1)
driver.execute_script(f"document.body.style.zoom = '{zoom_level}'")
driver.execute_script("arguments[0].scrollIntoView();", div)
im = bytes_to_image(driver.get_screenshot_as_png())
div_x = int(driver.execute_script("return arguments[0].getBoundingClientRect().left;", div))
div_y = int(driver.execute_script("return arguments[0].getBoundingClientRect().top;", div))
im = im.crop((div_x, div_y, div_x + int(div_w * zoom_level), div_y + int(div_h * zoom_level)))
if zoom_level != 1:
im = im.resize((div_w, div_h), Image.LANCZOS)
driver.execute_script("document.body.style.zoom = '1'")
return im
def hide_between_start_end(driver, parent, start: str, end: str, visible=False):
"""Hides all children of the parent that are between start (inclusive) to end (text representation)"""
children = parent.get_property('children')
start_index = None
end_index = None
for i, child in enumerate(children):
if child.text.strip() == start:
start_index = i
elif child.text.strip() == end:
end_index = i
break
assert start_index is not None
assert end_index is not None
for i in range(end_index - 1, start_index-1, -1):
driver.execute_script(f"arguments[0].style.display = '{'' if visible else 'none'}';\
arguments[0].style.visibility = '{'' if visible else 'hidden'}';", children[i])
def copy_element_as_first_child(driver, source_locator, destination_locator):
"""Copies the source_locator to be the first child of the destination_locator"""
script = """
var source = arguments[0];
var destination = arguments[1];
var clone = source.cloneNode(true);
destination.insertBefore(clone, destination.firstChild);
"""
driver.execute_script(script, source_locator, destination_locator)
def create_pdf_from_images(images_bytes, output_pdf_path, dpi=100, quality=90):
"""Create a PDF file with one image per page from the images_bytes list"""
pdf_merger = PdfMerger()
for img_bytes in images_bytes:
img = bytes_to_image(img_bytes)
pdf_buffer = BytesIO()
img.save(pdf_buffer, format='PDF', resolution=dpi, quality=quality)
pdf_buffer.seek(0)
pdf_merger.append(pdf_buffer)
pdf_merger.write(output_pdf_path)
def create_image_from_text(text, size=(800, 200), as_bytes=True):
"""Renders a text"""
image = Image.new('RGB', size, color='white')
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("DejaVuSans.ttf", 28)
text_bbox = draw.textbbox((0, 0), text, font=font)
text_width = text_bbox[2] - text_bbox[0]
text_height = text_bbox[3] - text_bbox[1]
position = ((size[0]-text_width)/2, (size[1]-text_height)/2)
draw.text(position, text, fill="black", font=font)
draw.rectangle([0, 0, size[0]-1, size[1]-1], outline="black")
if as_bytes:
return image_to_bytes(image)
return image