fix(platform): 汇总知识库问答与图表展示修复

This commit is contained in:
HTEWJ\26070045 committed 2026-08-06 17:07:31 +08:00
1 parent 9838b77441
commit e7ff6bc2dd
41 files changed
+2100 -795

No files matched your search

+240 -22
View File
@@ -326,6 +326,7 @@ def _is_allowed_preview_url(target_url: str) -> bool:
def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 * 1024):
"""
从上游文件 URL 拉取二进制内容(供预览接口复用)。
核心逻辑:共享盘直读 / 固资图 / HTTP 拉取;integration kind=source 404 时回退 md → Dify 原文件 → 分段文本。
如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。
返回: (content_bytes, content_type, error_tuple)
其中 error_tuple = (message, status_code);成功时为 None。
@@ -500,6 +501,10 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
file_url = refreshed_url
current_app.logger.warning(f"[file-preview] upstream returned status {upstream.status_code} for {file_url}")
if upstream.status_code == 404:
# [STEP] 源文件 404:先试 integration kind=md,再试 Dify 原文件/分段文本
fallback = _fetch_preview_bytes_after_source_404(file_url, max_size=max_size)
if fallback[0] is not None or fallback[2] is not None:
return fallback
return None, None, ('source file not found', 404)
return None, None, (f'upstream returned status {upstream.status_code}', 502)
@@ -513,6 +518,174 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
return (None, None, ('upstream returned invalid preview payload', 502))
return (content, content_type, None)
def _rewrite_integration_download_kind(file_url: str, kind: str) -> str:
"""
将 integration download URL 的 kind 查询参数改写为目标值。
@param file_url: 原始下载 URL
@param kind: 目标 kind(如 md)
@returns 改写后的 URL;无法识别时原样返回
"""
from urllib.parse import parse_qs, urlencode, urlunparse
raw = str(file_url or '').strip()
if not raw or '/api/integration/files/' not in raw:
return raw
parsed = urlparse(raw)
qs = parse_qs(parsed.query, keep_blank_values=True)
qs['kind'] = [str(kind)]
flat: dict = {}
for key, values in qs.items():
flat[key] = values[0] if len(values) == 1 else values
new_query = urlencode(flat, doseq=True)
return urlunparse((parsed.scheme, parsed.netloc, parsed.path, parsed.params, new_query, parsed.fragment))
def _extract_integration_token_ids(file_url: str) -> tuple[str, str]:
"""
从 integration 下载 URL 的 JWT token 中解析 dataset_id / remote_document_id。
@returns (dataset_id, remote_document_id),失败时为空字符串
"""
import base64
from urllib.parse import parse_qs
try:
parsed = urlparse(str(file_url or ''))
qs = parse_qs(parsed.query)
token = (qs.get('token') or [''])[0]
if not token:
return ('', '')
parts = token.split('.')
if len(parts) < 2:
return ('', '')
payload_b64 = parts[1] + '=' * (-len(parts[1]) % 4)
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
dataset_id = str(payload_data.get('dataset_id') or '').strip()
remote_document_id = str(payload_data.get('remote_document_id') or '').strip()
return (dataset_id, remote_document_id)
except Exception:
return ('', '')
def _fetch_dify_source_bytes(dataset_id: str, remote_document_id: str, max_size: int | None):
"""
从 Dify 拉取文档原始二进制(签名下载 URL)。
【AI 触发时机】本地 source 文件丢失、integration 404 时作为预览兜底。
@returns (content, content_type, error_tuple) 与 _fetch_preview_source_bytes 一致
"""
if not dataset_id or not remote_document_id:
return (None, None, None)
try:
info = IntegrationApiService._lookup_from_dify_document_api(dataset_id, remote_document_id)
source_url = str((info or {}).get('source_download_url') or '').strip()
if not source_url:
return (None, None, None)
upstream = requests.get(source_url, timeout=(5, 30))
if upstream.status_code != 200:
current_app.logger.warning(
'[file-preview] dify source download status=%s dataset=%s doc=%s',
upstream.status_code,
dataset_id,
remote_document_id,
)
return (None, None, None)
content = upstream.content or b''
if max_size is not None and len(content) > max_size:
return (None, None, ('file too large for online preview', 413))
content_type = (upstream.headers.get('content-type') or '').split(';')[0].strip().lower()
return (content, content_type or None, None)
except Exception as exc:
current_app.logger.warning(
'[file-preview] dify source download failed dataset=%s doc=%s err=%s',
dataset_id,
remote_document_id,
exc,
)
return (None, None, None)
def _looks_like_text_document(content: bytes) -> bool:
"""
判断内容是否可按文本/Markdown 预览,避免把 OLE/PDF 等二进制当文本导致乱码。
核心逻辑:识别常见二进制魔数;抽样解码后要求可打印字符占比足够高。
"""
if not content:
return False
# [STEP 1] 排除 PDF / ZIP(OOXML) / OLE(旧版 Office)
if content.startswith((b'%PDF-', b'PK\x03\x04', b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1')):
return False
sample = content[:4096]
if b'\x00' in sample:
return False
text = None
for enc in ('utf-8', 'utf-8-sig', 'gb18030'):
try:
text = sample.decode(enc)
break
except UnicodeDecodeError:
continue
if text is None:
return False
printable = sum(1 for ch in text if ch.isprintable() or ch in '\r\n\t')
return (printable / max(len(text), 1)) >= 0.85
def _fetch_preview_bytes_after_source_404(file_url: str, max_size: int | None):
"""
源文件 404 后的预览兜底链:integration md → Dify 原文件 → Dify 分段文本。
"""
# [STEP 1] kind=source → kind=md(清洗稿,必须是可读文本)
if 'kind=source' in str(file_url or '') and '/api/integration/files/' in str(file_url or ''):
md_url = _rewrite_integration_download_kind(file_url, 'md')
if md_url and md_url != file_url:
try:
api_key = IntegrationApiService.get_api_key()
headers = {'X-Integration-Key': api_key} if api_key else {}
upstream = requests.get(md_url, headers=headers, timeout=(5, 20))
if upstream.status_code == 200:
content = upstream.content or b''
if max_size is not None and len(content) > max_size:
return (None, None, ('file too large for online preview', 413))
content_type = (upstream.headers.get('content-type') or '').split(';')[0].strip().lower()
if content_type == 'application/json':
current_app.logger.warning('[file-preview] md fallback returned json url=%s', md_url)
elif not _looks_like_text_document(content):
current_app.logger.warning(
'[file-preview] md fallback ignored binary payload url=%s',
md_url,
)
else:
current_app.logger.info('[file-preview] source 404 fallback to markdown url=%s', md_url)
return (content, content_type or 'text/markdown', None)
except requests.RequestException as exc:
current_app.logger.warning('[file-preview] markdown fallback failed: %s', exc)
dataset_id, remote_document_id = _extract_integration_token_ids(file_url)
# [STEP 2] Dify 原始文件下载
dify_bytes = _fetch_dify_source_bytes(dataset_id, remote_document_id, max_size)
if dify_bytes[0] is not None:
current_app.logger.info(
'[file-preview] source 404 fallback to dify binary dataset=%s doc=%s',
dataset_id,
remote_document_id,
)
return dify_bytes
if dify_bytes[2] is not None:
return dify_bytes
# [STEP 3] Dify 分段文本(任意文档形态)
text = _fetch_dify_document_segments_text(dataset_id, remote_document_id)
if text:
current_app.logger.info(
'[file-preview] source 404 fallback to dify segments dataset=%s doc=%s',
dataset_id,
remote_document_id,
)
return (text.encode('utf-8'), 'text/plain; charset=utf-8', None)
return (None, None, None)
def _extract_placeholder_text(content: bytes) -> str:
sample = content[:2048]
for enc in ('utf-16le', 'utf-8', 'utf-8-sig', 'gb18030', 'latin-1'):
@@ -531,6 +704,46 @@ def _extract_placeholder_text(content: bytes) -> str:
return ''
def _fetch_dify_document_segments_text(dataset_id: str, remote_document_id: str) -> str | None:
"""
拼接 Dify 文档全部分段文本,不限制 doc_form(供源文件丢失时的预览兜底)。
"""
if not dataset_id or not remote_document_id:
return None
try:
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
service = KbDifySyncService()
segments_payload = service._request(
'GET',
f'/datasets/{dataset_id}/documents/{remote_document_id}/segments?limit=1000',
)
rows = []
if isinstance(segments_payload, dict):
rows = segments_payload.get('data') or []
elif isinstance(segments_payload, list):
rows = segments_payload
if not isinstance(rows, list) or not rows:
return None
ordered_rows = sorted(
[row for row in rows if isinstance(row, dict)],
key=lambda row: (int(row.get('position') or 0), str(row.get('id') or '')),
)
parts: list[str] = []
for row in ordered_rows:
text_part = str(row.get('content') or '').strip()
if text_part:
parts.append(text_part)
return '\n\n'.join(parts).strip() or None
except Exception as e:
current_app.logger.warning(
'[source-file-text] failed to fetch dify segments dataset=%s doc=%s err=%s',
dataset_id,
remote_document_id,
e,
)
return None
def _fetch_dify_text_document(dataset_id: str, remote_document_id: str) -> str | None:
"""
对于 Dify 中以 text_model / txt 形式存储的文档,
@@ -564,28 +777,7 @@ def _fetch_dify_text_document(dataset_id: str, remote_document_id: str) -> str |
if not is_text_doc:
return None
segments_payload = service._request(
'GET',
f'/datasets/{dataset_id}/documents/{remote_document_id}/segments?limit=1000',
)
rows = []
if isinstance(segments_payload, dict):
rows = segments_payload.get('data') or []
elif isinstance(segments_payload, list):
rows = segments_payload
if not isinstance(rows, list) or not rows:
return None
ordered_rows = sorted(
[row for row in rows if isinstance(row, dict)],
key=lambda row: (int(row.get('position') or 0), str(row.get('id') or '')),
)
parts: list[str] = []
for row in ordered_rows:
text = str(row.get('content') or '').strip()
if text:
parts.append(text)
return '\n\n'.join(parts).strip() or None
return _fetch_dify_document_segments_text(dataset_id, remote_document_id)
except Exception as e:
current_app.logger.warning(
'[source-file-text] failed to fetch dify text document dataset=%s doc=%s err=%s',
@@ -2062,6 +2254,20 @@ def preview_file_raw():
# 根据文件二进制头部纠正扩展名,防止文件本身是 docx 却被命名为 doc,导致转换或下载后乱码
real_ext = _guess_ext_from_content(content, ext)
# 仅当内容确实是文本时,才允许按 content_type 切到 md/txt(避免 .doc OLE 被当文本渲染乱码)
normalized_ct = (content_type or '').split(';')[0].strip().lower()
if _looks_like_text_document(content):
if 'markdown' in normalized_ct:
real_ext = 'md'
elif normalized_ct.startswith('text/') and original_ext in (
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx',
):
real_ext = 'txt'
elif real_ext in ('md', 'markdown', 'txt') and original_ext in (
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx',
):
# content_type/文件名声称是文本,但载荷是 Office 二进制:以魔数扩展名为准
real_ext = _guess_ext_from_content(content, original_ext or ext)
if real_ext != ext:
current_app.logger.info(f"[file-preview] corrected extension from {ext} to {real_ext}")
ext = real_ext
@@ -2069,6 +2275,18 @@ def preview_file_raw():
name = f"{name.rsplit('.', 1)[0]}.{ext}"
elif name:
name = f"{name}.{ext}"
# 回退文本预览时,避免仍带二进制 Content-Type 导致前端按 PDF 渲染
if ext in ('md', 'markdown', 'txt') and _looks_like_text_document(content):
if not str(content_type or '').lower().startswith('text/'):
content_type = {
'md': 'text/markdown; charset=utf-8',
'markdown': 'text/markdown; charset=utf-8',
'txt': 'text/plain; charset=utf-8',
}.get(ext)
elif ext in ('md', 'markdown', 'txt') and not _looks_like_text_document(content):
# 拒绝把二进制伪装成文本扩展名
ext = _guess_ext_from_content(content, original_ext or 'bin') or (original_ext or 'bin')
content_type = None
# 仅当文件真实格式仍然是旧版 Office/PPT 时才转 PDF。
# 如果原始文件名是 .doc 但内容实际是 .docx,则交给前端 Office 组件渲染,
+110 -11
View File
@@ -1,6 +1,9 @@
"""
backend/app/api/integration.py
文件用途:知识库外部集成查询接口
用途:知识库外部集成查询/下载接口(供 Dify Tool 与聊天源文件预览解析)。
依赖:Flask Blueprint、SQLAlchemy、IntegrationApiService、Kb* 模型。
逻辑:聊天预览经 /api/chat/preview-* 代理到本模块 download;dify-file 供 IntegrationApiService 反查本地映射。
"""
from __future__ import annotations
from pathlib import Path
@@ -144,6 +147,12 @@ def _kb_storage_root() -> Path:
return root
def _resolve_storage_path(path_value: str | None) -> Path | None:
"""
解析知识库存储相对/绝对路径,并校验落在 KB_STORAGE_ROOT 内。
核心逻辑:相对路径拼到存储根;绝对路径直接 resolve 后做越界校验。
@param path_value: 数据库中的路径字符串
@returns 合法绝对 Path,越界或空则 None
"""
if not path_value:
return None
raw_path = Path(str(path_value))
@@ -155,6 +164,45 @@ def _resolve_storage_path(path_value: str | None) -> Path | None:
return None
return candidate
def _existing_storage_path(path_value: str | None) -> Path | None:
"""
解析存储路径且要求文件真实存在。
核心逻辑:先 _resolve_storage_path,再校验 is_file。
@returns 存在的 Path,否则 None
"""
path = _resolve_storage_path(path_value)
if path is None or not path.exists() or not path.is_file():
return None
return path
def _markdown_storage_path(version: KbDocumentVersion) -> Path | None:
"""
取版本可用的清洗 Markdown 文件路径(优先 cleaned_file,其次 preview)。
核心逻辑:路径存在且内容像文本时才返回,避免误把 OLE 二进制当 md。
"""
for path_value in (version.cleaned_file_path, version.cleaned_preview_path):
path = _existing_storage_path(path_value)
if path is None:
continue
try:
head = path.read_bytes()[:4096]
except OSError:
continue
if head.startswith((b'%PDF-', b'PK\x03\x04', b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1')):
current_app.logger.warning(
'[integration] skip binary cleaned path version_id=%s path=%s',
version.id,
path,
)
continue
if b'\x00' in head:
continue
return path
return None
def _current_version(document: KbDocument) -> KbDocumentVersion | None:
versions = list(getattr(document, 'versions', []) or [])
if not versions:
@@ -165,13 +213,40 @@ def _document_query():
return db.session.query(KbDocument).options(joinedload(KbDocument.group), joinedload(KbDocument.versions).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False))
def _serialize_integration_document(document: KbDocument, *, version: KbDocumentVersion | None=None, sync_record: KbDifySyncRecord | None=None):
"""
序列化集成侧文档元数据与可下载 URL。
核心逻辑:源文件在磁盘存在时返回 kind=source;否则回退到清洗 Markdown(kind=md),
避免聊天预览拿到“库有映射、盘无文件”的死链。
"""
version = version or _current_version(document)
if not version:
abort(404, description='No current version found.')
sync_record = sync_record or (next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None) or (version.sync_records[0] if getattr(version, 'sync_records', None) else None))
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
markdown_download_url = _build_download_url(document.id, kind='md', version_id=version.id) if version.cleaned_file_path or version.cleaned_preview_path else None
return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': version.source_file_name, 'source_ext': version.source_file_ext, 'file_name': version.source_file_name, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}}
source_path = _existing_storage_path(version.source_file_path)
markdown_path = _markdown_storage_path(version)
markdown_download_url = (
_build_download_url(document.id, kind='md', version_id=version.id) if markdown_path else None
)
if source_path is not None:
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
source_filename = version.source_file_name
source_ext = version.source_file_ext
elif markdown_path is not None:
# [STEP] 源文件缺失时用清洗稿顶替预览入口,扩展名改为 md 以便前端走文本预览
source_download_url = markdown_download_url
stem = Path(str(version.source_file_name or document.title or f'document-{document.id}')).stem
source_filename = f'{stem}.md'
source_ext = 'md'
current_app.logger.info(
'[integration] source missing, serialize fallback to markdown document_id=%s version_id=%s',
document.id,
version.id,
)
else:
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
source_filename = version.source_file_name
source_ext = version.source_file_ext
return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': source_filename, 'source_ext': source_ext, 'file_name': source_filename, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}}
def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict:
return {'id': group.id, 'knowledge_base_id': group.id, 'name': group.name, 'description': group.description, 'department_id': group.department_id, 'dify_dataset_id': group.dify_dataset_id, 'document_count': int(document_count or 0), 'created_at': group.created_at.isoformat() if group.created_at else None, 'updated_at': group.updated_at.isoformat() if group.updated_at else None}
@@ -196,13 +271,31 @@ def _list_files_payload(*, knowledge_base_id: int | None=None, department_id: in
return payload
def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]:
"""
解析下载目标路径与文件名。
核心逻辑:kind=source 优先原始文件;缺失时回退清洗 Markdown,避免预览 404。
@param version: 文档版本
@param kind: source | md
@returns (绝对路径, 下载文件名)
@raises NotFoundError: 源文件与清洗稿均不存在
"""
if kind == 'source':
path = _resolve_storage_path(version.source_file_path)
if path is None:
raise NotFoundError('File not found on disk.')
filename = version.source_file_name or f'document-{version.document_id}'
return (path, filename)
preferred = _resolve_storage_path(version.cleaned_file_path) or _resolve_storage_path(version.cleaned_preview_path)
path = _existing_storage_path(version.source_file_path)
if path is not None:
filename = version.source_file_name or f'document-{version.document_id}'
return (path, filename)
preferred = _markdown_storage_path(version)
if preferred is not None:
current_app.logger.warning(
'[integration] source file missing, fallback to markdown document_id=%s version_id=%s path=%s',
version.document_id,
version.id,
preferred,
)
filename = f'document-{version.document_id}-v{version.version_no}.md'
return (preferred, filename)
raise NotFoundError('File not found on disk.')
preferred = _markdown_storage_path(version)
if not preferred:
abort(409, description='Markdown not ready.')
filename = f'document-{version.document_id}-v{version.version_no}.md'
@@ -248,6 +341,10 @@ def list_files_for_knowledge_base(knowledge_base_id: int):
@integration_bp.route('/dify-file', methods=['GET'])
def get_file_detail_by_dify():
"""
按 Dify dataset/document 反查本地知识库文件元数据。
核心逻辑:查 KbDifySyncRecord;若源文件与清洗稿均不在磁盘,返回 404 以便上层改走 Dify 下载。
"""
remote_document_id = str(request.args.get('remote_document_id') or '').strip()
dataset_id = str(request.args.get('dataset_id') or '').strip() or None
if not remote_document_id:
@@ -258,8 +355,10 @@ def get_file_detail_by_dify():
record = record_query.first()
version = record.document_version if record else None
document = version.document if version else None
if not document:
if not document or not version:
raise NotFoundError('No local file mapping found for the given Dify document.')
if _existing_storage_path(version.source_file_path) is None and _markdown_storage_path(version) is None:
raise NotFoundError('No readable local file for the given Dify document.')
return jsonify(_serialize_integration_document(document, version=version, sync_record=record))
@integration_bp.route('/dify-files/resolve', methods=['POST'])