import keras from keras.models import load_model from aiohttp import ClientSession from numpy import expand_dims as np_expand_dims from captcha_processor import CaptchaProcessor from asyncio import get_running_loop from asyncio import sleep as asyncsleep from random import randint model = load_model("model.h5") proxies = [ "http://207.180.218.96:80", "http://82.66.27.145:8118", "http://139.162.102.215:38118", ] async def get_binary_from_link(link: str) -> bytes: async with ClientSession() as session: for _ in range(20): try: a = await session.get(link, proxy=proxies[randint(0, len(proxies)-1)]) print(int(a.status)) if int(a.status) == 200: return await a.read() else: await asyncsleep(0.125) except Exception as e: print(e) return randint(100000, 999999) async def predict(url: str, recursion: int = 0) -> dict: binary = await get_binary_from_link(url) if type(binary) == type(0): return { "prediction": binary, "letters_predictions": None, "full_prediction": binary, "recursion": recursion } try: processor = CaptchaProcessor(binary) processor.replace_color(processor.get_background_color(), processor.WHITE_RGB) processor.replace_colors(processor.get_letters_color(), processor.WHITE_RGB) processor.convert_color_space(6) processor.threshold() except: print("error with image, trying again") return await predict(url, recursion + 1) try: processor.increase_letters_size(2) except IndexError: return await predict(url, recursion + 1) letters = processor.slice_letters() if len(letters) != 6: return await predict(url, recursion + 1) shorts = [] final = "" letters_solving = [ get_running_loop().run_in_executor(None, model.predict, np_expand_dims(letter, axis=0)) for letter in letters ] letters_solving = [await result for result in letters_solving] fulls = [list(map(lambda x: float(x), letter[0])) for letter in letters_solving] for prediction in fulls: shorts.append(prediction.index(max(*prediction))) for short in shorts: final += str(short) return { "prediction": final, "letters_predictions": shorts, "full_prediction": fulls, "recursion": recursion }