fix(pdf): make pdfplumber/pymupdf imports resilient with graceful fallback and add auto-venv discovery in app.py
This commit is contained in:
@@ -4,9 +4,24 @@ import sys
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
# Ensure src/ is on Python search path
|
# Ensure src/ is on Python search path
|
||||||
src_dir = Path(__file__).parent / "src"
|
root_dir = Path(__file__).resolve().parent
|
||||||
|
src_dir = root_dir / "src"
|
||||||
if str(src_dir) not in sys.path:
|
if str(src_dir) not in sys.path:
|
||||||
sys.path.insert(0, str(src_dir))
|
sys.path.insert(0, str(src_dir))
|
||||||
|
|
||||||
|
# Automatically detect and include local virtual environment site-packages
|
||||||
|
for venv_name in ("env", ".venv", "venv"):
|
||||||
|
# Windows
|
||||||
|
win_sp = root_dir / venv_name / "Lib" / "site-packages"
|
||||||
|
if win_sp.exists() and str(win_sp) not in sys.path:
|
||||||
|
sys.path.insert(0, str(win_sp))
|
||||||
|
# Linux / macOS
|
||||||
|
linux_lib = root_dir / venv_name / "lib"
|
||||||
|
if linux_lib.exists():
|
||||||
|
for py_dir in linux_lib.glob("python*"):
|
||||||
|
sp = py_dir / "site-packages"
|
||||||
|
if sp.exists() and str(sp) not in sys.path:
|
||||||
|
sys.path.insert(0, str(sp))
|
||||||
|
|
||||||
# Import and execute main Streamlit UI
|
# Import and execute main Streamlit UI
|
||||||
from medical_coding.ui.app import * # noqa: E402, F401, F403
|
from medical_coding.ui.app import * # noqa: E402, F401, F403
|
||||||
|
|||||||
@@ -5,8 +5,18 @@ import io
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import pdfplumber
|
try:
|
||||||
import pymupdf # Modern PyMuPDF import
|
import pdfplumber
|
||||||
|
except ImportError:
|
||||||
|
pdfplumber = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
import pymupdf # Modern PyMuPDF import
|
||||||
|
except ImportError:
|
||||||
|
try:
|
||||||
|
import fitz as pymupdf
|
||||||
|
except ImportError:
|
||||||
|
pymupdf = None
|
||||||
|
|
||||||
from medical_coding.pdf.models import ExtractedPage, PDFExtractionStatus
|
from medical_coding.pdf.models import ExtractedPage, PDFExtractionStatus
|
||||||
from medical_coding.pdf.normalizer import DocumentNormalizer
|
from medical_coding.pdf.normalizer import DocumentNormalizer
|
||||||
@@ -54,41 +64,64 @@ class PDFExtractor:
|
|||||||
|
|
||||||
def extract_sync(self, source: Path | bytes | str) -> ExtractorResult:
|
def extract_sync(self, source: Path | bytes | str) -> ExtractorResult:
|
||||||
"""Extract pages synchronously using PyMuPDF, falling back to pdfplumber if necessary."""
|
"""Extract pages synchronously using PyMuPDF, falling back to pdfplumber if necessary."""
|
||||||
# 1. Attempt primary extraction using PyMuPDF
|
# 1. Attempt primary extraction using PyMuPDF if available
|
||||||
try:
|
if pymupdf is not None:
|
||||||
result = self._extract_with_pymupdf(source)
|
|
||||||
# If PyMuPDF returned text, return its result directly
|
|
||||||
if result.status == PDFExtractionStatus.SUCCESS:
|
|
||||||
return result
|
|
||||||
# If PyMuPDF flagged scanned/needs OCR or empty, test pdfplumber before deciding
|
|
||||||
if result.status in (
|
|
||||||
PDFExtractionStatus.NEEDS_OCR,
|
|
||||||
PDFExtractionStatus.INSUFFICIENT_TEXT,
|
|
||||||
):
|
|
||||||
logger.info("PyMuPDF yielded low text count. Attempting pdfplumber fallback...")
|
|
||||||
fallback_result = self._extract_with_pdfplumber(source)
|
|
||||||
if fallback_result.status == PDFExtractionStatus.SUCCESS:
|
|
||||||
logger.info("pdfplumber fallback succeeded with valid text.")
|
|
||||||
return fallback_result
|
|
||||||
return result
|
|
||||||
|
|
||||||
except Exception as exc:
|
|
||||||
logger.warning(
|
|
||||||
"PyMuPDF raised exception on '%s': %s. Attempting pdfplumber fallback...",
|
|
||||||
source,
|
|
||||||
exc,
|
|
||||||
)
|
|
||||||
try:
|
try:
|
||||||
return self._extract_with_pdfplumber(source)
|
result = self._extract_with_pymupdf(source)
|
||||||
except Exception as fb_exc:
|
# If PyMuPDF returned text, return its result directly
|
||||||
logger.error("Both PyMuPDF and pdfplumber failed on '%s': %s", source, fb_exc)
|
if result.status == PDFExtractionStatus.SUCCESS:
|
||||||
|
return result
|
||||||
|
# If PyMuPDF flagged scanned/needs OCR or empty, test pdfplumber before deciding
|
||||||
|
if result.status in (
|
||||||
|
PDFExtractionStatus.NEEDS_OCR,
|
||||||
|
PDFExtractionStatus.INSUFFICIENT_TEXT,
|
||||||
|
):
|
||||||
|
if pdfplumber is not None:
|
||||||
|
logger.info("PyMuPDF yielded low text count. Attempting pdfplumber fallback...")
|
||||||
|
fallback_result = self._extract_with_pdfplumber(source)
|
||||||
|
if fallback_result.status == PDFExtractionStatus.SUCCESS:
|
||||||
|
logger.info("pdfplumber fallback succeeded with valid text.")
|
||||||
|
return fallback_result
|
||||||
|
return result
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning(
|
||||||
|
"PyMuPDF raised exception on '%s': %s. Attempting pdfplumber fallback...",
|
||||||
|
source,
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
if pdfplumber is not None:
|
||||||
|
try:
|
||||||
|
return self._extract_with_pdfplumber(source)
|
||||||
|
except Exception as fb_exc:
|
||||||
|
logger.error("Both PyMuPDF and pdfplumber failed on '%s': %s", source, fb_exc)
|
||||||
|
return ExtractorResult(
|
||||||
|
status=PDFExtractionStatus.MALFORMED_PDF,
|
||||||
|
pages=[],
|
||||||
|
full_raw_text="",
|
||||||
|
full_normalized_text="",
|
||||||
|
error_message=f"Failed to parse PDF document: {exc}; Fallback error: {fb_exc}",
|
||||||
|
extractor_used="fallback",
|
||||||
|
)
|
||||||
return ExtractorResult(
|
return ExtractorResult(
|
||||||
status=PDFExtractionStatus.MALFORMED_PDF,
|
status=PDFExtractionStatus.MALFORMED_PDF,
|
||||||
pages=[],
|
pages=[],
|
||||||
full_raw_text="",
|
full_raw_text="",
|
||||||
full_normalized_text="",
|
full_normalized_text="",
|
||||||
error_message=f"Failed to parse PDF document: {exc}; Fallback error: {fb_exc}",
|
error_message=f"Failed to parse PDF document: {exc}",
|
||||||
|
extractor_used="pymupdf",
|
||||||
)
|
)
|
||||||
|
elif pdfplumber is not None:
|
||||||
|
return self._extract_with_pdfplumber(source)
|
||||||
|
else:
|
||||||
|
return ExtractorResult(
|
||||||
|
status=PDFExtractionStatus.EXTRACTION_ERROR,
|
||||||
|
pages=[],
|
||||||
|
full_raw_text="",
|
||||||
|
full_normalized_text="",
|
||||||
|
error_message="Neither PyMuPDF nor pdfplumber is available in current environment.",
|
||||||
|
extractor_used="none",
|
||||||
|
)
|
||||||
|
|
||||||
def _extract_with_pymupdf(self, source: Path | bytes | str) -> ExtractorResult:
|
def _extract_with_pymupdf(self, source: Path | bytes | str) -> ExtractorResult:
|
||||||
"""Execute extraction using PyMuPDF (fitz)."""
|
"""Execute extraction using PyMuPDF (fitz)."""
|
||||||
@@ -245,6 +278,17 @@ class PDFExtractor:
|
|||||||
|
|
||||||
def _extract_with_pdfplumber(self, source: Path | bytes | str) -> ExtractorResult:
|
def _extract_with_pdfplumber(self, source: Path | bytes | str) -> ExtractorResult:
|
||||||
"""Fallback extraction using pdfplumber."""
|
"""Fallback extraction using pdfplumber."""
|
||||||
|
if pdfplumber is None:
|
||||||
|
logger.info("pdfplumber library is not installed; skipping fallback extraction.")
|
||||||
|
return ExtractorResult(
|
||||||
|
status=PDFExtractionStatus.EXTRACTION_ERROR,
|
||||||
|
pages=[],
|
||||||
|
full_raw_text="",
|
||||||
|
full_normalized_text="",
|
||||||
|
error_message="pdfplumber library is not installed.",
|
||||||
|
extractor_used="pdfplumber",
|
||||||
|
)
|
||||||
|
|
||||||
file_obj: Any = None
|
file_obj: Any = None
|
||||||
pdf: Any = None
|
pdf: Any = None
|
||||||
try:
|
try:
|
||||||
|
|||||||
Reference in New Issue
Block a user