吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 570|回复: 13
收起左侧

[求助] python paddleocr 打包 求助

[复制链接]
sea8523 发表于 2025-3-28 14:32
先说一下 做了一个 批量图片识别文字生成excel的py,执行没问题。现在想打包成exe文件。因为paddleocr 会调用很大第三方库,导致一直打包失败(文件不能正常使用),通过deepseek多轮沟通,仍无法解决,求大神门看看。
我的项目环境是用的python自带的 env 虚拟环境。包的路径是 D:\myenv\Lib\site-packages,会用到paddle_models, D:\myenv\md\paddle_models\。py代码如下
[Python] 纯文本查看 复制代码
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
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
import osimport re
import cv2
import numpy as np
import threading
from concurrent.futures import ThreadPoolExecutor
from paddleocr import PaddleOCR
import pandas as pd
import sys
import os
import paddleocr.tools
# 在脚本顶部添加
 
 
# ================== 配置区域 ==================
MODEL_DIR = r"D:\paddle_models"  # 模型存储路径(必须为英文)
INPUT_FOLDER = r"D:\images\im"  # 图片输入目录
OUTPUT_EXCEL = "商户数据.xlsx"  # 输出文件名
# ==============================================
 
 
def get_resource_path(relative_path):
    """ 处理打包后资源路径问题 """
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)
 
# 修改模型加载方式
MODEL_DIR = get_resource_path("paddle_models")
print(f"[DEBUG] 模型路径: {MODEL_DIR}"# 调试输出
 
# 初始化OCR引擎(调优参数)
ocr = PaddleOCR(
    lang="ch",
    use_angle_cls=False,
    det_model_dir=os.path.join(MODEL_DIR, "det/ch_PP-OCRv4_det_infer"),
    rec_model_dir=os.path.join(MODEL_DIR, "rec/ch_PP-OCRv4_rec_infer"),
    use_gpu=False,
    det_db_thresh=0.3# 降低检测阈值
    det_db_box_thresh=0.4# 提高框选灵敏度
    use_dilation=True  # 启用膨胀处理密集文本
)
 
# 全局存储容器(线程安全)
results = []
lock = threading.Lock()
 
 
def preprocess_image(img_path):
    img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), -1)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
 
    # 自适应直方图均衡化(限制对比度)
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    clahed = clahe.apply(gray)
 
    # 非局部均值去噪(保留边缘)
    denoised = cv2.fastNlMeansDenoising(clahed, h=7, templateWindowSize=7, searchWindowSize=21)
    return denoised
 
    """图像预处理增强"""
    try:
        # 读取图片并灰度化
        img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), -1# 支持中文路径
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
 
        # CLAHE对比度增强
        clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8))
        enhanced = clahe.apply(gray)
 
        # 高斯模糊降噪
        blurred = cv2.GaussianBlur(enhanced, (5, 5), 0)
        return blurred
    except Exception as e:
        print(f"图像预处理失败: {img_path}, 错误: {str(e)}")
        return None
 
 
def extract_merchant_number(text):
    """提取并验证商户编号"""
    # 匹配模式:商户编号开头,允许各种分隔符
    pattern = r'(?:商户编号|商编|商户号|Merchant\s*ID)\s*[::\-\s]*([89]{2}[\d\s\-]{13,})'
    match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE)
 
    if match:
        # 清理非数字字符
        cleaned = re.sub(r'\D', '', match.group(1))
        # 验证长度和起始数字
        if len(cleaned) == 15 and cleaned.startswith('89'):
            return cleaned
    return None
 
 
def process_image(img_path):
    """处理单张图片"""
    try:
        # 1. 图像预处理
        processed_img = preprocess_image(img_path)
        if processed_img is None:
            return
 
        # 2. OCR识别
        result = ocr.ocr(processed_img, cls=False)
 
        # 3. 提取文本
        text = " ".join(line[1][0] for line in (result[0] or []))
        print(f"DEBUG - {os.path.basename(img_path)} 原始文本:\n{text[:230]}...")
 
        # 4. 提取并验证商户编号
        merchant_no = extract_merchant_number(text)
 
        # 5. 线程安全存储
        with lock:
            results.append({
                "图片名称": os.path.basename(img_path),
                "商户编号": merchant_no or "未找到",
                "原始文本": text[:200] + "..."  # 截断长文本
            })
 
    except Exception as e:
        print(f"处理失败: {os.path.basename(img_path)}, 错误类型: {type(e).__name__}, 详情: {str(e)}")
 
 
