diff --git a/backend/app/services/knowledge_cleaning/dify_sync_service.py b/backend/app/services/knowledge_cleaning/dify_sync_service.py index 99569c2a..18148b8a 100644 --- a/backend/app/services/knowledge_cleaning/dify_sync_service.py +++ b/backend/app/services/knowledge_cleaning/dify_sync_service.py @@ -6,6 +6,7 @@ from __future__ import annotations from datetime import datetime import hashlib +import re from pathlib import Path import requests @@ -207,6 +208,13 @@ class KbDifySyncService: ) +def _strip_base64_images(text: str) -> str: + """Remove markdown image syntax containing base64 data to avoid token bloat in Dify.""" + # Matches ![alt](data:image/...) + pattern = r'!\[[^\]]*\]\(data:image\/[a-zA-Z]*;base64,[^)]*\)' + return re.sub(pattern, '', text) + + def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]: candidate_paths = [version.cleaned_file_path, version.cleaned_preview_path, version.source_file_path] for value in candidate_paths: @@ -217,6 +225,8 @@ def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]: continue text = path.read_text(encoding='utf-8', errors='ignore').strip() if text: + # Strip base64 images before syncing + text = _strip_base64_images(text) return text, str(path) raise KbDifySyncError('没有可用于同步的文本结果') diff --git a/backend/edkb_system/skills/loader_excel.py b/backend/edkb_system/skills/loader_excel.py index e060169c..a2340d7d 100644 --- a/backend/edkb_system/skills/loader_excel.py +++ b/backend/edkb_system/skills/loader_excel.py @@ -9,17 +9,39 @@ from __future__ import annotations from pathlib import Path -from openpyxl import load_workbook +from openpyxl import load_workbook, Workbook from edkb_system.contracts import Context from edkb_system.skills.soffice_util import convert_with_soffice, soffice_candidates +from edkb_system.skills.excel_bridge import convert_with_excel + + +def _convert_xls_to_xlsx_python(path: Path, output: Path) -> Path: + """使用 xlrd 和 openpyxl 进行纯 Python 转换。""" + import xlrd + + book = xlrd.open_workbook(str(path)) + wb = Workbook() + wb.remove(wb.active) # 移除默认的 Sheet + + for i in range(book.nsheets): + sheet = book.sheet_by_index(i) + new_ws = wb.create_sheet(title=sheet.name) + for row in range(sheet.nrows): + # 将 xlrd 的行值(list)追加到 openpyxl 的 sheet 中 + new_ws.append(sheet.row_values(row)) + + wb.save(str(output)) + return output def _convert_xls_to_xlsx(path: Path, out_dir: Path) -> Path: - """将 .xls 转为 .xlsx;soffice 调用带超时,见 EDKB_SOFFICE_TIMEOUT_SEC。""" + """将 .xls 转为 .xlsx。依次尝试 soffice、Excel COM 和 xlrd。""" out_dir.mkdir(parents=True, exist_ok=True) output = out_dir / f"{path.stem}.xlsx" errors: list[str] = [] + + # 1. 尝试 LibreOffice (soffice) for soffice in soffice_candidates(): if not soffice: continue @@ -30,22 +52,31 @@ def _convert_xls_to_xlsx(path: Path, out_dir: Path) -> Path: source_path=path, out_dir=out_dir, ) - except FileNotFoundError: - errors.append(f"soffice not found: {soffice}") - continue - except RuntimeError as exc: - errors.append(str(exc)) - continue - if proc.returncode == 0 and output.exists(): - return output - stderr = (proc.stderr or "").strip() - errors.append( - f"soffice failed ({soffice}, code={proc.returncode}): {stderr or 'no stderr'}" - ) + if proc.returncode == 0 and output.exists(): + return output + stderr = (proc.stderr or "").strip() + errors.append( + f"soffice failed ({soffice}, code={proc.returncode}): {stderr or 'no stderr'}" + ) + except Exception as exc: + errors.append(f"soffice attempt failed ({soffice}): {exc}") + + # 2. Windows 环境下尝试 Excel COM + if os.name == "nt": + try: + return convert_with_excel(path, output) + except Exception as exc: + errors.append(f"Excel COM conversion failed: {exc}") + + # 3. 最后尝试纯 Python (xlrd) + try: + return _convert_xls_to_xlsx_python(path, output) + except Exception as exc: + errors.append(f"Python xlrd conversion failed: {exc}") joined = "; ".join(errors) if errors else "no converter attempted" raise RuntimeError( - ".xls 转 .xlsx 失败。请安装 LibreOffice(soffice)或设置 EDKB_SOFFICE。" + ".xls 转 .xlsx 失败。请安装 LibreOffice(soffice)、Microsoft Excel 或检查文件。" f" details: {joined}" ) @@ -62,6 +93,7 @@ def _trim_trailing_empty(vals: list[str]) -> list[str]: def run(input_data: dict, context: Context) -> list[dict]: + import os file_path = Path(input_data["file_path"]) work_dir = Path(input_data["work_dir"]) if file_path.suffix.lower() == ".xls": diff --git a/backend/edkb_system/skills/loader_pdf.py b/backend/edkb_system/skills/loader_pdf.py index 36532d94..052c189e 100644 --- a/backend/edkb_system/skills/loader_pdf.py +++ b/backend/edkb_system/skills/loader_pdf.py @@ -16,7 +16,7 @@ _MIN_TEXT_HEAVY_IMAGE_BYTES = 24 * 1024 def _is_scanned(text_chars: int, pages: int) -> bool: - return text_chars < int(300 * max(pages, 1) / 10) + return text_chars < int(150 * max(pages, 1)) def _is_text_heavy_pdf(text_chars: int, pages: int) -> bool: diff --git a/backend/requirements.txt b/backend/requirements.txt index 99abc2e2..8eb50066 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -32,6 +32,7 @@ pypdfium2==5.0.0 python-pptx==1.0.2 beautifulsoup4==4.14.2 lxml==6.0.2 +xlrd==2.0.1 typer==0.17.4 croniter pyyaml