| import os |
| import sys |
| import json |
| import base64 |
| import asyncio |
| import aiofiles |
| from tqdm.asyncio import tqdm_asyncio |
| from openai import AsyncOpenAI |
| from rouge import Rouge |
|
|
| |
| Test_Model = "Gemini" |
|
|
| |
| |
| TEST_JSON_PATH = "/code/CogReasoner/Test/VisualWebBench_webqa.json" |
| |
| OUTPUT_JSON_PATH = f"/code/CogReasoner/Code/Evalaute/Result/Test-{Test_Model}-VisualWebBench_WebQA.json" |
| MAX_SAMPLE = 245 |
| MAX_CONCURRENT_REQUESTS = 5 |
| MODEL_NAME = "gemini-2.5-pro" |
| BASE_URL = "http://localhost:8080/v1" |
|
|
| |
| client = AsyncOpenAI(api_key="AIzaSyBCL2-lp3jOBPPZc7-5NsSy8r7wDFaqnFI", |
| base_url="https://generativelanguage.googleapis.com/v1beta/openai/") |
|
|
| |
| def eval_webqa(preds, golds, **kwargs): |
| """ |
| 计算 WebQA 的 F1 分数。 |
| preds: 预测答案的列表。 |
| golds: 参考答案的列表的列表 (每个问题可以有多个参考答案)。 |
| """ |
| assert len(preds) == len(golds), "预测数量和参考答案数量必须一致" |
| f1_scores = [] |
| |
| rouge = Rouge(metrics=['rouge-1']) |
| for pred, gold_list in zip(preds, golds): |
| if not pred: |
| pred = " " |
| |
| |
| |
| try: |
| current_f1 = max([rouge.get_scores([pred], [gold], avg=True)['rouge-1']['f'] for gold in gold_list]) |
| f1_scores.append(current_f1) |
| except Exception as e: |
| |
| print(f"Warning: Could not compute F1 score for pred='{pred}' and gold_list='{gold_list}'. Error: {e}") |
| f1_scores.append(0.0) |
|
|
| |
| if not f1_scores: |
| return dict(f1=0.0) |
|
|
| return dict( |
| f1=sum(f1_scores) / len(f1_scores) * 100 |
| ) |
|
|
| |
| async def process_item(index, item, sem): |
| async with sem: |
| image_path = item["images"][0] |
| |
| |
| |
| |
| ground_truth = [item["messages"][1]["content"].strip()] |
| |
| user_prompt = item["messages"][0]["content"] |
|
|
| |
| async with aiofiles.open(image_path, "rb") as f: |
| content = await f.read() |
| encoded_image = base64.b64encode(content).decode("utf-8") |
| image_data_uri = f"data:image/png;base64,{encoded_image}" |
|
|
| try: |
| |
| prompt_text = user_prompt.replace("<image>\n", "").strip() |
|
|
| response = await client.chat.completions.create( |
| model=MODEL_NAME, |
| messages=[ |
| {"role": "system", "content": "You are a helpful assistant."}, |
| { |
| "role": "user", |
| "content": [ |
| {"type": "image_url", "image_url": {"url": image_data_uri}}, |
| {"type": "text", "text": prompt_text}, |
| ], |
| }, |
| ], |
| temperature=0.1, |
| top_p=0.95, |
| max_tokens=1024, |
| ) |
| pred_text = response.choices[0].message.content.strip() |
| except Exception as e: |
| pred_text = f"[ERROR] {str(e)}" |
|
|
| return { |
| "image": image_path, |
| "ground_truth": ground_truth, |
| "prediction": pred_text, |
| } |
|
|
| |
| async def main(): |
| try: |
| with open(TEST_JSON_PATH, "r", encoding="utf-8") as f: |
| test_data = json.load(f)[:MAX_SAMPLE] |
| except FileNotFoundError: |
| print(f"错误:测试文件未找到,请检查路径: {TEST_JSON_PATH}") |
| return |
|
|
| sem = asyncio.Semaphore(MAX_CONCURRENT_REQUESTS) |
| tasks = [process_item(i, item, sem) for i, item in enumerate(test_data)] |
|
|
| print(f"\n🚀 Starting evaluation for WebQA on {len(tasks)} samples...\n") |
| results = await tqdm_asyncio.gather(*tasks) |
|
|
| predictions = [r["prediction"] for r in results] |
| references = [r["ground_truth"] for r in results] |
|
|
| |
| |
| metrics = eval_webqa(predictions, references) |
|
|
| output = { |
| "task": "WebQA", |
| "model": Test_Model, |
| "metrics": metrics, |
| "results": results, |
| } |
|
|
| |
| os.makedirs(os.path.dirname(OUTPUT_JSON_PATH), exist_ok=True) |
| with open(OUTPUT_JSON_PATH, "w", encoding="utf-8") as f: |
| json.dump(output, f, indent=2, ensure_ascii=False) |
|
|
| print(f"\n✅ Evaluation Complete!") |
| print(f"📊 Metrics: {json.dumps(metrics, indent=2)}") |
| print(f"📁 Results saved at: {OUTPUT_JSON_PATH}") |
|
|
| await client.close() |
|
|
| |
| if __name__ == "__main__": |
| |
| try: |
| from rouge import Rouge |
| except ImportError: |
| print("错误: rouge 库未安装。请运行 'pip install rouge' 或 'pip install rouge-chinese'") |
| sys.exit(1) |
| |
| asyncio.run(main()) |
| sys.exit(0) |