def main():
    # 获取所有图片文件
    valid_ext = ('.png', '.jpg', '.jpeg', '.pdf')
    files = [
        os.path.join(INPUT_FOLDER, f)
        for f in os.listdir(INPUT_FOLDER)
        if f.lower().endswith(valid_ext)
    ]
 
    # 多线程处理
    with ThreadPoolExecutor(max_workers=os.cpu_count() * 2) as executor:
        executor.map(process_image, files)
 
    # 生成Excel
    if results:
        df = pd.DataFrame(results)
        df = df[["图片名称", "商户编号", "原始文本"]]
        df.to_excel(OUTPUT_EXCEL, index=False)
        print(f"生成成功!文件保存至: {os.path.abspath(OUTPUT_EXCEL)}")
    else:
        print("未处理任何有效图片")
 
 
if __name__ == "__main__":
    main()


用的的 pyinstallerde 打包方法,设置了gui.spec配置文件。如下
[Python] 纯文本查看 复制代码
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
# -*- mode: python ; coding: utf-8 -*-
 
block_cipher = None
 
# ================== 核心配置增强 ==================
a = Analysis(
    ['ocr-ysf.py'],
 
    # 路径增强:包含虚拟环境和项目路径
    pathex=[
        'D:\\myenv\\Lib\\site-packages'# 虚拟环境主目录
        'D:\\myenv\\Lib\\site-packages\\paddle\\libs'# Paddle动态库
        'D:\\myenv\\Lib\\site-packages\\paddleocr'  # OCR核心模块
        'D:\\myenv\\Lib\\site-packages\\sqlalchemy\\dialects\\mysql',
        'D:\\myenv\\Lib\\site-packages\\scipy',
 
    ],
 
    binaries=[
        # 包含所有必要的二进制文件
        ('D:/myenv/Lib/site-packages/paddle/libs/*.dll', '.'),
        (r'D:\myenv\Lib\site-packages\scipy\_lib\*.pyd', 'scipy/_lib'),
        (r'D:\myenv\Lib\site-packages\scipy.libs\*.dll', 'libscipy'),
        (r'D:\myenv\Lib\site-packages\scipy\sparse\*.pyd', 'scipy/sparse'),
 
 
    ],
 
    datas=[
        # 递归包含模型文件(**表示包含所有子目录)
        ('D:/myenv/md/paddle_models/**', 'paddle_models'),
        ('D:/myenv/Lib/site-packages/paddleocr/**', 'paddleocr'),
        ('D:/myenv/Lib/site-packages/scipy/**', 'scipy'),
        (r'D:\myenv\Lib\site-packages\scipy.libs\*', 'libscipy')
    ],
 
    hiddenimports=[
        # 显式添加缺失的依赖模块
        'paddleocr',
        'paddle',
        'pyclipper',
        'shapely',
        'mx.DateTime',
        'MySQLdb',
        'pysqlite2',
        'scipy.special._cdflib',
        'scipy',
        'scipy.spatial.transform._rotation_groups'# 解决scipy子模块缺失
        'scipy.special',
        'scipy.sparse',
        'scipy.sparse.csgraph',
        'scipy.sparse.linalg',
        'scipy.sparse._sparsetools',
        'scipy._lib',
        'jinja2',
        'apted',        # 树编辑距离计算
        'lanms',        # 文本检测后处理
        'sklearn',      # 结构分析依赖
        'sklearn.utils._cython_blas',
        'sqlite3',      # 数据库支持
        'pysqlite3',    # 增强SQLite支持
 
    ],
 
    # 钩子配置增强
    hookspath=['hooks'],  # 创建hooks目录存放自定义钩子
 
    # 排除非必要模块减小体积
    excludes=['matplotlib', 'tkinter', 'scipy'],
 
    # 其他参数保持默认
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False
)
 
