LADBench / Code /ladbench_logic_test.py
SahasraK's picture
Reuploaded code, organized
b599d65 verified
Raw
History Blame Contribute Delete
12.3 kB
import os
import base64
from io import BytesIO
from PIL import Image
from dotenv import load_dotenv
from datasets import load_dataset
from openai import OpenAI
from openpyxl import Workbook, load_workbook
# ----------------------------------------------------------
# CONFIG
# ----------------------------------------------------------
load_dotenv()
#test mode vs benchmark mode, default full benchmark
MODE = os.getenv("MODE", "benchmark").lower()
DEBUG = (
os.getenv("DEBUG", "false").lower() == "true"
)
TEST_IMAGE_PATH = os.getenv(
"TEST_IMAGE_PATH"
)
TEST_LABEL = os.getenv(
"TEST_LABEL"
)
# Tested Model Details
TEST_PROVIDER = os.getenv("TEST_PROVIDER", "unknown")
TEST_API_KEY = os.getenv("TEST_API_KEY", "dummy")
TEST_BASE_URL = os.getenv("TEST_BASE_URL") or None
TEST_MODEL = os.getenv("TEST_MODEL")
# Grading Model Details
JUDGE_PROVIDER = os.getenv("JUDGE_PROVIDER", "unknown")
JUDGE_API_KEY = os.getenv("JUDGE_API_KEY", "dummy")
JUDGE_BASE_URL = os.getenv("JUDGE_BASE_URL") or None
JUDGE_MODEL = os.getenv("JUDGE_MODEL")
HF_DATASET = os.getenv("HF_DATASET", "SahasraK/LADBench")
HF_SPLIT = os.getenv("HF_SPLIT", "train")
OUTPUT_FILE = os.getenv("OUTPUT_FILE", "results.xlsx")
FIRST_PROMPT = None
SECOND_PROMPT = "There's something wrong with this image. Can you detect it?"
if not TEST_MODEL:
raise RuntimeError("TEST_MODEL not set. Configure .env based on .env.example.")
if not JUDGE_MODEL:
raise RuntimeError("JUDGE_MODEL not set. Configure .env based on .env.example.")
# ----------------------------------------------------------
# CLIENTS
# ----------------------------------------------------------
test_client = OpenAI(
api_key=TEST_API_KEY,
base_url=TEST_BASE_URL
)
judge_client = OpenAI(
api_key=JUDGE_API_KEY,
base_url=JUDGE_BASE_URL
)
# ----------------------------------------------------------
# HELPERS
# ----------------------------------------------------------
# Debug helper printer
def debug_print(*args):
if DEBUG:
print(*args)
# Encode images to base64
def pil_to_b64(image):
buffer = BytesIO()
image.save(
buffer,
format="PNG"
)
return base64.b64encode(
buffer.getvalue()
).decode("utf-8")
# Extract response text from total response from API
def extract_text(resp):
if getattr(resp, "output_text", None):
return resp.output_text.strip()
texts = []
try:
for item in getattr(resp, "output", []):
if getattr(item, "type", None) != "message":
continue
for content in getattr(item, "content", []):
ctype = getattr(
content,
"type",
None
)
if ctype in (
"output_text",
"text"
):
texts.append(content.text)
except Exception:
pass
return "\n".join(texts).strip()
# Single Image Loader
def load_test_image():
if not TEST_IMAGE_PATH:
raise RuntimeError(
"TEST_IMAGE_PATH required "
"when MODE=test"
)
if not TEST_LABEL:
raise RuntimeError(
"TEST_LABEL required "
"when MODE=test"
)
image = Image.open(TEST_IMAGE_PATH).convert("RGB")
return {
"image": image,
"label": TEST_LABEL,
"super_category": "Manual",
"sub_category": "",
"path": TEST_IMAGE_PATH, # IMPORTANT: always define this
}
def normalize_image(img):
if isinstance(img, Image.Image):
return img
if isinstance(img, dict) and "bytes" in img:
return Image.open(BytesIO(img["bytes"])).convert("RGB")
if isinstance(img, str):
return Image.open(img).convert("RGB")
raise ValueError(f"Unsupported image type: {type(img)}")
# ----------------------------------------------------------
# DATASET
# ----------------------------------------------------------
if MODE == "benchmark":
print(
f"Loading dataset: "
f"{HF_DATASET}"
)
dataset = load_dataset(
HF_DATASET,
split=HF_SPLIT
)
elif MODE == "test":
print("Running in TEST MODE")
dataset = [load_test_image()]
else:
raise RuntimeError(
f"Unknown MODE: {MODE}"
)
# ----------------------------------------------------------
# UNIVERSAL MODEL CALL
# ----------------------------------------------------------
# call vision capable models, default max output tokens is 400, adjust as required
def multimodal_call(client, model, content, max_tokens=400):
try:
kwargs = {
"model": model,
"input": [{
"role": "user",
"content": content
}],
"max_output_tokens": max_tokens,
}
debug_print(f"\n=== MODEL CALL ===")
debug_print(f"Model: {model}")
debug_print(f"Max tokens: {max_tokens}")
response = client.responses.create(
**kwargs
)
text = extract_text(response)
debug_print(f"Model response: {text}")
if text:
return text
except Exception as e:
print(
f"Responses API failed "
f"({model}): {e}"
)
# fall back endpoint
try:
chat_content = []
for item in content:
if item["type"] == "input_text":
chat_content.append({
"type": "text",
"text": item["text"]
})
elif item["type"] == "input_image":
chat_content.append({
"type": "image_url",
"image_url": {
"url": item["image_url"]
}
})
completion = (
client.chat.completions.create(
model=model,
messages=[{
"role": "user",
"content": chat_content
}],
max_tokens=max_tokens
)
)
return (completion.choices[0].message.content or "")
except Exception as e:
print(
f"Chat API failed "
f"({model}): {e}"
)
return ""
# ----------------------------------------------------------
# TEST MODEL
# ----------------------------------------------------------
# Function that asks for response from a model
def ask_model(image, prompt):
b64 = pil_to_b64(image)
content = []
if prompt:
content.append({
"type": "input_text",
"text": prompt
})
content.append({
"type": "input_image",
"image_url":
f"data:image/png;base64,{b64}"
})
return multimodal_call(test_client, TEST_MODEL, content,max_tokens=400)
# ----------------------------------------------------------
# JUDGING MODEL
# ----------------------------------------------------------
# Grading model call, uses 300 tokens for output, configurable here
def grade_model(label, response):
if not response:
return "No"
grading_prompt = f"""
You are grading logical flaw detection.
Ground truth flaw:
"{label}"
Model response:
"{response}"
If the model correctly identifies the flaw and clearly detects abnormality/danger/tampering, respond ONLY with:
Yes
Otherwise respond ONLY with:
No
"""
debug_print("\n=== JUDGE PROMPT ===")
debug_print(grading_prompt)
result = multimodal_call(
judge_client,
JUDGE_MODEL,
[{
"type": "input_text",
"text": grading_prompt
}],
max_tokens=300
)
debug_print("Judge Response: ", result)
return (
"Yes"
if result.lower().startswith("yes")
else "No"
)
# ----------------------------------------------------------
# EXCEL
# ----------------------------------------------------------
# initializes excel storing
def init_excel(filename, columns):
if not os.path.exists(filename):
wb = Workbook()
ws = wb.active
ws.append(columns)
wb.save(filename)
return set()
wb = load_workbook(filename)
ws = wb.active
processed = set()
for row in ws.iter_rows(min_row=2, values_only=True):
if row[4]:
processed.add(str(row[4]))
return processed
# add results to excel, allows saving after each prompt
def append_rows(filename, rows):
wb = load_workbook(filename)
ws = wb.active
for row in rows:
ws.append(row)
wb.save(filename)
# ----------------------------------------------------------
# OUTPUT SETUP
# ----------------------------------------------------------
columns = [
"Test Provider",
"Test Model",
"Judge Provider",
"Judge Model",
"Sample ID",
"Super Category",
"Sub Category",
"Prompt Level",
"Response",
"Detected At This Level",
"Grader Response"
]
if MODE == "benchmark":
processed = init_excel(OUTPUT_FILE, columns)
else:
processed = set()
levels = [
"a. Image alone",
"b. Explicit abnormality cue",
"c. Hint provided"
]
# ----------------------------------------------------------
# MAIN LOOP
# ----------------------------------------------------------
try:
for sample in dataset:
image = normalize_image(sample["image"])
if MODE == "test":
sample_id = TEST_IMAGE_PATH
else:
sample_id = (
sample.get("path")
or (sample.get("image", {}) or {}).get("path")
)
label = sample["label"]
if sample_id in processed:
print(
f"⊘ Skipping "
f"{sample_id}"
)
continue
super_category = sample["super_category"]
sub_category = sample["sub_category"]
third_prompt = (
f"Hint: {sub_category}. What is the abnormality? One short sentence."
if sub_category else
"Look closely — something unusual is happening. Identify it."
)
prompts = [
FIRST_PROMPT,
SECOND_PROMPT,
third_prompt
]
rows_to_write = []
cumulative_detected = False
print(
f"\nProcessing "
f"{sample_id}"
)
for level, prompt in zip(levels, prompts):
if cumulative_detected:
rows_to_write.append([
TEST_PROVIDER,
TEST_MODEL,
JUDGE_PROVIDER,
JUDGE_MODEL,
sample_id,
super_category,
sub_category,
level,
"SKIPPED",
"",
""
])
continue
debug_print("\n========================")
debug_print(f"LEVEL: {level}")
debug_print(f"PROMPT: {prompt}")
debug_print("========================")
response = ask_model(
image,
prompt
)
print("Test Model Response: ", response)
grade = grade_model(label, response)
detected = (grade == "Yes")
if detected:
cumulative_detected = True
rows_to_write.append([
TEST_PROVIDER,
TEST_MODEL,
JUDGE_PROVIDER,
JUDGE_MODEL,
sample_id,
super_category,
sub_category,
level,
response,
"Yes" if detected else "No",
grade
])
print(
f"{level}: {grade}"
)
if MODE == "benchmark":
append_rows(OUTPUT_FILE, rows_to_write)
print(
f"✓ Saved results "
f"for {sample_id}"
)
else:
print(f"Test Complete")
except KeyboardInterrupt:
print(
"\nInterrupted by user."
)
print(
f"\nDone. Results saved to "
f"{OUTPUT_FILE}"
)