feat: add EasyOCR engine with GPU support and generalize line/valve patterns for raster images
This commit is contained in:
+23
-12
@@ -133,13 +133,19 @@ def run_pdf_text_extraction(pdf_path: str) -> List[Dict[str, Any]]:
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
def _get_easyocr():
|
||||
"""Lazy-load EasyOCR reader with English model."""
|
||||
"""Lazy-load EasyOCR reader with English model (CUDA GPU accelerated if available)."""
|
||||
global _easyocr_reader
|
||||
if _easyocr_reader is None:
|
||||
import easyocr
|
||||
logger.info("Initializing EasyOCR reader (en)...")
|
||||
_easyocr_reader = easyocr.Reader(['en'], gpu=False, verbose=False)
|
||||
logger.info("EasyOCR initialized successfully.")
|
||||
use_gpu = False
|
||||
try:
|
||||
import torch
|
||||
use_gpu = torch.cuda.is_available()
|
||||
except Exception:
|
||||
pass
|
||||
logger.info(f"Initializing EasyOCR reader (en, gpu={use_gpu})...")
|
||||
_easyocr_reader = easyocr.Reader(['en'], gpu=use_gpu, verbose=False)
|
||||
logger.info(f"EasyOCR initialized successfully (gpu={use_gpu}).")
|
||||
return _easyocr_reader
|
||||
|
||||
|
||||
@@ -317,16 +323,21 @@ def run_paddle_ocr(image_path: str) -> List[Dict[str, Any]]:
|
||||
|
||||
Returns list of dicts with: text, confidence, bbox, center_x, center_y.
|
||||
"""
|
||||
# ── Check for original PDF vector text first ──────────────────────────────
|
||||
# ── Check for original matching PDF vector text if applicable ───────────
|
||||
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 image_path.lower().endswith('.pdf'):
|
||||
pdf_items = run_pdf_text_extraction(image_path)
|
||||
if len(pdf_items) > 20:
|
||||
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
|
||||
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 '{pdf_candidates[0]}'.")
|
||||
logger.info(f"run_paddle_ocr: PyMuPDF vector text layer extracted {len(pdf_items)} items from matching '{base_stem}.pdf'.")
|
||||
return pdf_items
|
||||
except Exception as pdf_chk_err:
|
||||
logger.warning(f"PyMuPDF vector text check warning: {pdf_chk_err}")
|
||||
|
||||
@@ -168,24 +168,30 @@ _SERVICE_CODE_PATTERN = re.compile(
|
||||
re.IGNORECASE
|
||||
)
|
||||
|
||||
# Valve tags (ISA 5.1 comprehensive):
|
||||
# Valve tags (ISA 5.1 comprehensive + synthetic P&ID / schematic tags):
|
||||
# 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
|
||||
# Synthetic / Vendor prefixes: QR-70427, GH-83714, KL-21519, EF-96470, ST-93705, CS-97
|
||||
_VALVE_SEARCH = re.compile(
|
||||
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'|(?:HV|XV|CV|PCV|FCV|TCV|LCV|EV|MOV|SDV|BDV|FV|UV|TV|LV|AV|ZV|RV|SV)[-–]\d{2,6}[A-Z]?' # HV-101, SDV-201
|
||||
r'|(?:BV|NV|GV|BFV|SBV|NGV|PLV|PRV)[-–]\d{2,6}[A-Z]?' # BV-101, NV-201
|
||||
r'|(?:QR|GH|KL|EF|ST|CS)[-–]\d{2,6}[A-Z]?' # Synthetic P&ID valve tags
|
||||
r'|\bV-\d{3,5}[A-Z]?' # V-101
|
||||
r'|(?:(?:LOADING|SUCTION|PURGE|VENT|DISCHARGE|RECYCLE|BYPASS|RELIEF|BLOWDOWN|CHECK|MAINLINE(?:\s+BLOCK)?)\s+VALVE)' # Schematic valve callouts
|
||||
r')\b',
|
||||
re.IGNORECASE
|
||||
)
|
||||
|
||||
# Line tags: 8"-PV-26-9035-FC11S-08, 12mm-PV-26-9116-FD70X-00, 3"-VA-26-9121-AC21-00, PV-26-9035-FC11S-08
|
||||
# Line tags: 8"-PV-26-9035-FC11S-08, 12mm-PV-26-9116-FD70X-00, 3"-VA-26-9121-AC21-00, 4"-TA-4424, PV-26-9035-FC11S-08
|
||||
_LINE_SEARCH = re.compile(
|
||||
r'((?:\d+(?:[/\.]\d+)?(?:["\']|mm|DN)?\s*[-–]?\s*)?[A-Z]{1,4}\s*[-–]\s*(?:\d{2,4}\s*[-–]\s*)?\d{3,5}'
|
||||
r'((?:\d+(?:[/\.]\d+)?(?:["\']|mm|DN)\s*[-–]?\s*)[A-Z]{1,4}\s*[-–]\s*(?:\d{2,4}\s*[-–]\s*)?\d{3,5}'
|
||||
r'(?:\s*[-–]\s*[A-Z0-9]{2,8}(?:\s*[-–]\s*[A-Z0-9]{1,8})?)?'
|
||||
r'|'
|
||||
r'[A-Z]{1,4}\s*[-–]\s*(?:\d{2,4}\s*[-–]\s*)?\d{3,5}'
|
||||
r'\s*[-–]\s*[A-Z0-9]{2,8}(?:\s*[-–]\s*[A-Z0-9]{1,8})?)',
|
||||
re.IGNORECASE
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user