image_to_excel.py 33.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
# -*- coding: utf-8 -*-
"""
文件名: tests/image_to_excel.py
职责: 将表格截图转为 Excel 文件。支持两种引擎:
      1. paddle(默认,推荐)—— PaddleOCR + PP-Structure,本地 OCR + 表格结构识别
      2. llm —— 调用 Qwen VL 视觉大模型解析(需要 API Key, 适用于复杂/非标准表格)
用法:
    python tests/image_to_excel.py <image_path>                                    # 默认 PaddleOCR
    python tests/image_to_excel.py <image_path> --engine paddle                    # 显式指定 PaddleOCR
    python tests/image_to_excel.py <image_path> --engine llm --api-key xxx         # 使用 LLM
    python tests/image_to_excel.py <image_path> --output output.xlsx
    python tests/image_to_excel.py <image_path> --engine llm --split 3             # LLM 长图分片模式
"""

import os
import sys
import json
import re
import io
import base64
import asyncio
import argparse
import logging
import numpy as np
from pathlib import Path

import httpx
import pandas as pd
from PIL import Image

# 确保项目根目录在 Python 路径中
_BASE_DIR = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(_BASE_DIR))

from app.core.config import settings

logger = logging.getLogger("image_to_excel")

# 默认缩放参数:最长边不超过此值,JPEG 质量
DEFAULT_MAX_SIZE = 2048
DEFAULT_QUALITY = 85


# =============================================================================
#  通用工具函数
# =============================================================================

def _normalize_cell(value):
    """清理 OCR 识别的单元格文本:去掉多余空格/换行,尝试保留数字类型。"""
    if value is None or (isinstance(value, float) and pd.isna(value)):
        return None
    s = str(value).strip()
    # 合并多余空白
    s = re.sub(r"\s+", " ", s)
    if s == "":
        return None
    # 尝试转数字
    try:
        if "." in s:
            return float(s)
        return int(s)
    except ValueError:
        pass
    return s


def _write_table_to_excel(table_data: dict, output_path: str, sheet_name: str = "Sheet1"):
    """将 table_data (headers + rows) 写入 Excel 并自适应列宽。"""
    headers = table_data.get("headers", [])
    rows = table_data.get("rows", [])

    if not headers and not rows:
        raise ValueError("表格数据为空,无法写入 Excel")

    # 如果没有表头但有数据行,生成默认列名
    if not headers and rows:
        max_cols = max(len(r) for r in rows)
        headers = [f"列{i+1}" for i in range(max_cols)]
    elif headers:
        max_cols = len(headers)
    else:
        max_cols = 0

    # 补齐不等长的行
    padded_rows = []
    for r in rows:
        if len(r) < max_cols:
            r = list(r) + [None] * (max_cols - len(r))
        elif len(r) > max_cols:
            r = r[:max_cols]
        # 规范化每个单元格
        r = [_normalize_cell(v) for v in r]
        padded_rows.append(r)

    df = pd.DataFrame(padded_rows, columns=headers)

    with pd.ExcelWriter(output_path, engine="openpyxl") as writer:
        df.to_excel(writer, index=False, sheet_name=sheet_name)
        worksheet = writer.sheets[sheet_name]

        for column in worksheet.columns:
            max_length = 0
            col_letter = column[0].column_letter
            for cell in column:
                try:
                    length = len(str(cell.value)) if cell.value is not None else 0
                    if length > max_length:
                        max_length = length
                except Exception:
                    pass
            adjusted = min(max_length + 2, 40)
            worksheet.column_dimensions[col_letter].width = max(adjusted, 8)

    return output_path


# =============================================================================
#  PaddleOCR + PP-Structure 引擎(推荐,本地 OCR 表格识别)
# =============================================================================

