Merge branch 'dev' into test

This commit is contained in:
runny committed 2026-05-30 14:13:01 +08:00
commit 744d623f2f
7 files changed
+509 -168

No files matched your search

+3 -2
View File
@@ -47,9 +47,10 @@ GUNICORN_WORKERS=10
# MinIO(知识库文档清洗图片托管;dev 与测试机同机时用测试 MinIO) # MinIO(知识库文档清洗图片托管;dev 与测试机同机时用测试 MinIO)
# 本地非 Docker 跑 worker 时可改为 127.0.0.1:9000 或 192.168.100.192:9000 # 本地非 Docker 跑 worker 时可改为 127.0.0.1:9000 或 192.168.100.192:9000
# 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD 保持一致
MINIO_ENDPOINT=host.docker.internal:9000 MINIO_ENDPOINT=host.docker.internal:9000
MINIO_BUCKET=image-hosting-service MINIO_BUCKET=image-hosting-service
MINIO_ACCESS_KEY=admin MINIO_ACCESS_KEY=minio_testing_admin
MINIO_SECRET_KEY=difyai123456 MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJ03RIHVZSRYlDouOMabasojfAGBlx
MINIO_SECURE=false MINIO_SECURE=false
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000 MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
+3 -2
View File
@@ -50,10 +50,11 @@ WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
# MinIO(知识库文档清洗图片托管,容器 minio-app) # MinIO(知识库文档清洗图片托管,容器 minio-app)
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1) # MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
# 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD(及 DIFY_S3_ACCESS_KEY)保持一致
MINIO_ENDPOINT=host.docker.internal:9000 MINIO_ENDPOINT=host.docker.internal:9000
MINIO_BUCKET=image-hosting-service MINIO_BUCKET=image-hosting-service
MINIO_ACCESS_KEY=admin MINIO_ACCESS_KEY=minio_testing_admin
MINIO_SECRET_KEY=difyai123456 MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJ03RIHVZSRYlDouOMabasojfAGBlx
MINIO_SECURE=false MINIO_SECURE=false
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问 # MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000 MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
+181 -26
View File
@@ -72,6 +72,13 @@ def _is_allowed_preview_url(target_url: str) -> bool:
if integration_host and host == integration_host: if integration_host and host == integration_host:
return True return True
# 放行当前请求的 Host (前端能够访问本接口说明 Host 是受信任的自身域名/IP)
from flask import request, has_request_context
if has_request_context():
req_host = (request.host.split(':')[0] or "").strip().lower()
if host == req_host:
return True
if host in ("localhost", "127.0.0.1", "::1"): if host in ("localhost", "127.0.0.1", "::1"):
return True return True
@@ -80,7 +87,7 @@ def _is_allowed_preview_url(target_url: str) -> bool:
return ip.is_private or ip.is_loopback return ip.is_private or ip.is_loopback
except ValueError: except ValueError:
# 非 IP 主机:仅放行内网风格本地域名。 # 非 IP 主机:仅放行内网风格本地域名。
return host.endswith(".local") or host.endswith(".lan") return host.endswith(".local") or host.endswith(".lan") or host.endswith(".well-trust.com")
except Exception: except Exception:
return False return False
@@ -165,8 +172,33 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
def _build_headers(raw_url: str): def _build_headers(raw_url: str):
next_headers = {} next_headers = {}
if base_url and raw_url.startswith(base_url) and api_key: if not api_key:
current_app.logger.info(f"[_build_headers] api_key is missing")
return next_headers
is_trusted = False
if base_url and raw_url.startswith(base_url):
is_trusted = True
elif _is_allowed_preview_url(raw_url):
is_trusted = True
else:
try:
parsed = urlparse(raw_url)
host = (parsed.hostname or "").strip().lower()
from flask import request, has_request_context
if has_request_context():
req_host = (request.host.split(':')[0] or "").strip().lower()
if host == req_host:
is_trusted = True
if host in ("localhost", "127.0.0.1", "::1"):
is_trusted = True
except Exception:
pass
current_app.logger.info(f"[_build_headers] raw_url={raw_url}, is_trusted={is_trusted}")
if is_trusted:
next_headers['X-Integration-Key'] = api_key next_headers['X-Integration-Key'] = api_key
return next_headers return next_headers
def _should_refresh_from_response(resp) -> bool: def _should_refresh_from_response(resp) -> bool:
@@ -217,6 +249,7 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
return None, None, ('failed to fetch source file', 502) return None, None, ('failed to fetch source file', 502)
if upstream.status_code != 200: if upstream.status_code != 200:
current_app.logger.warning(f"[file-preview] upstream returned status {upstream.status_code} for {file_url}")
return None, None, (f'upstream returned status {upstream.status_code}', 502) return None, None, (f'upstream returned status {upstream.status_code}', 502)
content = upstream.content or b'' content = upstream.content or b''
@@ -250,9 +283,11 @@ def _extract_placeholder_text(content: bytes) -> str:
def _convert_office_to_pdf(content: bytes, ext: str) -> bytes: def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
""" """
使用 LibreOffice 将 office 文件转为 PDF 使用 LibreOffice 或 WPS/MS Office 将 office 文件转为 PDF
""" """
with tempfile.TemporaryDirectory() as temp_dir: import shutil
temp_dir = tempfile.mkdtemp()
try:
input_path = os.path.join(temp_dir, f"input.{ext}") input_path = os.path.join(temp_dir, f"input.{ext}")
with open(input_path, 'wb') as f: with open(input_path, 'wb') as f:
f.write(content) f.write(content)
@@ -283,6 +318,9 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
# 如果 LibreOffice 失败,且是在 Windows 系统下,尝试调用本地安装的 WPS 或 MS Office # 如果 LibreOffice 失败,且是在 Windows 系统下,尝试调用本地安装的 WPS 或 MS Office
if not success and os.name == 'nt': if not success and os.name == 'nt':
app = None
doc_obj = None
pythoncom = None
try: try:
import win32com.client import win32com.client
import pythoncom import pythoncom
@@ -291,14 +329,42 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
if ext in ('doc', 'docx'): if ext in ('doc', 'docx'):
try: try:
app = win32com.client.Dispatch("KWPS.Application") # 尝试 WPS Word from pathlib import Path
from edkb_system.skills.word_bridge import convert_with_word
convert_with_word(Path(input_path), Path(output_path), 17)
success = True
except Exception as word_bridge_exc:
current_app.logger.warning("Word bridge conversion failed: %s", word_bridge_exc)
if not success and ext in ('doc', 'docx'):
try:
# 对旧版 .doc,MS Word 的 PDF 导出兼容性通常优于 WPS
app = win32com.client.Dispatch("Word.Application")
except Exception: except Exception:
app = win32com.client.Dispatch("Word.Application") # 回退 MS Word app = win32com.client.Dispatch("KWPS.Application")
app.Visible = False app.Visible = False
doc = app.Documents.Open(os.path.abspath(input_path)) app.DisplayAlerts = False
doc.SaveAs(os.path.abspath(output_path), FileFormat=17) # 17 = wdFormatPDF input_abs = os.path.abspath(input_path)
doc.Close() output_abs = os.path.abspath(output_path)
app.Quit() try:
doc_obj = app.Documents.Open(
FileName=input_abs,
ConfirmConversions=False,
ReadOnly=True,
AddToRecentFiles=False,
Visible=False,
NoEncodingDialog=True,
OpenAndRepair=True,
)
except TypeError:
doc_obj = app.Documents.Open(input_abs, ReadOnly=True)
try:
# 旧版 WPS/Word 对 ExportAsFixedFormat 的兼容通常优于 SaveAs(FileFormat=17)
doc_obj.ExportAsFixedFormat(output_abs, 17) # 17 = wdExportFormatPDF
except Exception:
doc_obj.SaveAs(output_abs, 17) # 17 = wdFormatPDF
success = True success = True
elif ext in ('ppt', 'pptx'): elif ext in ('ppt', 'pptx'):
@@ -307,10 +373,12 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
except Exception: except Exception:
app = win32com.client.Dispatch("PowerPoint.Application") # 回退 MS PPT app = win32com.client.Dispatch("PowerPoint.Application") # 回退 MS PPT
app.Visible = False app.Visible = False
presentation = app.Presentations.Open(os.path.abspath(input_path), WithWindow=False) try:
presentation.SaveAs(os.path.abspath(output_path), 32) # 32 = ppSaveAsPDF app.DisplayAlerts = False
presentation.Close() except Exception:
app.Quit() pass
doc_obj = app.Presentations.Open(os.path.abspath(input_path), ReadOnly=True, WithWindow=False)
doc_obj.SaveAs(os.path.abspath(output_path), 32) # 32 = ppSaveAsPDF
success = True success = True
elif ext in ('xls', 'xlsx'): elif ext in ('xls', 'xlsx'):
@@ -319,15 +387,30 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
except Exception: except Exception:
app = win32com.client.Dispatch("Excel.Application") # 回退 MS Excel app = win32com.client.Dispatch("Excel.Application") # 回退 MS Excel
app.Visible = False app.Visible = False
wb = app.Workbooks.Open(os.path.abspath(input_path)) app.DisplayAlerts = False
wb.ExportAsFixedFormat(0, os.path.abspath(output_path)) # 0 = xlTypePDF doc_obj = app.Workbooks.Open(os.path.abspath(input_path), ReadOnly=True)
wb.Close(False) doc_obj.ExportAsFixedFormat(0, os.path.abspath(output_path)) # 0 = xlTypePDF
app.Quit()
success = True success = True
except ImportError: except ImportError:
current_app.logger.warning("pywin32 not installed, cannot fallback to WPS/MS Office COM API.") current_app.logger.warning("pywin32 not installed, cannot fallback to WPS/MS Office COM API.")
except Exception as e: except Exception as e:
current_app.logger.warning(f"WPS/MS Office COM conversion failed: {e}") current_app.logger.warning(f"WPS/MS Office COM conversion failed: {e}")
finally:
if doc_obj is not None:
try:
doc_obj.Close(False)
except Exception:
pass
if app is not None:
try:
app.Quit()
except Exception:
pass
if pythoncom is not None:
try:
pythoncom.CoUninitialize()
except Exception:
pass
if not success: if not success:
raise Exception("Failed to convert document to PDF using LibreOffice or WPS/MS Office") raise Exception("Failed to convert document to PDF using LibreOffice or WPS/MS Office")
@@ -338,6 +421,8 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
return f.read() return f.read()
else: else:
raise Exception("PDF output not found after conversion") raise Exception("PDF output not found after conversion")
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
def _convert_excel_to_xlsx(content: bytes, ext: str) -> bytes: def _convert_excel_to_xlsx(content: bytes, ext: str) -> bytes:
@@ -911,8 +996,6 @@ def preview_excel():
name = (request.args.get('name') or '').strip() name = (request.args.get('name') or '').strip()
name_ext = (name.split('.')[-1] if '.' in name else '').lower() name_ext = (name.split('.')[-1] if '.' in name else '').lower()
ext = url_path_ext or name_ext ext = url_path_ext or name_ext
if ext and ext not in ('xlsx', 'xls'):
return jsonify({'error': f'unsupported file extension: {ext}'}), 415
try: try:
limit = int(request.args.get('limit', 100)) limit = int(request.args.get('limit', 100))
@@ -925,10 +1008,13 @@ def preview_excel():
msg, code = err msg, code = err
return jsonify({'error': msg}), code return jsonify({'error': msg}), code
detected_ext = _detect_excel_format(content or b'', ext)
if detected_ext not in ('xlsx', 'xls'):
return jsonify({'error': f'unsupported file extension: {ext or detected_ext or "unknown"}'}), 415
try: try:
wb = _load_excel_workbook(content, ext) wb = _load_excel_workbook(content, detected_ext)
except Exception as e: except Exception as e:
detected_ext = _detect_excel_format(content or b'', ext)
current_app.logger.warning( current_app.logger.warning(
"[excel-preview] parse workbook failed ext=%s detected_ext=%s size=%s name=%s url=%s err=%r", "[excel-preview] parse workbook failed ext=%s detected_ext=%s size=%s name=%s url=%s err=%r",
ext, ext,
@@ -1032,6 +1118,48 @@ def preview_text():
}) })
def _guess_ext_from_content(content: bytes, default_ext: str) -> str:
"""
根据文件内容(Magic Bytes)纠正可能的错误扩展名
"""
import io
import zipfile
if not content:
return default_ext
if content.startswith(b'%PDF-'):
return 'pdf'
if content.startswith(b'PK\x03\x04'):
# ZIP 归档,进一步检查内部目录判断是 docx/xlsx/pptx。
try:
with zipfile.ZipFile(io.BytesIO(content)) as zf:
names = {name.lower() for name in zf.namelist()}
if any(name.startswith('word/') for name in names):
return 'docx'
if any(name.startswith('xl/') for name in names):
return 'xlsx'
if any(name.startswith('ppt/') for name in names):
return 'pptx'
except Exception:
pass
if default_ext == 'doc':
return 'docx'
if default_ext == 'xls':
return 'xlsx'
if default_ext == 'ppt':
return 'pptx'
if default_ext in ('docx', 'xlsx', 'pptx'):
return default_ext
return 'docx'
if content.startswith(b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1'):
# OLE 复合文件,通常是 doc, xls, ppt 等。
if default_ext == 'docx': return 'doc'
if default_ext == 'xlsx': return 'xls'
if default_ext == 'pptx': return 'ppt'
if default_ext in ('doc', 'xls', 'ppt'): return default_ext
return 'doc'
return default_ext
@chat_bp.route('/preview-file-raw', methods=['GET']) @chat_bp.route('/preview-file-raw', methods=['GET'])
@require_agent_permission @require_agent_permission
def preview_file_raw(): def preview_file_raw():
@@ -1051,7 +1179,8 @@ def preview_file_raw():
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower() url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
name = (request.args.get('name') or '').strip() name = (request.args.get('name') or '').strip()
name_ext = (name.split('.')[-1] if '.' in name else '').lower() name_ext = (name.split('.')[-1] if '.' in name else '').lower()
ext = url_path_ext or name_ext original_ext = url_path_ext or name_ext
ext = original_ext
is_download = request.args.get('download') == '1' is_download = request.args.get('download') == '1'
max_size = None if is_download else 15 * 1024 * 1024 max_size = None if is_download else 15 * 1024 * 1024
content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size) content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size)
@@ -1059,15 +1188,39 @@ def preview_file_raw():
msg, code = err msg, code = err
return jsonify({'error': msg}), code return jsonify({'error': msg}), code
# 如果是无法纯前端渲染的旧版 Office 或 PPT 格式,尝试转为 PDF 供前端统一渲染 # 根据文件二进制头部纠正扩展名,防止文件本身是 docx 却被命名为 doc,导致转换或下载后乱码
if ext in ('doc', 'ppt', 'pptx') and request.args.get('download') != '1': real_ext = _guess_ext_from_content(content, ext)
if real_ext != ext:
current_app.logger.info(f"[file-preview] corrected extension from {ext} to {real_ext}")
ext = real_ext
if name and '.' in name:
name = f"{name.rsplit('.', 1)[0]}.{ext}"
elif name:
name = f"{name}.{ext}"
# 仅当文件真实格式仍然是旧版 Office/PPT 时才转 PDF。
# 如果原始文件名是 .doc 但内容实际是 .docx,则交给前端 Office 组件渲染,
# 避免在服务端走旧版转换链路导致长时间卡住。
needs_pdf_conversion = (
request.args.get('download') != '1'
and original_ext in ('doc', 'ppt', 'pptx')
and ext in ('doc', 'ppt', 'pptx')
)
if needs_pdf_conversion:
try: try:
content = _convert_office_to_pdf(content, ext) content = _convert_office_to_pdf(content, ext)
ext = 'pdf' ext = 'pdf'
content_type = 'application/pdf' content_type = 'application/pdf'
except Exception as e: except Exception as e:
current_app.logger.error("[file-preview] LibreOffice conversion failed: %s", e) current_app.logger.error("[file-preview] LibreOffice conversion failed: %s", e)
# 转换失败则回退到原始格式 placeholder_text = _extract_placeholder_text(content)
if placeholder_text:
content = placeholder_text.encode('utf-8')
ext = 'txt'
content_type = 'text/plain; charset=utf-8'
current_app.logger.info('[file-preview] office preview degraded to text placeholder for %s', file_url)
else:
return jsonify({'error': 'failed to convert office file for preview'}), 422
fallback_types = { fallback_types = {
'pdf': 'application/pdf', 'pdf': 'application/pdf',
@@ -1101,4 +1254,6 @@ def preview_file_raw():
resp = Response(content, status=200, mimetype=mime) resp = Response(content, status=200, mimetype=mime)
resp.headers['Content-Disposition'] = f"{disposition_type}; filename=\"{ascii_filename}\"; filename*=UTF-8''{encoded_filename}" resp.headers['Content-Disposition'] = f"{disposition_type}; filename=\"{ascii_filename}\"; filename*=UTF-8''{encoded_filename}"
resp.headers['Cache-Control'] = 'no-store' resp.headers['Cache-Control'] = 'no-store'
resp.headers['X-Preview-Actual-Ext'] = ext or ''
resp.headers['X-Preview-Original-Ext'] = original_ext or ''
return resp return resp
+17 -3
View File
@@ -19,11 +19,25 @@ integration_bp = Blueprint('integration', __name__)
def _require_integration_key(): def _require_integration_key():
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip() configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
incoming = str(request.headers.get('X-Integration-Key') or '').strip() incoming = str(request.headers.get('X-Integration-Key') or '').strip()
if not configured: if not configured:
return jsonify({'error': 'INTEGRATION_API_KEY is not configured'}), 503 return jsonify({'error': 'INTEGRATION_API_KEY is not configured'}), 503
if configured != incoming:
return jsonify({'error': 'Unauthorized'}), 401 if configured == incoming:
return None return None
token = request.args.get('token')
if token:
try:
import jwt
secret = configured or str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
jwt.decode(token, secret, algorithms=['HS256'])
return None
except Exception as e:
current_app.logger.warning(f"Integration API token validation failed: {e}")
pass
return jsonify({'error': 'Unauthorized'}), 401
def _integration_base_url() -> str: def _integration_base_url() -> str:
+202 -56
View File
@@ -1,7 +1,7 @@
""" """
Integration API client for resolving original source-file download links. Integration API client for resolving original source-file download links.
""" """
from datetime import datetime from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional, Tuple from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse from urllib.parse import urlparse
@@ -14,6 +14,88 @@ from app.config import Config
class IntegrationApiService: class IntegrationApiService:
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {} _cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
@staticmethod
def _lookup_from_dify_document_api(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
"""
当集成映射服务缺失时,直接调用 Dify 数据集文档下载接口兜底。
适用于“检索已返回 document_id,但 8891 没有同步 source file mapping”的场景。
"""
if not dataset_id or not remote_document_id:
return None
try:
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
except Exception:
return None
try:
service = KbDifySyncService()
if not service.base_url or not service.api_key:
return None
document_payload = service.get_document(
dataset_id=str(dataset_id),
document_id=str(remote_document_id),
)
if not isinstance(document_payload, dict):
return None
download_resp = requests.get(
f"{service.base_url.rstrip('/')}/datasets/{dataset_id}/documents/{remote_document_id}/download",
headers=service._headers(),
timeout=(5, 15),
)
if download_resp.status_code != 200:
if has_app_context():
current_app.logger.info(
"Dify document download lookup missed: dataset_id=%s remote_document_id=%s status=%s",
dataset_id,
remote_document_id,
download_resp.status_code,
)
return None
download_payload = download_resp.json() if download_resp.content else {}
source_url = str((download_payload or {}).get("url") or "").strip()
if not source_url:
return None
upload_info = (
((document_payload.get("data_source_info") or {}).get("upload_file"))
if isinstance(document_payload.get("data_source_info"), dict)
else {}
) or {}
source_filename = str(
upload_info.get("name")
or document_payload.get("name")
or ""
).strip() or None
source_ext = str(
upload_info.get("extension")
or (source_filename.rsplit(".", 1)[-1] if source_filename and "." in source_filename else "")
).strip().lower() or None
# Dify 返回的签名下载地址通常是短效的,这里主动给缓存一个较短 TTL,避免长期复用旧链接。
expires_at = (datetime.now(timezone.utc) + timedelta(minutes=10)).isoformat()
return {
"source_download_url": source_url,
"source_filename": source_filename,
"source_ext": source_ext,
"download_url_expires_at": expires_at,
"version_id": None,
"document_id": remote_document_id,
}
except Exception as e:
if has_app_context():
current_app.logger.warning(
"Dify document API fallback lookup failed: dataset_id=%s remote_document_id=%s err=%s",
dataset_id,
remote_document_id,
e,
)
return None
@staticmethod @staticmethod
def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]: def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]:
if not isinstance(row, dict): if not isinstance(row, dict):
@@ -114,6 +196,63 @@ class IntegrationApiService:
return True return True
@staticmethod
def _lookup_local_db(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
if not has_app_context():
return None
from app import db
from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument
record = (
db.session.query(KbDifySyncRecord)
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
.filter(
KbDocument.is_deleted.is_(False),
KbDifySyncRecord.remote_document_id == remote_document_id,
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
.first()
)
if not record or not record.document_version or not record.document_version.document:
return None
version = record.document_version
document = version.document
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
if explicit:
base_url = explicit
elif has_request_context():
base_url = request.host_url.rstrip('/')
else:
base_url = ''
import time
import jwt
secret = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
if not secret:
secret = str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
exp = int(time.time()) + 86400 * 7 # 7 days expiration for local tokens
payload = {
'dataset_id': 'local',
'remote_document_id': remote_document_id,
'exp': exp
}
token = jwt.encode(payload, secret, algorithm='HS256')
source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source&token={token}'
return {
"source_download_url": source_download_url,
"source_filename": version.source_file_name,
"source_ext": version.source_file_ext,
"download_url_expires_at": None,
"version_id": version.id,
"document_id": document.id,
}
@staticmethod @staticmethod
def lookup_file_by_dify(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]: def lookup_file_by_dify(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
if not dataset_id or not remote_document_id: if not dataset_id or not remote_document_id:
@@ -169,25 +308,35 @@ class IntegrationApiService:
} }
try: try:
resp = requests.post(batch_url, headers=batch_headers, json=batch_body, timeout=(5, 12)) resp = requests.post(batch_url, headers=batch_headers, json=batch_body, timeout=(5, 12))
if resp.status_code != 200: if resp.status_code == 200:
return None payload = resp.json()
payload = resp.json() data = payload.get("data") if isinstance(payload, dict) else None
data = payload.get("data") if isinstance(payload, dict) else None if isinstance(data, list):
if not isinstance(data, list): for row in data:
return None normalized_row = IntegrationApiService._normalize_batch_row(row)
for row in data: if not normalized_row:
normalized_row = IntegrationApiService._normalize_batch_row(row) continue
if not normalized_row: key, normalized = normalized_row
continue IntegrationApiService._cache[key] = normalized
key, normalized = normalized_row if key == cache_key:
IntegrationApiService._cache[key] = normalized return normalized
if key == cache_key:
return normalized
return None
except Exception as e: except Exception as e:
if has_app_context(): if has_app_context():
current_app.logger.warning(f"Integration API batch fallback lookup failed: {e}") current_app.logger.warning(f"Integration API batch fallback lookup failed: {e}")
return None
# Fallback to local database if remote integration API fails or misses
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
if local_result:
IntegrationApiService._cache[cache_key] = local_result
return local_result
# Last fallback: query Dify document API directly and request a signed download URL.
dify_result = IntegrationApiService._lookup_from_dify_document_api(dataset_id, remote_document_id)
if dify_result:
IntegrationApiService._cache[cache_key] = dify_result
return dify_result
return None
@staticmethod @staticmethod
def lookup_files_by_dify(items: List[Dict[str, str]]) -> Dict[Tuple[str, str], Dict[str, Any]]: def lookup_files_by_dify(items: List[Dict[str, str]]) -> Dict[Tuple[str, str], Dict[str, Any]]:
@@ -243,45 +392,42 @@ class IntegrationApiService:
current_app.logger.warning( current_app.logger.warning(
"Integration API batch lookup failed: status=%s", resp.status_code "Integration API batch lookup failed: status=%s", resp.status_code
) )
# Fallback to single lookup for reliability. else:
for item in unresolved: payload = resp.json()
payload = IntegrationApiService.lookup_file_by_dify( data = payload.get("data") if isinstance(payload, dict) else None
item["dataset_id"], item["remote_document_id"] if isinstance(data, list):
) for row in data:
if payload: if not isinstance(row, dict):
key = IntegrationApiService._cache_key( continue
item["dataset_id"], item["remote_document_id"] normalized_row = IntegrationApiService._normalize_batch_row(row)
) if not normalized_row:
results[key] = payload continue
return results key, normalized = normalized_row
IntegrationApiService._cache[key] = normalized
payload = resp.json() results[key] = normalized
data = payload.get("data") if isinstance(payload, dict) else None
if not isinstance(data, list):
return results
for row in data:
if not isinstance(row, dict):
continue
normalized_row = IntegrationApiService._normalize_batch_row(row)
if not normalized_row:
continue
key, normalized = normalized_row
IntegrationApiService._cache[key] = normalized
results[key] = normalized
return results
except Exception as e: except Exception as e:
if has_app_context(): if has_app_context():
current_app.logger.warning(f"Integration API batch lookup exception: {e}") current_app.logger.warning(f"Integration API batch lookup exception: {e}")
# Fallback to single lookup when batch call errors.
for item in unresolved: # Fallback to single lookup or local DB for unresolved items
payload = IntegrationApiService.lookup_file_by_dify( for item in unresolved:
item["dataset_id"], item["remote_document_id"] dataset_id = item["dataset_id"]
) remote_document_id = item["remote_document_id"]
if payload: key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
key = IntegrationApiService._cache_key( if key in results:
item["dataset_id"], item["remote_document_id"] continue
)
results[key] = payload # Check if single lookup was not called already (if it was, it might be cached)
return results # Actually, `_lookup_local_db` should be checked directly since remote batch failed to find it.
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
if local_result:
IntegrationApiService._cache[key] = local_result
results[key] = local_result
continue
# As a last resort, try remote single lookup if batch missed it
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
if payload:
results[key] = payload
return results
+4 -3
View File
@@ -379,6 +379,7 @@ class Text2SQLService:
- 严禁生成任何 INSERT、UPDATE、DELETE、MERGE、ALTER、DROP、TRUNCATE、CREATE 语句。 - 严禁生成任何 INSERT、UPDATE、DELETE、MERGE、ALTER、DROP、TRUNCATE、CREATE 语句。
- 仅允许输出单条 SELECT 或 WITH 开头的查询。 - 仅允许输出单条 SELECT 或 WITH 开头的查询。
- 必须使用 Schema 中出现的精确表名,包含完整前缀,如 ERP_VIEW_USER.ERP_FAJ_FILE_V。 - 必须使用 Schema 中出现的精确表名,包含完整前缀,如 ERP_VIEW_USER.ERP_FAJ_FILE_V。
- 如果用户查询的是列表明细而非聚合总数(如“列出...”、“有哪些...”),你必须强制在 SQL 结尾添加 FETCH FIRST 50 ROWS ONLY,避免一次性返回几十万条数据导致系统崩溃。
- 必须只使用 Schema 中明确出现过的字段名,禁止臆造通用字段名,例如 FILE_TYPE、STATUS_NAME、AMOUNT 等。 - 必须只使用 Schema 中明确出现过的字段名,禁止臆造通用字段名,例如 FILE_TYPE、STATUS_NAME、AMOUNT 等。
- 优先选择最相关字段,避免 SELECT *。 - 优先选择最相关字段,避免 SELECT *。
- 当问题涉及“多少、总额、平均值、数量、占比、排名”时,请使用清晰的聚合逻辑与英文别名。 - 当问题涉及“多少、总额、平均值、数量、占比、排名”时,请使用清晰的聚合逻辑与英文别名。
@@ -500,7 +501,7 @@ class Text2SQLService:
final_conversation_id = conversation_id or f"erp_{int(time.time())}" final_conversation_id = conversation_id or f"erp_{int(time.time())}"
try: try:
# 1. Generate SQL # 1. Generate SQL
yield f"data: {json.dumps({'event': 'message', 'answer': '正在分析问题并生成 SQL...\n'})}\n\n" yield f"data: {json.dumps({'event': 'message', 'answer': '🧠 正在理解您的问题并生成底层查询代码 (SQL)...\n'})}\n\n"
stage_start = time.time() stage_start = time.time()
sql = Text2SQLService.generate_sql(query) sql = Text2SQLService.generate_sql(query)
generate_sql_ms = int((time.time() - stage_start) * 1000) generate_sql_ms = int((time.time() - stage_start) * 1000)
@@ -511,7 +512,7 @@ class Text2SQLService:
generate_sql_ms, generate_sql_ms,
(sql or "")[:300], (sql or "")[:300],
) )
yield f"data: {json.dumps({'event': 'message', 'answer': '已完成查询口径分析,正在查询数据库...\n'})}\n\n" yield f"data: {json.dumps({'event': 'message', 'answer': '🔍 已完成查询口径分析,正在数据库中检索海量数据,请稍候...\n'})}\n\n"
# 2. Execute SQL # 2. Execute SQL
stage_start = time.time() stage_start = time.time()
@@ -554,7 +555,7 @@ class Text2SQLService:
) )
# 3. Format result # 3. Format result
yield f"data: {json.dumps({'event': 'message', 'answer': '正在整理结果并生成业务汇总...\n'})}\n\n" yield f"data: {json.dumps({'event': 'message', 'answer': '📝 数据检索完成,正在生成最终业务报告...\n'})}\n\n"
stage_start = time.time() stage_start = time.time()
result_text = Text2SQLService.format_result(columns, rows, sql, query) result_text = Text2SQLService.format_result(columns, rows, sql, query)
format_result_ms = int((time.time() - stage_start) * 1000) format_result_ms = int((time.time() - stage_start) * 1000)
+99 -76
View File
@@ -54,6 +54,7 @@ const excelPreview = ref<ExcelPreviewData | null>(null);
const officeSrc = ref<string | ArrayBuffer | Blob>(''); const officeSrc = ref<string | ArrayBuffer | Blob>('');
const officeKind = ref<OfficeKind>(null); const officeKind = ref<OfficeKind>(null);
const officeObjectUrl = ref<string>(''); const officeObjectUrl = ref<string>('');
const officeRenderKey = ref(0);
/** /**
* 从 URL 或文件名中提取扩展名。 * 从 URL 或文件名中提取扩展名。
@@ -163,6 +164,66 @@ const clearOfficeObjectUrl = () => {
officeKind.value = null; officeKind.value = null;
}; };
const applyExcelPreview = (buffer: ArrayBuffer) => {
const workbook = XLSX.read(buffer, { type: 'array' });
if (!workbook.SheetNames.length) {
throw new Error('workbook has no sheets');
}
const sheetName = workbook.SheetNames[0] || 'Sheet1';
const worksheet = workbook.Sheets[sheetName];
if (!worksheet) {
throw new Error(`worksheet not found: ${sheetName}`);
}
const matrix = XLSX.utils.sheet_to_json<(string | number | boolean)[]>(worksheet, {
header: 1,
raw: false,
defval: '',
});
const limit = 100;
const rows = matrix.slice(0, limit).map((row) => row.map((cell) => cell ?? ''));
const maxCols = rows.reduce((max, row) => Math.max(max, row.length), 0);
const normalizedRows = rows.map((row) =>
row.length < maxCols ? [...row, ...Array(maxCols - row.length).fill('')] : row
);
excelPreview.value = {
sheet_name: sheetName,
sheets: workbook.SheetNames,
columns: Array.from({ length: maxCols }, (_, i) => `COL_${i + 1}`),
rows: normalizedRows,
limit,
truncated: matrix.length > limit,
};
};
const tryApplyExcelPreview = (buffer: ArrayBuffer) => {
try {
applyExcelPreview(buffer);
return true;
} catch {
return false;
}
};
const loadSheetPreview = async () => {
if (!props.file?.url) return;
if (!props.agentId) throw new Error('agent_id is required for excel preview');
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
});
const res = await fetch(`/api/chat/preview-excel?${params.toString()}`, {
headers: props.authHeaders || {},
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data?.error || `HTTP ${res.status}`);
}
excelPreview.value = await res.json();
};
const loadOfficeContent = async () => { const loadOfficeContent = async () => {
if (!props.file?.url) return; if (!props.file?.url) return;
if (!props.agentId) throw new Error('agent_id is required for office preview'); if (!props.agentId) throw new Error('agent_id is required for office preview');
@@ -180,20 +241,29 @@ const loadOfficeContent = async () => {
throw new Error(err?.error || `HTTP ${res.status}`); throw new Error(err?.error || `HTTP ${res.status}`);
} }
const blob = await res.blob(); const buffer = await res.arrayBuffer();
clearOfficeObjectUrl(); clearOfficeObjectUrl();
officeObjectUrl.value = URL.createObjectURL(blob); officeSrc.value = buffer;
officeSrc.value = officeObjectUrl.value; officeRenderKey.value += 1;
if (ext.value === 'docx' || ext.value === 'doc') officeKind.value = 'docx'; if (ext.value === 'docx' || ext.value === 'doc') officeKind.value = 'docx';
else if (ext.value === 'xlsx' || ext.value === 'xls') officeKind.value = 'excel'; else if (ext.value === 'xlsx' || ext.value === 'xls') officeKind.value = 'excel';
else officeKind.value = null; else officeKind.value = null;
}; };
const loadPdfContent = async () => { const loadPdfContent = async (): Promise<'iframe' | 'office' | 'sheet'> => {
if (!props.file?.url) return; if (!props.file?.url) return;
if (!props.agentId) throw new Error('agent_id is required for pdf preview'); if (!props.agentId) throw new Error('agent_id is required for pdf preview');
if (ext.value === 'doc') {
try {
await loadSheetPreview();
return 'sheet';
} catch {
// Not an excel-disguised-as-doc file, continue with the normal document preview flow.
}
}
const params = new URLSearchParams({ const params = new URLSearchParams({
agent_id: String(props.agentId), agent_id: String(props.agentId),
url: props.file.url, url: props.file.url,
@@ -209,11 +279,30 @@ const loadPdfContent = async () => {
const blob = await res.blob(); const blob = await res.blob();
clearOfficeObjectUrl(); clearOfficeObjectUrl();
const buffer = await blob.arrayBuffer();
const actualExt = (res.headers.get('X-Preview-Actual-Ext') || '').toLowerCase();
const blobType = (blob.type || '').toLowerCase();
const isDocxPayload = actualExt === 'docx' || blobType.includes('wordprocessingml.document');
const isExcelPayload = ['xlsx', 'xls'].includes(actualExt) || blobType.includes('spreadsheetml.sheet') || blobType.includes('application/vnd.ms-excel');
if (isExcelPayload) {
await loadSheetPreview();
return 'sheet';
}
if (!blobType.includes('pdf') && tryApplyExcelPreview(buffer)) {
return 'sheet';
}
if (isDocxPayload) {
officeSrc.value = buffer;
officeRenderKey.value += 1;
officeKind.value = 'docx';
return 'office';
}
let fallbackType = 'application/octet-stream'; let fallbackType = 'application/octet-stream';
if (ext.value === 'pdf' || ['doc', 'ppt', 'pptx'].includes(ext.value)) fallbackType = 'application/pdf'; if (ext.value === 'pdf' || ['doc', 'ppt', 'pptx'].includes(ext.value)) fallbackType = 'application/pdf';
else if (ext.value === 'docx') fallbackType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; else if (ext.value === 'docx') fallbackType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
const effectiveBlob = blob.type ? blob : new Blob([blob], { type: fallbackType }); const effectiveBlob = blob.type ? blob : new Blob([blob], { type: fallbackType });
officeObjectUrl.value = URL.createObjectURL(effectiveBlob); officeObjectUrl.value = URL.createObjectURL(effectiveBlob);
return 'iframe';
}; };
const loadBinaryContent = async () => { const loadBinaryContent = async () => {
@@ -263,8 +352,7 @@ const loadContent = async () => {
} }
isLoading.value = true; isLoading.value = true;
try { try {
await loadPdfContent(); // This fetches as Blob, and sets officeObjectUrl which will be used in iframeSrc resolvedMode.value = await loadPdfContent();
resolvedMode.value = 'iframe';
} catch (e: any) { } catch (e: any) {
error.value = e?.message || `Failed to preview ${ext.value}`; error.value = e?.message || `Failed to preview ${ext.value}`;
resolvedMode.value = 'iframe'; resolvedMode.value = 'iframe';
@@ -291,54 +379,9 @@ const loadContent = async () => {
return; return;
} }
if (preferredMode.value === 'sheet') { if (preferredMode.value === 'sheet') {
if (!props.agentId) {
error.value = 'agent_id is required for excel preview';
return;
}
isLoading.value = true; isLoading.value = true;
try { try {
const params = new URLSearchParams({ await loadSheetPreview();
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
});
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
headers: props.authHeaders || {},
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data?.error || `HTTP ${res.status}`);
}
const buffer = await res.arrayBuffer();
const workbook = XLSX.read(buffer, { type: 'array' });
if (!workbook.SheetNames.length) {
throw new Error('workbook has no sheets');
}
const sheetName = workbook.SheetNames[0] || 'Sheet1';
const worksheet = workbook.Sheets[sheetName];
if (!worksheet) {
throw new Error(`worksheet not found: ${sheetName}`);
}
const matrix = XLSX.utils.sheet_to_json<(string | number | boolean)[]>(worksheet, {
header: 1,
raw: false,
defval: '',
});
const limit = 100;
const rows = matrix.slice(0, limit).map((row) => row.map((cell) => cell ?? ''));
const maxCols = rows.reduce((max, row) => Math.max(max, row.length), 0);
const normalizedRows = rows.map((row) =>
row.length < maxCols ? [...row, ...Array(maxCols - row.length).fill('')] : row
);
excelPreview.value = {
sheet_name: sheetName,
sheets: workbook.SheetNames,
columns: Array.from({ length: maxCols }, (_, i) => `COL_${i + 1}`),
rows: normalizedRows,
limit,
truncated: matrix.length > limit,
};
resolvedMode.value = 'sheet'; resolvedMode.value = 'sheet';
} catch (e: any) { } catch (e: any) {
error.value = e?.message || 'Failed to preview excel'; error.value = e?.message || 'Failed to preview excel';
@@ -423,16 +466,6 @@ watch(
<div class="min-w-0"> <div class="min-w-0">
<div class="label-field tracking-wide">{{ t('filePreview.title') }}</div> <div class="label-field tracking-wide">{{ t('filePreview.title') }}</div>
<div class="mt-1 font-semibold text-primary break-words">{{ file.name }}</div> <div class="mt-1 font-semibold text-primary break-words">{{ file.name }}</div>
<button type="button" @click="downloadFile" :disabled="isDownloading" class="btn-secondary btn-sm mt-2 inline-flex border-brand-200 text-brand-700 hover:bg-brand-50 disabled:opacity-50 disabled:cursor-not-allowed">
<svg v-if="!isDownloading" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
<svg v-else class="animate-spin -ml-1 mr-2 h-4 w-4 text-brand-700" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{{ isDownloading ? t('filePreview.downloading') : t('filePreview.download') }}
</button>
</div> </div>
<button type="button" class="btn-secondary shrink-0" @click="close">{{ t('common.close') }}</button> <button type="button" class="btn-secondary shrink-0" @click="close">{{ t('common.close') }}</button>
</div> </div>
@@ -491,11 +524,15 @@ watch(
> >
<VueOfficeDocx <VueOfficeDocx
v-if="officeKind === 'docx'" v-if="officeKind === 'docx'"
:key="`docx-${officeRenderKey}`"
:src="officeSrc" :src="officeSrc"
@rendered="error = ''"
@error="error = 'DOCX render failed'"
style="height: 100%; width: 100%;" style="height: 100%; width: 100%;"
/> />
<VueOfficeExcel <VueOfficeExcel
v-else-if="officeKind === 'excel'" v-else-if="officeKind === 'excel'"
:key="`excel-${officeRenderKey}`"
:src="officeSrc" :src="officeSrc"
style="height: 100%; width: 100%;" style="height: 100%; width: 100%;"
/> />
@@ -523,20 +560,6 @@ watch(
<div class="mt-2 text-sm text-muted"> <div class="mt-2 text-sm text-muted">
This Office file uses a private or non-HTTPS link, so online preview cannot render it. This Office file uses a private or non-HTTPS link, so online preview cannot render it.
</div> </div>
<div class="mt-4 flex gap-3">
<button
type="button"
@click="downloadFile"
:disabled="isDownloading"
class="btn-primary btn-sm inline-flex"
>
<svg v-if="isDownloading" class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{{ isDownloading ? t('filePreview.downloading') : t('filePreview.download') }}
</button>
</div>
</div> </div>
<iframe <iframe
v-else v-else