perf(kb):1.优化 PDF只对可疑页做 image box 分析避免整本重复扫描/重复 reopen;2.doc/.docx 不再因为“有图片”就强制 OCR;3.只在 intake 路由 明确要求 OCR 时才跑

This commit is contained in:
runny committed 2026-06-06 16:53:05 +08:00
1 parent a3123cd602
commit c58ed37cc1
11 files changed
+717 -122

No files matched your search

+65
View File
@@ -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"![{alt}]({rel_path})"
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 ""))