def _call_paddle_structure(image_path: str) -> list:
    """
    使用 PaddleOCR PP-Structure 识别图片中的表格。
    返回 list[dict],每个 dict 为 {"headers": [...], "rows": [[...], ...]}。
    一张图片可能包含多个表格,每个表格对应 Excel 的一个 sheet。
    """
    from paddleocr import PPStructureV3

    # 禁用 oneDNN,避免 Windows + Python 3.13 + Paddle 3.3 的 PIR 算子 bug
    # NotImplementedError: ConvertPirAttribute2RuntimeAttribute not support
    #   [pir::ArrayAttribute<pir::DoubleAttribute>]  at onednn_instruction.cc:118
    import paddle
    paddle.set_flags({"FLAGS_use_mkldnn": False})

    path = Path(image_path)
    if not path.exists():
        raise FileNotFoundError(f"图片不存在: {image_path}")

    print(f"[*] PaddleOCR PP-Structure 识别中: {image_path}")
    img = Image.open(path)
    orig_w, orig_h = img.size[0], img.size[1]
    print(f"  [图片] {orig_w}x{orig_h}, mode={img.mode}")

    # 大图缩放:长边限制 1600px,大幅加速纯 CPU 推理
    MAX_LONG_SIDE = 1600
    long_side = max(orig_w, orig_h)
    if long_side > MAX_LONG_SIDE:
        scale = MAX_LONG_SIDE / long_side
        new_w, new_h = int(orig_w * scale), int(orig_h * scale)
        img = img.resize((new_w, new_h), Image.LANCZOS)
        print(f"  [缩放] {orig_w}x{orig_h} → {new_w}x{new_h}(长边限制 {MAX_LONG_SIDE}px)")
        # 保存缩放后的图片到临时文件
        import tempfile
        tmp_fd, tmp_path = tempfile.mkstemp(suffix='.png')
        os.close(tmp_fd)
        img.save(tmp_path)
        img.close()
        predict_path = tmp_path
    else:
        img.close()
        predict_path = str(path)

    # PPStructureV3 自动完成:布局分析 → 表格检测 → 表格结构识别 → 单元格 OCR
    # use_doc_unwarping=False 避免加载 UVDoc 弯曲矫正模型(减少依赖/权限问题)
    engine = PPStructureV3(use_doc_unwarping=False, enable_mkldnn=False)
    print(f"[*] 开始执行 predict(输入: {predict_path})...")
    try:
        result = engine.predict(predict_path)
    finally:
        if predict_path != str(path):
            os.unlink(predict_path)
    print(f"[*] predict 完成,返回类型: {type(result)}")

    # PPStructureV3.predict() 返回生成器,需要 list() 展开
    if not isinstance(result, list):
        result = list(result)
    print(f"[*] 结果数量: {len(result)}")

    # PPStructureV3 返回的是 StructureResult 对象(非 dict),
    # 表格数据在其 .table_res_list 属性中,每个元素含 .html 和 .cell_box 等属性
    tables = []
    for r in result:
        if isinstance(r, dict):
            # 兼容不同版本的 PPStructure 返回的 dict
            if r.get("type") == "table":
                tables.append(r)
            elif "table_res_list" in r:
                # 某些版本 predict() 返回 dict,其中包含 table_res_list
                for tbl in r["table_res_list"]:
                    tables.append(tbl)
        elif hasattr(r, 'table_res_list'):
            # 新版 PPStructureV3 返回对象
            for tbl in r.table_res_list:
                tables.append(tbl)
        elif hasattr(r, 'json'):
            # 某些版本支持 .json() 序列化
            try:
                rj = r.json if callable(getattr(r, 'json', None)) else r.json
                if isinstance(rj, dict) and 'table_res_list' in rj:
                    tables.extend(rj['table_res_list'])
            except Exception:
                pass

    print(f"  [检测] 发现 {len(tables)} 个表格")
    if not tables:
        # 调试:打印结果结构帮助定位
        for idx, r in enumerate(result):
            rtype = type(r).__name__
            if isinstance(r, dict):
                print(f"  [{idx}] dict keys={list(r.keys())[:10]}")
            else:
                attrs = [a for a in dir(r) if not a.startswith('_')][:15]
                print(f"  [{idx}] {rtype} attrs={attrs}")
        raise RuntimeError("未在图片中检测到表格,请确认图片包含清晰的表格区域")

    print(f"  [检测] 发现 {len(tables)} 个表格")
    all_table_data = []

    for i, tbl in enumerate(tables):
        # 兼容新旧两种返回格式
        if isinstance(tbl, dict):
            html = tbl.get("res", {}).get("html", "") or tbl.get("html", "")
        else:
            # PPStructureV3 对象:直接取 .html 属性
            html = getattr(tbl, "html", "") or ""
            if not html:
                # 尝试从 .json 属性获取
                try:
                    rj = tbl.json if isinstance(tbl.json, dict) else {}
                    html = rj.get("html", "")
                except Exception:
                    html = ""
        if not html:
            print(f"  [表 {i+1}] 跳过:无 HTML 输出")
            continue

        # 解析 HTML 表格为 DataFrame
        try:
            dfs: list[pd.DataFrame] = pd.read_html(io.StringIO(html))
            if not dfs:
                print(f"  [表 {i+1}] 跳过:HTML 解析失败")
                continue
            df = dfs[0]
        except Exception as e:
            print(f"  [表 {i+1}] HTML 解析失败: {e}")
            continue

        # 用第一行作为表头
        headers = [str(c) for c in df.columns.tolist()]
        rows = df.values.tolist()

        # 如果第一行看起来像是表头(非纯数字),保留为 headers
        # 否则可能是无表头表格,把第一行作为数据
        all_table_data.append({"headers": headers, "rows": rows})
        print(f"  [表 {i+1}] {len(rows)} 行 x {len(headers)} 列")

    if not all_table_data:
        raise RuntimeError("虽然检测到表格区域,但无法解析表格内容")

    return all_table_data


