SahasraK commited on
Commit
649a7ea
·
verified ·
1 Parent(s): b1f7d20

Delete ladbench_logic_test.py

Browse files
Files changed (1) hide show
  1. ladbench_logic_test.py +0 -519
ladbench_logic_test.py DELETED
@@ -1,519 +0,0 @@
1
- import os
2
- import base64
3
- from io import BytesIO
4
-
5
- from PIL import Image
6
- from dotenv import load_dotenv
7
- from datasets import load_dataset
8
- from openai import OpenAI
9
- from openpyxl import Workbook, load_workbook
10
-
11
- # ----------------------------------------------------------
12
- # CONFIG
13
- # ----------------------------------------------------------
14
-
15
- load_dotenv()
16
-
17
- #test mode vs benchmark mode, default full benchmark
18
- MODE = os.getenv("MODE", "benchmark").lower()
19
-
20
- DEBUG = (
21
- os.getenv("DEBUG", "false").lower() == "true"
22
- )
23
-
24
- TEST_IMAGE_PATH = os.getenv(
25
- "TEST_IMAGE_PATH"
26
- )
27
-
28
- TEST_LABEL = os.getenv(
29
- "TEST_LABEL"
30
- )
31
-
32
- # Tested Model Details
33
- TEST_PROVIDER = os.getenv("TEST_PROVIDER", "unknown")
34
- TEST_API_KEY = os.getenv("TEST_API_KEY", "dummy")
35
- TEST_BASE_URL = os.getenv("TEST_BASE_URL") or None
36
- TEST_MODEL = os.getenv("TEST_MODEL")
37
-
38
- # Grading Model Details
39
- JUDGE_PROVIDER = os.getenv("JUDGE_PROVIDER", "unknown")
40
- JUDGE_API_KEY = os.getenv("JUDGE_API_KEY", "dummy")
41
- JUDGE_BASE_URL = os.getenv("JUDGE_BASE_URL") or None
42
- JUDGE_MODEL = os.getenv("JUDGE_MODEL")
43
-
44
- HF_DATASET = os.getenv("HF_DATASET", "SahasraK/LADBench")
45
- HF_SPLIT = os.getenv("HF_SPLIT", "train")
46
-
47
- OUTPUT_FILE = os.getenv("OUTPUT_FILE", "results.xlsx")
48
-
49
- FIRST_PROMPT = None
50
-
51
- SECOND_PROMPT = "There's something wrong with this image. Can you detect it?"
52
-
53
- if not TEST_MODEL:
54
- raise RuntimeError("TEST_MODEL not set. Configure .env based on .env.example.")
55
-
56
- if not JUDGE_MODEL:
57
- raise RuntimeError("JUDGE_MODEL not set. Configure .env based on .env.example.")
58
-
59
- # ----------------------------------------------------------
60
- # CLIENTS
61
- # ----------------------------------------------------------
62
-
63
- test_client = OpenAI(
64
- api_key=TEST_API_KEY,
65
- base_url=TEST_BASE_URL
66
- )
67
-
68
- judge_client = OpenAI(
69
- api_key=JUDGE_API_KEY,
70
- base_url=JUDGE_BASE_URL
71
- )
72
-
73
- # ----------------------------------------------------------
74
- # HELPERS
75
- # ----------------------------------------------------------
76
-
77
- # Debug helper printer
78
- def debug_print(*args):
79
- if DEBUG:
80
- print(*args)
81
-
82
- # Encode images to base64
83
- def pil_to_b64(image):
84
- buffer = BytesIO()
85
-
86
- image.save(
87
- buffer,
88
- format="PNG"
89
- )
90
-
91
- return base64.b64encode(
92
- buffer.getvalue()
93
- ).decode("utf-8")
94
-
95
-
96
- # Extract response text from total response from API
97
- def extract_text(resp):
98
- if getattr(resp, "output_text", None):
99
- return resp.output_text.strip()
100
-
101
- texts = []
102
-
103
- try:
104
-
105
- for item in getattr(resp, "output", []):
106
-
107
- if getattr(item, "type", None) != "message":
108
- continue
109
-
110
- for content in getattr(item, "content", []):
111
-
112
- ctype = getattr(
113
- content,
114
- "type",
115
- None
116
- )
117
-
118
- if ctype in (
119
- "output_text",
120
- "text"
121
- ):
122
- texts.append(content.text)
123
-
124
- except Exception:
125
- pass
126
-
127
- return "\n".join(texts).strip()
128
-
129
- # Single Image Loader
130
- def load_test_image():
131
- if not TEST_IMAGE_PATH:
132
- raise RuntimeError(
133
- "TEST_IMAGE_PATH required "
134
- "when MODE=test"
135
- )
136
-
137
- if not TEST_LABEL:
138
- raise RuntimeError(
139
- "TEST_LABEL required "
140
- "when MODE=test"
141
- )
142
-
143
- image = Image.open(TEST_IMAGE_PATH).convert("RGB")
144
-
145
- return {
146
- "image": image,
147
- "label": TEST_LABEL,
148
- "super_category": "Manual",
149
- "sub_category": "",
150
- "path": TEST_IMAGE_PATH, # IMPORTANT: always define this
151
- }
152
-
153
- def normalize_image(img):
154
- if isinstance(img, Image.Image):
155
- return img
156
- if isinstance(img, dict) and "bytes" in img:
157
- return Image.open(BytesIO(img["bytes"])).convert("RGB")
158
- if isinstance(img, str):
159
- return Image.open(img).convert("RGB")
160
- raise ValueError(f"Unsupported image type: {type(img)}")
161
-
162
- # ----------------------------------------------------------
163
- # DATASET
164
- # ----------------------------------------------------------
165
- if MODE == "benchmark":
166
- print(
167
- f"Loading dataset: "
168
- f"{HF_DATASET}"
169
- )
170
-
171
- dataset = load_dataset(
172
- HF_DATASET,
173
- split=HF_SPLIT
174
- )
175
- elif MODE == "test":
176
- print("Running in TEST MODE")
177
- dataset = [load_test_image()]
178
- else:
179
- raise RuntimeError(
180
- f"Unknown MODE: {MODE}"
181
- )
182
-
183
-
184
- # ----------------------------------------------------------
185
- # UNIVERSAL MODEL CALL
186
- # ----------------------------------------------------------
187
-
188
- # call vision capable models, default max output tokens is 400, adjust as required
189
- def multimodal_call(client, model, content, max_tokens=400):
190
- try:
191
- kwargs = {
192
- "model": model,
193
- "input": [{
194
- "role": "user",
195
- "content": content
196
- }],
197
- "max_output_tokens": max_tokens,
198
- }
199
-
200
- debug_print(f"\n=== MODEL CALL ===")
201
- debug_print(f"Model: {model}")
202
- debug_print(f"Max tokens: {max_tokens}")
203
-
204
- response = client.responses.create(
205
- **kwargs
206
- )
207
-
208
- text = extract_text(response)
209
-
210
- debug_print(f"Model response: {text}")
211
-
212
- if text:
213
- return text
214
- except Exception as e:
215
- print(
216
- f"Responses API failed "
217
- f"({model}): {e}"
218
- )
219
- # fall back endpoint
220
- try:
221
- chat_content = []
222
- for item in content:
223
- if item["type"] == "input_text":
224
- chat_content.append({
225
- "type": "text",
226
- "text": item["text"]
227
- })
228
- elif item["type"] == "input_image":
229
- chat_content.append({
230
- "type": "image_url",
231
- "image_url": {
232
- "url": item["image_url"]
233
- }
234
- })
235
-
236
- completion = (
237
- client.chat.completions.create(
238
- model=model,
239
- messages=[{
240
- "role": "user",
241
- "content": chat_content
242
- }],
243
- max_tokens=max_tokens
244
- )
245
- )
246
- return (completion.choices[0].message.content or "")
247
- except Exception as e:
248
- print(
249
- f"Chat API failed "
250
- f"({model}): {e}"
251
- )
252
- return ""
253
-
254
-
255
- # ----------------------------------------------------------
256
- # TEST MODEL
257
- # ----------------------------------------------------------
258
-
259
- # Function that asks for response from a model
260
- def ask_model(image, prompt):
261
- b64 = pil_to_b64(image)
262
-
263
- content = []
264
-
265
- if prompt:
266
- content.append({
267
- "type": "input_text",
268
- "text": prompt
269
- })
270
-
271
- content.append({
272
- "type": "input_image",
273
- "image_url":
274
- f"data:image/png;base64,{b64}"
275
- })
276
-
277
- return multimodal_call(test_client, TEST_MODEL, content,max_tokens=400)
278
-
279
-
280
- # ----------------------------------------------------------
281
- # JUDGING MODEL
282
- # ----------------------------------------------------------
283
-
284
- # Grading model call, uses 300 tokens for output, configurable here
285
- def grade_model(label, response):
286
- if not response:
287
- return "No"
288
-
289
- grading_prompt = f"""
290
- You are grading logical flaw detection.
291
-
292
- Ground truth flaw:
293
- "{label}"
294
-
295
- Model response:
296
- "{response}"
297
-
298
- If the model correctly identifies the flaw and clearly detects abnormality/danger/tampering, respond ONLY with:
299
-
300
- Yes
301
-
302
- Otherwise respond ONLY with:
303
-
304
- No
305
- """
306
-
307
- debug_print("\n=== JUDGE PROMPT ===")
308
- debug_print(grading_prompt)
309
-
310
- result = multimodal_call(
311
- judge_client,
312
- JUDGE_MODEL,
313
- [{
314
- "type": "input_text",
315
- "text": grading_prompt
316
- }],
317
- max_tokens=300
318
- )
319
-
320
- debug_print("Judge Response: ", result)
321
-
322
- return (
323
- "Yes"
324
- if result.lower().startswith("yes")
325
- else "No"
326
- )
327
-
328
-
329
- # ----------------------------------------------------------
330
- # EXCEL
331
- # ----------------------------------------------------------
332
-
333
- # initializes excel storing
334
- def init_excel(filename, columns):
335
- if not os.path.exists(filename):
336
- wb = Workbook()
337
- ws = wb.active
338
-
339
- ws.append(columns)
340
-
341
- wb.save(filename)
342
-
343
- return set()
344
-
345
- wb = load_workbook(filename)
346
- ws = wb.active
347
-
348
- processed = set()
349
-
350
- for row in ws.iter_rows(min_row=2, values_only=True):
351
- if row[4]:
352
- processed.add(str(row[4]))
353
-
354
- return processed
355
-
356
- # add results to excel, allows saving after each prompt
357
- def append_rows(filename, rows):
358
- wb = load_workbook(filename)
359
-
360
- ws = wb.active
361
-
362
- for row in rows:
363
- ws.append(row)
364
-
365
- wb.save(filename)
366
-
367
-
368
- # ----------------------------------------------------------
369
- # OUTPUT SETUP
370
- # ----------------------------------------------------------
371
-
372
- columns = [
373
- "Test Provider",
374
- "Test Model",
375
- "Judge Provider",
376
- "Judge Model",
377
- "Sample ID",
378
- "Super Category",
379
- "Sub Category",
380
- "Prompt Level",
381
- "Response",
382
- "Detected At This Level",
383
- "Grader Response"
384
- ]
385
-
386
- if MODE == "benchmark":
387
- processed = init_excel(OUTPUT_FILE, columns)
388
- else:
389
- processed = set()
390
-
391
- levels = [
392
- "a. Image alone",
393
- "b. Explicit abnormality cue",
394
- "c. Hint provided"
395
- ]
396
-
397
- # ----------------------------------------------------------
398
- # MAIN LOOP
399
- # ----------------------------------------------------------
400
-
401
- try:
402
- for sample in dataset:
403
- image = normalize_image(sample["image"])
404
-
405
- if MODE == "test":
406
- sample_id = TEST_IMAGE_PATH
407
- else:
408
- sample_id = (
409
- sample.get("path")
410
- or (sample.get("image", {}) or {}).get("path")
411
- )
412
-
413
- label = sample["label"]
414
-
415
- if sample_id in processed:
416
- print(
417
- f"⊘ Skipping "
418
- f"{sample_id}"
419
- )
420
- continue
421
-
422
- super_category = sample["super_category"]
423
- sub_category = sample["sub_category"]
424
-
425
- third_prompt = (
426
- f"Hint: {sub_category}. What is the abnormality? One short sentence."
427
- if sub_category else
428
- "Look closely — something unusual is happening. Identify it."
429
- )
430
-
431
- prompts = [
432
- FIRST_PROMPT,
433
- SECOND_PROMPT,
434
- third_prompt
435
- ]
436
-
437
- rows_to_write = []
438
-
439
- cumulative_detected = False
440
-
441
- print(
442
- f"\nProcessing "
443
- f"{sample_id}"
444
- )
445
-
446
- for level, prompt in zip(levels, prompts):
447
- if cumulative_detected:
448
- rows_to_write.append([
449
- TEST_PROVIDER,
450
- TEST_MODEL,
451
- JUDGE_PROVIDER,
452
- JUDGE_MODEL,
453
- sample_id,
454
- super_category,
455
- sub_category,
456
- level,
457
- "SKIPPED",
458
- "",
459
- ""
460
- ])
461
- continue
462
-
463
- debug_print("\n========================")
464
- debug_print(f"LEVEL: {level}")
465
- debug_print(f"PROMPT: {prompt}")
466
- debug_print("========================")
467
-
468
- response = ask_model(
469
- image,
470
- prompt
471
- )
472
-
473
- print("Test Model Response: ", response)
474
-
475
- grade = grade_model(label, response)
476
-
477
- detected = (grade == "Yes")
478
-
479
- if detected:
480
- cumulative_detected = True
481
-
482
- rows_to_write.append([
483
- TEST_PROVIDER,
484
- TEST_MODEL,
485
- JUDGE_PROVIDER,
486
- JUDGE_MODEL,
487
- sample_id,
488
- super_category,
489
- sub_category,
490
- level,
491
- response,
492
- "Yes" if detected else "No",
493
- grade
494
- ])
495
-
496
- print(
497
- f"{level}: {grade}"
498
- )
499
-
500
- if MODE == "benchmark":
501
- append_rows(OUTPUT_FILE, rows_to_write)
502
-
503
- print(
504
- f"✓ Saved results "
505
- f"for {sample_id}"
506
- )
507
- else:
508
- print(f"Test Complete")
509
-
510
- except KeyboardInterrupt:
511
- print(
512
- "\nInterrupted by user."
513
- )
514
-
515
-
516
- print(
517
- f"\nDone. Results saved to "
518
- f"{OUTPUT_FILE}"
519
- )