File size: 9,869 Bytes
f79f2ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import argparse
import base64
import io
import json
import os
from openai import OpenAI
from together import Together
import anthropic
from dotenv import load_dotenv
from PIL import Image

load_dotenv()
OpenAI_API_KEY = os.getenv("OpenAI_API_KEY")
Anthropic_API_KEY = os.getenv("Anthropic_API_KEY")
Gemini_API_KEY = os.getenv("Gemini_API_KEY")
Together_API_KEY = os.getenv("Together_API_KEY")

PROMPT = "What is the primary object that is completely occluded in this image? Be as specific as you can."
NUDGE_SUFFIX = " Pay close attention to any reflective surfaces or shadows in the image as you will need it to answer the question."
NUDGE_OCCLUSION = (
    "You are answering visual questions about images where a primary object may be completely occluded by a visible mask, box, or polygon.\n\n"
    "Your task is to identify the hidden object, not the occluder and not merely a shadow, reflection, surface, or visible nearby object.\n\n"
    "Before answering, carefully inspect the whole image. Pay special attention to:\n"
    "- shadows, reflections, mirrors, glass, water, shiny surfaces, and other indirect visual cues;\n"
    "- whether those cues physically correspond to the hidden object given position, lighting, orientation, scale, and scene geometry;\n"
    "- surrounding context, but only as secondary evidence when direct visual cues are insufficient.\n\n"
    "Do not rely mainly on common-sense priors if a shadow or reflection provides more specific evidence. Do not answer \"shadow\" or \"reflection\" unless the question specifically asks for the visual phenomenon itself; answer the object casting the shadow or being reflected.\n\n"
    "Give your best single answer. Be specific enough to distinguish the object when the image supports it, but do not over-specify uncertain details."
)
FOLLOWUP_PROMPT = "What is it a reflection of?"

JUDGE_RESPONSE_PROMPT = (
    "A vision model was asked to identify the primary occluded object in an image. "
    "Here is its response:\n\n\"{response}\"\n\n"
    "Does this response identify a reflective surface (such as a mirror, puddle, or similar) "
    "WITHOUT specifying what that surface is reflecting? "
    "Answer only 'yes' or 'no'."
)

JUDGE_GT_PROMPT = (
    "The ground truth answer for an occluded object identification task is:\n\n\"{ground_truth}\"\n\n"
    "Is this ground truth answer itself just a reflective surface (e.g. a mirror or puddle), "
    "with no information about what it is reflecting? "
    "Answer only 'yes' or 'no'."
)

def init_client(model):
    if "gpt" in model or model[0] == 'o':
        return OpenAI(api_key=OpenAI_API_KEY)
    elif "gemini" in model:
        return OpenAI(api_key=Gemini_API_KEY, base_url="https://generativelanguage.googleapis.com/v1beta/openai/")
    elif "claude" in model:
        return anthropic.Anthropic(api_key=Anthropic_API_KEY)
    else:
        return Together(api_key=Together_API_KEY)

def judge(prompt, judge_model):
    client = OpenAI(api_key=OpenAI_API_KEY)
    verdict = client.chat.completions.create(
        model=judge_model,
        temperature=0,
        messages=[{"role": "user", "content": prompt}]
    ).choices[0].message.content.strip().lower()
    return verdict.startswith("yes")

def encode_image(image_path, max_bytes=3.5 * 1024 * 1024):
    with open(image_path, "rb") as f:
        data = f.read()
    if len(data) <= max_bytes:
        return base64.b64encode(data).decode("utf-8")
    # Scale down until under max_bytes
    img = Image.open(io.BytesIO(data))
    scale = 0.9
    while True:
        buf = io.BytesIO()
        img.save(buf, format="PNG", optimize=True)
        if buf.tell() <= max_bytes:
            break
        w, h = img.size
        img = img.resize((int(w * scale), int(h * scale)), Image.LANCZOS)
    return base64.b64encode(buf.getvalue()).decode("utf-8")

def chat_completion(model, client, image_path, prompt=PROMPT):
    b64 = encode_image(image_path)
    media_type = "image/png"

    if "claude" in model:
        return client.messages.create(
            model=model,
            max_tokens=500,
            temperature=0,
            messages=[{
                "role": "user",
                "content": [
                    {"type": "image", "source": {"type": "base64", "media_type": media_type, "data": b64}},
                    {"type": "text", "text": prompt}
                ]
            }]
        ).content[0].text
    else:
        return client.chat.completions.create(
            model=model,
            temperature=0,
            messages=[{
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": f"data:{media_type};base64,{b64}"}},
                    {"type": "text", "text": prompt}
                ]
            }]
        ).choices[0].message.content

