import argparse import json from pathlib import Path import numpy as np import torch from PIL import Image from transformers import ( AutoImageProcessor, AutoModelForDepthEstimation, AutoModelForZeroShotObjectDetection, AutoProcessor, ) BOX_THRESHOLD = 0.06 TEXT_THRESHOLD = 0.06 MIN_AREA = 0.0015 MAX_AREA = 0.55 CLAIM_RELATION = {"left_right": "left", "above_below": "above", "front_behind": "front", "on_not_on": "on"} def load_tools(gdino_dir, depth_dir, device): det_processor = AutoProcessor.from_pretrained(gdino_dir) det_model = AutoModelForZeroShotObjectDetection.from_pretrained(gdino_dir).to(device).eval() depth_processor = AutoImageProcessor.from_pretrained(depth_dir) depth_model = AutoModelForDepthEstimation.from_pretrained(depth_dir).to(device).eval() return det_processor, det_model, depth_processor, depth_model def detect(det_processor, det_model, image, labels, device): width, height = image.size boxes = {} for label in labels: text = f"{label} ." inputs = det_processor(images=image, text=text, return_tensors="pt").to(device) with torch.no_grad(): outputs = det_model(**inputs) results = det_processor.post_process_grounded_object_detection( outputs, inputs["input_ids"], threshold=BOX_THRESHOLD, text_threshold=TEXT_THRESHOLD, target_sizes=[image.size[::-1]], )[0] names = results.get("text_labels") if names is None: names = results["labels"] best = None best_any = None for box, score, name in zip(results["boxes"], results["scores"], names): label_text = str(name).strip().lower().replace("_", " ") if label not in label_text: continue x0, y0, x1, y1 = [float(v) for v in box] if x1 <= x0 or y1 <= y0: continue area = ((x1 - x0) * (y1 - y0)) / (width * height) entry = { "box": [x0 / width, y0 / height, x1 / width, y1 / height], "score": float(score), "area": area, } if best_any is None or entry["score"] > best_any["score"]: best_any = entry if not MIN_AREA <= area <= MAX_AREA: continue if best is None or entry["score"] > best["score"]: best = entry chosen = best or best_any if chosen is not None: boxes[label] = chosen return boxes def depth_map(depth_processor, depth_model, image, device): inputs = depth_processor(images=image, return_tensors="pt").to(device) with torch.no_grad(): outputs = depth_model(**inputs) pred = torch.nn.functional.interpolate( outputs.predicted_depth.unsqueeze(1), size=image.size[::-1], mode="bicubic", align_corners=False, ).squeeze() arr = pred.detach().cpu().numpy().astype(np.float32) lo, hi = float(arr.min()), float(arr.max()) if hi - lo < 1e-6: return np.zeros_like(arr) return (arr - lo) / (hi - lo) def box_median_depth(depth, box): height, width = depth.shape x0, y0, x1, y1 = box c0 = int(max(0, min(width - 1, round(x0 * width)))) c1 = int(max(1, min(width, round(x1 * width)))) r0 = int(max(0, min(height - 1, round(y0 * height)))) r1 = int(max(1, min(height, round(y1 * height)))) patch = depth[r0:r1, c0:c1] if patch.size == 0: return float("nan") return float(np.median(patch)) def measurements(sub, obj, sub_depth, obj_depth): dx = (sub[0] + sub[2]) / 2 - (obj[0] + obj[2]) / 2 dy = (sub[3] + sub[1]) / 2 - (obj[3] + obj[1]) / 2 dz = sub_depth - obj_depth gap = sub[3] - obj[3] lo = max(sub[0], obj[0]) hi = min(sub[2], obj[2]) inter = max(0.0, hi - lo) width = min(sub[2] - sub[0], obj[2] - obj[0]) overlap = inter / width if width > 0 else 0.0 return {"dx": dx, "dy": dy, "dz": dz, "gap": gap, "overlap": overlap} def main(): parser = argparse.ArgumentParser() parser.add_argument("--truth", required=True) parser.add_argument("--out", required=True) parser.add_argument("--gdino", default="/repository/models/grounding-dino-tiny") parser.add_argument("--depth", default="/repository/models/depth-anything-v2-small") parser.add_argument("--root", default=".") parser.add_argument("--device", default="cuda:0") parser.add_argument("--limit", type=int, default=0) parser.add_argument("--shard", type=int, default=0) parser.add_argument("--shards", type=int, default=1) args = parser.parse_args() root = Path(args.root) rows = [json.loads(line) for line in Path(args.truth).open(encoding="utf-8")] rows = [r for i, r in enumerate(rows) if i % args.shards == args.shard] if args.limit: rows = rows[: args.limit] det_processor, det_model, depth_processor, depth_model = load_tools(args.gdino, args.depth, args.device) out = Path(args.out) out.parent.mkdir(parents=True, exist_ok=True) with out.open("w", encoding="utf-8") as fh: for index, row in enumerate(rows): base = { "scene_id": row["scene_id"], "state": row["state"], "family": row["family"], "image": row["image"], "truth": row["computed"], "claim": CLAIM_RELATION[row["family"]], } image = Image.open(root / row["image"]).convert("RGB") subject = (row.get("subject_category") or "").strip().lower().replace("_", " ") obj = (row.get("object_category") or "").strip().lower().replace("_", " ") if not subject or not obj: raise RuntimeError(f"missing categories for {row['scene_id']}") boxes = detect(det_processor, det_model, image, [subject, obj], args.device) if subject not in boxes or obj not in boxes: fh.write(json.dumps({**base, "detected": False, "subject_score": boxes.get(subject, {}).get("score"), "object_score": boxes.get(obj, {}).get("score")}, ensure_ascii=False) + "\n") fh.flush() continue depth = depth_map(depth_processor, depth_model, image, args.device) sub_box = boxes[subject]["box"] obj_box = boxes[obj]["box"] sub_depth = box_median_depth(depth, sub_box) obj_depth = box_median_depth(depth, obj_box) fh.write(json.dumps({ **base, "detected": True, "subject_score": boxes[subject]["score"], "object_score": boxes[obj]["score"], "subject_box": sub_box, "object_box": obj_box, "subject_depth": sub_depth, "object_depth": obj_depth, **measurements(sub_box, obj_box, sub_depth, obj_depth), }, ensure_ascii=False) + "\n") fh.flush() if (index + 1) % 50 == 0: print(f"PROGRESS {index + 1}/{len(rows)}", flush=True) print(f"WROTE {out}") if __name__ == "__main__": main()