init
This commit is contained in:
commit
fe636432d0
154 files changed
+30381
No files matched your search
@@ -0,0 +1,250 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import io
|
||||
from pathlib import Path
|
||||
|
||||
from edkb_system.contracts import Block, Context
|
||||
|
||||
|
||||
def _is_scanned(text_chars: int, pages: int) -> bool:
|
||||
return text_chars < int(300 * max(pages, 1) / 10)
|
||||
|
||||
|
||||
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_chars: int,
|
||||
image_count: int,
|
||||
largest_ratio: float,
|
||||
total_ratio: float,
|
||||
) -> bool:
|
||||
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 <= 120 and (
|
||||
largest_ratio >= 0.72 or (image_count >= 5 and total_ratio >= 0.45)
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _collect_image_boxes(
|
||||
file_path: Path, page_count: int
|
||||
) -> dict[int, list[tuple[float, float, float, float]]]:
|
||||
try:
|
||||
import pypdfium2 as pdfium
|
||||
import pypdfium2.raw as pdfium_c
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
out: dict[int, list[tuple[float, float, float, float]]] = {}
|
||||
doc = None
|
||||
try:
|
||||
doc = pdfium.PdfDocument(str(file_path))
|
||||
for page_idx in range(page_count):
|
||||
page = doc[page_idx]
|
||||
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_idx + 1] = boxes
|
||||
except Exception:
|
||||
return {}
|
||||
finally:
|
||||
try:
|
||||
if doc is not None:
|
||||
doc.close()
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def _render_page_png(
|
||||
file_path: Path, page_number: int, scale: float = 2.0
|
||||
) -> bytes | None:
|
||||
try:
|
||||
import pypdfium2 as pdfium
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
doc = None
|
||||
try:
|
||||
doc = pdfium.PdfDocument(str(file_path))
|
||||
page = doc[page_number - 1]
|
||||
bitmap = page.render(scale=scale)
|
||||
pil_image = bitmap.to_pil()
|
||||
buf = io.BytesIO()
|
||||
pil_image.save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
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:
|
||||
for img_idx, img in enumerate(getattr(p, "images", []) or [], start=1):
|
||||
data = getattr(img, "data", None)
|
||||
if not data:
|
||||
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})
|
||||
|
||||
scan_likely = _is_scanned(text_chars, context.pages)
|
||||
image_boxes_by_page = _collect_image_boxes(file_path, context.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(1000.0, 1000.0, image_boxes)
|
||||
use_page_image_mode = _should_use_page_image_mode(
|
||||
scan_likely=scan_likely,
|
||||
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_png(file_path, page_idx)
|
||||
if rendered:
|
||||
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={
|
||||
"data_uri": _to_data_uri(rendered, "image/png"),
|
||||
"page_image": True,
|
||||
},
|
||||
)
|
||||
)
|
||||
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 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)
|
||||
)
|
||||
except Exception as exc:
|
||||
context.warnings.append(f"PDF parse failed: {exc}")
|
||||
|
||||
return blocks
|
||||
Reference in new issue
Block a user