
# ========== 安装特定 transformers 版本 ==========
import subprocess
subprocess.run(["pip", "install", "transformers==4.37.2"], check=True)
print("安装完成，继续执行后续代码...")

from collections import defaultdict
from datetime import datetime
from PIL import Image
from tqdm import tqdm
import numpy as np
import torchvision.transforms as T
from torchvision.transforms.functional import InterpolationMode
from transformers import AutoModel, AutoTokenizer, AutoProcessor
import httpx, os, json, base64, re, argparse, torch, pytz
from openai import OpenAI


# ========== 工具函数 ==========
IMAGENET_MEAN = (0.485, 0.456, 0.406)
IMAGENET_STD = (0.229, 0.224, 0.225)

def encode_image(image_path: str) -> str:
    with open(image_path, "rb") as f:
        return base64.b64encode(f.read()).decode('utf-8')


def write_jsonl(data: list, path: str):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, 'a', encoding='utf-8') as f:
        for d in data:
            f.write(json.dumps(d, ensure_ascii=False) + '\n')


def build_transform(input_size):
    return T.Compose([
        T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
        T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
        T.ToTensor(),
        T.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
    ])


def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
    best_diff = float('inf')
    best = (1, 1)
    area = width * height
    for i, j in target_ratios:
        ar = i / j
        diff = abs(aspect_ratio - ar)
        if diff < best_diff or (diff == best_diff and area > 0.5 * image_size * image_size * i * j):
            best_diff, best = diff, (i, j)
    return best


