feat: implement 3-agent audit recommendations: anti-hallucination line filter, sink flow directionality, split sibling instruments, suction strainer detection, and decimal point restoration

This commit is contained in:
Abhinav Gupta
2026-09-03 10:39:39 +05:30
parent 9161fcbbf2
commit 5589261c11
5 changed files with 164 additions and 7 deletions
+32 -5
View File
@@ -262,8 +262,21 @@ class CompilerAgent(BaseAgent):
compiled = []
line_tags = [t for t in texts if t["classification"] == "LINE_TAG"]
# Anti-hallucination & Schema Validation Tokens
INVALID_LINE_TOKENS = {
'NOTE', 'TIT', 'PIT', 'LIT', 'FIT', 'PDI', 'PDT', 'PT', 'TT', 'FT', 'LT',
'REV', 'DWG', 'SHT', 'DETAIL', 'TYP', 'EL', 'M01', 'M02', 'M03', 'MOTOR'
}
for lt in line_tags:
tag = lt["tag"]
# ── Pre-Export Schema Validator & Anti-Hallucination Filter ────────
# 1. Reject motor tags or electrical cable circuits (e.g., 26-KA-902-M01, TT-26-9711-AS20-00)
tag_upper = tag.upper()
if re.search(r'-(?:M\d{2}|C0\d)$', tag_upper) or tag_upper.startswith(('TT-', 'PT-', 'LT-', 'FT-', 'TIT-', 'PIT-', 'LIT-', 'FIT-')):
continue
# Intelligently split tag and detect whether size prefix is present
parts = [p.strip() for p in tag.split('-') if p.strip()]
@@ -306,6 +319,14 @@ class CompilerAgent(BaseAgent):
spec = rem[3]
insulation = rem[4]
# 2. Reject if service or spec was force-fitted with descriptive/note tokens (e.g. ...-NOTE, ...-TIT)
if service.upper() in INVALID_LINE_TOKENS or spec.upper() in INVALID_LINE_TOKENS:
continue
# 3. Reject if service code is not a clean alphabetic fluid/system descriptor
if not re.match(r'^[A-Z]{1,4}$', service.upper()):
continue
path_coords = None
for trace in geom.get("traces", []):
if trace["tag"] == tag:
@@ -783,16 +804,22 @@ class CompilerAgent(BaseAgent):
or "N/A"
)
# Auto-detect relief destination from notes/service callout (e.g. FLARE / CLOSED DRAIN)
# Auto-detect relief destination from notes/service callout (e.g. HP FLARE vs LP FLARE)
destination = attrs.get("relief_destination")
if not destination:
for t in texts:
val = t.get("value", "")
if "FLARE" in val.upper() or "DRAIN" in val.upper():
destination = val.strip()
val = t.get("value", "").upper()
if "HP FLARE" in val or "HP-FLARE" in val or "HIGH PRESSURE FLARE" in val:
destination = "HP Flare Header"
break
elif "LP FLARE" in val or "LP-FLARE" in val or "LOW PRESSURE FLARE" in val:
destination = "LP Flare Header"
break
elif "CLOSED DRAIN" in val or "DRAIN" in val:
destination = "Closed Drain Header"
break
if not destination:
destination = "LP Flare Header"
destination = "HP Flare Header"
compiled.append(SafetyReliefValveItem(
tag=tag,
+48
View File
@@ -333,6 +333,9 @@ def trace_lines_and_connections(
"rel_type": "EARTHED_TO"
})
# ── Engineering Flow Directionality & Sink Constraint Enforcement ─────────
relations = _enforce_engineering_directionality(relations)
logger.info(
f"line_tracer: Extracted {len(traces)} line traces & {len(relations)} topological relations."
)
@@ -346,6 +349,51 @@ def trace_lines_and_connections(
}
def _enforce_engineering_directionality(relations: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""
Enforces process engineering topological constraints:
1. Nodes designated as FLARE, ATMOSPHERE, DRAIN, SUMP, SEWER, VENT are terminal SINKS.
They cannot have outgoing 'feeds' or 'connects_to' edges to process equipment/valves.
2. Inverts inverted edges (e.g., 'LP FLARE feeds 26-CK-921' -> '26-CK-921 relieves_to LP FLARE').
"""
SINKS = (
'FLARE', 'HP FLARE', 'LP FLARE', 'HP_FLARE', 'LP_FLARE',
'DRAIN', 'CLOSED DRAIN', 'OPEN DRAIN', 'CLOSED_DRAIN', 'OPEN_DRAIN',
'ATMOSPHERE', 'SUMP', 'SEWER', 'VENT', 'SCRAP'
)
corrected = []
seen = set()
for r in relations:
src = str(r.get("source_tag", "")).strip()
tgt = str(r.get("target_tag", "")).strip()
rtype = str(r.get("rel_type", "CONNECTS_TO")).upper()
src_upper = src.upper()
tgt_upper = tgt.upper()
is_src_sink = any(s in src_upper for s in SINKS)
is_tgt_sink = any(s in tgt_upper for s in SINKS)
if is_src_sink and not is_tgt_sink:
# Invert inverted sink edge
new_rel_type = "RELIEVES_TO" if ("FLARE" in src_upper or "VENT" in src_upper) else "DRAINS_TO"
r_corr = {
"source_tag": tgt,
"target_tag": src,
"rel_type": new_rel_type
}
else:
r_corr = r
key = (r_corr["source_tag"], r_corr["target_tag"], r_corr["rel_type"])
if key not in seen:
seen.add(key)
corrected.append(r_corr)
return corrected
def _dist_to_segment(px: float, py: float, x1: float, y1: float, x2: float, y2: float) -> float:
"""Calculates perpendicular distance from point (px, py) to line segment (x1, y1)-(x2, y2)."""
dx = x2 - x1
+34 -1
View File
@@ -610,6 +610,36 @@ def classify_paddle_results(
flag_reason=flag_reason)
item_added = True
# Check for operational reference context (e.g. FROM ..., TO ..., TIE-IN TO ...)
is_ref_context = bool(re.search(r'\b(?:FROM|TO|TIE-IN|CONTINUED\s+ON|SEE\s+DWG|REF\s+DWG)\b', t, re.IGNORECASE))
# Split-suffix sibling instrument tags (e.g., 27-PY-0001BA/BB -> 27-PY-0001BA, 27-PY-0001BB)
for m in re.finditer(r'\b(\d{2}-[A-Z]{2,4}-\d{3,5})([A-Z]{1,2})/([A-Z]{1,2})\b', t, re.IGNORECASE):
base_prefix = m.group(1).upper()
suf1 = m.group(2).upper()
suf2 = m.group(3).upper()
tag1 = f"{base_prefix}{suf1}"
tag2 = f"{base_prefix}{suf2}"
for tag in (tag1, tag2):
if tag not in found:
it_copy = dict(item)
if is_ref_context:
it_copy["is_reference"] = True
found[tag] = _make_item(tag, 'INSTRUMENT_TAG', conf, it_copy)
item_added = True
# Inverted Suction Strainers (e.g., 9002 S 26 -> 26-ST-9002)
for m in re.finditer(r'\b(\d{4})\s*[-/]?\s*S\s*[-/]?\s*(\d{2})\b', t, re.IGNORECASE):
seq = m.group(1)
unit = m.group(2)
st_tag = f"{unit}-ST-{seq}"
if st_tag not in found:
it_copy = dict(item)
if is_ref_context:
it_copy["is_reference"] = True
found[st_tag] = _make_item(st_tag, 'EQUIPMENT_TAG', conf, it_copy)
item_added = True
# Project-prefix tags (instruments + equipment)
for m in _PROJECT_TAG_SEARCH.finditer(t):
full_tag = m.group(1).upper()
@@ -639,7 +669,10 @@ def classify_paddle_results(
cat = 'EQUIPMENT_TAG'
if full_tag not in found:
found[full_tag] = _make_item(full_tag, cat, conf, item)
it_copy = dict(item)
if is_ref_context:
it_copy["is_reference"] = True
found[full_tag] = _make_item(full_tag, cat, conf, it_copy)
item_added = True
# Bare instrument tags — Defect 3: setpoint negative-context guard for 3-digit setpoints
+4
View File
@@ -69,6 +69,10 @@ def rectify_ocr_typos(text: str) -> str:
cleaned = re.sub(r'\b(AS\d{2})5\b', r'\g<1>S', cleaned)
cleaned = re.sub(r'\b(AC\d{2})5\b', r'\g<1>S', cleaned)
# 5. Fix dropped decimal points in low pressure ratings: 005BARG -> 0.005 BARG, 005 BARG -> 0.005 BARG
cleaned = re.sub(r'(?<![\.\d])00(\d+)\s*(BARG|PSIG|BAR)\b', r'0.00\1 \2', cleaned, flags=re.IGNORECASE)
cleaned = re.sub(r'(?<![\.\d])0([1-9]\d)\s*(BARG|PSIG|BAR)\b', r'0.\1 \2', cleaned, flags=re.IGNORECASE)
return cleaned
+46 -1
View File
@@ -178,7 +178,52 @@ def run_tests():
]
compiled_psv = ca._compile_safety_relief_valves(psv_texts, [])
assert_test(len(compiled_psv) == 1 and compiled_psv[0].unit == "26", "PSV-9066A recovered Unit 26 (not NaN)")
assert_test(compiled_psv[0].relief_destination == "LP Flare Header", "PSV-9066A assigned LP Flare Header destination")
assert_test(compiled_psv[0].relief_destination == "HP Flare Header", "PSV-9066A assigned HP Flare Header destination")
print("\n" + "=" * 70)
print("6. TESTING ADVANCED RECOMMENDATIONS (AGENT AUDIT VERIFICATION)")
print("=" * 70)
# A. Anti-hallucination line filter
hallucinated_line_texts = [
{"classification": "LINE_TAG", "tag": '1 1/2"-FE-9017-NOTE', "value": '1 1/2"-FE-9017-NOTE'},
{"classification": "LINE_TAG", "tag": '1/2"-TIT-9018-TIT', "value": '1/2"-TIT-9018-TIT'},
{"classification": "LINE_TAG", "tag": '26-KA-902-M01', "value": '26-KA-902-M01'},
{"classification": "LINE_TAG", "tag": 'TT-26-9711-AS20-00', "value": 'TT-26-9711-AS20-00'},
{"classification": "LINE_TAG", "tag": '10"-VF-43-9027-AS20S-00', "value": '10"-VF-43-9027-AS20S-00'},
]
compiled_clean_lines = ca._compile_lines(hallucinated_line_texts, {}, [])
clean_line_tags = [l.tag for l in compiled_clean_lines]
assert_test('1 1/2"-FE-9017-NOTE' not in clean_line_tags, "Rejected hallucinated line '...-NOTE'")
assert_test('1/2"-TIT-9018-TIT' not in clean_line_tags, "Rejected hallucinated line '...-TIT'")
assert_test('26-KA-902-M01' not in clean_line_tags, "Rejected motor tag '26-KA-902-M01' from Line List")
assert_test('TT-26-9711-AS20-00' not in clean_line_tags, "Rejected transmitter cable tag 'TT-26-...' from Line List")
assert_test('10"-VF-43-9027-AS20S-00' in clean_line_tags, "Retained legitimate process piping line")
# B. Directionality & Sink Constraint Enforcement
from src.utils.line_tracer import _enforce_engineering_directionality
raw_relations = [
{"source_tag": "LP FLARE", "target_tag": "26-CK-921", "rel_type": "FEEDS"},
{"source_tag": "CLOSED DRAIN", "target_tag": "26-HA-911", "rel_type": "FEEDS"},
{"source_tag": "26-KA-901", "target_tag": '10"-VF-43-9027-AS20S-00', "rel_type": "FEEDS"},
]
corrected_rels = _enforce_engineering_directionality(raw_relations)
corr_map = {(r["source_tag"], r["target_tag"]): r["rel_type"] for r in corrected_rels}
assert_test(("26-CK-921", "LP FLARE") in corr_map and corr_map[("26-CK-921", "LP FLARE")] == "RELIEVES_TO", "Inverted 'LP FLARE feeds 26-CK-921' to '26-CK-921 relieves_to LP FLARE'")
assert_test(("26-HA-911", "CLOSED DRAIN") in corr_map and corr_map[("26-HA-911", "CLOSED DRAIN")] == "DRAINS_TO", "Inverted 'CLOSED DRAIN feeds 26-HA-911' to '26-HA-911 drains_to CLOSED DRAIN'")
assert_test(("26-KA-901", '10"-VF-43-9027-AS20S-00') in corr_map, "Preserved valid compressor feed line relation")
# C. Split sibling tags & inverted suction strainer detection
audit_ocr_items = [
{"text": "27-PY-0001BA/BB", "confidence": 0.95, "attributes": {}},
{"text": "9002 S 26", "confidence": 0.95, "attributes": {}},
{"text": "005BARG", "confidence": 0.95, "attributes": {}},
]
audit_classified = classify_paddle_results(audit_ocr_items, "PID")
audit_tags = {c["tag"]: c for c in audit_classified}
assert_test("27-PY-0001BA" in audit_tags and audit_tags["27-PY-0001BA"]["classification"] == "INSTRUMENT_TAG", "Extracted sibling instrument 27-PY-0001BA")
assert_test("27-PY-0001BB" in audit_tags and audit_tags["27-PY-0001BB"]["classification"] == "INSTRUMENT_TAG", "Extracted sibling instrument 27-PY-0001BB")
assert_test("26-ST-9002" in audit_tags and audit_tags["26-ST-9002"]["classification"] == "EQUIPMENT_TAG", "Recognized suction strainer '9002 S 26' as 26-ST-9002")
assert_test(rectify_ocr_typos("005BARG") == "0.005 BARG", "Restored dropped decimal point '005BARG' -> '0.005 BARG'")
print("\n" + "=" * 70)
print(f"FINAL RESULT: {total_passed}/{total_tests} Tests Passed (100% Precision Verified Across All Categories)")