solveedit_benchmark_2728 / code /src /pvr_eval /agent /region_resolver.py
wenjieshu's picture
Add files using upload-large-folder tool
b8ea052 verified
Raw History Blame Contribute Delete
20.8 kB
"""Resolve typed region proposals into conservative, traceable checker zones."""
from __future__ import annotations
import json
import math
import re
from collections import Counter
from pathlib import Path
from typing import Any, Iterable, Mapping
from PIL import Image
def parse_json(value: Any, default: Any) -> Any:
try:
return json.loads(value or "")
except (TypeError, ValueError):
return default
def parse_bbox(value: Any) -> list[float] | None:
try:
result = [float(item) for item in str(value or "").split(",")]
except (TypeError, ValueError):
return None
if len(result) != 4 or result[2] <= result[0] or result[3] <= result[1]:
return None
return result
def bbox_iou(left: list[float], right: list[float]) -> float:
x0, y0 = max(left[0], right[0]), max(left[1], right[1])
x1, y1 = min(left[2], right[2]), min(left[3], right[3])
inter = max(0.0, x1 - x0) * max(0.0, y1 - y0)
area_left = (left[2] - left[0]) * (left[3] - left[1])
area_right = (right[2] - right[0]) * (right[3] - right[1])
return inter / max(1e-9, area_left + area_right - inter)
def _area(box: list[float]) -> float:
return max(0.0, box[2] - box[0]) * max(0.0, box[3] - box[1])
def _reference_metrics(
box: list[float], reference: list[float], image_size: tuple[int, int] | None
) -> dict[str, float]:
width, height = image_size or (1, 1)
center = ((box[0] + box[2]) / 2, (box[1] + box[3]) / 2)
reference_center = ((reference[0] + reference[2]) / 2, (reference[1] + reference[3]) / 2)
center_distance = math.hypot(center[0] - reference_center[0], center[1] - reference_center[1])
center_distance /= max(1.0, math.hypot(width, height))
area = max(1e-9, (box[2] - box[0]) * (box[3] - box[1]))
reference_area = max(1e-9, (reference[2] - reference[0]) * (reference[3] - reference[1]))
return {
"reference_iou": bbox_iou(box, reference),
"reference_center_distance": center_distance,
"reference_area_ratio": area / reference_area,
}
def _scale_reference_box(
box: list[float],
source_size: tuple[int, int] | None,
target_size: tuple[int, int] | None,
) -> list[float]:
"""Transfer an input ROI by normalized coordinates when sizes differ."""
if not source_size or not target_size or source_size == target_size:
return list(box)
source_width, source_height = source_size
target_width, target_height = target_size
if source_width <= 0 or source_height <= 0:
return list(box)
scale_x = target_width / source_width
scale_y = target_height / source_height
return [box[0] * scale_x, box[1] * scale_y, box[2] * scale_x, box[3] * scale_y]
def _image_size(proposal: Mapping[str, str]) -> tuple[int, int] | None:
role = proposal.get("image_role", "pred")
raw = proposal.get(role, "")
if not raw:
return None
try:
with Image.open(Path(raw)) as image:
return image.size
except Exception:
return None
def _backend_priority(item: Mapping[str, Any]) -> int:
backend = str(item.get("backend", "")).lower()
return 0 if "dino" in backend else 1
def semantic_area_bounds(
region_id: str,
expected_queries: Iterable[str],
*,
minimum: float,
maximum: float,
) -> tuple[float, float]:
"""Apply conservative geometry priors only for unambiguous region types."""
tokens = set(str(region_id).lower().replace("-", "_").split("_"))
query_text = " ".join(str(item).lower() for item in expected_queries)
exclusion_region = bool(tokens.intersection({"allowed", "edit", "exclusion"}))
# A desktop/tabletop surface should occupy a substantial portion of the
# image. Small laptop/paper boxes are a common false grounding for this
# phrase and must become insufficient rather than a false objective ROI.
if "surface" in tokens and any(term in tokens or term in query_text for term in ("desk", "desktop", "tabletop")):
minimum = max(minimum, 0.12)
# Patios/terraces in the current object-zone cases are local horizontal
# scene supports, not aliases for the whole garden or the whole lower
# half of the image. Open-vocabulary detectors commonly return a broad
# ``patio + lawn`` proposal for these nouns. Reject that proposal rather
# than letting SAM refine an already incorrect prompt box.
if not exclusion_region and (
"patio" in tokens or "terrace" in tokens
or "patio" in query_text or "terrace" in query_text
):
minimum = max(minimum, 0.01)
maximum = min(maximum, 0.30)
return minimum, maximum
def semantic_shape_bounds(region_id: str, expected_queries: Iterable[str]) -> tuple[float, float]:
"""Return minimum width coverage and aspect ratio for clear layout surfaces."""
tokens = set(str(region_id).lower().replace("-", "_").split("_"))
query_text = " ".join(str(item).lower() for item in expected_queries)
exclusion_region = bool(tokens.intersection({"allowed", "edit", "exclusion"}))
# Conference tables are often viewed obliquely and land around aspect
# ratio 1.4--1.7; the generic desk prior of 1.8 rejected valid surfaces.
if "surface" in tokens and "conference" in query_text and ("table" in query_text or "tabletop" in query_text):
return 0.60, 1.35
if "surface" in tokens and any(term in tokens or term in query_text for term in ("desk", "desktop", "tabletop")):
return 0.65, 1.8
# A paved patio/terrace is a horizontal support region. Tall edge strips
# and building-side boxes are frequent false proposals for this semantic
# noun and are not safe destination zones.
if not exclusion_region and (
"patio" in tokens or "terrace" in tokens
or "patio" in query_text or "terrace" in query_text
):
return 0.15, 1.05
return 0.0, 0.0
def select_region_candidates(
items: Iterable[dict[str, Any]],
*,
expected_queries: list[str],
threshold: float,
image_size: tuple[int, int] | None,
max_candidates: int,
nms_iou: float,
min_area_fraction: float,
max_area_fraction: float,
min_width_fraction: float = 0.0,
min_aspect_ratio: float = 0.0,
selection_text: str = "",
reference_bbox: list[float] | None = None,
) -> tuple[list[dict[str, Any]], Counter[str]]:
"""Select at most one box per noun query, preferring DINO over fallback detectors."""
accepted: list[dict[str, Any]] = []
rejected: Counter[str] = Counter()
width, height = image_size or (0, 0)
image_area = float(width * height)
for item in items:
if item["score_value"] < threshold:
rejected["below_score"] += 1
continue
box = item["bbox"]
box_width = box[2] - box[0]
box_height = box[3] - box[1]
area_fraction = (box_width * box_height / image_area) if image_area else None
width_fraction = box_width / width if width else None
aspect_ratio = box_width / max(1e-9, box_height)
item["area_fraction"] = area_fraction
item["width_fraction"] = width_fraction
item["aspect_ratio"] = aspect_ratio
if reference_bbox is not None:
item.update(_reference_metrics(box, reference_bbox, image_size))
if area_fraction is not None and area_fraction < min_area_fraction:
rejected["too_small"] += 1
continue
if area_fraction is not None and area_fraction > max_area_fraction:
rejected["too_large"] += 1
continue
if width_fraction is not None and width_fraction < min_width_fraction:
rejected["too_narrow"] += 1
continue
if aspect_ratio < min_aspect_ratio:
rejected["wrong_aspect_ratio"] += 1
continue
generic_surface_queries = {
"cabinet compartment", "cabinet compartments", "compartment", "shelf", "shelves",
"ledge", "window ledge", "support surface", "support surfaces",
}
if area_fraction is not None and str(item.get("query_text", "")).lower() in generic_surface_queries and area_fraction > 0.25:
rejected["generic_surface_too_large"] += 1
continue
accepted.append(item)
query_order = expected_queries or list(dict.fromkeys(str(item.get("query_text", "")) for item in accepted))
best_by_query: list[dict[str, Any]] = []
for query in query_order:
query_items = [item for item in accepted if str(item.get("query_text", "")) == query]
if not query_items:
rejected["query_without_candidate"] += 1
continue
if reference_bbox is not None:
matched = [
item for item in query_items
if float(item.get("reference_iou", 0.0)) >= 0.15
or (
float(item.get("reference_center_distance", 1.0)) <= 0.06
and 0.40 <= float(item.get("reference_area_ratio", 0.0)) <= 2.50
)
]
rejected["reference_mismatch"] += len(query_items) - len(matched)
query_items = matched
if not query_items:
rejected["query_without_reference_match"] += 1
continue
# DINO is the proposal source. YOLO-World remains a fallback/corroborator,
# not a silent replacement merely because its uncalibrated score is higher.
if reference_bbox is not None:
best = min(
query_items,
key=lambda item: (
_backend_priority(item),
-float(item.get("reference_iou", 0.0)),
float(item.get("reference_center_distance", 1.0)),
abs(math.log(max(1e-9, float(item.get("reference_area_ratio", 1.0))))),
-item["score_value"],
),
)
elif re.search(r"\blarge\b", selection_text.lower()):
best = min(
query_items,
key=lambda item: (
_backend_priority(item),
-float(item.get("area_fraction") or 0.0),
-item["score_value"],
),
)
else:
best = min(query_items, key=lambda item: (_backend_priority(item), -item["score_value"]))
supporting = sorted(
{
str(item.get("backend", ""))
for item in query_items
if bbox_iou(best["bbox"], item["bbox"]) >= 0.50 and str(item.get("backend", ""))
}
)
best = {**best, "supporting_backends": supporting}
best_by_query.append(best)
selected: list[dict[str, Any]] = []
for item in best_by_query:
if any(bbox_iou(item["bbox"], kept["bbox"]) >= nms_iou for kept in selected):
rejected["semantic_nms"] += 1
continue
selected.append(item)
if len(selected) >= max_candidates:
rejected["max_candidates"] += max(0, len(best_by_query) - len(selected))
break
if len(query_order) <= 1:
selected = selected[:1]
return selected, rejected
def materialize_region_rows(
tool_calls: Iterable[dict[str, str]],
detection_rows: Iterable[dict[str, str]],
*,
default_min_score: float = 0.10,
) -> list[dict[str, Any]]:
proposals: dict[str, dict[str, str]] = {}
resolvers: list[dict[str, str]] = []
for row in tool_calls:
params = parse_json(row.get("params", "{}"), {})
if row.get("tool") == "open_vocabulary_detector" and params.get("purpose") == "region_proposal":
proposals[row["call_id"]] = row
elif row.get("tool") == "region_resolver":
resolvers.append(row)
candidates: dict[str, list[dict[str, Any]]] = {call_id: [] for call_id in proposals}
for row in detection_rows:
call_id = row.get("call_id", "")
box = parse_bbox(row.get("bbox_xyxy", ""))
if call_id not in proposals or box is None or row.get("status") != "ok":
continue
try:
score = float(row.get("score", "0") or 0)
except ValueError:
score = 0.0
candidates[call_id].append({**row, "bbox": box, "score_value": score})
output: list[dict[str, Any]] = []
reference_boxes: dict[
tuple[str, str, str], tuple[list[float], tuple[int, int] | None]
] = {}
for resolver in sorted(
resolvers,
key=lambda row: (
row.get("case_key", ""),
row.get("check_ids", ""),
0 if row.get("image_role") == "input" else 1,
row["call_id"],
),
):
params = parse_json(resolver.get("params", "{}"), {})
region_ids = parse_json(resolver.get("region_ids", "[]"), [])
dependencies = parse_json(resolver.get("depends_on", "[]"), [])
threshold = float(params.get("min_score", default_min_score))
for region_id in region_ids:
proposal_ids = [
call_id for call_id in dependencies
if call_id in proposals and region_id in parse_json(proposals[call_id].get("region_ids", "[]"), [])
]
proposal = proposals.get(proposal_ids[0], {}) if proposal_ids else {}
expected_queries = [str(item) for item in parse_json(proposal.get("queries", "[]"), [])]
items = [item for call_id in proposal_ids for item in candidates.get(call_id, [])]
min_area_fraction, max_area_fraction = semantic_area_bounds(
region_id,
expected_queries,
minimum=float(params.get("min_area_fraction", 0.0005)),
maximum=float(params.get("max_area_fraction", 0.90)),
)
min_width_fraction, min_aspect_ratio = semantic_shape_bounds(region_id, expected_queries)
region_spec = next(
(item for item in params.get("regions", []) if isinstance(item, dict) and item.get("region_id") == region_id),
{},
)
reference_key = (resolver.get("case_key", ""), resolver.get("check_ids", ""), region_id)
image_roles = set(region_spec.get("image_roles", []))
stable_pair = (
params.get("cross_role_policy") == "stable_input_reference"
and {"input", "pred"}.issubset(image_roles)
)
reference = reference_boxes.get(reference_key) if resolver.get("image_role") == "pred" and stable_pair else None
proposal_image_size = _image_size(proposal)
reference_bbox = (
_scale_reference_box(reference[0], reference[1], proposal_image_size)
if reference is not None
else None
)
selected, rejected = select_region_candidates(
items,
expected_queries=expected_queries,
threshold=threshold,
image_size=proposal_image_size,
max_candidates=max(1, int(params.get("max_candidates", 6))),
nms_iou=float(params.get("nms_iou", 0.70)),
min_area_fraction=min_area_fraction,
max_area_fraction=max_area_fraction,
min_width_fraction=min_width_fraction,
min_aspect_ratio=min_aspect_ratio,
selection_text=str(region_spec.get("query_or_rule", "")),
reference_bbox=reference_bbox,
)
if resolver.get("image_role") == "input" and stable_pair and selected:
reference_boxes[reference_key] = (selected[0]["bbox"], proposal_image_size)
transferred_reference = False
if (
resolver.get("image_role") == "pred"
and stable_pair
and reference_bbox is not None
and not selected
):
width, height = proposal_image_size or (0, 0)
image_area = float(width * height)
selected = [{
"bbox": reference_bbox,
"score_value": 0.0,
"query_text": expected_queries[0] if expected_queries else "",
"label": "stable input reference ROI",
"backend": "stable_input_reference",
"supporting_backends": [],
"area_fraction": _area(reference_bbox) / image_area if image_area else None,
"width_fraction": (reference_bbox[2] - reference_bbox[0]) / width if width else None,
"aspect_ratio": (reference_bbox[2] - reference_bbox[0]) / max(1e-9, reference_bbox[3] - reference_bbox[1]),
"reference_iou": 1.0,
"reference_center_distance": 0.0,
"reference_area_ratio": 1.0,
}]
transferred_reference = True
evidence = {
"proposal_method": region_spec.get("proposal_method", ""),
"proposal_call_ids": proposal_ids,
"expected_queries": expected_queries,
"selection_policy": params.get("selection_policy", "dino_first_top1_per_query"),
"cross_role_policy": params.get("cross_role_policy", "independent"),
"reference_bbox": reference_bbox,
"reference_transfer": {
"applied": transferred_reference,
"method": "normalized_input_roi_transfer" if transferred_reference else "none",
"detector_substitution": False,
},
"min_score": threshold,
"min_area_fraction": min_area_fraction,
"max_area_fraction": max_area_fraction,
"min_width_fraction": min_width_fraction,
"min_aspect_ratio": min_aspect_ratio,
"rejected": dict(rejected),
"selected": [
{
"backend": item.get("backend", ""),
"supporting_backends": item.get("supporting_backends", []),
"label": item.get("label", ""),
"query_text": item.get("query_text", ""),
"score": item["score_value"],
"bbox_xyxy": item["bbox"],
"area_fraction": item.get("area_fraction"),
"width_fraction": item.get("width_fraction"),
"aspect_ratio": item.get("aspect_ratio"),
"reference_iou": item.get("reference_iou"),
"reference_center_distance": item.get("reference_center_distance"),
"reference_area_ratio": item.get("reference_area_ratio"),
}
for item in selected
],
}
emitted = selected or [None]
parent_region_id = str(
region_spec.get("parent_materialized_region_id") or region_id
)
for index, best in enumerate(emitted):
output.append(
{
"case_key": resolver.get("case_key", ""),
"check_id": (resolver.get("check_ids", "").split("|") or [""])[0],
"check_ids": resolver.get("check_ids", ""),
"call_id": resolver["call_id"],
"proposal_call_id": proposal_ids[0] if proposal_ids else "",
"parent_region_id": parent_region_id,
"region_id": region_id if index == 0 else f"{region_id}__{index + 1:02d}",
"selection_rank": index + 1 if best else "",
"image_role": resolver.get("image_role", "pred"),
"status": "ok" if best else "insufficient",
"query_text": (best or {}).get("query_text", ""),
"bbox_xyxy": "" if best is None else ",".join(str(value) for value in best["bbox"]),
"score": "" if best is None else f"{best['score_value']:.6f}",
"backend": (best or {}).get("backend", ""),
"supporting_backends": "|".join((best or {}).get("supporting_backends", [])),
"area_fraction": "" if best is None or best.get("area_fraction") is None else f"{best['area_fraction']:.8f}",
"candidate_count": len(items),
"evidence_json": json.dumps(evidence, ensure_ascii=False, separators=(",", ":")),
}
)
return output