# ================== 打包配置优化 ==================
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
 
exe = EXE(pyz,
    a.scripts,             # 位置参数
    a.binaries,
    a.zipfiles,
    a.datas,
    [],                    # 空列表(默认参数占位)
    exclude_binaries=True, # 关键字参数开始
    name='main',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    console=True)
 
coll = COLLECT(exe,
     a.binaries,
     a.zipfiles,
     a.datas,
     strip=False,
     upx=True,
     upx_exclude=[],
     name='main')


可以打包完成,但不能使用,通过命令查看log,
[Bash shell] 纯文本查看 复制代码
1
main.exe > out1.log 2>&1


提示如下:

Traceback (most recent call last):
  File "ocr-ysf.py", line 7, in <module>
  File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 935, in _load_unlocked
  File "PyInstaller\loader\pyimod02_importers.py", line 450, in exec_module
  File "paddleocr\__init__.py", line 14, in <module>
    # limitations under the License.
  File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 935, in _load_unlocked
  File "PyInstaller\loader\pyimod02_importers.py", line 450, in exec_module
  File "paddleocr\paddleocr.py", line 45, in <module>
    tools = _import_file(
            ^^^^^^^^^^^^^
  File "paddleocr\paddleocr.py", line 39, in _import_file
    spec.loader.exec_module(module)
  File "<frozen importlib._bootstrap_external>", line 991, in exec_module
  File "<frozen importlib._bootstrap_external>", line 1128, in get_code
  File "<frozen importlib._bootstrap_external>", line 1186, in get_data
FileNotFoundError: [Errno 2] No such file or directory: 'D:\\myenv\\md\\dist\\main\\_internal\\paddleocr\\tools/__init__.py'
[PYI-20068:ERROR] Failed to execute script 'ocr-ysf' due to unhandled exception!





代码文件已上传至 https://wwaa.lanzouo.com/iicgn2rw96re

哪位大神给看看,求生成exe文件

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

reody 发表于 2025-3-28 14:52
用这个auto-py-to-exe试试
chenzhigang 发表于 2025-3-28 14:59
没打包\paddleocr\\tools  把这个弄进去  https://github.com/PaddlePaddle/PaddleOCR/discussions/11342
你的paddle 版本和pyinstaller 版本是多少了 pyinstaller 好像不能太高
但是pyinstaller  现在有GUI 了 ,不都是命令吗
mtluck 发表于 2025-3-28 15:34
yks1985 发表于 2025-3-28 16:09
等待教程的出现
 楼主| sea8523 发表于 2025-3-28 16:33
reody 发表于 2025-3-28 14:52
用这个auto-py-to-exe试试

试过的 ,不行
 楼主| sea8523 发表于 2025-3-28 16:38
chenzhigang 发表于 2025-3-28 14:59
没打包\paddleocr\\tools  把这个弄进去  https://github.com/PaddlePaddle/PaddleOCR/discussions/11342
...

对,但是明明 D:\myenv\Lib\site-packages\paddleocr\tools,这个路径下有tools文件,却没有打包进去,不知道问题在哪里。 版本如下

[Lua] 纯文本查看 复制代码
1
2
3
4
5
(myenv) D:\myenv\md\dist\main>python --version
Python 3.12.4
 
(myenv) D:\myenv\md\dist\main>pyinstaller  --version
6.12.0
chenzhigang 发表于 2025-3-28 17:33
pyinstaller 版本太高了 装5.12.0的
wyao 发表于 2025-3-28 17:35
本帖最后由 wyao 于 2025-3-28 17:43 编辑

直接把代码放到豆包的AI编程里,打出你的要求 会有提示,打开新大陆 哈哈。    或者给你个打包工具你看下能用不(https://wyao.lanzn.com/ipzMl2rx134b)   PS:AI是个好东西,我都不会编程,只会复制粘贴
wayne333 发表于 2025-3-28 18:54
期待教程的出现
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-4-7 18:20

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表