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

@@ -18,6 +18,32 @@ from app import db
from app.models import KbDocumentVersion, KbJob
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]:
@@ -117,18 +143,28 @@ def claim_next_kb_job() -> KbJob | None:
"""
now = datetime.utcnow()
try:
job = (
has_running_word_job = _has_running_word_clean_job()
candidates = (
db.session.query(KbJob)
.filter(KbJob.job_type.in_(('path_upload', 'clean', 'sync_dify')), KbJob.status == 'queued')
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
.with_for_update(skip_locked=True)
.first()
.limit(20)
.all()
)
except OperationalError:
db.session.rollback()
logger.exception('failed to claim next kb job')
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:
db.session.rollback()
return None
@@ -137,7 +173,7 @@ def claim_next_kb_job() -> KbJob | None:
job.started_at = job.started_at or now
job.progress = max(int(job.progress or 0), 1)
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':
job.message = 'worker 已领取同步任务'
else: