#!/usr/bin/env python3 """ Task 1: QSO Host Galaxy Classification (AGN vs Galaxy) Classifies galaxy images using vision LLMs with a physics-based prompt focusing on accretion disk vs stellar bulge emission mechanisms. """ import argparse import base64 import csv 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" / "Task1_QSOHost" # ========================= # 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") # ========================= # PROMPTS # ========================= SYSTEM_PROMPT_GUIDED = """**Task:** Classify this image as either AGN or Galaxy. **Instructions:** Both categories are massive galaxies consisting of billions of stars spread over thousands of light-years. The distinction lies entirely in the physical mechanism dominating the very core: - Normal Galaxy: The light emission from the central region is purely the collective glow of the inner stellar populations, typically forming a central "bulge." A bulge is a massive, spheroidal concentration of older stars. While the stellar density naturally increases and peaks at the very center, the emission remains fundamentally rooted in a thermal population distributed across a spatial volume spanning hundreds to thousands of light-years. - Type-1 AGN: In addition to the host galaxy's extended stellar components (like the disk and the central bulge), the exact geometric center hosts a supermassive black hole with an active accretion disk. This disk emits a staggering amount of radiative energy from a physically microscopic volume (often just light-days across). This results in a hyper-luminous, practically dimensionless energy source sitting directly on top of the extended stellar bulge. Examine the image, focusing on the interplay between the central emission and the extended host structure. Rely on your understanding of how these underlying physical realities would naturally manifest visually: - If your analysis indicates the *presence* of an active accretion disk governing the core's emission, respond: AGN - If your analysis indicates the core is purely governed by distributed stellar emission (e.g., the bulge) without an overpowering active black hole component, respond: Galaxy **Output requirements:** - Respond with a JSON object in the following format: {"answer": "", "reason": ""} - The "answer" field must be either: AGN or Galaxy - The "reason" field should contain a brief explanation of your classification decision, explicitly linking the visual manifestation to the physical presence or absence of the central accretion disk versus a purely stellar bulge. - Do not include any text outside the JSON object""" SYSTEM_PROMPT_WOGUIDE = """Classify this galaxy image as either AGN or Galaxy. Output requirements: - Respond with a JSON object in the following format: {"answer": "", "reason": ""} - The "answer" field must be either: AGN or Galaxy - The "reason" field should contain a brief explanation of your classification decision - Do not include any text outside the JSON object""" SYSTEM_PROMPT_PHENOMENOLOGICAL = """**Task:** Classify this image as either AGN or Galaxy. **Instructions:** Examine the central region of this galaxy image in high detail. Follow these steps internally: 1. Analyze core sharpness: determine whether the core is an unresolved point source (PSF-like) or a resolved, extended structure. 2. Check for optical artifacts such as diffraction spikes or saturation bleeding. 3. Evaluate the transition from the center to the disk: smooth and gradual (bulge-like) versus a sharp point superposed on extended light (AGN-like). - If the center is dominated by an unresolved point source consistent with a Type-1 AGN, respond: AGN - If the center is dominated by a resolved stellar bulge, respond: Galaxy **Output requirements:** - Respond with a JSON object in the following format: {"answer": "", "reason": ""} - The "answer" field must be either: AGN or Galaxy - The "reason" field should contain a brief explanation of your classification decision - Do not include any text outside the JSON object""" USER_TEXT = "Label this image based on the underlying physical emission mechanisms present. Respond with JSON format." # ========================= # MODEL CALL # ========================= def classify_image(client: OpenAI, image_path: pathlib.Path, model: str, system_prompt: 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/jpeg;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": ""} # ========================= # MAIN PIPELINE # ========================= def run( csv_path: pathlib.Path, root: pathlib.Path, model: str, limit: Optional[int], results_dir: pathlib.Path, prompt_type: str, max_completion_tokens: int, resume: bool, ) -> pathlib.Path: client = get_client(model) if prompt_type == "guided": system_prompt = SYSTEM_PROMPT_GUIDED elif prompt_type == "woguide": system_prompt = SYSTEM_PROMPT_WOGUIDE elif prompt_type == "phenomenological": system_prompt = SYSTEM_PROMPT_PHENOMENOLOGICAL else: raise ValueError(f"Unknown prompt type: {prompt_type}") rows = list(csv.DictReader(csv_path.open())) results_dir.mkdir(parents=True, exist_ok=True) out_path = results_dir / f"predictions-{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) for i, row in enumerate(rows): if limit is not None and i >= limit: break image_path = (root / row["image"]).resolve() if str(image_path) in processed_images: continue label = row["label"].strip() response = classify_image(client, image_path, model, system_prompt, max_completion_tokens) content = response.choices[0].message.content pred = parse_prediction(content) answer = pred.get("answer", "") is_correct = answer.strip().lower() == label.lower() 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"{image_path.name}: 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="Task1: QSO Host Galaxy Classification") parser.add_argument("--csv", type=pathlib.Path, default=DATA_DIR / "image_labels.csv") parser.add_argument("--root", type=pathlib.Path, default=DATA_DIR) parser.add_argument("--model", default="gpt-4o") parser.add_argument("--prompt-type", choices=["guided", "woguide", "phenomenological"], 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( csv_path=args.csv, root=args.root, 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, )