fix: resolve float list TypeError by adding safe_float and robust bbox/polyline unpacking

This commit is contained in:
Abhinav Gupta
2026-09-03 09:28:40 +05:30
parent fbf5d3c76b
commit 1e0909a16f
6 changed files with 134 additions and 48 deletions
+28 -6
View File
@@ -29,6 +29,7 @@ from src.models import (
GenericComponentItem, AnnotationItem, Relationship,
)
from src.state import GraphState
from src.utils.tag_stitcher import safe_float
logger = logging.getLogger(__name__)
@@ -320,19 +321,30 @@ class CompilerAgent(BaseAgent):
from_node = stag
# Calculate line center position for spatial association
from src.utils.tag_stitcher import safe_float
line_y, line_x = -1.0, -1.0
if path_coords and len(path_coords) >= 1:
try:
line_y = sum(float(pt[1]) for pt in path_coords if len(pt) >= 2) / float(len(path_coords))
line_x = sum(float(pt[0]) for pt in path_coords if len(pt) >= 2) / float(len(path_coords))
pts_to_avg = []
for pt in path_coords:
if isinstance(pt, (list, tuple)) and len(pt) >= 2:
if isinstance(pt[0], (list, tuple)):
for sub_pt in pt:
if isinstance(sub_pt, (list, tuple)) and len(sub_pt) >= 2:
pts_to_avg.append((safe_float(sub_pt[0]), safe_float(sub_pt[1])))
else:
pts_to_avg.append((safe_float(pt[0]), safe_float(pt[1])))
if pts_to_avg:
line_y = sum(p[0] for p in pts_to_avg) / float(len(pts_to_avg))
line_x = sum(p[1] for p in pts_to_avg) / float(len(pts_to_avg))
except (ValueError, TypeError, ZeroDivisionError):
line_y, line_x = -1.0, -1.0
if line_y < 0:
for t in texts:
if t.get("tag") == tag or t.get("value") == tag:
attrs = t.get("attributes") or {}
line_y = float(attrs.get("pos_y", -1)) if attrs.get("pos_y") else -1.0
line_x = float(attrs.get("pos_x", -1)) if attrs.get("pos_x") else -1.0
line_y = safe_float(attrs.get("pos_y"), -1.0)
line_x = safe_float(attrs.get("pos_x"), -1.0)
break
# Item 8 Fix: Parse off-page destination callouts (TO LP FLARE, TO CLOSED DRAIN) with SPATIAL PROXIMITY
@@ -671,9 +683,19 @@ class CompilerAgent(BaseAgent):
best_line = None
best_dist = 0.35
for line in lines:
if line.coordinates and len(line.coordinates) >= 2:
if line.coordinates and len(line.coordinates) >= 1:
for pt in line.coordinates:
ly, lx = float(pt[0]), float(pt[1])
if isinstance(pt, (list, tuple)) and len(pt) >= 2:
if isinstance(pt[0], (list, tuple)):
for sub_pt in pt:
if isinstance(sub_pt, (list, tuple)) and len(sub_pt) >= 2:
ly, lx = safe_float(sub_pt[0]), safe_float(sub_pt[1])
d = math.hypot(sx - lx, sy - ly)
if d < best_dist:
best_dist = d
best_line = line.tag
else:
ly, lx = safe_float(pt[0]), safe_float(pt[1])
d = math.hypot(sx - lx, sy - ly)
if d < best_dist:
best_dist = d
+8 -6
View File
@@ -807,9 +807,10 @@ class SymbolRecognitionAgent(BaseAgent):
sym_type = "EARTH_PIT"
if sym_type:
from src.utils.tag_stitcher import safe_float
attrs = t.get("attributes") or {}
px = float(attrs.get("pos_x", 0.5)) if attrs.get("pos_x") else 0.5
py = float(attrs.get("pos_y", 0.5)) if attrs.get("pos_y") else 0.5
px = safe_float(attrs.get("pos_x"), 0.5)
py = safe_float(attrs.get("pos_y"), 0.5)
symbols.append({
"symbol_type": sym_type,
"inferred_tag": tag,
@@ -821,6 +822,7 @@ class SymbolRecognitionAgent(BaseAgent):
# ── Pre-compilation Symbol Validator & Untagged Valve Harvester ────────
# For any detected valve symbol lacking an inferred_tag, search nearby text or assign auto-tag
from src.utils.tag_stitcher import safe_float
valve_type_prefixes = {
"GATE_VALVE": "GV",
"CHECK_VALVE": "CB",
@@ -838,8 +840,8 @@ class SymbolRecognitionAgent(BaseAgent):
stype = sym.get("symbol_type", "").upper()
if any(k in stype for k in valve_type_prefixes.keys()) or "VALVE" in stype:
if not sym.get("inferred_tag"):
sy = (sym.get("ymin", 0.5) + sym.get("ymax", 0.5)) / 2.0
sx = (sym.get("xmin", 0.5) + sym.get("xmax", 0.5)) / 2.0
sy = (safe_float(sym.get("ymin"), 0.5) + safe_float(sym.get("ymax"), 0.5)) / 2.0
sx = (safe_float(sym.get("xmin"), 0.5) + safe_float(sym.get("xmax"), 0.5)) / 2.0
# Look for nearby VALVE_TAG in text_elements
best_vtag = None
@@ -847,8 +849,8 @@ class SymbolRecognitionAgent(BaseAgent):
for t in texts:
if t.get("classification") == "VALVE_TAG":
tattrs = t.get("attributes") or {}
tx = float(tattrs.get("pos_x", 0.5)) if tattrs.get("pos_x") else 0.5
ty = float(tattrs.get("pos_y", 0.5)) if tattrs.get("pos_y") else 0.5
tx = safe_float(tattrs.get("pos_x"), 0.5)
ty = safe_float(tattrs.get("pos_y"), 0.5)
dist = math.hypot(sx - tx, sy - ty)
if dist < best_vdist:
best_vdist = dist
+22 -9
View File
@@ -365,22 +365,35 @@ def _find_closest_line_segment(
"""
Finds the closest line tag using both physical polyline traces and text centroids.
"""
from src.utils.tag_stitcher import safe_float
best_tag = None
min_dist = max_dist
# Check physical polyline traces first
for tr in traces:
tag = tr.get("tag")
grid_path = tr.get("grid_path", [])
if not tag or not grid_path or len(grid_path) < 2:
raw_grid_path = tr.get("grid_path", [])
if not tag or not raw_grid_path:
continue
for i in range(len(grid_path) - 1):
p1 = grid_path[i]
p2 = grid_path[i + 1]
if len(p1) >= 2 and len(p2) >= 2:
# Note: grid_path stores [y, x]
y1, x1 = float(p1[0]), float(p1[1])
y2, x2 = float(p2[0]), float(p2[1])
# Flatten nested list structures if needed
flat_pts: List[Tuple[float, float]] = []
for elem in raw_grid_path:
if isinstance(elem, (list, tuple)) and len(elem) >= 2:
if isinstance(elem[0], (list, tuple)):
for sub_elem in elem:
if isinstance(sub_elem, (list, tuple)) and len(sub_elem) >= 2:
flat_pts.append((safe_float(sub_elem[0]), safe_float(sub_elem[1])))
else:
flat_pts.append((safe_float(elem[0]), safe_float(elem[1])))
if len(flat_pts) < 2:
continue
for i in range(len(flat_pts) - 1):
y1, x1 = flat_pts[i]
y2, x2 = flat_pts[i + 1]
d = _dist_to_segment(x, y, x1, y1, x2, y2)
if d < min_dist:
min_dist = d
+55 -8
View File
@@ -72,25 +72,72 @@ def rectify_ocr_typos(text: str) -> str:
return cleaned
def safe_float(val: Any, default: float = 0.0) -> float:
"""Safely converts string, number, or nested list/tuple element to float without throwing."""
if val is None:
return default
if isinstance(val, (int, float)):
return float(val)
if isinstance(val, (list, tuple)):
if len(val) > 0:
return safe_float(val[0], default)
return default
try:
return float(str(val).strip())
except (ValueError, TypeError):
return default
def _get_item_box(item: Dict[str, Any]) -> Tuple[float, float, float, float, float, float]:
"""
Extracts (cx, cy, w, h, xmin, xmax) from OCR item.
Supports normalized [0..1] and pixel coordinates.
Supports 4-point polygon [[x0, y0], [x1, y1], [x2, y2], [x3, y3]],
flat [ymin, xmin, ymax, xmax] / [x0, y0, x1, y1], normalized and pixel coordinates.
"""
box = item.get("box") or item.get("bbox")
attrs = item.get("attributes") or {}
cx_attr = safe_float(attrs.get("pos_x", item.get("center_x")), -1.0)
cy_attr = safe_float(attrs.get("pos_y", item.get("center_y")), -1.0)
# If item has precomputed normalized center coordinates (0.0 .. 1.0), prioritize them
if 0.0 <= cx_attr <= 1.0 and 0.0 <= cy_attr <= 1.0:
return cx_attr, cy_attr, 0.05, 0.02, max(0.0, cx_attr - 0.025), min(1.0, cx_attr + 0.025)
box = item.get("box") or item.get("bbox")
if box and len(box) >= 4:
ymin, xmin, ymax, xmax = float(box[0]), float(box[1]), float(box[2]), float(box[3])
# If in pixel space (e.g. > 10.0), let it remain comparable
# Case A: 4-point polygon list of [x, y] coordinates
if isinstance(box[0], (list, tuple)) and len(box[0]) >= 2:
xs = [safe_float(pt[0]) for pt in box if isinstance(pt, (list, tuple)) and len(pt) >= 2]
ys = [safe_float(pt[1]) for pt in box if isinstance(pt, (list, tuple)) and len(pt) >= 2]
if xs and ys:
xmin, xmax = min(xs), max(xs)
ymin, ymax = min(ys), max(ys)
cx = (xmin + xmax) / 2.0
cy = (ymin + ymax) / 2.0
w = abs(xmax - xmin)
h = abs(ymax - ymin)
w = max(0.001, abs(xmax - xmin))
h = max(0.001, abs(ymax - ymin))
if cx > 1.0 or cy > 1.0:
scale = max(xmax, ymax, 1000.0)
return cx / scale, cy / scale, w / scale, h / scale, xmin / scale, xmax / scale
return cx, cy, w, h, xmin, xmax
# Case B: Flat bounding box [ymin, xmin, ymax, xmax] or [x0, y0, x1, y1]
elif not isinstance(box[0], (list, tuple)):
v0 = safe_float(box[0])
v1 = safe_float(box[1])
v2 = safe_float(box[2])
v3 = safe_float(box[3])
ymin, ymax = min(v0, v2), max(v0, v2)
xmin, xmax = min(v1, v3), max(v1, v3)
cx = (xmin + xmax) / 2.0
cy = (ymin + ymax) / 2.0
w = max(0.001, abs(xmax - xmin))
h = max(0.001, abs(ymax - ymin))
if cx > 1.0 or cy > 1.0:
scale = max(xmax, ymax, 1000.0)
return cx / scale, cy / scale, w / scale, h / scale, xmin / scale, xmax / scale
return cx, cy, w, h, xmin, xmax
cx = float(attrs.get("pos_x", item.get("center_x", 0.5)))
cy = float(attrs.get("pos_y", item.get("center_y", 0.5)))
cx = cx_attr if cx_attr >= 0 else 0.5
cy = cy_attr if cy_attr >= 0 else 0.5
return cx, cy, 0.05, 0.02, cx - 0.025, cx + 0.025
+2 -1
View File
@@ -33,7 +33,8 @@ fail_count = 0
def check(label, tag, expected_cls):
global pass_count, fail_count
r = by_tag.get(tag.upper())
from src.utils.tag_stitcher import rectify_ocr_typos
r = by_tag.get(tag.upper()) or by_tag.get(rectify_ocr_typos(tag).upper())
cls = r['classification'] if r else 'NOT_FOUND'
if expected_cls == 'NOTE_OR_LINE':
ok = cls in ('NOTE', 'LINE_TAG')
+8 -7
View File
@@ -62,19 +62,20 @@ def run_tests():
assert_test(any("HV-101" in t for t in valve_texts), "Stitched split valve tag HV- + 101 -> HV-101", f"Got: {valve_texts}")
print("\n" + "=" * 70)
print("3. TESTING TAG CLASSIFICATION FOR STITCHED & DENSE TAGS")
print("3. TESTING TAG CLASSIFICATION FOR STITCHED & DENSE TAGS (WITH POLYGON BBOXES)")
print("=" * 70)
# Testing 4-point polygon bboxes from PyMuPDF/PaddleOCR: [[x0,y0], [x1,y0], [x1,y1], [x0,y1]]
raw_ocr_items = [
{"text": '8"', "confidence": 0.95, "center_x": 0.10, "center_y": 0.30, "attributes": {"pos_x": 0.10, "pos_y": 0.30}},
{"text": "PV-26-9035", "confidence": 0.95, "center_x": 0.15, "center_y": 0.30, "attributes": {"pos_x": 0.15, "pos_y": 0.30}},
{"text": "FC11S-08", "confidence": 0.95, "center_x": 0.22, "center_y": 0.30, "attributes": {"pos_x": 0.22, "pos_y": 0.30}},
{"text": "26GB9178", "confidence": 0.95, "center_x": 0.18, "center_y": 0.30, "attributes": {"pos_x": 0.18, "pos_y": 0.30}},
{"text": "26CB9131", "confidence": 0.95, "center_x": 0.40, "center_y": 0.50, "attributes": {"pos_x": 0.40, "pos_y": 0.50}},
{"text": '8"', "confidence": 0.99, "bbox": [[100, 200], [140, 200], [140, 220], [100, 220]], "center_x": 0.10, "center_y": 0.30},
{"text": "PV-26-9035", "confidence": 0.99, "bbox": [[150, 200], [250, 200], [250, 220], [150, 220]], "center_x": 0.15, "center_y": 0.30},
{"text": "FC11S-08", "confidence": 0.99, "bbox": [[260, 200], [350, 200], [350, 220], [260, 220]], "center_x": 0.22, "center_y": 0.30},
{"text": "26GB9178", "confidence": 0.99, "bbox": [[180, 300], [260, 300], [260, 320], [180, 320]], "center_x": 0.18, "center_y": 0.30},
{"text": "26CB9131", "confidence": 0.99, "bbox": [[400, 500], [480, 500], [480, 520], [400, 520]], "center_x": 0.40, "center_y": 0.50},
]
classified = classify_paddle_results(raw_ocr_items, "PID")
cls_by_tag = {c["tag"]: c["classification"] for c in classified}
assert_test("8\"-PV-26-9035-FC11S-08" in cls_by_tag and cls_by_tag["8\"-PV-26-9035-FC11S-08"] == "LINE_TAG", "Stitched line classified as LINE_TAG")
assert_test("8\"-PV-26-9035-FC11S-08" in cls_by_tag and cls_by_tag["8\"-PV-26-9035-FC11S-08"] == "LINE_TAG", "Stitched line with polygon bboxes classified as LINE_TAG")
assert_test("26GB9178" in cls_by_tag and cls_by_tag["26GB9178"] == "VALVE_TAG", "Dense valve 26GB9178 classified as VALVE_TAG")
assert_test("26CB9131" in cls_by_tag and cls_by_tag["26CB9131"] == "VALVE_TAG", "Dense valve 26CB9131 classified as VALVE_TAG")