File size: 9,182 Bytes
325693c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#!/usr/bin/env python3
"""
Task 2: Radio Galaxy Morphology Classification (FRI vs FRII)

Classifies radio galaxy images using the Fanaroff-Riley classification scheme.
Supports MiraBest_F (FIRST survey) and MiraBest_N (NVSS survey) datasets.
"""

import argparse
import base64
import json
import os
import pathlib
import re
import time
from typing import Optional

from dotenv import load_dotenv
load_dotenv(override=True)

from openai import OpenAI


# =========================
# CONFIGURATION
# =========================

DATA_DIR = pathlib.Path(__file__).resolve().parent.parent.parent / "data" / "Task2_RadioMorph"


# =========================
# CLIENT
# =========================

def get_client(model: str) -> OpenAI:
    """Create OpenAI-compatible client based on model name.

    Requires environment variables:
      - OPENAI_API_KEY / OPENAI_BASE_URL for OpenAI/compatible models
      - CLAUDE_API_KEY for Claude models
      - GROK_API_KEY for Grok models
      - QWEN_API_KEY for Qwen models
      - INTERN_API_KEY for InternVL models
    """
    api_key = os.getenv("OPENAI_API_KEY")
    base_url = os.getenv("OPENAI_BASE_URL")

    if "intern" in model.lower():
        api_key = os.getenv("INTERN_API_KEY")
        base_url = os.getenv("INTERN_BASE_URL")
    elif "qwen" in model.lower():
        api_key = os.getenv("QWEN_API_KEY")
        base_url = os.getenv("QWEN_BASE_URL")
    elif "grok" in model.lower():
        api_key = os.getenv("GROK_API_KEY")
    elif "claude" in model.lower():
        api_key = os.getenv("CLAUDE_API_KEY")

    return OpenAI(api_key=api_key, base_url=base_url)


# =========================
# IMAGE UTILS
# =========================

def encode_image(path: pathlib.Path) -> str:
    with open(path, "rb") as f:
        return base64.b64encode(f.read()).decode("utf-8")


# =========================
# DATA LOADING
# =========================

def load_metadata(dataset: str, data_dir: pathlib.Path = DATA_DIR) -> list:
    metadata_path = data_dir / dataset / "metadata.jsonl"
    samples = []
    with open(metadata_path, 'r') as f:
        for line in f:
            data = json.loads(line.strip())
            samples.append(data)
    return samples


def get_survey_name(dataset: str) -> str:
    if dataset == "MiraBest_F":
        return "FIRST"
    elif dataset == "MiraBest_N":
        return "NVSS"
    return "radio"


# =========================
# PROMPTS
# =========================

def build_prompt_guided(survey: str) -> str:
    return f"""**Task:** Classify the radio galaxy image from {survey} survey according to the Fanaroff-Riley classification scheme (Class I or Class II).

**Instructions:**
- FRI (Fanaroff-Riley Type I): Edge-darkened sources where the radio emission is brightest near the core and fades toward the edges. The jets are typically less collimated and more turbulent.
- FRII (Fanaroff-Riley Type II): Edge-brightened sources with prominent hotspots at the outer edges of the radio lobes. The jets remain well-collimated until they reach the hotspots.

**Output requirements:**
- Respond with a JSON object in the following format: {{"answer": "", "reason": ""}}
- The "answer" field must be either: FRI or FRII
- The "reason" field should contain a brief explanation of your classification decision
- Do not include any text outside the JSON object
"""


def build_prompt_woguide(survey: str) -> str:
    return f"""Classify this radio galaxy image from {survey} survey as FRI or FRII.

Output requirements:
- Respond with a JSON object in the following format: {{"answer": "", "reason": ""}}
- The "answer" field must be either: FRI or FRII
- The "reason" field should contain a brief explanation of your classification decision
- Do not include any text outside the JSON object
"""


USER_TEXT = "Classify this radio galaxy image: FRI or FRII. Respond with JSON format."


# =========================
# MODEL CALL
# =========================

