csv-test / app.py
bbbdbbb's picture
Update app.py
d5bf59e verified
raw
history blame
1.3 kB
import pandas as pd
import matplotlib.pyplot as plt
import gradio as gr
import tempfile
import os
def analyze_csv(file):
# 读取上传的文件
df = pd.read_csv(file.name)
# 统计信息
stats = df.describe().loc[["mean", "std", "min", "max"]].round(2).to_string()
# 临时生成图片路径
tmp_img_path = os.path.join(tempfile.gettempdir(), "income_vs_score.png")
# 绘制散点图
plt.figure(figsize=(6, 4))
plt.scatter(df["Income"], df["SpendingScore"], alpha=0.7)
plt.title("Income vs Spending Score")
plt.xlabel("Income")
plt.ylabel("Spending Score")
plt.grid(True)
plt.tight_layout()
plt.savefig(tmp_img_path)
plt.close()
# 返回字典结构,避免多输出 schema 解析问题
return {
"统计摘要": stats,
"图表": tmp_img_path
}
# Gradio 接口,注意 outputs 使用 gr.Json 兼容 dict 返回
iface = gr.Interface(
fn=analyze_csv,
inputs=gr.File(file_types=[".csv"], label="上传CSV文件"),
outputs=gr.JSON(label="分析结果(包含统计摘要 + 图像路径)"),
title="📊 表格分析大模型",
description="上传一个CSV表格,我将输出统计分析结果并展示一张图表的路径。"
)
if __name__ == "__main__":
iface.launch()