You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PyInstaller打包含T5、NER Transformers模型的Python代码遇错求助

PyInstaller打包HuggingFace Transformers代码报错解决方法

针对你遇到的importlib.metadata.PackageNotFoundError报错,即便已安装huggingface-hub仍无法打包的问题,可尝试以下解决步骤:

  • 确认环境一致性
    检查打包使用的Python环境与安装依赖的环境是否一致,避免跨环境导致依赖未被纳入打包范围。可通过where python(Windows)或which python(Linux/macOS)查看当前Python路径,确保PyInstaller和所有依赖都安装在同一虚拟环境中。

  • 强制指定隐藏依赖
    在PyInstaller打包命令中直接添加--hidden-import参数,强制打包huggingface-hub及相关依赖:

    pyinstaller --hidden-import huggingface-hub --hidden-import transformers your_script.py
    
  • 手动添加钩子文件
    创建名为hook-huggingface-hub.py的钩子文件,内容如下:

    from PyInstaller.utils.hooks import collect_data_files
    
    datas = collect_data_files('huggingface_hub')
    

    将该文件放入PyInstaller默认hooks目录,或在打包时用--additional-hooks-dir指定钩子文件夹路径:

    pyinstaller --additional-hooks-dir ./hooks_folder your_script.py
    
  • 验证依赖版本匹配
    确认huggingface-hub版本符合transformers的要求(>=0.19.3,<1.0),执行以下命令查看版本:

    pip show huggingface-hub
    

    若版本不符,重新安装指定版本:

    pip install huggingface-hub==0.19.3
    
  • 打包本地模型文件(若适用)
    若代码加载的是本地下载的T5/NER模型,需将模型文件夹一并打包:

    • Windows系统:
      pyinstaller --add-data "path/to/your/model;./model" your_script.py
      
    • Linux/macOS系统:
      pyinstaller --add-data "path/to/your/model:./model" your_script.py
      

    同时修改代码中模型加载路径,适配打包后的临时目录:

    import sys
    import os
    from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
    
    def resource_path(relative_path):
        try:
            base_path = sys._MEIPASS
        except Exception:
            base_path = os.path.abspath(".")
        return os.path.join(base_path, relative_path)
    
    model = AutoModelForSeq2SeqLM.from_pretrained(resource_path("model"))
    tokenizer = AutoTokenizer.from_pretrained(resource_path("model"))
    

内容的提问来源于stack exchange,提问作者puja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 09:42:28