def _save_paddle_tables(all_table_data: list, output_path: str):
    """将 PP-Structure 返回的多个表格写入 Excel(多个 sheet)。"""
    if len(all_table_data) == 1:
        _write_table_to_excel(all_table_data[0], output_path, "Sheet1")
        print(f"[+] 已保存: {output_path}")
        return output_path

    # 多个表格:每个表格一个 sheet
    with pd.ExcelWriter(output_path, engine="openpyxl") as writer:
        for i, tbl in enumerate(all_table_data):
            headers = tbl.get("headers", [])
            rows = tbl.get("rows", [])
            sheet_name = f"Table_{i+1}"
            if not headers and rows:
                max_cols = max(len(r) for r in rows)
                headers = [f"列{j+1}" for j in range(max_cols)]
            padded_rows = []
            max_cols = len(headers)
            for r in rows:
                if len(r) < max_cols:
                    r = list(r) + [None] * (max_cols - len(r))
                elif len(r) > max_cols:
                    r = r[:max_cols]
                r = [_normalize_cell(v) for v in r]
                padded_rows.append(r)
            df = pd.DataFrame(padded_rows, columns=headers)
            df.to_excel(writer, index=False, sheet_name=sheet_name)
        print(f"[+] 已保存: {output_path}({len(all_table_data)} 个 Sheet)")

    return output_path


# =============================================================================
#  LLM 视觉模型引擎(备选,适用于复杂/非标准表格)
# =============================================================================

def _preprocess_image(image_path: str, max_size: int = DEFAULT_MAX_SIZE,
                      quality: int = DEFAULT_QUALITY) -> tuple:
    """
    预处理图片:缩放至 max_size 以内,转 JPEG 压缩以减少 base64 体积。
    返回 (base64_data_uri, mime_type, (orig_w, orig_h), (new_w, new_h))
    """
    path = Path(image_path)
    if not path.exists():
        raise FileNotFoundError(f"图片不存在: {image_path}")

    img = Image.open(path)
    orig_w, orig_h = img.size

    # 等比缩放
    if max(orig_w, orig_h) > max_size:
        ratio = max_size / max(orig_w, orig_h)
        new_w, new_h = int(orig_w * ratio), int(orig_h * ratio)
        img = img.resize((new_w, new_h), Image.LANCZOS)
    else:
        new_w, new_h = orig_w, orig_h

    # 转 JPEG 压缩输出(PNG 转 JPEG 大幅减小体积)
    buf = io.BytesIO()
    # 如果原图是 RGBA,填充白色背景后转 RGB
    if img.mode in ("RGBA", "LA", "P"):
        background = Image.new("RGB", img.size, (255, 255, 255))
        if img.mode == "P":
            img = img.convert("RGBA")
        background.paste(img, mask=img.split()[-1] if img.mode == "RGBA" else None)
        img = background
    elif img.mode != "RGB":
        img = img.convert("RGB")
    img.save(buf, format="JPEG", quality=quality)
    img.close()

    encoded = base64.b64encode(buf.getvalue()).decode("utf-8")
    size_kb = len(buf.getvalue()) / 1024
    return f"data:image/jpeg;base64,{encoded}", "image/jpeg", (orig_w, orig_h), (new_w, new_h), size_kb


