File size: 7,529 Bytes
b12284c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | """OCR extraction for scanned / image-based PDF pages.
Uses pytesseract with OpenCV preprocessing. Falls back gracefully
if Tesseract is not installed.
"""
from __future__ import annotations
import logging
import re
from pathlib import Path
import fitz # PyMuPDF β to rasterize pages
from PIL import Image
from app.schemas.extraction import (
BlockType,
ContentBlock,
HeadingLevel,
ListItem,
PageResult,
TableBlock,
TableCell,
)
from app.services.preprocessing import (
is_mostly_blank,
preprocess_for_ocr,
)
logger = logging.getLogger(__name__)
# ββ Tesseract availability ββ
_TESSERACT_AVAILABLE = False
try:
import pytesseract
# Quick sanity check
pytesseract.get_tesseract_version()
_TESSERACT_AVAILABLE = True
except Exception:
logger.warning("pytesseract / Tesseract not available; OCR will be disabled")
def tesseract_available() -> bool:
return _TESSERACT_AVAILABLE
def configure_tesseract(cmd: str) -> None:
"""Override the tesseract binary path at runtime."""
global _TESSERACT_AVAILABLE
if cmd:
import pytesseract as _pt
_pt.pytesseract.tesseract_cmd = cmd
try:
_pt.get_tesseract_version()
_TESSERACT_AVAILABLE = True
except Exception:
_TESSERACT_AVAILABLE = False
# ββ Rasterize a PDF page to PIL Image ββ
def rasterize_page(pdf_path: str | Path, page_num: int, dpi: int = 300) -> Image.Image:
"""Render a PDF page to a PIL Image at the given DPI."""
with fitz.open(str(pdf_path)) as doc:
page = doc[page_num]
zoom = dpi / 72.0
mat = fitz.Matrix(zoom, zoom)
pix = page.get_pixmap(matrix=mat, alpha=False)
return Image.frombytes("RGB", (pix.width, pix.height), pix.samples)
# ββ OCR a single page ββ
_HEADING_PATTERN = re.compile(
r"^(?:chapter|section|part|article)\s+\d+",
re.IGNORECASE,
)
_LIST_PATTERN = re.compile(r"^\s*(?:[β’\-ββββ β‘βΊβΈβ]|\d+[.)]\s|[a-z][.)]\s)", re.IGNORECASE)
def _classify_ocr_lines(lines: list[str]) -> list[ContentBlock]:
"""Heuristic classification of OCR text lines into content blocks."""
blocks: list[ContentBlock] = []
para_lines: list[str] = []
def flush():
if para_lines:
text = " ".join(para_lines).strip()
if text:
blocks.append(ContentBlock(
block_type=BlockType.PARAGRAPH,
text=text,
source="ocr",
))
para_lines.clear()
for line in lines:
stripped = line.strip()
if not stripped:
flush()
continue
# All-caps short line or "Chapter N" pattern β heading
if (
(len(stripped) < 80 and stripped == stripped.upper() and len(stripped) > 3)
or _HEADING_PATTERN.match(stripped)
):
flush()
blocks.append(ContentBlock(
block_type=BlockType.HEADING,
text=stripped,
heading_level=HeadingLevel.H2,
source="ocr",
))
continue
if _LIST_PATTERN.match(stripped):
flush()
# Strip bullet character
clean = re.sub(r"^\s*[β’\-ββββ β‘βΊβΈβ]\s*", "", stripped)
clean = re.sub(r"^\s*\d+[.)]\s*", "", clean) or stripped
blocks.append(ContentBlock(
block_type=BlockType.LIST,
list_items=[ListItem(text=clean)],
source="ocr",
))
continue
para_lines.append(stripped)
flush()
return blocks
def ocr_page(
pdf_path: str | Path,
page_num: int,
dpi: int = 300,
lang: str = "eng",
) -> PageResult:
"""Run OCR on a single PDF page and return structured blocks."""
if not _TESSERACT_AVAILABLE:
return PageResult(
page_number=page_num + 1,
blocks=[ContentBlock(
block_type=BlockType.PARAGRAPH,
text="[OCR unavailable β Tesseract not installed]",
source="ocr",
confidence=0.0,
)],
plain_text="[OCR unavailable]",
is_scanned=True,
ocr_confidence=0.0,
)
import pytesseract
image = rasterize_page(pdf_path, page_num, dpi)
if is_mostly_blank(image):
return PageResult(
page_number=page_num + 1,
is_scanned=True,
ocr_confidence=1.0,
plain_text="",
blocks=[],
)
# Preprocess for OCR
processed = preprocess_for_ocr(image)
# Run Tesseract with full data for confidence scores
ocr_data = pytesseract.image_to_data(
processed, lang=lang, output_type=pytesseract.Output.DICT,
)
# Compute average confidence (skip -1 entries)
confs = [c for c in ocr_data.get("conf", []) if isinstance(c, (int, float)) and c >= 0]
avg_conf = sum(confs) / len(confs) / 100.0 if confs else 0.0
# Also get plain text
plain_text = pytesseract.image_to_string(processed, lang=lang).strip()
lines = plain_text.split("\n")
blocks = _classify_ocr_lines(lines)
# Set confidence on all blocks
for b in blocks:
b.confidence = avg_conf
# Attempt table detection via Tesseract TSV data
table_blocks = _detect_tables_from_ocr(ocr_data)
blocks.extend(table_blocks)
with fitz.open(str(pdf_path)) as doc:
rect = doc[page_num].rect
return PageResult(
page_number=page_num + 1,
width=rect.width,
height=rect.height,
blocks=blocks,
plain_text=plain_text,
is_scanned=True,
ocr_confidence=round(avg_conf, 3),
)
def _detect_tables_from_ocr(ocr_data: dict) -> list[ContentBlock]:
"""Basic table detection from OCR bounding-box alignment.
Groups words by similar y-coordinates (rows) and x-gaps (columns).
This is a heuristic β it won't catch every table but gives a
reasonable first pass.
"""
blocks: list[ContentBlock] = []
tops = ocr_data.get("top", [])
lefts = ocr_data.get("left", [])
widths = ocr_data.get("width", [])
heights = ocr_data.get("height", [])
texts = ocr_data.get("text", [])
if not tops or len(tops) < 4:
return blocks
# Group by block_num
block_nums = ocr_data.get("block_num", [])
line_nums = ocr_data.get("line_num", [])
word_nums = ocr_data.get("word_num", [])
# Build lines: group words with same (block, line)
line_groups: dict[tuple[int, int], list[dict]] = {}
for i in range(len(texts)):
txt = (texts[i] or "").strip()
if not txt:
continue
key = (block_nums[i], line_nums[i])
line_groups.setdefault(key, []).append({
"text": txt,
"left": lefts[i],
"top": tops[i],
"width": widths[i],
"height": heights[i],
})
# Look for blocks where multiple lines have consistent tab-stop alignment
# (indicates tabular layout). This is a simplified heuristic.
# For production, consider using opencv line-detection on the original image.
return blocks
|