Merge branch 'dev' into test
This commit is contained in:
commit
8c98438370
11 files changed
+717
-122
No files matched your search
@@ -23,8 +23,12 @@ KB_WORKER_CONCURRENCY=3
|
|||||||
EDKB_SOFFICE=/usr/bin/soffice
|
EDKB_SOFFICE=/usr/bin/soffice
|
||||||
# LibreOffice 单次格式转换超时(秒);复杂 .doc 在容器内可能需 10 分钟左右
|
# LibreOffice 单次格式转换超时(秒);复杂 .doc 在容器内可能需 10 分钟左右
|
||||||
EDKB_SOFFICE_TIMEOUT_SEC=600
|
EDKB_SOFFICE_TIMEOUT_SEC=600
|
||||||
|
# Windows Word COM / word_bridge 单次转换超时(秒);复杂 .doc 可适当放宽
|
||||||
|
EDKB_WORD_TIMEOUT_SEC=300
|
||||||
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免单条任务长期卡住整个 worker
|
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免单条任务长期卡住整个 worker
|
||||||
EDKB_FILE_TIMEOUT_SEC=180
|
EDKB_FILE_TIMEOUT_SEC=180
|
||||||
|
# Word 文档(.doc/.docx)单文件清洗总超时(秒);优先于 EDKB_FILE_TIMEOUT_SEC
|
||||||
|
EDKB_WORD_FILE_TIMEOUT_SEC=420
|
||||||
# running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时
|
# running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时
|
||||||
KB_JOB_RUNNING_TIMEOUT_SECONDS=900
|
KB_JOB_RUNNING_TIMEOUT_SECONDS=900
|
||||||
|
|
||||||
|
|||||||
@@ -96,14 +96,46 @@ def _resolve_storage_path(path_value: str | None) -> Path | None:
|
|||||||
return None
|
return None
|
||||||
return candidate
|
return candidate
|
||||||
|
|
||||||
def _resolve_markdown_read_path(version: KbDocumentVersion) -> tuple[Path | None, str]:
|
|
||||||
|
def _ensure_preview_markdown(version: KbDocumentVersion) -> tuple[Path | None, str]:
|
||||||
primary = _resolve_storage_path(version.cleaned_file_path)
|
primary = _resolve_storage_path(version.cleaned_file_path)
|
||||||
if primary and primary.exists():
|
|
||||||
return (primary, 'markdown')
|
|
||||||
preview = _resolve_storage_path(version.cleaned_preview_path)
|
preview = _resolve_storage_path(version.cleaned_preview_path)
|
||||||
if preview and preview.exists():
|
preview_exists = bool(preview and preview.exists())
|
||||||
return (preview, 'preview')
|
primary_exists = bool(primary and primary.exists())
|
||||||
return (None, 'markdown')
|
|
||||||
|
if preview_exists:
|
||||||
|
preview_content = preview.read_text(encoding='utf-8', errors='ignore')
|
||||||
|
# Some legacy versions incorrectly store cleaned_preview_path as document.md.
|
||||||
|
if preview != primary and 'data:image/' not in preview_content:
|
||||||
|
return (preview, 'preview')
|
||||||
|
|
||||||
|
source = primary if primary_exists else preview if preview_exists else None
|
||||||
|
if not source:
|
||||||
|
return (None, 'markdown')
|
||||||
|
|
||||||
|
content = source.read_text(encoding='utf-8', errors='ignore')
|
||||||
|
if 'data:image/' not in content:
|
||||||
|
if source == preview:
|
||||||
|
return (preview, 'preview')
|
||||||
|
if not version.cleaned_preview_path:
|
||||||
|
version.cleaned_preview_path = str(primary)
|
||||||
|
db.session.commit()
|
||||||
|
return (primary, 'markdown')
|
||||||
|
|
||||||
|
from edkb_system.skills.export import _LocalPreviewImageRewriter
|
||||||
|
|
||||||
|
preview = primary.parent / 'document_preview.md'
|
||||||
|
images_dir = primary.parent / 'images_view'
|
||||||
|
if images_dir.exists():
|
||||||
|
shutil.rmtree(images_dir, ignore_errors=True)
|
||||||
|
rewriter = _LocalPreviewImageRewriter(images_dir=images_dir)
|
||||||
|
preview.write_text(rewriter.replace_text(content), encoding='utf-8')
|
||||||
|
version.cleaned_preview_path = str(preview)
|
||||||
|
db.session.commit()
|
||||||
|
return (preview, 'preview')
|
||||||
|
|
||||||
|
def _resolve_markdown_read_path(version: KbDocumentVersion) -> tuple[Path | None, str]:
|
||||||
|
return _ensure_preview_markdown(version)
|
||||||
|
|
||||||
def _resolve_markdown_write_path(version: KbDocumentVersion) -> Path | None:
|
def _resolve_markdown_write_path(version: KbDocumentVersion) -> Path | None:
|
||||||
primary = _resolve_storage_path(version.cleaned_file_path)
|
primary = _resolve_storage_path(version.cleaned_file_path)
|
||||||
@@ -120,6 +152,20 @@ def _resolve_markdown_write_path(version: KbDocumentVersion) -> Path | None:
|
|||||||
def _serialize_markdown_payload(document: KbDocument, version: KbDocumentVersion, content: str, kind: str):
|
def _serialize_markdown_payload(document: KbDocument, version: KbDocumentVersion, content: str, kind: str):
|
||||||
return {'document_id': document.id, 'title': document.title, 'version': _serialize_version(version), 'content': content, 'kind': kind}
|
return {'document_id': document.id, 'title': document.title, 'version': _serialize_version(version), 'content': content, 'kind': kind}
|
||||||
|
|
||||||
|
|
||||||
|
def _markdown_unavailable_message(version: KbDocumentVersion) -> str:
|
||||||
|
status = str(getattr(version, 'status', '') or '').strip().lower()
|
||||||
|
error_message = str(getattr(version, 'error_message', '') or '').strip()
|
||||||
|
if status == 'failed':
|
||||||
|
if error_message:
|
||||||
|
return f'当前文档清洗失败,尚未生成 Markdown。失败原因:{error_message}'
|
||||||
|
return '当前文档清洗失败,尚未生成 Markdown,请重新清洗后重试'
|
||||||
|
if status == 'processing':
|
||||||
|
return '当前文档正在清洗中,暂未生成 Markdown,请稍后再试'
|
||||||
|
if status == 'uploaded':
|
||||||
|
return '当前文档待清洗,暂未生成 Markdown,请先发起清洗'
|
||||||
|
return '当前文档尚未生成可编辑 Markdown'
|
||||||
|
|
||||||
@knowledge_base_bp.route('/dify/settings', methods=['GET'])
|
@knowledge_base_bp.route('/dify/settings', methods=['GET'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def get_dify_settings():
|
def get_dify_settings():
|
||||||
@@ -752,7 +798,7 @@ def get_document_markdown(document_id: int):
|
|||||||
raise NotFoundError('当前文档暂无版本记录')
|
raise NotFoundError('当前文档暂无版本记录')
|
||||||
markdown_path, kind = _resolve_markdown_read_path(version)
|
markdown_path, kind = _resolve_markdown_read_path(version)
|
||||||
if not markdown_path:
|
if not markdown_path:
|
||||||
raise ConflictError('当前文档尚未生成可编辑 Markdown')
|
raise ConflictError(_markdown_unavailable_message(version))
|
||||||
content = markdown_path.read_text(encoding='utf-8', errors='ignore')
|
content = markdown_path.read_text(encoding='utf-8', errors='ignore')
|
||||||
return jsonify(_serialize_markdown_payload(document, version, content, kind))
|
return jsonify(_serialize_markdown_payload(document, version, content, kind))
|
||||||
|
|
||||||
@@ -771,7 +817,7 @@ def update_document_markdown(document_id: int):
|
|||||||
raise ValidationError('content is required')
|
raise ValidationError('content is required')
|
||||||
markdown_path = _resolve_markdown_write_path(version)
|
markdown_path = _resolve_markdown_write_path(version)
|
||||||
if not markdown_path:
|
if not markdown_path:
|
||||||
raise ConflictError('当前文档尚未生成可编辑 Markdown')
|
raise ConflictError(_markdown_unavailable_message(version))
|
||||||
markdown_path.parent.mkdir(parents=True, exist_ok=True)
|
markdown_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
markdown_path.write_text(content, encoding='utf-8')
|
markdown_path.write_text(content, encoding='utf-8')
|
||||||
version.cleaned_file_path = str(markdown_path)
|
version.cleaned_file_path = str(markdown_path)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ backend/app/services/knowledge_cleaning/edkb_adapter.py
|
|||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
import tempfile
|
import tempfile
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -12,6 +13,27 @@ from pathlib import Path
|
|||||||
TEXT_EXTS = {'.txt', '.md'}
|
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:
|
def _find_generated_markdown(output_root: Path) -> Path:
|
||||||
# Look for md files directly inside output_root or inside any of its subdirectories
|
# 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
|
# 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]
|
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:
|
def _write_text_result(source_path: Path, target_dir: Path) -> dict:
|
||||||
target_dir.mkdir(parents=True, exist_ok=True)
|
target_dir.mkdir(parents=True, exist_ok=True)
|
||||||
cleaned_path = target_dir / 'document.md'
|
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)
|
shutil.copy2(source_path, tmp_source_path)
|
||||||
|
|
||||||
config = SystemConfig.load(None)
|
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']
|
failures = [item for item in result if item.get('status') == 'failed']
|
||||||
if failures:
|
if failures:
|
||||||
raise RuntimeError(failures[0].get('error') or 'edkb_system failed.')
|
raise RuntimeError(failures[0].get('error') or 'edkb_system failed.')
|
||||||
|
|
||||||
markdown_source = _find_generated_markdown(output_dir)
|
markdown_source = _find_generated_markdown(output_dir)
|
||||||
|
preview_source = _find_generated_preview_markdown(output_dir)
|
||||||
cleaned_path = target_dir / 'document.md'
|
cleaned_path = target_dir / 'document.md'
|
||||||
shutil.copy2(markdown_source, cleaned_path)
|
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')
|
content = cleaned_path.read_text(encoding='utf-8', errors='ignore')
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'mode': 'edkb_system',
|
'mode': 'edkb_system',
|
||||||
'cleaned_file_path': str(cleaned_path),
|
'cleaned_file_path': str(cleaned_path),
|
||||||
'cleaned_preview_path': str(cleaned_path),
|
'cleaned_preview_path': str(preview_path),
|
||||||
'word_count': len(content.split()),
|
'word_count': len(content.split()),
|
||||||
}
|
}
|
||||||
@@ -18,6 +18,32 @@ from app import db
|
|||||||
from app.models import KbDocumentVersion, KbJob
|
from app.models import KbDocumentVersion, KbJob
|
||||||
|
|
||||||
logger = logging.getLogger('kb-worker')
|
logger = logging.getLogger('kb-worker')
|
||||||
|
_WORD_EXTENSIONS = {'doc', 'docx'}
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_source_ext(value: str | None) -> str:
|
||||||
|
return str(value or '').strip().lower().lstrip('.')
|
||||||
|
|
||||||
|
|
||||||
|
def _is_word_clean_job(job: KbJob | None) -> bool:
|
||||||
|
if not job or job.job_type != 'clean' or not job.document_version:
|
||||||
|
return False
|
||||||
|
return _normalize_source_ext(job.document_version.source_file_ext) in _WORD_EXTENSIONS
|
||||||
|
|
||||||
|
|
||||||
|
def _has_running_word_clean_job() -> bool:
|
||||||
|
running_jobs = (
|
||||||
|
db.session.query(KbJob)
|
||||||
|
.join(KbDocumentVersion, KbDocumentVersion.id == KbJob.document_version_id)
|
||||||
|
.filter(
|
||||||
|
KbJob.job_type == 'clean',
|
||||||
|
KbJob.status == 'running',
|
||||||
|
KbDocumentVersion.source_file_ext.isnot(None),
|
||||||
|
)
|
||||||
|
.order_by(KbJob.started_at.asc(), KbJob.id.asc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
return any(_is_word_clean_job(job) for job in running_jobs)
|
||||||
|
|
||||||
|
|
||||||
def recover_stale_running_jobs() -> tuple[int, str]:
|
def recover_stale_running_jobs() -> tuple[int, str]:
|
||||||
@@ -117,18 +143,28 @@ def claim_next_kb_job() -> KbJob | None:
|
|||||||
"""
|
"""
|
||||||
now = datetime.utcnow()
|
now = datetime.utcnow()
|
||||||
try:
|
try:
|
||||||
job = (
|
has_running_word_job = _has_running_word_clean_job()
|
||||||
|
candidates = (
|
||||||
db.session.query(KbJob)
|
db.session.query(KbJob)
|
||||||
.filter(KbJob.job_type.in_(('path_upload', 'clean', 'sync_dify')), KbJob.status == 'queued')
|
.filter(KbJob.job_type.in_(('path_upload', 'clean', 'sync_dify')), KbJob.status == 'queued')
|
||||||
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
|
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
|
||||||
.with_for_update(skip_locked=True)
|
.with_for_update(skip_locked=True)
|
||||||
.first()
|
.limit(20)
|
||||||
|
.all()
|
||||||
)
|
)
|
||||||
except OperationalError:
|
except OperationalError:
|
||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
logger.exception('failed to claim next kb job')
|
logger.exception('failed to claim next kb job')
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
job = next(
|
||||||
|
(
|
||||||
|
item for item in candidates
|
||||||
|
if not (has_running_word_job and _is_word_clean_job(item))
|
||||||
|
),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
|
||||||
if not job:
|
if not job:
|
||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
return None
|
return None
|
||||||
@@ -137,7 +173,7 @@ def claim_next_kb_job() -> KbJob | None:
|
|||||||
job.started_at = job.started_at or now
|
job.started_at = job.started_at or now
|
||||||
job.progress = max(int(job.progress or 0), 1)
|
job.progress = max(int(job.progress or 0), 1)
|
||||||
if job.job_type == 'clean':
|
if job.job_type == 'clean':
|
||||||
job.message = 'worker 已领取清洗任务'
|
job.message = 'worker 已领取 Word 串行清洗任务' if _is_word_clean_job(job) else 'worker 已领取清洗任务'
|
||||||
elif job.job_type == 'sync_dify':
|
elif job.job_type == 'sync_dify':
|
||||||
job.message = 'worker 已领取同步任务'
|
job.message = 'worker 已领取同步任务'
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -212,12 +212,33 @@ def _derive_output_rel_md(file_path: Path, input_path: Path) -> Path:
|
|||||||
return rel.with_suffix(".md")
|
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:
|
def _normalize_path_for_match(p: Path | str) -> str:
|
||||||
return str(p).replace("\\", "/")
|
return str(p).replace("\\", "/")
|
||||||
|
|
||||||
|
|
||||||
def _file_timeout_sec() -> int | None:
|
_WORD_TIMEOUT_EXTS = {".doc", ".docx"}
|
||||||
raw = str(os.environ.get("EDKB_FILE_TIMEOUT_SEC", "0")).strip()
|
|
||||||
|
|
||||||
|
def _parse_timeout_env(name: str, default: str = "0") -> int | None:
|
||||||
|
raw = str(os.environ.get(name, default)).strip()
|
||||||
try:
|
try:
|
||||||
value = int(raw)
|
value = int(raw)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
@@ -225,6 +246,15 @@ def _file_timeout_sec() -> int | None:
|
|||||||
return value if value > 0 else 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]:
|
def _cleanup_input_temp_files(input_path: Path) -> list[Path]:
|
||||||
if input_path.is_file():
|
if input_path.is_file():
|
||||||
candidates = [input_path]
|
candidates = [input_path]
|
||||||
@@ -246,6 +276,28 @@ def _cleanup_input_temp_files(input_path: Path) -> list[Path]:
|
|||||||
return removed
|
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:
|
def _matches_pattern(candidates: list[str], patterns: list[str]) -> str | None:
|
||||||
if not patterns:
|
if not patterns:
|
||||||
return None
|
return None
|
||||||
@@ -311,7 +363,7 @@ def _run_one_with_timeout(
|
|||||||
final_md_path: Path | None = None,
|
final_md_path: Path | None = None,
|
||||||
progress_label: str | None = None,
|
progress_label: str | None = None,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
timeout = _file_timeout_sec()
|
timeout = _file_timeout_sec(file_path)
|
||||||
if not timeout:
|
if not timeout:
|
||||||
return _run_one(
|
return _run_one(
|
||||||
file_path,
|
file_path,
|
||||||
@@ -536,18 +588,14 @@ def _run_one(
|
|||||||
|
|
||||||
if blocks:
|
if blocks:
|
||||||
ctx.images = sum(1 for b in blocks if b.type == "image")
|
ctx.images = sum(1 for b in blocks if b.type == "image")
|
||||||
should_ocr = cfg.ocr.enable and (
|
should_ocr = _should_run_ocr(profile, cfg, blocks, ctx)
|
||||||
"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
|
|
||||||
if should_ocr:
|
if should_ocr:
|
||||||
_announce("ocr")
|
_announce("ocr")
|
||||||
t0 = time.perf_counter()
|
t0 = time.perf_counter()
|
||||||
blocks = ocr.run(blocks, ctx, min_confidence=cfg.ocr.min_confidence)
|
blocks = ocr.run(blocks, ctx, min_confidence=cfg.ocr.min_confidence)
|
||||||
_mark("edkb-ocr", t0)
|
_mark("edkb-ocr", t0)
|
||||||
trace_steps.append("edkb-ocr")
|
trace_steps.append("edkb-ocr")
|
||||||
|
blocks = _strip_in_memory_images(blocks)
|
||||||
|
|
||||||
doc_kind = (ctx.extras.get("intake") or {}).get("doc_kind")
|
doc_kind = (ctx.extras.get("intake") or {}).get("doc_kind")
|
||||||
policy_text = doc_kind == "policy_text"
|
policy_text = doc_kind == "policy_text"
|
||||||
|
|||||||
@@ -206,7 +206,17 @@ def blocks_to_plain_markdown(blocks: list[Block]) -> str:
|
|||||||
lines.append(f"## {txt}")
|
lines.append(f"## {txt}")
|
||||||
elif b.type == "image":
|
elif b.type == "image":
|
||||||
data_uri = b.meta.get("data_uri") if b.meta else None
|
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
|
image_idx += 1
|
||||||
if b.meta and b.meta.get("page_image"):
|
if b.meta and b.meta.get("page_image"):
|
||||||
lines.append(f"")
|
lines.append(f"")
|
||||||
@@ -220,11 +230,7 @@ def blocks_to_plain_markdown(blocks: list[Block]) -> str:
|
|||||||
page_body_chars.get(b.page, 0) >= 15
|
page_body_chars.get(b.page, 0) >= 15
|
||||||
or page_text_chars.get(b.page, 0) >= 40
|
or page_text_chars.get(b.page, 0) >= 40
|
||||||
)
|
)
|
||||||
if (
|
if b.meta and b.meta.get("page_image"):
|
||||||
b.meta
|
|
||||||
and b.meta.get("page_image")
|
|
||||||
and b.meta.get("page_image_source") != "pptx"
|
|
||||||
):
|
|
||||||
lines.extend(_page_image_structured_lines(ocr_text))
|
lines.extend(_page_image_structured_lines(ocr_text))
|
||||||
if not suppress_pptx_ocr:
|
if not suppress_pptx_ocr:
|
||||||
lines.append(f"图中文字:{ocr_text}")
|
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:
|
def run(input_data: dict, context: Context) -> dict:
|
||||||
out_dir = Path(input_data["out_dir"])
|
out_dir = Path(input_data["out_dir"])
|
||||||
out_dir.mkdir(parents=True, exist_ok=True)
|
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]
|
exported_chunks = [replace(c, text=rewriter.replace_text(c.text)) for c in chunks]
|
||||||
rewriter.finalize()
|
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(out_dir / "03_clean.md", clean_md)
|
||||||
_write(flat_clean_path, 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]
|
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 ""))
|
_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.soffice_util import convert_with_soffice, soffice_candidates
|
||||||
from edkb_system.skills.word_bridge import convert_with_word
|
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:
|
def _to_data_uri(blob: bytes, content_type: str | None = None) -> str:
|
||||||
ct = content_type or "image/png"
|
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:
|
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:
|
try:
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
with Image.open(io.BytesIO(blob)) as im:
|
with Image.open(io.BytesIO(blob)) as im:
|
||||||
rgb = Image.new("RGB", im.size, (255, 255, 255))
|
if im.mode in {"RGB", "L"} and ct in {"image/png", "image/bmp"}:
|
||||||
rgba = im.convert("RGBA")
|
uri = _to_data_uri(blob, ct)
|
||||||
rgb.paste(rgba, mask=rgba.split()[3])
|
else:
|
||||||
out = io.BytesIO()
|
rgb = Image.new("RGB", im.size, (255, 255, 255))
|
||||||
rgb.save(out, format="JPEG", quality=90)
|
rgba = im.convert("RGBA")
|
||||||
return _to_data_uri(out.getvalue(), "image/jpeg")
|
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:
|
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]:
|
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]
|
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] = []
|
uris: list[str] = []
|
||||||
|
seen_rids: set[str] = set()
|
||||||
try:
|
try:
|
||||||
rids = para._element.xpath(".//a:blip/@r:embed")
|
rids = para._element.xpath(".//a:blip/@r:embed")
|
||||||
except Exception:
|
except Exception:
|
||||||
return uris
|
return uris
|
||||||
for rid in rids:
|
for rid in rids:
|
||||||
|
rid = str(rid)
|
||||||
|
if rid in seen_rids:
|
||||||
|
continue
|
||||||
|
seen_rids.add(rid)
|
||||||
try:
|
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]
|
part = doc.part.related_parts[rid]
|
||||||
blob = part.blob
|
blob = part.blob
|
||||||
content_type = getattr(part, "content_type", None)
|
content_type = getattr(part, "content_type", None)
|
||||||
@@ -226,42 +285,34 @@ def _extract_image_uris_from_paragraph(para, doc) -> list[str]:
|
|||||||
return uris
|
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] = []
|
uris: list[str] = []
|
||||||
seen: set[str] = set()
|
seen: set[str] = set()
|
||||||
rel_items = list(doc.part.rels.items())
|
for uri in _build_image_uri_map(doc).values():
|
||||||
rel_items.sort(
|
if uri in seen:
|
||||||
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:
|
|
||||||
continue
|
continue
|
||||||
|
seen.add(uri)
|
||||||
|
uris.append(uri)
|
||||||
return uris
|
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] = []
|
uris: list[str] = []
|
||||||
seen: set[str] = set()
|
seen: set[str] = set()
|
||||||
try:
|
try:
|
||||||
for row in table.rows:
|
for row in table.rows:
|
||||||
for cell in row.cells:
|
for cell in row.cells:
|
||||||
for para in cell.paragraphs:
|
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:
|
if uri in seen:
|
||||||
continue
|
continue
|
||||||
seen.add(uri)
|
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]] = []
|
rows: list[list[str]] = []
|
||||||
seen_img_uri: set[str] = set()
|
seen_img_uri: set[str] = set()
|
||||||
for r in table.rows:
|
for r in table.rows:
|
||||||
@@ -1308,7 +1361,9 @@ def _table_to_markdown(table, doc) -> str:
|
|||||||
img_uris: list[str] = []
|
img_uris: list[str] = []
|
||||||
try:
|
try:
|
||||||
for para in c.paragraphs:
|
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:
|
if uri in seen_img_uri:
|
||||||
continue
|
continue
|
||||||
seen_img_uri.add(uri)
|
seen_img_uri.add(uri)
|
||||||
@@ -1664,6 +1719,7 @@ def run(input_data: dict, context: Context) -> list[Block]:
|
|||||||
|
|
||||||
parsed: list[Block] = []
|
parsed: list[Block] = []
|
||||||
doc = Document(str(docx_path))
|
doc = Document(str(docx_path))
|
||||||
|
image_uri_by_rid = _build_image_uri_map(doc)
|
||||||
num_to_abs, levels = _load_numbering_schema(docx_path)
|
num_to_abs, levels = _load_numbering_schema(docx_path)
|
||||||
list_states: dict[str, dict[int, int]] = {}
|
list_states: dict[str, dict[int, int]] = {}
|
||||||
context.pages = 1
|
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):
|
if marker and text and not text.startswith(marker):
|
||||||
text = f"{marker} {text}"
|
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:
|
if text:
|
||||||
idx += 1
|
idx += 1
|
||||||
typ = (
|
typ = (
|
||||||
@@ -1738,7 +1796,7 @@ def run(input_data: dict, context: Context) -> list[Block]:
|
|||||||
)
|
)
|
||||||
elif isinstance(child, CT_Tbl):
|
elif isinstance(child, CT_Tbl):
|
||||||
table = Table(child, doc)
|
table = Table(child, doc)
|
||||||
md = _table_to_markdown(table, doc)
|
md = _table_to_markdown(table, doc, image_uri_by_rid)
|
||||||
if md:
|
if md:
|
||||||
if _looks_like_form_metadata_table(md):
|
if _looks_like_form_metadata_table(md):
|
||||||
blocks = _form_table_to_blocks(table, idx)
|
blocks = _form_table_to_blocks(table, idx)
|
||||||
@@ -1760,7 +1818,7 @@ def run(input_data: dict, context: Context) -> list[Block]:
|
|||||||
# 表格内图片已并入表格 markdown 单元格,避免脱离原始位置。
|
# 表格内图片已并入表格 markdown 单元格,避免脱离原始位置。
|
||||||
|
|
||||||
if not any(b.type == "image" for b in parsed):
|
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
|
idx += 1
|
||||||
context.images += 1
|
context.images += 1
|
||||||
parsed.append(
|
parsed.append(
|
||||||
|
|||||||
@@ -6,6 +6,9 @@ from pathlib import Path
|
|||||||
|
|
||||||
from edkb_system.contracts import Block, Context
|
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:
|
def _is_scanned(text_chars: int, pages: int) -> bool:
|
||||||
return text_chars < int(300 * max(pages, 1) / 10)
|
return text_chars < int(300 * max(pages, 1) / 10)
|
||||||
@@ -76,32 +79,58 @@ def _should_use_page_image_mode(
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def _collect_image_boxes(
|
def _analysis_candidate_pages(
|
||||||
file_path: Path, page_count: int
|
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]]]:
|
) -> dict[int, list[tuple[float, float, float, float]]]:
|
||||||
try:
|
try:
|
||||||
import pypdfium2 as pdfium
|
|
||||||
import pypdfium2.raw as pdfium_c
|
import pypdfium2.raw as pdfium_c
|
||||||
except Exception:
|
except Exception:
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
out: dict[int, list[tuple[float, float, float, float]]] = {}
|
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
|
doc = None
|
||||||
try:
|
try:
|
||||||
doc = pdfium.PdfDocument(str(file_path))
|
doc = pdfium.PdfDocument(str(file_path))
|
||||||
for page_idx in range(page_count):
|
return _collect_image_boxes_from_doc(doc, page_numbers)
|
||||||
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:
|
except Exception:
|
||||||
return {}
|
return {}
|
||||||
finally:
|
finally:
|
||||||
@@ -110,12 +139,25 @@ def _collect_image_boxes(
|
|||||||
doc.close()
|
doc.close()
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
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(
|
def _render_page_png(
|
||||||
file_path: Path, page_number: int, scale: float = 2.0
|
file_path: Path, page_number: int, scale: float = _PAGE_IMAGE_RENDER_SCALE
|
||||||
) -> bytes | None:
|
) -> object | None:
|
||||||
try:
|
try:
|
||||||
import pypdfium2 as pdfium
|
import pypdfium2 as pdfium
|
||||||
except Exception:
|
except Exception:
|
||||||
@@ -124,12 +166,7 @@ def _render_page_png(
|
|||||||
doc = None
|
doc = None
|
||||||
try:
|
try:
|
||||||
doc = pdfium.PdfDocument(str(file_path))
|
doc = pdfium.PdfDocument(str(file_path))
|
||||||
page = doc[page_number - 1]
|
return _render_page_image_from_doc(doc, page_number, scale=scale)
|
||||||
bitmap = page.render(scale=scale)
|
|
||||||
pil_image = bitmap.to_pil()
|
|
||||||
buf = io.BytesIO()
|
|
||||||
pil_image.save(buf, format="PNG")
|
|
||||||
return buf.getvalue()
|
|
||||||
except Exception:
|
except Exception:
|
||||||
return None
|
return None
|
||||||
finally:
|
finally:
|
||||||
@@ -170,7 +207,19 @@ def run(input_data: dict, context: Context) -> list[Block]:
|
|||||||
page_payloads.append({"page": page_idx, "text": text, "images": images})
|
page_payloads.append({"page": page_idx, "text": text, "images": images})
|
||||||
|
|
||||||
scan_likely = _is_scanned(text_chars, context.pages)
|
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] = []
|
page_image_mode_pages: list[int] = []
|
||||||
|
|
||||||
for payload in page_payloads:
|
for payload in page_payloads:
|
||||||
@@ -199,8 +248,12 @@ def run(input_data: dict, context: Context) -> list[Block]:
|
|||||||
)
|
)
|
||||||
|
|
||||||
if use_page_image_mode:
|
if use_page_image_mode:
|
||||||
rendered = _render_page_png(file_path, page_idx)
|
rendered = (
|
||||||
if 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(
|
blocks.append(
|
||||||
Block(
|
Block(
|
||||||
id=f"pdf-page-{page_idx}",
|
id=f"pdf-page-{page_idx}",
|
||||||
@@ -209,8 +262,9 @@ def run(input_data: dict, context: Context) -> list[Block]:
|
|||||||
text="",
|
text="",
|
||||||
bbox=(0.0, 0.0, 1000.0, 1000.0),
|
bbox=(0.0, 0.0, 1000.0, 1000.0),
|
||||||
meta={
|
meta={
|
||||||
"data_uri": _to_data_uri(rendered, "image/png"),
|
|
||||||
"page_image": True,
|
"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: "
|
"pdf page-image mode pages: "
|
||||||
+ ", ".join(str(x) for x in 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:
|
except Exception as exc:
|
||||||
context.warnings.append(f"PDF parse failed: {exc}")
|
context.warnings.append(f"PDF parse failed: {exc}")
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,9 @@ import re
|
|||||||
|
|
||||||
from edkb_system.contracts import Block, Context
|
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):
|
def _decode_data_uri_image(data_uri: str):
|
||||||
m = re.match(r"^data:image/[^;]+;base64,(.+)$", data_uri or "", re.DOTALL)
|
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
|
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(
|
def run(
|
||||||
input_data: list[Block], context: Context, min_confidence: float = 0.3
|
input_data: list[Block], context: Context, min_confidence: float = 0.3
|
||||||
) -> list[Block]:
|
) -> list[Block]:
|
||||||
blocks = input_data
|
blocks = input_data
|
||||||
try:
|
try:
|
||||||
from rapidocr_onnxruntime import RapidOCR # type: ignore
|
engine = _get_ocr_engine()
|
||||||
except Exception:
|
except Exception:
|
||||||
context.warnings.append("RapidOCR unavailable; skip OCR")
|
context.warnings.append("RapidOCR unavailable; skip OCR")
|
||||||
return blocks
|
return blocks
|
||||||
|
|
||||||
engine = RapidOCR()
|
|
||||||
out: list[Block] = []
|
out: list[Block] = []
|
||||||
for b in blocks:
|
for b in blocks:
|
||||||
out.append(b)
|
out.append(b)
|
||||||
@@ -46,6 +98,8 @@ def run(
|
|||||||
image_obj = b.meta.get("image")
|
image_obj = b.meta.get("image")
|
||||||
if image_obj is None and b.meta and b.meta.get("data_uri"):
|
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")))
|
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:
|
if image_obj is None:
|
||||||
out.append(
|
out.append(
|
||||||
Block(
|
Block(
|
||||||
@@ -59,7 +113,7 @@ def run(
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
try:
|
try:
|
||||||
result, _ = engine(image_obj)
|
result, _ = engine(image_obj, **_ocr_call_kwargs(b))
|
||||||
lines = []
|
lines = []
|
||||||
for it in result or []:
|
for it in result or []:
|
||||||
if len(it) < 3:
|
if len(it) < 3:
|
||||||
|
|||||||
@@ -86,6 +86,8 @@ const failureModalType = ref<'upload' | 'clean' | 'sync' | null>(null);
|
|||||||
const failureModalPage = ref(1);
|
const failureModalPage = ref(1);
|
||||||
const retryingFailureKey = ref('');
|
const retryingFailureKey = ref('');
|
||||||
const documentStageFilter = ref<'all' | 'upload' | 'clean' | 'sync'>('all');
|
const documentStageFilter = ref<'all' | 'upload' | 'clean' | 'sync'>('all');
|
||||||
|
const documentListPage = ref(1);
|
||||||
|
const documentListPageSize = ref(50);
|
||||||
const batchSubmitting = ref(false);
|
const batchSubmitting = ref(false);
|
||||||
const selectedDocumentIds = ref<number[]>([]);
|
const selectedDocumentIds = ref<number[]>([]);
|
||||||
const pathUploadDraftText = ref('');
|
const pathUploadDraftText = ref('');
|
||||||
@@ -176,10 +178,15 @@ type PathUploadTaskItem = {
|
|||||||
finishedAt?: string;
|
finishedAt?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type LoadListOptions = {
|
||||||
|
silent?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
const FAILURE_PAGE_SIZE = 15;
|
const FAILURE_PAGE_SIZE = 15;
|
||||||
const PATH_UPLOAD_BATCH_SIZE = 30;
|
const PATH_UPLOAD_BATCH_SIZE = 30;
|
||||||
const PATH_UPLOAD_BATCH_INTERVAL_MS = 500;
|
const PATH_UPLOAD_BATCH_INTERVAL_MS = 500;
|
||||||
const PATH_UPLOAD_CONCURRENCY = 3;
|
const PATH_UPLOAD_CONCURRENCY = 3;
|
||||||
|
const DOCUMENT_PAGE_SIZE_OPTIONS = [20, 50, 100, 200] as const;
|
||||||
const pathUploadTask = ref<{
|
const pathUploadTask = ref<{
|
||||||
running: boolean;
|
running: boolean;
|
||||||
groupId: number | null;
|
groupId: number | null;
|
||||||
@@ -397,6 +404,24 @@ const filteredDocuments = computed(() =>
|
|||||||
documents.value.filter((doc) => matchesDocumentStageFilter(doc, documentStageFilter.value))
|
documents.value.filter((doc) => matchesDocumentStageFilter(doc, documentStageFilter.value))
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const filteredDocumentTotalPages = computed(() =>
|
||||||
|
Math.max(1, Math.ceil(filteredDocuments.value.length / documentListPageSize.value))
|
||||||
|
);
|
||||||
|
|
||||||
|
const pagedFilteredDocuments = computed(() => {
|
||||||
|
const start = (documentListPage.value - 1) * documentListPageSize.value;
|
||||||
|
return filteredDocuments.value.slice(start, start + documentListPageSize.value);
|
||||||
|
});
|
||||||
|
|
||||||
|
const pagedDocumentRange = computed(() => {
|
||||||
|
if (filteredDocuments.value.length === 0) {
|
||||||
|
return { start: 0, end: 0 };
|
||||||
|
}
|
||||||
|
const start = (documentListPage.value - 1) * documentListPageSize.value + 1;
|
||||||
|
const end = Math.min(filteredDocuments.value.length, documentListPage.value * documentListPageSize.value);
|
||||||
|
return { start, end };
|
||||||
|
});
|
||||||
|
|
||||||
const selectedDocuments = computed(() =>
|
const selectedDocuments = computed(() =>
|
||||||
documents.value.filter((doc) => selectedDocumentIds.value.includes(doc.id))
|
documents.value.filter((doc) => selectedDocumentIds.value.includes(doc.id))
|
||||||
);
|
);
|
||||||
@@ -657,8 +682,32 @@ const selectedPathRoots = computed(() => {
|
|||||||
return Array.from(roots);
|
return Array.from(roots);
|
||||||
});
|
});
|
||||||
|
|
||||||
const loadGroups = async () => {
|
const mergeStableItems = <T extends { id: number | string }>(current: T[], incoming: T[]) => {
|
||||||
isLoading.value = true;
|
const incomingMap = new Map(incoming.map((item) => [String(item.id), item] as const));
|
||||||
|
const next: T[] = [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
|
||||||
|
current.forEach((item) => {
|
||||||
|
const key = String(item.id);
|
||||||
|
const incomingItem = incomingMap.get(key);
|
||||||
|
if (!incomingItem) return;
|
||||||
|
next.push(incomingItem);
|
||||||
|
seen.add(key);
|
||||||
|
});
|
||||||
|
|
||||||
|
incoming.forEach((item) => {
|
||||||
|
const key = String(item.id);
|
||||||
|
if (seen.has(key)) return;
|
||||||
|
next.push(item);
|
||||||
|
});
|
||||||
|
|
||||||
|
return next;
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadGroups = async (options: LoadListOptions = {}) => {
|
||||||
|
if (!options.silent) {
|
||||||
|
isLoading.value = true;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const result = await getKbGroupsSafe();
|
const result = await getKbGroupsSafe();
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
@@ -666,17 +715,20 @@ const loadGroups = async () => {
|
|||||||
feedbackType.value = 'error';
|
feedbackType.value = 'error';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
groups.value = result.data;
|
groups.value = options.silent ? mergeStableItems(groups.value, result.data) : result.data;
|
||||||
const firstGroup = groups.value[0];
|
const firstGroup = groups.value[0];
|
||||||
if (!selectedGroupId.value && firstGroup && viewMode.value === 'group_detail') {
|
if (!selectedGroupId.value && firstGroup && viewMode.value === 'group_detail') {
|
||||||
selectedGroupId.value = firstGroup.id;
|
selectedGroupId.value = firstGroup.id;
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
isLoading.value = false;
|
if (!options.silent) {
|
||||||
|
isLoading.value = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadJobs = async () => {
|
const loadJobs = async () => {
|
||||||
|
const hadActiveKbJobs = kbJobPollingActive.value;
|
||||||
const result = await getKbJobsSafe();
|
const result = await getKbJobsSafe();
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
feedback.value = result.error || '加载任务列表失败';
|
feedback.value = result.error || '加载任务列表失败';
|
||||||
@@ -695,9 +747,23 @@ const loadJobs = async () => {
|
|||||||
startPathUploadPolling();
|
startPathUploadPolling();
|
||||||
} else {
|
} else {
|
||||||
stopPathUploadPollTimer();
|
stopPathUploadPollTimer();
|
||||||
|
if (hadActiveKbJobs && viewMode.value === 'group_detail') {
|
||||||
|
await Promise.all([
|
||||||
|
loadDocuments(selectedGroupId.value, { silent: true }),
|
||||||
|
loadGroups({ silent: true }),
|
||||||
|
]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const refreshWorkflowStatusOnly = async () => {
|
||||||
|
await Promise.all([
|
||||||
|
loadJobs(),
|
||||||
|
loadGroups({ silent: true }),
|
||||||
|
loadDocuments(selectedGroupId.value, { silent: true }),
|
||||||
|
]);
|
||||||
|
};
|
||||||
|
|
||||||
const refreshCurrentView = async () => {
|
const refreshCurrentView = async () => {
|
||||||
if (viewMode.value === 'group_overview') {
|
if (viewMode.value === 'group_overview') {
|
||||||
await Promise.all([loadGroups(), loadJobs()]);
|
await Promise.all([loadGroups(), loadJobs()]);
|
||||||
@@ -809,6 +875,33 @@ const getWorkflowBadges = (doc: KbDocumentItem) => {
|
|||||||
];
|
];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getMarkdownUnavailableMessage = (
|
||||||
|
doc: KbDocumentItem,
|
||||||
|
fallback?: string | null,
|
||||||
|
) => {
|
||||||
|
const latestStatus = String(doc.latest_version?.status || '').toLowerCase();
|
||||||
|
const normalizedReason = normalizeWorkflowErrorMessage(
|
||||||
|
doc.latest_version?.error_message,
|
||||||
|
'clean',
|
||||||
|
);
|
||||||
|
|
||||||
|
if (latestStatus === 'failed') {
|
||||||
|
return normalizedReason
|
||||||
|
? `当前文档清洗失败,尚未生成 Markdown。失败原因:${normalizedReason}`
|
||||||
|
: '当前文档清洗失败,尚未生成 Markdown,请重新清洗后重试';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (latestStatus === 'processing') {
|
||||||
|
return '当前文档正在清洗中,暂未生成 Markdown,请稍后再试';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (latestStatus === 'uploaded') {
|
||||||
|
return '当前文档待清洗,暂未生成 Markdown,请先发起清洗';
|
||||||
|
}
|
||||||
|
|
||||||
|
return fallback || '当前文档尚未生成 Markdown';
|
||||||
|
};
|
||||||
|
|
||||||
const resetGroupForm = () => {
|
const resetGroupForm = () => {
|
||||||
editingGroupId.value = null;
|
editingGroupId.value = null;
|
||||||
groupForm.value = {
|
groupForm.value = {
|
||||||
@@ -905,8 +998,10 @@ const handleDeleteGroup = async (group: KbGroup) => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadDocuments = async (groupId: number | null) => {
|
const loadDocuments = async (groupId: number | null, options: LoadListOptions = {}) => {
|
||||||
isDocumentsLoading.value = true;
|
if (!options.silent) {
|
||||||
|
isDocumentsLoading.value = true;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
if (!groupId) {
|
if (!groupId) {
|
||||||
documents.value = [];
|
documents.value = [];
|
||||||
@@ -921,7 +1016,10 @@ const loadDocuments = async (groupId: number | null) => {
|
|||||||
feedbackType.value = 'error';
|
feedbackType.value = 'error';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
documents.value = result.data;
|
const nextDocuments = options.silent
|
||||||
|
? mergeStableItems(documents.value, result.data)
|
||||||
|
: result.data;
|
||||||
|
documents.value = nextDocuments;
|
||||||
if (selectedDocumentId.value && !documents.value.some((item) => item.id === selectedDocumentId.value)) {
|
if (selectedDocumentId.value && !documents.value.some((item) => item.id === selectedDocumentId.value)) {
|
||||||
selectedDocumentId.value = null;
|
selectedDocumentId.value = null;
|
||||||
selectedDocumentVersions.value = [];
|
selectedDocumentVersions.value = [];
|
||||||
@@ -935,7 +1033,9 @@ const loadDocuments = async (groupId: number | null) => {
|
|||||||
}
|
}
|
||||||
selectedDocumentIds.value = selectedDocumentIds.value.filter((id) => documents.value.some((item) => item.id === id));
|
selectedDocumentIds.value = selectedDocumentIds.value.filter((id) => documents.value.some((item) => item.id === id));
|
||||||
} finally {
|
} finally {
|
||||||
isDocumentsLoading.value = false;
|
if (!options.silent) {
|
||||||
|
isDocumentsLoading.value = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1200,7 +1300,11 @@ const startPathUploadPolling = () => {
|
|||||||
stopPathUploadPollTimer();
|
stopPathUploadPollTimer();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
void Promise.all([loadJobs(), loadDocuments(selectedGroupId.value), loadGroups()]);
|
void Promise.all([
|
||||||
|
loadJobs(),
|
||||||
|
loadDocuments(selectedGroupId.value, { silent: true }),
|
||||||
|
loadGroups({ silent: true }),
|
||||||
|
]);
|
||||||
}, 3000);
|
}, 3000);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1307,7 +1411,7 @@ const handleConfirmPathUpload = async () => {
|
|||||||
localItem.error = undefined;
|
localItem.error = undefined;
|
||||||
updatePathUploadFeedback();
|
updatePathUploadFeedback();
|
||||||
}
|
}
|
||||||
await Promise.all([loadDocuments(selectedGroupId.value), loadJobs()]);
|
await Promise.all([loadDocuments(selectedGroupId.value, { silent: true }), loadJobs()]);
|
||||||
};
|
};
|
||||||
|
|
||||||
const files = [...pendingFiles];
|
const files = [...pendingFiles];
|
||||||
@@ -1328,7 +1432,7 @@ const handleConfirmPathUpload = async () => {
|
|||||||
feedbackType.value = 'success';
|
feedbackType.value = 'success';
|
||||||
startPathUploadPolling();
|
startPathUploadPolling();
|
||||||
resetPathUploadDraft();
|
resetPathUploadDraft();
|
||||||
await Promise.all([loadJobs(), loadDocuments(selectedGroupId.value), loadGroups()]);
|
await refreshWorkflowStatusOnly();
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDeletePathUploadItem = async (job: KbJob | null, item: PathUploadTaskItem) => {
|
const handleDeletePathUploadItem = async (job: KbJob | null, item: PathUploadTaskItem) => {
|
||||||
@@ -1345,7 +1449,7 @@ const handleDeletePathUploadItem = async (job: KbJob | null, item: PathUploadTas
|
|||||||
if (pathUploadTask.value.items.length <= 1) {
|
if (pathUploadTask.value.items.length <= 1) {
|
||||||
showPathUploadDetails.value = false;
|
showPathUploadDetails.value = false;
|
||||||
}
|
}
|
||||||
await Promise.all([loadJobs(), loadDocuments(selectedGroupId.value), loadGroups()]);
|
await refreshWorkflowStatusOnly();
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1402,7 +1506,7 @@ const handleRetryFailedPathUpload = async (
|
|||||||
startPathUploadPolling();
|
startPathUploadPolling();
|
||||||
feedback.value = relativePaths?.length === 1 ? '已重新提交该失败文件' : '已重新提交失败文件';
|
feedback.value = relativePaths?.length === 1 ? '已重新提交该失败文件' : '已重新提交失败文件';
|
||||||
feedbackType.value = 'success';
|
feedbackType.value = 'success';
|
||||||
await Promise.all([loadJobs(), loadDocuments(selectedGroupId.value), loadGroups()]);
|
await refreshWorkflowStatusOnly();
|
||||||
};
|
};
|
||||||
|
|
||||||
const toggleDocumentSelection = (documentId: number) => {
|
const toggleDocumentSelection = (documentId: number) => {
|
||||||
@@ -1471,7 +1575,7 @@ const handleBatchSync = async () => {
|
|||||||
if (successCount > 0) {
|
if (successCount > 0) {
|
||||||
startPathUploadPolling();
|
startPathUploadPolling();
|
||||||
}
|
}
|
||||||
await Promise.all([loadGroups(), loadDocuments(selectedGroupId.value), loadJobs()]);
|
await refreshWorkflowStatusOnly();
|
||||||
} finally {
|
} finally {
|
||||||
batchSubmitting.value = false;
|
batchSubmitting.value = false;
|
||||||
}
|
}
|
||||||
@@ -1507,7 +1611,7 @@ const handleBatchClean = async () => {
|
|||||||
if (successCount > 0) {
|
if (successCount > 0) {
|
||||||
startPathUploadPolling();
|
startPathUploadPolling();
|
||||||
}
|
}
|
||||||
await Promise.all([loadGroups(), loadDocuments(selectedGroupId.value), loadJobs()]);
|
await refreshWorkflowStatusOnly();
|
||||||
} finally {
|
} finally {
|
||||||
batchSubmitting.value = false;
|
batchSubmitting.value = false;
|
||||||
}
|
}
|
||||||
@@ -1584,7 +1688,7 @@ const handleRetryFailedItem = async (
|
|||||||
feedbackType.value = 'success';
|
feedbackType.value = 'success';
|
||||||
startPathUploadPolling();
|
startPathUploadPolling();
|
||||||
}
|
}
|
||||||
await Promise.all([loadGroups(), loadDocuments(selectedGroupId.value), loadJobs()]);
|
await refreshWorkflowStatusOnly();
|
||||||
if (selectedDocumentId.value) {
|
if (selectedDocumentId.value) {
|
||||||
await loadDocumentVersions(selectedDocumentId.value);
|
await loadDocumentVersions(selectedDocumentId.value);
|
||||||
}
|
}
|
||||||
@@ -1679,9 +1783,7 @@ const handleFileSelected = async (event: Event) => {
|
|||||||
input.value = '';
|
input.value = '';
|
||||||
isSubmitting.value = false;
|
isSubmitting.value = false;
|
||||||
|
|
||||||
await loadGroups();
|
await refreshWorkflowStatusOnly();
|
||||||
await loadDocuments(selectedGroupId.value);
|
|
||||||
await loadJobs();
|
|
||||||
if (selectedDocumentId.value) {
|
if (selectedDocumentId.value) {
|
||||||
await loadDocumentVersions(selectedDocumentId.value);
|
await loadDocumentVersions(selectedDocumentId.value);
|
||||||
}
|
}
|
||||||
@@ -1700,7 +1802,7 @@ const handleSyncDocument = async (documentId: number) => {
|
|||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
feedback.value = result.error ? `同步到 Dify 失败:${result.error}` : '同步到 Dify 失败';
|
feedback.value = result.error ? `同步到 Dify 失败:${result.error}` : '同步到 Dify 失败';
|
||||||
feedbackType.value = 'error';
|
feedbackType.value = 'error';
|
||||||
await loadDocuments(selectedGroupId.value);
|
await loadDocuments(selectedGroupId.value, { silent: true });
|
||||||
await loadJobs();
|
await loadJobs();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -1708,7 +1810,7 @@ const handleSyncDocument = async (documentId: number) => {
|
|||||||
feedback.value = result.job?.message || '同步任务已提交,等待后台处理';
|
feedback.value = result.job?.message || '同步任务已提交,等待后台处理';
|
||||||
feedbackType.value = 'success';
|
feedbackType.value = 'success';
|
||||||
startPathUploadPolling();
|
startPathUploadPolling();
|
||||||
await loadDocuments(selectedGroupId.value);
|
await loadDocuments(selectedGroupId.value, { silent: true });
|
||||||
await loadJobs();
|
await loadJobs();
|
||||||
selectedDocumentId.value = documentId;
|
selectedDocumentId.value = documentId;
|
||||||
await loadDocumentVersions(documentId);
|
await loadDocumentVersions(documentId);
|
||||||
@@ -1734,7 +1836,7 @@ const openMarkdownEditor = async (doc: KbDocumentItem) => {
|
|||||||
const result = await getKbDocumentMarkdown(doc.id);
|
const result = await getKbDocumentMarkdown(doc.id);
|
||||||
isMarkdownLoading.value = false;
|
isMarkdownLoading.value = false;
|
||||||
if (!result.ok || !result.data) {
|
if (!result.ok || !result.data) {
|
||||||
markdownError.value = result.error || '读取清洗后的 Markdown 失败';
|
markdownError.value = getMarkdownUnavailableMessage(doc, result.error || '读取清洗后的 Markdown 失败');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
applyMarkdownPayload(result.data);
|
applyMarkdownPayload(result.data);
|
||||||
@@ -1761,7 +1863,10 @@ const handleSaveMarkdown = async () => {
|
|||||||
isMarkdownSaving.value = false;
|
isMarkdownSaving.value = false;
|
||||||
|
|
||||||
if (!result.ok || !result.data) {
|
if (!result.ok || !result.data) {
|
||||||
markdownError.value = result.error || '保存 Markdown 失败';
|
const currentDoc = documents.value.find((item) => item.id === markdownDocumentId.value) || null;
|
||||||
|
markdownError.value = currentDoc
|
||||||
|
? getMarkdownUnavailableMessage(currentDoc, result.error || '保存 Markdown 失败')
|
||||||
|
: (result.error || '保存 Markdown 失败');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1778,6 +1883,7 @@ const handleSaveMarkdown = async () => {
|
|||||||
watch(selectedGroupId, (groupId) => {
|
watch(selectedGroupId, (groupId) => {
|
||||||
feedback.value = '';
|
feedback.value = '';
|
||||||
feedbackType.value = '';
|
feedbackType.value = '';
|
||||||
|
documentListPage.value = 1;
|
||||||
selectedDocumentId.value = null;
|
selectedDocumentId.value = null;
|
||||||
selectedDocumentIds.value = [];
|
selectedDocumentIds.value = [];
|
||||||
selectedDocumentVersions.value = [];
|
selectedDocumentVersions.value = [];
|
||||||
@@ -1786,6 +1892,20 @@ watch(selectedGroupId, (groupId) => {
|
|||||||
applyPathUploadJob(latestPathUploadJob.value);
|
applyPathUploadJob(latestPathUploadJob.value);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
watch(documentStageFilter, () => {
|
||||||
|
documentListPage.value = 1;
|
||||||
|
});
|
||||||
|
|
||||||
|
watch(documentListPageSize, () => {
|
||||||
|
documentListPage.value = 1;
|
||||||
|
});
|
||||||
|
|
||||||
|
watch(filteredDocumentTotalPages, (totalPages) => {
|
||||||
|
if (documentListPage.value > totalPages) {
|
||||||
|
documentListPage.value = totalPages;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
watch(selectedPathUploadHistoryJob, (job) => {
|
watch(selectedPathUploadHistoryJob, (job) => {
|
||||||
const validKeys = new Set(getPathUploadJobItems(job).map((item) => item.key));
|
const validKeys = new Set(getPathUploadJobItems(job).map((item) => item.key));
|
||||||
selectedPathUploadHistoryItemKeys.value = selectedPathUploadHistoryItemKeys.value.filter((key) => validKeys.has(key));
|
selectedPathUploadHistoryItemKeys.value = selectedPathUploadHistoryItemKeys.value.filter((key) => validKeys.has(key));
|
||||||
@@ -2198,7 +2318,20 @@ onUnmounted(() => {
|
|||||||
<span class="rounded-full bg-surface-soft px-2 py-0.5 text-xs ">{{ tab.count }}</span>
|
<span class="rounded-full bg-surface-soft px-2 py-0.5 text-xs ">{{ tab.count }}</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="text-sm text-muted">已选 {{ selectedDocuments.length }} 条 · 共 {{ filteredDocuments.length }} 条</div>
|
<div class="flex flex-wrap items-center gap-3 text-sm text-muted">
|
||||||
|
<label class="inline-flex items-center gap-2">
|
||||||
|
<span>每页</span>
|
||||||
|
<select
|
||||||
|
v-model.number="documentListPageSize"
|
||||||
|
class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-secondary outline-none transition-colors focus:border-brand-300"
|
||||||
|
>
|
||||||
|
<option v-for="size in DOCUMENT_PAGE_SIZE_OPTIONS" :key="size" :value="size">{{ size }}</option>
|
||||||
|
</select>
|
||||||
|
<span>条</span>
|
||||||
|
</label>
|
||||||
|
<span>已选 {{ selectedDocuments.length }} 条 · 共 {{ filteredDocuments.length }} 条</span>
|
||||||
|
<span v-if="filteredDocuments.length > 0">当前显示 {{ pagedDocumentRange.start }}-{{ pagedDocumentRange.end }} 条</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-if="!selectedGroupId" class="rounded-2xl border border-dashed border-default px-4 py-12 text-center text-sm text-muted ">
|
<div v-if="!selectedGroupId" class="rounded-2xl border border-dashed border-default px-4 py-12 text-center text-sm text-muted ">
|
||||||
@@ -2212,7 +2345,7 @@ onUnmounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
<div v-else class="space-y-3">
|
<div v-else class="space-y-3">
|
||||||
<div
|
<div
|
||||||
v-for="doc in filteredDocuments"
|
v-for="doc in pagedFilteredDocuments"
|
||||||
:key="doc.id"
|
:key="doc.id"
|
||||||
class="rounded-2xl border px-4 py-4 transition-colors"
|
class="rounded-2xl border px-4 py-4 transition-colors"
|
||||||
:class="selectedDocumentId === doc.id
|
:class="selectedDocumentId === doc.id
|
||||||
@@ -2314,6 +2447,30 @@ onUnmounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div
|
||||||
|
v-if="filteredDocuments.length > documentListPageSize"
|
||||||
|
class="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-default px-4 py-3 "
|
||||||
|
>
|
||||||
|
<div class="text-sm text-muted">
|
||||||
|
第 {{ documentListPage }} / {{ filteredDocumentTotalPages }} 页 · 共 {{ filteredDocuments.length }} 条
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
@click="documentListPage = Math.max(1, documentListPage - 1)"
|
||||||
|
:disabled="documentListPage === 1"
|
||||||
|
class="inline-flex items-center justify-center rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60 hover-surface-soft"
|
||||||
|
>
|
||||||
|
上一页
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
@click="documentListPage = Math.min(filteredDocumentTotalPages, documentListPage + 1)"
|
||||||
|
:disabled="documentListPage === filteredDocumentTotalPages"
|
||||||
|
class="inline-flex items-center justify-center rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60 hover-surface-soft"
|
||||||
|
>
|
||||||
|
下一页
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
Reference in new issue
Block a user