perf(kb):1.优化 PDF只对可疑页做 image box 分析避免整本重复扫描/重复 reopen;2.doc/.docx 不再因为“有图片”就强制 OCR;3.只在 intake 路由 明确要求 OCR 时才跑
This commit is contained in:
1 parent
a3123cd602
commit
c58ed37cc1
11 files changed
+717
-122
No files matched your search
@@ -212,12 +212,33 @@ def _derive_output_rel_md(file_path: Path, input_path: Path) -> Path:
|
||||
return rel.with_suffix(".md")
|
||||
|
||||
|
||||
def _strip_in_memory_images(blocks: list) -> list:
|
||||
out = []
|
||||
for b in blocks:
|
||||
meta = dict(getattr(b, "meta", {}) or {})
|
||||
if "image" in meta:
|
||||
meta.pop("image", None)
|
||||
b = type(b)(
|
||||
id=b.id,
|
||||
page=b.page,
|
||||
type=b.type,
|
||||
text=b.text,
|
||||
bbox=b.bbox,
|
||||
meta=meta,
|
||||
)
|
||||
out.append(b)
|
||||
return out
|
||||
|
||||
|
||||
def _normalize_path_for_match(p: Path | str) -> str:
|
||||
return str(p).replace("\\", "/")
|
||||
|
||||
|
||||
def _file_timeout_sec() -> int | None:
|
||||
raw = str(os.environ.get("EDKB_FILE_TIMEOUT_SEC", "0")).strip()
|
||||
_WORD_TIMEOUT_EXTS = {".doc", ".docx"}
|
||||
|
||||
|
||||
def _parse_timeout_env(name: str, default: str = "0") -> int | None:
|
||||
raw = str(os.environ.get(name, default)).strip()
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError:
|
||||
@@ -225,6 +246,15 @@ def _file_timeout_sec() -> int | None:
|
||||
return value if value > 0 else None
|
||||
|
||||
|
||||
def _file_timeout_sec(file_path: Path | None = None) -> int | None:
|
||||
suffix = str(getattr(file_path, "suffix", "") or "").lower()
|
||||
if suffix in _WORD_TIMEOUT_EXTS:
|
||||
specific = _parse_timeout_env("EDKB_WORD_FILE_TIMEOUT_SEC")
|
||||
if specific:
|
||||
return specific
|
||||
return _parse_timeout_env("EDKB_FILE_TIMEOUT_SEC")
|
||||
|
||||
|
||||
def _cleanup_input_temp_files(input_path: Path) -> list[Path]:
|
||||
if input_path.is_file():
|
||||
candidates = [input_path]
|
||||
@@ -246,6 +276,28 @@ def _cleanup_input_temp_files(input_path: Path) -> list[Path]:
|
||||
return removed
|
||||
|
||||
|
||||
def _should_run_ocr(profile, cfg, blocks: list, context: Context | None = None) -> bool:
|
||||
if not blocks or not cfg.ocr.enable:
|
||||
return False
|
||||
if profile.file_type in {"ppt", "pptx"}:
|
||||
return False
|
||||
|
||||
pipeline_requests_ocr = "edkb-ocr" in profile.recommended_pipeline
|
||||
has_image_blocks = any(b.type == "image" for b in blocks)
|
||||
|
||||
# Word documents often contain decorative or embedded images. If intake
|
||||
# did not explicitly request OCR, do not force a slow OCR pass just because
|
||||
# image blocks exist.
|
||||
if profile.file_type in {"doc", "docx"} and not pipeline_requests_ocr:
|
||||
return False
|
||||
|
||||
if profile.file_type == "pdf" and not pipeline_requests_ocr:
|
||||
extras = getattr(context, "extras", {}) or {}
|
||||
return bool(extras.get("scan_likely") or extras.get("pdf_page_image_mode_pages"))
|
||||
|
||||
return pipeline_requests_ocr or has_image_blocks
|
||||
|
||||
|
||||
def _matches_pattern(candidates: list[str], patterns: list[str]) -> str | None:
|
||||
if not patterns:
|
||||
return None
|
||||
@@ -311,7 +363,7 @@ def _run_one_with_timeout(
|
||||
final_md_path: Path | None = None,
|
||||
progress_label: str | None = None,
|
||||
) -> dict:
|
||||
timeout = _file_timeout_sec()
|
||||
timeout = _file_timeout_sec(file_path)
|
||||
if not timeout:
|
||||
return _run_one(
|
||||
file_path,
|
||||
@@ -536,18 +588,14 @@ def _run_one(
|
||||
|
||||
if blocks:
|
||||
ctx.images = sum(1 for b in blocks if b.type == "image")
|
||||
should_ocr = cfg.ocr.enable and (
|
||||
"edkb-ocr" in profile.recommended_pipeline
|
||||
or any(b.type == "image" for b in blocks)
|
||||
)
|
||||
if profile.file_type in {"ppt", "pptx"}:
|
||||
should_ocr = False
|
||||
should_ocr = _should_run_ocr(profile, cfg, blocks, ctx)
|
||||
if should_ocr:
|
||||
_announce("ocr")
|
||||
t0 = time.perf_counter()
|
||||
blocks = ocr.run(blocks, ctx, min_confidence=cfg.ocr.min_confidence)
|
||||
_mark("edkb-ocr", t0)
|
||||
trace_steps.append("edkb-ocr")
|
||||
blocks = _strip_in_memory_images(blocks)
|
||||
|
||||
doc_kind = (ctx.extras.get("intake") or {}).get("doc_kind")
|
||||
policy_text = doc_kind == "policy_text"
|
||||
|
||||
@@ -206,7 +206,17 @@ def blocks_to_plain_markdown(blocks: list[Block]) -> str:
|
||||
lines.append(f"## {txt}")
|
||||
elif b.type == "image":
|
||||
data_uri = b.meta.get("data_uri") if b.meta else None
|
||||
if data_uri:
|
||||
is_pdf_page_image = bool(
|
||||
b.meta
|
||||
and b.meta.get("page_image")
|
||||
and b.meta.get("page_image_source") == "pdf"
|
||||
)
|
||||
if is_pdf_page_image:
|
||||
lines.append(f"![page-image-{b.page}]")
|
||||
ocr_text = ocr_by_image.get(b.id)
|
||||
if ocr_text:
|
||||
lines.append(f"图中文字:{ocr_text}")
|
||||
elif data_uri:
|
||||
image_idx += 1
|
||||
if b.meta and b.meta.get("page_image"):
|
||||
lines.append(f"")
|
||||
@@ -220,11 +230,7 @@ def blocks_to_plain_markdown(blocks: list[Block]) -> str:
|
||||
page_body_chars.get(b.page, 0) >= 15
|
||||
or page_text_chars.get(b.page, 0) >= 40
|
||||
)
|
||||
if (
|
||||
b.meta
|
||||
and b.meta.get("page_image")
|
||||
and b.meta.get("page_image_source") != "pptx"
|
||||
):
|
||||
if b.meta and b.meta.get("page_image"):
|
||||
lines.extend(_page_image_structured_lines(ocr_text))
|
||||
if not suppress_pptx_ocr:
|
||||
lines.append(f"图中文字:{ocr_text}")
|
||||
|
||||
@@ -472,6 +472,67 @@ class _RemoteImageRewriter:
|
||||
)
|
||||
|
||||
|
||||
class _LocalPreviewImageRewriter:
|
||||
def __init__(self, *, images_dir: Path) -> None:
|
||||
self.images_dir = images_dir
|
||||
self.uri_cache: dict[str, str] = {}
|
||||
self.sha_cache: dict[str, str] = {}
|
||||
self._next_image_index = 1
|
||||
|
||||
def _store_embedded_uri(self, uri: str, fmt: str, b64_raw: str) -> str:
|
||||
cached = self.uri_cache.get(uri)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
b64_clean = re.sub(r"\s+", "", b64_raw or "")
|
||||
try:
|
||||
blob = base64.b64decode(b64_clean, validate=False)
|
||||
except Exception:
|
||||
self.uri_cache[uri] = ""
|
||||
return ""
|
||||
|
||||
if not _is_valid_image_blob(blob):
|
||||
self.uri_cache[uri] = ""
|
||||
return ""
|
||||
|
||||
sha = hashlib.sha256(blob).hexdigest()
|
||||
cached_sha = self.sha_cache.get(sha)
|
||||
if cached_sha is not None:
|
||||
self.uri_cache[uri] = cached_sha
|
||||
return cached_sha
|
||||
|
||||
ext = _normalize_ext(fmt, blob)
|
||||
file_name = f"img_{self._next_image_index:03d}_{sha[:8]}.{ext}"
|
||||
self._next_image_index += 1
|
||||
self.images_dir.mkdir(parents=True, exist_ok=True)
|
||||
image_path = self.images_dir / file_name
|
||||
image_path.write_bytes(blob)
|
||||
rel_path = f"{self.images_dir.name}/{file_name}"
|
||||
self.sha_cache[sha] = rel_path
|
||||
self.uri_cache[uri] = rel_path
|
||||
return rel_path
|
||||
|
||||
def replace_text(self, text: str) -> str:
|
||||
if not text or "data:image/" not in text:
|
||||
return text
|
||||
|
||||
def repl(m: re.Match[str]) -> str:
|
||||
alt = m.group("alt") or "image"
|
||||
rel_path = self._store_embedded_uri(
|
||||
m.group("uri"),
|
||||
m.group("fmt") or "png",
|
||||
m.group("b64") or "",
|
||||
)
|
||||
if not rel_path:
|
||||
return f"![{alt}]"
|
||||
return f""
|
||||
|
||||
out = _EMBEDDED_IMG_RE.sub(repl, text)
|
||||
if "data:image/" in out:
|
||||
out = _EMBEDDED_IMG_ANY_RE.sub("![image]", out)
|
||||
return out
|
||||
|
||||
|
||||
def run(input_data: dict, context: Context) -> dict:
|
||||
out_dir = Path(input_data["out_dir"])
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -518,8 +579,12 @@ def run(input_data: dict, context: Context) -> dict:
|
||||
exported_chunks = [replace(c, text=rewriter.replace_text(c.text)) for c in chunks]
|
||||
rewriter.finalize()
|
||||
|
||||
preview_rewriter = _LocalPreviewImageRewriter(images_dir=view_images_dir)
|
||||
preview_md = preview_rewriter.replace_text(clean_md)
|
||||
|
||||
_write(out_dir / "03_clean.md", clean_md)
|
||||
_write(flat_clean_path, clean_md)
|
||||
_write(view_clean_path, preview_md)
|
||||
|
||||
lines = [json.dumps(asdict(c), ensure_ascii=False) for c in exported_chunks]
|
||||
_write(out_dir / "04_chunks.jsonl", "\n".join(lines) + ("\n" if lines else ""))
|
||||
|
||||
@@ -17,6 +17,9 @@ from edkb_system.contracts import Block, Context
|
||||
from edkb_system.skills.soffice_util import convert_with_soffice, soffice_candidates
|
||||
from edkb_system.skills.word_bridge import convert_with_word
|
||||
|
||||
_IMAGE_URI_CACHE: dict[tuple[str, str], str] = {}
|
||||
_IMAGE_URI_CACHE_MAX = 512
|
||||
|
||||
|
||||
def _to_data_uri(blob: bytes, content_type: str | None = None) -> str:
|
||||
ct = content_type or "image/png"
|
||||
@@ -25,18 +28,64 @@ def _to_data_uri(blob: bytes, content_type: str | None = None) -> str:
|
||||
|
||||
|
||||
def _to_preferred_image_data_uri(blob: bytes, content_type: str | None = None) -> str:
|
||||
ct = str(content_type or "image/png").strip().lower() or "image/png"
|
||||
cache_key = (hashlib.sha1(blob).hexdigest(), ct)
|
||||
cached = _IMAGE_URI_CACHE.get(cache_key)
|
||||
if cached:
|
||||
return cached
|
||||
|
||||
if ct in {"image/jpeg", "image/jpg"}:
|
||||
uri = _to_data_uri(blob, "image/jpeg")
|
||||
if len(_IMAGE_URI_CACHE) >= _IMAGE_URI_CACHE_MAX:
|
||||
_IMAGE_URI_CACHE.clear()
|
||||
_IMAGE_URI_CACHE[cache_key] = uri
|
||||
return uri
|
||||
|
||||
try:
|
||||
from PIL import Image
|
||||
|
||||
with Image.open(io.BytesIO(blob)) as im:
|
||||
rgb = Image.new("RGB", im.size, (255, 255, 255))
|
||||
rgba = im.convert("RGBA")
|
||||
rgb.paste(rgba, mask=rgba.split()[3])
|
||||
out = io.BytesIO()
|
||||
rgb.save(out, format="JPEG", quality=90)
|
||||
return _to_data_uri(out.getvalue(), "image/jpeg")
|
||||
if im.mode in {"RGB", "L"} and ct in {"image/png", "image/bmp"}:
|
||||
uri = _to_data_uri(blob, ct)
|
||||
else:
|
||||
rgb = Image.new("RGB", im.size, (255, 255, 255))
|
||||
rgba = im.convert("RGBA")
|
||||
rgb.paste(rgba, mask=rgba.split()[3])
|
||||
out = io.BytesIO()
|
||||
rgb.save(out, format="JPEG", quality=90)
|
||||
uri = _to_data_uri(out.getvalue(), "image/jpeg")
|
||||
if len(_IMAGE_URI_CACHE) >= _IMAGE_URI_CACHE_MAX:
|
||||
_IMAGE_URI_CACHE.clear()
|
||||
_IMAGE_URI_CACHE[cache_key] = uri
|
||||
return uri
|
||||
except Exception:
|
||||
return _to_data_uri(blob, content_type)
|
||||
uri = _to_data_uri(blob, content_type)
|
||||
if len(_IMAGE_URI_CACHE) >= _IMAGE_URI_CACHE_MAX:
|
||||
_IMAGE_URI_CACHE.clear()
|
||||
_IMAGE_URI_CACHE[cache_key] = uri
|
||||
return uri
|
||||
|
||||
|
||||
def _build_image_uri_map(doc) -> dict[str, str]:
|
||||
image_uri_by_rid: dict[str, str] = {}
|
||||
rel_items = list(doc.part.rels.items())
|
||||
rel_items.sort(
|
||||
key=lambda kv: int((kv[0] or "rId0").replace("rId", "") or 0)
|
||||
if (kv[0] or "").startswith("rId")
|
||||
else 0
|
||||
)
|
||||
for rid, rel in rel_items:
|
||||
reltype = getattr(rel, "reltype", "") or ""
|
||||
if "image" not in reltype:
|
||||
continue
|
||||
try:
|
||||
part = rel.target_part
|
||||
blob = part.blob
|
||||
content_type = getattr(part, "content_type", None)
|
||||
image_uri_by_rid[str(rid)] = _to_preferred_image_data_uri(blob, content_type)
|
||||
except Exception:
|
||||
continue
|
||||
return image_uri_by_rid
|
||||
|
||||
|
||||
def _image_dimensions(blob: bytes, ext: str) -> tuple[int, int]:
|
||||
@@ -209,14 +258,24 @@ def _split_tall_image(blob: bytes, ext: str) -> list[bytes]:
|
||||
return [blob]
|
||||
|
||||
|
||||
def _extract_image_uris_from_paragraph(para, doc) -> list[str]:
|
||||
def _extract_image_uris_from_paragraph(
|
||||
para, doc, image_uri_by_rid: dict[str, str] | None = None
|
||||
) -> list[str]:
|
||||
uris: list[str] = []
|
||||
seen_rids: set[str] = set()
|
||||
try:
|
||||
rids = para._element.xpath(".//a:blip/@r:embed")
|
||||
except Exception:
|
||||
return uris
|
||||
for rid in rids:
|
||||
rid = str(rid)
|
||||
if rid in seen_rids:
|
||||
continue
|
||||
seen_rids.add(rid)
|
||||
try:
|
||||
if image_uri_by_rid and rid in image_uri_by_rid:
|
||||
uris.append(image_uri_by_rid[rid])
|
||||
continue
|
||||
part = doc.part.related_parts[rid]
|
||||
blob = part.blob
|
||||
content_type = getattr(part, "content_type", None)
|
||||
@@ -226,42 +285,34 @@ def _extract_image_uris_from_paragraph(para, doc) -> list[str]:
|
||||
return uris
|
||||
|
||||
|
||||
def _extract_all_image_uris_from_doc(doc) -> list[str]:
|
||||
def _extract_all_image_uris_from_doc(
|
||||
doc, image_uri_by_rid: dict[str, str] | None = None
|
||||
) -> list[str]:
|
||||
if image_uri_by_rid:
|
||||
return list(dict.fromkeys(image_uri_by_rid.values()))
|
||||
|
||||
uris: list[str] = []
|
||||
seen: set[str] = set()
|
||||
rel_items = list(doc.part.rels.items())
|
||||
rel_items.sort(
|
||||
key=lambda kv: int((kv[0] or "rId0").replace("rId", "") or 0)
|
||||
if (kv[0] or "").startswith("rId")
|
||||
else 0
|
||||
)
|
||||
for _, rel in rel_items:
|
||||
reltype = getattr(rel, "reltype", "") or ""
|
||||
if "image" not in reltype:
|
||||
continue
|
||||
try:
|
||||
part = rel.target_part
|
||||
blob = part.blob
|
||||
content_type = getattr(part, "content_type", None)
|
||||
uri = _to_preferred_image_data_uri(blob, content_type)
|
||||
key = hashlib.sha1(blob).hexdigest()
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
uris.append(uri)
|
||||
except Exception:
|
||||
for uri in _build_image_uri_map(doc).values():
|
||||
if uri in seen:
|
||||
continue
|
||||
seen.add(uri)
|
||||
uris.append(uri)
|
||||
return uris
|
||||
|
||||
|
||||
def _extract_image_uris_from_table(table, doc) -> list[str]:
|
||||
def _extract_image_uris_from_table(
|
||||
table, doc, image_uri_by_rid: dict[str, str] | None = None
|
||||
) -> list[str]:
|
||||
uris: list[str] = []
|
||||
seen: set[str] = set()
|
||||
try:
|
||||
for row in table.rows:
|
||||
for cell in row.cells:
|
||||
for para in cell.paragraphs:
|
||||
for uri in _extract_image_uris_from_paragraph(para, doc):
|
||||
for uri in _extract_image_uris_from_paragraph(
|
||||
para, doc, image_uri_by_rid
|
||||
):
|
||||
if uri in seen:
|
||||
continue
|
||||
seen.add(uri)
|
||||
@@ -1298,7 +1349,9 @@ def _extract_missing_634_badge_table_from_word_html(
|
||||
]
|
||||
|
||||
|
||||
def _table_to_markdown(table, doc) -> str:
|
||||
def _table_to_markdown(
|
||||
table, doc, image_uri_by_rid: dict[str, str] | None = None
|
||||
) -> str:
|
||||
rows: list[list[str]] = []
|
||||
seen_img_uri: set[str] = set()
|
||||
for r in table.rows:
|
||||
@@ -1308,7 +1361,9 @@ def _table_to_markdown(table, doc) -> str:
|
||||
img_uris: list[str] = []
|
||||
try:
|
||||
for para in c.paragraphs:
|
||||
for uri in _extract_image_uris_from_paragraph(para, doc):
|
||||
for uri in _extract_image_uris_from_paragraph(
|
||||
para, doc, image_uri_by_rid
|
||||
):
|
||||
if uri in seen_img_uri:
|
||||
continue
|
||||
seen_img_uri.add(uri)
|
||||
@@ -1664,6 +1719,7 @@ def run(input_data: dict, context: Context) -> list[Block]:
|
||||
|
||||
parsed: list[Block] = []
|
||||
doc = Document(str(docx_path))
|
||||
image_uri_by_rid = _build_image_uri_map(doc)
|
||||
num_to_abs, levels = _load_numbering_schema(docx_path)
|
||||
list_states: dict[str, dict[int, int]] = {}
|
||||
context.pages = 1
|
||||
@@ -1706,7 +1762,9 @@ def run(input_data: dict, context: Context) -> list[Block]:
|
||||
|
||||
if marker and text and not text.startswith(marker):
|
||||
text = f"{marker} {text}"
|
||||
image_uris = _extract_image_uris_from_paragraph(para, doc)
|
||||
image_uris = _extract_image_uris_from_paragraph(
|
||||
para, doc, image_uri_by_rid
|
||||
)
|
||||
if text:
|
||||
idx += 1
|
||||
typ = (
|
||||
@@ -1738,7 +1796,7 @@ def run(input_data: dict, context: Context) -> list[Block]:
|
||||
)
|
||||
elif isinstance(child, CT_Tbl):
|
||||
table = Table(child, doc)
|
||||
md = _table_to_markdown(table, doc)
|
||||
md = _table_to_markdown(table, doc, image_uri_by_rid)
|
||||
if md:
|
||||
if _looks_like_form_metadata_table(md):
|
||||
blocks = _form_table_to_blocks(table, idx)
|
||||
@@ -1760,7 +1818,7 @@ def run(input_data: dict, context: Context) -> list[Block]:
|
||||
# 表格内图片已并入表格 markdown 单元格,避免脱离原始位置。
|
||||
|
||||
if not any(b.type == "image" for b in parsed):
|
||||
for uri in _extract_all_image_uris_from_doc(doc):
|
||||
for uri in _extract_all_image_uris_from_doc(doc, image_uri_by_rid):
|
||||
idx += 1
|
||||
context.images += 1
|
||||
parsed.append(
|
||||
|
||||
@@ -6,6 +6,9 @@ from pathlib import Path
|
||||
|
||||
from edkb_system.contracts import Block, Context
|
||||
|
||||
_PAGE_IMAGE_RENDER_SCALE = 0.75
|
||||
_PAGE_IMAGE_JPEG_QUALITY = 82
|
||||
|
||||
|
||||
def _is_scanned(text_chars: int, pages: int) -> bool:
|
||||
return text_chars < int(300 * max(pages, 1) / 10)
|
||||
@@ -76,32 +79,58 @@ def _should_use_page_image_mode(
|
||||
return False
|
||||
|
||||
|
||||
def _collect_image_boxes(
|
||||
file_path: Path, page_count: int
|
||||
def _analysis_candidate_pages(
|
||||
page_payloads: list[dict], scan_likely: bool
|
||||
) -> list[int]:
|
||||
if scan_likely:
|
||||
return [int(payload["page"]) for payload in page_payloads]
|
||||
return [
|
||||
int(payload["page"])
|
||||
for payload in page_payloads
|
||||
if len(str(payload.get("text") or "")) <= 120
|
||||
]
|
||||
|
||||
|
||||
def _collect_image_boxes_from_doc(
|
||||
doc, page_numbers: list[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]]] = {}
|
||||
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))
|
||||
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
|
||||
return _collect_image_boxes_from_doc(doc, page_numbers)
|
||||
except Exception:
|
||||
return {}
|
||||
finally:
|
||||
@@ -110,12 +139,25 @@ def _collect_image_boxes(
|
||||
doc.close()
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
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 = 2.0
|
||||
) -> bytes | None:
|
||||
file_path: Path, page_number: int, scale: float = _PAGE_IMAGE_RENDER_SCALE
|
||||
) -> object | None:
|
||||
try:
|
||||
import pypdfium2 as pdfium
|
||||
except Exception:
|
||||
@@ -124,12 +166,7 @@ def _render_page_png(
|
||||
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()
|
||||
return _render_page_image_from_doc(doc, page_number, scale=scale)
|
||||
except Exception:
|
||||
return None
|
||||
finally:
|
||||
@@ -170,7 +207,19 @@ def run(input_data: dict, context: Context) -> list[Block]:
|
||||
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)
|
||||
candidate_pages = _analysis_candidate_pages(page_payloads, scan_likely)
|
||||
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:
|
||||
@@ -199,8 +248,12 @@ def run(input_data: dict, context: Context) -> list[Block]:
|
||||
)
|
||||
|
||||
if use_page_image_mode:
|
||||
rendered = _render_page_png(file_path, page_idx)
|
||||
if rendered:
|
||||
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}",
|
||||
@@ -209,8 +262,9 @@ def run(input_data: dict, context: Context) -> list[Block]:
|
||||
text="",
|
||||
bbox=(0.0, 0.0, 1000.0, 1000.0),
|
||||
meta={
|
||||
"data_uri": _to_data_uri(rendered, "image/png"),
|
||||
"page_image": True,
|
||||
"page_image_source": "pdf",
|
||||
"image": rendered,
|
||||
},
|
||||
)
|
||||
)
|
||||
@@ -244,6 +298,11 @@ def run(input_data: dict, context: Context) -> list[Block]:
|
||||
"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}")
|
||||
|
||||
|
||||
@@ -6,6 +6,9 @@ import re
|
||||
|
||||
from edkb_system.contracts import Block, Context
|
||||
|
||||
_RAPID_OCR_ENGINE = None
|
||||
_PDF_PAGE_IMAGE_MAX_EDGE = 1800
|
||||
|
||||
|
||||
def _decode_data_uri_image(data_uri: str):
|
||||
m = re.match(r"^data:image/[^;]+;base64,(.+)$", data_uri or "", re.DOTALL)
|
||||
@@ -26,17 +29,66 @@ def _decode_data_uri_image(data_uri: str):
|
||||
return None
|
||||
|
||||
|
||||
def _get_ocr_engine():
|
||||
global _RAPID_OCR_ENGINE
|
||||
if _RAPID_OCR_ENGINE is not None:
|
||||
return _RAPID_OCR_ENGINE
|
||||
|
||||
from rapidocr_onnxruntime import RapidOCR # type: ignore
|
||||
|
||||
_RAPID_OCR_ENGINE = RapidOCR()
|
||||
return _RAPID_OCR_ENGINE
|
||||
|
||||
|
||||
def _prepare_image_for_ocr(image_obj, block: Block):
|
||||
meta = getattr(block, "meta", {}) or {}
|
||||
if not (
|
||||
meta.get("page_image")
|
||||
and str(meta.get("page_image_source") or "").lower() == "pdf"
|
||||
):
|
||||
return image_obj
|
||||
|
||||
try:
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
if not hasattr(image_obj, "shape") or len(image_obj.shape) < 2:
|
||||
return image_obj
|
||||
height = int(image_obj.shape[0])
|
||||
width = int(image_obj.shape[1])
|
||||
max_edge = max(width, height)
|
||||
if max_edge <= _PDF_PAGE_IMAGE_MAX_EDGE:
|
||||
return image_obj
|
||||
|
||||
scale = _PDF_PAGE_IMAGE_MAX_EDGE / float(max_edge)
|
||||
target_size = (
|
||||
max(1, int(round(width * scale))),
|
||||
max(1, int(round(height * scale))),
|
||||
)
|
||||
pil_image = Image.fromarray(np.asarray(image_obj, dtype=np.uint8))
|
||||
resized = pil_image.resize(target_size, Image.Resampling.LANCZOS)
|
||||
return np.asarray(resized)
|
||||
except Exception:
|
||||
return image_obj
|
||||
|
||||
|
||||
def _ocr_call_kwargs(block: Block) -> dict:
|
||||
meta = getattr(block, "meta", {}) or {}
|
||||
if meta.get("page_image") and str(meta.get("page_image_source") or "").lower() == "pdf":
|
||||
return {"use_det": True, "use_cls": False, "use_rec": True}
|
||||
return {}
|
||||
|
||||
|
||||
def run(
|
||||
input_data: list[Block], context: Context, min_confidence: float = 0.3
|
||||
) -> list[Block]:
|
||||
blocks = input_data
|
||||
try:
|
||||
from rapidocr_onnxruntime import RapidOCR # type: ignore
|
||||
engine = _get_ocr_engine()
|
||||
except Exception:
|
||||
context.warnings.append("RapidOCR unavailable; skip OCR")
|
||||
return blocks
|
||||
|
||||
engine = RapidOCR()
|
||||
out: list[Block] = []
|
||||
for b in blocks:
|
||||
out.append(b)
|
||||
@@ -46,6 +98,8 @@ def run(
|
||||
image_obj = b.meta.get("image")
|
||||
if image_obj is None and b.meta and b.meta.get("data_uri"):
|
||||
image_obj = _decode_data_uri_image(str(b.meta.get("data_uri")))
|
||||
if image_obj is not None:
|
||||
image_obj = _prepare_image_for_ocr(image_obj, b)
|
||||
if image_obj is None:
|
||||
out.append(
|
||||
Block(
|
||||
@@ -59,7 +113,7 @@ def run(
|
||||
continue
|
||||
|
||||
try:
|
||||
result, _ = engine(image_obj)
|
||||
result, _ = engine(image_obj, **_ocr_call_kwargs(b))
|
||||
lines = []
|
||||
for it in result or []:
|
||||
if len(it) < 3:
|
||||
|
||||
Reference in new issue
Block a user