Datasets:
Download evaluation/run_evaluation_vlm.py from yiseo0/GIS-Bench: direct link, hf CLI and curl.
- Browser
- Download file 18 kB
-
https://huggingface.co/datasets/yiseo0/GIS-Bench/resolve/main/evaluation/run_evaluation_vlm.py
- Command line
-
hf download hf://datasets/yiseo0/GIS-Bench/evaluation/run_evaluation_vlm.py
-
curl -L -o run_evaluation_vlm.py https://huggingface.co/datasets/yiseo0/GIS-Bench/resolve/main/evaluation/run_evaluation_vlm.py
18 kB
| """ | |
| GIS_Bench 통합 VLM 평가 파이프라인 v4 (최종) | |
| ======================================== | |
| 모든 출력물(HTML / PNG / JPG)을 동일한 VLM Judge로 평가 | |
| v4 변경사항 : | |
| 1. 평가 모델 추가: claude_zeroshot, gpt_5.4_mini (총 5개 모델) | |
| 2. 결과 저장 폴더명 변경: evaluation_results_vlm → evaluation_results_final | |
| 3. 스크린샷 폴더명 변경: screenshots → screenshots_final | |
| 평가 흐름: | |
| HTML → Playwright 렌더링(3초 대기) → 스크린샷 → Claude VLM × 3회 | |
| PNG / JPG → 직접 → Claude VLM × 3회 | |
| 실행 방법: | |
| set ANTHROPIC_API_KEY=your_key_here | |
| python run_evaluation_vlm_v4_final.py | |
| """ | |
| import os, json, base64, time, re | |
| from pathlib import Path | |
| from playwright.sync_api import sync_playwright | |
| import anthropic | |
| import openpyxl | |
| import pandas as pd | |
| # ══════════════════════════════════════════════════════ | |
| # 설정 | |
| # ══════════════════════════════════════════════════════ | |
| BASE_DIR = r"C:\Users\A\Desktop\대학원 졸업논문" | |
| EXCEL_PATH = os.path.join(BASE_DIR, "GIS_Bench_문항.xlsx") | |
| MODELS = ["claude_mcp", "claude_baseline", "claude_zeroshot", "gpt_5.2", "gpt_5.4_mini"] | |
| RESULT_DIR = os.path.join(BASE_DIR, "evaluation_results_final") | |
| SHOT_DIR = os.path.join(RESULT_DIR, "screenshots_final") | |
| os.makedirs(RESULT_DIR, exist_ok=True) | |
| os.makedirs(SHOT_DIR, exist_ok=True) | |
| N_REPEAT = 3 # VLM 반복 횟수 | |
| PASS_SCORE = 60 # Pass 기준 (100점 정규화 기준) | |
| RENDER_WAIT = 5000 # HTML 렌더링 대기 시간 (ms) | |
| VIEWPORT = {"width": 1280, "height": 800} | |
| client = anthropic.Anthropic() | |
| # ══════════════════════════════════════════════════════ | |
| # 태스크 로드 | |
| # ══════════════════════════════════════════════════════ | |
| def load_tasks(excel_path: str) -> dict: | |
| wb = openpyxl.load_workbook(excel_path) | |
| ws = wb.active | |
| tasks = {} | |
| for row in ws.iter_rows(min_row=2, values_only=True): | |
| no, prompt, level = row[0], row[1], row[2] | |
| if no and prompt: | |
| lv = int(str(level).replace("Level", "").strip()[0]) | |
| tasks[int(no)] = {"prompt": prompt, "level": lv} | |
| return tasks | |
| # ══════════════════════════════════════════════════════ | |
| # 파일 탐색 | |
| # ══════════════════════════════════════════════════════ | |
| def find_output_file(model: str, task_no: int) -> Path | None: | |
| folder = Path(BASE_DIR) / model | |
| if not folder.exists(): | |
| return None | |
| for ext in [".html", ".htm", ".png", ".jpg", ".jpeg"]: | |
| exact = folder / f"{task_no}{ext}" | |
| if exact.exists(): | |
| return exact | |
| matches = sorted(folder.glob(f"{task_no}_*{ext}")) | |
| if matches: | |
| return matches[0] | |
| return None | |
| # ══════════════════════════════════════════════════════ | |
| # HTML → 스크린샷 변환 | |
| # ══════════════════════════════════════════════════════ | |
| def html_to_screenshot(html_path: str, out_path: str, page) -> bool: | |
| try: | |
| file_uri = Path(html_path).as_uri() | |
| page.goto(file_uri, timeout=30000) | |
| page.wait_for_timeout(RENDER_WAIT) | |
| try: | |
| page.wait_for_selector(".leaflet-container", timeout=3000) | |
| page.wait_for_timeout(1000) | |
| except Exception: | |
| pass | |
| page.screenshot(path=out_path, full_page=False) | |
| return True | |
| except Exception as e: | |
| print(f" ⚠️ 스크린샷 실패: {e}") | |
| return False | |
| # ══════════════════════════════════════════════════════ | |
| # 이미지 → base64 인코딩 | |
| # ══════════════════════════════════════════════════════ | |
| def encode_image(image_path: str) -> tuple[str, str]: | |
| ext = Path(image_path).suffix.lower() | |
| media_type = "image/jpeg" if ext in [".jpg", ".jpeg"] else "image/png" | |
| with open(image_path, "rb") as f: | |
| return base64.standard_b64encode(f.read()).decode("utf-8"), media_type | |
| # ══════════════════════════════════════════════════════ | |
| # JSON 파싱 (마크다운·불완전 응답 방어) | |
| # ══════════════════════════════════════════════════════ | |
| def safe_parse_json(text: str) -> dict | None: | |
| text = text.replace("```json", "").replace("```", "").strip() | |
| match = re.search(r'\{.*\}', text, re.DOTALL) | |
| if not match: | |
| return None | |
| try: | |
| return json.loads(match.group()) | |
| except json.JSONDecodeError: | |
| return None | |
| # ══════════════════════════════════════════════════════ | |
| # VLM Judge 프롬프트 | |
| # ══════════════════════════════════════════════════════ | |
| JUDGE_PROMPT_TEMPLATE = """GIS 결과물 평가 전문가로서 아래 태스크의 출력 이미지를 채점하세요. | |
| [태스크 Level {level}] | |
| {prompt} | |
| [채점 기준 — 130점 만점] | |
| 기본(100점): | |
| exists(0/20): 의미있는 시각화 존재 여부 | |
| accuracy(0-30): 요청 지역·데이터셋 정확성 | |
| requirement(0-30): 색상·필터·버퍼 등 조건 충족 | |
| completeness(0-20): 범례·제목·라벨 완성도 | |
| 공간정확성(30점, 스크린샷 시각 판단): | |
| spatial_location(0/8/15): 데이터가 올바른 지역에 표시되는지 | |
| 15=정상, 8=경미한 이상, 0=좌표오류·엉뚱한위치 | |
| geometry_validity(0/2/5): 폴리곤·버퍼 형태 이상 여부 | |
| 5=정상, 2=경미한이상, 0=명백한왜곡 | |
| numeric_match(0/5/10): 수치·조건이 결과에 반영되었는지 | |
| 10=일치, 5=부분반영, 0=미반영 | |
| total_raw = 7개 항목 합계 | |
| total_normalized = round(total_raw / 130 * 100) | |
| [응답] JSON만 출력, 다른 텍스트 금지: | |
| {{"exists":정수,"accuracy":정수,"requirement":정수,"completeness":정수,"spatial_location":정수,"geometry_validity":정수,"numeric_match":정수,"total_raw":정수,"total_normalized":정수,"pass":불리언,"reason":"한줄이유"}}""" | |
| # ══════════════════════════════════════════════════════ | |
| # VLM Judge 실행 | |
| # ══════════════════════════════════════════════════════ | |
| def vlm_judge(image_path: str, task_no: int, prompt: str, level: int, | |
| source_type: str) -> dict: | |
| img_b64, media_type = encode_image(image_path) | |
| judge_prompt = JUDGE_PROMPT_TEMPLATE.format(level=level, prompt=prompt) | |
| raw_scores = [] | |
| raw_scores_130 = [] | |
| parsed_results = [] | |
| for attempt in range(N_REPEAT): | |
| try: | |
| resp = client.messages.create( | |
| model="claude-sonnet-4-6", | |
| max_tokens=1024, | |
| messages=[{ | |
| "role": "user", | |
| "content": [ | |
| {"type": "image", | |
| "source": {"type": "base64", | |
| "media_type": media_type, | |
| "data": img_b64}}, | |
| {"type": "text", "text": judge_prompt} | |
| ] | |
| }] | |
| ) | |
| text = resp.content[0].text.strip() | |
| r = safe_parse_json(text) | |
| if r is None: | |
| raise ValueError(f"JSON 파싱 실패: {text[:80]}") | |
| if "total_normalized" not in r: | |
| basic = int(r.get("exists",0)) + int(r.get("accuracy",0)) + \ | |
| int(r.get("requirement",0)) + int(r.get("completeness",0)) | |
| spatial = int(r.get("spatial_location",0)) + \ | |
| int(r.get("geometry_validity",0)) + \ | |
| int(r.get("numeric_match",0)) | |
| r["total_raw"] = basic + spatial | |
| r["total_normalized"] = round((basic + spatial) / 130 * 100) | |
| raw_scores.append(int(r["total_normalized"])) | |
| raw_scores_130.append(int(r.get("total_raw", 0))) | |
| parsed_results.append(r) | |
| except Exception as e: | |
| print(f" ⚠️ VLM 호출 오류 (시도 {attempt+1}): {e}") | |
| raw_scores.append(0) | |
| raw_scores_130.append(0) | |
| parsed_results.append({}) | |
| time.sleep(1.5) | |
| avg_normalized = round(sum(raw_scores) / max(len(raw_scores), 1), 1) | |
| avg_raw = round(sum(raw_scores_130) / max(len(raw_scores_130), 1), 1) | |
| def avg_field(field): | |
| vals = [r.get(field, 0) for r in parsed_results if r] | |
| return round(sum(vals) / max(len(vals), 1), 1) | |
| reason_parts = [r.get("reason", "") for r in parsed_results if r.get("reason")] | |
| reason_summary = reason_parts[0] if reason_parts else "vlm_no_reason" | |
| return { | |
| "file_type": "html_screenshot" if source_type == "screenshot" else Path(image_path).suffix.lstrip("."), | |
| "scores_3x": raw_scores, | |
| "scores_3x_raw": raw_scores_130, | |
| "score": avg_normalized, | |
| "score_raw": avg_raw, | |
| "spatial_location": avg_field("spatial_location"), | |
| "geometry_validity": avg_field("geometry_validity"), | |
| "numeric_match": avg_field("numeric_match"), | |
| "pass": avg_normalized >= PASS_SCORE, | |
| "reason": f"vlm_avg({','.join(map(str, raw_scores))}) | {reason_summary}" | |
| } | |
| # ══════════════════════════════════════════════════════ | |
| # 빈 결과 행 생성 헬퍼 | |
| # ══════════════════════════════════════════════════════ | |
| def empty_row(task_no, level_str, model, file_type, reason): | |
| return { | |
| "task_no": task_no, "level": level_str, | |
| "model": model, "file_type": file_type, | |
| "score": 0, "score_raw": 0, | |
| "spatial_location": 0, "geometry_validity": 0, "numeric_match": 0, | |
| "pass": False, "reason": reason, | |
| "scores_3x": "", "scores_3x_raw": "" | |
| } | |
| # ══════════════════════════════════════════════════════ | |
| # 메인 실행 | |
| # ══════════════════════════════════════════════════════ | |
| def main(): | |
| print("📂 태스크 로드 중...") | |
| tasks = load_tasks(EXCEL_PATH) | |
| print(f" 총 {len(tasks)}개 태스크 로드 완료") | |
| print(f" 평가 모델: {MODELS}\n") | |
| results = [] | |
| with sync_playwright() as pw: | |
| browser = pw.chromium.launch(headless=True) | |
| page = browser.new_page(viewport=VIEWPORT) | |
| for task_no in range(1, 51): | |
| task_info = tasks.get(task_no, {}) | |
| prompt = task_info.get("prompt", "") | |
| level = task_info.get("level", 1) | |
| level_str = f"Level{level}" | |
| for model in MODELS: | |
| filepath = find_output_file(model, task_no) | |
| tag = f"[{model:20s}] Task {task_no:02d} (L{level})" | |
| # ── 파일 없음 ────────────────────────────────── | |
| if filepath is None: | |
| results.append(empty_row(task_no, level_str, model, "없음", "출력파일없음")) | |
| print(f" {tag}: ❌ 파일 없음") | |
| continue | |
| ext = filepath.suffix.lower() | |
| # ── HTML: 스크린샷 변환 후 VLM ───────────────── | |
| if ext in [".html", ".htm"]: | |
| shot_name = f"{model}_{task_no:02d}.png" | |
| shot_path = os.path.join(SHOT_DIR, shot_name) | |
| print(f" {tag}: 🖥️ 렌더링 중... ({filepath.name})") | |
| ok = html_to_screenshot(str(filepath), shot_path, page) | |
| if not ok: | |
| results.append(empty_row(task_no, level_str, model, "html_render_fail", "HTML 렌더링 실패")) | |
| continue | |
| res = vlm_judge(shot_path, task_no, prompt, level, "screenshot") | |
| # ── PNG / JPG: 직접 VLM ──────────────────────── | |
| elif ext in [".png", ".jpg", ".jpeg"]: | |
| print(f" {tag}: 🖼️ 이미지 VLM 평가 중... ({filepath.name})") | |
| res = vlm_judge(str(filepath), task_no, prompt, level, "original") | |
| # ── 지원하지 않는 형식 ───────────────────────── | |
| else: | |
| results.append(empty_row(task_no, level_str, model, ext, f"미지원형식:{ext}")) | |
| print(f" {tag}: ⏭️ 미지원 형식 ({ext})") | |
| continue | |
| icon = "✅" if res["pass"] else "❌" | |
| print(f" {tag}: {icon} {res['score']:5.1f}점 " | |
| f"[{res['file_type']}] scores={res['scores_3x']}") | |
| results.append({ | |
| "task_no": task_no, | |
| "level": level_str, | |
| "model": model, | |
| "file_type": res["file_type"], | |
| "score": res["score"], | |
| "score_raw": res["score_raw"], | |
| "spatial_location": res["spatial_location"], | |
| "geometry_validity": res["geometry_validity"], | |
| "numeric_match": res["numeric_match"], | |
| "pass": res["pass"], | |
| "reason": res["reason"], | |
| "scores_3x": str(res["scores_3x"]), | |
| "scores_3x_raw": str(res["scores_3x_raw"]) | |
| }) | |
| browser.close() | |
| # ── 결과 저장 ────────────────────────────────────── | |
| df = pd.DataFrame(results) | |
| all_path = os.path.join(RESULT_DIR, "all_scores_final.csv") | |
| summary_path = os.path.join(RESULT_DIR, "paper_table_final.csv") | |
| df.to_csv(all_path, index=False, encoding="utf-8-sig") | |
| # ── 요약 출력 ────────────────────────────────────── | |
| print("\n" + "═" * 70) | |
| print("📊 모델 × 레벨별 성공률 (SR%) — 100점 정규화") | |
| print("═" * 70) | |
| sr = (df.groupby(["model", "level"])["pass"] | |
| .mean().mul(100).round(1).unstack()) | |
| sr["전체"] = df.groupby("model")["pass"].mean().mul(100).round(1) | |
| # 모델 순서 고정 | |
| model_order = [m for m in MODELS if m in sr.index] | |
| print(sr.reindex(model_order).to_string()) | |
| print("\n📊 모델별 평균 점수 (100점 정규화)") | |
| avg_score = df.groupby("model")["score"].mean().round(1) | |
| print(avg_score.reindex(model_order).to_string()) | |
| print("\n📊 레벨별 평균 점수 (100점 정규화)") | |
| print(df.groupby("level")["score"].mean().round(1).to_string()) | |
| print("\n📊 모델별 공간 정확성 항목 평균 (원점수)") | |
| spatial_cols = ["spatial_location", "geometry_validity", "numeric_match"] | |
| spatial_avg = df.groupby("model")[spatial_cols].mean().round(1) | |
| print(spatial_avg.reindex(model_order).to_string()) | |
| print(" 만점: spatial_location=15 / geometry_validity=5 / numeric_match=10") | |
| # ── 논문용 요약 테이블 ───────────────────────────── | |
| summary = df.groupby(["model", "level"]).agg( | |
| SR = ("pass", lambda x: f"{x.mean() * 100:.1f}%"), | |
| Score = ("score", lambda x: f"{x.mean():.1f}"), | |
| Score_raw = ("score_raw", lambda x: f"{x.mean():.1f}"), | |
| Spatial_loc = ("spatial_location", lambda x: f"{x.mean():.1f}"), | |
| Geom_validity = ("geometry_validity", lambda x: f"{x.mean():.1f}"), | |
| Numeric_match = ("numeric_match", lambda x: f"{x.mean():.1f}"), | |
| ).reset_index() | |
| summary.to_csv(summary_path, index=False, encoding="utf-8-sig") | |
| print(f"\n✅ 결과 저장 완료") | |
| print(f" 전체 점수 : {all_path}") | |
| print(f" 논문 테이블 : {summary_path}") | |
| print(f" 스크린샷 폴더: {SHOT_DIR}") | |
| if __name__ == "__main__": | |
| main() | |