|
| 1 | +import gradio as gr |
| 2 | +import pandas as pd |
| 3 | +import matplotlib.pyplot as plt |
| 4 | +import tempfile |
| 5 | + |
| 6 | +def generate_pie_chart(file): |
| 7 | + try: |
| 8 | + # Read the uploaded CSV |
| 9 | + df = pd.read_csv(file) |
| 10 | + |
| 11 | + # Ensure the CSV has exactly one column |
| 12 | + if df.shape[1] != 1: |
| 13 | + return None, "Error: The uploaded CSV must have exactly one column of data." |
| 14 | + |
| 15 | + # Extract the single column |
| 16 | + column = df.iloc[:, 0] |
| 17 | + |
| 18 | + # Compute the top 5 most frequent values |
| 19 | + top_five = column.value_counts().head(5) |
| 20 | + |
| 21 | + # Generate the pie chart |
| 22 | + plt.figure(figsize=(8, 6)) |
| 23 | + plt.pie( |
| 24 | + top_five.values, |
| 25 | + labels=top_five.index.astype(str), |
| 26 | + autopct='%1.1f%%', |
| 27 | + startangle=140, |
| 28 | + colors=plt.cm.tab10.colors |
| 29 | + ) |
| 30 | + plt.title("Top 5 Most Frequent Values", fontsize=14) |
| 31 | + |
| 32 | + # Save the pie chart to a temporary file |
| 33 | + temp_image_path = tempfile.mktemp(suffix=".png") |
| 34 | + plt.savefig(temp_image_path) |
| 35 | + plt.close() |
| 36 | + |
| 37 | + return temp_image_path, "Pie chart generated successfully." |
| 38 | + except Exception as e: |
| 39 | + return None, f"Error: {e}" |
| 40 | + |
| 41 | +# Gradio interface |
| 42 | +with gr.Blocks() as app: |
| 43 | + gr.Markdown("### Drag and Drop a CSV File to Create a Pie Chart") |
| 44 | + |
| 45 | + csv_input = gr.File(label="Upload CSV File", file_types=[".csv"]) |
| 46 | + graph_output = gr.Image(label="Pie Chart") |
| 47 | + status_output = gr.Textbox(label="Status", interactive=False) |
| 48 | + |
| 49 | + generate_button = gr.Button("Generate Pie Chart") |
| 50 | + |
| 51 | + generate_button.click( |
| 52 | + generate_pie_chart, |
| 53 | + inputs=[csv_input], |
| 54 | + outputs=[graph_output, status_output] |
| 55 | + ) |
| 56 | + |
| 57 | +app.launch(server_name="0.0.0.0", server_port=7863) |
0 commit comments