Download scripts/evaluate.py from QLU-LLM/CADGUI-Bench: direct link, hf CLI and curl.
- Browser
- Download file 9.59 kB
-
https://huggingface.co/datasets/QLU-LLM/CADGUI-Bench/resolve/main/scripts/evaluate.py
- Command line
-
hf download hf://datasets/QLU-LLM/CADGUI-Bench/scripts/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/datasets/QLU-LLM/CADGUI-Bench/resolve/main/scripts/evaluate.py
9.59 kB
| #!/usr/bin/env python3 | |
| """Run CADGUI-Bench against any OpenAI-compatible multimodal API.""" | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| import time | |
| from pathlib import Path | |
| REPO_ROOT = Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, str(REPO_ROOT / "evaluation")) | |
| import benchmark_evaluator as be # noqa: E402 | |
| from openai import OpenAI # noqa: E402 | |
| TASKS = { | |
| "1.1": ("localization", "任务1.1.json", "task1"), | |
| "1.2": ("localization", "任务1.2.json", "task1"), | |
| "1.3": ("localization", "任务1.3.json", "task1"), | |
| "2.1": ("localization", "任务2.1.json", "task2"), | |
| "2.2": ("localization", "任务2.2.json", "task2"), | |
| "2.3": ("localization", "任务2.3.json", "task2"), | |
| "3.1": ("localization", "任务3.1基础任务.json", "task3.1"), | |
| "3.2": ("localization", "任务3.2方位任务.json", "task3.2"), | |
| "3.3": ("localization", "任务3.3属性任务.json", "task3.3"), | |
| "3.4": ("localization", "任务3.4几何任务.json", "task3.4"), | |
| "3.5": ("localization", "任务3.5三维定位.json", "task3.5"), | |
| "4.1": ("action", "任务4.1平移缩放旋转.json", "task4.1"), | |
| "4.2": ("action", "任务4.2特殊操作.json", "task4.2"), | |
| "4.3": ("action", "任务4.3框选拖拽.json", "task4.3"), | |
| "5.1": ("multistep", "任务5.1_非画图操作.json", "task5.1"), | |
| "5.2": ("multistep", "任务5.2_画图操作.json", "task5.2"), | |
| } | |
| def load_json(path): | |
| with path.open("r", encoding="utf-8-sig") as stream: | |
| return json.load(stream) | |
| def write_result(path, result): | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") | |
| def run_localization(client, model, task_id, benchmark_path, image_dir, mode, tries): | |
| results = be.run_localization( | |
| client, model, str(benchmark_path), str(image_dir), mode=mode, tries=tries | |
| ) | |
| total_tries = sum(row["tries"] for row in results) | |
| summary = { | |
| "task": task_id, | |
| "model": model, | |
| "mode": mode, | |
| "n_items": len(results), | |
| "hits": sum(row["hits"] for row in results), | |
| "tries": total_tries, | |
| "hit_rate": round(100 * sum(row["hits"] for row in results) / total_tries, 2) if total_tries else 0, | |
| "parse_fail": sum(row.get("parse_fail", 0) for row in results), | |
| "results": results, | |
| } | |
| if mode == "bbox": | |
| ious = [row["avg_iou"] for row in results if "avg_iou" in row] | |
| if ious: | |
| summary["mean_iou"] = round(sum(ious) / len(ious), 4) | |
| summary["acc50"] = round(100 * sum(row["acc50"] for row in results if "acc50" in row) / len(ious), 2) | |
| return summary | |
| def run_action(client, model, task_id, benchmark_path, image_dir, tries): | |
| data = load_json(benchmark_path) | |
| rows = [] | |
| for item in data: | |
| image = image_dir / item["image_path"] | |
| width, height = item["image_resolution"] | |
| prompt = be.PROMPT_ACTION.format(instruction=item["instruction"]) | |
| action_hits = 0 | |
| full_hits = 0 | |
| parse_fail = 0 | |
| for _ in range(tries): | |
| reply = be.call_vlm(client, model, str(image), prompt, max_tokens=300) | |
| if reply.startswith("API_ERROR"): | |
| parse_fail += 1 | |
| continue | |
| score = be.eval_step(reply, item["ground_truth"], width, height) | |
| action_hits += int(score["action_ok"]) | |
| full_hits += int(score["step_ok"]) | |
| rows.append({ | |
| "id": item["id"], "action_hits": action_hits, "full_hits": full_hits, | |
| "tries": tries, "parse_fail": parse_fail, | |
| }) | |
| total = len(rows) * tries | |
| return { | |
| "task": task_id, "model": model, "n_items": len(rows), "tries_per_item": tries, | |
| "action_acc": round(100 * sum(row["action_hits"] for row in rows) / total, 2) if total else 0, | |
| "full_acc": round(100 * sum(row["full_hits"] for row in rows) / total, 2) if total else 0, | |
| "parse_fail": sum(row["parse_fail"] for row in rows), "results": rows, | |
| } | |
| def run_multistep(client, model, task_id, benchmark_path, image_dir): | |
| data = load_json(benchmark_path) | |
| task_results = [] | |
| for task in data: | |
| task_id_in_data = task["task_id"] | |
| instruction = task["high_level_instruction"] | |
| history = [] | |
| steps = [] | |
| first_error = None | |
| for step in task["steps"]: | |
| relative = step["image_path"].replace("\\", "/") | |
| relative = relative.replace("/raw_images/", "/") | |
| image = image_dir / relative | |
| if not image.exists(): | |
| image = image_dir / f"record_{task_id_in_data:03d}" / "raw_images" / Path(relative).name | |
| if not image.exists(): | |
| raise FileNotFoundError(f"Missing benchmark image: {image}") | |
| width, height = step["image_resolution"] | |
| history_text = "\n".join(history) if history else "(none)" | |
| prompt = ( | |
| "You are controlling SOLIDWORKS from the current screenshot.\n" | |
| f"Task: {instruction}\n" | |
| f"Previously completed actions (in order):\n{history_text}\n" | |
| f"Choose the next single action for the current screenshot.\n" | |
| f"{be.ACTION_SPACE}\n\n{be.COORD_SYSTEM}\n" | |
| "Output exactly:\nAction: <action_name>\n" | |
| "Params: <[x,y] or [x1,y1] [x2,y2] or direction or text or NONE>" | |
| ) | |
| reply = be.call_vlm(client, model, str(image), prompt, max_tokens=400) | |
| if reply.startswith("API_ERROR"): | |
| score = {"action_ok": False, "param_ok": False, "step_ok": False, "action": None} | |
| else: | |
| score = be.eval_step(reply, step["ground_truth"], width, height) | |
| steps.append({"step": step["step"], **score}) | |
| if not score["step_ok"] and first_error is None: | |
| first_error = step["step"] | |
| history.append(f"Step {step['step']}: {step['ground_truth']['action_type']}") | |
| correct = sum(row["step_ok"] for row in steps) | |
| task_results.append({ | |
| "task_id": task_id_in_data, "total_steps": len(steps), "correct_steps": correct, | |
| "step_accuracy": round(100 * correct / len(steps), 2) if steps else 0, | |
| "task_success": correct == len(steps), "first_error_step": first_error, "steps": steps, | |
| }) | |
| item_count = len(task_results) | |
| total_steps = sum(row["total_steps"] for row in task_results) | |
| correct_steps = sum(row["correct_steps"] for row in task_results) | |
| return { | |
| "task": task_id, "model": model, "n_items": item_count, "total_steps": total_steps, | |
| "correct_steps": correct_steps, | |
| "step_accuracy": round(100 * correct_steps / total_steps, 2) if total_steps else 0, | |
| "task_success_rate": round(100 * sum(row["task_success"] for row in task_results) / item_count, 2) if item_count else 0, | |
| "results": task_results, | |
| } | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--task", choices=[*TASKS, "all"], default="all") | |
| parser.add_argument("--model", required=True, help="Model name sent to the OpenAI-compatible endpoint") | |
| parser.add_argument("--api-base-url", default=os.getenv("API_BASE_URL", "http://localhost:8000/v1")) | |
| parser.add_argument("--api-key", default=os.getenv("API_KEY", "EMPTY")) | |
| parser.add_argument("--mode", choices=["point", "bbox", "both"], default="point") | |
| parser.add_argument("--tries", type=int, default=None, help="Calls per item; defaults to 1 for tasks 1-2, 10 otherwise") | |
| parser.add_argument("--output-dir", type=Path, default=Path("results")) | |
| args = parser.parse_args() | |
| if args.tries is not None and args.tries < 1: | |
| parser.error("--tries must be at least 1") | |
| client = OpenAI(api_key=args.api_key, base_url=args.api_base_url, timeout=120, max_retries=2) | |
| selected_tasks = list(TASKS) if args.task == "all" else [args.task] | |
| for task_id in selected_tasks: | |
| kind, filename, image_folder = TASKS[task_id] | |
| benchmark_path = REPO_ROOT / "Benchmark" / filename | |
| image_dir = REPO_ROOT / "images" / image_folder | |
| supports_bbox = kind == "localization" and task_id.startswith(("1.", "2.")) | |
| if supports_bbox and args.mode == "both": | |
| modes = ["point", "bbox"] | |
| elif supports_bbox: | |
| modes = [args.mode] | |
| elif kind == "localization": | |
| modes = ["point"] | |
| else: | |
| modes = [None] | |
| for mode in modes: | |
| started = time.perf_counter() | |
| tries = args.tries or (1 if task_id.startswith(("1.", "2.")) else 10) | |
| if kind == "localization": | |
| result = run_localization(client, args.model, task_id, benchmark_path, image_dir, mode, tries) | |
| elif kind == "action": | |
| result = run_action(client, args.model, task_id, benchmark_path, image_dir, tries) | |
| else: | |
| result = run_multistep(client, args.model, task_id, benchmark_path, image_dir) | |
| result["elapsed_seconds"] = round(time.perf_counter() - started, 2) | |
| suffix = f"_{mode}" if mode else "" | |
| output_path = args.output_dir / args.model.replace("/", "_") / f"task_{task_id}{suffix}.json" | |
| write_result(output_path, result) | |
| print(json.dumps({key: value for key, value in result.items() if key != "results"}, ensure_ascii=False)) | |
| print(f"Detailed results: {output_path}") | |
| if __name__ == "__main__": | |
| main() | |