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

Streamlit部署ML模型:上传Zip文件报seek属性错误的解决方法

解决Streamlit上传Zip文件时的AttributeError错误

你遇到的AttributeError: 'list' object has no attribute 'seek'错误,核心原因是当st.file_uploader设置accept_multiple_files=True时,返回的是文件对象列表,而非单个文件,但zipfile.ZipFile需要传入单个类文件对象,直接传入列表就会触发这个错误。

修复方案

需要遍历上传的文件列表,逐个判断是否为Zip文件后分别处理:

  • 遍历每个上传的文件对象
  • 用zipfile.is_zipfile()判断是否为Zip文件,若是则解压到指定目录
  • 非Zip格式的图片文件直接保留,用于后续预测
  • 统一用指定目录存储文件,避免污染当前工作目录

修改后的完整代码

import altair as alt
import streamlit as st
from PIL import Image
from pathlib import Path
import zipfile
import os

# 页面配置
st.set_page_config(page_title='Br Classifier', page_icon='nm.jpg', layout='wide', 
                   initial_sidebar_state='expanded')

# 加载顶部图片(改用相对路径,适配部署场景)
try:
    image = Image.open("image.jfif")
    st.image(image, use_column_width=True)
except FileNotFoundError:
    st.warning("顶部图片未找到,请检查路径")

st.write("""
# CLASSIFICATION

This application helps to classify different classes

***
""")

def main():
    st.info("上传包含图片的Zip文件或单个/多个图片文件,系统将自动处理并用于分类")
    
    # 允许上传多个文件(zip/图片)
    file_uploaded = st.file_uploader("上传文件", type=["png","jpg","jpeg", "zip"], 
                                     accept_multiple_files=True)
    
    # 创建存储解压图片的目录
    extracted_dir = "extracted_images"
    os.makedirs(extracted_dir, exist_ok=True)
    
    # 存储所有待预测的图片路径
    image_paths = []
    
    if file_uploaded:
        for file in file_uploaded:
            # 判断是否为Zip文件
            if zipfile.is_zipfile(file):
                with zipfile.ZipFile(file, "r") as z:
                    # 解压所有文件到指定目录
                    z.extractall(extracted_dir)
                    st.success(f"已解压Zip文件:{file.name},文件存放在 {extracted_dir}")
                    # 收集解压后的图片路径
                    for img_ext in ["*.png", "*.jpg", "*.jpeg"]:
                        for img_path in Path(extracted_dir).rglob(img_ext):
                            image_paths.append(str(img_path))
            else:
                # 非Zip文件,直接保存临时文件并收集路径
                temp_path = os.path.join(extracted_dir, file.name)
                with open(temp_path, "wb") as f:
                    f.write(file.getbuffer())
                image_paths.append(temp_path)
                st.success(f"已上传图片:{file.name}")
    
    # 模型选择
    selected_model = st.sidebar.selectbox(
        '选择图片分类模型',
        ('CNN_CLASSIFIER', 'Neural Network'))
    st.write('你选择的模型:', selected_model)
    
    # 展示待预测图片列表,后续可用于模型预测
    if image_paths:
        st.subheader("待预测图片列表")
        st.write(image_paths)

if __name__ == "__main__":
    main()

关键修改点说明

  • 移除了未实际使用的get_static_store缓存函数
  • 遍历file_uploaded列表,逐个处理每个上传的文件
  • 用zipfile.is_zipfile()准确判断Zip文件,避免类型判断错误
  • 创建extracted_images目录统一存放解压和上传的图片,便于后续管理
  • 收集所有待预测的图片路径,方便后续传入模型进行推理
  • 优化顶部图片加载逻辑,添加异常处理并改用相对路径,适配部署场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 11:06:20