def followup_completion(model, client, image_path, initial_response, prompt=PROMPT):
    b64 = encode_image(image_path)
    media_type = "image/png"

    if "claude" in model:
        return client.messages.create(
            model=model,
            max_tokens=500,
            temperature=0,
            messages=[
                {
                    "role": "user",
                    "content": [
                        {"type": "image", "source": {"type": "base64", "media_type": media_type, "data": b64}},
                        {"type": "text", "text": prompt}
                    ]
                },
                {"role": "assistant", "content": initial_response},
                {"role": "user", "content": FOLLOWUP_PROMPT}
            ]
        ).content[0].text
    else:
        return client.chat.completions.create(
            model=model,
            temperature=0,
            messages=[
                {
                    "role": "user",
                    "content": [
                        {"type": "image_url", "image_url": {"url": f"data:{media_type};base64,{b64}"}},
                        {"type": "text", "text": prompt}
                    ]
                },
                {"role": "assistant", "content": initial_response},
                {"role": "user", "content": FOLLOWUP_PROMPT}
            ]
        ).choices[0].message.content

def run_eval(args, client):
    with open(os.path.join(args.data_dir, "annotations.json")) as f:
        entries = json.load(f)

    model_name = args.model.split("/")[-1]
    output_path = os.path.join(args.output_dir, f"{model_name}_results.json")

    # Load existing results for recovery
    if os.path.exists(output_path):
        with open(output_path) as f:
            results = json.load(f)
        done_ids = {r["id"] for r in results}
        print(f"Resuming: {len(done_ids)} already done, {len(entries) - len(done_ids)} remaining.")
    else:
        results = []
        done_ids = set()

    for entry in entries:
        if entry["id"] in done_ids:
            continue

        base = os.path.splitext(entry["original_file"])[0]
        occluded_path = os.path.join(args.data_dir, f"{base}_occluded.png")
        if not os.path.exists(occluded_path):
            continue
        ground_truth = entry.get("answer", "")

        is_physical = entry.get("physical", False)
        if args.nudge and not is_physical:
            continue
        if args.nudge == "reflective":
            prompt = PROMPT + NUDGE_SUFFIX
        elif args.nudge == "occlusion":
            prompt = NUDGE_OCCLUSION
        else:
            prompt = PROMPT

        print(f"Running {entry['id']}...")
        response = chat_completion(args.model, client, occluded_path, prompt=prompt)
        print(f"  Response: {response}")

        result = {
            "id": entry["id"],
            "ground_truth": ground_truth,
            "response": response,
            "followup_response": None
        }

        # Only consider a follow-up if the GT itself isn't just a bare reflective surface
        gt_is_bare_reflective = judge(
            JUDGE_GT_PROMPT.format(ground_truth=ground_truth),
            args.judge_model
        )

        if not gt_is_bare_reflective:
            response_is_bare_reflective = judge(
                JUDGE_RESPONSE_PROMPT.format(response=response),
                args.judge_model
            )
            if response_is_bare_reflective:
                print(f"  [Judge] Reflective surface without specifics — sending follow-up...")
                followup = followup_completion(args.model, client, occluded_path, response, prompt=prompt)
                print(f"  Follow-up: {followup}")
                result["followup_response"] = followup

        results.append(result)

        # Save after each entry so progress is never lost
        os.makedirs(args.output_dir, exist_ok=True)
        with open(output_path, "w") as f:
            json.dump(results, f, indent=2)

    return results

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--model", type=str, default="gpt-4o")
    parser.add_argument("--data_dir", type=str, default="data/combined_output")
    parser.add_argument("--output_dir", type=str, default="data/eval_results")
    parser.add_argument("--judge_model", type=str, default="gpt-5.4")
    parser.add_argument("--nudge", type=str, default=None, choices=["reflective", "occlusion"],
                        help="Nudge variant for physical entries: 'reflective' appends the reflective-surface hint; 'occlusion' uses a detailed occlusion-aware prompt.")
    return parser.parse_args()

def main(args):
    client = init_client(args.model)
    os.makedirs(args.output_dir, exist_ok=True)
    results = run_eval(args, client)
    model_name = args.model.split("/")[-1]
    print(f"Done. {len(results)} results in {os.path.join(args.output_dir, f'{model_name}_results.json')}")

if __name__ == "__main__":
    args = parse_args()
    main(args)