kbzhishiku
This commit is contained in:
1 parent
7f542f54a5
commit
08a19ebe96
68 files changed
+16602
-229
No files matched your search
@@ -0,0 +1,3 @@
|
||||
"""
|
||||
知识库清洗服务包
|
||||
"""
|
||||
@@ -0,0 +1,305 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/dify_sync_service.py
|
||||
文件用途:知识库文档版本到 Dify 的最小同步服务
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocumentVersion, KbGroup
|
||||
from app.services.knowledge_cleaning.settings_service import get_kb_dify_settings
|
||||
|
||||
|
||||
class KbDifySyncError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class KbDifySyncService:
|
||||
def __init__(self) -> None:
|
||||
settings = get_kb_dify_settings()
|
||||
self.base_url = str(settings.get('DIFY_API_BASE') or '').rstrip('/')
|
||||
self.api_key = str(settings.get('DIFY_API_KEY') or '').strip()
|
||||
self.permission = str(settings.get('KB_DIFY_PERMISSION') or 'only_me')
|
||||
self.indexing_technique = str(settings.get('KB_DIFY_INDEXING_TECHNIQUE') or 'high_quality')
|
||||
self.search_method = str(settings.get('KB_DIFY_SEARCH_METHOD') or 'semantic_search')
|
||||
self.doc_form = str(settings.get('KB_DIFY_DOC_FORM') or 'text_model')
|
||||
self.timeout = 60
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
if not self.base_url:
|
||||
raise KbDifySyncError('DIFY_API_BASE 未配置')
|
||||
if not self.api_key:
|
||||
raise KbDifySyncError('DIFY_API_KEY 未配置')
|
||||
return {
|
||||
'Authorization': f'Bearer {self.api_key}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
def _request(self, method: str, path: str, **kwargs):
|
||||
url = f'{self.base_url}{path}'
|
||||
try:
|
||||
response = requests.request(
|
||||
method,
|
||||
url,
|
||||
headers=self._headers(),
|
||||
timeout=self.timeout,
|
||||
**kwargs,
|
||||
)
|
||||
except requests.RequestException as exc:
|
||||
raise KbDifySyncError(f'Dify API {method} {path} 请求失败: {exc}') from exc
|
||||
if response.status_code >= 400:
|
||||
raise KbDifySyncError(
|
||||
f'Dify API {method} {path} failed: {response.status_code} {response.text}'
|
||||
)
|
||||
if response.status_code == 204:
|
||||
return None
|
||||
return response.json()
|
||||
|
||||
def list_datasets(self) -> list[dict]:
|
||||
payload = self._request('GET', '/datasets')
|
||||
return payload.get('data', []) if isinstance(payload, dict) else []
|
||||
|
||||
def create_dataset(self, *, name: str, description: str | None) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'description': description or '',
|
||||
'permission': self.permission,
|
||||
'indexing_technique': self.indexing_technique,
|
||||
'doc_form': self.doc_form,
|
||||
'retrieval_model': {
|
||||
'search_method': self.search_method,
|
||||
'reranking_enable': False,
|
||||
'top_k': 3,
|
||||
'score_threshold_enabled': False,
|
||||
'score_threshold': None,
|
||||
},
|
||||
}
|
||||
return self._request('POST', '/datasets', json=payload)
|
||||
|
||||
def ensure_dataset(self, group: KbGroup) -> tuple[str, str]:
|
||||
if group.dify_dataset_id:
|
||||
return group.dify_dataset_id, group.dify_dataset_name or group.name
|
||||
|
||||
dataset_name = group.dify_dataset_name or group.name
|
||||
existing = next((item for item in self.list_datasets() if item.get('name') == dataset_name), None)
|
||||
if existing:
|
||||
group.dify_dataset_id = existing.get('id')
|
||||
group.dify_dataset_name = existing.get('name') or dataset_name
|
||||
db.session.commit()
|
||||
return group.dify_dataset_id, group.dify_dataset_name
|
||||
|
||||
created = self.create_dataset(name=dataset_name, description=group.description)
|
||||
group.dify_dataset_id = created.get('id')
|
||||
group.dify_dataset_name = created.get('name') or dataset_name
|
||||
db.session.commit()
|
||||
return group.dify_dataset_id, group.dify_dataset_name
|
||||
|
||||
def create_document_by_text(self, *, dataset_id: str, name: str, text: str) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'text': text,
|
||||
'indexing_technique': self.indexing_technique,
|
||||
'doc_form': self.doc_form,
|
||||
'process_rule': {'mode': 'automatic'},
|
||||
}
|
||||
return self._request('POST', f'/datasets/{dataset_id}/document/create-by-text', json=payload)
|
||||
|
||||
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'text': text,
|
||||
'process_rule': {'mode': 'automatic'},
|
||||
}
|
||||
return self._request(
|
||||
'POST',
|
||||
f'/datasets/{dataset_id}/documents/{document_id}/update-by-text',
|
||||
json=payload,
|
||||
)
|
||||
|
||||
def get_document(self, *, dataset_id: str, document_id: str) -> dict:
|
||||
return self._request('GET', f'/datasets/{dataset_id}/documents/{document_id}')
|
||||
|
||||
def delete_document(self, *, dataset_id: str, document_id: str) -> None:
|
||||
self._request(
|
||||
'DELETE',
|
||||
f'/datasets/{dataset_id}/documents/{document_id}',
|
||||
)
|
||||
|
||||
|
||||
def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]:
|
||||
candidate_paths = [version.cleaned_file_path, version.cleaned_preview_path, version.source_file_path]
|
||||
for value in candidate_paths:
|
||||
if not value:
|
||||
continue
|
||||
path = Path(value)
|
||||
if not path.exists():
|
||||
continue
|
||||
text = path.read_text(encoding='utf-8', errors='ignore').strip()
|
||||
if text:
|
||||
return text, str(path)
|
||||
raise KbDifySyncError('没有可用于同步的文本结果')
|
||||
|
||||
|
||||
def _is_remote_document_missing(error_text: str) -> bool:
|
||||
return (
|
||||
'404' in error_text
|
||||
and ('Document not found' in error_text or '"code":"not_found"' in error_text)
|
||||
)
|
||||
|
||||
|
||||
def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | None = None) -> dict:
|
||||
version = db.session.get(KbDocumentVersion, document_version_id)
|
||||
if not version or not version.document or not version.document.group:
|
||||
raise KbDifySyncError('文档版本或关联分组不存在')
|
||||
|
||||
group = version.document.group
|
||||
document = version.document
|
||||
text, source_path = _load_sync_text(version)
|
||||
sync_hash = hashlib.sha256(text.encode('utf-8')).hexdigest()
|
||||
|
||||
service = KbDifySyncService()
|
||||
dataset_id, dataset_name = service.ensure_dataset(group)
|
||||
|
||||
existing_record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.filter(
|
||||
KbDifySyncRecord.document_id == document.id,
|
||||
KbDifySyncRecord.remote_document_id.isnot(None),
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
remote_document_id = None
|
||||
remote_document_name = None
|
||||
if existing_record and existing_record.dataset_id == dataset_id and existing_record.sync_hash == sync_hash:
|
||||
try:
|
||||
payload = service.get_document(
|
||||
dataset_id=dataset_id,
|
||||
document_id=existing_record.remote_document_id,
|
||||
)
|
||||
remote_document_id = payload.get('id') or existing_record.remote_document_id
|
||||
remote_document_name = payload.get('name') or existing_record.remote_document_name or document.title
|
||||
except KbDifySyncError as exc:
|
||||
if not _is_remote_document_missing(str(exc)):
|
||||
raise
|
||||
payload = service.create_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
|
||||
remote_document_name = payload.get('document', {}).get('name') or document.title
|
||||
elif existing_record and existing_record.dataset_id == dataset_id:
|
||||
try:
|
||||
payload = service.update_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
document_id=existing_record.remote_document_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
except KbDifySyncError as exc:
|
||||
if not _is_remote_document_missing(str(exc)):
|
||||
raise
|
||||
payload = service.create_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id
|
||||
remote_document_name = payload.get('document', {}).get('name') or document.title
|
||||
else:
|
||||
payload = service.create_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
|
||||
remote_document_name = payload.get('document', {}).get('name') or document.title
|
||||
|
||||
if not remote_document_id:
|
||||
raise KbDifySyncError('Dify 未返回远端文档 ID')
|
||||
|
||||
record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.filter(
|
||||
KbDifySyncRecord.document_version_id == version.id,
|
||||
KbDifySyncRecord.remote_document_id == remote_document_id,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not record:
|
||||
record = KbDifySyncRecord(
|
||||
group_id=group.id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
dataset_id=dataset_id,
|
||||
dataset_name=dataset_name,
|
||||
remote_document_id=remote_document_id,
|
||||
remote_document_name=remote_document_name,
|
||||
status='synced',
|
||||
sync_hash=sync_hash,
|
||||
synced_by_id=synced_by_id,
|
||||
)
|
||||
db.session.add(record)
|
||||
else:
|
||||
record.dataset_id = dataset_id
|
||||
record.dataset_name = dataset_name
|
||||
record.remote_document_name = remote_document_name
|
||||
record.status = 'synced'
|
||||
record.sync_hash = sync_hash
|
||||
record.error_message = None
|
||||
record.synced_by_id = synced_by_id
|
||||
|
||||
record.synced_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return {
|
||||
'dataset_id': dataset_id,
|
||||
'dataset_name': dataset_name,
|
||||
'remote_document_id': remote_document_id,
|
||||
'remote_document_name': remote_document_name,
|
||||
'sync_hash': sync_hash,
|
||||
'source_path': source_path,
|
||||
}
|
||||
|
||||
|
||||
def delete_document_from_dify(document_id: int) -> dict:
|
||||
records = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.filter(
|
||||
KbDifySyncRecord.document_id == document_id,
|
||||
KbDifySyncRecord.remote_document_id.isnot(None),
|
||||
KbDifySyncRecord.dataset_id.isnot(None),
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.all()
|
||||
)
|
||||
if not records:
|
||||
return {'deleted': True, 'remote_document_count': 0}
|
||||
|
||||
service = KbDifySyncService()
|
||||
deleted_count = 0
|
||||
visited: set[tuple[str, str]] = set()
|
||||
|
||||
for record in records:
|
||||
key = (str(record.dataset_id), str(record.remote_document_id))
|
||||
if key in visited:
|
||||
continue
|
||||
visited.add(key)
|
||||
try:
|
||||
service.delete_document(dataset_id=key[0], document_id=key[1])
|
||||
except KbDifySyncError as exc:
|
||||
if not _is_remote_document_missing(str(exc)):
|
||||
raise
|
||||
record.status = 'deleted'
|
||||
record.error_message = None
|
||||
record.synced_at = datetime.utcnow()
|
||||
deleted_count += 1
|
||||
|
||||
db.session.commit()
|
||||
return {'deleted': True, 'remote_document_count': deleted_count}
|
||||
@@ -0,0 +1,242 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/dify_sync_service.py
|
||||
文件用途:知识库文档版本到 Dify 的最小同步服务
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocumentVersion, KbGroup
|
||||
from app.services.knowledge_cleaning.settings_service import get_kb_dify_settings
|
||||
|
||||
|
||||
class KbDifySyncError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class KbDifySyncService:
|
||||
def __init__(self) -> None:
|
||||
settings = get_kb_dify_settings()
|
||||
self.base_url = str(settings.get('DIFY_API_BASE') or '').rstrip('/')
|
||||
self.api_key = str(settings.get('DIFY_API_KEY') or '').strip()
|
||||
self.permission = str(settings.get('KB_DIFY_PERMISSION') or 'only_me')
|
||||
self.indexing_technique = str(settings.get('KB_DIFY_INDEXING_TECHNIQUE') or 'high_quality')
|
||||
self.search_method = str(settings.get('KB_DIFY_SEARCH_METHOD') or 'semantic_search')
|
||||
self.doc_form = str(settings.get('KB_DIFY_DOC_FORM') or 'text_model')
|
||||
self.timeout = 60
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
if not self.base_url:
|
||||
raise KbDifySyncError('DIFY_API_BASE 未配置')
|
||||
if not self.api_key:
|
||||
raise KbDifySyncError('DIFY_API_KEY 未配置')
|
||||
return {
|
||||
'Authorization': f'Bearer {self.api_key}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
def _request(self, method: str, path: str, **kwargs):
|
||||
url = f'{self.base_url}{path}'
|
||||
try:
|
||||
response = requests.request(
|
||||
method,
|
||||
url,
|
||||
headers=self._headers(),
|
||||
timeout=self.timeout,
|
||||
**kwargs,
|
||||
)
|
||||
except requests.RequestException as exc:
|
||||
raise KbDifySyncError(f'Dify API {method} {path} 请求失败: {exc}') from exc
|
||||
if response.status_code >= 400:
|
||||
raise KbDifySyncError(
|
||||
f'Dify API {method} {path} failed: {response.status_code} {response.text}'
|
||||
)
|
||||
if response.status_code == 204:
|
||||
return None
|
||||
return response.json()
|
||||
|
||||
def list_datasets(self) -> list[dict]:
|
||||
payload = self._request('GET', '/datasets')
|
||||
return payload.get('data', []) if isinstance(payload, dict) else []
|
||||
|
||||
def create_dataset(self, *, name: str, description: str | None) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'description': description or '',
|
||||
'permission': self.permission,
|
||||
'indexing_technique': self.indexing_technique,
|
||||
'doc_form': self.doc_form,
|
||||
'retrieval_model': {
|
||||
'search_method': self.search_method,
|
||||
'reranking_enable': False,
|
||||
'top_k': 3,
|
||||
'score_threshold_enabled': False,
|
||||
'score_threshold': None,
|
||||
},
|
||||
}
|
||||
return self._request('POST', '/datasets', json=payload)
|
||||
|
||||
def ensure_dataset(self, group: KbGroup) -> tuple[str, str]:
|
||||
if group.dify_dataset_id:
|
||||
return group.dify_dataset_id, group.dify_dataset_name or group.name
|
||||
|
||||
dataset_name = group.dify_dataset_name or group.name
|
||||
existing = next((item for item in self.list_datasets() if item.get('name') == dataset_name), None)
|
||||
if existing:
|
||||
group.dify_dataset_id = existing.get('id')
|
||||
group.dify_dataset_name = existing.get('name') or dataset_name
|
||||
db.session.commit()
|
||||
return group.dify_dataset_id, group.dify_dataset_name
|
||||
|
||||
created = self.create_dataset(name=dataset_name, description=group.description)
|
||||
group.dify_dataset_id = created.get('id')
|
||||
group.dify_dataset_name = created.get('name') or dataset_name
|
||||
db.session.commit()
|
||||
return group.dify_dataset_id, group.dify_dataset_name
|
||||
|
||||
def create_document_by_text(self, *, dataset_id: str, name: str, text: str) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'text': text,
|
||||
'indexing_technique': self.indexing_technique,
|
||||
'doc_form': self.doc_form,
|
||||
'process_rule': {'mode': 'automatic'},
|
||||
}
|
||||
return self._request('POST', f'/datasets/{dataset_id}/document/create-by-text', json=payload)
|
||||
|
||||
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'text': text,
|
||||
'process_rule': {'mode': 'automatic'},
|
||||
}
|
||||
return self._request(
|
||||
'POST',
|
||||
f'/datasets/{dataset_id}/documents/{document_id}/update-by-text',
|
||||
json=payload,
|
||||
)
|
||||
|
||||
|
||||
def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]:
|
||||
candidate_paths = [version.cleaned_file_path, version.cleaned_preview_path, version.source_file_path]
|
||||
for value in candidate_paths:
|
||||
if not value:
|
||||
continue
|
||||
path = Path(value)
|
||||
if not path.exists():
|
||||
continue
|
||||
text = path.read_text(encoding='utf-8', errors='ignore').strip()
|
||||
if text:
|
||||
return text, str(path)
|
||||
raise KbDifySyncError('没有可用于同步的文本结果')
|
||||
|
||||
|
||||
def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | None = None) -> dict:
|
||||
version = db.session.get(KbDocumentVersion, document_version_id)
|
||||
if not version or not version.document or not version.document.group:
|
||||
raise KbDifySyncError('文档版本或关联分组不存在')
|
||||
|
||||
group = version.document.group
|
||||
document = version.document
|
||||
text, source_path = _load_sync_text(version)
|
||||
sync_hash = hashlib.sha256(text.encode('utf-8')).hexdigest()
|
||||
|
||||
service = KbDifySyncService()
|
||||
dataset_id, dataset_name = service.ensure_dataset(group)
|
||||
|
||||
existing_record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.filter(
|
||||
KbDifySyncRecord.document_id == document.id,
|
||||
KbDifySyncRecord.remote_document_id.isnot(None),
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
remote_document_id = None
|
||||
remote_document_name = None
|
||||
if existing_record and existing_record.sync_hash == sync_hash:
|
||||
remote_document_id = existing_record.remote_document_id
|
||||
remote_document_name = existing_record.remote_document_name
|
||||
elif existing_record and existing_record.dataset_id == dataset_id:
|
||||
try:
|
||||
payload = service.update_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
document_id=existing_record.remote_document_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
except KbDifySyncError as exc:
|
||||
error_text = str(exc)
|
||||
remote_missing = (
|
||||
'404' in error_text
|
||||
and ('Document not found' in error_text or '"code":"not_found"' in error_text)
|
||||
)
|
||||
if not remote_missing:
|
||||
raise
|
||||
payload = service.create_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id
|
||||
remote_document_name = payload.get('document', {}).get('name') or document.title
|
||||
else:
|
||||
payload = service.create_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
|
||||
remote_document_name = payload.get('document', {}).get('name') or document.title
|
||||
|
||||
if not remote_document_id:
|
||||
raise KbDifySyncError('Dify 未返回远端文档 ID')
|
||||
|
||||
record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.filter(
|
||||
KbDifySyncRecord.document_version_id == version.id,
|
||||
KbDifySyncRecord.remote_document_id == remote_document_id,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not record:
|
||||
record = KbDifySyncRecord(
|
||||
group_id=group.id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
dataset_id=dataset_id,
|
||||
dataset_name=dataset_name,
|
||||
remote_document_id=remote_document_id,
|
||||
remote_document_name=remote_document_name,
|
||||
status='synced',
|
||||
sync_hash=sync_hash,
|
||||
synced_by_id=synced_by_id,
|
||||
)
|
||||
db.session.add(record)
|
||||
else:
|
||||
record.dataset_id = dataset_id
|
||||
record.dataset_name = dataset_name
|
||||
record.remote_document_name = remote_document_name
|
||||
record.status = 'synced'
|
||||
record.sync_hash = sync_hash
|
||||
record.error_message = None
|
||||
record.synced_by_id = synced_by_id
|
||||
|
||||
record.synced_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return {
|
||||
'dataset_id': dataset_id,
|
||||
'dataset_name': dataset_name,
|
||||
'remote_document_id': remote_document_id,
|
||||
'remote_document_name': remote_document_name,
|
||||
'sync_hash': sync_hash,
|
||||
'source_path': source_path,
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/edkb_adapter.py
|
||||
文件用途:edkb_system 轻量适配层
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
TEXT_EXTS = {'.txt', '.md'}
|
||||
|
||||
|
||||
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 _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)
|
||||
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)
|
||||
cleaned_path = target_dir / 'document.md'
|
||||
shutil.copy2(markdown_source, cleaned_path)
|
||||
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),
|
||||
'word_count': len(content.split()),
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/queue_service.py
|
||||
文件用途:知识库任务调度最小实现
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import KbJob
|
||||
|
||||
|
||||
def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
|
||||
"""
|
||||
最小任务调度器:
|
||||
- sync: 上传后立即在请求内执行;
|
||||
- worker: 仅保留 queued,等待独立 worker 轮询;
|
||||
- manual: 保留 queued,等待管理台手动执行。
|
||||
"""
|
||||
mode = str(current_app.config.get('KB_TASK_EXECUTION_MODE', 'sync')).strip().lower()
|
||||
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job:
|
||||
return False, 'job_not_found'
|
||||
|
||||
if mode == 'sync':
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job
|
||||
|
||||
if job.job_type == 'clean':
|
||||
return run_clean_job(job_id)
|
||||
if job.job_type == 'path_upload':
|
||||
return run_path_upload_job(job_id)
|
||||
return False, f'unsupported_sync_job:{job.job_type}'
|
||||
|
||||
if mode == 'worker':
|
||||
return True, 'queued_for_worker'
|
||||
|
||||
return True, 'queued_manual'
|
||||
|
||||
|
||||
def enqueue_clean_job(job_id: int) -> tuple[bool, str]:
|
||||
return enqueue_kb_job(job_id)
|
||||
|
||||
|
||||
def process_next_kb_job() -> tuple[bool, str]:
|
||||
job = (
|
||||
db.session.query(KbJob)
|
||||
.filter(KbJob.job_type.in_(('path_upload', 'clean')), KbJob.status == 'queued')
|
||||
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
|
||||
.first()
|
||||
)
|
||||
if not job:
|
||||
return False, 'no_job'
|
||||
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job
|
||||
|
||||
if job.job_type == 'path_upload':
|
||||
return run_path_upload_job(job.id)
|
||||
return run_clean_job(job.id)
|
||||
|
||||
|
||||
def process_next_clean_job() -> tuple[bool, str]:
|
||||
return process_next_kb_job()
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/settings_service.py
|
||||
文件用途:知识库 Dify 设置读写服务
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.env_persistence import persist_env_settings
|
||||
from app.models import AppSetting, KbDifySyncRecord, KbGroup, KbJob, KbDocumentVersion
|
||||
|
||||
|
||||
SETTING_DEFAULTS = {
|
||||
'DIFY_API_BASE': '',
|
||||
'DIFY_API_KEY': '',
|
||||
'KB_DIFY_PERMISSION': 'only_me',
|
||||
'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality',
|
||||
'KB_DIFY_SEARCH_METHOD': 'semantic_search',
|
||||
'KB_DIFY_DOC_FORM': 'text_model',
|
||||
}
|
||||
|
||||
|
||||
def _get_setting_value(key: str) -> str:
|
||||
row = db.session.get(AppSetting, key)
|
||||
if row and row.value is not None:
|
||||
return row.value
|
||||
config_value = current_app.config.get(key)
|
||||
if config_value is not None:
|
||||
return str(config_value)
|
||||
return str(os.getenv(key, SETTING_DEFAULTS.get(key, '')))
|
||||
|
||||
|
||||
def get_kb_dify_settings() -> dict:
|
||||
payload = {key: _get_setting_value(key) for key in SETTING_DEFAULTS}
|
||||
payload['dify_api_configured'] = bool(payload.get('DIFY_API_KEY'))
|
||||
return payload
|
||||
|
||||
|
||||
def save_kb_dify_settings(values: dict[str, object]) -> dict:
|
||||
allowed = {key: values[key] for key in SETTING_DEFAULTS if key in values}
|
||||
persisted = persist_env_settings(allowed)
|
||||
return {
|
||||
**get_kb_dify_settings(),
|
||||
**persisted,
|
||||
'dify_api_configured': bool((persisted.get('DIFY_API_KEY') or _get_setting_value('DIFY_API_KEY')).strip()),
|
||||
}
|
||||
|
||||
|
||||
def get_kb_dify_health_payload() -> dict:
|
||||
settings = get_kb_dify_settings()
|
||||
base_url = settings.get('DIFY_API_BASE') or ''
|
||||
api_key = settings.get('DIFY_API_KEY') or ''
|
||||
|
||||
payload = {
|
||||
'dify_base_url': base_url,
|
||||
'dify_api_configured': bool(api_key),
|
||||
'api': {
|
||||
'configured': bool(api_key),
|
||||
'reachable': False,
|
||||
'dataset_count': None,
|
||||
'error': None,
|
||||
},
|
||||
'local_sync_health': {
|
||||
'dataset_bound_groups': db.session.query(KbGroup).filter(KbGroup.dify_dataset_id.isnot(None)).count(),
|
||||
'sync_records': db.session.query(KbDifySyncRecord).count(),
|
||||
'syncing_versions': db.session.query(KbDocumentVersion).filter(KbDocumentVersion.status == 'syncing').count(),
|
||||
'synced_versions': db.session.query(KbDocumentVersion).filter(KbDocumentVersion.status == 'synced').count(),
|
||||
'failed_sync_records': db.session.query(KbDifySyncRecord).filter(KbDifySyncRecord.status == 'failed').count(),
|
||||
'pending_sync_jobs': db.session.query(KbJob).filter(KbJob.job_type == 'sync_dify', KbJob.status == 'queued').count(),
|
||||
},
|
||||
}
|
||||
return payload
|
||||
@@ -0,0 +1,471 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/tasks.py
|
||||
文件用途:知识库任务执行第一版
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import zipfile
|
||||
|
||||
from flask import current_app
|
||||
from app import db
|
||||
from app.models import KbDocument, KbDocumentVersion, KbJob
|
||||
from app.services.knowledge_cleaning.edkb_adapter import build_clean_result
|
||||
from app.services.knowledge_cleaning.dify_sync_service import (
|
||||
KbDifySyncError,
|
||||
sync_document_version_to_dify,
|
||||
)
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
|
||||
def _utc_now() -> datetime:
|
||||
return datetime.utcnow()
|
||||
|
||||
|
||||
def _infer_missing_extension(source_path: Path) -> str:
|
||||
if zipfile.is_zipfile(source_path):
|
||||
try:
|
||||
with zipfile.ZipFile(source_path) as archive:
|
||||
names = archive.namelist()
|
||||
except Exception:
|
||||
names = []
|
||||
if any(name.startswith('xl/') for name in names):
|
||||
return '.xlsx'
|
||||
if any(name.startswith('word/') for name in names):
|
||||
return '.docx'
|
||||
if any(name.startswith('ppt/') for name in names):
|
||||
return '.pptx'
|
||||
return '.zip'
|
||||
|
||||
try:
|
||||
header = source_path.read_bytes()[:8]
|
||||
except Exception:
|
||||
return ''
|
||||
if header.startswith(b'\xd0\xcf\x11\xe0'):
|
||||
return '.xls'
|
||||
return ''
|
||||
|
||||
|
||||
def _normalized_source_filename(version: KbDocumentVersion, source_path: Path) -> str:
|
||||
raw_name = Path(version.source_file_name or source_path.name).name
|
||||
if Path(raw_name).suffix:
|
||||
return raw_name
|
||||
|
||||
ext = version.source_file_ext
|
||||
if ext:
|
||||
normalized_ext = ext if str(ext).startswith('.') else f'.{ext}'
|
||||
else:
|
||||
normalized_ext = _infer_missing_extension(source_path)
|
||||
|
||||
return f'{raw_name}{normalized_ext}' if normalized_ext else raw_name
|
||||
|
||||
|
||||
def _hash_file(source_path: Path) -> tuple[str, int]:
|
||||
sha = hashlib.sha256()
|
||||
size = 0
|
||||
with source_path.open('rb') as handle:
|
||||
while True:
|
||||
chunk = handle.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
sha.update(chunk)
|
||||
size += len(chunk)
|
||||
return sha.hexdigest(), size
|
||||
|
||||
|
||||
def _safe_storage_filename(filename: str) -> str:
|
||||
candidate = Path(filename or '').name.strip()
|
||||
if not candidate:
|
||||
return 'uploaded_file'
|
||||
safe_stem = secure_filename(Path(candidate).stem) or 'uploaded_file'
|
||||
suffix = Path(candidate).suffix.lower()
|
||||
return f'{safe_stem}{suffix}'
|
||||
|
||||
|
||||
def _kb_storage_root() -> Path:
|
||||
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
return root
|
||||
|
||||
|
||||
def _get_or_create_document(*, group_id: int, title: str, description: str | None, user_id: int | None) -> KbDocument:
|
||||
document = (
|
||||
db.session.query(KbDocument)
|
||||
.filter(KbDocument.group_id == group_id, KbDocument.title == title)
|
||||
.first()
|
||||
)
|
||||
if document and document.is_deleted:
|
||||
document.is_deleted = False
|
||||
if document:
|
||||
document.description = description
|
||||
document.updated_by_id = user_id
|
||||
return document
|
||||
|
||||
document = KbDocument(
|
||||
group_id=group_id,
|
||||
title=title,
|
||||
description=description,
|
||||
status='draft',
|
||||
source_type='upload',
|
||||
created_by_id=user_id,
|
||||
updated_by_id=user_id,
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
return document
|
||||
|
||||
|
||||
def _find_existing_active_document(*, group_id: int, title: str) -> KbDocument | None:
|
||||
return (
|
||||
db.session.query(KbDocument)
|
||||
.filter(
|
||||
KbDocument.group_id == group_id,
|
||||
KbDocument.title == title,
|
||||
KbDocument.is_deleted.is_(False),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _next_version_no(document: KbDocument) -> int:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
return 1
|
||||
return max(item.version_no for item in versions) + 1
|
||||
|
||||
|
||||
def _register_document_version_from_staged_file(
|
||||
*,
|
||||
group_id: int,
|
||||
relative_path: str,
|
||||
staged_path: Path,
|
||||
original_name: str,
|
||||
user_id: int | None,
|
||||
) -> tuple[KbDocument, KbDocumentVersion, KbJob]:
|
||||
display_name = Path(original_name or relative_path).name or Path(relative_path).name or 'uploaded_file'
|
||||
if _find_existing_active_document(group_id=group_id, title=display_name):
|
||||
raise FileExistsError('上传失败,文件已存在')
|
||||
document = _get_or_create_document(
|
||||
group_id=group_id,
|
||||
title=display_name,
|
||||
description=display_name,
|
||||
user_id=user_id,
|
||||
)
|
||||
version_no = _next_version_no(document)
|
||||
source_file_name = _safe_storage_filename(original_name)
|
||||
ext = Path(source_file_name).suffix.lower().lstrip('.') or None
|
||||
version_dir = _kb_storage_root() / f'group_{group_id:04d}' / f'document_{document.id:06d}' / f'v{version_no:03d}'
|
||||
version_dir.mkdir(parents=True, exist_ok=True)
|
||||
target_path = version_dir / source_file_name
|
||||
shutil.copy2(staged_path, target_path)
|
||||
sha256, file_size = _hash_file(target_path)
|
||||
|
||||
for existing in document.versions:
|
||||
if existing.is_current:
|
||||
existing.is_current = False
|
||||
|
||||
version = KbDocumentVersion(
|
||||
document_id=document.id,
|
||||
version_no=version_no,
|
||||
status='uploaded',
|
||||
is_current=True,
|
||||
source_file_name=source_file_name,
|
||||
source_file_path=str(target_path),
|
||||
source_file_ext=ext,
|
||||
source_file_size=file_size,
|
||||
sha256=sha256,
|
||||
uploaded_by_id=user_id,
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
|
||||
document.source_type = 'upload'
|
||||
document.status = 'uploaded'
|
||||
document.updated_by_id = user_id
|
||||
|
||||
upload_job = KbJob(
|
||||
job_type='upload',
|
||||
status='success',
|
||||
group_id=group_id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
progress=100,
|
||||
message=f'已通过上传路径导入文件:{relative_path}',
|
||||
payload_json={
|
||||
'source_file_name': source_file_name,
|
||||
'relative_path': relative_path,
|
||||
'source_file_size': file_size,
|
||||
},
|
||||
result_json={
|
||||
'sha256': sha256,
|
||||
'stored_path': str(target_path),
|
||||
},
|
||||
created_by_id=user_id,
|
||||
started_at=version.created_at,
|
||||
finished_at=version.created_at,
|
||||
)
|
||||
clean_job = KbJob(
|
||||
job_type='clean',
|
||||
status='queued',
|
||||
group_id=group_id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
progress=0,
|
||||
message='等待清洗任务执行',
|
||||
payload_json={
|
||||
'document_version_id': version.id,
|
||||
'source_file_name': source_file_name,
|
||||
'relative_path': relative_path,
|
||||
},
|
||||
created_by_id=user_id,
|
||||
)
|
||||
db.session.add(upload_job)
|
||||
db.session.add(clean_job)
|
||||
db.session.commit()
|
||||
|
||||
from app.services.knowledge_cleaning.queue_service import enqueue_clean_job
|
||||
|
||||
enqueue_clean_job(clean_job.id)
|
||||
return document, version, clean_job
|
||||
|
||||
|
||||
def run_path_upload_job(job_id: int) -> tuple[bool, str]:
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job:
|
||||
return False, '任务不存在'
|
||||
if job.job_type != 'path_upload':
|
||||
return False, '当前任务不是 path_upload 类型'
|
||||
|
||||
payload = dict(job.payload_json or {})
|
||||
items = list(payload.get('files') or [])
|
||||
total = max(int(payload.get('total_files') or len(items) or 0), 1)
|
||||
result = dict(job.result_json or {})
|
||||
result.setdefault('total', total)
|
||||
result.setdefault('success', 0)
|
||||
result.setdefault('failed', 0)
|
||||
result.setdefault('staged', len(items))
|
||||
|
||||
job.status = 'running'
|
||||
job.progress = min(job.progress or 0, 5)
|
||||
job.message = '后台开始批量导入上传路径文件'
|
||||
job.started_at = job.started_at or _utc_now()
|
||||
db.session.commit()
|
||||
|
||||
success_count = 0
|
||||
fail_count = 0
|
||||
processed = 0
|
||||
|
||||
for item in items:
|
||||
if item.get('status') in ('success', 'failed'):
|
||||
processed += 1
|
||||
if item.get('status') == 'success':
|
||||
success_count += 1
|
||||
else:
|
||||
fail_count += 1
|
||||
continue
|
||||
|
||||
staged_path = Path(str(item.get('staged_path') or ''))
|
||||
item['status'] = 'uploading'
|
||||
item['error'] = None
|
||||
payload['current_file'] = item.get('relative_path') or item.get('original_name')
|
||||
job.payload_json = payload
|
||||
job.message = f'正在导入:{payload["current_file"]}'
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
if not staged_path.exists():
|
||||
raise FileNotFoundError('暂存文件不存在')
|
||||
|
||||
document, version, _clean_job = _register_document_version_from_staged_file(
|
||||
group_id=job.group_id,
|
||||
relative_path=str(item.get('relative_path') or item.get('original_name') or staged_path.name),
|
||||
staged_path=staged_path,
|
||||
original_name=str(item.get('original_name') or staged_path.name),
|
||||
user_id=job.created_by_id,
|
||||
)
|
||||
item['status'] = 'success'
|
||||
item['document_id'] = document.id
|
||||
item['version_id'] = version.id
|
||||
item['error'] = None
|
||||
success_count += 1
|
||||
except Exception as exc:
|
||||
item['status'] = 'failed'
|
||||
item['error'] = str(exc)
|
||||
fail_count += 1
|
||||
|
||||
processed += 1
|
||||
result['success'] = success_count
|
||||
result['failed'] = fail_count
|
||||
result['processed'] = processed
|
||||
result['items'] = items
|
||||
job.payload_json = payload
|
||||
job.result_json = result
|
||||
job.progress = min(int(processed * 100 / total), 100)
|
||||
db.session.commit()
|
||||
|
||||
payload['current_file'] = ''
|
||||
job.payload_json = payload
|
||||
job.result_json = result
|
||||
job.progress = 100
|
||||
job.finished_at = _utc_now()
|
||||
if fail_count > 0:
|
||||
job.status = 'failed'
|
||||
job.message = f'路径上传完成,成功 {success_count} 条,失败 {fail_count} 条'
|
||||
job.error_message = f'部分文件上传失败:{fail_count} 条'
|
||||
db.session.commit()
|
||||
return False, 'partial_failed'
|
||||
|
||||
job.status = 'success'
|
||||
job.message = f'路径上传完成,成功 {success_count} 条'
|
||||
job.error_message = None
|
||||
db.session.commit()
|
||||
return True, 'ok'
|
||||
|
||||
|
||||
def run_clean_job(job_id: int) -> tuple[bool, str]:
|
||||
"""
|
||||
第一版最小清洗任务执行器。
|
||||
当前先不接 edkb_system,只做以下动作:
|
||||
1. 把 queued 的 clean 任务改为 running/success;
|
||||
2. 为版本生成 cleaned_preview_path;
|
||||
3. 更新版本状态为 cleaned;
|
||||
4. 为下一步接真实清洗链路预留结构。
|
||||
"""
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job:
|
||||
return False, '任务不存在'
|
||||
if job.job_type != 'clean':
|
||||
return False, '当前任务不是 clean 类型'
|
||||
|
||||
version = db.session.get(KbDocumentVersion, job.document_version_id)
|
||||
if not version:
|
||||
job.status = 'failed'
|
||||
job.error_message = '关联文档版本不存在'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return False, '关联文档版本不存在'
|
||||
|
||||
source_path = Path(version.source_file_path)
|
||||
if not source_path.exists():
|
||||
job.status = 'failed'
|
||||
job.error_message = '原始文件不存在,无法执行 clean'
|
||||
version.status = 'failed'
|
||||
version.error_message = '原始文件不存在,无法执行 clean'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return False, '原始文件不存在'
|
||||
|
||||
job.status = 'running'
|
||||
job.progress = 20
|
||||
job.message = '开始执行最小清洗任务'
|
||||
job.started_at = _utc_now()
|
||||
version.status = 'processing'
|
||||
db.session.commit()
|
||||
|
||||
target_dir = source_path.parent
|
||||
warnings = []
|
||||
|
||||
try:
|
||||
normalized_name = _normalized_source_filename(version, source_path)
|
||||
staged_source = target_dir / normalized_name
|
||||
if staged_source != source_path:
|
||||
shutil.copy2(source_path, staged_source)
|
||||
source_path = staged_source
|
||||
|
||||
result = build_clean_result(source_path, target_dir)
|
||||
job_message = '真实清洗结果已生成'
|
||||
except Exception as exc:
|
||||
preview_path = target_dir / f'{_normalized_source_filename(version, source_path)}.preview.txt'
|
||||
preview_path.write_text(
|
||||
'\n'.join([
|
||||
f'source_file={source_path.name}',
|
||||
f'source_size={version.source_file_size or 0}',
|
||||
'clean_status=placeholder_success',
|
||||
f'fallback_reason={str(exc)}',
|
||||
]),
|
||||
encoding='utf-8',
|
||||
)
|
||||
result = {
|
||||
'mode': 'placeholder_clean',
|
||||
'cleaned_file_path': None,
|
||||
'cleaned_preview_path': str(preview_path),
|
||||
'word_count': 0,
|
||||
}
|
||||
warnings.append({'message': f'edkb_fallback={str(exc)}'})
|
||||
job_message = 'edkb_system 未就绪,已回退到占位清洗结果'
|
||||
|
||||
version.cleaned_file_path = result.get('cleaned_file_path')
|
||||
version.cleaned_preview_path = result.get('cleaned_preview_path')
|
||||
version.word_count = int(result.get('word_count') or 0)
|
||||
version.status = 'cleaned'
|
||||
version.converted_at = _utc_now()
|
||||
version.error_message = None
|
||||
version.warnings_json = warnings or None
|
||||
if version.document:
|
||||
version.document.status = 'ready'
|
||||
|
||||
job.status = 'success'
|
||||
job.progress = 100
|
||||
job.message = job_message
|
||||
job.error_message = None
|
||||
job.result_json = result
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
|
||||
return True, 'ok'
|
||||
|
||||
|
||||
def run_sync_job(job_id: int) -> tuple[bool, str]:
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job:
|
||||
return False, '任务不存在'
|
||||
if job.job_type != 'sync_dify':
|
||||
return False, '当前任务不是 sync_dify 类型'
|
||||
|
||||
version = db.session.get(KbDocumentVersion, job.document_version_id)
|
||||
if not version:
|
||||
job.status = 'failed'
|
||||
job.error_message = '关联文档版本不存在'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return False, '关联文档版本不存在'
|
||||
|
||||
job.status = 'running'
|
||||
job.progress = 20
|
||||
job.message = '开始同步到 Dify'
|
||||
job.started_at = _utc_now()
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
result = sync_document_version_to_dify(version.id, synced_by_id=job.created_by_id)
|
||||
except KbDifySyncError as exc:
|
||||
version.status = 'ready'
|
||||
job.status = 'failed'
|
||||
job.progress = 100
|
||||
job.error_message = str(exc)
|
||||
job.message = '同步到 Dify 失败'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return False, str(exc)
|
||||
except Exception as exc:
|
||||
version.status = 'ready'
|
||||
job.status = 'failed'
|
||||
job.progress = 100
|
||||
job.error_message = f'同步到 Dify 时发生未预期错误:{exc}'
|
||||
job.message = '同步到 Dify 失败'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return False, str(exc)
|
||||
|
||||
version.status = 'synced'
|
||||
job.status = 'success'
|
||||
job.progress = 100
|
||||
job.message = '已同步到 Dify'
|
||||
job.error_message = None
|
||||
job.result_json = result
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return True, 'ok'
|
||||
Reference in new issue
Block a user