fix(pipeline): complete Round 4 repair pass - restore instrument recall, fix spatial line callouts, enable equipment datasheets & twin PSVs

This commit is contained in:
Abhinav Gupta
2026-08-13 10:51:05 +05:30
parent 6c89ab9fb7
commit 7c40c311c5
7 changed files with 195 additions and 40 deletions
+51 -8
View File
@@ -221,7 +221,14 @@ class CompilerAgent(BaseAgent):
# ── Defect 5 Fix: populate datasheet fields from injected attributes ──
attrs = eq.get("attributes") or {}
aliases = eq.get("aliases") or []
confidence = float(eq.get("confidence", 1.0))
# Calculate dynamic completeness-based confidence
datasheet_keys = ["design_pressure", "design_temperature", "flow_rate", "duty", "material", "vendor", "quantity"]
populated_count = sum(1 for k in datasheet_keys if attrs.get(k))
if populated_count > 0:
confidence = round(0.60 + 0.40 * (populated_count / 7.0), 2)
else:
confidence = 0.60
item_obj = EquipmentItem(
tag=tag,
@@ -312,26 +319,62 @@ class CompilerAgent(BaseAgent):
elif ttag == tag:
from_node = stag
# Item 8 Fix: Parse off-page destination callouts (TO LP FLARE, TO CLOSED DRAIN)
# Calculate line center position for spatial association
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))
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
break
# Item 8 Fix: Parse off-page destination callouts (TO LP FLARE, TO CLOSED DRAIN) with SPATIAL PROXIMITY
if not to_node:
best_to_dest = None
best_to_dist = 0.15
for t in texts:
val = t.get("value") or ""
m_to = re.search(r'\bTO\s+([A-Z0-9\s-]+(?:FLARE|DRAIN|HEADER|UNIT|SYSTEM|ATMOSPHERE)?)\b', val, re.I)
if m_to:
dest = m_to.group(1).strip()
if len(dest) >= 3 and dest.upper() not in ("BE", "THE", "SUCTION"):
to_node = f"{dest} (off-page)"
break
if len(dest) >= 3 and dest.upper() not in ("BE", "THE", "SUCTION", "A", "AN"):
attrs = t.get("attributes") or {}
t_y = float(attrs.get("pos_y", -1)) if attrs.get("pos_y") else -1.0
t_x = float(attrs.get("pos_x", -1)) if attrs.get("pos_x") else -1.0
if line_y >= 0 and line_x >= 0 and t_y >= 0 and t_x >= 0:
dist = ((line_y - t_y) ** 2 + (line_x - t_x) ** 2) ** 0.5
if dist < best_to_dist:
best_to_dist = dist
best_to_dest = dest
if best_to_dest:
to_node = f"{best_to_dest} (off-page)"
if not from_node:
best_from_src = None
best_from_dist = 0.15
for t in texts:
val = t.get("value") or ""
m_from = re.search(r'\bFROM\s+([A-Z0-9\s-]+(?:FLARE|DRAIN|HEADER|UNIT|SYSTEM|VESSEL)?)\b', val, re.I)
if m_from:
src_callout = m_from.group(1).strip()
if len(src_callout) >= 3:
from_node = f"{src_callout} (off-page)"
break
if len(src_callout) >= 3 and src_callout.upper() not in ("BE", "THE", "SUCTION", "A", "AN"):
attrs = t.get("attributes") or {}
t_y = float(attrs.get("pos_y", -1)) if attrs.get("pos_y") else -1.0
t_x = float(attrs.get("pos_x", -1)) if attrs.get("pos_x") else -1.0
if line_y >= 0 and line_x >= 0 and t_y >= 0 and t_x >= 0:
dist = ((line_y - t_y) ** 2 + (line_x - t_x) ** 2) ** 0.5
if dist < best_from_dist:
best_from_dist = dist
best_from_src = src_callout
if best_from_src:
from_node = f"{best_from_src} (off-page)"
compiled.append(LineItem(
tag=tag,
+50 -13
View File
@@ -285,8 +285,12 @@ def _inject_datasheet_attributes(
pos_items = []
for item in structured:
attrs = item.get('attributes') or {}
cy = float(attrs.get('pos_y', -1)) if attrs.get('pos_y') else -1
cx = float(attrs.get('pos_x', -1)) if attrs.get('pos_x') else -1
cy = float(attrs.get('pos_y', -1)) if attrs.get('pos_y') else -1.0
cx = float(attrs.get('pos_x', -1)) if attrs.get('pos_x') else -1.0
if cy > 1.0:
cy = cy / 2338.0
if cx > 1.0:
cx = cx / 3300.0
pos_items.append({**item, 'center_y': cy, 'center_x': cx})
# Also add raw OCR items as position context (they have bbox/center coordinates)
@@ -297,6 +301,10 @@ def _inject_datasheet_attributes(
try:
cy = float(cy)
cx = float(cx)
if cy > 1.0:
cy = cy / 2338.0
if cx > 1.0:
cx = cx / 3300.0
except (ValueError, TypeError):
cy, cx = 0.5, 0.5
else:
@@ -310,6 +318,10 @@ def _inject_datasheet_attributes(
elif isinstance(box[0], (int, float)):
cy = (float(box[0]) + float(box[2])) / 2.0
cx = (float(box[1]) + float(box[3])) / 2.0
if cy > 1.0:
cy = cy / 2338.0
if cx > 1.0:
cx = cx / 3300.0
except (ValueError, TypeError, IndexError):
cy, cx = 0.5, 0.5
pos_items.append({
@@ -326,28 +338,53 @@ def _inject_datasheet_attributes(
psv_sp_map = parse_psv_set_pressures(pos_items)
psv_flange_map = parse_psv_flange_specs(pos_items)
from src.utils.tag_classifier import canonicalize_tag
# Inject into structured results
injected_count = 0
for item in structured:
tag = item.get('tag') or ''
cls = item.get('classification') or ''
if cls == 'EQUIPMENT_TAG' and tag in datasheet_map:
if cls == 'EQUIPMENT_TAG':
attrs = dict(item.get('attributes') or {})
fields = datasheet_map[tag]
for field, value in fields.items():
if field not in attrs or not attrs[field]:
attrs[field] = value
injected_count += 1
item['attributes'] = attrs
c_tag = canonicalize_tag(tag)
fields = datasheet_map.get(tag) or datasheet_map.get(tag.upper()) or datasheet_map.get(c_tag)
if not fields:
for k, v in datasheet_map.items():
if canonicalize_tag(k) == c_tag:
fields = v
break
if fields:
for field, value in fields.items():
if field not in attrs or not attrs[field]:
attrs[field] = value
injected_count += 1
item['attributes'] = attrs
elif cls == 'PSV_TAG':
attrs = dict(item.get('attributes') or {})
if tag in psv_sp_map and not attrs.get('set_pressure'):
attrs['set_pressure'] = psv_sp_map[tag]
c_tag = canonicalize_tag(tag)
base_key = re.sub(r'[A-Z]$', '', c_tag)
sp_val = psv_sp_map.get(tag) or psv_sp_map.get(c_tag)
if not sp_val:
for k, v in psv_sp_map.items():
if re.sub(r'[A-Z]$', '', canonicalize_tag(k)) == base_key:
sp_val = v
break
if sp_val and not attrs.get('set_pressure'):
attrs['set_pressure'] = sp_val
injected_count += 1
if tag in psv_flange_map:
for k, v in psv_flange_map[tag].items():
flange_val = psv_flange_map.get(tag) or psv_flange_map.get(c_tag)
if not flange_val:
for k, v in psv_flange_map.items():
if re.sub(r'[A-Z]$', '', canonicalize_tag(k)) == base_key:
flange_val = v
break
if flange_val:
for k, v in flange_val.items():
if k not in attrs or not attrs[k]:
attrs[k] = v
injected_count += 1
+8 -17
View File
@@ -563,17 +563,6 @@ def classify_paddle_results(
if full_tag in found and found[full_tag]['classification'] != 'NOTE':
continue
# Defect 3 Fix: Check setpoint context before emitting instrument tags
if code in _INSTRUMENT_CODES or (len(seq) >= 4 and code not in _EQUIPMENT_CODES):
if _is_setpoint_context_spatial(item_idx, items) or _is_setpoint_context(t, m.start(), m.end()):
found[full_tag] = _make_item(
full_tag, 'NOTE', 0.15, item,
flag_reason='ambiguous_setpoint_vs_tag'
)
item_added = True
logger.debug(f"Setpoint guard: demoted '{full_tag}' to NOTE")
continue
_VALVE_FUNCTION_CODES = {'CB', 'GB', 'BL', 'GT', 'BT', 'GL', 'NV'}
if code in _VALVE_FUNCTION_CODES and len(re.sub(r'\D', '', seq)) >= 4:
cat = 'VALVE_TAG'
@@ -590,22 +579,24 @@ def classify_paddle_results(
found[full_tag] = _make_item(full_tag, cat, conf, item)
item_added = True
# Bare instrument tags — Defect 3: setpoint negative-context guard
# Bare instrument tags — Defect 3: setpoint negative-context guard for 3-digit setpoints
for m in _BARE_INSTRUMENT_SEARCH.finditer(t):
tag = m.group(1).upper()
if tag in found:
continue
if _is_setpoint_context_spatial(item_idx, items) or _is_setpoint_context(t, m.start(), m.end()):
# Matches setpoint-like context — demote to NOTE with flag
seq_num = re.sub(r'\D', '', tag)
is_3digit_setpoint = len(seq_num) == 3
if is_3digit_setpoint and (_is_setpoint_context_spatial(item_idx, items) or _is_setpoint_context(t, m.start(), m.end())):
# 3-digit candidate matches setpoint context (e.g. PI-150 in SD HH: 150) — demote to NOTE
found[tag] = _make_item(
tag, 'NOTE', 0.15, item,
flag_reason='ambiguous_setpoint_vs_tag'
)
logger.debug(f"Setpoint guard: demoted bare '{tag}' to NOTE")
logger.debug(f"Setpoint guard: demoted bare setpoint '{tag}' to NOTE")
else:
# Real bare instrument tag (e.g. TIT-9025, PIT-9016)
found[tag] = _make_item(
tag, 'INSTRUMENT_TAG', min(conf, 0.60), item,
flag_reason='unverified_bare_instrument_tag'
tag, 'INSTRUMENT_TAG', min(conf, 0.85), item
)
item_added = True