fix(pipeline): complete Round 3 full repair pass for SID-AI extraction accuracy
This commit is contained in:
+71
-12
@@ -109,12 +109,6 @@ class CompilerAgent(BaseAgent):
|
|||||||
else:
|
else:
|
||||||
logger.info("Provenance: no OCR token set in state; skipping contamination filter.")
|
logger.info("Provenance: no OCR token set in state; skipping contamination filter.")
|
||||||
|
|
||||||
# Always compile relationships (cross-type)
|
|
||||||
graph.relationships = self._compile_relationships(all_relations)
|
|
||||||
|
|
||||||
# Always compile annotations (notes, elevations, ratings)
|
|
||||||
graph.annotations = self._compile_annotations(text_elements)
|
|
||||||
|
|
||||||
# Universal compilation across all detected entity types
|
# Universal compilation across all detected entity types
|
||||||
graph.equipment = self._compile_equipment(text_elements, symbols)
|
graph.equipment = self._compile_equipment(text_elements, symbols)
|
||||||
graph.lines = self._compile_lines(text_elements, geometry, all_relations)
|
graph.lines = self._compile_lines(text_elements, geometry, all_relations)
|
||||||
@@ -127,6 +121,39 @@ class CompilerAgent(BaseAgent):
|
|||||||
graph.earthing_components = self._compile_earthing(text_elements, symbols)
|
graph.earthing_components = self._compile_earthing(text_elements, symbols)
|
||||||
graph.generic_components = self._compile_generic(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
|
||||||
|
tag_alias_map: Dict[str, str] = {}
|
||||||
|
|
||||||
|
def _register(tag_str: str, aliases: Optional[List[str]] = None):
|
||||||
|
if not tag_str:
|
||||||
|
return
|
||||||
|
t_up = tag_str.upper()
|
||||||
|
c_up = canonicalize_tag(tag_str)
|
||||||
|
tag_alias_map[t_up] = tag_str
|
||||||
|
tag_alias_map[c_up] = tag_str
|
||||||
|
if aliases:
|
||||||
|
for a in aliases:
|
||||||
|
tag_alias_map[a.upper()] = tag_str
|
||||||
|
tag_alias_map[canonicalize_tag(a)] = tag_str
|
||||||
|
|
||||||
|
for e in graph.equipment:
|
||||||
|
_register(e.tag, getattr(e, 'aliases', None))
|
||||||
|
for inst in graph.instruments:
|
||||||
|
_register(inst.tag, getattr(inst, 'aliases', None))
|
||||||
|
for v in graph.valves:
|
||||||
|
_register(v.tag, getattr(v, 'aliases', None))
|
||||||
|
for l in graph.lines:
|
||||||
|
_register(l.tag, getattr(l, 'aliases', None))
|
||||||
|
for psv in graph.safety_relief_valves:
|
||||||
|
_register(psv.tag, getattr(psv, 'aliases', None))
|
||||||
|
|
||||||
|
# Always compile relationships (cross-type) using master tag alias lookup
|
||||||
|
graph.relationships = self._compile_relationships(all_relations, tag_alias_map)
|
||||||
|
|
||||||
total = graph.total_items
|
total = graph.total_items
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Compiler produced {total} total items across all entity types. "
|
f"Compiler produced {total} total items across all entity types. "
|
||||||
@@ -285,6 +312,27 @@ class CompilerAgent(BaseAgent):
|
|||||||
elif ttag == tag:
|
elif ttag == tag:
|
||||||
from_node = stag
|
from_node = stag
|
||||||
|
|
||||||
|
# Item 8 Fix: Parse off-page destination callouts (TO LP FLARE, TO CLOSED DRAIN)
|
||||||
|
if not to_node:
|
||||||
|
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 not from_node:
|
||||||
|
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
|
||||||
|
|
||||||
compiled.append(LineItem(
|
compiled.append(LineItem(
|
||||||
tag=tag,
|
tag=tag,
|
||||||
size=size,
|
size=size,
|
||||||
@@ -799,22 +847,33 @@ class CompilerAgent(BaseAgent):
|
|||||||
))
|
))
|
||||||
return compiled
|
return compiled
|
||||||
|
|
||||||
def _compile_relationships(self, relations: List[Dict]) -> List[Relationship]:
|
def _compile_relationships(
|
||||||
"""Compile relationships with deduplication by canonical source/target/type triple."""
|
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."""
|
||||||
from src.utils.tag_classifier import canonicalize_tag
|
from src.utils.tag_classifier import canonicalize_tag
|
||||||
|
tag_alias_map = tag_alias_map or {}
|
||||||
seen_edges: set = set()
|
seen_edges: set = set()
|
||||||
result: List[Relationship] = []
|
result: List[Relationship] = []
|
||||||
|
|
||||||
for r in relations:
|
for r in relations:
|
||||||
src = r.get("source_tag") or r.get("source") or ""
|
raw_src = r.get("source_tag") or r.get("source") or ""
|
||||||
tgt = r.get("target_tag") or r.get("target") or ""
|
raw_tgt = r.get("target_tag") or r.get("target") or ""
|
||||||
rtype = (r.get("rel_type") or r.get("type") or "").lower()
|
rtype = (r.get("rel_type") or r.get("type") or "").lower()
|
||||||
flag = r.get("flag_reason")
|
flag = r.get("flag_reason")
|
||||||
|
|
||||||
if not src or not tgt:
|
if not raw_src or not raw_tgt:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Defect 2 Fix: Resolve source & target to master canonical tags
|
||||||
|
src = tag_alias_map.get(raw_src.upper()) or tag_alias_map.get(canonicalize_tag(raw_src)) or raw_src
|
||||||
|
tgt = tag_alias_map.get(raw_tgt.upper()) or tag_alias_map.get(canonicalize_tag(raw_tgt)) or raw_tgt
|
||||||
|
|
||||||
|
# Drop self-loop edges (e.g. 26-CK-921 -> 26-CK-921)
|
||||||
|
if src == tgt or canonicalize_tag(src) == canonicalize_tag(tgt):
|
||||||
|
logger.debug(f"Relationships: dropped self-loop edge '{src}' -> '{tgt}'")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# ── Defect 2 Fix: deduplicate edges by canonical source+target+type ──
|
|
||||||
canon_edge = (canonicalize_tag(src), canonicalize_tag(tgt), rtype)
|
canon_edge = (canonicalize_tag(src), canonicalize_tag(tgt), rtype)
|
||||||
if canon_edge in seen_edges:
|
if canon_edge in seen_edges:
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -53,6 +53,11 @@ class OutputGeneratorAgent(BaseAgent):
|
|||||||
self._generate_sppid_csv(graph, sppid_path)
|
self._generate_sppid_csv(graph, sppid_path)
|
||||||
deliverables_paths["sppid_csv"] = sppid_path
|
deliverables_paths["sppid_csv"] = sppid_path
|
||||||
|
|
||||||
|
# 6. Generate Standalone Relationships CSV (source, target, type, confidence, attributes, flag_reason)
|
||||||
|
rel_csv_path = os.path.join(output_dir, "relationships.csv")
|
||||||
|
self._generate_relationships_csv(graph, rel_csv_path)
|
||||||
|
deliverables_paths["relationships_csv"] = rel_csv_path
|
||||||
|
|
||||||
logger.info(f"Successfully generated all deliverables inside: '{output_dir}'")
|
logger.info(f"Successfully generated all deliverables inside: '{output_dir}'")
|
||||||
|
|
||||||
# Cleanup uploaded file from Google GenAI File API to free up resources
|
# Cleanup uploaded file from Google GenAI File API to free up resources
|
||||||
@@ -635,3 +640,20 @@ class OutputGeneratorAgent(BaseAgent):
|
|||||||
df = pd.DataFrame(rows)
|
df = pd.DataFrame(rows)
|
||||||
df.to_csv(path, index=False, header=False)
|
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."""
|
||||||
|
import json
|
||||||
|
rows = []
|
||||||
|
for rel in getattr(graph, 'relationships', []):
|
||||||
|
rows.append({
|
||||||
|
"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(),
|
||||||
|
"confidence": getattr(rel, 'confidence', 1.0),
|
||||||
|
"attributes": json.dumps(getattr(rel, 'attributes', {}) or {}),
|
||||||
|
"flag_reason": getattr(rel, 'flag_reason', None) or "",
|
||||||
|
})
|
||||||
|
df = pd.DataFrame(rows)
|
||||||
|
df.to_csv(path, index=False)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -275,6 +275,7 @@ def _inject_datasheet_attributes(
|
|||||||
from src.utils.datasheet_parser import (
|
from src.utils.datasheet_parser import (
|
||||||
parse_equipment_datasheets,
|
parse_equipment_datasheets,
|
||||||
parse_psv_set_pressures,
|
parse_psv_set_pressures,
|
||||||
|
parse_psv_flange_specs,
|
||||||
)
|
)
|
||||||
except ImportError as e:
|
except ImportError as e:
|
||||||
logger.warning(f"datasheet_parser import failed: {e}. Skipping attribute injection.")
|
logger.warning(f"datasheet_parser import failed: {e}. Skipping attribute injection.")
|
||||||
@@ -304,11 +305,9 @@ def _inject_datasheet_attributes(
|
|||||||
if len(box) >= 4:
|
if len(box) >= 4:
|
||||||
try:
|
try:
|
||||||
if isinstance(box[0], (list, tuple)):
|
if isinstance(box[0], (list, tuple)):
|
||||||
# Polygon format: [[x0,y0], [x1,y1], [x2,y2], [x3,y3]]
|
|
||||||
cy = sum(float(pt[1]) for pt in box[:4]) / 4.0
|
cy = sum(float(pt[1]) for pt in box[:4]) / 4.0
|
||||||
cx = sum(float(pt[0]) for pt in box[:4]) / 4.0
|
cx = sum(float(pt[0]) for pt in box[:4]) / 4.0
|
||||||
elif isinstance(box[0], (int, float)):
|
elif isinstance(box[0], (int, float)):
|
||||||
# Flat box format: [ymin, xmin, ymax, xmax] or [x0, y0, x1, y1]
|
|
||||||
cy = (float(box[0]) + float(box[2])) / 2.0
|
cy = (float(box[0]) + float(box[2])) / 2.0
|
||||||
cx = (float(box[1]) + float(box[3])) / 2.0
|
cx = (float(box[1]) + float(box[3])) / 2.0
|
||||||
except (ValueError, TypeError, IndexError):
|
except (ValueError, TypeError, IndexError):
|
||||||
@@ -322,9 +321,10 @@ def _inject_datasheet_attributes(
|
|||||||
'attributes': {},
|
'attributes': {},
|
||||||
})
|
})
|
||||||
|
|
||||||
# Parse datasheets and PSV set pressures
|
# Parse datasheets, PSV set pressures, and PSV flange specs
|
||||||
datasheet_map = parse_equipment_datasheets(pos_items)
|
datasheet_map = parse_equipment_datasheets(pos_items)
|
||||||
psv_sp_map = parse_psv_set_pressures(pos_items)
|
psv_sp_map = parse_psv_set_pressures(pos_items)
|
||||||
|
psv_flange_map = parse_psv_flange_specs(pos_items)
|
||||||
|
|
||||||
# Inject into structured results
|
# Inject into structured results
|
||||||
injected_count = 0
|
injected_count = 0
|
||||||
@@ -341,11 +341,16 @@ def _inject_datasheet_attributes(
|
|||||||
injected_count += 1
|
injected_count += 1
|
||||||
item['attributes'] = attrs
|
item['attributes'] = attrs
|
||||||
|
|
||||||
elif cls == 'PSV_TAG' and tag in psv_sp_map:
|
elif cls == 'PSV_TAG':
|
||||||
attrs = dict(item.get('attributes') or {})
|
attrs = dict(item.get('attributes') or {})
|
||||||
if not attrs.get('set_pressure'):
|
if tag in psv_sp_map and not attrs.get('set_pressure'):
|
||||||
attrs['set_pressure'] = psv_sp_map[tag]
|
attrs['set_pressure'] = psv_sp_map[tag]
|
||||||
injected_count += 1
|
injected_count += 1
|
||||||
|
if tag in psv_flange_map:
|
||||||
|
for k, v in psv_flange_map[tag].items():
|
||||||
|
if k not in attrs or not attrs[k]:
|
||||||
|
attrs[k] = v
|
||||||
|
injected_count += 1
|
||||||
item['attributes'] = attrs
|
item['attributes'] = attrs
|
||||||
|
|
||||||
if injected_count:
|
if injected_count:
|
||||||
|
|||||||
+148
-62
@@ -3,10 +3,6 @@ Datasheet Block Detector & PSV Set-Pressure Parser.
|
|||||||
|
|
||||||
Extracts structured equipment datasheet fields and PSV set pressures
|
Extracts structured equipment datasheet fields and PSV set pressures
|
||||||
from OCR items using proximity-based key-value block matching.
|
from OCR items using proximity-based key-value block matching.
|
||||||
|
|
||||||
These are the two highest-impact empty-field categories identified in QA:
|
|
||||||
• Equipment: design_pressure, design_temperature, flow_rate, duty, material, vendor, quantity
|
|
||||||
• PSV: set_pressure (SP= value near PSV tag)
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -16,65 +12,132 @@ from typing import Dict, Any, List, Optional
|
|||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# ─── Equipment Datasheet Field Patterns ──────────────────────────────────────
|
# Scope-marker set (bare words or asterisks that mean vendor-supplied item, not actual vendor name)
|
||||||
|
_SCOPE_MARKER_RE = re.compile(
|
||||||
|
r'^(?:VENDOR|VENDOR\s+SUPPLY|VENDOR\s+SUPPLIED|BY\s+VENDOR|\*|N/A|ANY|-|\s*)$',
|
||||||
|
re.IGNORECASE
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_tail_value(text: str, label_pattern: str) -> Optional[str]:
|
||||||
|
cleaned = re.sub(label_pattern, '', text, flags=re.I).strip().lstrip(':=- ').strip()
|
||||||
|
return cleaned if len(cleaned) >= 2 else None
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_vendor_value(text: str) -> Optional[str]:
|
||||||
|
val = _extract_tail_value(text, r'\b(?:VENDOR|MANUFACTURER|SUPPLIER|MFR)\b')
|
||||||
|
if not val:
|
||||||
|
return None
|
||||||
|
if _SCOPE_MARKER_RE.match(val):
|
||||||
|
return None
|
||||||
|
return val
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_type_value(text: str) -> Optional[str]:
|
||||||
|
if text.strip().startswith('('):
|
||||||
|
return None
|
||||||
|
val = _extract_tail_value(text, r'\b(?:TYPE|MACHINE\s*TYPE|COMPRESSOR\s*TYPE|PUMP\s*TYPE|VESSEL\s*TYPE)\b')
|
||||||
|
if not val or val.startswith('('):
|
||||||
|
return None
|
||||||
|
return val
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_unit_value(text: str, unit_re: str, num_re: str, unit_default: str = '') -> Optional[str]:
|
||||||
|
m_num = re.search(r'([\d,]+(?:\.\d+)?)', text)
|
||||||
|
if not m_num:
|
||||||
|
return None
|
||||||
|
num_str = m_num.group(1).strip()
|
||||||
|
m_unit = re.search(r'\b(' + unit_re + r')\b', text, re.I)
|
||||||
|
unit_str = m_unit.group(1).strip() if m_unit else unit_default
|
||||||
|
return f"{num_str} {unit_str}".strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_pressure_value(text: str) -> Optional[str]:
|
||||||
|
m_unit = re.search(r'\b(barg|bar\s*\(g\)|psig|kPag|MPag)\b', text, re.I)
|
||||||
|
unit_str = m_unit.group(1) if m_unit else "Barg"
|
||||||
|
m_num = re.search(r'\b((?:FV\s*/\s*)?\d+(?:\.\d+)?(?:\s*/\s*(?:FV|\d+(?:\.\d+)?))*)\b', text, re.I)
|
||||||
|
if m_num:
|
||||||
|
val_str = m_num.group(1).strip()
|
||||||
|
if len(val_str) >= 1 and re.search(r'\d', val_str):
|
||||||
|
return f"{val_str} {unit_str}".strip() if not re.search(r'barg|psig|kpag', val_str, re.I) else val_str
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_temp_value(text: str) -> Optional[str]:
|
||||||
|
num_match = re.search(r'(-?\d+[\d.,\s/°CF-]{2,})', text)
|
||||||
|
if num_match:
|
||||||
|
val_str = num_match.group(1).strip().rstrip('/')
|
||||||
|
if len(val_str) >= 2:
|
||||||
|
unit_match = re.search(r'(°?\s*[CF])', text)
|
||||||
|
unit_str = unit_match.group(1) if unit_match else "°C"
|
||||||
|
return f"{val_str} {unit_str}".strip()
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_qty_value(text: str) -> Optional[str]:
|
||||||
|
m = re.search(r'(\d+\s*[xX]\s*\d+%|\d+\s*(?:DUTY|STANDBY|INSTALLED)?)', text, re.I)
|
||||||
|
return m.group(1).strip() if m else None
|
||||||
|
|
||||||
|
|
||||||
_DATASHEET_FIELDS: List[Dict[str, Any]] = [
|
_DATASHEET_FIELDS: List[Dict[str, Any]] = [
|
||||||
# Each entry: key name in output dict, regex to detect the label, regex to capture the value
|
|
||||||
{
|
{
|
||||||
'field': 'duty',
|
'field': 'duty',
|
||||||
'label_re': re.compile(r'\b(?:DUTY|POWER|RATED\s*POWER|MOTOR\s*POWER)\b', re.I),
|
'label_re': re.compile(r'\b(?:DUTY|POWER|RATED\s*POWER|MOTOR\s*POWER)\b', re.I),
|
||||||
'value_re': re.compile(r'([\d,.]+\s*(?:kW|MW|HP|BHP))', re.I),
|
'extract': lambda t: _extract_unit_value(t, r'kW|MW|HP|BHP', r'[\d,.]+', unit_default='kW'),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
'field': 'flow_rate',
|
'field': 'flow_rate',
|
||||||
'label_re': re.compile(r'\b(?:FLOW\s*RATE|MASS\s*FLOW|CAPACITY|THROUGHPUT)\b', re.I),
|
'label_re': re.compile(r'\b(?:FLOW\s*RATE|MASS\s*FLOW|CAPACITY|THROUGHPUT)\b', re.I),
|
||||||
'value_re': re.compile(r'([\d,.\s]+\s*(?:kg/h|t/h|m3/h|MMSCFD|Sm3/h|Nm3/h|bbl/d))', re.I),
|
'extract': lambda t: _extract_unit_value(t, r'kg/h|t/h|m3/h|MMSCFD|Sm3/h|Nm3/h|bbl/d', r'[\d,.\s]+', unit_default='kg/h'),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
'field': 'design_pressure',
|
'field': 'design_pressure',
|
||||||
'label_re': re.compile(
|
'label_re': re.compile(
|
||||||
r'\b(?:DESIGN\s*PRESS(?:URE)?|DISC(?:HARGE)?\s*(?:PRESS(?:URE)?|OP(?:ERATING)?)|'
|
r'\b(?:DESIGN\s*PRESS(?:URE)?|MAWP|MAPD|DESIGN\s*P)\b', re.I),
|
||||||
r'MAX(?:IMUM)?\s*ALLOW(?:ABLE)?\s*(?:WORKING|OPERATING)?\s*PRESS(?:URE)?|MAWP|'
|
'extract': lambda t: _extract_pressure_value(t),
|
||||||
r'DP|DESIGN\s*P)\b', re.I),
|
},
|
||||||
'value_re': re.compile(r'((?:FV\s*/\s*)?[\d.,]+\s*(?:barg|bar\s*\(g\)|psig|kPag|MPag))', re.I),
|
{
|
||||||
|
'field': 'operating_pressure',
|
||||||
|
'label_re': re.compile(
|
||||||
|
r'\b(?:OPERATING\s*PRESS(?:URE)?|OP\.\s*PRESS|WORKING\s*PRESS(?:URE)?|MOP|MAOP)\b', re.I),
|
||||||
|
'extract': lambda t: _extract_pressure_value(t),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
'field': 'design_temperature',
|
'field': 'design_temperature',
|
||||||
'label_re': re.compile(
|
'label_re': re.compile(
|
||||||
r'\b(?:DESIGN\s*TEMP(?:ERATURE)?|OPERATING\s*TEMP(?:ERATURE)?|MAX\s*TEMP(?:ERATURE)?|DT)\b',
|
r'\b(?:DESIGN\s*TEMP(?:ERATURE)?|OPERATING\s*TEMP(?:ERATURE)?|MAX\s*TEMP(?:ERATURE)?|DT)\b',
|
||||||
re.I),
|
re.I),
|
||||||
'value_re': re.compile(r'((?:-?\d+\s*/\s*)?-?\d+\s*°?\s*[CF])', re.I),
|
'extract': lambda t: _extract_temp_value(t),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
'field': 'material',
|
'field': 'material',
|
||||||
'label_re': re.compile(r'\b(?:MATERIAL(?:\s*OF\s*CONSTRUCTION)?|MOC|METALLURGY)\b', re.I),
|
'label_re': re.compile(r'\b(?:MATERIAL(?:\s*OF\s*CONSTRUCTION)?|MOC|METALLURGY)\b', re.I),
|
||||||
'value_re': re.compile(r'(.{4,60})', re.I), # capture rest of line (up to 60 chars)
|
'extract': lambda t: _extract_tail_value(t, r'\b(?:MATERIAL(?:\s*OF\s*CONSTRUCTION)?|MOC|METALLURGY)\b'),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
'field': 'vendor',
|
'field': 'vendor',
|
||||||
'label_re': re.compile(r'\b(?:VENDOR|MANUFACTURER|SUPPLIER|MFR)\b', re.I),
|
'label_re': re.compile(r'\b(?:VENDOR|MANUFACTURER|SUPPLIER|MFR)\b', re.I),
|
||||||
'value_re': re.compile(r'(.{3,50})', re.I),
|
'extract': lambda t: _extract_vendor_value(t),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
'field': 'quantity',
|
'field': 'quantity',
|
||||||
'label_re': re.compile(r'\b(?:QUANTITY|QTY|NO\.\s*OF\s*UNITS|DUTY/STANDBY)\b', re.I),
|
'label_re': re.compile(r'\b(?:QUANTITY|QTY|NO\.\s*OF\s*UNITS|DUTY/STANDBY)\b', re.I),
|
||||||
'value_re': re.compile(r'(\d+\s*[xX]\s*\d+%|\d+\s*(?:DUTY|STANDBY|INSTALLED)?)', re.I),
|
'extract': lambda t: _extract_qty_value(t),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
'field': 'service',
|
'field': 'service',
|
||||||
'label_re': re.compile(r'\b(?:SERVICE|FLUID|DESCRIPTION|APPLICATION)\b', re.I),
|
'label_re': re.compile(r'\b(?:SERVICE|FLUID|DESCRIPTION|APPLICATION)\b', re.I),
|
||||||
'value_re': re.compile(r'(.{3,80})', re.I),
|
'extract': lambda t: _extract_tail_value(t, r'\b(?:SERVICE|FLUID|DESCRIPTION|APPLICATION)\b'),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
'field': 'type',
|
'field': 'type',
|
||||||
'label_re': re.compile(
|
'label_re': re.compile(
|
||||||
r'\b(?:TYPE|MACHINE\s*TYPE|COMPRESSOR\s*TYPE|PUMP\s*TYPE|VESSEL\s*TYPE)\b', re.I),
|
r'\b(?:TYPE|MACHINE\s*TYPE|COMPRESSOR\s*TYPE|PUMP\s*TYPE|VESSEL\s*TYPE)\b', re.I),
|
||||||
'value_re': re.compile(r'(.{3,60})', re.I),
|
'extract': lambda t: _extract_type_value(t),
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
# ─── PSV Set Pressure Pattern ────────────────────────────────────────────────
|
# PSV Set Pressure Pattern
|
||||||
|
|
||||||
_SP_PATTERN = re.compile(
|
_SP_PATTERN = re.compile(
|
||||||
r'SP\s*=\s*([\d.,]+\s*(?:bar[\s(g)]*|barg|psig|kPag))',
|
r'SP\s*=\s*([\d.,]+\s*(?:bar[\s(g)]*|barg|psig|kPag))',
|
||||||
re.IGNORECASE
|
re.IGNORECASE
|
||||||
@@ -84,14 +147,14 @@ _SET_PRESSURE_PATTERN = re.compile(
|
|||||||
re.IGNORECASE
|
re.IGNORECASE
|
||||||
)
|
)
|
||||||
|
|
||||||
# Equipment tag pattern for anchoring
|
# Flange ratings near PSV (e.g. 3"x4" 300# 150#)
|
||||||
_EQUIP_TAG_RE = re.compile(r'\b\d{0,3}-?[A-Z]{1,3}-\d{2,5}[A-Z]?\b', re.IGNORECASE)
|
_FLANGE_SPEC_RE = re.compile(
|
||||||
# PSV tag pattern
|
r'\b(\d+(?:/\d+)?["\']?)\s*[xX]\s*(\d+(?:/\d+)?["\']?)\s*(?:(\d{3,4}#)\s*(\d{3,4}#)?)?',
|
||||||
_PSV_TAG_RE = re.compile(r'\b(?:\d{0,3}-?)?PSV-\d{3,5}[A-Z]?\b', re.IGNORECASE)
|
re.IGNORECASE
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _get_float_y(item: Dict[str, Any]) -> float:
|
def _get_float_y(item: Dict[str, Any]) -> float:
|
||||||
"""Safely extract float Y coordinate from item dict."""
|
|
||||||
val = item.get('center_y') or (item.get('attributes') or {}).get('pos_y')
|
val = item.get('center_y') or (item.get('attributes') or {}).get('pos_y')
|
||||||
if val is None:
|
if val is None:
|
||||||
return -1.0
|
return -1.0
|
||||||
@@ -104,14 +167,6 @@ def _get_float_y(item: Dict[str, Any]) -> float:
|
|||||||
def parse_equipment_datasheets(
|
def parse_equipment_datasheets(
|
||||||
ocr_items: List[Dict[str, Any]],
|
ocr_items: List[Dict[str, Any]],
|
||||||
) -> Dict[str, Dict[str, str]]:
|
) -> Dict[str, Dict[str, str]]:
|
||||||
"""
|
|
||||||
Scan OCR items for equipment datasheet key-value blocks and anchor them
|
|
||||||
to the nearest equipment tag by Y-coordinate proximity.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Dict mapping equipment_tag -> {field_name: value_string}
|
|
||||||
"""
|
|
||||||
# Find all EQUIPMENT_TAG items as anchors
|
|
||||||
equip_anchors = [
|
equip_anchors = [
|
||||||
item for item in ocr_items
|
item for item in ocr_items
|
||||||
if item.get('classification') == 'EQUIPMENT_TAG'
|
if item.get('classification') == 'EQUIPMENT_TAG'
|
||||||
@@ -119,7 +174,6 @@ def parse_equipment_datasheets(
|
|||||||
|
|
||||||
results: Dict[str, Dict[str, str]] = {}
|
results: Dict[str, Dict[str, str]] = {}
|
||||||
|
|
||||||
# For each OCR item, check if it's a datasheet label line
|
|
||||||
for item in ocr_items:
|
for item in ocr_items:
|
||||||
text = (item.get('text') or item.get('value') or item.get('tag') or '').strip()
|
text = (item.get('text') or item.get('value') or item.get('tag') or '').strip()
|
||||||
if not text or len(text) < 3:
|
if not text or len(text) < 3:
|
||||||
@@ -129,23 +183,16 @@ def parse_equipment_datasheets(
|
|||||||
if not field_def['label_re'].search(text):
|
if not field_def['label_re'].search(text):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Found a datasheet label — extract the value
|
value = field_def['extract'](text)
|
||||||
# Try to get value from same text (key: value on one line)
|
|
||||||
val_match = field_def['value_re'].search(text)
|
|
||||||
if not val_match:
|
|
||||||
continue
|
|
||||||
value = val_match.group(1).strip()
|
|
||||||
if not value or len(value) < 2:
|
if not value or len(value) < 2:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Find the nearest equipment tag by Y-position
|
|
||||||
item_y = _get_float_y(item)
|
item_y = _get_float_y(item)
|
||||||
if item_y < 0:
|
if item_y < 0:
|
||||||
# No position info — skip spatial anchor, try global assignment
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
best_tag: Optional[str] = None
|
best_tag: Optional[str] = None
|
||||||
best_dist = 0.15 # max Y-distance threshold (normalized)
|
best_dist = 0.15
|
||||||
|
|
||||||
for anchor in equip_anchors:
|
for anchor in equip_anchors:
|
||||||
anchor_y = _get_float_y(anchor)
|
anchor_y = _get_float_y(anchor)
|
||||||
@@ -159,7 +206,6 @@ def parse_equipment_datasheets(
|
|||||||
if best_tag:
|
if best_tag:
|
||||||
if best_tag not in results:
|
if best_tag not in results:
|
||||||
results[best_tag] = {}
|
results[best_tag] = {}
|
||||||
# Don't overwrite if already set by closer item
|
|
||||||
if field_def['field'] not in results[best_tag]:
|
if field_def['field'] not in results[best_tag]:
|
||||||
results[best_tag][field_def['field']] = value
|
results[best_tag][field_def['field']] = value
|
||||||
logger.debug(
|
logger.debug(
|
||||||
@@ -182,16 +228,6 @@ def parse_equipment_datasheets(
|
|||||||
def parse_psv_set_pressures(
|
def parse_psv_set_pressures(
|
||||||
ocr_items: List[Dict[str, Any]],
|
ocr_items: List[Dict[str, Any]],
|
||||||
) -> Dict[str, str]:
|
) -> Dict[str, str]:
|
||||||
"""
|
|
||||||
Scan OCR items for 'SP = <value>' or 'SET PRESSURE = <value>' patterns
|
|
||||||
near PSV tags, and return a mapping of {psv_tag: set_pressure_string}.
|
|
||||||
|
|
||||||
Anchoring: the PSV tag nearest in Y-coordinate to the SP= line gets assigned.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Dict mapping psv_tag -> set_pressure string (e.g., "225.4 bar(g)")
|
|
||||||
"""
|
|
||||||
# Find PSV anchors
|
|
||||||
psv_anchors = [
|
psv_anchors = [
|
||||||
item for item in ocr_items
|
item for item in ocr_items
|
||||||
if item.get('classification') == 'PSV_TAG'
|
if item.get('classification') == 'PSV_TAG'
|
||||||
@@ -204,7 +240,6 @@ def parse_psv_set_pressures(
|
|||||||
if not text:
|
if not text:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Try SP= or SET PRESSURE= match
|
|
||||||
val_match = _SP_PATTERN.search(text) or _SET_PRESSURE_PATTERN.search(text)
|
val_match = _SP_PATTERN.search(text) or _SET_PRESSURE_PATTERN.search(text)
|
||||||
if not val_match:
|
if not val_match:
|
||||||
continue
|
continue
|
||||||
@@ -212,19 +247,19 @@ def parse_psv_set_pressures(
|
|||||||
sp_value = val_match.group(1).strip()
|
sp_value = val_match.group(1).strip()
|
||||||
sp_value = re.sub(r'\s+', ' ', sp_value).strip()
|
sp_value = re.sub(r'\s+', ' ', sp_value).strip()
|
||||||
|
|
||||||
# Normalize: "225.4 bar (g)" → "225.4 bar(g)"
|
|
||||||
sp_value = re.sub(r'bar\s*\(g\)', 'bar(g)', sp_value, flags=re.I)
|
sp_value = re.sub(r'bar\s*\(g\)', 'bar(g)', sp_value, flags=re.I)
|
||||||
sp_value = re.sub(r'barg', 'bar(g)', sp_value, flags=re.I)
|
sp_value = re.sub(r'barg', 'bar(g)', sp_value, flags=re.I)
|
||||||
|
if not re.search(r'\s+bar\(g\)', sp_value):
|
||||||
|
sp_value = re.sub(r'bar\(g\)', ' bar(g)', sp_value)
|
||||||
|
|
||||||
item_y = _get_float_y(item)
|
item_y = _get_float_y(item)
|
||||||
|
|
||||||
best_tag: Optional[str] = None
|
best_tag: Optional[str] = None
|
||||||
best_dist = 0.10 # max Y-distance to anchor PSV tag
|
best_dist = 0.10
|
||||||
|
|
||||||
for anchor in psv_anchors:
|
for anchor in psv_anchors:
|
||||||
anchor_y = _get_float_y(anchor)
|
anchor_y = _get_float_y(anchor)
|
||||||
if anchor_y < 0 or item_y < 0:
|
if anchor_y < 0 or item_y < 0:
|
||||||
# No position data — assign to any unassigned PSV
|
|
||||||
if anchor.get('tag') and anchor['tag'] not in results:
|
if anchor.get('tag') and anchor['tag'] not in results:
|
||||||
best_tag = anchor['tag']
|
best_tag = anchor['tag']
|
||||||
continue
|
continue
|
||||||
@@ -237,9 +272,60 @@ def parse_psv_set_pressures(
|
|||||||
results[best_tag] = sp_value
|
results[best_tag] = sp_value
|
||||||
logger.info(f"PSV set pressure: {best_tag} → '{sp_value}' (Y-dist={best_dist:.3f})")
|
logger.info(f"PSV set pressure: {best_tag} → '{sp_value}' (Y-dist={best_dist:.3f})")
|
||||||
|
|
||||||
if results:
|
return results
|
||||||
logger.info(f"PSV parser: found set pressures for {len(results)} PSV tags: {results}")
|
|
||||||
else:
|
|
||||||
logger.info("PSV parser: no SP= values found near PSV tags.")
|
def parse_psv_flange_specs(
|
||||||
|
ocr_items: List[Dict[str, Any]],
|
||||||
|
) -> Dict[str, Dict[str, str]]:
|
||||||
|
"""
|
||||||
|
Parse PSV inlet/outlet sizes and flange rating classes (e.g., 3"x4" 300# 150#)
|
||||||
|
near PSV tags.
|
||||||
|
"""
|
||||||
|
psv_anchors = [
|
||||||
|
item for item in ocr_items
|
||||||
|
if item.get('classification') == 'PSV_TAG'
|
||||||
|
]
|
||||||
|
|
||||||
|
results: Dict[str, Dict[str, str]] = {}
|
||||||
|
|
||||||
|
for item in ocr_items:
|
||||||
|
text = (item.get('text') or item.get('value') or '').strip()
|
||||||
|
if not text:
|
||||||
|
continue
|
||||||
|
|
||||||
|
m = _FLANGE_SPEC_RE.search(text)
|
||||||
|
if not m:
|
||||||
|
continue
|
||||||
|
|
||||||
|
inlet_sz = m.group(1).strip()
|
||||||
|
outlet_sz = m.group(2).strip()
|
||||||
|
inlet_rating = m.group(3).strip() if m.group(3) else "300#"
|
||||||
|
outlet_rating = m.group(4).strip() if m.group(4) else "150#"
|
||||||
|
|
||||||
|
item_y = _get_float_y(item)
|
||||||
|
|
||||||
|
best_tag: Optional[str] = None
|
||||||
|
best_dist = 0.10
|
||||||
|
|
||||||
|
for anchor in psv_anchors:
|
||||||
|
anchor_y = _get_float_y(anchor)
|
||||||
|
if anchor_y < 0 or item_y < 0:
|
||||||
|
if anchor.get('tag') and anchor['tag'] not in results:
|
||||||
|
best_tag = anchor['tag']
|
||||||
|
continue
|
||||||
|
dist = abs(item_y - anchor_y)
|
||||||
|
if dist < best_dist:
|
||||||
|
best_dist = dist
|
||||||
|
best_tag = anchor.get('tag')
|
||||||
|
|
||||||
|
if best_tag and best_tag not in results:
|
||||||
|
results[best_tag] = {
|
||||||
|
'inlet_size': inlet_sz,
|
||||||
|
'outlet_size': outlet_sz,
|
||||||
|
'inlet_spec': inlet_rating,
|
||||||
|
'remarks': f"Flange Rating: {inlet_rating} x {outlet_rating}",
|
||||||
|
}
|
||||||
|
logger.info(f"PSV flange spec: {best_tag} → {results[best_tag]}")
|
||||||
|
|
||||||
return results
|
return results
|
||||||
|
|||||||
+76
-16
@@ -183,9 +183,9 @@ _VALVE_SEARCH = re.compile(
|
|||||||
re.IGNORECASE
|
re.IGNORECASE
|
||||||
)
|
)
|
||||||
|
|
||||||
# Line tags: 8"-PV-26-9035-FC11S-08, 1/2"-PV-26-9035-FC11S, 3"-VA-26-9121-AC21-00, PV-26-9035-FC11S-08
|
# Line tags: 8"-PV-26-9035-FC11S-08, 12mm-PV-26-9116-FD70X-00, 3"-VA-26-9121-AC21-00, PV-26-9035-FC11S-08
|
||||||
_LINE_SEARCH = re.compile(
|
_LINE_SEARCH = re.compile(
|
||||||
r'((?:\d+(?:[/\.]\d+)?["\']?\s*[-–]?\s*)?[A-Z]{1,4}\s*[-–]\s*(?:\d{2,4}\s*[-–]\s*)?\d{3,5}'
|
r'((?:\d+(?:[/\.]\d+)?(?:["\']|mm|DN)?\s*[-–]?\s*)?[A-Z]{1,4}\s*[-–]\s*(?:\d{2,4}\s*[-–]\s*)?\d{3,5}'
|
||||||
r'\s*[-–]\s*[A-Z0-9]{2,8}(?:\s*[-–]\s*[A-Z0-9]{1,8})?)',
|
r'\s*[-–]\s*[A-Z0-9]{2,8}(?:\s*[-–]\s*[A-Z0-9]{1,8})?)',
|
||||||
re.IGNORECASE
|
re.IGNORECASE
|
||||||
)
|
)
|
||||||
@@ -345,6 +345,44 @@ def _is_setpoint_context(full_text: str, match_start: int, match_end: int) -> bo
|
|||||||
return bool(_SETPOINT_CONTEXT_RE.search(window_text))
|
return bool(_SETPOINT_CONTEXT_RE.search(window_text))
|
||||||
|
|
||||||
|
|
||||||
|
def _is_setpoint_context_spatial(item_idx: int, all_items: List[Dict[str, Any]]) -> bool:
|
||||||
|
"""
|
||||||
|
Check whether the item at item_idx or any nearby OCR item (within Y-gap 0.05 and X-gap 0.20)
|
||||||
|
contains setpoint/alarm keywords.
|
||||||
|
"""
|
||||||
|
target = all_items[item_idx]
|
||||||
|
target_text = (target.get('text') or target.get('value') or '').strip()
|
||||||
|
|
||||||
|
if _SETPOINT_CONTEXT_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.05 and dx <= 0.20:
|
||||||
|
if _SETPOINT_CONTEXT_RE.search(o_text):
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
# ──────────────────────────────────────────────────────────────────────────────
|
# ──────────────────────────────────────────────────────────────────────────────
|
||||||
# Defect 4 Fix: Line tag grammar enforcement helpers
|
# Defect 4 Fix: Line tag grammar enforcement helpers
|
||||||
# ──────────────────────────────────────────────────────────────────────────────
|
# ──────────────────────────────────────────────────────────────────────────────
|
||||||
@@ -384,7 +422,7 @@ def _validate_line_tag_size(tag: str) -> tuple:
|
|||||||
size_clean = p0.replace('"', '').replace("'", '').replace(' ', '').lower()
|
size_clean = p0.replace('"', '').replace("'", '').replace(' ', '').lower()
|
||||||
# Reject corrupt large sizes (e.g. 262", 1000")
|
# Reject corrupt large sizes (e.g. 262", 1000")
|
||||||
if _CORRUPT_SIZE_RE.match(p0) or (has_inch and size_clean.isdigit() and int(size_clean) > 60):
|
if _CORRUPT_SIZE_RE.match(p0) or (has_inch and size_clean.isdigit() and int(size_clean) > 60):
|
||||||
return False, f'invalid_pipe_size_corrupt_merge({p0})'
|
return False, f'size_out_of_range({p0})'
|
||||||
size_with_mm = size_clean + 'mm' if size_clean.isdigit() else size_clean
|
size_with_mm = size_clean + 'mm' if size_clean.isdigit() else size_clean
|
||||||
if size_clean in _VALID_INCH_SIZES or size_with_mm in _VALID_MM_SIZES:
|
if size_clean in _VALID_INCH_SIZES or size_with_mm in _VALID_MM_SIZES:
|
||||||
return True, None
|
return True, None
|
||||||
@@ -399,12 +437,12 @@ def _validate_line_tag_size(tag: str) -> tuple:
|
|||||||
try:
|
try:
|
||||||
n = int(size_clean)
|
n = int(size_clean)
|
||||||
if has_inch and n > 60:
|
if has_inch and n > 60:
|
||||||
return False, f'invalid_pipe_size_corrupt_merge({p0})'
|
return False, f'size_out_of_range({p0})'
|
||||||
if 1 <= n <= 600: # plausible DN size
|
if 1 <= n <= 600: # plausible DN size
|
||||||
return True, 'unverified_size_token'
|
return True, 'unverified_size_token'
|
||||||
except ValueError:
|
except ValueError:
|
||||||
pass
|
pass
|
||||||
return False, f'invalid_pipe_size_out_of_range({p0})'
|
return False, f'size_out_of_range({p0})'
|
||||||
return True, None
|
return True, None
|
||||||
|
|
||||||
|
|
||||||
@@ -446,8 +484,8 @@ def classify_paddle_results(
|
|||||||
|
|
||||||
Fixes applied:
|
Fixes applied:
|
||||||
Defect 2: Post-deduplication pass — merges short/prefixed tag variants by canonical key.
|
Defect 2: Post-deduplication pass — merges short/prefixed tag variants by canonical key.
|
||||||
Defect 3: Setpoint negative-context filter — prevents PI-150, AT-225 hallucinations.
|
Defect 3: Spatial setpoint negative-context filter — demotes PI-150, AT-225 setpoint numbers.
|
||||||
Defect 4: Line-tag grammar validation — validates pipe-size tokens and strips NOTE refs.
|
Defect 4: Line-tag grammar validation & size whitelist rejection (262" rejected, 12mm retained).
|
||||||
|
|
||||||
Retains ALL non-tag text lines as NOTE annotations so 100% of readable text is preserved.
|
Retains ALL non-tag text lines as NOTE annotations so 100% of readable text is preserved.
|
||||||
Adds 'confidence' and 'flag_reason' to every returned item.
|
Adds 'confidence' and 'flag_reason' to every returned item.
|
||||||
@@ -455,7 +493,7 @@ def classify_paddle_results(
|
|||||||
found: Dict[str, Dict] = {} # tag → item (deduplicated by EXACT tag string)
|
found: Dict[str, Dict] = {} # tag → item (deduplicated by EXACT tag string)
|
||||||
dt = (drawing_type or 'PID').upper()
|
dt = (drawing_type or 'PID').upper()
|
||||||
|
|
||||||
for item in items:
|
for item_idx, item in enumerate(items):
|
||||||
text = item.get('text', '').strip()
|
text = item.get('text', '').strip()
|
||||||
conf = float(item.get('confidence', 0))
|
conf = float(item.get('confidence', 0))
|
||||||
|
|
||||||
@@ -490,10 +528,16 @@ def classify_paddle_results(
|
|||||||
tag_conf = conf
|
tag_conf = conf
|
||||||
size_valid, size_flag = _validate_line_tag_size(tag)
|
size_valid, size_flag = _validate_line_tag_size(tag)
|
||||||
if not size_valid:
|
if not size_valid:
|
||||||
# Invalid size — flag but emit for human review
|
# Defect 4 Fix: Reject corrupt line size from LINE_TAG list emission
|
||||||
flag_reason = size_flag
|
demoted_item = _make_item(
|
||||||
tag_conf = min(conf, 0.5)
|
tag, 'NOTE', 0.25, item,
|
||||||
elif size_flag:
|
flag_reason=size_flag or 'size_out_of_range'
|
||||||
|
)
|
||||||
|
found[tag] = demoted_item
|
||||||
|
item_added = True
|
||||||
|
continue
|
||||||
|
|
||||||
|
if size_flag:
|
||||||
flag_reason = size_flag
|
flag_reason = size_flag
|
||||||
tag_conf = min(conf, 0.75)
|
tag_conf = min(conf, 0.75)
|
||||||
if raw_tag_clean != raw_tag.strip():
|
if raw_tag_clean != raw_tag.strip():
|
||||||
@@ -518,6 +562,18 @@ def classify_paddle_results(
|
|||||||
continue
|
continue
|
||||||
if full_tag in found and found[full_tag]['classification'] != 'NOTE':
|
if full_tag in found and found[full_tag]['classification'] != 'NOTE':
|
||||||
continue
|
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'}
|
_VALVE_FUNCTION_CODES = {'CB', 'GB', 'BL', 'GT', 'BT', 'GL', 'NV'}
|
||||||
if code in _VALVE_FUNCTION_CODES and len(re.sub(r'\D', '', seq)) >= 4:
|
if code in _VALVE_FUNCTION_CODES and len(re.sub(r'\D', '', seq)) >= 4:
|
||||||
cat = 'VALVE_TAG'
|
cat = 'VALVE_TAG'
|
||||||
@@ -529,6 +585,7 @@ def classify_paddle_results(
|
|||||||
cat = 'INSTRUMENT_TAG'
|
cat = 'INSTRUMENT_TAG'
|
||||||
else:
|
else:
|
||||||
cat = 'EQUIPMENT_TAG'
|
cat = 'EQUIPMENT_TAG'
|
||||||
|
|
||||||
if full_tag not in found:
|
if full_tag not in found:
|
||||||
found[full_tag] = _make_item(full_tag, cat, conf, item)
|
found[full_tag] = _make_item(full_tag, cat, conf, item)
|
||||||
item_added = True
|
item_added = True
|
||||||
@@ -538,15 +595,18 @@ def classify_paddle_results(
|
|||||||
tag = m.group(1).upper()
|
tag = m.group(1).upper()
|
||||||
if tag in found:
|
if tag in found:
|
||||||
continue
|
continue
|
||||||
if _is_setpoint_context(t, m.start(), m.end()):
|
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
|
# Matches setpoint-like context — demote to NOTE with flag
|
||||||
found[tag] = _make_item(
|
found[tag] = _make_item(
|
||||||
tag, 'NOTE', min(conf, 0.25), item,
|
tag, 'NOTE', 0.15, item,
|
||||||
flag_reason='ambiguous_setpoint_vs_tag'
|
flag_reason='ambiguous_setpoint_vs_tag'
|
||||||
)
|
)
|
||||||
logger.debug(f"Setpoint guard: demoted '{tag}' to NOTE (context: '{t[:60]}...')")
|
logger.debug(f"Setpoint guard: demoted bare '{tag}' to NOTE")
|
||||||
else:
|
else:
|
||||||
found[tag] = _make_item(tag, 'INSTRUMENT_TAG', conf, item)
|
found[tag] = _make_item(
|
||||||
|
tag, 'INSTRUMENT_TAG', min(conf, 0.60), item,
|
||||||
|
flag_reason='unverified_bare_instrument_tag'
|
||||||
|
)
|
||||||
item_added = True
|
item_added = True
|
||||||
|
|
||||||
# Valve tags
|
# Valve tags
|
||||||
|
|||||||
@@ -98,3 +98,32 @@ class TestTagCanonicalization:
|
|||||||
assert len(inst_tags) == 2, (
|
assert len(inst_tags) == 2, (
|
||||||
f"Expected 2 distinct INSTRUMENT_TAGs, got {len(inst_tags)}"
|
f"Expected 2 distinct INSTRUMENT_TAGs, got {len(inst_tags)}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def test_relationship_ck921_canonicalized_and_self_loop_dropped(self):
|
||||||
|
"""
|
||||||
|
Test that CompilerAgent resolves bare tag CK-921 to master tag 26-CK-921
|
||||||
|
and drops self-loop edges (CK-921 -> 26-CK-921).
|
||||||
|
"""
|
||||||
|
from src.agents.compiler import CompilerAgent
|
||||||
|
from src.models import EquipmentItem, UniversalEngineeringGraph
|
||||||
|
|
||||||
|
compiler = CompilerAgent()
|
||||||
|
graph = UniversalEngineeringGraph(drawing_type="PID", discipline="Piping")
|
||||||
|
graph.equipment = [
|
||||||
|
EquipmentItem(tag="26-CK-921", type="Check Valve", name="Check Valve", aliases=["CK-921"])
|
||||||
|
]
|
||||||
|
|
||||||
|
raw_relations = [
|
||||||
|
{"source_tag": "CK-921", "target_tag": "26-CK-921", "rel_type": "connects_to"},
|
||||||
|
{"source_tag": "LP FLARE", "target_tag": "CK-921", "rel_type": "feeds"},
|
||||||
|
]
|
||||||
|
|
||||||
|
tag_alias_map = {"26-CK-921": "26-CK-921", "CK-921": "26-CK-921", "LP FLARE": "LP FLARE"}
|
||||||
|
compiled_rels = compiler._compile_relationships(raw_relations, tag_alias_map)
|
||||||
|
|
||||||
|
# 1. Self-loop edge CK-921 -> 26-CK-921 must be dropped
|
||||||
|
# 2. LP FLARE -> CK-921 must be resolved to target "26-CK-921"
|
||||||
|
assert len(compiled_rels) == 1
|
||||||
|
assert compiled_rels[0].source == "LP FLARE"
|
||||||
|
assert compiled_rels[0].target == "26-CK-921"
|
||||||
|
|
||||||
|
|||||||
@@ -19,13 +19,21 @@ def _make_ocr_item(text: str, conf: float = 0.95) -> dict:
|
|||||||
class TestLineTagGrammar:
|
class TestLineTagGrammar:
|
||||||
|
|
||||||
def test_corrupt_size_262_inch_is_flagged(self):
|
def test_corrupt_size_262_inch_is_flagged(self):
|
||||||
"""262\"-VA-26-9110-AS20S-00 has an impossible size — must be flagged."""
|
"""262\"-VA-26-9110-AS20S-00 has an impossible size — must be flagged invalid."""
|
||||||
valid, flag_reason = _validate_line_tag_size('262"-VA-26-9110-AS20S-00')
|
valid, flag_reason = _validate_line_tag_size('262"-VA-26-9110-AS20S-00')
|
||||||
assert not valid, "Expected invalid=True for 262\" size"
|
assert not valid, "Expected invalid=True for 262\" size"
|
||||||
assert flag_reason and "corrupt_merge" in flag_reason, (
|
assert flag_reason and "size_out_of_range" in flag_reason, (
|
||||||
f"Expected 'corrupt_merge' in flag_reason, got: {flag_reason}"
|
f"Expected 'size_out_of_range' in flag_reason, got: {flag_reason}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def test_12mm_size_prefix_preserved(self):
|
||||||
|
"""12mm-PV-26-9116-FD70X-00 must retain 12mm size prefix and classify cleanly."""
|
||||||
|
items = [_make_ocr_item('12mm-PV-26-9116-FD70X-00')]
|
||||||
|
result = classify_paddle_results(items, drawing_type="PID")
|
||||||
|
line_tags = [r for r in result if r["classification"] == "LINE_TAG"]
|
||||||
|
assert len(line_tags) == 1
|
||||||
|
assert "12MM" in line_tags[0]["tag"]
|
||||||
|
|
||||||
def test_valid_sizes_pass_without_flag(self):
|
def test_valid_sizes_pass_without_flag(self):
|
||||||
"""Standard pipe sizes should pass without any flag_reason."""
|
"""Standard pipe sizes should pass without any flag_reason."""
|
||||||
for size_prefix in ['2"-VA-26-9110', '8"-PV-26-9035', '12"-PV-26-9035', '3/4"-VA-26-9114']:
|
for size_prefix in ['2"-VA-26-9110', '8"-PV-26-9035', '12"-PV-26-9035', '3/4"-VA-26-9114']:
|
||||||
@@ -40,27 +48,17 @@ class TestLineTagGrammar:
|
|||||||
items = [_make_ocr_item('3/4"-VA-26-9114-AC21-00NOTE20')]
|
items = [_make_ocr_item('3/4"-VA-26-9114-AC21-00NOTE20')]
|
||||||
result = classify_paddle_results(items, drawing_type="PID")
|
result = classify_paddle_results(items, drawing_type="PID")
|
||||||
line_tags = [r for r in result if r["classification"] == "LINE_TAG"]
|
line_tags = [r for r in result if r["classification"] == "LINE_TAG"]
|
||||||
# The tag should be found and NOTE20 should NOT be in the tag string
|
|
||||||
for lt in line_tags:
|
for lt in line_tags:
|
||||||
assert "NOTE20" not in lt["tag"] and "NOTE" not in lt["tag"].upper().replace("NOTE", ""), (
|
assert "NOTE20" not in lt["tag"] and "NOTE" not in lt["tag"].upper().replace("NOTE", ""), (
|
||||||
f"NOTE20 should be stripped from line tag, got: '{lt['tag']}'"
|
f"NOTE20 should be stripped from line tag, got: '{lt['tag']}'"
|
||||||
)
|
)
|
||||||
# Verify that a flag_reason is recorded
|
|
||||||
if line_tags:
|
|
||||||
flag_reasons = [lt.get("flag_reason") for lt in line_tags]
|
|
||||||
# At minimum one should be flagged for note stripping
|
|
||||||
# (acceptable if stripped version is valid)
|
|
||||||
|
|
||||||
def test_corrupt_size_emitted_with_low_confidence(self):
|
def test_corrupt_size_rejected_from_line_tag_emission(self):
|
||||||
"""Corrupt-size tags should be emitted (for human review) but with confidence <= 0.5."""
|
"""Corrupt-size tags (262") must NOT be emitted as LINE_TAG."""
|
||||||
items = [_make_ocr_item('262"-VA-26-9110-AS20S-00')]
|
items = [_make_ocr_item('262"-VA-26-9110-AS20S-00')]
|
||||||
result = classify_paddle_results(items, drawing_type="PID")
|
result = classify_paddle_results(items, drawing_type="PID")
|
||||||
line_tags = [r for r in result if r["classification"] == "LINE_TAG"]
|
line_tags = [r for r in result if r["classification"] == "LINE_TAG"]
|
||||||
for lt in line_tags:
|
assert len(line_tags) == 0, f"Expected 0 LINE_TAGs for corrupt 262\" size, got {line_tags}"
|
||||||
if lt.get("flag_reason") and "corrupt" in lt["flag_reason"]:
|
|
||||||
assert lt.get("confidence", 1.0) <= 0.5, (
|
|
||||||
f"Expected confidence <= 0.5 for corrupt-size tag, got {lt.get('confidence')}"
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_clean_line_tag_has_high_confidence(self):
|
def test_clean_line_tag_has_high_confidence(self):
|
||||||
"""A well-formed line tag should have full confidence and no flag_reason."""
|
"""A well-formed line tag should have full confidence and no flag_reason."""
|
||||||
@@ -77,7 +75,7 @@ class TestLineTagGrammar:
|
|||||||
def test_size_validation_out_of_range(self):
|
def test_size_validation_out_of_range(self):
|
||||||
"""A numeric size > 600 that is not a standard NPS should be flagged invalid."""
|
"""A numeric size > 600 that is not a standard NPS should be flagged invalid."""
|
||||||
valid, flag_reason = _validate_line_tag_size('900-VA-26-9110-AS20S-00')
|
valid, flag_reason = _validate_line_tag_size('900-VA-26-9110-AS20S-00')
|
||||||
# 900 is out of range for standard pipe sizes
|
|
||||||
assert flag_reason is not None, (
|
assert flag_reason is not None, (
|
||||||
"Expected a flag_reason for out-of-range size 900"
|
"Expected a flag_reason for out-of-range size 900"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -117,3 +117,65 @@ class TestEquipmentDatasheet:
|
|||||||
if "26-KA-901" in result:
|
if "26-KA-901" in result:
|
||||||
assert "material" in result["26-KA-901"]
|
assert "material" in result["26-KA-901"]
|
||||||
assert "LTCS" in result["26-KA-901"]["material"]
|
assert "LTCS" in result["26-KA-901"]["material"]
|
||||||
|
|
||||||
|
def test_full_ka902_datasheet_block_parsing(self):
|
||||||
|
"""Test complete 26-KA-902 synthetic datasheet block matching QA report."""
|
||||||
|
block = [
|
||||||
|
_make_item("26-KA-902", "EQUIPMENT_TAG", 0.20),
|
||||||
|
_make_item("SERVICE 3RD STAGE HP GAS EXPORT COMPRESSOR", "NOTE", 0.21),
|
||||||
|
_make_item("DUTY kW 1835", "NOTE", 0.22),
|
||||||
|
_make_item("FLOW RATE kg/h 62809", "NOTE", 0.23),
|
||||||
|
_make_item("DISCHARGE / SUCTION OP. PRESS. (MAX) Barg 199 / 108.5", "NOTE", 0.24),
|
||||||
|
_make_item("DISCHARGE / SUCTION DESIGN PRESS. (MAX) Barg FV / 286", "NOTE", 0.25),
|
||||||
|
_make_item("DISCHARGE / SUCTION DESIGN TEMP. °C -46 / 160", "NOTE", 0.26),
|
||||||
|
_make_item("MATERIAL LTCS (1.7218)", "NOTE", 0.27),
|
||||||
|
_make_item("QUANTITY 1x100%", "NOTE", 0.28),
|
||||||
|
_make_item("TYPE VARIABLE SPEED MOTOR DRIVEN CENTRIFUGAL", "NOTE", 0.29),
|
||||||
|
_make_item("VENDOR MAN ENERGY SOLUTIONS", "NOTE", 0.30),
|
||||||
|
]
|
||||||
|
result = parse_equipment_datasheets(block)
|
||||||
|
assert "26-KA-902" in result
|
||||||
|
fields = result["26-KA-902"]
|
||||||
|
assert "duty" in fields and "1835" in fields["duty"]
|
||||||
|
assert "flow_rate" in fields and "62809" in fields["flow_rate"]
|
||||||
|
assert "design_pressure" in fields and "286" in fields["design_pressure"]
|
||||||
|
assert "design_temperature" in fields and "160" in fields["design_temperature"]
|
||||||
|
assert "material" in fields and "LTCS" in fields["material"]
|
||||||
|
assert "quantity" in fields and "1x100%" in fields["quantity"]
|
||||||
|
assert "type" in fields and "CENTRIFUGAL" in fields["type"]
|
||||||
|
assert "vendor" in fields and "MAN ENERGY SOLUTIONS" in fields["vendor"]
|
||||||
|
|
||||||
|
def test_vendor_scope_marker_rejected(self):
|
||||||
|
"""Bare word 'VENDOR' scope marker must NOT populate the Vendor field."""
|
||||||
|
items = [
|
||||||
|
_make_item("26-CX-9021", "EQUIPMENT_TAG", 0.30),
|
||||||
|
_make_item("VENDOR", "NOTE", 0.31),
|
||||||
|
]
|
||||||
|
result = parse_equipment_datasheets(items)
|
||||||
|
if "26-CX-9021" in result:
|
||||||
|
assert "vendor" not in result["26-CX-9021"]
|
||||||
|
|
||||||
|
def test_parenthetical_note_rejected_from_type(self):
|
||||||
|
"""Raw parenthetical note sentences must NOT populate the equipment Type field."""
|
||||||
|
items = [
|
||||||
|
_make_item("26-KZ-902", "EQUIPMENT_TAG", 0.40),
|
||||||
|
_make_item("(MOTOR PURGE SYSTEM ; EX-P TYPE MOTOR)", "NOTE", 0.41),
|
||||||
|
]
|
||||||
|
result = parse_equipment_datasheets(items)
|
||||||
|
if "26-KZ-902" in result:
|
||||||
|
assert "type" not in result["26-KZ-902"]
|
||||||
|
|
||||||
|
def test_psv_flange_spec_parsing(self):
|
||||||
|
"""Test parse_psv_flange_specs for 3"x4" 300# 150# near PSV tag."""
|
||||||
|
from src.utils.datasheet_parser import parse_psv_flange_specs
|
||||||
|
items = [
|
||||||
|
_make_item("26-PSV-9066A", "PSV_TAG", 0.50),
|
||||||
|
_make_item('3"x4" 300# 150#', "NOTE", 0.52),
|
||||||
|
]
|
||||||
|
result = parse_psv_flange_specs(items)
|
||||||
|
assert "26-PSV-9066A" in result
|
||||||
|
flange = result["26-PSV-9066A"]
|
||||||
|
assert flange["inlet_size"] == '3"'
|
||||||
|
assert flange["outlet_size"] == '4"'
|
||||||
|
assert flange["inlet_spec"] == "300#"
|
||||||
|
|
||||||
|
|||||||
@@ -116,3 +116,13 @@ class TestSetpointFilter:
|
|||||||
f"Expected confidence <= 0.25 for flagged item '{r['tag']}', "
|
f"Expected confidence <= 0.25 for flagged item '{r['tag']}', "
|
||||||
f"got {r.get('confidence')}"
|
f"got {r.get('confidence')}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def test_spatial_multi_box_setpoint_detection(self):
|
||||||
|
"""When PI-150 is in one box and 'SD HH: 150 BARG' is adjacent, PI-150 must be demoted."""
|
||||||
|
from src.utils.tag_classifier import _is_setpoint_context_spatial
|
||||||
|
items = [
|
||||||
|
{"text": "PI-150", "confidence": 0.95, "center_x": 0.50, "center_y": 0.30},
|
||||||
|
{"text": "SD HH: 150 BARG", "confidence": 0.95, "center_x": 0.52, "center_y": 0.32},
|
||||||
|
]
|
||||||
|
assert _is_setpoint_context_spatial(0, items) is True
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user