def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
    w, h = image.size
    ar = w / h
    ratios = sorted({(i, j) for n in range(min_num, max_num+1) for i in range(1, n+1) for j in range(1, n+1) if i*j>=min_num and i*j<=max_num}, key=lambda x: x[0]*x[1])
    rows, cols = find_closest_aspect_ratio(ar, ratios, w, h, image_size)
    tw, th = image_size*rows, image_size*cols
    resized = image.resize((tw, th))
    tiles = []
    for idx in range(rows*cols):
        x0 = (idx % rows) * image_size
        y0 = (idx // rows) * image_size
        tiles.append(resized.crop((x0, y0, x0+image_size, y0+image_size)))
    if use_thumbnail and len(tiles)>1:
        tiles.append(image.resize((image_size, image_size)))
    return tiles


def load_image(image_file, input_size=448, max_num=12):
    img = Image.open(image_file).convert('RGB')
    transform = build_transform(input_size)
    parts = dynamic_preprocess(img, max_num=max_num, use_thumbnail=True, image_size=input_size)
    return torch.stack([transform(p) for p in parts])



def prepare_data(system_prompt: str, json_path: str, imgs_path: str, vllm_format=False) -> list:
    items = []
    with open(json_path, 'r', encoding='utf-8') as f:
        for line in f:
            items.append(json.loads(line))

    label_data = []
    for data in items:
        img_file = os.path.join(imgs_path, data['img_path'])
        w, h = Image.open(img_file).size
        bbox = [
            int(data['bounds'][0] / w * 1000),
            int(data['bounds'][1] / h * 1000),
            int(data['bounds'][2] / w * 1000),
            int(data['bounds'][3] / h * 1000)
        ]
        # 默认格式
        query = system_prompt.format(data['instruction'])
        # vLLM 专用格式
        if vllm_format:
            query = [{
                "role": "user",
                "content": [
                    {"type": 'image_url', "image_url": {"url": f"data:image/jpeg;base64,{encode_image(img_file)}"}},
                    {"type": 'text',      "text": system_prompt.format(data['instruction'])}
                ]
            }]

        label_data.append({
            'img_path': img_file,
            'query': query,
            'width': w,
            'height': h,
            'bbox': bbox,
            'device': data.get('device'),
            'data_type': data.get('data_type')
        })
    return label_data



def parse_output(text: str) -> list:
    try:
        data = json.loads(text)
        if all(k in data for k in ["x", "y", "width", "height"]):
            center_x = data["x"] + data["width"] // 2
            center_y = data["y"] + data["height"] // 2
            return [center_x, center_y]
    except json.JSONDecodeError:
        pass  # 继续执行正则解析

    match = re.search(r"\(\s*(\d+)\s*,\s*(\d+)\s*\)\s*,\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)", text)
    if match:
        x1, y1, x2, y2 = map(int, match.groups())  # 转换为整数
        center_x = (x1 + x2) // 2
        center_y = (y1 + y2) // 2
        return [center_x, center_y]

    pattern = r"(\d+\.\d+|\d+)[, ]+(\d+\.\d+|\d+)(?:[, ]+(\d+\.\d+|\d+)[, ]+(\d+\.\d+|\d+))?"
    matches = re.findall(pattern, text)

    results = []
    for match in matches:
        numbers = list(filter(None, match))  # 过滤掉空匹配项
        numbers = list(map(float, numbers))  # 转换为浮点数
        numbers = list(map(int, numbers))    # 取整（四舍五入改为 `round()`）

        if len(numbers) == 4:
            x1, y1, x2, y2 = numbers
            center_x = (x1 + x2) // 2
            center_y = (y1 + y2) // 2
            results.append([center_x, center_y])  # 计算中心点
        elif len(numbers) == 2:
            results.append(numbers)
        else:
            results.append([0, 0])

    results = results[0] if len(results) != 0 else [0, 0]
    return results


def is_point_in_bbox(pt: list, bbox: list) -> bool:
    x,y = pt; x1,y1,x2,y2 = bbox; return x1<=x<=x2 and y1<=y<=y2


def batch_data(lst: list, bs: int):
    for i in range(0, len(lst), bs): yield lst[i:i+bs]

# ========== 模型接口抽象 ==========
class BaseVisionModel:
    def infer_batch(self, batch): raise NotImplementedError

# ========== Transformers 实现 ==========
class TransformersVisionModel(BaseVisionModel):
    def __init__(self, args):
        self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        self.model = AutoModel.from_pretrained(
            args.model_path, 
            torch_dtype=torch.bfloat16,
            low_cpu_mem_usage=True, 
            trust_remote_code=True).eval().cuda()
        self.tokenizer = AutoTokenizer.from_pretrained(
            args.model_path, 
            trust_remote_code=True, 
            use_fast=False)

    def infer_batch(self, batch):
        outs=[]
        for d in batch:
            pv = load_image(d['img_path'], max_num=6).to(torch.bfloat16).cuda()
            res, _ = self.model.chat(self.tokenizer, pv, d['query'], {'max_new_tokens':1024,'do_sample':True}, None, return_history=True)
            outs.append(res)
        return outs

# ========== vLLM API 实现 ==========
class VLLMVisionModel(BaseVisionModel):
    def __init__(self, args):
        client = httpx.Client(proxies={'http://':args.proxy,'https://':args.proxy})
        self.openai=OpenAI(base_url=args.vllm_url, api_key='empty', http_client=client)
        self.deployment=args.deployment_name

    def infer_batch(self,batch):
        res=[]
        for d in batch:
            try:
                r=self.openai.chat.completions.create(model=self.deployment,messages=d['query'],frequency_penalty=1,max_tokens=32,temperature=0.0,top_p=0.7)
                res.append(r.choices[0].message.content)
            except Exception as e:
                print(f"⚠️ vLLM 调用失败: {e}")
                res.append(None)
        return res

# ========== 评估函数 ==========
def evaluate(model,args):
    sys_prompt="In the screenshot of this web page, please give me the coordinates of the element I want to click on according to my instructions(with point).\n\"{}\""
    data=prepare_data(sys_prompt,args.json_path,args.img_path, bool(args.vllm_url))
    all_scores, grouped=[], defaultdict(list)
    for batch in tqdm(batch_data(data,args.batch_size)):
        outs=model.infer_batch(batch)
        for d,t in zip(batch,outs):
            d['response']=t
            d['predict']=parse_output(t)
            correct=is_point_in_bbox(d['predict'],d['bbox'])
            d['correct']=correct
            if type(d['query']) is list and d['query'][0]['content'][0].get('image_url'):
                d['query'][0]['content'][0]['image_url']='masked'
            key = f"{d['device']}_{d['data_type']}"
            grouped[key].append(float(correct))
            all_scores.append(float(correct))
        write_jsonl(batch,args.result_path_file)
        for itm in batch: 
            print(itm)
    write_jsonl([vars(args)], args.result_path_file)
    stats=[{"item":k,"score":np.mean(v)} for k,v in grouped.items()]
    stats.append({"item":"all","score":np.mean(all_sc)})
    write_jsonl(stats,args.result_path_file)
    for s in stats: print(s)

if __name__=="__main__":
    p=argparse.ArgumentParser()
    p.add_argument('-m','--model_path',type=str,default='your_path/OS-Atlas-Base-4B')
    p.add_argument('-json','--json_path',type=str,default='your_path/pub_version/grounding.jsonl')
    p.add_argument('-img','--img_path',type=str,default='your_path/img/grounding')
    p.add_argument('-o','--result_path',type=str,default='your_path/gui-ceval/grounding')
    p.add_argument('-url','--vllm_url',type=str,default=None)
    p.add_argument('--deployment_name',type=str,default='os-atlas')
    p.add_argument('--proxy',type=str,default='if needed')
    p.add_argument('--batch_size',type=int,default=1)
    args=p.parse_args()
    now=datetime.now(pytz.timezone("Asia/Shanghai")).strftime("%Y%m%d%H%M%S")
    fname=f"{now}_{os.path.basename(args.model_path)}_mab_grounding_general.jsonl"
    args.result_path_file=os.path.join(args.result_path,fname)
    model=VLLMVisionModel(args) if args.vllm_url else TransformersVisionModel(args)
    evaluate(model,args)