From 900a13722c084b21987a26785ae0be824994d376 Mon Sep 17 00:00:00 2001 From: "DESKTOP-JKIE562\\PC" <1013397054@qq.com> Date: Mon, 8 Jun 2026 13:47:46 +0800 Subject: [PATCH] =?UTF-8?q?fex(kb):=E7=9F=A5=E8=AF=86=E5=BA=93=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E6=B8=85=E6=B4=97=E9=92=88=E5=AF=B9pdf=E5=90=AB?= =?UTF-8?q?=E6=9C=89=E5=A4=A7=E9=87=8F=E5=9B=BE=E7=89=87ocr=E6=B8=85?= =?UTF-8?q?=E6=B4=97=E8=B6=85=E6=97=B6=E9=97=AE=E9=A2=98=E4=BC=98=E5=8C=96?= =?UTF-8?q?=EF=BC=9Bperf(chat):=E9=97=AE=E7=AD=94=E5=9B=9E=E5=A4=8D?= =?UTF-8?q?=E7=82=B9=E5=87=BBdoc=E7=A7=BB=E5=8A=A8=E7=AB=AF=E6=97=A0?= =?UTF-8?q?=E6=B3=95=E9=A2=84=E8=A7=88=E9=97=AE=E9=A2=98=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/chat.py | 8 ++ backend/app/services/text2sql.py | 4 +- backend/edkb_system/skills/common.py | 37 +++++++- backend/edkb_system/skills/export.py | 10 ++- backend/edkb_system/skills/loader_pdf.py | 92 ++++++++++++++++++-- backend/edkb_system/skills/ocr.py | 17 +++- frontend/src/components/FilePreviewModal.vue | 18 +++- frontend/src/views/ChatView.vue | 2 +- 8 files changed, 170 insertions(+), 18 deletions(-) diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index b9ed72c7..47580079 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -1673,6 +1673,10 @@ def preview_file_raw(): content = _convert_office_to_pdf(content, ext) ext = 'pdf' content_type = 'application/pdf' + if name and '.' in name: + name = f"{name.rsplit('.', 1)[0]}.pdf" + elif name: + name = f"{name}.pdf" except Exception as e: current_app.logger.error("[file-preview] LibreOffice conversion failed: %s", e) placeholder_text = _extract_placeholder_text(content) @@ -1680,6 +1684,10 @@ def preview_file_raw(): content = placeholder_text.encode('utf-8') ext = 'txt' content_type = 'text/plain; charset=utf-8' + if name and '.' in name: + name = f"{name.rsplit('.', 1)[0]}.txt" + elif name: + name = f"{name}.txt" current_app.logger.info('[file-preview] office preview degraded to text placeholder for %s', file_url) else: raise AppError( diff --git a/backend/app/services/text2sql.py b/backend/app/services/text2sql.py index 252e92ae..94189acb 100644 --- a/backend/app/services/text2sql.py +++ b/backend/app/services/text2sql.py @@ -379,7 +379,6 @@ 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 *。 - 当问题涉及“多少、总额、平均值、数量、占比、排名”时,请使用清晰的聚合逻辑与英文别名。 @@ -459,7 +458,8 @@ class Text2SQLService: cursor.execute(sql) columns = [col[0] for col in cursor.description] - rows = cursor.fetchall() + # Use fetchmany(50) instead of LLM-generated FETCH FIRST to support older Oracle versions + rows = cursor.fetchmany(50) cursor.close() connection.close() diff --git a/backend/edkb_system/skills/common.py b/backend/edkb_system/skills/common.py index 05cddbdc..9aed779a 100644 --- a/backend/edkb_system/skills/common.py +++ b/backend/edkb_system/skills/common.py @@ -163,6 +163,26 @@ def _page_image_structured_lines(payload: str) -> list[str]: def blocks_to_plain_markdown(blocks: list[Block]) -> str: + def _is_meaningful_ocr_segment(text: str) -> bool: + token = re.sub(r"\s+", "", text or "") + if not token or re.fullmatch(r"[\W_]+", token): + return False + cjk_count = len(re.findall(r"[\u4e00-\u9fff]", token)) + alnum_count = len(re.findall(r"[A-Za-z0-9]", token)) + if cjk_count >= 2: + return True + if cjk_count >= 1 and len(token) >= 2: + return True + if alnum_count >= 5: + return True + return len(token) >= 4 + + def _is_rich_ocr_payload(payload: str) -> bool: + token = re.sub(r"\s+", "", payload or "") + cjk_count = len(re.findall(r"[\u4e00-\u9fff]", token)) + alnum_count = len(re.findall(r"[A-Za-z0-9]", token)) + return cjk_count >= 6 or alnum_count >= 12 or len(token) >= 20 + def _ocr_payload(txt: str) -> str: payload = txt if payload.startswith("OCR_TEXT:"): @@ -170,8 +190,12 @@ def blocks_to_plain_markdown(blocks: list[Block]) -> str: if not payload or payload == "": return "" payload = re.sub(r"(?m)^\s*-\s*", "", payload) - payload = ";".join(x.strip() for x in payload.splitlines() if x.strip()) - return payload + segments = [ + x.strip() + for x in payload.splitlines() + if x.strip() and _is_meaningful_ocr_segment(x.strip()) + ] + return ";".join(segments) ocr_by_image: dict[str, str] = {} for b in blocks: @@ -212,9 +236,14 @@ def blocks_to_plain_markdown(blocks: list[Block]) -> str: and b.meta.get("page_image_source") == "pdf" ) if is_pdf_page_image: - lines.append(f"![page-image-{b.page}]") ocr_text = ocr_by_image.get(b.id) - if ocr_text: + suppress_pdf_page_image = ( + page_body_chars.get(b.page, 0) >= 80 + or page_text_chars.get(b.page, 0) >= 120 + ) and not _is_rich_ocr_payload(ocr_text or "") + if not suppress_pdf_page_image: + lines.append(f"![page-image-{b.page}]") + if ocr_text and not suppress_pdf_page_image: lines.append(f"图中文字:{ocr_text}") elif data_uri: image_idx += 1 diff --git a/backend/edkb_system/skills/export.py b/backend/edkb_system/skills/export.py index ba7d63b7..149616b6 100644 --- a/backend/edkb_system/skills/export.py +++ b/backend/edkb_system/skills/export.py @@ -579,12 +579,16 @@ def run(input_data: dict, context: Context) -> dict: exported_chunks = [replace(c, text=rewriter.replace_text(c.text)) for c in chunks] rewriter.finalize() - preview_rewriter = _LocalPreviewImageRewriter(images_dir=view_images_dir) - preview_md = preview_rewriter.replace_text(clean_md) + preview_md = "" + needs_preview_assets = "data:image/" in clean_md + if needs_preview_assets: + preview_rewriter = _LocalPreviewImageRewriter(images_dir=view_images_dir) + preview_md = preview_rewriter.replace_text(clean_md) _write(out_dir / "03_clean.md", clean_md) _write(flat_clean_path, clean_md) - _write(view_clean_path, preview_md) + if needs_preview_assets: + _write(view_clean_path, preview_md) lines = [json.dumps(asdict(c), ensure_ascii=False) for c in exported_chunks] _write(out_dir / "04_chunks.jsonl", "\n".join(lines) + ("\n" if lines else "")) diff --git a/backend/edkb_system/skills/loader_pdf.py b/backend/edkb_system/skills/loader_pdf.py index 1c09d1e6..36532d94 100644 --- a/backend/edkb_system/skills/loader_pdf.py +++ b/backend/edkb_system/skills/loader_pdf.py @@ -8,12 +8,37 @@ from edkb_system.contracts import Block, Context _PAGE_IMAGE_RENDER_SCALE = 0.75 _PAGE_IMAGE_JPEG_QUALITY = 82 +_TEXT_HEAVY_PAGE_TEXT_LIMIT = 40 +_DEFAULT_PAGE_TEXT_LIMIT = 120 +_MIN_SCAN_IMAGE_BYTES = 4 * 1024 +_MIN_DEFAULT_IMAGE_BYTES = 16 * 1024 +_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) +def _is_text_heavy_pdf(text_chars: int, pages: int) -> bool: + return text_chars >= max(800, 180 * max(pages, 1)) + + +def _should_keep_embedded_image( + *, + data_size: int, + page_text_chars: int, + scan_likely: bool, + text_heavy_pdf: bool, +) -> bool: + if data_size <= 0: + return False + if scan_likely: + return data_size >= _MIN_SCAN_IMAGE_BYTES + if text_heavy_pdf: + return page_text_chars <= _TEXT_HEAVY_PAGE_TEXT_LIMIT and data_size >= _MIN_TEXT_HEAVY_IMAGE_BYTES + return page_text_chars <= 80 or data_size >= _MIN_DEFAULT_IMAGE_BYTES + + def _to_data_uri(blob: bytes, content_type: str = "image/png") -> str: b64 = base64.b64encode(blob).decode("ascii") return f"data:{content_type};base64,{b64}" @@ -62,32 +87,45 @@ def _page_image_stats( def _should_use_page_image_mode( *, scan_likely: bool, + text_heavy_pdf: bool, text_chars: int, image_count: int, largest_ratio: float, total_ratio: float, ) -> bool: + if text_heavy_pdf and text_chars > _TEXT_HEAVY_PAGE_TEXT_LIMIT: + return False if scan_likely: if image_count == 0: return True if largest_ratio >= 0.55 or total_ratio >= 0.65 or image_count >= 3: return True - if text_chars <= 120 and ( + if text_chars <= _DEFAULT_PAGE_TEXT_LIMIT and ( largest_ratio >= 0.72 or (image_count >= 5 and total_ratio >= 0.45) ): return True + if text_heavy_pdf: + return text_chars <= _TEXT_HEAVY_PAGE_TEXT_LIMIT and ( + largest_ratio >= 0.88 or total_ratio >= 0.95 or image_count >= 8 + ) return False def _analysis_candidate_pages( - page_payloads: list[dict], scan_likely: bool + page_payloads: list[dict], scan_likely: bool, text_heavy_pdf: bool ) -> list[int]: if scan_likely: return [int(payload["page"]) for payload in page_payloads] + if text_heavy_pdf: + return [ + int(payload["page"]) + for payload in page_payloads + if len(str(payload.get("text") or "")) <= _TEXT_HEAVY_PAGE_TEXT_LIMIT + ] return [ int(payload["page"]) for payload in page_payloads - if len(str(payload.get("text") or "")) <= 120 + if len(str(payload.get("text") or "")) <= _DEFAULT_PAGE_TEXT_LIMIT ] @@ -193,21 +231,56 @@ def run(input_data: dict, context: Context) -> list[Block]: images: list[dict] = [] if text: text_chars += len(text) + try: + page_width = float(getattr(getattr(p, "mediabox", None), "width", 1000.0) or 1000.0) + page_height = float(getattr(getattr(p, "mediabox", None), "height", 1000.0) or 1000.0) + except Exception: + page_width = 1000.0 + page_height = 1000.0 try: for img_idx, img in enumerate(getattr(p, "images", []) or [], start=1): data = getattr(img, "data", None) if not data: continue + if not _should_keep_embedded_image( + data_size=len(data), + page_text_chars=len(text), + scan_likely=False, + text_heavy_pdf=False, + ): + continue ext = (getattr(img, "image_format", "") or "").lower() ct = f"image/{ext}" if ext else "image/png" images.append({"id": img_idx, "data": data, "content_type": ct}) except Exception: pass - page_payloads.append({"page": page_idx, "text": text, "images": images}) + page_payloads.append( + { + "page": page_idx, + "text": text, + "images": images, + "page_width": page_width, + "page_height": page_height, + } + ) scan_likely = _is_scanned(text_chars, context.pages) - candidate_pages = _analysis_candidate_pages(page_payloads, scan_likely) + text_heavy_pdf = _is_text_heavy_pdf(text_chars, context.pages) + for payload in page_payloads: + payload["images"] = [ + item + for item in payload["images"] + if _should_keep_embedded_image( + data_size=len(item.get("data") or b""), + page_text_chars=len(str(payload.get("text") or "")), + scan_likely=scan_likely, + text_heavy_pdf=text_heavy_pdf, + ) + ] + candidate_pages = _analysis_candidate_pages( + page_payloads, scan_likely, text_heavy_pdf + ) image_boxes_by_page: dict[int, list[tuple[float, float, float, float]]] = {} pdfium_doc = None if candidate_pages: @@ -227,9 +300,14 @@ def run(input_data: dict, context: Context) -> list[Block]: text = str(payload["text"] or "") page_images = list(payload["images"]) image_boxes = image_boxes_by_page.get(page_idx, []) - stats = _page_image_stats(1000.0, 1000.0, image_boxes) + stats = _page_image_stats( + float(payload.get("page_width") or 1000.0), + float(payload.get("page_height") or 1000.0), + image_boxes, + ) use_page_image_mode = _should_use_page_image_mode( scan_likely=scan_likely, + text_heavy_pdf=text_heavy_pdf, text_chars=len(text), image_count=len(page_images) or int(stats["count"]), largest_ratio=float(stats["largest_ratio"]), @@ -292,6 +370,8 @@ def run(input_data: dict, context: Context) -> list[Block]: if scan_likely: context.warnings.append("pdf likely scanned; OCR recommended") context.extras["scan_likely"] = True + if text_heavy_pdf: + context.extras["text_heavy_pdf"] = True if page_image_mode_pages: context.extras["pdf_page_image_mode_pages"] = page_image_mode_pages context.warnings.append( diff --git a/backend/edkb_system/skills/ocr.py b/backend/edkb_system/skills/ocr.py index c21c0fde..e7b05b44 100644 --- a/backend/edkb_system/skills/ocr.py +++ b/backend/edkb_system/skills/ocr.py @@ -10,6 +10,21 @@ _RAPID_OCR_ENGINE = None _PDF_PAGE_IMAGE_MAX_EDGE = 1800 +def _is_meaningful_ocr_line(text: str) -> bool: + token = re.sub(r"\s+", "", text or "") + if not token or re.fullmatch(r"[\W_]+", token): + return False + cjk_count = len(re.findall(r"[\u4e00-\u9fff]", token)) + alnum_count = len(re.findall(r"[A-Za-z0-9]", token)) + if cjk_count >= 2: + return True + if cjk_count >= 1 and len(token) >= 2: + return True + if alnum_count >= 5: + return True + return len(token) >= 4 + + def _decode_data_uri_image(data_uri: str): m = re.match(r"^data:image/[^;]+;base64,(.+)$", data_uri or "", re.DOTALL) if not m: @@ -120,7 +135,7 @@ def run( continue txt = str(it[1]).strip() conf = float(it[2]) - if txt and conf >= min_confidence: + if txt and conf >= min_confidence and _is_meaningful_ocr_line(txt): lines.append(txt) if lines: text = "OCR_TEXT:\n" + "\n".join(f"- {x}" for x in lines) diff --git a/frontend/src/components/FilePreviewModal.vue b/frontend/src/components/FilePreviewModal.vue index 1452f8ea..8f296563 100644 --- a/frontend/src/components/FilePreviewModal.vue +++ b/frontend/src/components/FilePreviewModal.vue @@ -14,6 +14,7 @@ import { marked } from 'marked'; import * as XLSX from 'xlsx'; import VueOfficeDocx from '@vue-office/docx'; import VueOfficeExcel from '@vue-office/excel'; +import VueOfficePdf from '@vue-office/pdf'; import '@vue-office/docx/lib/index.css'; import '@vue-office/excel/lib/index.css'; @@ -32,7 +33,7 @@ interface ExcelPreviewData { truncated: boolean; } -type OfficeKind = 'docx' | 'excel' | null; +type OfficeKind = 'docx' | 'excel' | 'pdf' | null; type PreviewMode = 'markdown' | 'image' | 'iframe' | 'sheet' | 'office'; const props = defineProps<{ @@ -290,6 +291,15 @@ const loadPdfContent = async (): Promise<'iframe' | 'office' | 'sheet'> => { 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 }); + if ( + ['doc', 'ppt', 'pptx'].includes(ext.value) + && effectiveBlob.type.toLowerCase().includes('pdf') + ) { + officeSrc.value = effectiveBlob; + officeRenderKey.value += 1; + officeKind.value = 'pdf'; + return 'office'; + } officeObjectUrl.value = URL.createObjectURL(effectiveBlob); return 'iframe'; }; @@ -525,6 +535,12 @@ watch( :src="officeSrc" style="height: 100%; width: 100%;" /> +
diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index d1e61286..92355651 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -618,7 +618,7 @@ const shouldBypassEmbeddedPreview = (file: { name?: string; url?: string; actual const ext = getSourcePreviewExt(file); if (!isMobile.value || !isWeComMobileWebView()) return false; if (!/^https?:\/\//i.test(file?.url || '')) return false; - return ['pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'].includes(ext); + return ['pdf', 'xls', 'xlsx'].includes(ext); }; const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string; url: string; actualExt?: string }> => {