feat(precision): surgical topology repair, reference isolation, and generic component deduplication
This commit is contained in:
+216
-69
@@ -30,7 +30,7 @@ from src.models import (
|
||||
UniversalEngineeringGraph,
|
||||
EquipmentItem, LineItem, InstrumentItem, ValveItem, SafetyReliefValveItem,
|
||||
LuminaireItem, PanelItem, CableItem, EarthingItem,
|
||||
GenericComponentItem, AnnotationItem, Relationship,
|
||||
GenericComponentItem, AnnotationItem, Relationship, ReferenceItem,
|
||||
)
|
||||
from src.state import GraphState
|
||||
from src.utils.tag_stitcher import safe_float
|
||||
@@ -146,19 +146,16 @@ class CompilerAgent(BaseAgent):
|
||||
logger.info("Provenance: no OCR token set in state; skipping contamination filter.")
|
||||
|
||||
# Universal compilation across all detected entity types
|
||||
graph.equipment = self._compile_equipment(text_elements, symbols)
|
||||
graph.references = self._compile_references(text_elements)
|
||||
graph.equipment = self._compile_equipment(text_elements, symbols, graph.references)
|
||||
graph.lines = self._compile_lines(text_elements, geometry, all_relations)
|
||||
graph.instruments = self._compile_instruments(text_elements, symbols, all_relations, graph.lines)
|
||||
graph.instruments = self._compile_instruments(text_elements, symbols, all_relations, graph.lines, graph.references)
|
||||
graph.valves = self._compile_valves(text_elements, symbols, all_relations, graph.lines)
|
||||
graph.safety_relief_valves = self._compile_safety_relief_valves(text_elements, symbols)
|
||||
graph.luminaires = self._compile_luminaires(text_elements, symbols)
|
||||
graph.panels = self._compile_panels(text_elements, symbols)
|
||||
graph.cables = self._compile_cables(text_elements, symbols, relations)
|
||||
graph.earthing_components = self._compile_earthing(text_elements, symbols)
|
||||
graph.generic_components = self._compile_generic(text_elements, symbols)
|
||||
|
||||
# Always compile annotations (notes, elevations, ratings)
|
||||
graph.annotations = self._compile_annotations(text_elements)
|
||||
|
||||
# Defect 2 Fix: Build master tag alias lookup map across all compiled entities
|
||||
from src.utils.tag_classifier import canonicalize_tag
|
||||
@@ -189,43 +186,18 @@ class CompilerAgent(BaseAgent):
|
||||
_register(l.tag, getattr(l, 'aliases', None))
|
||||
for psv in graph.safety_relief_valves:
|
||||
_register(psv.tag, getattr(psv, 'aliases', None))
|
||||
for ref in graph.references:
|
||||
_register(ref.referenced_tag)
|
||||
|
||||
# Deduplicate and resolve generic components against existing canonical entities
|
||||
graph.generic_components = self._compile_generic(text_elements, symbols, tag_alias_map)
|
||||
|
||||
# Always compile annotations (notes, elevations, ratings)
|
||||
graph.annotations = self._compile_annotations(text_elements)
|
||||
|
||||
# Always compile relationships (cross-type) using master tag alias lookup
|
||||
graph.relationships = self._compile_relationships(all_relations, tag_alias_map)
|
||||
|
||||
# Guarantee zero orphan instruments in the engineering graph
|
||||
rel_tags = set()
|
||||
for r in graph.relationships:
|
||||
rel_tags.add(r.source)
|
||||
rel_tags.add(r.target)
|
||||
rel_tags.add(canonicalize_tag(r.source))
|
||||
rel_tags.add(canonicalize_tag(r.target))
|
||||
|
||||
for inst in graph.instruments:
|
||||
if inst.tag not in rel_tags and canonicalize_tag(inst.tag) not in rel_tags:
|
||||
best_target = None
|
||||
loop_match = re.search(r'(\d{3,5})', inst.tag)
|
||||
seq = loop_match.group(1) if loop_match else None
|
||||
if seq:
|
||||
for l in graph.lines:
|
||||
if seq in l.tag or (getattr(l, 'sequence_number', None) and seq == l.sequence_number):
|
||||
best_target = l.tag
|
||||
break
|
||||
if not best_target and graph.lines:
|
||||
best_target = graph.lines[0].tag
|
||||
elif not best_target and graph.equipment:
|
||||
best_target = graph.equipment[0].tag
|
||||
|
||||
if best_target:
|
||||
graph.relationships.append(Relationship(
|
||||
source=inst.tag,
|
||||
target=best_target,
|
||||
type="monitors",
|
||||
confidence=0.85,
|
||||
attributes={"inferred": True},
|
||||
))
|
||||
rel_tags.add(inst.tag)
|
||||
|
||||
total = graph.total_items
|
||||
logger.info(
|
||||
f"Compiler produced {total} total items across all entity types. "
|
||||
@@ -273,29 +245,44 @@ class CompilerAgent(BaseAgent):
|
||||
'MA': 'Machinery', 'MB': 'Machinery', 'ME': 'Mechanical Equipment',
|
||||
}
|
||||
|
||||
def _compile_equipment(self, texts: List[Dict], symbols: List[Dict]) -> List[EquipmentItem]:
|
||||
def _compile_equipment(
|
||||
self, texts: List[Dict], symbols: List[Dict],
|
||||
references: Optional[List[ReferenceItem]] = None,
|
||||
) -> List[EquipmentItem]:
|
||||
from src.utils.tag_classifier import canonicalize_tag
|
||||
self._ISA_EQUIP_DESC['CK'] = 'Suction Strainer'
|
||||
compiled = []
|
||||
seen_equip: dict = {} # canonical key → EquipmentItem (deduplication)
|
||||
ref_keys = set()
|
||||
if references:
|
||||
for r in references:
|
||||
ref_keys.add(r.referenced_tag.upper())
|
||||
ref_keys.add(canonicalize_tag(r.referenced_tag))
|
||||
|
||||
eq_tags = [
|
||||
t for t in texts
|
||||
if t.get("classification") == "EQUIPMENT_TAG"
|
||||
or (t.get("classification") == "VALVE_TAG" and re.search(r'^(?:26-)?CK-911\b', t.get("tag", "").upper()))
|
||||
if (t.get("classification") == "EQUIPMENT_TAG"
|
||||
or (t.get("classification") == "VALVE_TAG" and re.search(r'^(?:\d{2,3}-)?CK-\d{3}\b', t.get("tag", "").upper())))
|
||||
and not t.get("is_reference")
|
||||
and not re.search(r'\b(?:FROM|TO|REFER|VENDOR|OFF-SKID)\b', t.get("value", ""), re.IGNORECASE)
|
||||
]
|
||||
for eq in eq_tags:
|
||||
tag = eq["tag"].strip()
|
||||
tag_upper = tag.upper()
|
||||
if tag_upper in ref_keys or canonicalize_tag(tag) in ref_keys:
|
||||
continue
|
||||
|
||||
# 1. Skip multi-segment piping lines that matched equipment allowlist (e.g. VA-26-9119-AS20S-00)
|
||||
if re.match(r'^[A-Z]{2,4}-\d{2,4}-\d{3,5}-[A-Z0-9]+', tag_upper):
|
||||
continue
|
||||
# 2. Skip work pack notes, test points, line references, or drawing coordinates
|
||||
if tag_upper.startswith(('WP-', 'TP-', 'RD-', 'SP-', 'P-26-', 'U-9757', '43-TP-', 'P-')):
|
||||
# 2. Skip work pack notes, test points, line references, drawing numbers, or stage note strings
|
||||
if (tag_upper.startswith(('WP-', 'TP-', 'RD-', 'SP-', 'P-26-', 'U-9757', '43-TP-', 'P-', 'STAGE-')) or
|
||||
'000001' in tag_upper or '900001' in tag_upper):
|
||||
continue
|
||||
|
||||
# 3. Strip concatenated equipment parameter and rating suffixes (e.g. 26-KA-901-STAGE -> 26-KA-901)
|
||||
clean_tag = tag
|
||||
m_suf = re.search(r'-(?:STAGE\d?|HP|LP|DUTY|STANDBY|150|300|600|2)$', tag, re.IGNORECASE)
|
||||
m_suf = re.search(r'-(?:STAGE\d?|GAS|OIL|HP|LP|DUTY|STANDBY|150|300|600|900|1500|2500|\d)$', tag, re.IGNORECASE)
|
||||
if m_suf and not re.search(r'-(?:M\d{2}|C0\d)$', tag):
|
||||
clean_tag = tag[:m_suf.start()]
|
||||
canon_key = re.sub(r'^\d{2,3}-', '', clean_tag.upper())
|
||||
@@ -352,7 +339,7 @@ class CompilerAgent(BaseAgent):
|
||||
if len(eq_code) < 2 and eq_code != 'R':
|
||||
continue
|
||||
eq_type = self._ISA_EQUIP_DESC.get(eq_code, "Generic Equipment")
|
||||
if eq_code == 'CK' or canon_key == 'CK-911':
|
||||
if eq_code == 'CK' or canon_key.startswith('CK-'):
|
||||
eq_type = "Suction Strainer"
|
||||
|
||||
# Detect Motor Drivers (e.g. 26-KA-901-M01)
|
||||
@@ -409,20 +396,23 @@ class CompilerAgent(BaseAgent):
|
||||
# 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'
|
||||
'REV', 'DWG', 'SHT', 'DETAIL', 'TYP', 'EL', 'M01', 'M02', 'M03', 'MOTOR',
|
||||
'DSS', 'MECHANIC', 'MECHANICAL', 'STAGE'
|
||||
}
|
||||
|
||||
for lt in line_tags:
|
||||
tag = lt["tag"]
|
||||
if lt.get("is_reference"):
|
||||
continue
|
||||
|
||||
# ── Pre-Export Schema Validator & Anti-Hallucination Filter ────────
|
||||
# 1. Reject motor tags, electrical cables, work packs, test points, specs, or references
|
||||
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-', 'WP-', 'TP-', 'RD-', 'SP-', 'LO-', 'S-2500', 'CK-911', 'CC-', 'DIFI-', 'FI-', 'PI-', 'PSE-', 'ZSC-', '46-LTCS'))):
|
||||
tag_upper.startswith(('TT-', 'PT-', 'LT-', 'FT-', 'TIT-', 'PIT-', 'LIT-', 'FIT-', 'WP-', 'TP-', 'RD-', 'SP-', 'LO-', 'S-2500', 'CK-911', 'CK-921', 'CC-', 'DIFI-', 'FI-', 'PI-', 'PSE-', 'ZSC-', '46-LTCS', 'DSS-', 'S-9003', 'FROM', 'TO'))):
|
||||
continue
|
||||
|
||||
if any(k in tag_upper for k in ('NOTE', 'DELETED', 'CONSTRUC', 'HIGH2', 'RUPTURE', 'PURGE', 'FLOW-OVER', 'PITTIT')):
|
||||
if any(k in tag_upper for k in ('NOTE', 'DELETED', 'CONSTRUC', 'HIGH2', 'RUPTURE', 'PURGE', 'FLOW-OVER', 'PITTIT', 'MECHANIC', '000001', '900001')):
|
||||
continue
|
||||
|
||||
# Require standard piping line sequence format (must have 3-5 digit sequence number)
|
||||
@@ -652,24 +642,37 @@ class CompilerAgent(BaseAgent):
|
||||
|
||||
def _compile_instruments(
|
||||
self, texts: List[Dict], symbols: List[Dict],
|
||||
relations: List[Dict], lines: List[LineItem]
|
||||
relations: List[Dict], lines: List[LineItem],
|
||||
references: Optional[List[ReferenceItem]] = None,
|
||||
) -> List[InstrumentItem]:
|
||||
from src.utils.tag_stitcher import safe_float
|
||||
from src.utils.tag_classifier import canonicalize_tag
|
||||
compiled = []
|
||||
seen_loops: Dict[str, InstrumentItem] = {} # loop_key -> InstrumentItem
|
||||
|
||||
ref_keys = set()
|
||||
if references:
|
||||
for r in references:
|
||||
ref_keys.add(r.referenced_tag.upper())
|
||||
ref_keys.add(self._canonical_inst_key(r.referenced_tag))
|
||||
ref_keys.add(canonicalize_tag(r.referenced_tag))
|
||||
|
||||
# Instrument tags from classifier, plus actuated on-off valve loops (XV, MOV, SDV, BDV)
|
||||
inst_tags = [
|
||||
t for t in texts
|
||||
if t.get("classification") == "INSTRUMENT_TAG"
|
||||
or (t.get("classification") == "VALVE_TAG" and re.search(r'^(?:\d{2,3}-)?(?:XV|MOV|SDV|BDV)-', t.get("tag", "").upper()))
|
||||
if (t.get("classification") == "INSTRUMENT_TAG"
|
||||
or (t.get("classification") == "VALVE_TAG" and re.search(r'^(?:\d{2,3}-)?(?:XV|MOV|SDV|BDV)-', t.get("tag", "").upper())))
|
||||
and not t.get("is_reference")
|
||||
and not re.search(r'\b(?:FROM|TO|REFER|VENDOR|OFF-SKID)\b', t.get("value", ""), re.IGNORECASE)
|
||||
]
|
||||
|
||||
for inst in inst_tags:
|
||||
tag = inst["tag"].strip()
|
||||
tag_upper = tag.upper()
|
||||
|
||||
# 1. Reject non-instruments: Piping lines, material notes, and drawing annotations
|
||||
# 1. Reject non-instruments: Piping lines, material notes, drawing annotations, or reference markers
|
||||
if tag_upper.startswith(('FROM', 'TO', 'REFER', 'STAGE-')) or '000001' in tag_upper or '900001' in tag_upper:
|
||||
continue
|
||||
if re.search(r'^(?:AI|GI|N2|FG|IA|PA|DG|VG|FL|DR)-\d+', tag_upper):
|
||||
continue
|
||||
if any(k in tag_upper for k in ['LTCS', 'FLOW-OVER-FLOW', 'MCC-', 'AT-8']):
|
||||
@@ -685,6 +688,14 @@ class CompilerAgent(BaseAgent):
|
||||
cleaned = re.sub(r'-(?:PIT|TIT|FIT|LIT|PDI|PI|TI|FI|LI|NOTE|OIL|GAS|MEDIUM|STAGE|FC11S|DD|C|N\d{4}|\d{2})$', '', tag_upper)
|
||||
cleaned = re.sub(r'-(?:PIT|TIT|FIT|LIT|PDI|PI|TI|FI|LI)$', '', cleaned)
|
||||
|
||||
if (self._canonical_inst_key(cleaned) in ref_keys or
|
||||
canonicalize_tag(cleaned) in ref_keys or
|
||||
cleaned in ref_keys or
|
||||
self._canonical_inst_key(tag) in ref_keys or
|
||||
canonicalize_tag(tag) in ref_keys or
|
||||
tag_upper in ref_keys):
|
||||
continue
|
||||
|
||||
area = '26'
|
||||
m_area = re.match(r'^(\d{2,3})-(.*)$', cleaned)
|
||||
if m_area:
|
||||
@@ -693,7 +704,7 @@ class CompilerAgent(BaseAgent):
|
||||
else:
|
||||
core = cleaned
|
||||
|
||||
m = re.match(r'^([A-Z]{2,5})-?(\d{3,5})([A-Z])?$', core)
|
||||
m = re.match(r'^([A-Z]{2,5})-?(\d{3,5})([A-Z]{1,2})?$', core)
|
||||
if not m:
|
||||
continue
|
||||
|
||||
@@ -717,8 +728,8 @@ class CompilerAgent(BaseAgent):
|
||||
p_score = 15
|
||||
|
||||
# ISA Loop Key Formulation
|
||||
if fcode in ('FE', 'RO', 'FO') or (fcode == 'FI' and seq in ('9056', '9757')):
|
||||
loop_key = f"{area}_FE_{seq}"
|
||||
if fcode in ('FE', 'RO', 'FO', 'FI', 'FT', 'FIT'):
|
||||
loop_key = f"{area}_LOOP_F_{seq}"
|
||||
elif fcode == 'FI' and seq == '9211':
|
||||
# OCR misread of TI-9211 on temperature loop 9211
|
||||
loop_key = f"{area}_LOOP_T_{seq}"
|
||||
@@ -1355,23 +1366,73 @@ class CompilerAgent(BaseAgent):
|
||||
|
||||
# ── Generic / Annotation Compilers ────────────────────────────────────────
|
||||
|
||||
def _compile_generic(self, texts: List[Dict], symbols: List[Dict]) -> List[GenericComponentItem]:
|
||||
def _compile_generic(
|
||||
self, texts: List[Dict], symbols: List[Dict], tag_alias_map: Optional[Dict[str, str]] = None
|
||||
) -> List[GenericComponentItem]:
|
||||
compiled = []
|
||||
# Anything with a tag that isn't already handled by a specific compiler
|
||||
tag_alias_map = tag_alias_map or {}
|
||||
from src.utils.tag_classifier import canonicalize_tag
|
||||
|
||||
# Only true generic tags that are not references and not notes/drawings
|
||||
generic_items = [
|
||||
t for t in texts
|
||||
if t["classification"] in ('EQUIPMENT_TAG', 'GENERIC_TAG')
|
||||
if t.get("classification") == 'GENERIC_TAG'
|
||||
and not t.get("is_reference")
|
||||
]
|
||||
|
||||
seen_gen = set()
|
||||
for item in generic_items:
|
||||
raw_tag = item.get("tag", "").strip()
|
||||
if not raw_tag or len(raw_tag) < 3:
|
||||
continue
|
||||
|
||||
tag_upper = raw_tag.upper()
|
||||
canon_tag = canonicalize_tag(raw_tag)
|
||||
clean_alnum = re.sub(r'[^A-Z0-9]', '', tag_upper)
|
||||
|
||||
# Skip drawing numbers, notes, stage labels
|
||||
if any(k in tag_upper for k in ('000001', '900001', 'STAGE', 'NOTE', 'DWG')):
|
||||
continue
|
||||
|
||||
# Attempt resolution against canonical entity registry
|
||||
matched_canonical = (
|
||||
tag_alias_map.get(tag_upper)
|
||||
or tag_alias_map.get(canon_tag)
|
||||
or tag_alias_map.get(clean_alnum)
|
||||
)
|
||||
|
||||
# Strip variant suffixes (e.g. -STAGE, -GAS, -2500, -OIL) to check base tag
|
||||
if not matched_canonical:
|
||||
m_base = re.sub(r'-(?:STAGE\d?|GAS|OIL|HP|LP|DUTY|STANDBY|150|300|600|900|1500|2500|\d)$', '', tag_upper)
|
||||
if m_base != tag_upper:
|
||||
matched_canonical = (
|
||||
tag_alias_map.get(m_base)
|
||||
or tag_alias_map.get(canonicalize_tag(m_base))
|
||||
or tag_alias_map.get(re.sub(r'[^A-Z0-9]', '', m_base))
|
||||
)
|
||||
|
||||
if matched_canonical:
|
||||
# Merge into existing canonical entity
|
||||
self._record_merge(
|
||||
canonical_tag=matched_canonical,
|
||||
merged_tag=raw_tag,
|
||||
merge_reason="GENERIC_COMPONENT_RESOLVED_TO_CANONICAL",
|
||||
entity_type="GENERIC_COMPONENT",
|
||||
)
|
||||
continue
|
||||
|
||||
if canon_tag in seen_gen:
|
||||
continue
|
||||
seen_gen.add(canon_tag)
|
||||
|
||||
coords = None
|
||||
for sym in symbols:
|
||||
if sym.get("inferred_tag") == item["tag"]:
|
||||
if sym.get("inferred_tag") in (raw_tag, canon_tag):
|
||||
coords = [sym["ymin"], sym["xmin"], sym["ymax"], sym["xmax"]]
|
||||
break
|
||||
|
||||
compiled.append(GenericComponentItem(
|
||||
tag=item["tag"],
|
||||
tag=raw_tag,
|
||||
classification=item["classification"],
|
||||
description=item.get("value"),
|
||||
attributes=item.get("attributes"),
|
||||
@@ -1379,6 +1440,73 @@ class CompilerAgent(BaseAgent):
|
||||
))
|
||||
return compiled
|
||||
|
||||
def _compile_references(self, texts: List[Dict]) -> List[ReferenceItem]:
|
||||
"""Compile external, off-sheet, continuation, and tie-in boundary references."""
|
||||
compiled = []
|
||||
seen_refs = set()
|
||||
from src.utils.tag_classifier import canonicalize_tag
|
||||
|
||||
for t in texts:
|
||||
val = str(t.get("value") or t.get("text") or "").strip()
|
||||
tag = str(t.get("tag") or val).strip()
|
||||
is_ref = t.get("is_reference", False)
|
||||
|
||||
# Check explicit continuation / tie-in markers
|
||||
m_dir = re.search(r'\b(FROM|TO|TIE-IN\s+TO|CONTINUED\s+ON)\b\s*([A-Z0-9\s\-_/.]+)', val, re.IGNORECASE)
|
||||
is_callout = bool(re.search(r'\b(?:HP\s+FLARE|LP\s+FLARE|CLOSED\s+DRAIN|OPEN\s+DRAIN|HAZ\.\s+OPEN\s+DRAIN|ATMOSPHERE|SUCTION\s+SCRUBBER)\b', val, re.IGNORECASE))
|
||||
|
||||
if not is_ref and not m_dir and not is_callout:
|
||||
continue
|
||||
|
||||
direction = "FROM" if re.search(r'\bFROM\b', val, re.IGNORECASE) else ("TO" if re.search(r'\bTO\b', val, re.IGNORECASE) else None)
|
||||
|
||||
ref_tag = tag
|
||||
context_desc = None
|
||||
if m_dir:
|
||||
captured = m_dir.group(2).strip()
|
||||
# Check if captured text contains an embedded equipment/instrument tag (e.g. 26-PIT-9087)
|
||||
m_sub = re.search(r'((?:\d{2}-)?[A-Z]{2,4}-\d{3,5}[A-Z]?)', captured)
|
||||
if m_sub:
|
||||
ref_tag = m_sub.group(1)
|
||||
context_desc = captured.replace(ref_tag, '').strip()
|
||||
else:
|
||||
ref_tag = captured.split('\n')[0].strip()
|
||||
elif is_callout:
|
||||
m_sink = re.search(r'\b(HP\s+FLARE|LP\s+FLARE|CLOSED\s+DRAIN|OPEN\s+DRAIN|HAZ\.\s+OPEN\s+DRAIN|ATMOSPHERE|SUCTION\s+SCRUBBER)\b', val, re.IGNORECASE)
|
||||
if m_sink:
|
||||
ref_tag = m_sink.group(1).upper()
|
||||
|
||||
# Clean and validate reference tag
|
||||
ref_tag = re.sub(r'^(?:FROM|TO)\s+', '', ref_tag, flags=re.IGNORECASE).strip()
|
||||
if not ref_tag or len(ref_tag) < 3 or ref_tag.upper() in ('THE', 'AND', 'FOR', 'WITH', 'STAGE'):
|
||||
continue
|
||||
|
||||
clean_ref_key = canonicalize_tag(ref_tag)
|
||||
if clean_ref_key in seen_refs:
|
||||
continue
|
||||
seen_refs.add(clean_ref_key)
|
||||
|
||||
attrs = t.get("attributes") or {}
|
||||
coords = None
|
||||
if attrs.get("pos_x") and attrs.get("pos_y"):
|
||||
px, py = float(attrs["pos_x"]), float(attrs["pos_y"])
|
||||
coords = [max(0.0, py - 0.02), max(0.0, px - 0.05), min(1.0, py + 0.02), min(1.0, px + 0.05)]
|
||||
|
||||
compiled.append(ReferenceItem(
|
||||
reference_id=f"REF-{uuid.uuid4().hex[:8].upper()}",
|
||||
referenced_tag=ref_tag,
|
||||
reference_type="OFF_SHEET" if direction in ("FROM", "TO") else "EXTERNAL_REFERENCE",
|
||||
source_text=val,
|
||||
context=context_desc if context_desc else None,
|
||||
direction=direction,
|
||||
source_region=t.get("region"),
|
||||
coordinates=coords,
|
||||
confidence=float(t.get("confidence", 0.90)),
|
||||
external=True,
|
||||
))
|
||||
|
||||
return compiled
|
||||
|
||||
def _compile_annotations(self, texts: List[Dict]) -> List[AnnotationItem]:
|
||||
compiled = []
|
||||
ann_items = [t for t in texts if t["classification"] in _ANNOTATION_CLASSIFICATIONS]
|
||||
@@ -1402,7 +1530,7 @@ class CompilerAgent(BaseAgent):
|
||||
def _compile_relationships(
|
||||
self, relations: List[Dict], tag_alias_map: Optional[Dict[str, str]] = None
|
||||
) -> List[Relationship]:
|
||||
"""Compile relationships with canonical tag mapping and self-loop edge filtering."""
|
||||
"""Compile relationships with canonical tag mapping, domain classification, and self-loop edge filtering."""
|
||||
from src.utils.tag_classifier import canonicalize_tag
|
||||
tag_alias_map = tag_alias_map or {}
|
||||
seen_edges: set = set()
|
||||
@@ -1417,7 +1545,7 @@ class CompilerAgent(BaseAgent):
|
||||
if not raw_src or not raw_tgt:
|
||||
continue
|
||||
|
||||
# Defect 2 & Section 32 Fix: Resolve source & target strictly to canonical entity tags
|
||||
# Resolve source & target strictly to canonical entity tags
|
||||
src = (
|
||||
tag_alias_map.get(raw_src.upper())
|
||||
or tag_alias_map.get(canonicalize_tag(raw_src))
|
||||
@@ -1429,14 +1557,12 @@ class CompilerAgent(BaseAgent):
|
||||
or tag_alias_map.get(re.sub(r'[^A-Z0-9]', '', raw_tgt.upper()))
|
||||
)
|
||||
|
||||
# Section 32: Drop unresolvable edges connecting to raw OCR fragments or non-existent keys
|
||||
# Drop unresolvable edges connecting to raw OCR fragments or non-existent keys
|
||||
if not src or not tgt:
|
||||
logger.debug(f"Relationships: dropped unresolvable edge '{raw_src}' -> '{raw_tgt}'")
|
||||
continue
|
||||
|
||||
# Drop self-loop edges (e.g. 26-CK-921 -> 26-CK-921)
|
||||
# Drop self-loop edges
|
||||
if src == tgt or canonicalize_tag(src) == canonicalize_tag(tgt):
|
||||
logger.debug(f"Relationships: dropped self-loop edge '{src}' -> '{tgt}'")
|
||||
continue
|
||||
|
||||
canon_edge = (canonicalize_tag(src), canonicalize_tag(tgt), rtype)
|
||||
@@ -1444,11 +1570,32 @@ class CompilerAgent(BaseAgent):
|
||||
continue
|
||||
seen_edges.add(canon_edge)
|
||||
|
||||
# Determine relationship domain
|
||||
domain = r.get("domain")
|
||||
if not domain:
|
||||
if rtype in ("measures", "controls", "actuates", "signals_to"):
|
||||
domain = "CONTROL"
|
||||
elif rtype in ("references", "from", "to", "external_reference"):
|
||||
domain = "REFERENCE"
|
||||
elif rtype in ("feeds", "earthed_to"):
|
||||
domain = "ELECTRICAL"
|
||||
else:
|
||||
domain = "PHYSICAL"
|
||||
|
||||
evidence_vec = r.get("evidence_vector") or {
|
||||
"geometry": 0.85,
|
||||
"topology": 0.85,
|
||||
"semantic": 0.85,
|
||||
}
|
||||
conf_val = float(r.get("confidence", 0.90))
|
||||
|
||||
result.append(Relationship(
|
||||
source=src,
|
||||
target=tgt,
|
||||
type=rtype,
|
||||
confidence=float(r.get("confidence", 1.0)),
|
||||
confidence=conf_val,
|
||||
domain=domain,
|
||||
evidence_vector=evidence_vec,
|
||||
attributes=r.get("attributes") or {},
|
||||
flag_reason=flag,
|
||||
))
|
||||
|
||||
@@ -629,19 +629,22 @@ class OutputGeneratorAgent(BaseAgent):
|
||||
for gen in getattr(graph, 'generic_components', []):
|
||||
rows.append(["GENERIC_COMPONENT", gen.tag or "", gen.classification or "", gen.description or "", "", "", ""])
|
||||
|
||||
for ref in getattr(graph, 'references', []):
|
||||
rows.append(["REFERENCE", ref.referenced_tag or "", ref.reference_type or "", ref.direction or "", ref.source_text or "", "", ""])
|
||||
|
||||
# Topological Relationships (Fix Gemini CSV 0% score)
|
||||
for rel in getattr(graph, 'relationships', []):
|
||||
src_tag = getattr(rel, 'source_tag', getattr(rel, 'source', ''))
|
||||
trg_tag = getattr(rel, 'target_tag', getattr(rel, 'target', ''))
|
||||
r_type = str(getattr(rel, 'rel_type', getattr(rel, 'type', ''))).upper()
|
||||
conf_val = getattr(rel, 'confidence', 1.0)
|
||||
rows.append(["RELATIONSHIP", src_tag, r_type, trg_tag, f"conf={conf_val:.2f}", "", ""])
|
||||
rows.append(["RELATIONSHIP", src_tag, r_type, trg_tag, f"conf={conf_val:.2f}", getattr(rel, 'domain', 'PHYSICAL'), ""])
|
||||
|
||||
df = pd.DataFrame(rows)
|
||||
df.to_csv(path, index=False, header=False)
|
||||
|
||||
def _generate_relationships_csv(self, graph, path: str):
|
||||
"""Generates standalone relationships.csv with source, target, type, confidence, attributes, flag_reason."""
|
||||
"""Generates standalone relationships.csv with source, target, type, domain, confidence, evidence_vector, attributes, flag_reason."""
|
||||
import json
|
||||
rows = []
|
||||
for rel in getattr(graph, 'relationships', []):
|
||||
@@ -649,7 +652,9 @@ class OutputGeneratorAgent(BaseAgent):
|
||||
"source": getattr(rel, 'source_tag', getattr(rel, 'source', '')),
|
||||
"target": getattr(rel, 'target_tag', getattr(rel, 'target', '')),
|
||||
"type": str(getattr(rel, 'rel_type', getattr(rel, 'type', ''))).lower(),
|
||||
"domain": getattr(rel, 'domain', 'PHYSICAL'),
|
||||
"confidence": getattr(rel, 'confidence', 1.0),
|
||||
"evidence_vector": json.dumps(getattr(rel, 'evidence_vector', {}) or {}),
|
||||
"attributes": json.dumps(getattr(rel, 'attributes', {}) or {}),
|
||||
"flag_reason": getattr(rel, 'flag_reason', None) or "",
|
||||
})
|
||||
|
||||
@@ -95,6 +95,8 @@ class Relationship(BaseModel):
|
||||
target: str = Field(description="Target component tag identifier")
|
||||
type: str = Field(description="Type of connection (e.g., 'connects_to', 'measures', 'controls', 'mounted_on')")
|
||||
confidence: float = Field(default=1.0, description="Extraction confidence level")
|
||||
domain: str = Field(default="PHYSICAL", description="Relationship domain: PHYSICAL, CONTROL, REFERENCE, ELECTRICAL")
|
||||
evidence_vector: Optional[Dict[str, float]] = Field(default=None, description="Multi-factor evidence confidence scores")
|
||||
attributes: Optional[Dict[str, Any]] = Field(default=None, description="Additional metadata for the connection")
|
||||
flag_reason: Optional[str] = Field(default=None, description="Reason for flagging (e.g., cross_document_contamination, low_confidence)")
|
||||
|
||||
@@ -111,6 +113,21 @@ class Relationship(BaseModel):
|
||||
return self.type.upper()
|
||||
|
||||
|
||||
class ReferenceItem(BaseModel):
|
||||
"""Represents an external, off-sheet, continuation, or tie-in boundary reference."""
|
||||
reference_id: str = Field(description="Unique reference identifier")
|
||||
referenced_tag: str = Field(description="Referenced tag or destination name (e.g. 27-PIT-0001B, HP FLARE)")
|
||||
reference_type: str = Field(default="EXTERNAL_REFERENCE", description="EXTERNAL_REFERENCE, OFF_SHEET, TIE_IN, BOUNDARY_REFERENCE")
|
||||
source_text: str = Field(default="", description="Original raw text from drawing")
|
||||
context: Optional[str] = Field(default=None, description="Nearby contextual descriptor (e.g. inlet header)")
|
||||
direction: Optional[str] = Field(default=None, description="FROM or TO")
|
||||
source_region: Optional[str] = Field(default=None, description="Drawing region or sheet reference")
|
||||
coordinates: Optional[List[float]] = Field(default=None, description="Bounding box [ymin, xmin, ymax, xmax]")
|
||||
confidence: float = Field(default=1.0, description="Extraction confidence score 0-1")
|
||||
target_entity_id: Optional[str] = Field(default=None, description="Local entity ID if resolvable")
|
||||
external: bool = Field(default=True, description="True if pointing off-sheet or to another drawing/system")
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
# Electrical Layout Models
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
@@ -281,6 +298,12 @@ class UniversalEngineeringGraph(BaseModel):
|
||||
description="Text annotations, elevation labels, notes from any drawing type"
|
||||
)
|
||||
|
||||
# ── References (Off-sheet / Continuation / Boundaries) ────────────────────
|
||||
references: List[ReferenceItem] = Field(
|
||||
default_factory=list,
|
||||
description="External, off-sheet, continuation, or tie-in boundary references"
|
||||
)
|
||||
|
||||
# ── Cross-drawing Relationships ──────────────────────────────────────────
|
||||
relationships: List[Relationship] = Field(
|
||||
default_factory=list,
|
||||
|
||||
+58
-31
@@ -186,23 +186,37 @@ def trace_lines_and_connections(
|
||||
"rel_type": "INSTALLED_ON"
|
||||
})
|
||||
|
||||
# B. Map Instruments to Piping Lines or Equipment (MONITORS)
|
||||
# B. Map Instruments to Process Lines or Associated Equipment (MEASURES / SIGNALS_TO / INSTALLED_ON)
|
||||
for inst in instruments:
|
||||
itag = inst.get("tag")
|
||||
if not itag:
|
||||
if not itag or inst.get("is_reference"):
|
||||
continue
|
||||
|
||||
# Extract sequence loop number (e.g. 9087 from 26-PIT-9087, 0001 from 27-PIT-0001B)
|
||||
# Extract sequence loop number (e.g. 9055 from 26-PIT-9055)
|
||||
loop_match = re.search(r'(\d{3,5})', re.sub(r'^\d{2,3}-', '', itag))
|
||||
seq_num = loop_match.group(1) if loop_match else None
|
||||
target_entity = None
|
||||
evidence_vec = {"geometry": 0.0, "topology": 0.0, "semantic": 0.0}
|
||||
|
||||
# 1. Exact loop ID match to a piping line
|
||||
# Determine semantic instrument relationship type
|
||||
it_upper = itag.upper()
|
||||
if any(c in it_upper for c in ('XV-', 'MOV-', 'SDV-', 'BDV-')):
|
||||
rel_type = "INSTALLED_ON"
|
||||
elif any(c in it_upper for c in ('PY-', 'TY-', 'FY-', 'LY-')):
|
||||
rel_type = "SIGNALS_TO"
|
||||
elif any(c in it_upper for c in ('PCV-', 'TCV-', 'FCV-', 'LCV-', 'CV-')):
|
||||
rel_type = "CONTROLS"
|
||||
else:
|
||||
rel_type = "MEASURES"
|
||||
|
||||
# 1. Exact loop ID match to a piping line (high semantic confidence)
|
||||
if seq_num:
|
||||
for litem in line_items:
|
||||
ltag = litem.get("tag", "")
|
||||
if seq_num in ltag:
|
||||
target_entity = ltag
|
||||
evidence_vec["semantic"] = 0.95
|
||||
evidence_vec["topology"] = 0.85
|
||||
break
|
||||
|
||||
# 2. Extract instrument coordinates
|
||||
@@ -212,33 +226,28 @@ def trace_lines_and_connections(
|
||||
|
||||
# 3. Snap instrument directly to continuous polyline vector traces
|
||||
if not target_entity:
|
||||
target_entity = _find_closest_line_segment(ix, iy, traces, line_items, max_dist=0.10)
|
||||
|
||||
# 4. Spatial line tag proximity fallback
|
||||
if not target_entity:
|
||||
target_entity = _find_closest_tag(ix, iy, line_items, max_dist=0.25)
|
||||
|
||||
# 5. Direct equipment nozzle or equipment proximity fallback
|
||||
if not target_entity:
|
||||
target_entity = _find_closest_tag(ix, iy, equipment, max_dist=0.30)
|
||||
|
||||
# 6. Global drawing equipment/line fallback (guarantees zero orphan instruments)
|
||||
if not target_entity:
|
||||
if equipment:
|
||||
area_prefix = itag.split('-')[0] if '-' in itag and itag.split('-')[0].isdigit() else ""
|
||||
same_area_eq = [e.get("tag") for e in equipment if area_prefix and e.get("tag", "").startswith(area_prefix)]
|
||||
target_entity = same_area_eq[0] if same_area_eq else equipment[0].get("tag")
|
||||
elif line_items:
|
||||
target_entity = line_items[0].get("tag")
|
||||
closest_line, dist = _find_closest_line_segment_with_dist(ix, iy, traces, line_items, max_dist=0.08)
|
||||
if closest_line:
|
||||
target_entity = closest_line
|
||||
evidence_vec["geometry"] = round(max(0.40, 1.0 - (dist / 0.08) * 0.5), 2)
|
||||
evidence_vec["topology"] = 0.70
|
||||
|
||||
if target_entity:
|
||||
rkey = (itag, target_entity, "MONITORS")
|
||||
geom_c = evidence_vec.get("geometry", 0.0)
|
||||
topo_c = evidence_vec.get("topology", 0.0)
|
||||
sem_c = evidence_vec.get("semantic", 0.0)
|
||||
rel_conf = round(max(0.50, 0.40 * geom_c + 0.30 * topo_c + 0.30 * sem_c), 2)
|
||||
|
||||
rkey = (itag, target_entity, rel_type)
|
||||
if rkey not in existing_rels:
|
||||
existing_rels.add(rkey)
|
||||
relations.append({
|
||||
"source_tag": itag,
|
||||
"target_tag": target_entity,
|
||||
"rel_type": "MONITORS"
|
||||
"rel_type": rel_type,
|
||||
"confidence": rel_conf,
|
||||
"domain": "CONTROL" if rel_type in ("SIGNALS_TO", "CONTROLS") else "PHYSICAL",
|
||||
"evidence_vector": evidence_vec,
|
||||
})
|
||||
|
||||
# C. Map PSVs to Host Piping Lines & Relief Destinations (Eliminates distant equipment false snapping)
|
||||
@@ -433,11 +442,12 @@ def _dist_to_segment(px: float, py: float, x1: float, y1: float, x2: float, y2:
|
||||
return math.hypot(px - proj_x, py - proj_y)
|
||||
|
||||
|
||||
def _find_closest_line_segment(
|
||||
x: float, y: float, traces: List[Dict[str, Any]], line_items: List[Dict[str, Any]], max_dist: float = 0.40
|
||||
) -> Optional[str]:
|
||||
def _find_closest_line_segment_with_dist(
|
||||
x: float, y: float, traces: List[Dict[str, Any]], line_items: List[Dict[str, Any]], max_dist: float = 0.10
|
||||
) -> Tuple[Optional[str], float]:
|
||||
"""
|
||||
Finds the closest line tag using both physical polyline traces and text centroids.
|
||||
Finds the closest line tag using both physical polyline traces and text centroids,
|
||||
returning the matching tag and the exact minimum distance.
|
||||
"""
|
||||
from src.utils.tag_stitcher import safe_float
|
||||
|
||||
@@ -451,7 +461,6 @@ def _find_closest_line_segment(
|
||||
if not tag or not raw_grid_path:
|
||||
continue
|
||||
|
||||
# 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:
|
||||
@@ -475,9 +484,27 @@ def _find_closest_line_segment(
|
||||
|
||||
# Fallback to centroid proximity
|
||||
if not best_tag:
|
||||
best_tag = _find_closest_tag(x, y, line_items, max_dist=max_dist)
|
||||
for item in line_items:
|
||||
tag = item.get("tag")
|
||||
if not tag:
|
||||
continue
|
||||
attrs = item.get("attributes") or {}
|
||||
cx = float(attrs.get("pos_x", 0.5)) if attrs.get("pos_x") else 0.5
|
||||
cy = float(attrs.get("pos_y", 0.5)) if attrs.get("pos_y") else 0.5
|
||||
d = math.hypot(x - cx, y - cy)
|
||||
if d < min_dist:
|
||||
min_dist = d
|
||||
best_tag = tag
|
||||
|
||||
return best_tag
|
||||
return best_tag, min_dist
|
||||
|
||||
|
||||
def _find_closest_line_segment(
|
||||
x: float, y: float, traces: List[Dict[str, Any]], line_items: List[Dict[str, Any]], max_dist: float = 0.40
|
||||
) -> Optional[str]:
|
||||
"""Finds the closest line tag using both physical polyline traces and text centroids."""
|
||||
tag, _ = _find_closest_line_segment_with_dist(x, y, traces, line_items, max_dist=max_dist)
|
||||
return tag
|
||||
|
||||
|
||||
def _find_closest_tag(
|
||||
|
||||
+98
-17
@@ -449,6 +449,51 @@ def _is_setpoint_context_spatial(item_idx: int, all_items: List[Dict[str, Any]])
|
||||
return False
|
||||
|
||||
|
||||
# Operational Reference Context Guard (e.g. FROM 27-PIT-0001B, FROM 26-PIT-9087)
|
||||
_REF_MARKER_RE = re.compile(
|
||||
r'\b(?:FROM|TO|REFER|VENDOR|OFF-SKID|BY\s+MAN|BY\s+PIPING|TIE-IN|CONTINUED\s+ON|SEE\s+DWG|REF\s+DWG|INLET\s+HEADER|DISCHARGE\s+HEADER)\b',
|
||||
re.IGNORECASE
|
||||
)
|
||||
|
||||
|
||||
def _is_reference_context_spatial(item_idx: int, all_items: List[Dict[str, Any]]) -> bool:
|
||||
"""
|
||||
Check whether item at item_idx or any adjacent OCR item (within Y-gap 0.04 and X-gap 0.12)
|
||||
contains operational continuation/reference keywords.
|
||||
"""
|
||||
target = all_items[item_idx]
|
||||
target_text = (target.get('text') or target.get('value') or '').strip()
|
||||
if _REF_MARKER_RE.search(target_text):
|
||||
return True
|
||||
|
||||
t_y = float(target.get('center_y') or (target.get('attributes') or {}).get('pos_y') or -1)
|
||||
t_x = float(target.get('center_x') or (target.get('attributes') or {}).get('pos_x') or -1)
|
||||
|
||||
if t_y < 0 or t_x < 0:
|
||||
return False
|
||||
|
||||
for i, other in enumerate(all_items):
|
||||
if i == item_idx:
|
||||
continue
|
||||
o_text = (other.get('text') or other.get('value') or '').strip()
|
||||
if not o_text:
|
||||
continue
|
||||
o_y = float(other.get('center_y') or (other.get('attributes') or {}).get('pos_y') or -1)
|
||||
o_x = float(other.get('center_x') or (other.get('attributes') or {}).get('pos_x') or -1)
|
||||
if o_y < 0 or o_x < 0:
|
||||
continue
|
||||
|
||||
dy = abs(t_y - o_y)
|
||||
dx = abs(t_x - o_x)
|
||||
|
||||
if dy <= 0.04 and dx <= 0.12:
|
||||
if _REF_MARKER_RE.search(o_text):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
# Defect 4 Fix: Line tag grammar enforcement helpers
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
@@ -576,6 +621,13 @@ def classify_paddle_results(
|
||||
# Pre-pass: stitch fragmented OCR tags and rectify typos
|
||||
items = stitch_fragmented_tags(items)
|
||||
|
||||
# Pre-scan explicit reference callouts across all items (e.g. FROM 27-PIT-0001B, FROM 26-PIT-9087)
|
||||
explicit_ref_tags = set()
|
||||
for it in items:
|
||||
it_txt = it.get('text') or it.get('value') or it.get('tag') or ''
|
||||
for m_ref in re.finditer(r'\b(?:FROM|TO)\s+((?:\d{2}-)?[A-Z]{2,4}-\d{3,5}[A-Z]?)', str(it_txt), re.IGNORECASE):
|
||||
explicit_ref_tags.add(m_ref.group(1).upper())
|
||||
|
||||
found: Dict[str, Dict] = {} # tag → item (deduplicated by EXACT tag string)
|
||||
dt = (drawing_type or 'PID').upper()
|
||||
|
||||
@@ -658,8 +710,8 @@ 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))
|
||||
# Check for operational reference context (e.g. FROM ..., TO ...)
|
||||
is_ref_context = bool(re.search(r'^\s*(?:FROM|TO)\s+', 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):
|
||||
@@ -669,9 +721,12 @@ def classify_paddle_results(
|
||||
tag1 = f"{base_prefix}{suf1}"
|
||||
tag2 = f"{base_prefix}{suf2}"
|
||||
for tag in (tag1, tag2):
|
||||
if tag not in found:
|
||||
tag_is_ref = is_ref_context or (tag in explicit_ref_tags)
|
||||
if tag in found and tag_is_ref:
|
||||
found[tag]["is_reference"] = True
|
||||
elif tag not in found:
|
||||
it_copy = dict(item)
|
||||
if is_ref_context:
|
||||
if tag_is_ref:
|
||||
it_copy["is_reference"] = True
|
||||
found[tag] = _make_item(tag, 'INSTRUMENT_TAG', conf, it_copy)
|
||||
item_added = True
|
||||
@@ -681,9 +736,12 @@ def classify_paddle_results(
|
||||
seq = m.group(1)
|
||||
unit = m.group(2)
|
||||
st_tag = f"{unit}-ST-{seq}"
|
||||
if st_tag not in found:
|
||||
tag_is_ref = is_ref_context or (st_tag in explicit_ref_tags)
|
||||
if st_tag in found and tag_is_ref:
|
||||
found[st_tag]["is_reference"] = True
|
||||
elif st_tag not in found:
|
||||
it_copy = dict(item)
|
||||
if is_ref_context:
|
||||
if tag_is_ref:
|
||||
it_copy["is_reference"] = True
|
||||
found[st_tag] = _make_item(st_tag, 'EQUIPMENT_TAG', conf, it_copy)
|
||||
item_added = True
|
||||
@@ -693,20 +751,29 @@ def classify_paddle_results(
|
||||
full_tag = m.group(1).upper()
|
||||
code = m.group(2).upper()
|
||||
seq = m.group(3)
|
||||
if len(seq) == 6:
|
||||
continue # Drawing reference number, skip
|
||||
# Only skip if sequence is purely numeric 6-digits (drawing reference number e.g. 26-000001-001)
|
||||
if seq.isdigit() and len(seq) == 6:
|
||||
continue
|
||||
# Reject spec codes like GC11S, AS20S embedded in full tag
|
||||
if _SPEC_CODE_PATTERN.match(full_tag) or _SERVICE_CODE_PATTERN.match(full_tag):
|
||||
continue
|
||||
if full_tag in found and found[full_tag]['classification'] != 'NOTE':
|
||||
continue
|
||||
tag_is_ref = is_ref_context or (full_tag in explicit_ref_tags)
|
||||
if full_tag in found:
|
||||
if tag_is_ref:
|
||||
found[full_tag]["is_reference"] = True
|
||||
if found[full_tag]['classification'] != 'NOTE':
|
||||
continue
|
||||
|
||||
_VALVE_FUNCTION_CODES = {
|
||||
'CB', 'GB', 'BL', 'GT', 'BT', 'GL', 'NV', 'BV', 'PL', 'BF', 'CK', 'ND',
|
||||
'HV', 'XV', 'MOV', 'SDV', 'BDV', 'CV', 'PCV', 'TCV', 'FCV', 'LCV', 'ZV', 'EV',
|
||||
'FV', 'PV', 'TV', 'LV', 'AV', 'RV', 'SV', 'DV', 'WV', 'MV', 'BFV', 'PLV', 'PRV'
|
||||
}
|
||||
if code in _VALVE_FUNCTION_CODES and len(re.sub(r'\D', '', seq)) >= 3:
|
||||
num_digits = len(re.sub(r'\D', '', seq))
|
||||
if code == 'CK' and num_digits == 3:
|
||||
# 3-digit CK is a Temporary Commissioning Suction Strainer (Equipment)
|
||||
cat = 'EQUIPMENT_TAG'
|
||||
elif code in _VALVE_FUNCTION_CODES and num_digits >= 3:
|
||||
cat = 'VALVE_TAG'
|
||||
elif code in _EQUIPMENT_CODES:
|
||||
cat = 'EQUIPMENT_TAG'
|
||||
@@ -719,7 +786,7 @@ def classify_paddle_results(
|
||||
|
||||
if full_tag not in found:
|
||||
it_copy = dict(item)
|
||||
if is_ref_context:
|
||||
if tag_is_ref:
|
||||
it_copy["is_reference"] = True
|
||||
found[full_tag] = _make_item(full_tag, cat, conf, it_copy)
|
||||
item_added = True
|
||||
@@ -727,15 +794,18 @@ def classify_paddle_results(
|
||||
# Bare equipment tags without project prefix (e.g. KA-902, KA-901, CX-9021, CX-9011, HA-911, TK-901, FA-9015)
|
||||
for m in _GENERIC_EQUIP_PATTERN.finditer(t):
|
||||
full_tag = m.group(1).upper()
|
||||
code_m = re.match(r'^([A-Z]{1,3})', full_tag)
|
||||
code = code_m.group(1) if code_m else ""
|
||||
prefix_m = re.match(r'^([A-Z]+)-', full_tag)
|
||||
code = prefix_m.group(1) if prefix_m else ""
|
||||
if (code in _EQUIP_PREFIX_ALLOWLIST
|
||||
and not _EQUIP_REJECT_PATTERN.match(full_tag)
|
||||
and not _SPEC_CODE_PATTERN.match(full_tag)
|
||||
and not _SERVICE_CODE_PATTERN.match(full_tag)):
|
||||
if full_tag not in found:
|
||||
tag_is_ref = is_ref_context or (full_tag in explicit_ref_tags)
|
||||
if full_tag in found and tag_is_ref:
|
||||
found[full_tag]["is_reference"] = True
|
||||
elif full_tag not in found:
|
||||
it_copy = dict(item)
|
||||
if is_ref_context:
|
||||
if tag_is_ref:
|
||||
it_copy["is_reference"] = True
|
||||
found[full_tag] = _make_item(full_tag, 'EQUIPMENT_TAG', conf, it_copy)
|
||||
item_added = True
|
||||
@@ -743,7 +813,10 @@ def classify_paddle_results(
|
||||
# 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()
|
||||
tag_is_ref = is_ref_context or (tag in explicit_ref_tags)
|
||||
if tag in found:
|
||||
if tag_is_ref:
|
||||
found[tag]["is_reference"] = True
|
||||
continue
|
||||
seq_num = re.sub(r'\D', '', tag)
|
||||
is_3digit_setpoint = len(seq_num) == 3
|
||||
@@ -756,8 +829,11 @@ def classify_paddle_results(
|
||||
logger.debug(f"Setpoint guard: demoted bare setpoint '{tag}' to NOTE")
|
||||
else:
|
||||
# Real bare instrument tag (e.g. TIT-9025, PIT-9016)
|
||||
it_copy = dict(item)
|
||||
if tag_is_ref:
|
||||
it_copy["is_reference"] = True
|
||||
found[tag] = _make_item(
|
||||
tag, 'INSTRUMENT_TAG', min(conf, 0.85), item
|
||||
tag, 'INSTRUMENT_TAG', min(conf, 0.85), it_copy
|
||||
)
|
||||
item_added = True
|
||||
|
||||
@@ -894,6 +970,10 @@ def classify_paddle_results(
|
||||
winner_item['alarms'] = merged_alarms
|
||||
winner_item['attributes']['alarms'] = ','.join(merged_alarms)
|
||||
|
||||
# Preserve reference flag
|
||||
if loser_item.get('is_reference'):
|
||||
winner_item['is_reference'] = True
|
||||
|
||||
# Preserve coordinates if winner lacks them
|
||||
if not winner_item.get('attributes', {}).get('pos_x') and loser_item.get('attributes', {}).get('pos_x'):
|
||||
winner_item['attributes']['pos_x'] = loser_item['attributes']['pos_x']
|
||||
@@ -985,6 +1065,7 @@ def _make_item(
|
||||
'aliases': [],
|
||||
'alarms': alarms,
|
||||
'sub_component': sub_comp,
|
||||
'is_reference': bool(raw_item.get('is_reference', False)),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -343,8 +343,10 @@ def stitch_symbol_bubbles(items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
cx1 = float(it1.get('center_x', 0))
|
||||
cy1 = float(it1.get('center_y', 0))
|
||||
|
||||
# Skip long notes / descriptions
|
||||
if len(t1) > 16 or any(w in t1.upper() for w in ['NOTE', 'PLEASE', 'TOLERANCE', 'DRAWING', 'VALVES', 'CLOSED VESSEL', 'TEMPERATURE', 'ALL FIXTURES']):
|
||||
# Skip long notes / descriptions / drawing references / continuation callouts or multi-numbers
|
||||
_BUBBLE_EXCLUDE_WORDS = {'NOTE', 'PLEASE', 'TOLERANCE', 'DRAWING', 'DWG', 'VALVES', 'CLOSED VESSEL', 'TEMPERATURE', 'ALL FIXTURES', 'STAGE', 'HEADER', 'INLET', 'OUTLET', 'COMPRESSOR', 'FROM', 'TO', 'REFER'}
|
||||
if (len(t1) > 16 or any(w in t1.upper() for w in _BUBBLE_EXCLUDE_WORDS) or
|
||||
re.search(r'\d{5,}', t1) or re.search(r'\d{3,}\s+\d{3,}', t1)):
|
||||
continue
|
||||
|
||||
# Look for tokens vertically stacked with i (same X column within 0.015, Y gap within 0.038)
|
||||
@@ -355,7 +357,8 @@ def stitch_symbol_bubbles(items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
continue
|
||||
it2 = sorted_items[j]
|
||||
t2 = str(it2.get('text', '')).strip()
|
||||
if len(t2) > 16 or any(w in t2.upper() for w in ['NOTE', 'PLEASE', 'TOLERANCE', 'DRAWING']):
|
||||
if (len(t2) > 16 or any(w in t2.upper() for w in _BUBBLE_EXCLUDE_WORDS) or
|
||||
re.search(r'\d{5,}', t2) or re.search(r'\d{3,}\s+\d{3,}', t2)):
|
||||
continue
|
||||
cx2 = float(it2.get('center_x', 0))
|
||||
cy2 = float(it2.get('center_y', 0))
|
||||
|
||||
Reference in New Issue
Block a user