def classify_image(client: OpenAI, image_path: pathlib.Path, system_prompt: str, model: str, max_completion_tokens: int):
    img_b64 = encode_image(image_path)

    messages = [
        {"role": "system", "content": system_prompt},
        {
            "role": "user",
            "content": [
                {"type": "text", "text": USER_TEXT},
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:image/png;base64,{img_b64}",
                        "detail": "high",
                    },
                },
            ],
        },
    ]

    extra = {"enable_thinking": False} if "qwen" in model.lower() else {}
    for attempt in range(5):
        try:
            response = client.chat.completions.create(
                model=model,
                messages=messages,
                temperature=0,
                max_completion_tokens=max_completion_tokens,
                extra_body=extra if extra else None,
            )
            return response
        except Exception as e:
            if attempt < 4:
                wait = 2 ** attempt * 5
                print(f"  Attempt {attempt+1} failed ({e}), retrying in {wait}s...")
                time.sleep(wait)
            else:
                raise


# =========================
# PARSE PREDICTION
# =========================

def parse_prediction(raw: str) -> dict:
    cleaned = re.sub(r"```json\s*", "", raw)
    cleaned = re.sub(r"```\s*", "", cleaned)
    cleaned = cleaned.strip()
    try:
        return json.loads(cleaned)
    except json.JSONDecodeError:
        return {"answer": raw, "reason": ""}


def canonicalize_label(value: str) -> str:
    val = (value or "").strip().upper()
    if "FRII" in val or "FR2" in val or "II" in val:
        return "FRII"
    if "FRI" in val or "FR1" in val:
        return "FRI"
    return "Unknown"


# =========================
# MAIN PIPELINE
# =========================

def run(
    dataset: str,
    model: str,
    limit: Optional[int],
    results_dir: pathlib.Path,
    prompt_type: str,
    max_completion_tokens: int,
    resume: bool,
    data_dir: pathlib.Path = DATA_DIR,
) -> pathlib.Path:

    client = get_client(model)
    samples = load_metadata(dataset, data_dir)
    results_dir.mkdir(parents=True, exist_ok=True)

    out_path = results_dir / f"predictions-{dataset}-{prompt_type}-{model}.json"

    results = []
    processed_images = set()
    if resume and out_path.exists():
        with out_path.open("r") as f:
            results = json.load(f)
            processed_images = {r["image"] for r in results}
        print(f"Resuming from {len(results)} existing predictions")

    correct = sum(r["correct"] for r in results)
    total = len(results)

    survey = get_survey_name(dataset)
    if prompt_type == "guided":
        system_prompt = build_prompt_guided(survey)
    else:
        system_prompt = build_prompt_woguide(survey)

    for i, sample in enumerate(samples):
        if limit is not None and i >= limit:
            break

        image_path = data_dir / dataset / sample["filename"]
        if str(image_path) in processed_images:
            continue

        label = sample["label"]

        response = classify_image(client, image_path, system_prompt, model, max_completion_tokens)
        content = response.choices[0].message.content
        pred = parse_prediction(content)
        answer = canonicalize_label(pred.get("answer", ""))
        is_correct = answer == label

        total += 1
        correct += int(is_correct)

        results.append({
            "image": str(image_path),
            "label": label,
            "prediction": pred,
            "correct": int(is_correct),
            "raw_response": response.model_dump(),
        })
        print(f"{sample['filename']}: pred={answer} label={label} {'✓' if is_correct else '✗'}")

        with out_path.open("w") as f:
            json.dump(results, f, indent=2)

    if total > 0:
        print(f"Accuracy on {total} checked: {correct}/{total} = {correct/total:.2%}")

    print(f"Saved predictions to {out_path}")
    return out_path


# =========================
# ARGPARSE
# =========================

def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Task2: Radio Galaxy Morphology Classification")
    parser.add_argument("--dataset", choices=["MiraBest_F", "MiraBest_N"], default="MiraBest_F")
    parser.add_argument("--model", default="gpt-4o")
    parser.add_argument("--prompt-type", choices=["guided", "woguide"], default="guided")
    parser.add_argument("--limit", type=int, default=None)
    parser.add_argument("--results-dir", type=pathlib.Path, default=pathlib.Path("./results"))
    parser.add_argument("--max-completion-tokens", type=int, default=16384)
    parser.add_argument("--resume", action="store_true")
    return parser.parse_args()


if __name__ == "__main__":
    args = parse_args()
    run(
        dataset=args.dataset,
        model=args.model,
        limit=args.limit,
        results_dir=args.results_dir,
        prompt_type=args.prompt_type,
        max_completion_tokens=args.max_completion_tokens,
        resume=args.resume,
    )