File size: 2,505 Bytes
e723446
e212778
 
 
 
 
 
 
 
 
aa6b547
 
 
 
 
e212778
 
 
 
 
aa6b547
e212778
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
    }