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

@@ -4,6 +4,7 @@ backend/app/services/knowledge_cleaning/edkb_adapter.py
"""
from __future__ import annotations
import os
import shutil
import tempfile
from pathlib import Path
@@ -12,6 +13,27 @@ from pathlib import Path
TEXT_EXTS = {'.txt', '.md'}
def _temporary_env(**overrides: str):
saved: dict[str, str | None] = {}
class _EnvGuard:
def __enter__(self):
for key, value in overrides.items():
saved[key] = os.environ.get(key)
os.environ[key] = value
return self
def __exit__(self, exc_type, exc, tb):
for key, old_value in saved.items():
if old_value is None:
os.environ.pop(key, None)
else:
os.environ[key] = old_value
return False
return _EnvGuard()
def _find_generated_markdown(output_root: Path) -> Path:
# Look for md files directly inside output_root or inside any of its subdirectories
# Note that edkb_system puts output inside a directory matching the parent dir name, which might be tmp_dir
@@ -22,6 +44,28 @@ def _find_generated_markdown(output_root: Path) -> Path:
return candidates[0]
def _find_generated_preview_markdown(output_root: Path) -> Path | None:
candidates = [path for path in output_root.rglob('03_clean_view.md') if path.is_file()]
if not candidates:
return None
candidates.sort(key=lambda item: len(item.parts))
return candidates[0]
def _rewrite_preview_markdown_if_needed(preview_path: Path, target_dir: Path) -> None:
content = preview_path.read_text(encoding='utf-8', errors='ignore')
if 'data:image/' not in content:
return
from edkb_system.skills.export import _LocalPreviewImageRewriter
images_dir = target_dir / 'images_view'
if images_dir.exists():
shutil.rmtree(images_dir)
rewriter = _LocalPreviewImageRewriter(images_dir=images_dir)
preview_path.write_text(rewriter.replace_text(content), encoding='utf-8')
def _write_text_result(source_path: Path, target_dir: Path) -> dict:
target_dir.mkdir(parents=True, exist_ok=True)
cleaned_path = target_dir / 'document.md'
@@ -70,19 +114,37 @@ def build_clean_result(source_path: Path, target_dir: Path) -> dict:
shutil.copy2(source_path, tmp_source_path)
config = SystemConfig.load(None)
result = build_knowledge(tmp_source_path, output_dir, config, cache_dir)
# Align with the xx system: do not spend clean-time uploading images to MinIO.
# Keep embedded-image fallback so Markdown can still be produced locally.
with _temporary_env(
MINIO_UPLOAD_ENABLED='false',
MINIO_ALLOW_EMBED_FALLBACK='true',
):
result = build_knowledge(tmp_source_path, output_dir, config, cache_dir)
failures = [item for item in result if item.get('status') == 'failed']
if failures:
raise RuntimeError(failures[0].get('error') or 'edkb_system failed.')
markdown_source = _find_generated_markdown(output_dir)
preview_source = _find_generated_preview_markdown(output_dir)
cleaned_path = target_dir / 'document.md'
shutil.copy2(markdown_source, cleaned_path)
preview_path = cleaned_path
if preview_source and preview_source.exists():
preview_path = target_dir / 'document_preview.md'
shutil.copy2(preview_source, preview_path)
preview_images_dir = preview_source.parent / 'images_view'
target_preview_images_dir = target_dir / 'images_view'
if target_preview_images_dir.exists():
shutil.rmtree(target_preview_images_dir)
if preview_images_dir.exists():
shutil.copytree(preview_images_dir, target_preview_images_dir)
_rewrite_preview_markdown_if_needed(preview_path, target_dir)
content = cleaned_path.read_text(encoding='utf-8', errors='ignore')
return {
'mode': 'edkb_system',
'cleaned_file_path': str(cleaned_path),
'cleaned_preview_path': str(cleaned_path),
'cleaned_preview_path': str(preview_path),
'word_count': len(content.split()),
}