Spaces:
Runtime error
Runtime error
import gradio as gr | |
import io | |
import zipfile | |
# 自定义CSS,固定左右面板的大小 & 按钮样式 | |
CUSTOM_CSS = """ | |
/* 左侧面板 */ | |
#left-panel { | |
width: 300px; | |
height: 400px; /* 固定高度,你可根据需求调整 */ | |
overflow-y: auto; /* 超出时滚动 */ | |
border-right: 1px solid #ccc; | |
padding: 10px; | |
box-sizing: border-box; | |
} | |
/* 右侧面板 */ | |
#right-panel { | |
width: 300px; | |
height: 400px; /* 固定高度 */ | |
overflow-y: auto; | |
border-left: 1px solid #ccc; | |
padding: 10px; | |
box-sizing: border-box; | |
} | |
/* 合并按钮 */ | |
#combine-button { | |
background-color: orange; | |
color: white; | |
font-size: 16px; | |
border-radius: 5px; | |
border: none; | |
padding: 10px 20px; | |
cursor: pointer; | |
} | |
/* 下载ZIP按钮 */ | |
#download-zip { | |
background-color: blue; | |
color: white; | |
font-size: 16px; | |
border-radius: 5px; | |
border: none; | |
padding: 10px 20px; | |
cursor: pointer; | |
} | |
""" | |
def combine_action(): | |
""" | |
合并按钮点击后,你可以在这里执行实际逻辑。 | |
下面仅示例返回一个字符串或做一个简单处理。 | |
""" | |
print("合并逻辑被触发!") | |
return "已合并(此处可替换为实际处理逻辑)" | |
def create_zip(): | |
""" | |
动态生成并返回一个 zip 文件(内存中)。 | |
Gradio 会将返回的 BytesIO 作为 File 下载。 | |
""" | |
buf = io.BytesIO() | |
with zipfile.ZipFile(buf, 'w') as zf: | |
# 往 zip 中写一个示例文件 | |
zf.writestr("test.txt", "这是一个测试文件!\nHello World!") | |
buf.seek(0) | |
return buf # 返回内存中的 zip | |
with gr.Blocks(css=CUSTOM_CSS) as demo: | |
# 主布局 | |
with gr.Row(): | |
# 左侧面板 | |
with gr.Box(elem_id="left-panel"): | |
gr.Markdown("**上传区域**") | |
uploader = gr.File(label="在此处上传文件") | |
# 右侧面板 | |
with gr.Box(elem_id="right-panel"): | |
gr.Markdown("**结果缩略图**") | |
gr.Markdown("这里可以放置处理后的缩略图或任何输出") | |
# 底部按钮 | |
with gr.Row(): | |
combine_btn = gr.Button("合并", elem_id="combine-button") | |
download_btn = gr.Button("下载 Zip", elem_id="download-zip") | |
# 点击“合并”时(这里仅做一个演示) | |
combine_btn.click(fn=combine_action, inputs=[], outputs=[]) | |
# 准备一个隐藏的 File 组件,用来承载生成的 zip 文件 | |
# 一旦函数返回文件,该组件就会显示“下载链接” | |
zip_file = gr.File(label="点此下载生成的 ZIP", visible=False) | |
# 点击“下载 Zip”时,调用 create_zip,输出到 zip_file | |
download_btn.click(fn=create_zip, inputs=[], outputs=zip_file) | |
demo.launch() |