yiseo0 commited on
Commit
20e893b
·
verified ·
1 Parent(s): 1ff0f6e

Upload run_evaluation_vlm.py

Browse files
Files changed (1) hide show
  1. run_evaluation_vlm.py +362 -0
run_evaluation_vlm.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ GIS_Bench 통합 VLM 평가 파이프라인 v4 (최종)
3
+ ========================================
4
+ 모든 출력물(HTML / PNG / JPG)을 동일한 VLM Judge로 평가
5
+
6
+ v4 변경사항 :
7
+ 1. 평가 모델 추가: claude_zeroshot, gpt_5.4_mini (총 5개 모델)
8
+ 2. 결과 저장 폴더명 변경: evaluation_results_vlm → evaluation_results_final
9
+ 3. 스크린샷 폴더명 변경: screenshots → screenshots_final
10
+
11
+ 평가 흐름:
12
+ HTML → Playwright 렌더링(3초 대기) → 스크린샷 → Claude VLM × 3회
13
+ PNG / JPG → 직접 → Claude VLM × 3회
14
+
15
+ 실행 방법:
16
+ set ANTHROPIC_API_KEY=your_key_here
17
+ python run_evaluation_vlm_v4_final.py
18
+ """
19
+
20
+ import os, json, base64, time, re
21
+ from pathlib import Path
22
+ from playwright.sync_api import sync_playwright
23
+ import anthropic
24
+ import openpyxl
25
+ import pandas as pd
26
+
27
+ # ══════════════════════════════════════════════════════
28
+ # 설정
29
+ # ══════════════════════════════════════════════════════
30
+ BASE_DIR = r"C:\Users\A\Desktop\대학원 졸업논문"
31
+ EXCEL_PATH = os.path.join(BASE_DIR, "GIS_Bench_문항.xlsx")
32
+ MODELS = ["claude_mcp", "claude_baseline", "claude_zeroshot", "gpt_5.2", "gpt_5.4_mini"]
33
+ RESULT_DIR = os.path.join(BASE_DIR, "evaluation_results_final")
34
+ SHOT_DIR = os.path.join(RESULT_DIR, "screenshots_final")
35
+ os.makedirs(RESULT_DIR, exist_ok=True)
36
+ os.makedirs(SHOT_DIR, exist_ok=True)
37
+
38
+ N_REPEAT = 3 # VLM 반복 횟수
39
+ PASS_SCORE = 60 # Pass 기준 (100점 정규화 기준)
40
+ RENDER_WAIT = 5000 # HTML 렌더링 대기 시간 (ms)
41
+ VIEWPORT = {"width": 1280, "height": 800}
42
+
43
+ client = anthropic.Anthropic()
44
+
45
+ # ══════════════════════════════════════════════════════
46
+ # 태스크 로드
47
+ # ══════════════════════════════════════════════════════
48
+ def load_tasks(excel_path: str) -> dict:
49
+ wb = openpyxl.load_workbook(excel_path)
50
+ ws = wb.active
51
+ tasks = {}
52
+ for row in ws.iter_rows(min_row=2, values_only=True):
53
+ no, prompt, level = row[0], row[1], row[2]
54
+ if no and prompt:
55
+ lv = int(str(level).replace("Level", "").strip()[0])
56
+ tasks[int(no)] = {"prompt": prompt, "level": lv}
57
+ return tasks
58
+
59
+ # ══════════════════════════════════════════════════════
60
+ # 파일 탐색
61
+ # ══════════════════════════════════════════════════════
62
+ def find_output_file(model: str, task_no: int) -> Path | None:
63
+ folder = Path(BASE_DIR) / model
64
+ if not folder.exists():
65
+ return None
66
+ for ext in [".html", ".htm", ".png", ".jpg", ".jpeg"]:
67
+ exact = folder / f"{task_no}{ext}"
68
+ if exact.exists():
69
+ return exact
70
+ matches = sorted(folder.glob(f"{task_no}_*{ext}"))
71
+ if matches:
72
+ return matches[0]
73
+ return None
74
+
75
+ # ══════════════════════════════════════════════════════
76
+ # HTML → 스크린샷 변환
77
+ # ══════════════════════════════════════════════════════
78
+ def html_to_screenshot(html_path: str, out_path: str, page) -> bool:
79
+ try:
80
+ file_uri = Path(html_path).as_uri()
81
+ page.goto(file_uri, timeout=30000)
82
+ page.wait_for_timeout(RENDER_WAIT)
83
+ try:
84
+ page.wait_for_selector(".leaflet-container", timeout=3000)
85
+ page.wait_for_timeout(1000)
86
+ except Exception:
87
+ pass
88
+ page.screenshot(path=out_path, full_page=False)
89
+ return True
90
+ except Exception as e:
91
+ print(f" ⚠️ 스크린샷 실패: {e}")
92
+ return False
93
+
94
+ # ══════════════════════════════════════════════════════
95
+ # 이미지 → base64 인코딩
96
+ # ══════════════════════════════════════════════════════
97
+ def encode_image(image_path: str) -> tuple[str, str]:
98
+ ext = Path(image_path).suffix.lower()
99
+ media_type = "image/jpeg" if ext in [".jpg", ".jpeg"] else "image/png"
100
+ with open(image_path, "rb") as f:
101
+ return base64.standard_b64encode(f.read()).decode("utf-8"), media_type
102
+
103
+ # ══════════════════════════════════════════════════════
104
+ # JSON 파싱 (마크다운·불완전 응답 방어)
105
+ # ══════════════════════════════════════════════════════
106
+ def safe_parse_json(text: str) -> dict | None:
107
+ text = text.replace("```json", "").replace("```", "").strip()
108
+ match = re.search(r'\{.*\}', text, re.DOTALL)
109
+ if not match:
110
+ return None
111
+ try:
112
+ return json.loads(match.group())
113
+ except json.JSONDecodeError:
114
+ return None
115
+
116
+ # ══════════════════════════════════════════════════════
117
+ # VLM Judge 프롬프트
118
+ # ══════════════════════════════════════════════════════
119
+ JUDGE_PROMPT_TEMPLATE = """GIS 결과물 평가 전문가로서 아래 태스크의 출력 이미지를 채점하세요.
120
+
121
+ [태스크 Level {level}]
122
+ {prompt}
123
+
124
+ [채점 기준 — 130점 만점]
125
+ 기본(100점):
126
+ exists(0/20): 의미있는 시각화 존재 여부
127
+ accuracy(0-30): 요청 지역·데이터셋 정확성
128
+ requirement(0-30): 색상·필터·버퍼 등 조건 충족
129
+ completeness(0-20): 범례·제목·라벨 완성도
130
+
131
+ 공간정확성(30점, 스크린샷 시각 판단):
132
+ spatial_location(0/8/15): 데이터가 올바른 지역에 표시되는지
133
+ 15=정상, 8=경미한 이상, 0=좌표오류·엉뚱한위치
134
+ geometry_validity(0/2/5): 폴리곤·버퍼 형태 이상 여부
135
+ 5=정상, 2=경미한이상, 0=명백한왜곡
136
+ numeric_match(0/5/10): 수치·조건이 결과에 반영되었는지
137
+ 10=일치, 5=부분반영, 0=미반영
138
+
139
+ total_raw = 7개 항목 합계
140
+ total_normalized = round(total_raw / 130 * 100)
141
+
142
+ [응답] JSON만 출력, 다른 텍스트 금지:
143
+ {{"exists":정수,"accuracy":정수,"requirement":정수,"completeness":정수,"spatial_location":정수,"geometry_validity":정수,"numeric_match":정수,"total_raw":정수,"total_normalized":정수,"pass":불리언,"reason":"한줄이유"}}"""
144
+
145
+
146
+ # ══════════════════════════════════════════════════════
147
+ # VLM Judge 실행
148
+ # ══════════════════════════════════════════════════════
149
+ def vlm_judge(image_path: str, task_no: int, prompt: str, level: int,
150
+ source_type: str) -> dict:
151
+ img_b64, media_type = encode_image(image_path)
152
+ judge_prompt = JUDGE_PROMPT_TEMPLATE.format(level=level, prompt=prompt)
153
+
154
+ raw_scores = []
155
+ raw_scores_130 = []
156
+ parsed_results = []
157
+
158
+ for attempt in range(N_REPEAT):
159
+ try:
160
+ resp = client.messages.create(
161
+ model="claude-sonnet-4-6",
162
+ max_tokens=1024,
163
+ messages=[{
164
+ "role": "user",
165
+ "content": [
166
+ {"type": "image",
167
+ "source": {"type": "base64",
168
+ "media_type": media_type,
169
+ "data": img_b64}},
170
+ {"type": "text", "text": judge_prompt}
171
+ ]
172
+ }]
173
+ )
174
+ text = resp.content[0].text.strip()
175
+ r = safe_parse_json(text)
176
+
177
+ if r is None:
178
+ raise ValueError(f"JSON 파싱 실패: {text[:80]}")
179
+
180
+ if "total_normalized" not in r:
181
+ basic = int(r.get("exists",0)) + int(r.get("accuracy",0)) + \
182
+ int(r.get("requirement",0)) + int(r.get("completeness",0))
183
+ spatial = int(r.get("spatial_location",0)) + \
184
+ int(r.get("geometry_validity",0)) + \
185
+ int(r.get("numeric_match",0))
186
+ r["total_raw"] = basic + spatial
187
+ r["total_normalized"] = round((basic + spatial) / 130 * 100)
188
+
189
+ raw_scores.append(int(r["total_normalized"]))
190
+ raw_scores_130.append(int(r.get("total_raw", 0)))
191
+ parsed_results.append(r)
192
+
193
+ except Exception as e:
194
+ print(f" ⚠️ VLM 호출 오류 (시도 {attempt+1}): {e}")
195
+ raw_scores.append(0)
196
+ raw_scores_130.append(0)
197
+ parsed_results.append({})
198
+
199
+ time.sleep(1.5)
200
+
201
+ avg_normalized = round(sum(raw_scores) / max(len(raw_scores), 1), 1)
202
+ avg_raw = round(sum(raw_scores_130) / max(len(raw_scores_130), 1), 1)
203
+
204
+ def avg_field(field):
205
+ vals = [r.get(field, 0) for r in parsed_results if r]
206
+ return round(sum(vals) / max(len(vals), 1), 1)
207
+
208
+ reason_parts = [r.get("reason", "") for r in parsed_results if r.get("reason")]
209
+ reason_summary = reason_parts[0] if reason_parts else "vlm_no_reason"
210
+
211
+ return {
212
+ "file_type": "html_screenshot" if source_type == "screenshot" else Path(image_path).suffix.lstrip("."),
213
+ "scores_3x": raw_scores,
214
+ "scores_3x_raw": raw_scores_130,
215
+ "score": avg_normalized,
216
+ "score_raw": avg_raw,
217
+ "spatial_location": avg_field("spatial_location"),
218
+ "geometry_validity": avg_field("geometry_validity"),
219
+ "numeric_match": avg_field("numeric_match"),
220
+ "pass": avg_normalized >= PASS_SCORE,
221
+ "reason": f"vlm_avg({','.join(map(str, raw_scores))}) | {reason_summary}"
222
+ }
223
+
224
+ # ══════════════════════════════════════════════════════
225
+ # 빈 결과 행 생성 헬퍼
226
+ # ══════════════════════════════════════════════════════
227
+ def empty_row(task_no, level_str, model, file_type, reason):
228
+ return {
229
+ "task_no": task_no, "level": level_str,
230
+ "model": model, "file_type": file_type,
231
+ "score": 0, "score_raw": 0,
232
+ "spatial_location": 0, "geometry_validity": 0, "numeric_match": 0,
233
+ "pass": False, "reason": reason,
234
+ "scores_3x": "", "scores_3x_raw": ""
235
+ }
236
+
237
+ # ══════════════════════════════════════════════════════
238
+ # 메인 실행
239
+ # ══════════════════════════════════════════════════════
240
+ def main():
241
+ print("📂 태스크 로드 중...")
242
+ tasks = load_tasks(EXCEL_PATH)
243
+ print(f" 총 {len(tasks)}개 태스크 로드 완료")
244
+ print(f" 평가 모델: {MODELS}\n")
245
+
246
+ results = []
247
+
248
+ with sync_playwright() as pw:
249
+ browser = pw.chromium.launch(headless=True)
250
+ page = browser.new_page(viewport=VIEWPORT)
251
+
252
+ for task_no in range(1, 51):
253
+ task_info = tasks.get(task_no, {})
254
+ prompt = task_info.get("prompt", "")
255
+ level = task_info.get("level", 1)
256
+ level_str = f"Level{level}"
257
+
258
+ for model in MODELS:
259
+ filepath = find_output_file(model, task_no)
260
+ tag = f"[{model:20s}] Task {task_no:02d} (L{level})"
261
+
262
+ # ── 파일 없음 ──────────────────────────────────
263
+ if filepath is None:
264
+ results.append(empty_row(task_no, level_str, model, "없음", "출력파일없음"))
265
+ print(f" {tag}: ❌ 파일 없음")
266
+ continue
267
+
268
+ ext = filepath.suffix.lower()
269
+
270
+ # ── HTML: 스크린샷 변환 후 VLM ─────────────────
271
+ if ext in [".html", ".htm"]:
272
+ shot_name = f"{model}_{task_no:02d}.png"
273
+ shot_path = os.path.join(SHOT_DIR, shot_name)
274
+ print(f" {tag}: 🖥️ 렌더링 중... ({filepath.name})")
275
+ ok = html_to_screenshot(str(filepath), shot_path, page)
276
+ if not ok:
277
+ results.append(empty_row(task_no, level_str, model, "html_render_fail", "HTML 렌더링 실패"))
278
+ continue
279
+ res = vlm_judge(shot_path, task_no, prompt, level, "screenshot")
280
+
281
+ # ── PNG / JPG: 직접 VLM ────────────────────────
282
+ elif ext in [".png", ".jpg", ".jpeg"]:
283
+ print(f" {tag}: 🖼️ 이미지 VLM 평가 중... ({filepath.name})")
284
+ res = vlm_judge(str(filepath), task_no, prompt, level, "original")
285
+
286
+ # ── 지원하지 않는 형식 ─────────────────────────
287
+ else:
288
+ results.append(empty_row(task_no, level_str, model, ext, f"미지원형식:{ext}"))
289
+ print(f" {tag}: ⏭️ 미지원 형식 ({ext})")
290
+ continue
291
+
292
+ icon = "✅" if res["pass"] else "❌"
293
+ print(f" {tag}: {icon} {res['score']:5.1f}점 "
294
+ f"[{res['file_type']}] scores={res['scores_3x']}")
295
+
296
+ results.append({
297
+ "task_no": task_no,
298
+ "level": level_str,
299
+ "model": model,
300
+ "file_type": res["file_type"],
301
+ "score": res["score"],
302
+ "score_raw": res["score_raw"],
303
+ "spatial_location": res["spatial_location"],
304
+ "geometry_validity": res["geometry_validity"],
305
+ "numeric_match": res["numeric_match"],
306
+ "pass": res["pass"],
307
+ "reason": res["reason"],
308
+ "scores_3x": str(res["scores_3x"]),
309
+ "scores_3x_raw": str(res["scores_3x_raw"])
310
+ })
311
+
312
+ browser.close()
313
+
314
+ # ── 결과 저장 ──────────────────────────────────────
315
+ df = pd.DataFrame(results)
316
+ all_path = os.path.join(RESULT_DIR, "all_scores_final.csv")
317
+ summary_path = os.path.join(RESULT_DIR, "paper_table_final.csv")
318
+ df.to_csv(all_path, index=False, encoding="utf-8-sig")
319
+
320
+ # ── 요약 출력 ──────────────────────────────────────
321
+ print("\n" + "═" * 70)
322
+ print("📊 모델 × 레벨별 성공률 (SR%) — 100점 정규화")
323
+ print("═" * 70)
324
+ sr = (df.groupby(["model", "level"])["pass"]
325
+ .mean().mul(100).round(1).unstack())
326
+ sr["전체"] = df.groupby("model")["pass"].mean().mul(100).round(1)
327
+ # 모델 순서 고정
328
+ model_order = [m for m in MODELS if m in sr.index]
329
+ print(sr.reindex(model_order).to_string())
330
+
331
+ print("\n📊 모델별 평균 점수 (100점 정규화)")
332
+ avg_score = df.groupby("model")["score"].mean().round(1)
333
+ print(avg_score.reindex(model_order).to_string())
334
+
335
+ print("\n📊 레벨별 평균 점수 (100점 정규화)")
336
+ print(df.groupby("level")["score"].mean().round(1).to_string())
337
+
338
+ print("\n📊 모델별 공간 정확성 항목 평균 (원점수)")
339
+ spatial_cols = ["spatial_location", "geometry_validity", "numeric_match"]
340
+ spatial_avg = df.groupby("model")[spatial_cols].mean().round(1)
341
+ print(spatial_avg.reindex(model_order).to_string())
342
+ print(" 만점: spatial_location=15 / geometry_validity=5 / numeric_match=10")
343
+
344
+ # ── 논문용 요약 테이블 ─────────────────────────────
345
+ summary = df.groupby(["model", "level"]).agg(
346
+ SR = ("pass", lambda x: f"{x.mean() * 100:.1f}%"),
347
+ Score = ("score", lambda x: f"{x.mean():.1f}"),
348
+ Score_raw = ("score_raw", lambda x: f"{x.mean():.1f}"),
349
+ Spatial_loc = ("spatial_location", lambda x: f"{x.mean():.1f}"),
350
+ Geom_validity = ("geometry_validity", lambda x: f"{x.mean():.1f}"),
351
+ Numeric_match = ("numeric_match", lambda x: f"{x.mean():.1f}"),
352
+ ).reset_index()
353
+ summary.to_csv(summary_path, index=False, encoding="utf-8-sig")
354
+
355
+ print(f"\n✅ 결과 저장 완료")
356
+ print(f" 전체 점수 : {all_path}")
357
+ print(f" 논문 테이블 : {summary_path}")
358
+ print(f" 스크린샷 폴더: {SHOT_DIR}")
359
+
360
+
361
+ if __name__ == "__main__":
362
+ main()