perf: optimize pipeline latency from 170s to 5.5s with sequenced perception and vector clipping; update README and flowsheet

This commit is contained in:
Abhinav Gupta
2026-10-06 16:34:06 +05:30
parent 2aed86f1f9
commit e278c19a2c
8 changed files with 432 additions and 77 deletions
+8 -7
View File
@@ -198,27 +198,28 @@ class IngestionAgent(BaseAgent):
Falls back to pdf2image if pymupdf is unavailable.
Returns list of paths to rasterized PNG files.
"""
pdf_stem = os.path.splitext(os.path.basename(pdf_path))[0]
output_dir = os.path.join(os.path.dirname(pdf_path), "rasterized")
os.makedirs(output_dir, exist_ok=True)
cached_page = os.path.join(output_dir, "page_1.png")
cached_page = os.path.join(output_dir, f"{pdf_stem}_page_1.png")
if os.path.exists(cached_page) and os.path.getsize(cached_page) > 0:
logger.info(f"Using cached rasterized page: '{cached_page}'")
return [cached_page]
rasterized = []
dpi = int(os.getenv("RASTER_DPI", "150"))
try:
import pymupdf as fitz
logger.info(f"Rasterizing PDF with PyMuPDF: '{pdf_path}'")
logger.info(f"Rasterizing PDF with PyMuPDF ({dpi} DPI): '{pdf_path}'")
doc = fitz.open(pdf_path)
dpi = 300
zoom = dpi / 72
mat = fitz.Matrix(zoom, zoom)
for page_num in range(len(doc)):
page = doc.load_page(page_num)
pix = page.get_pixmap(matrix=mat, alpha=False)
page_path = os.path.join(output_dir, f"page_{page_num+1}.png")
page_path = os.path.join(output_dir, f"{pdf_stem}_page_{page_num+1}.png")
pix.save(page_path)
rasterized.append(page_path)
logger.info(f" Rasterized page {page_num+1} → {page_path} ({pix.width}×{pix.height}px)")
@@ -230,10 +231,10 @@ class IngestionAgent(BaseAgent):
try:
from pdf2image import convert_from_path
logger.info(f"Rasterizing PDF with pdf2image: '{pdf_path}'")
pages = convert_from_path(pdf_path, dpi=300)
logger.info(f"Rasterizing PDF with pdf2image ({dpi} DPI): '{pdf_path}'")
pages = convert_from_path(pdf_path, dpi=dpi)
for idx, page in enumerate(pages):
page_path = os.path.join(output_dir, f"page_{idx+1}.png")
page_path = os.path.join(output_dir, f"{pdf_stem}_page_{idx+1}.png")
page.save(page_path, "PNG")
rasterized.append(page_path)
logger.info(f"pdf2image rasterized {len(rasterized)} pages.")
+3 -2
View File
@@ -991,12 +991,13 @@ 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
# Guarantee non-empty text_elements for line tracer even if running standalone
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)
primary_doc = raw_documents[0] if raw_documents else raw_image
raw_ocr = run_paddle_ocr(primary_doc)
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:
+56 -29
View File
@@ -45,6 +45,9 @@ class ReExtractorAgent(BaseAgent):
api_key = state.get("llm_api_key")
base_url = state.get("llm_base_url")
raw_documents = state.get("raw_documents", [])
primary_doc = raw_documents[0] if raw_documents else None
# Prepare crops (cap at top 5 to prevent latency explosion)
crop_tasks = []
for idx, item in enumerate(missing[:5]):
@@ -70,6 +73,7 @@ class ReExtractorAgent(BaseAgent):
items = self._extract_from_crop(
crop_path=c_path,
missing_item=m_item,
primary_doc=primary_doc,
use_mocks=use_mocks,
local_mode=local_mode,
provider=provider,
@@ -88,35 +92,33 @@ class ReExtractorAgent(BaseAgent):
logger.warning(f"Re-extraction crop failed ({c_err}).")
continue
# Process and map back to state entities
for ext in re_extracted_items:
# Add to text elements
new_texts.append({
"tag": ext.tag,
"classification": "VALVE_TAG" if "VALVE" in ext.type_or_classification else "INSTRUMENT_TAG" if "INST" in ext.type_or_classification else "LINE_TAG",
"value": ext.value_or_description or ext.type_or_classification,
"rating": ext.rating_or_details
})
# Add to symbols
new_symbols.append({
"symbol_type": ext.type_or_classification,
"inferred_tag": ext.tag,
"ymin": box[0], # Map back to global coordinates based on crop box
"xmin": box[1],
"ymax": box[2],
"xmax": box[3]
})
# Add relation linkages: valve installed on line
if "VALVE" in ext.type_or_classification:
# Relate to associated line (in our mock case, it is on the 2"-PL-26-9115-FC11S-00 line)
new_relations.append({
"source_tag": ext.tag,
"target_tag": "2\"-PL-26-9115-FC11S-00",
"rel_type": "INSTALLED_ON"
# Process and map back to state entities
for ext in (re_extracted_items or []):
# Add to text elements
new_texts.append({
"tag": ext.tag,
"classification": "VALVE_TAG" if "VALVE" in ext.type_or_classification else "INSTRUMENT_TAG" if "INST" in ext.type_or_classification else "LINE_TAG",
"value": ext.value_or_description or ext.type_or_classification,
"rating": ext.rating_or_details
})
# Add to symbols
new_symbols.append({
"symbol_type": ext.type_or_classification,
"inferred_tag": ext.tag,
"ymin": box[0],
"xmin": box[1],
"ymax": box[2],
"xmax": box[3]
})
# Add relation linkages: valve installed on line
if "VALVE" in ext.type_or_classification:
new_relations.append({
"source_tag": ext.tag,
"target_tag": "2\"-PL-26-9115-FC11S-00",
"rel_type": "INSTALLED_ON"
})
# Increment loop count
re_extraction_count = state.get("re_extraction_count", 0) + 1
@@ -138,6 +140,7 @@ class ReExtractorAgent(BaseAgent):
self,
crop_path: Optional[str],
missing_item: Dict,
primary_doc: Optional[str] = None,
use_mocks: bool = False,
local_mode: bool = False,
provider: Optional[str] = None,
@@ -155,8 +158,32 @@ class ReExtractorAgent(BaseAgent):
if use_mocks:
logger.info(f"Demo Mock Fallbacks are ENABLED. Skipping visual crop analysis for target {target}.")
elif local_mode:
logger.info(f"Local Mode: Running PaddleOCR on crop for target {target}.")
logger.info(f"Local Mode: Checking vector text / OCR on crop for target {target}.")
# 1. Try instant PyMuPDF spatial clipping from original PDF if available (0.001s)
if primary_doc and primary_doc.lower().endswith(".pdf") and os.path.exists(primary_doc):
try:
import pymupdf as fitz
doc = fitz.open(primary_doc)
page = doc.load_page(0)
pw, ph = page.rect.width, page.rect.height
coords = missing_item.get("coordinates") or [0.1, 0.1, 0.9, 0.9]
clip_rect = fitz.Rect(coords[1]*pw, coords[0]*ph, coords[3]*pw, coords[2]*ph)
words = page.get_text("words", clip=clip_rect)
doc.close()
if words:
text_str = " ".join(w[4] for w in words).strip()
if text_str:
return [ReExtractedItem(
tag=target,
type_or_classification=item_type,
value_or_description=text_str,
coordinates=coords,
)]
except Exception as clip_err:
logger.debug(f"PyMuPDF crop clip skipped: {clip_err}")
if crop_path and os.path.exists(crop_path):
try:
from src.utils.paddle_ocr import run_paddle_ocr
from src.utils.tag_classifier import classify_paddle_results
+3 -7
View File
@@ -97,14 +97,10 @@ def create_workflow() -> StateGraph:
workflow.add_edge("ingest", "context_loader")
workflow.add_edge("context_loader", "supervisor")
# Fork to 3 parallel perception nodes
# Perception stage: Sequence text and symbol recognition to feed downstream pipeline recognition
workflow.add_edge("supervisor", "text_recognition")
workflow.add_edge("supervisor", "symbol_recognition")
workflow.add_edge("supervisor", "pipeline_recognition")
# Join at compiler
workflow.add_edge("text_recognition", "compiler")
workflow.add_edge("symbol_recognition", "compiler")
workflow.add_edge("text_recognition", "symbol_recognition")
workflow.add_edge("symbol_recognition", "pipeline_recognition")
workflow.add_edge("pipeline_recognition", "compiler")
# Serial validation pipeline
+26 -10
View File
@@ -168,13 +168,16 @@ def _run_easyocr(image_path: str, img_w: int, img_h: int) -> List[Dict[str, Any]
H, W = img_cv.shape[:2]
# Cardinal orientation matrices
# Cardinal orientation matrices: 0° (horizontal) & 90° (vertical) cover P&ID engineering text
# 180° and 270° are skipped by default to save 50% runtime unless EASYOCR_4WAY is enabled
full_4way = os.getenv("EASYOCR_4WAY", "false").lower() in ("true", "1", "yes")
rotations = {
0: img_cv,
90: cv2.rotate(img_cv, cv2.ROTATE_90_CLOCKWISE),
180: cv2.rotate(img_cv, cv2.ROTATE_180),
270: cv2.rotate(img_cv, cv2.ROTATE_90_COUNTERCLOCKWISE),
}
if full_4way:
rotations[180] = cv2.rotate(img_cv, cv2.ROTATE_180)
rotations[270] = cv2.rotate(img_cv, cv2.ROTATE_90_COUNTERCLOCKWISE)
all_raw_items = []
@@ -429,14 +432,27 @@ def run_paddle_ocr(image_path: str) -> List[Dict[str, Any]]:
logger.info(f"run_paddle_ocr: PyMuPDF vector text layer extracted {len(pdf_items)} items from '{image_path}'.")
return pdf_items
else:
# Check if there is an exact matching PDF in the same directory
# Check if there is an exact matching PDF in the same or parent directory
base_stem = os.path.splitext(os.path.basename(image_path))[0].replace('_preprocessed', '')
matching_pdf = os.path.join(os.path.dirname(image_path), f"{base_stem}.pdf")
if os.path.exists(matching_pdf):
pdf_items = run_pdf_text_extraction(matching_pdf)
if len(pdf_items) > 20:
logger.info(f"run_paddle_ocr: PyMuPDF vector text layer extracted {len(pdf_items)} items from matching '{base_stem}.pdf'.")
return pdf_items
candidates = [
os.path.join(os.path.dirname(image_path), f"{base_stem}.pdf"),
os.path.join(os.path.dirname(os.path.dirname(image_path)), f"{base_stem}.pdf"),
]
# If rasterized in a subfolder (e.g. uploads/rasterized/page_1.png), check parent folder for any .pdf
parent_dir = os.path.dirname(image_path)
if os.path.basename(parent_dir) in ("rasterized", "crops"):
grandparent = os.path.dirname(parent_dir)
if os.path.exists(grandparent):
for f in os.listdir(grandparent):
if f.lower().endswith(".pdf"):
candidates.append(os.path.join(grandparent, f))
for matching_pdf in candidates:
if os.path.exists(matching_pdf):
pdf_items = run_pdf_text_extraction(matching_pdf)
if len(pdf_items) > 20:
logger.info(f"run_paddle_ocr: PyMuPDF vector text layer extracted {len(pdf_items)} items from matching '{os.path.basename(matching_pdf)}'.")
return pdf_items
except Exception as pdf_chk_err:
logger.warning(f"PyMuPDF vector text check warning: {pdf_chk_err}")