def _extract_json(text: str) -> str:
    """从 LLM 返回文本中提取 JSON,去除 Markdown 代码块标记并尽量容错。"""
    text = text.strip()

    # 去除 Markdown ```json ... ``` 或 ``` ... ``` 包裹
    if "```" in text:
        # 寻找第一个 ``` 和最后一个 ```
        start_idx = text.find("```")
        # 跳过开头标记,如 ```json
        first_newline = text.find("\n", start_idx)
        if first_newline != -1:
            start_pos = first_newline + 1
        else:
            start_pos = start_idx + 3
        
        end_idx = text.rfind("```")
        if end_idx > start_pos:
            text = text[start_pos:end_idx].strip()
        else:
            text = text[start_pos:].strip()

    # 如果 LLM 在 JSON 前后加了说明文字,尝试提取第一个 JSON 对象
    brace_start = text.find("{")
    brace_end = text.rfind("}")
    if brace_start != -1 and brace_end != -1 and brace_end > brace_start:
        text = text[brace_start:brace_end + 1]

    # 容错处理:处理常见的 LLM JSON 错误
    # 1. 移除多余的逗号 (trailing commas)
    text = re.sub(r',\s*([}\]])', r'\1', text)
    
    # 2. 移除单行注释 // ...
    text = re.sub(r'//.*$', '', text, flags=re.MULTILINE)
    
    # 3. 处理可能的截断问题:如果最后一个字符不是 } 或 ],尝试补齐
    # 但这比较危险,先不自动补齐,而是打印更多调试信息
    
    return text


def _get_http_client(no_proxy: bool = False) -> httpx.AsyncClient:
    """创建 httpx 客户端,处理代理逻辑"""
    client_kwargs = {"timeout": 180.0}
    
    if not no_proxy:
        proxy_url = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")
        if proxy_url:
            client_kwargs["proxy"] = proxy_url
            # print(f"  [代理] {proxy_url}") # 调试用,实际调用处会打印
            
    return httpx.AsyncClient(**client_kwargs)


