File size: 5,782 Bytes
f4d52c1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 |
import time
import urllib.request
import os
import re
from random import randint
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from commands.driver_instance import create_url_headers, tab_handler
from commands.exec_path import imgList
from commands.universal import searchQuery, save_Search, continue_Search, contains_works
from ai.classifying_ai import img_classifier
def getOrderedYandexImages(
driver, exec_path, user_search, num_pics, filters, imageOrientation):
global image_locations, image_names, ai_mode
image_names = imgList(mode=2)
ai_mode = True
recents = True if 1 in filters else False
image_locations = []
link = "https://yandex.com/images/search?isize=large&"
link = link + "text=" + user_search.replace(" ", "+").replace("_", "+")
if imageOrientation:
orientations = ["horizontal", "vertical", "square"]
link += f"&iorient={orientations[imageOrientation]}"
driver.get(link)
WebDriverWait(driver, timeout=11).until(
EC.presence_of_element_located((By.XPATH, '//*[@class="SerpList"]'))
)
driver.find_element(
By.XPATH,
"//*[@class='SimpleImage SimpleImage_showPlaceholderIcon SerpItem-Thumb']//a",
).click()
grid_search(driver, num_pics, exec_path, user_search)
time.sleep(20)
driver.close()
return image_locations
def grid_search(driver, num_pics, exec_path, user_search):
WebDriverWait(driver, timeout=11).until(
EC.presence_of_element_located(
(By.XPATH, "//*[contains(@class, 'MMGallery-Item')]")
)
)
images = driver.find_elements(By.XPATH, "//*[@class='MMGallery-Container']/*")
for image in images:
time.sleep(2)
# Navigate the webpage and filter the image link
try:
if len(image_locations) >= num_pics:
break
driver.execute_script("arguments[0].click();", image)
time.sleep(0.5)
imageLink = driver.find_element(
By.XPATH,
'//*[@class="OpenImageButton OpenImageButton_text OpenImageButton_sizes MMViewerButtons-OpenImageSizes"]//a',
).get_attribute("href")
if (imageLink.rsplit("/",1)[-1].encode("ascii", "ignore")
.decode("ascii")) in image_names:
print("Image already exists, moving to another image...\n")
continue
except:
print("I ran into an error finding the image, closing the tab and moving on...\n")
time.sleep(randint(0, 1) + randint(0, 9) / 10)
continue
# Ai mode check
try:
if ai_mode:
checker = ai_dl(image, exec_path, driver, user_search)
if checker:
continue
except Exception as e: # TODO: Implement proper exception handling in case of http error 404
time.sleep(randint(0, 1) + randint(0, 9) / 10)
checker = ai_dl(image, exec_path, driver, user_search, site="https://yandex.com/")
except:
time.sleep(randint(0, 1) + randint(0, 9) / 10)
print("AI mode failed to check the image, skipping...\n")
continue
# Download the image
try:
download_image(
exec_path=exec_path,
driver=driver,
image=imageLink,
user_search=user_search,
)
except: # TODO: Use the same exception handling as above to try and redownload the image
print("I ran into an error downloading, closing the tab and moving on...\n")
time.sleep(randint(0, 1) + randint(0, 9) / 10)
def download_image(exec_path, driver, image, user_search, mode=1, site=0):
tempDLAttr = image
matching = re.search(r"([^/]+\.(?:jpg|jpeg|png|webp))", image.rsplit("/", 1)[-1])
if not matching:
tempDLAttr += ".png"
if tempDLAttr.startswith('//'):
tempDLAttr = 'https:' + tempDLAttr
tempDLName = (
re.search(r"([^/]+\.(?:jpg|jpeg|png|webp))", tempDLAttr.rsplit("/", 1)[-1])
.group(1)
.encode("ascii", "ignore")
.decode("ascii"))
if not mode:
tempDLName = re.sub(r'[\\/*?:"<>|]', "", tempDLName)
img_loc = f"./{exec_path.folder_path}/{tempDLName}"
# User other site headers (to be implemented properly)
if site:
urllib.request.install_opener(create_url_headers(tempDLAttr, site=site))
urllib.request.urlretrieve(tempDLAttr, img_loc)
urllib.request.install_opener(create_url_headers(tempDLAttr))
urllib.request.urlretrieve(tempDLAttr, img_loc)
if mode:
print(f"{tempDLAttr}\n")
image_locations.append(img_loc)
image_names.append(f"{tempDLName.split('.')[0]}")
return img_loc
def ai_dl(image, exec_path, driver, user_search, site=""):
checker = 0
image_thumbnail = image.find_element(
By.XPATH, './/*[@class="MMThumbImage-Image"]'
).get_attribute("style")
# Filter url from the style attribute
image_thumbnail = re.findall(r'url\("(.+?)"\)', image_thumbnail)[0]
# Download the image thumbnail
image_loc = download_image(
exec_path=exec_path,
driver=driver,
image=image_thumbnail,
user_search=user_search,
mode=0,
site=site
)
# Check if the image is good or not and delete the image
if img_classifier(image_loc):
print("AI Mode: I approve this image")
else:
print("AI Mode: Skipping this image\n")
checker = 1
os.remove(image_loc)
return checker
|