390 lines
13 KiB
Python
390 lines
13 KiB
Python
from __future__ import annotations
|
|
|
|
import base64
|
|
import io
|
|
from pathlib import Path
|
|
|
|
from edkb_system.contracts import Block, Context
|
|
|
|
_PAGE_IMAGE_RENDER_SCALE = 0.75
|
|
_PAGE_IMAGE_JPEG_QUALITY = 82
|
|
_TEXT_HEAVY_PAGE_TEXT_LIMIT = 40
|
|
_DEFAULT_PAGE_TEXT_LIMIT = 120
|
|
_MIN_SCAN_IMAGE_BYTES = 4 * 1024
|
|
_MIN_DEFAULT_IMAGE_BYTES = 16 * 1024
|
|
_MIN_TEXT_HEAVY_IMAGE_BYTES = 24 * 1024
|
|
|
|
|
|
def _is_scanned(text_chars: int, pages: int) -> bool:
|
|
return text_chars < int(150 * max(pages, 1))
|
|
|
|
|
|
def _is_text_heavy_pdf(text_chars: int, pages: int) -> bool:
|
|
return text_chars >= max(800, 180 * max(pages, 1))
|
|
|
|
|
|
def _should_keep_embedded_image(
|
|
*,
|
|
data_size: int,
|
|
page_text_chars: int,
|
|
scan_likely: bool,
|
|
text_heavy_pdf: bool,
|
|
) -> bool:
|
|
if data_size <= 0:
|
|
return False
|
|
if scan_likely:
|
|
return data_size >= _MIN_SCAN_IMAGE_BYTES
|
|
if text_heavy_pdf:
|
|
return page_text_chars <= _TEXT_HEAVY_PAGE_TEXT_LIMIT and data_size >= _MIN_TEXT_HEAVY_IMAGE_BYTES
|
|
return page_text_chars <= 80 or data_size >= _MIN_DEFAULT_IMAGE_BYTES
|
|
|
|
|
|
def _to_data_uri(blob: bytes, content_type: str = "image/png") -> str:
|
|
b64 = base64.b64encode(blob).decode("ascii")
|
|
return f"data:{content_type};base64,{b64}"
|
|
|
|
|
|
def _normalize_box(
|
|
bounds: tuple[float, float, float, float],
|
|
) -> tuple[float, float, float, float]:
|
|
x0, y0, x1, y1 = bounds
|
|
left = min(x0, x1)
|
|
right = max(x0, x1)
|
|
top = min(y0, y1)
|
|
bottom = max(y0, y1)
|
|
return (left, top, right, bottom)
|
|
|
|
|
|
def _page_image_stats(
|
|
page_width: float,
|
|
page_height: float,
|
|
image_boxes: list[tuple[float, float, float, float]],
|
|
) -> dict[str, float]:
|
|
if page_width <= 0 or page_height <= 0 or not image_boxes:
|
|
return {
|
|
"count": float(len(image_boxes)),
|
|
"largest_ratio": 0.0,
|
|
"total_ratio": 0.0,
|
|
}
|
|
|
|
page_area = max(page_width * page_height, 1.0)
|
|
largest_ratio = 0.0
|
|
total_ratio = 0.0
|
|
for raw in image_boxes:
|
|
x0, y0, x1, y1 = _normalize_box(raw)
|
|
width = max(x1 - x0, 0.0)
|
|
height = max(y1 - y0, 0.0)
|
|
ratio = min((width * height) / page_area, 1.0)
|
|
largest_ratio = max(largest_ratio, ratio)
|
|
total_ratio += ratio
|
|
return {
|
|
"count": float(len(image_boxes)),
|
|
"largest_ratio": largest_ratio,
|
|
"total_ratio": min(total_ratio, 1.5),
|
|
}
|
|
|
|
|
|
def _should_use_page_image_mode(
|
|
*,
|
|
scan_likely: bool,
|
|
text_heavy_pdf: bool,
|
|
text_chars: int,
|
|
image_count: int,
|
|
largest_ratio: float,
|
|
total_ratio: float,
|
|
) -> bool:
|
|
if text_heavy_pdf and text_chars > _TEXT_HEAVY_PAGE_TEXT_LIMIT:
|
|
return False
|
|
if scan_likely:
|
|
if image_count == 0:
|
|
return True
|
|
if largest_ratio >= 0.55 or total_ratio >= 0.65 or image_count >= 3:
|
|
return True
|
|
if text_chars <= _DEFAULT_PAGE_TEXT_LIMIT and (
|
|
largest_ratio >= 0.72 or (image_count >= 5 and total_ratio >= 0.45)
|
|
):
|
|
return True
|
|
if text_heavy_pdf:
|
|
return text_chars <= _TEXT_HEAVY_PAGE_TEXT_LIMIT and (
|
|
largest_ratio >= 0.88 or total_ratio >= 0.95 or image_count >= 8
|
|
)
|
|
return False
|
|
|
|
|
|
def _analysis_candidate_pages(
|
|
page_payloads: list[dict], scan_likely: bool, text_heavy_pdf: bool
|
|
) -> list[int]:
|
|
if scan_likely:
|
|
return [int(payload["page"]) for payload in page_payloads]
|
|
if text_heavy_pdf:
|
|
return [
|
|
int(payload["page"])
|
|
for payload in page_payloads
|
|
if len(str(payload.get("text") or "")) <= _TEXT_HEAVY_PAGE_TEXT_LIMIT
|
|
]
|
|
return [
|
|
int(payload["page"])
|
|
for payload in page_payloads
|
|
if len(str(payload.get("text") or "")) <= _DEFAULT_PAGE_TEXT_LIMIT
|
|
]
|
|
|
|
|
|
def _collect_image_boxes_from_doc(
|
|
doc, page_numbers: list[int]
|
|
) -> dict[int, list[tuple[float, float, float, float]]]:
|
|
try:
|
|
import pypdfium2.raw as pdfium_c
|
|
except Exception:
|
|
return {}
|
|
|
|
out: dict[int, list[tuple[float, float, float, float]]] = {}
|
|
for page_number in page_numbers:
|
|
try:
|
|
page = doc[page_number - 1]
|
|
except Exception:
|
|
continue
|
|
boxes: list[tuple[float, float, float, float]] = []
|
|
try:
|
|
for obj in page.get_objects(filter=[pdfium_c.FPDF_PAGEOBJ_IMAGE]):
|
|
try:
|
|
bounds = obj.get_bounds()
|
|
except Exception:
|
|
bounds = obj.get_pos()
|
|
boxes.append(tuple(float(v) for v in bounds))
|
|
except Exception:
|
|
boxes = []
|
|
out[page_number] = boxes
|
|
return out
|
|
|
|
|
|
def _collect_image_boxes(
|
|
file_path: Path, page_numbers: list[int]
|
|
) -> dict[int, list[tuple[float, float, float, float]]]:
|
|
try:
|
|
import pypdfium2 as pdfium
|
|
except Exception:
|
|
return {}
|
|
|
|
doc = None
|
|
try:
|
|
doc = pdfium.PdfDocument(str(file_path))
|
|
return _collect_image_boxes_from_doc(doc, page_numbers)
|
|
except Exception:
|
|
return {}
|
|
finally:
|
|
try:
|
|
if doc is not None:
|
|
doc.close()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _render_page_image_from_doc(
|
|
doc, page_number: int, scale: float = _PAGE_IMAGE_RENDER_SCALE
|
|
) -> object | None:
|
|
try:
|
|
import numpy as np
|
|
|
|
page = doc[page_number - 1]
|
|
bitmap = page.render(scale=scale)
|
|
pil_image = bitmap.to_pil().convert("RGB")
|
|
return np.asarray(pil_image)
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def _render_page_png(
|
|
file_path: Path, page_number: int, scale: float = _PAGE_IMAGE_RENDER_SCALE
|
|
) -> object | None:
|
|
try:
|
|
import pypdfium2 as pdfium
|
|
except Exception:
|
|
return None
|
|
|
|
doc = None
|
|
try:
|
|
doc = pdfium.PdfDocument(str(file_path))
|
|
return _render_page_image_from_doc(doc, page_number, scale=scale)
|
|
except Exception:
|
|
return None
|
|
finally:
|
|
try:
|
|
if doc is not None:
|
|
doc.close()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def run(input_data: dict, context: Context) -> list[Block]:
|
|
file_path = Path(input_data["file_path"])
|
|
blocks: list[Block] = []
|
|
|
|
try:
|
|
from pypdf import PdfReader
|
|
|
|
reader = PdfReader(str(file_path))
|
|
context.pages = len(reader.pages)
|
|
text_chars = 0
|
|
page_payloads: list[dict] = []
|
|
for page_idx, p in enumerate(reader.pages, start=1):
|
|
text = (p.extract_text() or "").strip()
|
|
images: list[dict] = []
|
|
if text:
|
|
text_chars += len(text)
|
|
try:
|
|
page_width = float(getattr(getattr(p, "mediabox", None), "width", 1000.0) or 1000.0)
|
|
page_height = float(getattr(getattr(p, "mediabox", None), "height", 1000.0) or 1000.0)
|
|
except Exception:
|
|
page_width = 1000.0
|
|
page_height = 1000.0
|
|
|
|
try:
|
|
for img_idx, img in enumerate(getattr(p, "images", []) or [], start=1):
|
|
data = getattr(img, "data", None)
|
|
if not data:
|
|
continue
|
|
if not _should_keep_embedded_image(
|
|
data_size=len(data),
|
|
page_text_chars=len(text),
|
|
scan_likely=False,
|
|
text_heavy_pdf=False,
|
|
):
|
|
continue
|
|
ext = (getattr(img, "image_format", "") or "").lower()
|
|
ct = f"image/{ext}" if ext else "image/png"
|
|
images.append({"id": img_idx, "data": data, "content_type": ct})
|
|
except Exception:
|
|
pass
|
|
page_payloads.append(
|
|
{
|
|
"page": page_idx,
|
|
"text": text,
|
|
"images": images,
|
|
"page_width": page_width,
|
|
"page_height": page_height,
|
|
}
|
|
)
|
|
|
|
scan_likely = _is_scanned(text_chars, context.pages)
|
|
text_heavy_pdf = _is_text_heavy_pdf(text_chars, context.pages)
|
|
for payload in page_payloads:
|
|
payload["images"] = [
|
|
item
|
|
for item in payload["images"]
|
|
if _should_keep_embedded_image(
|
|
data_size=len(item.get("data") or b""),
|
|
page_text_chars=len(str(payload.get("text") or "")),
|
|
scan_likely=scan_likely,
|
|
text_heavy_pdf=text_heavy_pdf,
|
|
)
|
|
]
|
|
candidate_pages = _analysis_candidate_pages(
|
|
page_payloads, scan_likely, text_heavy_pdf
|
|
)
|
|
image_boxes_by_page: dict[int, list[tuple[float, float, float, float]]] = {}
|
|
pdfium_doc = None
|
|
if candidate_pages:
|
|
try:
|
|
import pypdfium2 as pdfium
|
|
|
|
pdfium_doc = pdfium.PdfDocument(str(file_path))
|
|
image_boxes_by_page = _collect_image_boxes_from_doc(
|
|
pdfium_doc, candidate_pages
|
|
)
|
|
except Exception:
|
|
image_boxes_by_page = _collect_image_boxes(file_path, candidate_pages)
|
|
page_image_mode_pages: list[int] = []
|
|
|
|
for payload in page_payloads:
|
|
page_idx = int(payload["page"])
|
|
text = str(payload["text"] or "")
|
|
page_images = list(payload["images"])
|
|
image_boxes = image_boxes_by_page.get(page_idx, [])
|
|
stats = _page_image_stats(
|
|
float(payload.get("page_width") or 1000.0),
|
|
float(payload.get("page_height") or 1000.0),
|
|
image_boxes,
|
|
)
|
|
use_page_image_mode = _should_use_page_image_mode(
|
|
scan_likely=scan_likely,
|
|
text_heavy_pdf=text_heavy_pdf,
|
|
text_chars=len(text),
|
|
image_count=len(page_images) or int(stats["count"]),
|
|
largest_ratio=float(stats["largest_ratio"]),
|
|
total_ratio=float(stats["total_ratio"]),
|
|
)
|
|
|
|
if text:
|
|
blocks.append(
|
|
Block(
|
|
id=f"pdf-{page_idx}",
|
|
page=page_idx,
|
|
type="paragraph",
|
|
text=text,
|
|
bbox=(0.0, 0.0, 1000.0, 1000.0),
|
|
)
|
|
)
|
|
|
|
if use_page_image_mode:
|
|
rendered = (
|
|
_render_page_image_from_doc(pdfium_doc, page_idx)
|
|
if pdfium_doc is not None
|
|
else _render_page_png(file_path, page_idx)
|
|
)
|
|
if rendered is not None:
|
|
blocks.append(
|
|
Block(
|
|
id=f"pdf-page-{page_idx}",
|
|
page=page_idx,
|
|
type="image",
|
|
text="",
|
|
bbox=(0.0, 0.0, 1000.0, 1000.0),
|
|
meta={
|
|
"page_image": True,
|
|
"page_image_source": "pdf",
|
|
"image": rendered,
|
|
},
|
|
)
|
|
)
|
|
context.images += 1
|
|
page_image_mode_pages.append(page_idx)
|
|
continue
|
|
|
|
for item in page_images:
|
|
blocks.append(
|
|
Block(
|
|
id=f"pdf-{page_idx}-img-{item['id']}",
|
|
page=page_idx,
|
|
type="image",
|
|
text="",
|
|
bbox=(0.0, 0.0, 1000.0, 1000.0),
|
|
meta={
|
|
"data_uri": _to_data_uri(
|
|
item["data"], str(item["content_type"])
|
|
)
|
|
},
|
|
)
|
|
)
|
|
context.images += 1
|
|
|
|
if scan_likely:
|
|
context.warnings.append("pdf likely scanned; OCR recommended")
|
|
context.extras["scan_likely"] = True
|
|
if text_heavy_pdf:
|
|
context.extras["text_heavy_pdf"] = True
|
|
if page_image_mode_pages:
|
|
context.extras["pdf_page_image_mode_pages"] = page_image_mode_pages
|
|
context.warnings.append(
|
|
"pdf page-image mode pages: "
|
|
+ ", ".join(str(x) for x in page_image_mode_pages)
|
|
)
|
|
try:
|
|
if pdfium_doc is not None:
|
|
pdfium_doc.close()
|
|
except Exception:
|
|
pass
|
|
except Exception as exc:
|
|
context.warnings.append(f"PDF parse failed: {exc}")
|
|
|
|
return blocks
|