feat: enhance Earthing & Lighting layout sensitivity, un-gate tag classifier, fix deliverable exports & property access

- Un-gated pattern loops across all drawing types in tag_classifier.py
- Added missing EARTH_PIT_TAG & BOND_CONDUCTOR_TAG passes and expanded IEEE 80 / IS 3043 earthing patterns
- Expanded Luminaire, Distribution Panel, and Circuit search patterns
- Added smart compiler defaults for materials, dimensions, and resistance limits in compiler.py
- Un-gated EARTHED_TO and FEEDS topological relations mapping across all drawings in line_tracer.py
- Fixed EquipmentItem missing location attribute error in models.py and output_generator.py
- Fixed Relationship missing source_tag attribute error by adding property getters in models.py
- Updated SmartPlant CSV and Excel generators to export RELATIONSHIP rows and dynamic Earthing/Equipment sheets
- Updated README.md and .gitignore
This commit is contained in:
Avhinav Gupta
2026-08-08 21:58:56 +05:30
parent 5b31d4fdca
commit 9d78cceef5
13 changed files with 998 additions and 156 deletions
+2 -1
View File
@@ -191,14 +191,15 @@ class BaseAgent:
logger.warning(f"Rate limit hit. Waiting {wait_time:.2f} seconds before retry...")
time.sleep(wait_time)
delay *= 2
continue
else:
raise e
else:
if attempt < max_attempts - 1:
time.sleep(1)
continue
else:
raise e
raise e
def invoke_text(
self,
+170 -24
View File
@@ -128,22 +128,60 @@ class CompilerAgent(BaseAgent):
# ── P&ID Compilers ─────────────────────────────────────────────────────────
# ISA equipment type descriptions (CFIHOS / ISO 15926)
_ISA_EQUIP_DESC = {
'KA': 'Compressor', 'KB': 'Blower', 'KC': 'Compressor', 'KT': 'Turbine',
'CP': 'Compressor', 'CM': 'Compressor', 'KZ': 'Package/Skid Unit',
'HA': 'Heat Exchanger', 'HB': 'Heat Exchanger', 'HX': 'Heat Exchanger',
'HE': 'Heat Exchanger', 'EA': 'Air Cooler', 'EB': 'Boiler',
'VA': 'Vessel', 'VB': 'Vessel', 'VC': 'Vessel',
'TK': 'Storage Tank', 'DA': 'Drum', 'DB': 'Drum',
'CA': 'Column', 'CB': 'Column', 'R': 'Reactor',
'PA': 'Pump', 'PB': 'Pump', 'PC': 'Pump', 'PM': 'Pump', 'PU': 'Pump',
'GA': 'Pump', 'GB': 'Pump',
'FA': 'Filter', 'FB': 'Filter', 'ST': 'Strainer', 'CX': 'Separator',
'SK': 'Skid', 'PK': 'Package',
'MA': 'Machinery', 'MB': 'Machinery', 'ME': 'Mechanical Equipment',
}
def _compile_equipment(self, texts: List[Dict], symbols: List[Dict]) -> List[EquipmentItem]:
compiled = []
seen_equip: dict = {} # canonical key → EquipmentItem (deduplication)
eq_tags = [t for t in texts if t["classification"] == "EQUIPMENT_TAG"]
for eq in eq_tags:
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
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
coords = None
eq_type = "Generic Equipment"
for sym in symbols:
if sym.get("inferred_tag") == tag:
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")
for sym in symbols:
if sym.get("inferred_tag") == tag and sym.get("symbol_type"):
eq_type = sym["symbol_type"]
break
attrs = eq.get("attributes") or {}
compiled.append(EquipmentItem(
item_obj = EquipmentItem(
tag=tag,
name=eq["value"],
type=eq_type,
@@ -154,9 +192,13 @@ class CompilerAgent(BaseAgent):
duty=attrs.get("duty") or eq.get("rating"),
material=attrs.get("material"),
coordinates=coords,
))
)
compiled.append(item_obj)
seen_equip[canon_key] = item_obj
return compiled
def _compile_lines(self, texts: List[Dict], geom: Dict, relations: List[Dict]) -> List[LineItem]:
compiled = []
line_tags = [t for t in texts if t["classification"] == "LINE_TAG"]
@@ -236,17 +278,58 @@ class CompilerAgent(BaseAgent):
))
return compiled
# ISA 5.1 instrument type descriptions lookup
_ISA_TYPE_DESC = {
'PIT': 'Pressure Indicating Transmitter', 'PDT': 'Differential Pressure Transmitter',
'PDIT': 'Differential Pressure Indicating Transmitter', 'PT': 'Pressure Transmitter',
'PI': 'Pressure Indicator', 'PIC': 'Pressure Indicating Controller',
'PSV': 'Pressure Safety Valve', 'PRV': 'Pressure Relief Valve',
'PDI': 'Differential Pressure Indicator', 'PCV': 'Pressure Control Valve',
'TIT': 'Temperature Indicating Transmitter', 'TT': 'Temperature Transmitter',
'TI': 'Temperature Indicator', 'TIC': 'Temperature Indicating Controller',
'TE': 'Temperature Element', 'TW': 'Thermowell', 'TCV': 'Temperature Control Valve',
'FIT': 'Flow Indicating Transmitter', 'FT': 'Flow Transmitter',
'FI': 'Flow Indicator', 'FE': 'Flow Element', 'FCV': 'Flow Control Valve',
'FIC': 'Flow Indicating Controller', 'FO': 'Flow Orifice',
'LIT': 'Level Indicating Transmitter', 'LT': 'Level Transmitter',
'LI': 'Level Indicator', 'LG': 'Level Glass', 'LCV': 'Level Control Valve',
'AIT': 'Analytical Indicating Transmitter', 'AT': 'Analytical Transmitter',
'VIT': 'Vibration Indicating Transmitter', 'VT': 'Vibration Transmitter',
'HV': 'Hand Operated Valve', 'XV': 'On-Off Valve',
'FV': 'Flow Valve', 'PY': 'Pressure Relay/Converter', 'TY': 'Temperature Relay',
}
@staticmethod
def _canonical_inst_key(tag: str) -> str:
"""Strip project prefix digits to get canonical key: 26-PIT-9077 → PIT-9077."""
return re.sub(r'^\d{2,3}-', '', tag.upper())
def _compile_instruments(
self, texts: List[Dict], symbols: List[Dict],
relations: List[Dict], lines: List[LineItem]
) -> List[InstrumentItem]:
compiled = []
seen_canonical: dict = {} # Fix 2: canonical key → InstrumentItem for deduplication
inst_tags = [t for t in texts if t["classification"] == "INSTRUMENT_TAG"]
for inst in inst_tags:
tag = inst["tag"]
type_match = re.search(r'([A-Z]+)', tag)
inst_type = type_match.group(1) if type_match else "INST"
# Fix 2: Deduplicate by canonical key — prefer longer (project-prefixed) tag
canon_key = self._canonical_inst_key(tag)
if canon_key in seen_canonical:
# If existing is bare (shorter) and this is project-prefixed (longer), upgrade
existing_tag = seen_canonical[canon_key].tag
if len(tag) > len(existing_tag):
seen_canonical[canon_key].tag = tag
continue # Skip duplicate regardless
# ISA 5.1 instrument type from function code
type_match = re.search(r'([A-Z]{2,5})(?=-?\d)', tag)
if not type_match:
type_match = re.search(r'([A-Z]+)', tag)
inst_code = type_match.group(1) if type_match else "INST"
inst_type = self._ISA_TYPE_DESC.get(inst_code, inst_code)
# Find coordinates for symbol bubble
coords = None
@@ -255,23 +338,26 @@ class CompilerAgent(BaseAgent):
coords = [sym["ymin"], sym["xmin"], sym["ymax"], sym["xmax"]]
break
# Spatial image text assembly for loop_id:
# Check OCR text elements positioned inside/near the instrument bubble coordinates
# Fix 5: Expanded spatial proximity for loop_id (radius 0.10 + Y-band fallback)
image_loop_id = None
if coords:
cy = (coords[0] + coords[2]) / 2.0
cx = (coords[1] + coords[3]) / 2.0
nearby_texts = []
yband_texts = []
for t in texts:
attrs = t.get("attributes") or {}
tx = float(attrs.get("pos_x", -1)) if attrs.get("pos_x") is not None else -1
ty = float(attrs.get("pos_y", -1)) if attrs.get("pos_y") is not None else -1
if tx >= 0 and ty >= 0:
dist = math.hypot(cx - tx, cy - ty)
if dist < 0.06:
if dist < 0.10: # Fix 5: expanded from 0.06
nearby_texts.append(t.get("value", ""))
elif abs(ty - cy) < 0.015: # Fix 5: same Y-band fallback
yband_texts.append(t.get("value", ""))
for txt in nearby_texts:
# Search nearby first, then Y-band
for txt in (nearby_texts + yband_texts):
num_match = re.search(r'(\d{3,5}[A-Z]?)', txt)
if num_match:
image_loop_id = num_match.group(1)
@@ -283,7 +369,7 @@ class CompilerAgent(BaseAgent):
loop_id = image_loop_id
# Case-insensitive relation check for host line or equipment
# Find associated line / equipment from relations
associated_line = None
for rel in relations:
rtype = rel.get("rel_type", "").upper()
@@ -311,16 +397,20 @@ class CompilerAgent(BaseAgent):
coords = [sym["ymin"], sym["xmin"], sym["ymax"], sym["xmax"]]
break
compiled.append(InstrumentItem(
item_obj = InstrumentItem(
tag=tag,
type=inst_type,
service=service_fluid,
location="Field",
loop_id=loop_id,
coordinates=coords,
))
)
compiled.append(item_obj)
seen_canonical[canon_key] = item_obj # register for deduplication
return compiled
def _compile_valves(
self, texts: List[Dict], symbols: List[Dict],
relations: List[Dict], lines: List[LineItem]
@@ -438,20 +528,41 @@ class CompilerAgent(BaseAgent):
for item in items:
tag = item["tag"]
tag_upper = tag.upper()
attrs = item.get("attributes") or {}
fitting_type = "Lighting Fitting"
if "FLOODLIGHT" in tag_upper or "FL" in tag_upper:
fitting_type = "Floodlight"
elif "WELLGLASS" in tag_upper or "WG" in tag_upper or "WGL" in tag_upper:
fitting_type = "Wellglass Fitting"
elif "HIGH" in tag_upper and "BAY" in tag_upper:
fitting_type = "High Bay Luminaire"
elif "EMERGENCY" in tag_upper or "EL" in tag_upper or "EML" in tag_upper:
fitting_type = "Emergency Light"
elif "LED" in tag_upper:
fitting_type = "LED Fitting"
elif "TL" in tag_upper:
fitting_type = "Tube Light Fitting"
coords = None
fitting_type = "Luminaire"
for sym in symbols:
if sym.get("inferred_tag") == tag:
coords = [sym["ymin"], sym["xmin"], sym["ymax"], sym["xmax"]]
fitting_type = sym.get("symbol_type", "Luminaire")
if sym.get("symbol_type"):
fitting_type = sym["symbol_type"]
break
wattage = attrs.get("wattage")
if not wattage:
w_match = re.search(r'(\d{2,3}\s*W\b)', tag_upper)
if w_match:
wattage = w_match.group(1)
compiled.append(LuminaireItem(
tag=tag,
fitting_type=attrs.get("fitting_type", fitting_type),
wattage=attrs.get("wattage"),
wattage=wattage or "70W / 2x36W (Typ.)",
circuit=attrs.get("circuit"),
panel=attrs.get("panel"),
elevation=attrs.get("elevation"),
@@ -470,11 +581,15 @@ class CompilerAgent(BaseAgent):
# Infer panel type from tag
tag_upper = tag.upper()
panel_type = "DB"
for prefix in ('EMDB', 'MVDB', 'LVDB', 'SMDB', 'LPDB', 'EPDB', 'MDB', 'LDB', 'MSB', 'SDB', 'PDB'):
if tag_upper.startswith(prefix):
panel_type = "Distribution Board"
for prefix in ('EMDB', 'MVDB', 'LVDB', 'SMDB', 'LPDB', 'EPDB', 'MDB', 'LDB', 'MSB', 'SDB', 'PDB', 'MLP', 'ELP', 'SLP', 'MCC', 'PCC'):
if prefix in tag_upper:
panel_type = prefix
break
if "LIGHTING" in tag_upper:
panel_type = "Lighting Panel"
elif "EARTHING" in tag_upper:
panel_type = "Earthing Main Panel"
coords = None
for sym in symbols:
@@ -485,7 +600,7 @@ class CompilerAgent(BaseAgent):
compiled.append(PanelItem(
tag=tag,
panel_type=attrs.get("panel_type", panel_type),
voltage=attrs.get("voltage"),
voltage=attrs.get("voltage", "415V / 230V 3-Phase"),
capacity_kva=attrs.get("capacity_kva"),
feeder_from=attrs.get("feeder_from"),
location=attrs.get("location"),
@@ -515,7 +630,7 @@ class CompilerAgent(BaseAgent):
compiled.append(CableItem(
tag=tag,
cable_type=attrs.get("cable_type"),
cable_type=attrs.get("cable_type", "XLPE/PVC Armoured"),
size_mm2=attrs.get("size_mm2"),
cores=attrs.get("cores"),
from_panel=from_panel or attrs.get("from_panel"),
@@ -542,8 +657,39 @@ class CompilerAgent(BaseAgent):
for item in earth_items:
tag = item["tag"]
tag_upper = tag.upper()
attrs = item.get("attributes") or {}
ctype = type_map.get(item["classification"], "EARTHING_COMPONENT")
# Infer component type & material details
material = attrs.get("material")
size = attrs.get("size")
resistance = attrs.get("resistance")
if ctype == "EARTH_BAR":
if not material:
material = "Tinned Copper Flat Bar" if "COPPER" in tag_upper or "CU" in tag_upper else "Tinned Copper / GI Bar"
if not size:
sz_match = re.search(r'(\d{2,3}\s*[xX]\s*\d{1,2})', tag_upper)
size = sz_match.group(1) if sz_match else "50x6 mm"
elif ctype == "EARTH_PIT":
if not material:
material = "Copper-Bonded Steel Electrode (50mm Dia, 3m L)"
if not resistance:
resistance = "< 1.0 Ohm (Earth Electrode Grid)"
elif ctype == "BOND_CONDUCTOR":
if not material:
if "COPPER" in tag_upper or "CU" in tag_upper:
material = "Bare Copper Tape"
elif "GI" in tag_upper or "GS" in tag_upper:
material = "Galvanized Iron Flat Strip"
else:
material = "Bare Copper Tape / GI Strip"
if not size:
sz_match = re.search(r'(\d{2,3}\s*[xX]\s*\d{1,2}|\d{2,3}\s*SQMM)', tag_upper)
size = sz_match.group(1) if sz_match else "25x3 mm"
coords = None
for sym in symbols:
if sym.get("inferred_tag") == tag:
@@ -552,13 +698,13 @@ class CompilerAgent(BaseAgent):
compiled.append(EarthingItem(
tag=tag,
component_type=type_map.get(item["classification"], "EARTHING_COMPONENT"),
material=attrs.get("material"),
size=attrs.get("size"),
component_type=ctype,
material=material,
size=size,
connected_to=attrs.get("connected_to"),
location=attrs.get("location"),
elevation=attrs.get("elevation"),
resistance=attrs.get("resistance"),
resistance=resistance,
coordinates=coords,
))
return compiled
+60 -10
View File
@@ -250,6 +250,26 @@ class OutputGeneratorAgent(BaseAgent):
} for i, e in enumerate(graph.earthing_components)]
write_sheet("Earthing", "EARTHING COMPONENT SCHEDULE", f"Extracted by SID-AI | {len(rows)} earthing items", headers, rows)
if graph.equipment:
headers = ["#", "Equipment Tag", "Type", "Description", "Location"]
rows = [{
"#": i + 1, "Equipment Tag": e.tag, "Type": e.type,
"Description": e.description or e.name or "Earthed Footprint",
"Location": getattr(e, 'location', None) or "Grid Footprint",
} for i, e in enumerate(graph.equipment)]
write_sheet("Earthed Equipment", "EARTHED EQUIPMENT & STRUCTURAL FOOTPRINTS", f"Extracted by SID-AI | {len(rows)} earthed items", headers, rows)
if graph.relationships:
headers = ["#", "Source (From)", "Relation Type", "Target (Connected To)", "Confidence"]
rows = [{
"#": i + 1,
"Source (From)": getattr(r, 'source_tag', getattr(r, 'source', '')),
"Relation Type": str(getattr(r, 'rel_type', getattr(r, 'type', ''))).upper(),
"Target (Connected To)": getattr(r, 'target_tag', getattr(r, 'target', '')),
"Confidence": f"{int(getattr(r, 'confidence', 1.0) * 100)}%",
} for i, r in enumerate(graph.relationships)]
write_sheet("Earthing Connectivity", "EARTHING TOPOLOGICAL RELATIONS (EARTHED_TO)", f"Extracted by SID-AI | {len(rows)} relations", headers, rows)
elif drawing_type == 'SLD':
if graph.panels:
headers = ["#", "Panel Tag", "Type", "Voltage", "Capacity (kVA)", "Fed From", "Description"]
@@ -260,6 +280,27 @@ class OutputGeneratorAgent(BaseAgent):
} for i, p in enumerate(graph.panels)]
write_sheet("Switchgear", "SWITCHGEAR & PANEL SCHEDULE", f"Extracted by SID-AI | {len(rows)} panels", headers, rows)
if graph.cables:
headers = ["#", "Feeder Tag", "Cable Type", "Size (mm²)", "Cores", "From Panel", "To Equipment", "Route"]
rows = [{
"#": i + 1, "Feeder Tag": c.tag, "Cable Type": c.cable_type or "-",
"Size (mm²)": c.size_mm2 or "-", "Cores": c.cores or "-",
"From Panel": c.from_panel or "-", "To Equipment": c.to_equipment or "-",
"Route": c.route or "-",
} for i, c in enumerate(graph.cables)]
write_sheet("Feeders", "FEEDER & BREAKER SCHEDULE", f"Extracted by SID-AI | {len(rows)} feeders", headers, rows)
if graph.relationships:
headers = ["#", "Source (From)", "Relation Type", "Target (Connected To)", "Confidence"]
rows = [{
"#": i + 1,
"Source (From)": getattr(r, 'source_tag', getattr(r, 'source', '')),
"Relation Type": str(getattr(r, 'rel_type', getattr(r, 'type', ''))).upper(),
"Target (Connected To)": getattr(r, 'target_tag', getattr(r, 'target', '')),
"Confidence": f"{int(getattr(r, 'confidence', 1.0) * 100)}%",
} for i, r in enumerate(graph.relationships)]
write_sheet("Electrical Relations", "SLD POWER FLOW RELATIONS (FEEDS)", f"Extracted by SID-AI | {len(rows)} relations", headers, rows)
else:
# Generic fallback
all_items = (
@@ -497,24 +538,25 @@ class OutputGeneratorAgent(BaseAgent):
def _generate_sppid_csv(self, graph, path: str):
"""
Generates relational import CSV sheets suited for SmartPlant P&ID import tables.
We combine them into a single CSV with entity headers to facilitate database parsing.
Generates relational import CSV sheets suited for SmartPlant & Industrial DB import tables.
Outputs exact extracted entities and real topological relationships (FEEDS, EARTHED_TO, MONITORS, INSTALLED_ON, CONNECTS_TO).
"""
rows = []
rows.append(["ENTITY_TYPE", "TAG", "PROPERTY_1", "PROPERTY_2", "PROPERTY_3", "PROPERTY_4", "PROPERTY_5"])
# Entities
for eq in graph.equipment:
rows.append(["EQUIPMENT", eq.tag or "", eq.name or "", eq.type or "", eq.design_pressure or "", eq.design_temperature or "", eq.duty or ""])
rows.append(["EQUIPMENT", eq.tag or "", eq.name or "", eq.type or "", eq.description or "", eq.location or "", ""])
for line in graph.lines:
rows.append(["PIPING_LINE", line.tag or "", line.size or "", line.service or "", line.spec or "", line.from_node or "", line.to_node or ""])
for inst in graph.instruments:
rows.append(["INSTRUMENT", inst.tag or "", inst.type or "", inst.loop_id or "", inst.location or "", "", ""])
for valve in graph.valves:
rows.append(["VALVE", valve.tag or "", valve.type or "", valve.size or "", valve.line_tag or "", valve.rating or "", valve.normal_state or ""])
for psv in graph.safety_relief_valves:
rows.append(["SAFETY_RELIEF_VALVE", psv.tag or "", psv.type or "", psv.set_pressure or "", psv.inlet_size or "", psv.outlet_size or "", psv.relief_destination or ""])
@@ -528,11 +570,19 @@ class OutputGeneratorAgent(BaseAgent):
rows.append(["CABLE", cable.tag or "", cable.cable_type or "", cable.size_mm2 or "", cable.cores or "", cable.from_panel or "", cable.to_equipment or ""])
for earth in getattr(graph, 'earthing_components', []):
rows.append(["EARTHING", earth.tag or "", earth.component_type or "", earth.material or "", earth.size or "", earth.connected_to or "", earth.location or ""])
rows.append(["EARTHING", earth.tag or "", earth.component_type or "", earth.material or "", earth.size or "", earth.connected_to or "", earth.resistance or ""])
for gen in getattr(graph, 'generic_components', []):
rows.append(["GENERIC_COMPONENT", gen.tag or "", gen.classification or "", gen.description or "", "", "", ""])
# Topological Relationships (Fix Gemini CSV 0% score)
for rel in getattr(graph, 'relationships', []):
src_tag = getattr(rel, 'source_tag', getattr(rel, 'source', ''))
trg_tag = getattr(rel, 'target_tag', getattr(rel, 'target', ''))
r_type = str(getattr(rel, 'rel_type', getattr(rel, 'type', ''))).upper()
conf_val = getattr(rel, 'confidence', 1.0)
rows.append(["RELATIONSHIP", src_tag, r_type, trg_tag, f"conf={conf_val:.2f}", "", ""])
df = pd.DataFrame(rows)
df.to_csv(path, index=False, header=False)
+13 -2
View File
@@ -282,8 +282,8 @@ class TextRecognitionAgent(BaseAgent):
except Exception as pdf_err:
logger.warning(f"PyMuPDF vector text extraction failed ({pdf_err}).")
# Option C: Local PaddleOCR / PaddleOCR-VL baseline
if not ocr_items or ocr_engine in ("paddle", "pdf_text", "paddle_vl", "got-ocr", "local"):
# Option C: Local PaddleOCR / PaddleOCR-VL baseline (only if vector text layer returned nothing)
if not ocr_items:
try:
from src.utils.preprocess import preprocess_for_ocr
from src.utils.paddle_ocr import run_paddle_ocr
@@ -597,6 +597,17 @@ class PipelineRecognitionAgent(BaseAgent):
text_elements = state.get("extracted_entities", {}).get("text_elements", [])
symbols = state.get("extracted_entities", {}).get("symbols", [])
# Guarantee non-empty text_elements for line tracer even if running in parallel
if not text_elements:
try:
from src.utils.paddle_ocr import run_paddle_ocr
from src.utils.tag_classifier import classify_paddle_results
raw_ocr = run_paddle_ocr(raw_image)
text_elements = classify_paddle_results(raw_ocr, drawing_type)
logger.info(f"PipelineRecognitionAgent fallback OCR loaded {len(text_elements)} text elements.")
except Exception as e:
logger.warning(f"PipelineRecognitionAgent fallback OCR failed: {e}")
cv_res = trace_lines_and_connections(
image_path=raw_image,
text_elements=text_elements,
+14
View File
@@ -26,6 +26,7 @@ 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")
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]")
@@ -83,8 +84,21 @@ class Relationship(BaseModel):
source: str = Field(description="Source component tag identifier")
target: str = Field(description="Target component tag identifier")
type: str = Field(description="Type of connection (e.g., 'connects_to', 'measures', 'controls', 'mounted_on')")
confidence: float = Field(default=1.0, description="Extraction confidence level")
attributes: Optional[Dict[str, Any]] = Field(default=None, description="Additional metadata for the connection")
@property
def source_tag(self) -> str:
return self.source
@property
def target_tag(self) -> str:
return self.target
@property
def rel_type(self) -> str:
return self.type.upper()
# ──────────────────────────────────────────────────────────────────────────────
# Electrical Layout Models
+3 -3
View File
@@ -53,10 +53,10 @@ _TITLE_KEYWORDS: List[tuple[re.Pattern, DrawingType]] = [
# P&ID / PFD
(re.compile(r'\bP\s*&\s*I\s*D\b|\bPIPING\s+(AND\s+)?INSTRUMENTATION\b', re.IGNORECASE), DrawingType.PID),
(re.compile(r'\bPROCESS\s+FLOW\s+(DIAGRAM|CHART)\b|\bPFD\b', re.IGNORECASE), DrawingType.PFD),
# Electrical
(re.compile(r'\bEARTHING\b|\bGROUNDING\b|\bEARTH\s+LAYOUT\b', re.IGNORECASE), DrawingType.EARTHING_LAYOUT),
# Electrical & Earthing
(re.compile(r'\bEARTHING\b|\bGROUNDING\b|\bEARTH\s+LAYOUT\b|\bEARTH\s+GRID\b|\bBONDING\b', re.IGNORECASE), DrawingType.EARTHING_LAYOUT),
(re.compile(r'\bSINGLE\s+LINE\s+(DIAGRAM|SCHEMATIC)\b|\bSLD\b|\bONE\s+LINE\b', re.IGNORECASE), DrawingType.SLD),
(re.compile(r'\bLIGHTING\s+LAYOUT\b|\bELECTRICAL\s+LAYOUT\b|\bPOWER\s+LAYOUT\b|\bLUMINAIRE\b', re.IGNORECASE), DrawingType.ELECTRICAL_LAYOUT),
(re.compile(r'\bLIGHTING\b|\bELECTRICAL\s+LAYOUT\b|\bPOWER\s+LAYOUT\b|\bLUMINAIRE\b|\bLIGHTING\s+LAYOUT\b', re.IGNORECASE), DrawingType.ELECTRICAL_LAYOUT),
(re.compile(r'\bCABLE\s+(SCHEDULE|TRAY|ROUTING|LAYOUT)\b', re.IGNORECASE), DrawingType.CABLE_SCHEDULE),
# HVAC
(re.compile(r'\bHVAC\b|\bVENTILATION\s+LAYOUT\b|\bAIR\s+HANDLING\b|\bDUCT\s+LAYOUT\b', re.IGNORECASE), DrawingType.HVAC_LAYOUT),
+46 -25
View File
@@ -248,35 +248,56 @@ def trace_lines_and_connections(
"rel_type": "CONNECTS_TO"
})
# E. Map Electrical Panels to Circuits/Equipment (FEEDS)
if dt in ("ELECTRICAL_LAYOUT", "SLD", "CABLE_SCHEDULE"):
panel_tags = [p.get("tag") for p in panels if "DB" in p.get("tag", "").upper() or "PANEL" in p.get("tag", "").upper()]
circuit_tags = [c.get("tag") for c in panels if c.get("tag") not in panel_tags]
# E. Map Electrical Panels to Circuits/Luminaires (FEEDS) — un-gated for all drawings
panel_items = [p for p in text_elements if p.get("classification") == "PANEL_TAG"]
circuit_items = [c for c in text_elements if c.get("classification") in ("CIRCUIT_TAG", "LUMINAIRE_TAG")]
if panel_items and circuit_items:
for pitem in panel_items[:5]:
ptag = pitem.get("tag")
if not ptag:
continue
for citem in circuit_items[:20]:
ctag = citem.get("tag")
if ctag and ctag != ptag:
rkey = (ptag, ctag, "FEEDS")
if rkey not in existing_rels:
existing_rels.add(rkey)
relations.append({
"source_tag": ptag,
"target_tag": ctag,
"rel_type": "FEEDS"
})
if panel_tags and circuit_tags:
main_panel = panel_tags[0]
for ctag in circuit_tags[:20]:
rkey = (main_panel, ctag, "FEEDS")
# F. Map Earthing Components & Equipment (EARTHED_TO) — un-gated for all drawings
earthing_items = [e for e in text_elements if e.get("classification") in ("EARTH_BAR_TAG", "EARTH_PIT_TAG", "BOND_CONDUCTOR_TAG")]
eb_tags = [e.get("tag") for e in earthing_items if e.get("classification") == "EARTH_BAR_TAG"]
ep_tags = [e.get("tag") for e in earthing_items if e.get("classification") in ("EARTH_PIT_TAG", "BOND_CONDUCTOR_TAG")]
# Map Earth Pits / Conductors to Earth Bars
if eb_tags:
target_eb = eb_tags[0]
for e_tag in ep_tags:
rkey = (e_tag, target_eb, "EARTHED_TO")
if rkey not in existing_rels:
existing_rels.add(rkey)
relations.append({
"source_tag": e_tag,
"target_tag": target_eb,
"rel_type": "EARTHED_TO"
})
# Map Equipment to nearest Earth Bar (EARTHED_TO)
if eb_tags and equipment:
target_eb = eb_tags[0]
for eq_item in equipment[:15]:
eq_tag = eq_item.get("tag")
if eq_tag:
rkey = (eq_tag, target_eb, "EARTHED_TO")
if rkey not in existing_rels:
existing_rels.add(rkey)
relations.append({
"source_tag": main_panel,
"target_tag": ctag,
"rel_type": "FEEDS"
})
# F. Map Earthing Components (EARTHED_TO)
if dt == "EARTHING_LAYOUT":
eb_tags = [e.get("tag") for e in earthing if "EB" in e.get("tag", "").upper()]
ep_tags = [e.get("tag") for e in earthing if "EP" in e.get("tag", "").upper()]
if eb_tags and ep_tags:
for ep in ep_tags:
rkey = (ep, eb_tags[0], "EARTHED_TO")
if rkey not in existing_rels:
existing_rels.add(rkey)
relations.append({
"source_tag": ep,
"target_tag": eb_tags[0],
"source_tag": eq_tag,
"target_tag": target_eb,
"rel_type": "EARTHED_TO"
})
+22
View File
@@ -11,6 +11,7 @@ Zero API tokens consumed by any of these methods.
"""
import logging
import os
import re
from typing import List, Dict, Any, Optional
logger = logging.getLogger(__name__)
@@ -94,6 +95,27 @@ def run_pdf_text_extraction(pdf_path: str) -> List[Dict[str, Any]]:
"center_y": cy,
})
# 3. Spatial vertical assembly for instrument bubbles (code on top, loop number directly below)
from src.utils.tag_classifier import _INSTRUMENT_CODES
for t1 in word_list:
txt1 = t1["text"].upper()
if txt1 in _INSTRUMENT_CODES:
x1, y1 = t1["center_x"], t1["center_y"]
for t2 in word_list:
txt2 = t2["text"].upper()
if re.match(r'^\d{3,5}[A-Z]?$', txt2):
x2, y2 = t2["center_x"], t2["center_y"]
# Vertically aligned: same X (+/- 0.02), bottom Y is 0.005 to 0.04 below top Y
if abs(x1 - x2) < 0.02 and 0.005 < (y2 - y1) < 0.04:
joined_tag = f"{txt1}-{txt2}"
items.append({
"text": joined_tag,
"confidence": 0.99,
"bbox": t1["bbox"],
"center_x": x1,
"center_y": y1,
})
doc.close()
if items:
logger.info(f"PyMuPDF text layer extracted {len(items)} items & assembled lines from '{pdf_path}'.")
+217 -42
View File
@@ -89,11 +89,36 @@ _EQUIPMENT_CODES = {
'EC', 'GH', 'GJ', 'KD', 'KE', 'LA', 'LB',
}
# Generic 1-3 letter + number equipment (e.g., P-101, TK-101, E-201, V-301, C-101, M-101)
# Equipment prefix allowlist — only known equipment codes to eliminate false positives
# (line specs like FC11S, GC11S, drawing refs like AB-1234 are excluded)
_EQUIP_PREFIX_ALLOWLIST = {
# Compressors, blowers, turbines, motors
'K', 'KA', 'KB', 'KC', 'KT', 'CM', 'CP', 'MT', 'MG',
# Heat exchangers, coolers, heaters, furnaces
'E', 'EA', 'EB', 'HX', 'HE', 'BA',
# Vessels, drums, tanks, columns
'V', 'VA', 'VB', 'TK', 'T', 'D', 'DA', 'C', 'R', 'DR',
# Pumps
'P', 'PA', 'PB', 'PC', 'G', 'GA', 'PM', 'PU',
# Filters, separators, strainers
'F', 'FA', 'FB', 'ST', 'CX',
# Skids, packages
'SK', 'PK',
# General mechanical
'M', 'MA', 'MB', 'U', 'UA', 'W', 'WA',
}
# Generic 1-3 letter + number equipment — guarded with prefix allowlist
_GENERIC_EQUIP_PATTERN = re.compile(
r'\b([A-Z]{1,3}-\d{2,5}[A-Z]?(?:/[A-Z])?)\b', re.IGNORECASE
)
# Patterns that must NOT be classified as equipment (spec codes, sheet refs, etc.)
_EQUIP_REJECT_PATTERN = re.compile(
r'^(?:FC|GC|AC|AS|VC|SC|DC|WF|PV|VF|VA|HC|RC)[0-9]', # spec codes
re.IGNORECASE
)
# ──────────────────────────────────────────────────────────────────────────────
# P&ID Search Patterns
# ──────────────────────────────────────────────────────────────────────────────
@@ -110,16 +135,51 @@ _PROJECT_TAG_SEARCH = re.compile(
re.IGNORECASE
)
# Bare instrument tags without project prefix: PIT-9062, TIT-9057, PDIT-9054, PDI-9054, TE-101
# Bare instrument tags without project prefix: PIT-9062, TIT-9057, PDIT-9054, PDI-9054
# RULES:
# 1. Require mandatory hyphen separator (prevents GC11S, AS20S, FC11S spec code matches)
# 2. Require 3+ digit loop numbers (prevents PV-26, VA-26 service-code matches)
# 3. Only use unambiguous ISA codes (exclude 2-letter codes that match spec prefixes)
_ISA_CODES_JOINED = '|'.join(sorted(_INSTRUMENT_CODES, key=len, reverse=True))
# Unambiguous codes only — 3+ letter codes first, then safe 2-letter instrument codes
# Excludes: AC, AS, GC, FC, SC, VC, DC, WF, RC — these match spec code prefixes
_ISA_SAFE_CODES = [
c for c in sorted(_INSTRUMENT_CODES, key=len, reverse=True)
if len(c) >= 3 or c.upper() not in {
'AC', 'AS', 'GC', 'FC', 'SC', 'VC', 'DC', 'RC',
'WF', 'PV', 'TV', 'LV', 'AV', 'FV', 'ZV', # valve-action codes (classified as valves)
}
]
_ISA_SAFE_CODES_JOINED = '|'.join(_ISA_SAFE_CODES)
_BARE_INSTRUMENT_SEARCH = re.compile(
rf'\b((?:{_ISA_CODES_JOINED})-?\d{{2,5}}[A-Z]?)\b',
rf'\b((?:{_ISA_SAFE_CODES_JOINED})-\d{{3,5}}[A-Z]?)\b', # hyphen required, 3+ digits
re.IGNORECASE
)
# Valve tags: 26CB9131, 26-CB-9131, 26GB9178, 26-GB-9178, HV-101, XV-201, V-101, MOV-101
# Pipe spec code pattern — must NEVER be classified as instruments or equipment
# Matches: GC11S, AS20S, FC11S, AC21S, GC115, AC21 etc.
_SPEC_CODE_PATTERN = re.compile(
r'^(?:GC|AC|AS|FC|VC|SC|DC|WF|RC|CC|SG|CS|AG)[\dA-Z]{2,6}$',
re.IGNORECASE
)
# Also reject bare service codes (2-4 letters + 2-digit number): PV-26, VA-26
_SERVICE_CODE_PATTERN = re.compile(
r'^[A-Z]{1,4}-\d{2}$',
re.IGNORECASE
)
# Valve tags (ISA 5.1 comprehensive):
# Dense format: 26CB9131, 26GB9178 (no separator)
# Separated: 26-CB-9131A, 26-GB-9178
# Named control valves: HV-101, XV-201, FV-9076, PCV-9044, SDV-201
# Block valves: BV-101, NV-201, GV-101, BFV-201
_VALVE_SEARCH = re.compile(
r'\b(\d{2}-?[A-Z]{2}-?\d{4,6}|(?:HV|XV|CV|PCV|FCV|TCV|LCV|EV|MOV|SDV|BDV|FV|UV|PV|TV|LV|AV|ZV|V)-\d{2,5}[A-Z]?)\b',
r'\b('
r'\d{2}-?[A-Z]{2}-?\d{4,6}[A-Z]?' # 26CB9131, 26-CB-9131A
r'|(?:HV|XV|CV|PCV|FCV|TCV|LCV|EV|MOV|SDV|BDV|FV|UV|TV|LV|AV|ZV)[-–]\d{2,5}[A-Z]?' # HV-101, SDV-201
r'|(?:BV|NV|GV|BFV|SBV|NGV|PLV|RV|PRV)[-–]\d{2,5}[A-Z]?' # BV-101, NV-201
r'|\bV-\d{3,5}[A-Z]?' # V-101
r')\b',
re.IGNORECASE
)
@@ -139,9 +199,21 @@ _RATING_SEARCH = re.compile(
# Electrical Layout Patterns
# ──────────────────────────────────────────────────────────────────────────────
# Luminaire tags: L-01, LS-201, TL-101, FL-01
# Luminaire / Lighting Fitting tags: L-01, LS-201, TL-101, FL-01, FLOODLIGHT, WELLGLASS, HIGHBAY
_LUMINAIRE_SEARCH = re.compile(
r'\b((?:TL|FL|EL|SL|LS?|WL)-\d{1,4}[A-Z]?)\b', re.IGNORECASE
r'\b('
r'(?:TL|FL|EL|SL|LS|WL|LT|LP|LGT|FIX|LED|EML|WGL)[-–]?\d{1,4}[A-Z]?'
r'|L-\d{1,4}[A-Z]?'
r'|FLOODLIGHT(?:-?\d{1,4}[A-Z]?)?'
r'|WELLGLASS(?:-?\d{1,4}[A-Z]?)?'
r'|LUMINAIRE(?:-?\d{1,4}[A-Z]?)?'
r'|LIGHT\s+FIXTURE(?:-?\d{1,4}[A-Z]?)?'
r'|LIGHTING\s+FITTING(?:-?\d{1,4}[A-Z]?)?'
r'|HIGH\s*BAY(?:-?\d{1,4}[A-Z]?)?'
r'|LOW\s*BAY(?:-?\d{1,4}[A-Z]?)?'
r'|EMERGENCY\s+LIGHT(?:-?\d{1,4}[A-Z]?)?'
r')\b',
re.IGNORECASE
)
# Elevation / level labels: EL.101.445, EL 100.000, TL 101.445
@@ -150,29 +222,108 @@ _ELEVATION_SEARCH = re.compile(
re.IGNORECASE
)
# Panel / distribution board tags: DB-01, MDB-A, LDB-3, LPDB, EMDB, MVDB
# Panel / distribution board tags: DB-01, MDB-A, LDB-3, LPDB-01, EPDB, MVDB, LIGHTING PANEL, SWITCHBOARD
_PANEL_SEARCH = re.compile(
r'\b((?:EMDB|MVDB|LVDB|LPDB|EPDB|MDB|LDB|SDB|DB|PDB|NDB|MSB|LSB|ESB|SMDB)\s*[-–/]?\s*[A-Z0-9]{0,4})\b',
r'\b('
r'(?:EMDB|MVDB|LVDB|LPDB|EPDB|MDB|LDB|SDB|DB|PDB|NDB|MSB|LSB|ESB|SMDB|MLP|ELP|SLP|LP|MCC|PCC|PDP|PDPB)'
r'\s*[-–/]?\s*[A-Z0-9]{1,6}'
r'|LIGHTING\s+PANEL(?:\s*[-–/]?\s*[A-Z0-9]{1,4})?'
r'|DISTRIBUTION\s+BOARD(?:\s*[-–/]?\s*[A-Z0-9]{1,4})?'
r'|EARTHING\s+PANEL(?:\s*[-–/]?\s*[A-Z0-9]{1,4})?'
r'|SWITCHBOARD(?:\s*[-–/]?\s*[A-Z0-9]{1,4})?'
r'|SWITCHGEAR(?:\s*[-–/]?\s*[A-Z0-9]{1,4})?'
r')\b',
re.IGNORECASE
)
# Circuit / breaker tags: C-101, CB-01, MCB-1, MCCB-3, ACB-01
# Circuit / breaker tags: C-101, CB-01, MCB-1, MCCB-3, ACB-01, CK-01
_CIRCUIT_SEARCH = re.compile(
r'\b((?:MCB|RCCB|MCCB|ACB|VCB|CB|C)-\d{1,4}[A-Z]?)\b', re.IGNORECASE
r'\b((?:MCB|RCCB|MCCB|ACB|VCB|CB|CK|CIRCUIT|C)-\d{1,4}[A-Z]?)\b', re.IGNORECASE
)
# ──────────────────────────────────────────────────────────────────────────────
# Earthing Layout Patterns
# Earthing Layout Patterns (Comprehensive IEEE 80 / IS 3043 / IEC 62305)
# ──────────────────────────────────────────────────────────────────────────────
_EARTH_BAR_SEARCH = re.compile(r'\b(EBM?-\d{1,4}[A-Z]?|MEB|EBM?)\b', re.IGNORECASE)
_EARTH_PIT_SEARCH = re.compile(r'\b(EP-[A-Z0-9]{1,4}|EARTH\s+PIT)\b', re.IGNORECASE)
_BOND_CONDUCTOR_SEARCH = re.compile(r'\b([BE]C-\d{1,4}[A-Z]?)\b', re.IGNORECASE)
# Earth Bar / Busbar: EBM-01, EB-01, MEB-1, EEB-01, SEB-01, MAIN EARTH BAR, EARTH BUSBAR
_EARTH_BAR_SEARCH = re.compile(
r'\b('
r'(?:EBM|MEB|EEB|SEB|PEB|EGB|MGB|GBB|EB|EBB)[-–]?\d{1,4}[A-Z]?'
r'|MAIN\s+EARTH\s+BAR(?:\s*[-–]?\s*\d{1,4}[A-Z]?)?'
r'|EARTH\s+(?:BAR|BUSBAR|BUS|STRIP\s+BAR)(?:\s*[-–]?\s*[A-Z0-9]{1,4})?'
r'|GROUND\s+(?:BAR|BUSBAR|BUS)(?:\s*[-–]?\s*[A-Z0-9]{1,4})?'
r'|EARTHING\s+(?:BAR|BUSBAR|BUS)(?:\s*[-–]?\s*[A-Z0-9]{1,4})?'
r')\b',
re.IGNORECASE
)
# Earth Pit / Electrode: EP-01, EP-A, EE-01, EARTH PIT, EARTH CHAMBER, EARTH ELECTRODE, TEST PIT
_EARTH_PIT_SEARCH = re.compile(
r'\b('
r'(?:EP|EE|ER|GP|ELP)[-–]?\d{1,4}[A-Z]?'
r'|EARTH\s+(?:PIT|CHAMBER|ELECTRODE|WELL|ROD)(?:\s*[-–/]?\s*[A-Z0-9]{1,4})?'
r'|GROUND(?:ING)?\s+(?:PIT|CHAMBER|ELECTRODE|WELL)(?:\s*[-–/]?\s*[A-Z0-9]{1,4})?'
r'|EARTH\s+TEST\s+PIT'
r'|TEST\s+(?:PIT|LINK|CHAMBER)'
r'|DISCONNECTING\s+LINK'
r')\b',
re.IGNORECASE
)
# Bond Conductor / Earthing Strip: BC-01, EC-01, GC-01, COPPER TAPE, GS FLAT, GI FLAT, 25X3 MM, 50X6 MM, 70 SQMM
_BOND_CONDUCTOR_SEARCH = re.compile(
r'\b('
r'(?:BC|EC|EBC|GBC|GC-)[-–]?\d{1,4}[A-Z]?'
r'|COPPER\s+(?:TAPE|STRIP|CONDUCTOR|WIRE|CABLE)'
r'|CU\s+(?:TAPE|STRIP|CONDUCTOR)'
r'|(?:GS|GI|MS)\s+(?:FLAT|STRIP|TAPE)'
r'|EARTHING\s+(?:CONDUCTOR|STRIP|TAPE|GRID|MAT|LEAD)'
r'|GROUNDING\s+(?:CONDUCTOR|STRIP|TAPE|GRID|MAT|LEAD)'
r'|\d{2,3}\s*[xX]\s*\d{1,2}\s*(?:MM|MM2|SQMM)'
r'|\d{2,3}\s*(?:SQMM|SQ\.MM|MM2)'
r')\b',
re.IGNORECASE
)
# ──────────────────────────────────────────────────────────────────────────────
# Text normalization & bulk classifier
# ──────────────────────────────────────────────────────────────────────────────
# ──────────────────────────────────────────────────────────────────────────────
# OCR character correction table (Fix 1: pre-correct before regex matching)
# ──────────────────────────────────────────────────────────────────────────────
_OCR_CORRECTIONS = [
# In letter-only runs: 0 → O, 1 → I
(re.compile(r'(?<=[A-Z])0(?=[A-Z])'), 'O'),
(re.compile(r'(?<=[A-Z])1(?=[A-Z])'), 'I'),
# In digit-only runs: O → 0, l → 1, S → 5 (only when surrounded by digits)
(re.compile(r'(?<=\d)[Ol](?=\d)'), '0'),
# Pipe size inch mark: 8" → 8", protect known fractions
(re.compile(r'(\d)\"'), r'\1"'),
# Spec codes: protect known patterns from over-correction
(re.compile(r'\bFCllS\b'), 'FC11S'),
(re.compile(r'\bFCIIS\b'), 'FC11S'),
(re.compile(r'\bGCllS\b'), 'GC11S'),
(re.compile(r'\bACZlS\b'), 'AC21S'),
(re.compile(r'\bAS2OS\b'), 'AS20S'),
# Instrument code corrections: PlT → PIT, TlT → TIT, FlT → FIT
(re.compile(r'\bPlT\b'), 'PIT'),
(re.compile(r'\bTlT\b'), 'TIT'),
(re.compile(r'\bFlT\b'), 'FIT'),
(re.compile(r'\bLlT\b'), 'LIT'),
(re.compile(r'\bAlT\b'), 'AIT'),
(re.compile(r'\bPDl\b'), 'PDI'),
(re.compile(r'\bPDlT\b'), 'PDIT'),
]
def _ocr_correct(text: str) -> str:
"""Apply context-aware OCR character corrections before regex classification."""
for pattern, replacement in _OCR_CORRECTIONS:
text = pattern.sub(replacement, text)
return text
def _normalize(text: str) -> str:
if not text:
return ""
@@ -199,6 +350,7 @@ def classify_paddle_results(
continue
t = _normalize(text)
t = _ocr_correct(t) # Fix 1: pre-correct OCR character misreads
if not t or len(t) < 2:
continue
@@ -226,9 +378,17 @@ def classify_paddle_results(
seq = m.group(3)
if len(seq) == 6:
continue # Drawing reference number, skip
# Reject spec codes like GC11S, AS20S embedded in full tag
if _SPEC_CODE_PATTERN.match(full_tag) or _SERVICE_CODE_PATTERN.match(full_tag):
continue
if full_tag in found and found[full_tag]['classification'] != 'NOTE':
continue
if code in _INSTRUMENT_CODES:
# 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'
elif code in _INSTRUMENT_CODES:
cat = 'INSTRUMENT_TAG'
elif code in _EQUIPMENT_CODES:
cat = 'EQUIPMENT_TAG'
@@ -255,38 +415,53 @@ def classify_paddle_results(
found[tag] = _make_item(tag, 'VALVE_TAG', conf, item)
item_added = True
# Generic equipment
# Electrical / Earthing / SLD / Lighting patterns (un-gated for 100% sensitivity across all drawing types)
for m in _EARTH_BAR_SEARCH.finditer(t):
tag = m.group(1).upper()
if tag not in found:
found[tag] = _make_item(tag, 'EARTH_BAR_TAG', conf, item)
item_added = True
for m in _EARTH_PIT_SEARCH.finditer(t):
tag = m.group(1).upper()
if tag not in found:
found[tag] = _make_item(tag, 'EARTH_PIT_TAG', conf, item)
item_added = True
for m in _BOND_CONDUCTOR_SEARCH.finditer(t):
tag = m.group(1).upper()
if tag not in found:
found[tag] = _make_item(tag, 'BOND_CONDUCTOR_TAG', conf, item)
item_added = True
for m in _PANEL_SEARCH.finditer(t):
tag = m.group(1).upper()
if tag not in found:
found[tag] = _make_item(tag, 'PANEL_TAG', conf, item)
item_added = True
for m in _CIRCUIT_SEARCH.finditer(t):
tag = m.group(1).upper()
if tag not in found:
found[tag] = _make_item(tag, 'CIRCUIT_TAG', conf, item)
item_added = True
for m in _LUMINAIRE_SEARCH.finditer(t):
tag = m.group(1).upper()
if tag not in found:
found[tag] = _make_item(tag, 'LUMINAIRE_TAG', conf, item)
item_added = True
# Generic equipment — guarded with prefix allowlist (Fix 4)
for m in _GENERIC_EQUIP_PATTERN.finditer(t):
tag = m.group(1).upper()
if tag not in found:
prefix = tag.split('-')[0]
if len(prefix) <= 3 and prefix.isalpha():
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):
found[tag] = _make_item(tag, 'EQUIPMENT_TAG', conf, item)
item_added = True
# Electrical / Earthing / SLD specific patterns
if dt in ('ELECTRICAL_LAYOUT', 'EARTHING_LAYOUT', 'SLD', 'CABLE_SCHEDULE'):
for m in _PANEL_SEARCH.finditer(t):
tag = m.group(1).upper()
if tag not in found:
found[tag] = _make_item(tag, 'PANEL_TAG', conf, item)
item_added = True
for m in _CIRCUIT_SEARCH.finditer(t):
tag = m.group(1).upper()
if tag not in found:
found[tag] = _make_item(tag, 'CIRCUIT_TAG', conf, item)
item_added = True
for m in _LUMINAIRE_SEARCH.finditer(t):
tag = m.group(1).upper()
if tag not in found:
found[tag] = _make_item(tag, 'LUMINAIRE_TAG', conf, item)
item_added = True
for m in _EARTH_BAR_SEARCH.finditer(t):
tag = m.group(1).upper()
if tag not in found:
found[tag] = _make_item(tag, 'EARTH_BAR_TAG', conf, item)
item_added = True
# Elevation tags
for m in _ELEVATION_SEARCH.finditer(t):
tag = m.group(1).upper()