async def _call_vision_llm(image_path: str, max_size: int = DEFAULT_MAX_SIZE,
                           quality: int = DEFAULT_QUALITY,
                           api_url: str = "", api_key: str = "", model: str = "",
                           no_proxy: bool = False) -> dict:
    """
    调用 VL 模型提取图片中的表格为 JSON。
    自动缩放图片以满足 API 长度限制。
    """
    api_url = api_url or f"{settings.LLM_QWEN_BASE_URL}/chat/completions"
    api_key = api_key or settings.LLM_QWEN_API_KEY
    model = model or settings.LLM_QWEN_VISION_MODEL
    if not api_key:
        raise RuntimeError("API Key 未设置,请通过 --api-key 参数或 LLM_QWEN_API_KEY 环境变量提供")

    data_uri, mime_type, (ow, oh), (nw, nh), size_kb = _preprocess_image(image_path, max_size, quality)
    if (ow, oh) != (nw, nh):
        print(f"  [缩放] {ow}x{oh} -> {nw}x{nh}, base64={size_kb:.0f}KB")
    else:
        print(f"  [图片] {ow}x{oh}, base64={size_kb:.0f}KB")

    prompt = """你是一名数据录入专家。请仔细观察图片中的表格,将表头和每一行数据以 JSON 格式输出。

要求:
1. 数字保持为数字类型(如 100, 0.5),不要加引号
2. 百分比保持文本形式(如 "23.5%")
3. 空单元格使用 null
4. 不要添加任何解释文字

JSON 格式:
{
    "headers": ["列1", "列2", ...],
    "rows": [
        [值1, 值2, ...],
        [值1, 值2, ...]
    ]
}
仅返回 JSON,不要 Markdown 代码块。"""

    async def _do_request(use_proxy: bool):
        proxy_url = (os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")) if use_proxy else None
        if proxy_url:
            print(f"  [代理] {proxy_url}")
            
        async with _get_http_client(no_proxy=not use_proxy) as client:
            return await client.post(
                api_url,
                headers={
                    "Authorization": f"Bearer {api_key}",
                    "Content-Type": "application/json",
                },
                json={
                    "model": model,
                    "messages": [
                        {"role": "system", "content": "You are a data extraction assistant. Return JSON only."},
                        {
                            "role": "user",
                            "content": [
                                {"type": "image_url", "image_url": {"url": data_uri}},
                                {"type": "text", "text": prompt},
                            ],
                        },
                    ],
                    "temperature": 0.1,
                    "max_tokens": 8192,
                },
            )

    try:
        try:
            response = await _do_request(use_proxy=not no_proxy)
        except (httpx.ConnectError, httpx.ProxyError) as e:
            if not no_proxy and (os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")):
                print(f"  [重试] 代理连接失败,尝试直接连接... ({e})")
                response = await _do_request(use_proxy=False)
            else:
                raise

        if response.status_code != 200:
            logger.error(f"Vision LLM API Error: {response.status_code} - {response.text}")
            raise RuntimeError(f"API 请求失败: {response.status_code}")

        result = response.json()
        content = result["choices"][0]["message"]["content"]
        content = _extract_json(content)
        return json.loads(content)

    except json.JSONDecodeError as e:
        logger.error(f"Failed to parse LLM response as JSON. Error: {e}")
        # 打印末尾 500 个字符,帮助判断是否截断
        tail = content[-500:] if len(content) > 500 else content
        logger.error(f"Response Tail (last 500 chars):\n...{tail}")
        raise RuntimeError(f"LLM 返回内容不是合法 JSON: {e}")
    except Exception as e:
        logger.error(f"Failed to call vision LLM: {e}")
        raise


def _find_split_points(image_path: str, max_chunk_height: int = 1500) -> list:
    """
    智能寻找纵向切分点:
    1. 优先寻找全黑或全白的横向分割线。
    2. 其次寻找像素变化较小的行(可能是表格边框)。
    """
    img = Image.open(image_path).convert("L")
    w, h = img.size
    
    if h <= max_chunk_height:
        return [0, h]
    
    # 将图像转换为 numpy 数组以便快速处理
    data = np.array(img)
    # 计算每一行的平均亮度
    row_means = np.mean(data, axis=1)
    # 计算每一行像素的标准差(反映该行是否包含文字/线条)
    row_stds = np.std(data, axis=1)
    
    split_points = [0]
    current_y = 0
    
    while current_y + max_chunk_height < h:
        # 在目标切分点附近的窗口内寻找最佳切分位置
        search_start = current_y + int(max_chunk_height * 0.8)
        search_end = min(h, current_y + int(max_chunk_height * 1.2))
        
        # 寻找窗口内 std 最小的行(最可能是空白或直线)
        window_stds = row_stds[search_start:search_end]
        if len(window_stds) == 0:
            break
            
        best_in_window = np.argmin(window_stds)
        best_y = search_start + best_in_window
        
        split_points.append(int(best_y))
        current_y = best_y
        
    if split_points[-1] < h:
        split_points.append(h)
        
    img.close()
    return split_points


def _split_image(image_path: str, n_chunks: int = 0, max_size: int = DEFAULT_MAX_SIZE,
                 quality: int = DEFAULT_QUALITY) -> list:
    """
    将长图纵向切分。
    如果 n_chunks > 0, 则平均切分(带重叠)。
    如果 n_chunks == 0, 则根据图片高度自动智能切分。
    返回 [(data_uri, chunk_index, y1, y2, size_kb), ...]
    """
    img = Image.open(image_path)
    w, h = img.size
    
    # 确定切分点
    if n_chunks > 0:
        # 平均切分逻辑
        chunk_h = h // n_chunks
        overlap = int(chunk_h * 0.15)
        y_ranges = []
        for i in range(n_chunks):
            y1 = max(0, i * chunk_h - (overlap if i > 0 else 0))
            y2 = min(h, (i + 1) * chunk_h + (overlap if i < n_chunks - 1 else 0))
            y_ranges.append((y1, y2))
    else:
        # 自动智能切分逻辑
        # 设定单片建议高度(针对 VL 模型的 token 限制优化)
        target_h = 1800 if h > 2000 else h
        if h <= target_h:
            y_ranges = [(0, h)]
        else:
            points = _find_split_points(image_path, max_chunk_height=target_h)
            y_ranges = []
            # 增加 50px 的重叠以防万一
            overlap = 50
            for i in range(len(points) - 1):
                y1 = max(0, points[i] - (overlap if i > 0 else 0))
                y2 = min(h, points[i+1] + (overlap if i < len(points) - 2 else 0))
                y_ranges.append((y1, y2))

    n_actual = len(y_ranges)
    chunks = []
    for i, (y1, y2) in enumerate(y_ranges):
        chunk_img = img.crop((0, y1, w, y2))

        if max(chunk_img.size) > max_size:
            ratio = max_size / max(chunk_img.size)
            nw, nh = int(chunk_img.width * ratio), int(chunk_img.height * ratio)
            chunk_img = chunk_img.resize((nw, nh), Image.LANCZOS)

        buf = io.BytesIO()
        if chunk_img.mode in ("RGBA", "LA", "P"):
            bg = Image.new("RGB", chunk_img.size, (255, 255, 255))
            if chunk_img.mode == "P":
                chunk_img = chunk_img.convert("RGBA")
            bg.paste(chunk_img, mask=chunk_img.split()[-1] if chunk_img.mode == "RGBA" else None)
            chunk_img = bg
        elif chunk_img.mode != "RGB":
            chunk_img = chunk_img.convert("RGB")
        chunk_img.save(buf, format="JPEG", quality=quality)
        chunk_img.close()

        encoded = base64.b64encode(buf.getvalue()).decode("utf-8")
        size_kb = len(buf.getvalue()) / 1024
        data_uri = f"data:image/jpeg;base64,{encoded}"
        chunks.append((data_uri, i, y1, y2, size_kb))
        print(f"  [分片 {i + 1}/{n_actual}] y={y1}-{y2}, base64={size_kb:.0f}KB")

    img.close()
    return chunks


async def _call_vision_llm_split(image_path: str, n_chunks: int,
                                  max_size: int = DEFAULT_MAX_SIZE,
                                  quality: int = DEFAULT_QUALITY,
                                  api_url: str = "", api_key: str = "", model: str = "",
                                  no_proxy: bool = False) -> dict:
    """
    分片模式:将长图切成 n_chunks 段分别识别,合并结果(去重重叠行)。
    """
    api_url = api_url or f"{settings.LLM_QWEN_BASE_URL}/chat/completions"
    api_key = api_key or settings.LLM_QWEN_API_KEY
    model = model or settings.LLM_QWEN_VISION_MODEL
    if not api_key:
        raise RuntimeError("API Key 未设置,请通过 --api-key 参数或 LLM_QWEN_API_KEY 环境变量提供")

    chunks = _split_image(image_path, n_chunks, max_size, quality)

    prompt = """你是一名数据录入专家。这是表格图片的一部分(可能有部分行与上一段重叠)。
请提取这一部分中的所有行数据,第一行是表头(如果图片第一部分有表头的话,否则直接是数据行)。

JSON 格式:
{
    "has_header": true,
    "headers": ["列1", "列2", ...],
    "rows": [
        [值1, 值2, ...],
        [值1, 值2, ...]
    ]
}
仅返回 JSON,不要 Markdown 代码块。"""

    all_headers = []
    all_rows = []

    async def _do_chunk_request(client, data_uri, chunk_prompt):
        return await client.post(
            api_url,
            headers={
                "Authorization": f"Bearer {api_key}",
                "Content-Type": "application/json",
            },
            json={
                "model": model,
                "messages": [
                    {"role": "system", "content": "You are a data extraction assistant. Return JSON only."},
                    {
                        "role": "user",
                        "content": [
                            {"type": "image_url", "image_url": {"url": data_uri}},
                            {"type": "text", "text": chunk_prompt},
                        ],
                    },
                ],
                "temperature": 0.1,
                "max_tokens": 8192,
            },
        )

    async def _process_chunks(use_proxy: bool):
        proxy_url = (os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")) if use_proxy else None
        if proxy_url:
            print(f"  [代理] {proxy_url}")
            
        local_headers = []
        local_rows = []
        
        async with _get_http_client(no_proxy=not use_proxy) as client:
            n_actual = len(chunks)
            for idx, (data_uri, chunk_i, y1, y2, size_kb) in enumerate(chunks):
                is_first = (idx == 0)
                chunk_prompt = prompt + ("\n注意:这是图片的第一部分,请提取表头。" if is_first else "\n注意:这是图片的后续部分,不需要再提取表头,只提取数据行。")

                print(f"  [识别 {idx + 1}/{n_actual}] 发送请求...")
                response = await _do_chunk_request(client, data_uri, chunk_prompt)

                if response.status_code != 200:
                    logger.error(f"Chunk {idx} API Error: {response.status_code} - {response.text}")
                    raise RuntimeError(f"分片 {idx} API 请求失败: {response.status_code}")

                content = response.json()["choices"][0]["message"]["content"]
                try:
                    content = _extract_json(content)
                    chunk_data = json.loads(content)
                except json.JSONDecodeError as e:
                    logger.error(f"Failed to parse Chunk {idx} response as JSON. Error: {e}")
                    tail = content[-500:] if len(content) > 500 else content
                    logger.error(f"Response Tail:\n...{tail}")
                    raise RuntimeError(f"分片 {idx} 返回内容不是合法 JSON: {e}")

                if is_first and chunk_data.get("has_header", True):
                    local_headers = chunk_data.get("headers", [])
                chunk_rows = chunk_data.get("rows", [])

                if idx > 0 and local_rows and chunk_rows:
                    last_row = tuple(str(v) for v in local_rows[-1])
                    skip = 0
                    for r in chunk_rows:
                        if tuple(str(v) for v in r) == last_row:
                            skip += 1
                        elif skip > 0:
                            break
                    if skip > 0:
                        print(f"  [去重] 分片 {idx + 1} 跳过前 {skip} 行")
                        chunk_rows = chunk_rows[skip:]

                local_rows.extend(chunk_rows)
                print(f"  [分片 {idx + 1}] 提取 {len(chunk_rows)} 行")
        
        return local_headers, local_rows

    try:
        all_headers, all_rows = await _process_chunks(use_proxy=not no_proxy)
    except (httpx.ConnectError, httpx.ProxyError) as e:
        if not no_proxy and (os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")):
            print(f"  [重试] 代理连接失败,尝试直接连接... ({e})")
            all_headers, all_rows = await _process_chunks(use_proxy=False)
        else:
            raise

    return {"headers": all_headers, "rows": all_rows}


# =============================================================================
#  主入口
# =============================================================================

def main():
    parser = argparse.ArgumentParser(
        description="图片转 Excel —— 将表格截图识别为 Excel 文件",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
引擎说明:
  paddle   PaddleOCR + PP-Structure(默认),本地 OCR 引擎,
           对密集数字表格更稳定、更准确、免费无限次使用。
  llm      Qwen VL 等视觉大模型,适合非标准/复杂排版表格,
           需要 API Key,有调用成本。

示例:
  python image_to_excel.py table.png
  python image_to_excel.py table.png --output result.xlsx
  python image_to_excel.py table.png --engine llm --api-key sk-xxx
        """,
    )
    parser.add_argument("image", help="表格截图路径")
    parser.add_argument("--engine", choices=["paddle", "llm"], default="paddle",
                        help="识别引擎:paddle(PaddleOCR,默认), llm(视觉大模型)")
    parser.add_argument("--output", "-o", default=None,
                        help="输出路径,默认 <image>.xlsx")
    # LLM 专用参数
    parser.add_argument("--max-size", type=int, default=DEFAULT_MAX_SIZE,
                        help=f"LLM 模式:图片最长边缩放上限(像素),默认 {DEFAULT_MAX_SIZE}")
    parser.add_argument("--quality", "-q", type=int, default=DEFAULT_QUALITY,
                        help=f"LLM 模式:JPEG 压缩质量 1-100,默认 {DEFAULT_QUALITY}")
    parser.add_argument("--split", type=int, default=0, metavar="N",
                        help="LLM 模式:将长图纵向切成 N 段分别识别后合并")
    parser.add_argument("--api-url", default="",
                        help="LLM 模式:API 完整地址。不指定则使用 LLM_QWEN_BASE_URL")
    parser.add_argument("--api-key", default="",
                        help="LLM 模式:API Key。不指定则使用 LLM_QWEN_API_KEY")
    parser.add_argument("--model", "-m", default="",
                        help="LLM 模式:模型名称。不指定则使用 LLM_QWEN_VISION_MODEL")
    parser.add_argument("--no-proxy", action="store_true",
                        help="LLM 模式:禁用环境变量中的 HTTP/HTTPS 代理")
    args = parser.parse_args()

    output_path = args.output or str(Path(args.image).with_suffix(".xlsx"))

    # ── PaddleOCR 引擎 ──
    if args.engine == "paddle":
        try:
            all_table_data = _call_paddle_structure(args.image)
            rows_count = sum(len(t.get("rows", [])) for t in all_table_data)
            _save_paddle_tables(all_table_data, output_path)
            print(f"[+] 引擎: PaddleOCR PP-Structure\n   表格数: {len(all_table_data)}\n   总行数: {rows_count}")
        except RuntimeError as e:
            if settings.LLM_QWEN_API_KEY:
                print(f"[!] PaddleOCR 识别失败: {e}")
                print(f"[*] 自动切换到 LLM 引擎尝试识别...")
                table_data = asyncio.run(_call_vision_llm(
                    args.image, no_proxy=args.no_proxy
                ))
                rows_count = len(table_data.get("rows", []))
                _write_table_to_excel(table_data, output_path)
                print(f"[+] 已保存: {output_path}\n   模型: {settings.LLM_QWEN_VISION_MODEL}\n   行数: {rows_count}")
            else:
                raise

    # ── LLM 引擎 ──
    else:
        api_url = args.api_url
        api_key = args.api_key
        model = args.model

        print(f"[*] 调用 {model or settings.LLM_QWEN_VISION_MODEL} 解析图片: {args.image}")
        if api_url:
            print(f"[*] API: {api_url}")

        # 自动判断是否需要切分
        img = Image.open(args.image)
        height = img.size[1]
        img.close()
        
        # 如果用户手动指定了分段,或者图片太长(高度 > 2000),则进入切分模式
        if args.split > 0 or height > 2000:
            if args.split > 0:
                print(f"[*] 分片模式:手动指定 {args.split} 段")
            else:
                print(f"[*] 分片模式:图片高度 {height}px,自动智能切分")
                
            table_data = asyncio.run(_call_vision_llm_split(
                args.image, args.split, max_size=args.max_size, quality=args.quality,
                api_url=api_url, api_key=api_key, model=model, no_proxy=args.no_proxy
            ))
        else:
            table_data = asyncio.run(_call_vision_llm(
                args.image, max_size=args.max_size, quality=args.quality,
                api_url=api_url, api_key=api_key, model=model, no_proxy=args.no_proxy
            ))

        rows_count = len(table_data.get("rows", []))
        cols_count = len(table_data.get("headers", []))
        print(f"[*] 识别到 {rows_count} 行 {cols_count} 列数据")

        _write_table_to_excel(table_data, output_path)
        print(f"[+] 已保存: {output_path}\n   模型: {model or settings.LLM_QWEN_VISION_MODEL}\n   行数: {rows_count}")


if __name__ == "__main__":
    main()