feat: SID-AI accuracy repairs, cross-doc provenance filter, datasheet parser, setpoint guard, and updated README for Abhinav Gupta

This commit is contained in:
Abhinav Gupta
2026-08-12 22:56:16 +05:30
parent 36c7739c7e
commit 4adbbfae46
23 changed files with 1677 additions and 147 deletions
+3 -3
View File
@@ -54,7 +54,6 @@ class BaseAgent:
Uploads a file to the Google GenAI File API using the google-genai Client.
Polls until the file becomes ACTIVE.
"""
from google import genai
from src.config import GEMINI_API_KEY
if not GEMINI_API_KEY:
@@ -66,6 +65,7 @@ class BaseAgent:
return None
try:
from google import genai
logger.info(f"Uploading file '{file_path}' to Google GenAI File API...")
client = genai.Client(api_key=GEMINI_API_KEY)
uploaded = client.files.upload(file=file_path)
@@ -87,8 +87,8 @@ class BaseAgent:
else:
logger.error(f"File processing failed or timed out. State: {uploaded.state.name}")
return None
except Exception as e:
logger.error(f"Failed to upload file via Google GenAI File API: {e}")
except (ImportError, Exception) as e:
logger.warning(f"Failed to upload file via Google GenAI File API: {e}")
return None
def get_target_llm(
+94 -29
View File
@@ -93,6 +93,22 @@ class CompilerAgent(BaseAgent):
existing_rel_keys.add(key)
all_relations.append(cr)
# ── Defect 1 Fix: Provenance filter — drop cross-document contamination ──
ocr_token_set = state.get("ocr_token_set", set())
if ocr_token_set:
from src.utils.provenance import filter_relationships_by_provenance
all_relations, dropped = filter_relationships_by_provenance(
all_relations, ocr_token_set
)
if dropped:
examples = [f"{d.get('source_tag')}->{d.get('target_tag')}" for d in dropped[:3]]
logger.warning(
f"Provenance: dropped {len(dropped)} cross-document relationship(s). "
f"Examples: {examples}"
)
else:
logger.info("Provenance: no OCR token set in state; skipping contamination filter.")
# Always compile relationships (cross-type)
graph.relationships = self._compile_relationships(all_relations)
@@ -153,14 +169,10 @@ class CompilerAgent(BaseAgent):
tag = eq["tag"]
# Deduplicate by canonical key (strip project prefix AND trailing unit suffix)
# e.g.: 26-HA-911-C01 → HA-911, 26-KA-901-A → KA-901, KA-901 → KA-901
canon_key = re.sub(r'^\d{2,3}-', '', tag.upper()) # strip project prefix
# Strip trailing unit designator only if it contains at least one alpha char
# This prevents stripping the last digit of a sequence number (HA-911 → HA-91)
canon_key = re.sub(r'-[A-Z][A-Z0-9]{0,3}$', '', canon_key) # -C01, -A, -B only
canon_key = re.sub(r'^\d{2,3}-', '', tag.upper())
canon_key = re.sub(r'-[A-Z][A-Z0-9]{0,3}$', '', canon_key)
if canon_key in seen_equip:
# Prefer longer project-prefixed tag
if len(tag) > len(seen_equip[canon_key].tag):
seen_equip[canon_key].tag = tag
continue
@@ -171,7 +183,6 @@ class CompilerAgent(BaseAgent):
coords = [sym["ymin"], sym["xmin"], sym["ymax"], sym["xmax"]]
break
# Derive equipment type from ISA lookup
code_match = re.search(r'([A-Z]{1,3})(?=-?\d)', tag, re.IGNORECASE)
eq_code = code_match.group(1).upper() if code_match else ""
eq_type = self._ISA_EQUIP_DESC.get(eq_code, "Generic Equipment")
@@ -180,18 +191,27 @@ class CompilerAgent(BaseAgent):
eq_type = sym["symbol_type"]
break
# ── Defect 5 Fix: populate datasheet fields from injected attributes ──
attrs = eq.get("attributes") or {}
aliases = eq.get("aliases") or []
confidence = float(eq.get("confidence", 1.0))
item_obj = EquipmentItem(
tag=tag,
name=eq["value"],
type=eq_type,
description=eq["value"],
type=attrs.get("type") or eq_type,
description=attrs.get("service") or eq["value"],
design_pressure=attrs.get("design_pressure"),
design_temperature=attrs.get("design_temperature"),
flow_rate=attrs.get("flow_rate"),
duty=attrs.get("duty") or eq.get("rating"),
material=attrs.get("material"),
vendor=attrs.get("vendor"),
quantity=attrs.get("quantity"),
location=attrs.get("location"),
coordinates=coords,
aliases=aliases if aliases else None,
confidence=confidence,
)
compiled.append(item_obj)
seen_equip[canon_key] = item_obj
@@ -416,12 +436,31 @@ class CompilerAgent(BaseAgent):
relations: List[Dict], lines: List[LineItem]
) -> List[ValveItem]:
compiled = []
seen_canonical: dict = {} # ── Defect 2 Fix: deduplicate by canonical key
valve_tags = [t for t in texts if t["classification"] == "VALVE_TAG"]
for v in valve_tags:
tag = v["tag"]
tag_upper = tag.upper()
# Deduplicate — prefer the longer (project-prefixed) form
canon_key = re.sub(r'^\d{2,3}-?', '', tag_upper)
if canon_key in seen_canonical:
existing_tag = seen_canonical[canon_key].tag
if len(tag) > len(existing_tag):
seen_canonical[canon_key].tag = tag
# Merge alias
als = seen_canonical[canon_key].aliases or []
if existing_tag not in als:
als.append(existing_tag)
seen_canonical[canon_key].aliases = als
else:
als = seen_canonical[canon_key].aliases or []
if tag not in als:
als.append(tag)
seen_canonical[canon_key].aliases = als
continue # skip duplicate
v_type = "Valve"
if "GB" in tag_upper or "GATE" in tag_upper:
v_type = "Gate Valve"
@@ -440,7 +479,6 @@ class CompilerAgent(BaseAgent):
elif tag_upper.startswith(('MOV', 'SDV', 'BDV', 'EV')):
v_type = "On-Off Valve"
# Case-insensitive relation check for host line
associated_line = None
for rel in relations:
rtype = rel.get("rel_type", "").upper()
@@ -453,21 +491,15 @@ class CompilerAgent(BaseAgent):
associated_line = stag
break
# Derive size from the associated line
derived_size = None
if associated_line:
for line in lines:
if line.tag == associated_line:
derived_size = line.size
break
if not derived_size:
derived_size = None # Unknown — don't fabricate
# Rating from attrs
attrs = v.get("attributes") or {}
rating = v.get("rating") or attrs.get("rating") or attrs.get("pressure_class")
# Normal state from attrs
normal_state = attrs.get("normal_state")
coords = None
@@ -476,7 +508,7 @@ class CompilerAgent(BaseAgent):
coords = [sym["ymin"], sym["xmin"], sym["ymax"], sym["xmax"]]
break
compiled.append(ValveItem(
item_obj = ValveItem(
tag=tag,
type=v_type,
size=derived_size,
@@ -484,7 +516,13 @@ class CompilerAgent(BaseAgent):
rating=rating,
normal_state=normal_state,
coordinates=coords,
))
type_source="inferred_from_prefix", # ── Defect 6 Fix
confidence=float(v.get("confidence", 1.0)),
aliases=v.get("aliases") or None,
)
compiled.append(item_obj)
seen_canonical[canon_key] = item_obj
return compiled
def _compile_safety_relief_valves(self, texts: List[Dict], symbols: List[Dict]) -> List[SafetyReliefValveItem]:
@@ -495,7 +533,6 @@ class CompilerAgent(BaseAgent):
tag = psv["tag"]
attrs = psv.get("attributes") or {}
# Infer unit prefix from tag (e.g. "26" from "26-PSV-9066A")
unit_match = re.match(r'^(\d{2})-', tag)
unit = unit_match.group(1) if unit_match else ""
@@ -505,12 +542,19 @@ class CompilerAgent(BaseAgent):
coords = [sym["ymin"], sym["xmin"], sym["ymax"], sym["xmax"]]
break
# ── Defect 5 Fix: use parsed set_pressure from datasheet_parser (injected into attrs)
set_pressure = (
attrs.get("set_pressure")
or psv.get("rating")
or "N/A"
)
compiled.append(SafetyReliefValveItem(
tag=tag,
type=attrs.get("valve_type", "PSV"),
service=psv["value"],
unit=unit,
set_pressure=psv.get("rating") or attrs.get("set_pressure", "N/A"),
set_pressure=set_pressure,
inlet_size=attrs.get("inlet_size", "N/A"),
outlet_size=attrs.get("outlet_size", "N/A"),
inlet_spec=attrs.get("inlet_spec", "N/A"),
@@ -756,12 +800,33 @@ class CompilerAgent(BaseAgent):
return compiled
def _compile_relationships(self, relations: List[Dict]) -> List[Relationship]:
return [
Relationship(
source=r["source_tag"],
target=r["target_tag"],
type=r["rel_type"].lower(),
attributes={},
)
for r in relations
]
"""Compile relationships with deduplication by canonical source/target/type triple."""
from src.utils.tag_classifier import canonicalize_tag
seen_edges: set = set()
result: List[Relationship] = []
for r in relations:
src = r.get("source_tag") or r.get("source") or ""
tgt = r.get("target_tag") or r.get("target") or ""
rtype = (r.get("rel_type") or r.get("type") or "").lower()
flag = r.get("flag_reason")
if not src or not tgt:
continue
# ── Defect 2 Fix: deduplicate edges by canonical source+target+type ──
canon_edge = (canonicalize_tag(src), canonicalize_tag(tgt), rtype)
if canon_edge in seen_edges:
continue
seen_edges.add(canon_edge)
result.append(Relationship(
source=src,
target=tgt,
type=rtype,
confidence=float(r.get("confidence", 1.0)),
attributes=r.get("attributes") or {},
flag_reason=flag,
))
return result
+53 -4
View File
@@ -66,7 +66,7 @@ class OutputGeneratorAgent(BaseAgent):
client = genai.Client(api_key=GEMINI_API_KEY)
client.files.delete(name=file_name)
logger.info("Cloud file deletion completed successfully.")
except Exception as e:
except (ImportError, Exception) as e:
logger.warning(f"Could not delete uploaded file '{file_name}' from Google GenAI Files API: {e}")
return {
@@ -166,23 +166,28 @@ class OutputGeneratorAgent(BaseAgent):
# Instrument List
if graph.instruments:
headers = ["#", "Instrument Tag", "Type", "Loop ID", "Location", "Service"]
headers = ["#", "Instrument Tag", "Type", "Loop ID", "Location", "Service", "Aliases", "Confidence"]
rows = [{
"#": i + 1,
"Instrument Tag": inst.tag, "Type": inst.type,
"Loop ID": inst.loop_id or "-", "Location": inst.location or "Field",
"Service": inst.service or "-",
"Aliases": ", ".join(inst.aliases) if getattr(inst, 'aliases', None) else "-",
"Confidence": f"{int(getattr(inst, 'confidence', 1.0) * 100)}%",
} for i, inst in enumerate(graph.instruments)]
write_sheet("Instrument List", f"INSTRUMENT LIST — {dt_label}", f"Extracted by SID-AI | {len(rows)} instruments detected", headers, rows)
# Valve List
if graph.valves:
headers = ["#", "Valve Tag", "Type", "Size", "Rating", "Normal State", "Associated Line"]
headers = ["#", "Valve Tag", "Type", "Size", "Rating", "Normal State", "Associated Line", "Type Source", "Aliases", "Confidence"]
rows = [{
"#": i + 1,
"Valve Tag": v.tag, "Type": v.type, "Size": v.size or "-",
"Rating": v.rating or "-", "Normal State": v.normal_state or "-",
"Associated Line": v.line_tag or "-",
"Type Source": getattr(v, 'type_source', 'inferred_from_prefix'),
"Aliases": ", ".join(v.aliases) if getattr(v, 'aliases', None) else "-",
"Confidence": f"{int(getattr(v, 'confidence', 1.0) * 100)}%",
} for i, v in enumerate(graph.valves)]
write_sheet("Valve List", f"MANUAL VALVE LIST — {dt_label}", f"Extracted by SID-AI | {len(rows)} valves detected", headers, rows)
@@ -200,12 +205,15 @@ class OutputGeneratorAgent(BaseAgent):
# Equipment List
if graph.equipment:
headers = ["#", "Equipment Tag", "Type", "Description", "Design Pressure", "Design Temp", "Flow Rate", "Duty", "Material"]
headers = ["#", "Equipment Tag", "Type", "Description", "Design Pressure", "Design Temp", "Flow Rate", "Duty", "Material", "Vendor", "Quantity", "Aliases", "Confidence"]
rows = [{
"#": i + 1,
"Equipment Tag": e.tag, "Type": e.type, "Description": e.description or e.name,
"Design Pressure": e.design_pressure or "-", "Design Temp": e.design_temperature or "-",
"Flow Rate": e.flow_rate or "-", "Duty": e.duty or "-", "Material": e.material or "-",
"Vendor": getattr(e, 'vendor', None) or "-", "Quantity": getattr(e, 'quantity', None) or "-",
"Aliases": ", ".join(e.aliases) if getattr(e, 'aliases', None) else "-",
"Confidence": f"{int(getattr(e, 'confidence', 1.0) * 100)}%",
} for i, e in enumerate(graph.equipment)]
write_sheet("Equipment List", f"EQUIPMENT LIST — {dt_label}", f"Extracted by SID-AI | {len(rows)} equipment items detected", headers, rows)
@@ -322,6 +330,47 @@ class OutputGeneratorAgent(BaseAgent):
} for i, a in enumerate(graph.annotations)]
write_sheet("Annotations", "ANNOTATIONS & NOTES", f"Extracted by SID-AI | {len(rows)} annotations", headers, rows)
# ── Flagged Items Sheet (Human Review Queue) ──────────────────────────
flagged_rows = []
# Check instruments
for inst in graph.instruments:
if getattr(inst, 'flag_reason', None):
flagged_rows.append({
"Category": "Instrument", "Tag": inst.tag,
"Confidence": f"{int(getattr(inst, 'confidence', 1.0) * 100)}%",
"Flag Reason": inst.flag_reason, "Details": f"Type: {inst.type}, Location: {inst.location}"
})
# Check valves
for v in graph.valves:
if getattr(v, 'flag_reason', None):
flagged_rows.append({
"Category": "Valve", "Tag": v.tag,
"Confidence": f"{int(getattr(v, 'confidence', 1.0) * 100)}%",
"Flag Reason": v.flag_reason, "Details": f"Type: {v.type}, Source: {getattr(v, 'type_source', 'inferred')}"
})
# Check lines
for l in graph.lines:
if getattr(l, 'flag_reason', None):
flagged_rows.append({
"Category": "Line Tag", "Tag": l.tag,
"Confidence": f"{int(getattr(l, 'confidence', 1.0) * 100)}%",
"Flag Reason": l.flag_reason, "Details": f"Size: {l.size}, Spec: {l.spec}"
})
# Check relationships
for r in graph.relationships:
if getattr(r, 'flag_reason', None):
flagged_rows.append({
"Category": "Relationship",
"Tag": f"{getattr(r, 'source_tag', getattr(r, 'source', ''))} -> {getattr(r, 'target_tag', getattr(r, 'target', ''))}",
"Confidence": f"{int(getattr(r, 'confidence', 1.0) * 100)}%",
"Flag Reason": r.flag_reason, "Details": f"Rel Type: {getattr(r, 'rel_type', getattr(r, 'type', ''))}"
})
if flagged_rows:
headers = ["#", "Category", "Tag", "Confidence", "Flag Reason", "Details"]
rows = [{"#": i + 1, **row} for i, row in enumerate(flagged_rows)]
write_sheet("Flagged Items", "HUMAN REVIEW QUEUE — FLAGGED ITEMS", f"Flagged by SID-AI | {len(rows)} items require review", headers, rows)
if not wb.sheetnames:
ws = wb.create_sheet("No Data")
ws.cell(row=1, column=1, value="No entities were detected from this drawing.")
+243 -44
View File
@@ -42,6 +42,43 @@ def _is_cuda_available() -> bool:
return False
def _iou_box(b1: Dict[str, Any], b2: Dict[str, Any]) -> float:
"""Computes Intersection-over-Union (IoU) between two bounding boxes."""
ymin1, xmin1, ymax1, xmax1 = b1["ymin"], b1["xmin"], b1["ymax"], b1["xmax"]
ymin2, xmin2, ymax2, xmax2 = b2["ymin"], b2["xmin"], b2["ymax"], b2["xmax"]
inter_ymin = max(ymin1, ymin2)
inter_xmin = max(xmin1, xmin2)
inter_ymax = min(ymax1, ymax2)
inter_xmax = min(xmax1, xmax2)
inter_w = max(0.0, inter_xmax - inter_xmin)
inter_h = max(0.0, inter_ymax - inter_ymin)
inter_area = inter_w * inter_h
area1 = max(0.0, ymax1 - ymin1) * max(0.0, xmax1 - xmin1)
area2 = max(0.0, ymax2 - ymin2) * max(0.0, xmax2 - xmin2)
union_area = area1 + area2 - inter_area
if union_area <= 0:
return 0.0
return inter_area / union_area
def _deduplicate_tiled_boxes(raw_boxes: List[Dict[str, Any]], iou_thresh: float = 0.45) -> List[Dict[str, Any]]:
"""Applies Non-Maximum Suppression (NMS) on tiled patch detections."""
raw_boxes.sort(key=lambda b: b.get("confidence", 0.0), reverse=True)
kept = []
for box in raw_boxes:
overlap = False
for k in kept:
if box["symbol_type"] == k["symbol_type"] and _iou_box(box, k) > iou_thresh:
overlap = True
break
if not overlap:
kept.append(box)
return kept
# ──────────────────────────────────────────────────────────────────────────────
# Drawing-type-aware prompt builders
# ──────────────────────────────────────────────────────────────────────────────
@@ -220,6 +257,104 @@ class RawPipelineList(BaseModel):
# AGENT 1: Text Recognition Agent (OCR + Tag & Attribute Parsing)
# ──────────────────────────────────────────────────────────────────────────────
def _inject_datasheet_attributes(
structured: List[Dict[str, Any]],
ocr_items: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""
Defect 5 Fix: After Layer 2 classification, scan OCR items for equipment
datasheet blocks and PSV SP= values, then inject those field values into
the matching EQUIPMENT_TAG and PSV_TAG items.
This populates design_pressure, design_temperature, flow_rate, duty,
material, vendor, quantity (for Equipment) and set_pressure (for PSV)
which were previously always None/-/N/A in the output.
"""
try:
from src.utils.datasheet_parser import (
parse_equipment_datasheets,
parse_psv_set_pressures,
)
except ImportError as e:
logger.warning(f"datasheet_parser import failed: {e}. Skipping attribute injection.")
return structured
# Build position-aware OCR items list for spatial anchoring
pos_items = []
for item in structured:
attrs = item.get('attributes') or {}
cy = float(attrs.get('pos_y', -1)) if attrs.get('pos_y') else -1
cx = float(attrs.get('pos_x', -1)) if attrs.get('pos_x') else -1
pos_items.append({**item, 'center_y': cy, 'center_x': cx})
# Also add raw OCR items as position context (they have bbox/center coordinates)
for raw in ocr_items:
cy = raw.get('center_y') or (raw.get('attributes') or {}).get('pos_y')
cx = raw.get('center_x') or (raw.get('attributes') or {}).get('pos_x')
if cy is not None and cx is not None and cy != -1 and cx != -1:
try:
cy = float(cy)
cx = float(cx)
except (ValueError, TypeError):
cy, cx = 0.5, 0.5
else:
box = raw.get('box') or raw.get('bbox') or []
cx, cy = 0.5, 0.5
if len(box) >= 4:
try:
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
cx = sum(float(pt[0]) for pt in box[:4]) / 4.0
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
cx = (float(box[1]) + float(box[3])) / 2.0
except (ValueError, TypeError, IndexError):
cy, cx = 0.5, 0.5
pos_items.append({
'tag': raw.get('text', ''),
'classification': 'NOTE',
'value': raw.get('text', ''),
'center_y': cy,
'center_x': cx,
'attributes': {},
})
# Parse datasheets and PSV set pressures
datasheet_map = parse_equipment_datasheets(pos_items)
psv_sp_map = parse_psv_set_pressures(pos_items)
# Inject into structured results
injected_count = 0
for item in structured:
tag = item.get('tag') or ''
cls = item.get('classification') or ''
if cls == 'EQUIPMENT_TAG' and tag in datasheet_map:
attrs = dict(item.get('attributes') or {})
fields = datasheet_map[tag]
for field, value in fields.items():
if field not in attrs or not attrs[field]:
attrs[field] = value
injected_count += 1
item['attributes'] = attrs
elif cls == 'PSV_TAG' and tag in psv_sp_map:
attrs = dict(item.get('attributes') or {})
if not attrs.get('set_pressure'):
attrs['set_pressure'] = psv_sp_map[tag]
injected_count += 1
item['attributes'] = attrs
if injected_count:
logger.info(
f"Datasheet injection: enriched {injected_count} attribute fields "
f"across {len(datasheet_map)} equipment + {len(psv_sp_map)} PSV items."
)
return structured
class TextRecognitionAgent(BaseAgent):
"""
Dedicated Text Recognition Agent:
@@ -243,8 +378,11 @@ class TextRecognitionAgent(BaseAgent):
logger.error("No image pages available for text extraction.")
return {"extracted_entities": {"text_elements": []}}
# ── Defect 1 Fix: Only OCR the PRIMARY document, not reference/legend sheets ──
# raw_documents[0] is always the primary PDF/image being extracted.
# Additional docs (index 1+) are reference sheets — used for legend lookup only.
raw_image = pages[0] if pages else raw_documents[0]
original_doc = raw_documents[0] if raw_documents else raw_image
original_doc = raw_documents[0] if raw_documents else raw_image # PRIMARY DOC ONLY
local_mode = state.get("local_mode", False)
ocr_engine = state.get("ocr_engine", "paddle").lower()
@@ -276,11 +414,13 @@ class TextRecognitionAgent(BaseAgent):
if res_p.get("text_elements"):
logger.info(f"Pathnovo ISA 5.1 Engine extracted {len(res_p['text_elements'])} text elements.")
return {"extracted_entities": {"text_elements": res_p["text_elements"]}}
else:
logger.info("Pathnovo Engine returned 0 text elements. Falling back to local OCR pipeline...")
except Exception as p_err:
logger.warning(f"Pathnovo Engine failed ({p_err}). Falling back to local OCR pipeline.")
# Option B: PyMuPDF Vector Text Layer
if (ocr_engine == "pdf_text" or ocr_engine == "paddle") and original_doc.lower().endswith('.pdf'):
# Option B: PyMuPDF Vector Text Layer (for any PDF file)
if original_doc.lower().endswith('.pdf'):
try:
from src.utils.paddle_ocr import run_pdf_text_extraction
logger.info("Layer 1: Checking PyMuPDF text layer extraction on original PDF...")
@@ -335,7 +475,18 @@ class TextRecognitionAgent(BaseAgent):
logger.info("Layer 2: Executing Local Rule-Based Classifier (zero LLM tokens)...")
structured = classify_paddle_results(ocr_items, drawing_type=drawing_type)
logger.info(f"Layer 2: Rule-based classifier produced {len(structured)} structured items.")
return {"extracted_entities": {"text_elements": structured}}
# ── Defect 5 Fix: inject equipment datasheet fields and PSV set pressures ──
structured = _inject_datasheet_attributes(structured, ocr_items)
# ── Defect 1 Fix: build OCR token set for provenance filter in compiler ──
from src.utils.provenance import build_ocr_token_set
ocr_token_set = build_ocr_token_set(structured)
return {
"extracted_entities": {"text_elements": structured},
"ocr_token_set": ocr_token_set,
}
# Option B: Online LLM Deep Reasoning Engine (Qwen 3.7 VL, Gemini, OpenAI, etc.)
logger.info(f"Layer 2: Executing Online LLM Reasoning Engine using provider '{llm_provider}'...")
@@ -375,7 +526,18 @@ class TextRecognitionAgent(BaseAgent):
extracted_items = [item.model_dump() for item in result.items]
logger.info(f"Layer 2 Reasoning Engine ({llm_provider}): produced {len(extracted_items)} refined structured entities.")
return {"extracted_entities": {"text_elements": extracted_items}}
# ── Defect 5 Fix: inject equipment datasheet fields and PSV set pressures ──
extracted_items = _inject_datasheet_attributes(extracted_items, ocr_items)
# ── Defect 1 Fix: build OCR token set for provenance filter ──
from src.utils.provenance import build_ocr_token_set
ocr_token_set = build_ocr_token_set(extracted_items)
return {
"extracted_entities": {"text_elements": extracted_items},
"ocr_token_set": ocr_token_set,
}
except Exception as llm_err:
logger.warning(f"Layer 2 Reasoning Engine failed ({llm_err}). Falling back to local rule-based classifier.")
@@ -436,7 +598,7 @@ class SymbolRecognitionAgent(BaseAgent):
logger.warning(f"Pathnovo Symbol Parser failed ({p_err}). Falling back to standard VLM pipeline.")
# Option B: Trained YOLOv8 Symbol Detector (custom best.pt from training pipeline)
elif symbol_engine == "yolo_trained":
if not symbols and symbol_engine == "yolo_trained":
weights_path = (
state.get("yolo_weights_path")
or os.getenv("DEFAULT_YOLO_WEIGHTS", "")
@@ -449,58 +611,95 @@ class SymbolRecognitionAgent(BaseAgent):
)
else:
try:
import cv2
from ultralytics import YOLO
from src.agents.base import BaseAgent as _BA
from training.annotation_generator import SYMBOL_CLASSES
logger.info(f"SymbolRecognitionAgent: Loading trained YOLOv8 from '{weights_path}'...")
yolo_model = YOLO(weights_path)
# Encode image for inference
import numpy as np
from PIL import Image as _PilImage
with _PilImage.open(raw_image) as _img:
img_w, img_h = _img.size
_img_rgb = _img.convert("RGB")
conf_thresh = state.get("yolo_conf") or 0.15
iou_thresh = state.get("yolo_iou") or 0.45
results = yolo_model.predict(
source=str(raw_image),
conf=state.get("yolo_conf") or 0.25,
iou=state.get("yolo_iou") or 0.45,
imgsz=800, # Match training imgsz
device="0" if _is_cuda_available() else "cpu",
verbose=False,
)
img_cv = cv2.imread(raw_image)
if img_cv is not None:
H, W, _ = img_cv.shape
raw_boxes = []
# YOLO class names from the training annotation_generator
from training.annotation_generator import SYMBOL_CLASSES
# Tiled Patch Inference for large full-page engineering drawings
if W > 1200 or H > 1200:
logger.info(
f"SymbolRecognitionAgent: Large image ({W}x{H}px). "
f"Running Tiled Patch Inference (800x800 tiles, conf={conf_thresh})..."
)
tile_size = 800
stride = 500
for result in results:
for box in result.boxes:
cls_id = int(box.cls[0].item())
conf_val = float(box.conf[0].item())
# box.xyxyn → normalized [x1, y1, x2, y2]
x1n, y1n, x2n, y2n = box.xyxyn[0].tolist()
sym_type = SYMBOL_CLASSES[cls_id] if cls_id < len(SYMBOL_CLASSES) else "UNKNOWN"
for y in range(0, H, stride):
for x in range(0, W, stride):
x2 = min(x + tile_size, W)
y2 = min(y + tile_size, H)
tile = img_cv[y:y2, x:x2]
symbols.append({
"symbol_type" : sym_type,
"inferred_tag": None,
"ymin" : round(y1n, 4),
"xmin" : round(x1n, 4),
"ymax" : round(y2n, 4),
"xmax" : round(x2n, 4),
"confidence" : round(conf_val, 3),
})
res = yolo_model.predict(
source=tile,
conf=conf_thresh,
iou=iou_thresh,
imgsz=800,
device="0" if _is_cuda_available() else "cpu",
verbose=False,
)
for box in res[0].boxes:
cls_id = int(box.cls[0].item())
conf_val = float(box.conf[0].item())
tx1, ty1, tx2, ty2 = box.xyxy[0].tolist()
gx1, gy1, gx2, gy2 = x + tx1, y + ty1, x + tx2, y + ty2
sym_type = SYMBOL_CLASSES[cls_id] if cls_id < len(SYMBOL_CLASSES) else "UNKNOWN"
raw_boxes.append({
"symbol_type": sym_type,
"inferred_tag": None,
"ymin": round(max(0.0, gy1 / H), 4),
"xmin": round(max(0.0, gx1 / W), 4),
"ymax": round(min(1.0, gy2 / H), 4),
"xmax": round(min(1.0, gx2 / W), 4),
"confidence": round(conf_val, 3),
})
# Deduplicate overlapping tiled boxes
symbols = _deduplicate_tiled_boxes(raw_boxes, iou_thresh=iou_thresh)
else:
results = yolo_model.predict(
source=str(raw_image),
conf=conf_thresh,
iou=iou_thresh,
imgsz=800,
device="0" if _is_cuda_available() else "cpu",
verbose=False,
)
for result in results:
for box in result.boxes:
cls_id = int(box.cls[0].item())
conf_val = float(box.conf[0].item())
x1n, y1n, x2n, y2n = box.xyxyn[0].tolist()
sym_type = SYMBOL_CLASSES[cls_id] if cls_id < len(SYMBOL_CLASSES) else "UNKNOWN"
symbols.append({
"symbol_type" : sym_type,
"inferred_tag": None,
"ymin" : round(y1n, 4),
"xmin" : round(x1n, 4),
"ymax" : round(y2n, 4),
"xmax" : round(x2n, 4),
"confidence" : round(conf_val, 3),
})
logger.info(
f"SymbolRecognitionAgent (yolo_trained): detected {len(symbols)} symbols "
f"from '{os.path.basename(weights_path)}'."
)
except ImportError:
logger.error(
"ultralytics not installed. Run: pip install ultralytics. "
"Falling back to heuristic harvester."
)
except Exception as yolo_err:
logger.error(f"Trained YOLOv8 inference failed ({yolo_err}). Falling back to heuristic harvester.")
+11
View File
@@ -26,8 +26,12 @@ class EquipmentItem(BaseModel):
flow_rate: Optional[str] = Field(default=None, description="Flow rate (e.g., 62809 kg/h)")
duty: Optional[str] = Field(default=None, description="Duty rating (e.g., 1835 kW)")
material: Optional[str] = Field(default=None, description="Material of construction")
vendor: Optional[str] = Field(default=None, description="Equipment vendor or manufacturer")
quantity: Optional[str] = Field(default=None, description="Quantity and duty (e.g., 1x100%)")
location: Optional[str] = Field(default=None, description="Physical location or footprint grid reference")
coordinates: Optional[List[float]] = Field(default=None, description="Bounding box [ymin, xmin, ymax, xmax]")
aliases: Optional[List[str]] = Field(default=None, description="Alternative tag forms seen on drawing (e.g. short form without area prefix)")
confidence: float = Field(default=1.0, description="Extraction confidence score 0–1")
class LineItem(BaseModel):
@@ -51,6 +55,9 @@ class InstrumentItem(BaseModel):
location: Optional[str] = Field(default="Field", description="Physical location (e.g., Field, UCP, Control Room)")
loop_id: Optional[str] = Field(default=None, description="Instrument loop identifier number (e.g., 9055)")
coordinates: Optional[List[float]] = Field(default=None, description="Bounding box [ymin, xmin, ymax, xmax]")
aliases: Optional[List[str]] = Field(default=None, description="Alternative tag forms (e.g., bare form without area prefix)")
confidence: float = Field(default=1.0, description="Extraction confidence score 0–1")
flag_reason: Optional[str] = Field(default=None, description="Reason for low confidence or flagging (e.g., ambiguous_setpoint_vs_tag)")
class ValveItem(BaseModel):
@@ -62,6 +69,9 @@ class ValveItem(BaseModel):
rating: Optional[str] = Field(default=None, description="Pressure rating class (e.g., 150#, 300#, 2500#)")
normal_state: Optional[str] = Field(default=None, description="Normal operation state (e.g., CSO, LO, N)")
coordinates: Optional[List[float]] = Field(default=None, description="Bounding box [ymin, xmin, ymax, xmax]")
aliases: Optional[List[str]] = Field(default=None, description="Alternative tag forms seen on drawing")
type_source: str = Field(default="inferred_from_prefix", description="How valve type was determined: inferred_from_prefix | legend_verified")
confidence: float = Field(default=1.0, description="Extraction confidence score 0–1")
class SafetyReliefValveItem(BaseModel):
@@ -86,6 +96,7 @@ class Relationship(BaseModel):
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")
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)")
@property
def source_tag(self) -> str:
+5 -1
View File
@@ -1,4 +1,4 @@
from typing import List, Dict, Any, TypedDict, Optional, Annotated
from typing import List, Dict, Any, TypedDict, Optional, Annotated, Set
from src.models import UniversalEngineeringGraph
def merge_entities(left: Optional[Dict[str, Any]], right: Optional[Dict[str, Any]]) -> Dict[str, Any]:
@@ -95,3 +95,7 @@ class GraphState(TypedDict):
yolo_conf: Optional[float] # confidence threshold (default 0.25)
yolo_iou: Optional[float] # NMS IoU threshold (default 0.45)
# Defect 1 Fix: OCR token set built from primary PDF \u2014 used by provenance filter
# in CompilerAgent to drop cross-document contaminated relationship edges.
ocr_token_set: Optional[Set[str]]
+245
View File
@@ -0,0 +1,245 @@
"""
Datasheet Block Detector & PSV Set-Pressure Parser.
Extracts structured equipment datasheet fields and PSV set pressures
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
import re
import logging
from typing import Dict, Any, List, Optional
logger = logging.getLogger(__name__)
# ─── Equipment Datasheet Field Patterns ──────────────────────────────────────
_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',
'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),
},
{
'field': 'flow_rate',
'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),
},
{
'field': 'design_pressure',
'label_re': re.compile(
r'\b(?:DESIGN\s*PRESS(?:URE)?|DISC(?:HARGE)?\s*(?:PRESS(?:URE)?|OP(?:ERATING)?)|'
r'MAX(?:IMUM)?\s*ALLOW(?:ABLE)?\s*(?:WORKING|OPERATING)?\s*PRESS(?:URE)?|MAWP|'
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': 'design_temperature',
'label_re': re.compile(
r'\b(?:DESIGN\s*TEMP(?:ERATURE)?|OPERATING\s*TEMP(?:ERATURE)?|MAX\s*TEMP(?:ERATURE)?|DT)\b',
re.I),
'value_re': re.compile(r'((?:-?\d+\s*/\s*)?-?\d+\s*°?\s*[CF])', re.I),
},
{
'field': 'material',
'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)
},
{
'field': 'vendor',
'label_re': re.compile(r'\b(?:VENDOR|MANUFACTURER|SUPPLIER|MFR)\b', re.I),
'value_re': re.compile(r'(.{3,50})', re.I),
},
{
'field': 'quantity',
'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),
},
{
'field': 'service',
'label_re': re.compile(r'\b(?:SERVICE|FLUID|DESCRIPTION|APPLICATION)\b', re.I),
'value_re': re.compile(r'(.{3,80})', re.I),
},
{
'field': 'type',
'label_re': re.compile(
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),
},
]
# ─── PSV Set Pressure Pattern ────────────────────────────────────────────────
_SP_PATTERN = re.compile(
r'SP\s*=\s*([\d.,]+\s*(?:bar[\s(g)]*|barg|psig|kPag))',
re.IGNORECASE
)
_SET_PRESSURE_PATTERN = re.compile(
r'SET\s*PRESS(?:URE)?\s*[=:]\s*([\d.,]+\s*(?:bar[\s(g)]*|barg|psig|kPag))',
re.IGNORECASE
)
# Equipment tag pattern for anchoring
_EQUIP_TAG_RE = re.compile(r'\b\d{0,3}-?[A-Z]{1,3}-\d{2,5}[A-Z]?\b', re.IGNORECASE)
# PSV tag pattern
_PSV_TAG_RE = re.compile(r'\b(?:\d{0,3}-?)?PSV-\d{3,5}[A-Z]?\b', re.IGNORECASE)
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')
if val is None:
return -1.0
try:
return float(val)
except (ValueError, TypeError):
return -1.0
def parse_equipment_datasheets(
ocr_items: List[Dict[str, Any]],
) -> 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 = [
item for item in ocr_items
if item.get('classification') == 'EQUIPMENT_TAG'
]
results: Dict[str, Dict[str, str]] = {}
# For each OCR item, check if it's a datasheet label line
for item in ocr_items:
text = (item.get('text') or item.get('value') or item.get('tag') or '').strip()
if not text or len(text) < 3:
continue
for field_def in _DATASHEET_FIELDS:
if not field_def['label_re'].search(text):
continue
# Found a datasheet label — extract the value
# 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:
continue
# Find the nearest equipment tag by Y-position
item_y = _get_float_y(item)
if item_y < 0:
# No position info — skip spatial anchor, try global assignment
continue
best_tag: Optional[str] = None
best_dist = 0.15 # max Y-distance threshold (normalized)
for anchor in equip_anchors:
anchor_y = _get_float_y(anchor)
if anchor_y < 0:
continue
dist = abs(item_y - anchor_y)
if dist < best_dist:
best_dist = dist
best_tag = anchor.get('tag') or anchor.get('value')
if best_tag:
if best_tag not in results:
results[best_tag] = {}
# Don't overwrite if already set by closer item
if field_def['field'] not in results[best_tag]:
results[best_tag][field_def['field']] = value
logger.debug(
f"Datasheet: {best_tag}.{field_def['field']} = '{value}' "
f"(Y-dist={best_dist:.3f})"
)
if results:
total_fields = sum(len(v) for v in results.values())
logger.info(
f"Datasheet parser: found {total_fields} field values "
f"across {len(results)} equipment tags."
)
else:
logger.info("Datasheet parser: no equipment datasheet blocks found.")
return results
def parse_psv_set_pressures(
ocr_items: List[Dict[str, Any]],
) -> 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 = [
item for item in ocr_items
if item.get('classification') == 'PSV_TAG'
]
results: Dict[str, str] = {}
for item in ocr_items:
text = (item.get('text') or item.get('value') or item.get('tag') or '').strip()
if not text:
continue
# Try SP= or SET PRESSURE= match
val_match = _SP_PATTERN.search(text) or _SET_PRESSURE_PATTERN.search(text)
if not val_match:
continue
sp_value = val_match.group(1).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'barg', 'bar(g)', sp_value, flags=re.I)
item_y = _get_float_y(item)
best_tag: Optional[str] = None
best_dist = 0.10 # max Y-distance to anchor PSV tag
for anchor in psv_anchors:
anchor_y = _get_float_y(anchor)
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:
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] = sp_value
logger.info(f"PSV set pressure: {best_tag} → '{sp_value}' (Y-dist={best_dist:.3f})")
if 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.")
return results
+8 -6
View File
@@ -63,12 +63,14 @@ def trace_lines_and_connections(
if lines is not None:
logger.info(f"line_tracer: Hough Transform detected {len(lines)} raw line segments.")
for line in lines[:100]:
x1, y1, x2, y2 = line[0]
ny1 = round(y1 / max(img_h, 1), 4)
nx1 = round(x1 / max(img_w, 1), 4)
ny2 = round(y2 / max(img_h, 1), 4)
nx2 = round(x2 / max(img_w, 1), 4)
hough_polylines.append([[ny1, nx1], [ny2, nx2]])
pts = line.reshape(-1)
if len(pts) >= 4:
x1, y1, x2, y2 = pts[:4]
ny1 = round(float(y1) / max(img_h, 1), 4)
nx1 = round(float(x1) / max(img_w, 1), 4)
ny2 = round(float(y2) / max(img_h, 1), 4)
nx2 = round(float(x2) / max(img_w, 1), 4)
hough_polylines.append([[ny1, nx1], [ny2, nx2]])
except Exception as cv_err:
logger.warning(f"line_tracer: OpenCV line extraction failed ({cv_err}). Using spatial fallbacks.")
+30 -9
View File
@@ -144,16 +144,27 @@ def _get_easyocr():
def _run_easyocr(image_path: str, img_w: int, img_h: int) -> List[Dict[str, Any]]:
"""Run EasyOCR and normalize output to standard item format."""
"""Run EasyOCR on loaded image numpy array and normalize output."""
reader = _get_easyocr()
# EasyOCR returns: list of (bbox, text, confidence)
# bbox = [[x1,y1],[x2,y1],[x2,y2],[x1,y2]]
raw = reader.readtext(image_path, detail=1, paragraph=False,
import cv2
img_cv = cv2.imread(image_path)
if img_cv is None:
return []
raw = reader.readtext(img_cv, detail=1, paragraph=False,
min_size=5, text_threshold=0.4, low_text=0.25,
decoder='greedy', workers=0)
items = []
for (bbox, text, conf) in raw:
if not text.strip() or conf < 0.15:
for res in raw:
if len(res) == 3:
bbox, text, conf = res
elif len(res) == 2:
bbox, text = res
conf = 0.90
else:
continue
if not text.strip() or float(conf) < 0.15:
continue
xs = [pt[0] for pt in bbox]
ys = [pt[1] for pt in bbox]
@@ -306,9 +317,19 @@ def run_paddle_ocr(image_path: str) -> List[Dict[str, Any]]:
Returns list of dicts with: text, confidence, bbox, center_x, center_y.
"""
if not os.path.exists(image_path):
logger.error(f"Image not found: '{image_path}'")
return []
# ── Check for original PDF vector text first ──────────────────────────────
try:
parent_dir = os.path.dirname(os.path.dirname(image_path))
if os.path.exists(parent_dir):
pdf_candidates = [f for f in os.listdir(parent_dir) if f.lower().endswith(".pdf")]
if pdf_candidates:
pdf_path = os.path.join(parent_dir, pdf_candidates[0])
pdf_items = run_pdf_text_extraction(pdf_path)
if len(pdf_items) > 20:
logger.info(f"run_paddle_ocr: PyMuPDF vector text layer extracted {len(pdf_items)} items from '{pdf_candidates[0]}'.")
return pdf_items
except Exception as pdf_chk_err:
logger.warning(f"PyMuPDF vector text check warning: {pdf_chk_err}")
# Get image dimensions for normalization
img_w, img_h = 1, 1
+98
View File
@@ -0,0 +1,98 @@
"""
Provenance Filter — Cross-Document Contamination Guard.
Ensures every relationship in the output can be traced back to a tag that was
actually extracted from the PRIMARY input PDF, not from reference/legend sheets
uploaded alongside it.
Usage in CompilerAgent:
from src.utils.provenance import build_ocr_token_set, filter_relationships_by_provenance
"""
from __future__ import annotations
import logging
import re
from typing import Dict, Any, List, Set, Tuple
logger = logging.getLogger(__name__)
# Regex to canonicalize a tag for provenance matching: strip area prefix, uppercase
_PREFIX_RE = re.compile(r'^\d{2,3}-', re.IGNORECASE)
def _canonical(tag: str) -> str:
"""Strip leading unit prefix and uppercase for provenance comparison."""
return _PREFIX_RE.sub('', tag.strip().upper())
def build_ocr_token_set(ocr_items: List[Dict[str, Any]]) -> Set[str]:
"""
Build a set of canonical tag strings from the primary PDF's OCR result.
Both raw and canonicalized forms are stored so either variant matches.
Args:
ocr_items: List of classified items from classify_paddle_results().
Returns:
Set of uppercase tag strings (raw + canonical, no area prefix).
"""
token_set: Set[str] = set()
for item in ocr_items:
tag = item.get('tag') or item.get('text') or item.get('value') or ''
if tag:
raw = tag.strip().upper()
canon = _canonical(raw)
token_set.add(raw)
token_set.add(canon)
logger.info(f"Provenance: built token set with {len(token_set)} entries from {len(ocr_items)} OCR items.")
return token_set
def filter_relationships_by_provenance(
relations: List[Dict[str, Any]],
token_set: Set[str],
) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
"""
Filter out relationship edges where BOTH source and target tags are absent
from the primary PDF's OCR token set — these are cross-document contamination.
A relationship is kept if EITHER the source OR target appears in the primary
document's token set (one legitimate anchor is sufficient to keep an edge).
Both must be absent for the edge to be dropped.
Args:
relations: List of relationship dicts with 'source_tag', 'target_tag', 'rel_type'.
token_set: Set returned by build_ocr_token_set() for the primary PDF.
Returns:
(clean_relations, dropped_relations) tuple.
"""
clean: List[Dict[str, Any]] = []
dropped: List[Dict[str, Any]] = []
for rel in relations:
src = (rel.get('source_tag') or rel.get('source') or '').strip().upper()
tgt = (rel.get('target_tag') or rel.get('target') or '').strip().upper()
src_in = src in token_set or _canonical(src) in token_set
tgt_in = tgt in token_set or _canonical(tgt) in token_set
if not src_in and not tgt_in:
# Both tags are foreign — cross-document contamination
logger.warning(
f"Provenance DROP: '{src}' → '{tgt}' "
f"— neither tag found in primary PDF OCR."
)
dropped.append({**rel, 'flag_reason': 'cross_document_contamination'})
else:
clean.append(rel)
if dropped:
logger.info(
f"Provenance filter: kept {len(clean)}, dropped {len(dropped)} "
f"cross-document relationships."
)
else:
logger.info(f"Provenance filter: all {len(clean)} relationships verified clean.")
return clean, dropped
+200 -17
View File
@@ -317,6 +317,112 @@ _OCR_CORRECTIONS = [
]
# ──────────────────────────────────────────────────────────────────────────────
# Defect 3 Fix: Setpoint negative-context guard
# Prevents setpoint numbers (PI-150, AT-225) being classified as instrument tags
# ──────────────────────────────────────────────────────────────────────────────
_SETPOINT_CONTEXT_RE = re.compile(
r'\b(?:SD|HH|LL|HIGH\s*HIGH|LOW\s*LOW|TRIP|SHUT\s*DOWN|'
r'SP\s*=|SET\s*PRESS(?:URE)?|SETPOINT|'
r'MAX(?:IMUM)?|MIN(?:IMUM)?|DESIGN|'
r'MAWP|MAPD|MOP|MAOP|'
r'BARG|BAR\(G\)|PSIG|KPAG|MPA(?:G)?|'
r'\d+\.\d+\s*BAR|\d+\s*°[CF]|\d+\s*DEG(?:REE)?|'
r'H\s*:|L\s*:|HH\s*:|LL\s*:|ALARM|INTERLOCK)',
re.IGNORECASE
)
_WINDOW = 35 # characters to scan before/after match for setpoint context
def _is_setpoint_context(full_text: str, match_start: int, match_end: int) -> bool:
"""
Returns True if a setpoint/note keyword appears within _WINDOW chars
before or after the instrument tag match position.
This prevents classifying 'PI-150' in 'SD HH: 150 barg' as a real tag.
"""
window_text = full_text[max(0, match_start - _WINDOW): match_end + _WINDOW]
return bool(_SETPOINT_CONTEXT_RE.search(window_text))
# ──────────────────────────────────────────────────────────────────────────────
# Defect 4 Fix: Line tag grammar enforcement helpers
# ──────────────────────────────────────────────────────────────────────────────
# Strip NOTE xx references before line-tag matching
_NOTE_REF_STRIP_RE = re.compile(r'\s*NOTE\s*\d+', re.IGNORECASE)
# Valid nominal pipe sizes (NPS inches and DN metric)
_VALID_INCH_SIZES = {
'1/2', '3/4', '1', '1-1/4', '1-1/2', '2', '2-1/2', '3', '4',
'6', '8', '10', '12', '14', '16', '18', '20', '24',
}
_VALID_MM_SIZES = {
'15mm', '20mm', '25mm', '32mm', '40mm', '50mm', '65mm', '80mm',
'100mm', '125mm', '150mm', '200mm', '250mm', '300mm', '350mm',
'400mm', '450mm', '500mm', '600mm',
}
# Reject tokens where the numeric prefix has > 3 consecutive digits with inch mark
# (e.g. 262" is impossible, 12" is valid) OR bare digit-only size > 24" (> 600mm)
_CORRUPT_SIZE_RE = re.compile(r'^(\d{4,})"?$', re.IGNORECASE)
def _validate_line_tag_size(tag: str) -> tuple:
"""
Validate the size prefix of a line tag.
Returns (is_valid: bool, flag_reason: str or None).
"""
parts = tag.split('-')
if not parts:
return True, None
p0 = parts[0].strip()
# Check if there is a size token at all
if not re.match(r'^[\d/]', p0):
return True, None # No size prefix — that's OK
has_inch = '"' in p0 or "'" in p0
# Strip inch mark and whitespace for comparison
size_clean = p0.replace('"', '').replace("'", '').replace(' ', '').lower()
# 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):
return False, f'invalid_pipe_size_corrupt_merge({p0})'
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:
return True, None
# Accept fractional sizes like 3/4
if re.match(r'^\d+/\d+$', size_clean):
if size_clean in _VALID_INCH_SIZES:
return True, None
# Fraction not in whitelist — flag but keep
return True, 'unrecognized_fraction_size'
# Numeric but not in whitelist
if re.match(r'^\d+$', size_clean):
try:
n = int(size_clean)
if has_inch and n > 60:
return False, f'invalid_pipe_size_corrupt_merge({p0})'
if 1 <= n <= 600: # plausible DN size
return True, 'unverified_size_token'
except ValueError:
pass
return False, f'invalid_pipe_size_out_of_range({p0})'
return True, None
# ──────────────────────────────────────────────────────────────────────────────
# Defect 2 Fix: Tag canonicalization for deduplication
# ──────────────────────────────────────────────────────────────────────────────
_AREA_PREFIX_RE = re.compile(r'^\d{2,3}-', re.IGNORECASE)
def canonicalize_tag(tag: str) -> str:
"""
Strip leading unit/area number prefix (e.g. '26-', '43-') from a tag
to get the canonical form used for deduplication.
'26-PIT-9087' → 'PIT-9087', 'PIT-9087' → 'PIT-9087'
"""
return _AREA_PREFIX_RE.sub('', tag.strip().upper())
def _ocr_correct(text: str) -> str:
"""Apply context-aware OCR character corrections before regex classification."""
for pattern, replacement in _OCR_CORRECTIONS:
@@ -337,14 +443,21 @@ def classify_paddle_results(
) -> List[Dict[str, Any]]:
"""
Scan ALL OCR items for embedded engineering tags using drawing-type-aware patterns.
Fixes applied:
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 4: Line-tag grammar validation — validates pipe-size tokens and strips NOTE refs.
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.
"""
found: Dict[str, Dict] = {} # tag → item (deduplicated by tag string)
found: Dict[str, Dict] = {} # tag → item (deduplicated by EXACT tag string)
dt = (drawing_type or 'PID').upper()
for item in items:
text = item.get('text', '').strip()
conf = item.get('confidence', 0)
conf = float(item.get('confidence', 0))
if conf < 0.10 or not text:
continue
@@ -357,6 +470,7 @@ def classify_paddle_results(
item_added = False
# ── 1. Specific Engineering Tag Extraction ─────────────────────────────
# PSV tags
for m in _PSV_SEARCH.finditer(t):
tag = m.group(1).upper()
@@ -364,11 +478,32 @@ def classify_paddle_results(
found[tag] = _make_item(tag, 'PSV_TAG', conf, item)
item_added = True
# Line tags
# Line tags — Defect 4: strip NOTE refs, validate pipe size
for m in _LINE_SEARCH.finditer(t):
tag = re.sub(r'\s+', '', m.group(1)).upper()
raw_tag = m.group(1)
# Strip NOTE xx references before processing
raw_tag_clean = _NOTE_REF_STRIP_RE.sub('', raw_tag).strip().rstrip('-')
tag = re.sub(r'\s+', '', raw_tag_clean).upper()
if not tag or len(tag) < 4:
continue
flag_reason = None
tag_conf = conf
size_valid, size_flag = _validate_line_tag_size(tag)
if not size_valid:
# Invalid size — flag but emit for human review
flag_reason = size_flag
tag_conf = min(conf, 0.5)
elif size_flag:
flag_reason = size_flag
tag_conf = min(conf, 0.75)
if raw_tag_clean != raw_tag.strip():
# NOTE was stripped — record it
note_ref = _NOTE_REF_STRIP_RE.search(raw_tag)
if note_ref and not flag_reason:
flag_reason = f'note_ref_stripped({note_ref.group().strip()})'
if tag not in found:
found[tag] = _make_item(tag, 'LINE_TAG', conf, item)
found[tag] = _make_item(tag, 'LINE_TAG', tag_conf, item,
flag_reason=flag_reason)
item_added = True
# Project-prefix tags (instruments + equipment)
@@ -383,8 +518,6 @@ def classify_paddle_results(
continue
if full_tag in found and found[full_tag]['classification'] != 'NOTE':
continue
# ISA 5.1 valve codes with 4+ digit sequence → always VALVE_TAG
# (GB, CB, BL, GT are valves when seq >= 4 digits; equipment when seq <= 3)
_VALVE_FUNCTION_CODES = {'CB', 'GB', 'BL', 'GT', 'BT', 'GL', 'NV'}
if code in _VALVE_FUNCTION_CODES and len(re.sub(r'\D', '', seq)) >= 4:
cat = 'VALVE_TAG'
@@ -400,12 +533,21 @@ def classify_paddle_results(
found[full_tag] = _make_item(full_tag, cat, conf, item)
item_added = True
# Bare instrument tags
# Bare instrument tags — Defect 3: setpoint negative-context guard
for m in _BARE_INSTRUMENT_SEARCH.finditer(t):
tag = m.group(1).upper()
if tag not in found:
if tag in found:
continue
if _is_setpoint_context(t, m.start(), m.end()):
# Matches setpoint-like context — demote to NOTE with flag
found[tag] = _make_item(
tag, 'NOTE', min(conf, 0.25), item,
flag_reason='ambiguous_setpoint_vs_tag'
)
logger.debug(f"Setpoint guard: demoted '{tag}' to NOTE (context: '{t[:60]}...')")
else:
found[tag] = _make_item(tag, 'INSTRUMENT_TAG', conf, item)
item_added = True
item_added = True
# Valve tags
for m in _VALVE_SEARCH.finditer(t):
@@ -415,7 +557,7 @@ def classify_paddle_results(
found[tag] = _make_item(tag, 'VALVE_TAG', conf, item)
item_added = True
# Electrical / Earthing / SLD / Lighting patterns (un-gated for 100% sensitivity across all drawing types)
# Electrical / Earthing / SLD / Lighting patterns
for m in _EARTH_BAR_SEARCH.finditer(t):
tag = m.group(1).upper()
if tag not in found:
@@ -447,15 +589,13 @@ def classify_paddle_results(
found[tag] = _make_item(tag, 'LUMINAIRE_TAG', conf, item)
item_added = True
# Generic equipment — guarded with prefix allowlist (Fix 4)
# Generic equipment — guarded with prefix allowlist
for m in _GENERIC_EQUIP_PATTERN.finditer(t):
tag = m.group(1).upper()
if tag not in found:
prefix = tag.split('-')[0].upper()
# Reject spec codes, service codes (PV-26, VA-26), and drawing refs
if _SPEC_CODE_PATTERN.match(tag) or _SERVICE_CODE_PATTERN.match(tag):
continue
# Only accept known equipment prefixes; reject spec codes / line refs
if (prefix in _EQUIP_PREFIX_ALLOWLIST
and not _EQUIP_REJECT_PATTERN.match(tag)
and len(prefix) <= 3):
@@ -477,11 +617,41 @@ def classify_paddle_results(
item_added = True
# ── 2. Universal Note Preservation ────────────────────────────────────
# If the item did not contain a specific tag, preserve it as a NOTE
if not item_added and len(t) >= 3:
if t not in found:
found[t] = _make_item(t, 'NOTE', conf, item)
# ── Defect 2 Fix: Post-deduplication pass ─────────────────────────────────
# Merge items whose canonical form (strip area prefix) is identical.
# Keep the longer (project-prefixed) tag; record short form as alias.
canonical_map: Dict[str, str] = {} # canonical_key → winning raw tag
_ENG_CLASSES = {
'INSTRUMENT_TAG', 'VALVE_TAG', 'EQUIPMENT_TAG', 'PSV_TAG', 'LINE_TAG',
}
for tag, item in list(found.items()):
if item['classification'] not in _ENG_CLASSES:
continue
ck = canonicalize_tag(tag)
if ck in canonical_map:
winner_tag = canonical_map[ck]
loser_tag = tag
# Prefer the longer (project-prefixed) form
if len(tag) > len(winner_tag):
winner_tag, loser_tag = tag, winner_tag
canonical_map[ck] = winner_tag
# Merge alias into winner
winner_item = found[winner_tag]
aliases = winner_item.get('aliases') or []
if loser_tag not in aliases and loser_tag != winner_tag:
aliases.append(loser_tag)
winner_item['aliases'] = aliases
# Remove loser from found (replaced by winner)
if loser_tag in found and loser_tag != winner_tag:
del found[loser_tag]
logger.debug(f"Dedup: merged '{loser_tag}' into '{winner_tag}' (alias)")
else:
canonical_map[ck] = tag
results = list(found.values())
# Sort: engineering tags first, notes last
@@ -495,18 +665,28 @@ def classify_paddle_results(
results.sort(key=lambda x: priority.get(x['classification'], 99))
breakdown = {}
flagged = 0
for r in results:
breakdown[r['classification']] = breakdown.get(r['classification'], 0) + 1
if r.get('flag_reason'):
flagged += 1
logger.info(
f"[{dt}] Tag classifier extracted {len(results)} total items from "
f"{len(items)} OCR items. Breakdown: "
+ ', '.join(f"{k}:{v}" for k, v in sorted(breakdown.items()))
+ (f" | Flagged: {flagged}" if flagged else "")
)
return results
def _make_item(tag: str, classification: str, conf: float, raw_item: dict) -> dict:
"""Create a structured classification result dict."""
def _make_item(
tag: str,
classification: str,
conf: float,
raw_item: dict,
flag_reason: Optional[str] = None,
) -> dict:
"""Create a structured classification result dict with confidence and flag_reason."""
attrs = {
'ocr_confidence': str(round(conf, 2)),
'pos_x': str(raw_item.get('center_x', 0)),
@@ -518,6 +698,9 @@ def _make_item(tag: str, classification: str, conf: float, raw_item: dict) -> di
'value': tag,
'rating': None,
'attributes': attrs,
'confidence': round(conf, 3),
'flag_reason': flag_reason,
'aliases': [],
}