209 lines
8.3 KiB
Python
209 lines
8.3 KiB
Python
"""
|
||
backend/app/services/knowledge_cleaning/edkb_adapter.py
|
||
|
||
用途:把 edkb_system 的清洗产物适配为业务服务可直接使用的文件路径和统计信息。
|
||
依赖:edkb_system.controller、文件系统临时目录和导出产物约定。
|
||
逻辑:复制源文件到隔离目录执行清洗,再把 Markdown、分块和原始布局等必要产物持久化到目标目录。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import shutil
|
||
import tempfile
|
||
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
|
||
candidates = [path for path in output_root.rglob('*.md') if not path.name.startswith('_')]
|
||
if not candidates:
|
||
raise RuntimeError('No markdown output produced by edkb_system.')
|
||
candidates.sort(key=lambda item: len(item.parts))
|
||
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 _find_generated_chunks_jsonl(output_root: Path) -> Path | None:
|
||
candidates = [path for path in output_root.rglob('04_chunks.jsonl') if path.is_file()]
|
||
if not candidates:
|
||
return None
|
||
candidates.sort(key=lambda item: len(item.parts))
|
||
return candidates[0]
|
||
|
||
|
||
def _find_generated_raw_layout(output_root: Path) -> Path | None:
|
||
"""定位包含 OCR Block 元数据的原始布局产物,供下游复用检测框。"""
|
||
candidates = [path for path in output_root.rglob('01_raw_layout.json') if path.is_file()]
|
||
if not candidates:
|
||
return None
|
||
candidates.sort(key=lambda item: len(item.parts))
|
||
return candidates[0]
|
||
|
||
|
||
def _count_jsonl_lines(path: Path) -> int:
|
||
count = 0
|
||
with path.open(encoding='utf-8', errors='ignore') as handle:
|
||
for line in handle:
|
||
if line.strip():
|
||
count += 1
|
||
return count
|
||
|
||
|
||
def _persist_debug_chunks(output_root: Path, target_dir: Path) -> tuple[str | None, int | None]:
|
||
"""Copy edkb chunk artifacts into the KB version directory for local debugging."""
|
||
chunks_source = _find_generated_chunks_jsonl(output_root)
|
||
if not chunks_source or not chunks_source.exists():
|
||
return None, None
|
||
|
||
chunks_target = target_dir / '04_chunks.jsonl'
|
||
shutil.copy2(chunks_source, chunks_target)
|
||
|
||
chunks_dir_source = chunks_source.parent / 'chunks'
|
||
chunks_dir_target = target_dir / 'chunks'
|
||
if chunks_dir_source.is_dir():
|
||
if chunks_dir_target.exists():
|
||
shutil.rmtree(chunks_dir_target)
|
||
shutil.copytree(chunks_dir_source, chunks_dir_target)
|
||
|
||
return str(chunks_target), _count_jsonl_lines(chunks_target)
|
||
|
||
|
||
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'
|
||
content = source_path.read_text(encoding='utf-8', errors='ignore')
|
||
cleaned_path.write_text(content, encoding='utf-8')
|
||
return {
|
||
'mode': 'plain_text',
|
||
'cleaned_file_path': str(cleaned_path),
|
||
'cleaned_preview_path': str(cleaned_path),
|
||
'word_count': len(content.split()),
|
||
}
|
||
|
||
|
||
def build_clean_result(source_path: Path, target_dir: Path) -> dict:
|
||
"""
|
||
优先产出真实文本结果:
|
||
- txt/md:直接抽取文本;
|
||
- 其它格式:尝试走 edkb_system;
|
||
- 失败时由调用方决定是否回退。
|
||
"""
|
||
suffix = source_path.suffix.lower()
|
||
if suffix in TEXT_EXTS:
|
||
return _write_text_result(source_path, target_dir)
|
||
|
||
from edkb_system.config import SystemConfig
|
||
from edkb_system.controller import build_knowledge
|
||
|
||
target_dir.mkdir(parents=True, exist_ok=True)
|
||
with tempfile.TemporaryDirectory(prefix='edkb_', dir=str(target_dir.parent)) as tmp_dir:
|
||
tmp_root = Path(tmp_dir)
|
||
output_dir = tmp_root / 'output'
|
||
cache_dir = tmp_root / 'cache'
|
||
output_dir.mkdir(parents=True, exist_ok=True)
|
||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||
|
||
# IMPORTANT: copy the source file into tmp_root so that its parent directory is predictable
|
||
# edkb_system seems to output to output_dir / <parent_dir_name> / <filename>.md
|
||
# ALSO IMPORTANT: ensure the file has its original suffix, otherwise edkb_system might fail or output nothing
|
||
original_name = getattr(source_path, "original_filename", None)
|
||
if not original_name:
|
||
original_name = source_path.name
|
||
if "." not in original_name and hasattr(source_path, "suffix_hint"):
|
||
original_name += source_path.suffix_hint
|
||
|
||
tmp_source_path = tmp_root / original_name
|
||
shutil.copy2(source_path, tmp_source_path)
|
||
|
||
config = SystemConfig.load(None)
|
||
# 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')
|
||
chunks_file_path, chunks_count = _persist_debug_chunks(output_dir, target_dir)
|
||
raw_layout_source = _find_generated_raw_layout(output_dir)
|
||
raw_layout_path = None
|
||
if raw_layout_source:
|
||
raw_layout_target = target_dir / '01_raw_layout.json'
|
||
shutil.copy2(raw_layout_source, raw_layout_target)
|
||
raw_layout_path = str(raw_layout_target)
|
||
|
||
return {
|
||
'mode': 'edkb_system',
|
||
'cleaned_file_path': str(cleaned_path),
|
||
'cleaned_preview_path': str(preview_path),
|
||
'word_count': len(content.split()),
|
||
'chunks_file_path': chunks_file_path,
|
||
'chunks_count': chunks_count,
|
||
'raw_layout_path': raw_layout_path,
|
||
}
|