import time,re,json,requests,io
import numpy as np
from PIL import Image
from scipy import ndimage
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
urllib3=__import__('urllib3'); urllib3.disable_warnings()
o=Options(); o.set_preference('dom.webdriver.enabled',False)
o.set_preference('network.http.referer.spoofSource',True)
o.set_preference('network.http.referer.defaultReferrer','https://ein38eu95792b.4656hd15.cc/')
d=webdriver.Firefox(options=o)
try:
    d.get('http://127.0.0.1:9999/geetest_page.html'); time.sleep(6)
    info=d.execute_script("""function r(s){var e=document.querySelector(s);if(!e)return null;var b=e.getBoundingClientRect();return {t:b.top,l:b.left,w:b.width,h:b.height,bg:getComputedStyle(e).backgroundImage};}return {bg:r('.geetest_bg'),slice:r('.geetest_slice'),slicebg:r('.geetest_slice_bg')};""")
    def dl(u):
        m=re.search(r'url\("?([^")]+)"?\)',u or '');return requests.get(m.group(1).replace('http://','https://'),timeout=20,verify=False).content
    bg=Image.open(io.BytesIO(dl(info['bg']['bg']))).convert('RGB'); sl=Image.open(io.BytesIO(dl(info['slicebg']['bg']))).convert('RGBA')
    bg.save('iou_bg.png'); sl.save('iou_sl.png')
    g=np.array(bg.convert('L')).astype(np.float32); sa=np.array(sl); mask=sa[:,:,3]>128
    ys,xs=np.where(mask); ax0,ay0=xs.min(),ys.min(); aw,ah=xs.max()-ax0+1,ys.max()-ay0+1
    top=int(round((info['slice']['t']-info['bg']['t'])*bg.size[1]/info['bg']['h']))
    print('slice_top_nat',top,'alpha',ax0,ay0,aw,ah,'bg',bg.size,'css',info['bg']['w'],info['bg']['h'])
    best=[]
    for th in [50,60,70,80,90,100]:
        dark=(g<th)
        for x in range(0,bg.size[0]-aw+1):
            y=top
            reg=dark[y:y+ah,x+ax0:x+ax0+aw]
            m2=mask[ay0:ay0+ah,ax0:ax0+aw]
            inter=(reg&m2).sum(); union=(reg|m2).sum()
            iou=inter/union if union else 0
            best.append((iou,th,x,int(reg.sum())))
    top10=sorted(best,reverse=True)[:10]
    for t in top10: print('IoU',t)
finally: d.quit()
