
# ========== 安装特定 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
from decord import VideoReader, cpu
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, math
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):
    MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
    transform = 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=MEAN, std=STD)
    ])
    return transform
def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
    best_ratio_diff = float('inf')
    best_ratio = (1, 1)
    area = width * height
    for ratio in target_ratios:
        target_aspect_ratio = ratio[0] / ratio[1]
        ratio_diff = abs(aspect_ratio - target_aspect_ratio)
        if ratio_diff < best_ratio_diff:
            best_ratio_diff = ratio_diff
            best_ratio = ratio
        elif ratio_diff == best_ratio_diff:
            if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
                best_ratio = ratio
    return best_ratio

def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
    orig_width, orig_height = image.size
    aspect_ratio = orig_width / orig_height

    # calculate the existing image aspect ratio
    target_ratios = set(
        (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 <= max_num and i * j >= min_num)
    target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])

    # find the closest aspect ratio to the target
    target_aspect_ratio = find_closest_aspect_ratio(
        aspect_ratio, target_ratios, orig_width, orig_height, image_size)

    # calculate the target width and height
    target_width = image_size * target_aspect_ratio[0]
    target_height = image_size * target_aspect_ratio[1]
    blocks = target_aspect_ratio[0] * target_aspect_ratio[1]

    # resize the image
    resized_img = image.resize((target_width, target_height))
    processed_images = []
    for i in range(blocks):
        box = (
            (i % (target_width // image_size)) * image_size,
            (i // (target_width // image_size)) * image_size,
            ((i % (target_width // image_size)) + 1) * image_size,
            ((i // (target_width // image_size)) + 1) * image_size
        )
        # split the image
        split_img = resized_img.crop(box)
        processed_images.append(split_img)
    assert len(processed_images) == blocks
    if use_thumbnail and len(processed_images) != 1:
        thumbnail_img = image.resize((image_size, image_size))
        processed_images.append(thumbnail_img)
    return processed_images

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

def split_model(model_name):
    device_map = {}
    world_size = torch.cuda.device_count()
    config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
    num_layers = config.llm_config.num_hidden_layers
    # Since the first GPU will be used for ViT, treat it as half a GPU.
    num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
    num_layers_per_gpu = [num_layers_per_gpu] * world_size
    num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
    layer_cnt = 0
    for i, num_layer in enumerate(num_layers_per_gpu):
        for j in range(num_layer):
            device_map[f'language_model.model.layers.{layer_cnt}'] = i
            layer_cnt += 1
    device_map['vision_model'] = 0
    device_map['mlp1'] = 0
    device_map['language_model.model.tok_embeddings'] = 0
    device_map['language_model.model.embed_tokens'] = 0
    device_map['language_model.output'] = 0
    device_map['language_model.model.norm'] = 0
    device_map['language_model.model.rotary_emb'] = 0
    device_map['language_model.lm_head'] = 0
    device_map[f'language_model.model.layers.{num_layers - 1}'] = 0

    return device_map


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 = [
            float(data['bounds'][0] / w),
            float(data['bounds'][1] / h),
            float(data['bounds'][2] / w),
            float(data['bounds'][3] / h)
        ]
        # 默认格式
        query = system_prompt + data['instruction']
        # vLLM 专用格式
        if vllm_format:
            query = [
                {
                    "role": "system",
                    "content": system_prompt
                },
                {
                "role": "user",
                "content": [
                    {"type": 'image_url', "image_url": {"url": f"data:image/jpeg;base64,{encode_image(img_file)}"}},
                    {"type": 'text',      "text": 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):
    match = re.search(r"x\s*=\s*([\d.]+)\s*,\s*y\s*=\s*([\d.]+)", text)
    if match:
        x, y = map(float, match.groups())  # 转换为浮点数
        return [x, y]
    return [0, 0]


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="You are InternVL, a GUI agent. \n\nYou are given a task and a screenshot of the screen. You need to perform a series of pyautogui actions to complete the task.\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'
            d.pop('query')
            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_scores)})
    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/InternVL3-2B')
    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/GUI-CEval/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='internvl3-2b')
    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)