woolbot's picture
there once was a ship that put to sea
0f9d313
raw
history blame
3.13 kB
import random
import string
import requests
import pytesseract
from PIL import Image, ImageEnhance
def apipredict(request):
try:
if request.method == 'POST': url = request.form['url']
else: url = request.args['url']
if url.strip() in ['', None]:
raise Exception()
except: return {"status": "error", "details": { "error_code": 101, "error_details": "No link provided" }}
WALK_Y = 33
WHITE_RGB = (255, 255, 255)
def replaceColor(image: Image, forReplace: tuple, newColor: tuple):
for y in range(image.size[1]):
for x in range(image.size[0]):
if pix[x, y] == forReplace:
image.putpixel((x, y), newColor)
name = ''.join([random.choice(string.ascii_lowercase) for _ in range(random.randint(6,12))])
response = requests.get(url)
with open(f'{name}.png', 'wb') as fp:
fp.write(response.content)
image = Image.open(f'{name}.png')
pix = image.load()
garbageColor = image.getpixel((0, 0))
replaceColor(image, garbageColor, WHITE_RGB)
colors = []
for i in range(249):
pixel = image.getpixel((i, WALK_Y))
if pixel != WHITE_RGB:
colors.append(pixel)
captchaLettersColor = max(set(colors), key = colors.count)
for y in range(image.size[1]):
for x in range(image.size[0]):
if pix[x, y] != captchaLettersColor:
image.putpixel((x, y), WHITE_RGB)
image = ImageEnhance.Contrast(image).enhance(500)
for y in range(image.size[1]):
for x in range(image.size[0]):
if pix[x, y] == captchaLettersColor:
p1 = pix[x + 1, y]
p2 = pix[x - 1, y]
p3 = pix[x, y + 1]
p4 = pix[x, y - 1]
p5 = pix[x + 2, y]
p6 = pix[x - 2, y]
p7 = pix[x, y + 2]
p8 = pix[x, y - 2]
if p1 != captchaLettersColor:
image.putpixel((x + 1, y), captchaLettersColor)
if p2 != captchaLettersColor:
image.putpixel((x - 1, y), captchaLettersColor)
if p3 != captchaLettersColor:
image.putpixel((x, y + 1), captchaLettersColor)
if p4 != captchaLettersColor:
image.putpixel((x, y - 1), captchaLettersColor)
if p5 != captchaLettersColor:
image.putpixel((x + 2, y), captchaLettersColor)
if p6 != captchaLettersColor:
image.putpixel((x - 2, y), captchaLettersColor)
if p7 != captchaLettersColor:
image.putpixel((x, y + 2), captchaLettersColor)
if p8 != captchaLettersColor:
image.putpixel((x, y - 2), captchaLettersColor)
image = ImageEnhance.Contrast(image).enhance(1200)
resized = image.resize((image.size[0] * 5, image.size[1] * 5))
decoded = pytesseract.image_to_string(resized, config = "--psm 13 --oem 3 -c tessedit_char_whitelist=23456789", lang = "eng")
return {"solution": decoded}