Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344import pandas as pdimport matplotlib.pyplot as pltimport gradio as grimport tempfileimport osdef 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()1234567891011121314151617181920212223242526272829303132333435363738394041import gradio as grimport pandas as pdimport matplotlib.pyplot as pltimport tempfileimport osdef analyze(file_obj):# 读取CSVdf = pd.read_csv(file_obj.name)# 统计摘要stats = df.describe().loc[["mean", "std", "min", "max"]].round(2).to_string()# 生成图表并保存为临时图片tmp_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.xlabel("Income")plt.ylabel("Spending Score")plt.title("Income vs Spending Score")plt.grid(True)plt.tight_layout()plt.savefig(tmp_path)plt.close()return stats, tmp_pathwith gr.Blocks(title="CSV分析工具") as demo:gr.Markdown("## 📊 表格分析大模型\n请上传一个CSV文件,我将输出统计摘要并绘制图表。")with gr.Row():file_input = gr.File(label="上传 CSV 文件", file_types=[".csv"])run_btn = gr.Button("开始分析")output_text = gr.Textbox(label="统计摘要", lines=10)output_image = gr.Image(label="图表")run_btn.click(fn=analyze, inputs=file_input, outputs=[output_text, output_image])demo.launch()
app.py+25-28