From 7f66d6f20cc336e12dad83b148b2b1a37d4306a2 Mon Sep 17 00:00:00 2001 From: "DESKTOP-JKIE562\\PC" <1013397054@qq.com> Date: Sat, 30 May 2026 14:10:44 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=87=E4=BB=B6=E9=A2=84=E8=A7=88=E4=BC=98?= =?UTF-8?q?=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/chat.py | 209 +++++++++++++-- backend/app/api/integration.py | 20 +- backend/app/services/integration_api.py | 258 +++++++++++++++---- backend/app/services/text2sql.py | 7 +- frontend/src/components/FilePreviewModal.vue | 175 +++++++------ 5 files changed, 504 insertions(+), 165 deletions(-) diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index 37231092..1e787421 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -71,6 +71,13 @@ def _is_allowed_preview_url(target_url: str) -> bool: integration_host = (urlparse(integration_base).hostname or "").strip().lower() if integration_host and host == integration_host: 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"): return True @@ -80,7 +87,7 @@ def _is_allowed_preview_url(target_url: str) -> bool: return ip.is_private or ip.is_loopback except ValueError: # 非 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: 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): 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 + return next_headers 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) 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) 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: """ - 使用 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}") with open(input_path, 'wb') as f: f.write(content) @@ -283,6 +318,9 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes: # 如果 LibreOffice 失败,且是在 Windows 系统下,尝试调用本地安装的 WPS 或 MS Office if not success and os.name == 'nt': + app = None + doc_obj = None + pythoncom = None try: import win32com.client import pythoncom @@ -291,14 +329,42 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes: if ext in ('doc', 'docx'): 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: - app = win32com.client.Dispatch("Word.Application") # 回退 MS Word + app = win32com.client.Dispatch("KWPS.Application") app.Visible = False - doc = app.Documents.Open(os.path.abspath(input_path)) - doc.SaveAs(os.path.abspath(output_path), FileFormat=17) # 17 = wdFormatPDF - doc.Close() - app.Quit() + app.DisplayAlerts = False + input_abs = os.path.abspath(input_path) + output_abs = os.path.abspath(output_path) + 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 elif ext in ('ppt', 'pptx'): @@ -307,10 +373,12 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes: except Exception: app = win32com.client.Dispatch("PowerPoint.Application") # 回退 MS PPT app.Visible = False - presentation = app.Presentations.Open(os.path.abspath(input_path), WithWindow=False) - presentation.SaveAs(os.path.abspath(output_path), 32) # 32 = ppSaveAsPDF - presentation.Close() - app.Quit() + try: + app.DisplayAlerts = False + except Exception: + 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 elif ext in ('xls', 'xlsx'): @@ -319,15 +387,30 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes: except Exception: app = win32com.client.Dispatch("Excel.Application") # 回退 MS Excel app.Visible = False - wb = app.Workbooks.Open(os.path.abspath(input_path)) - wb.ExportAsFixedFormat(0, os.path.abspath(output_path)) # 0 = xlTypePDF - wb.Close(False) - app.Quit() + app.DisplayAlerts = False + doc_obj = app.Workbooks.Open(os.path.abspath(input_path), ReadOnly=True) + doc_obj.ExportAsFixedFormat(0, os.path.abspath(output_path)) # 0 = xlTypePDF success = True except ImportError: current_app.logger.warning("pywin32 not installed, cannot fallback to WPS/MS Office COM API.") except Exception as 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: 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() else: 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: @@ -911,8 +996,6 @@ def preview_excel(): name = (request.args.get('name') or '').strip() name_ext = (name.split('.')[-1] if '.' in name else '').lower() 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: limit = int(request.args.get('limit', 100)) @@ -925,10 +1008,13 @@ def preview_excel(): msg, code = err 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: - wb = _load_excel_workbook(content, ext) + wb = _load_excel_workbook(content, detected_ext) except Exception as e: - detected_ext = _detect_excel_format(content or b'', ext) current_app.logger.warning( "[excel-preview] parse workbook failed ext=%s detected_ext=%s size=%s name=%s url=%s err=%r", ext, @@ -1032,13 +1118,55 @@ 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']) @require_agent_permission def preview_file_raw(): """ 二进制文件内网代理预览接口。 用途: - - 为 pdf/doc/docx 生成可被前端 iframe 访问的同源地址; + - 为 pdf/doc/docx 生成可被前端 iframe 访问的同源地址; - 尽量使用 inline 响应头,避免强制下载。 """ file_url = (request.args.get('url') or '').strip() @@ -1051,7 +1179,8 @@ def preview_file_raw(): url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower() name = (request.args.get('name') or '').strip() 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' max_size = None if is_download else 15 * 1024 * 1024 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 return jsonify({'error': msg}), code - # 如果是无法纯前端渲染的旧版 Office 或 PPT 格式,尝试转为 PDF 供前端统一渲染 - if ext in ('doc', 'ppt', 'pptx') and request.args.get('download') != '1': + # 根据文件二进制头部纠正扩展名,防止文件本身是 docx 却被命名为 doc,导致转换或下载后乱码 + 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: content = _convert_office_to_pdf(content, ext) ext = 'pdf' content_type = 'application/pdf' except Exception as 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 = { 'pdf': 'application/pdf', @@ -1101,4 +1254,6 @@ def preview_file_raw(): resp = Response(content, status=200, mimetype=mime) resp.headers['Content-Disposition'] = f"{disposition_type}; filename=\"{ascii_filename}\"; filename*=UTF-8''{encoded_filename}" 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 diff --git a/backend/app/api/integration.py b/backend/app/api/integration.py index f5571285..d3b09fa0 100644 --- a/backend/app/api/integration.py +++ b/backend/app/api/integration.py @@ -19,11 +19,25 @@ integration_bp = Blueprint('integration', __name__) def _require_integration_key(): configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip() incoming = str(request.headers.get('X-Integration-Key') or '').strip() + if not configured: return jsonify({'error': 'INTEGRATION_API_KEY is not configured'}), 503 - if configured != incoming: - return jsonify({'error': 'Unauthorized'}), 401 - return None + + if configured == incoming: + 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: diff --git a/backend/app/services/integration_api.py b/backend/app/services/integration_api.py index 4a629c72..3227bc39 100644 --- a/backend/app/services/integration_api.py +++ b/backend/app/services/integration_api.py @@ -1,7 +1,7 @@ """ 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 urllib.parse import urlparse @@ -14,6 +14,88 @@ from app.config import Config class IntegrationApiService: _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 def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]: if not isinstance(row, dict): @@ -114,6 +196,63 @@ class IntegrationApiService: 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 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: @@ -169,25 +308,35 @@ class IntegrationApiService: } try: resp = requests.post(batch_url, headers=batch_headers, json=batch_body, timeout=(5, 12)) - if resp.status_code != 200: - return None - payload = resp.json() - data = payload.get("data") if isinstance(payload, dict) else None - if not isinstance(data, list): - return None - for row in data: - normalized_row = IntegrationApiService._normalize_batch_row(row) - if not normalized_row: - continue - key, normalized = normalized_row - IntegrationApiService._cache[key] = normalized - if key == cache_key: - return normalized - return None + if resp.status_code == 200: + payload = resp.json() + data = payload.get("data") if isinstance(payload, dict) else None + if isinstance(data, list): + for row in data: + normalized_row = IntegrationApiService._normalize_batch_row(row) + if not normalized_row: + continue + key, normalized = normalized_row + IntegrationApiService._cache[key] = normalized + if key == cache_key: + return normalized except Exception as e: if has_app_context(): 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 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( "Integration API batch lookup failed: status=%s", resp.status_code ) - # Fallback to single lookup for reliability. - for item in unresolved: - payload = IntegrationApiService.lookup_file_by_dify( - item["dataset_id"], item["remote_document_id"] - ) - if payload: - key = IntegrationApiService._cache_key( - item["dataset_id"], item["remote_document_id"] - ) - results[key] = payload - return results - - payload = resp.json() - 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 + else: + payload = resp.json() + data = payload.get("data") if isinstance(payload, dict) else None + if isinstance(data, list): + 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 except Exception as e: if has_app_context(): current_app.logger.warning(f"Integration API batch lookup exception: {e}") - # Fallback to single lookup when batch call errors. - for item in unresolved: - payload = IntegrationApiService.lookup_file_by_dify( - item["dataset_id"], item["remote_document_id"] - ) - if payload: - key = IntegrationApiService._cache_key( - item["dataset_id"], item["remote_document_id"] - ) - results[key] = payload - return results + + # Fallback to single lookup or local DB for unresolved items + for item in unresolved: + dataset_id = item["dataset_id"] + remote_document_id = item["remote_document_id"] + key = IntegrationApiService._cache_key(dataset_id, remote_document_id) + if key in results: + continue + + # Check if single lookup was not called already (if it was, it might be cached) + # 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 diff --git a/backend/app/services/text2sql.py b/backend/app/services/text2sql.py index 0a4af12c..3103df8c 100644 --- a/backend/app/services/text2sql.py +++ b/backend/app/services/text2sql.py @@ -379,6 +379,7 @@ class Text2SQLService: - 严禁生成任何 INSERT、UPDATE、DELETE、MERGE、ALTER、DROP、TRUNCATE、CREATE 语句。 - 仅允许输出单条 SELECT 或 WITH 开头的查询。 - 必须使用 Schema 中出现的精确表名,包含完整前缀,如 ERP_VIEW_USER.ERP_FAJ_FILE_V。 +- 如果用户查询的是列表明细而非聚合总数(如“列出...”、“有哪些...”),你必须强制在 SQL 结尾添加 FETCH FIRST 50 ROWS ONLY,避免一次性返回几十万条数据导致系统崩溃。 - 必须只使用 Schema 中明确出现过的字段名,禁止臆造通用字段名,例如 FILE_TYPE、STATUS_NAME、AMOUNT 等。 - 优先选择最相关字段,避免 SELECT *。 - 当问题涉及“多少、总额、平均值、数量、占比、排名”时,请使用清晰的聚合逻辑与英文别名。 @@ -500,7 +501,7 @@ class Text2SQLService: final_conversation_id = conversation_id or f"erp_{int(time.time())}" try: # 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() sql = Text2SQLService.generate_sql(query) generate_sql_ms = int((time.time() - stage_start) * 1000) @@ -511,7 +512,7 @@ class Text2SQLService: generate_sql_ms, (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 stage_start = time.time() @@ -554,7 +555,7 @@ class Text2SQLService: ) # 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() result_text = Text2SQLService.format_result(columns, rows, sql, query) format_result_ms = int((time.time() - stage_start) * 1000) diff --git a/frontend/src/components/FilePreviewModal.vue b/frontend/src/components/FilePreviewModal.vue index b4e0db31..cc7fb043 100644 --- a/frontend/src/components/FilePreviewModal.vue +++ b/frontend/src/components/FilePreviewModal.vue @@ -54,6 +54,7 @@ const excelPreview = ref(null); const officeSrc = ref(''); const officeKind = ref(null); const officeObjectUrl = ref(''); +const officeRenderKey = ref(0); /** * 从 URL 或文件名中提取扩展名。 @@ -163,6 +164,66 @@ const clearOfficeObjectUrl = () => { 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 () => { if (!props.file?.url) return; 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}`); } - const blob = await res.blob(); + const buffer = await res.arrayBuffer(); clearOfficeObjectUrl(); - officeObjectUrl.value = URL.createObjectURL(blob); - officeSrc.value = officeObjectUrl.value; + officeSrc.value = buffer; + officeRenderKey.value += 1; if (ext.value === 'docx' || ext.value === 'doc') officeKind.value = 'docx'; else if (ext.value === 'xlsx' || ext.value === 'xls') officeKind.value = 'excel'; else officeKind.value = null; }; -const loadPdfContent = async () => { +const loadPdfContent = async (): Promise<'iframe' | 'office' | 'sheet'> => { if (!props.file?.url) return; 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({ agent_id: String(props.agentId), url: props.file.url, @@ -209,11 +279,30 @@ const loadPdfContent = async () => { const blob = await res.blob(); 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'; 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'; const effectiveBlob = blob.type ? blob : new Blob([blob], { type: fallbackType }); officeObjectUrl.value = URL.createObjectURL(effectiveBlob); + return 'iframe'; }; const loadBinaryContent = async () => { @@ -263,8 +352,7 @@ const loadContent = async () => { } isLoading.value = true; try { - await loadPdfContent(); // This fetches as Blob, and sets officeObjectUrl which will be used in iframeSrc - resolvedMode.value = 'iframe'; + resolvedMode.value = await loadPdfContent(); } catch (e: any) { error.value = e?.message || `Failed to preview ${ext.value}`; resolvedMode.value = 'iframe'; @@ -291,54 +379,9 @@ const loadContent = async () => { return; } if (preferredMode.value === 'sheet') { - if (!props.agentId) { - error.value = 'agent_id is required for excel preview'; - return; - } isLoading.value = true; try { - const params = new URLSearchParams({ - 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, - }; + await loadSheetPreview(); resolvedMode.value = 'sheet'; } catch (e: any) { error.value = e?.message || 'Failed to preview excel'; @@ -423,16 +466,6 @@ watch(
{{ t('filePreview.title') }}
{{ file.name }}
-
@@ -491,11 +524,15 @@ watch( > @@ -523,20 +560,6 @@ watch(
This Office file uses a private or non-HTTPS link, so online preview cannot render it.
-
- -