Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718194 unmodified lines242526272829301 unmodified line32333435363738394041424344454647484950515253545556575859606162636465666768697071727374import osimport gradio as grimport pandas as pdfrom google import genai# 1. Initialize the Gemini client securely from the environmentapi_key = os.environ.get('GEMINI_API_KEY')client = genai.Client(api_key=api_key)# 2. Define the core data analysis logicdef analyze_data(uploaded_file, user_question):# Check if a file was actually uploadedif uploaded_file is None:return "⚠️ Please upload a CSV file first before asking a question."try:# Read the uploaded CSV file using Pandasdf = pd.read_csv(uploaded_file.name)4 unmodified linesdata_preview = df.head(3).to_string()data_types = df.dtypes.to_string()# Build a robust prompt telling Gemini about the data structuresystem_context = (f"You are an expert Python Data Analyst. The user has uploaded a dataset.\n"f"Dataset Statistics:\n"1 unmodified linef"- Total Columns: {col_count}\n"f"- Column Names: {column_names}\n\n"f"Data Types:\n{data_types}\n\n"f"Preview of first 3 rows:\n{data_preview}\n\n"f"Please answer the user's question by performing statistical logic or providing "f"Python code snippets if requested. Always base your calculations on this data framework.")# Send the metadata context and the user query to Geminiresponse = client.models.generate_content(model='gemini-2.5-flash',contents=[system_context, f"User Question: {user_question}"])return response.textexcept Exception as e:return f"❌ An error occurred processing the file: {str(e)}"# 3. Design a beautiful, custom web dashboard using Gradio Blockswith gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# 📊 Cloud AI Data Analyst")gr.Markdown("Upload a spreadsheet dataset and ask the AI to clean it, summarize it, or uncover hidden insights.")with gr.Row():with gr.Column(scale=1):file_input = gr.File(label="Step 1: Upload CSV Dataset", file_types=[".csv"])question_input = gr.Textbox(label="Step 2: What would you like to know about this data?",placeholder="e.g., Summarize the main trends, find missing values, or calculate averages...")submit_btn = gr.Button("Analyze Data", variant="primary")with gr.Column(scale=1):output_text = gr.Markdown(label="AI Analysis Result")# Connect the inputs to the function when clicking the buttonsubmit_btn.click(fn=analyze_data,inputs=[file_input, question_input],outputs=output_text)# 4. Launch the public cloud server123456789101112131415161718192021222324254 unmodified lines303132333435361 unmodified line3839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105import osimport gradio as grimport pandas as pdimport matplotlib# Use a non-interactive backend for Matplotlib to prevent cloud server crashesmatplotlib.use('Agg')import matplotlib.pyplot as pltfrom google import genai# 1. Initialize the Gemini client securely from the environmentapi_key = os.environ.get('GEMINI_API_KEY')client = genai.Client(api_key=api_key)# 2. Define the core data and plotting logicdef analyze_and_plot(uploaded_file, user_question):if uploaded_file is None:return "⚠️ Please upload a CSV file first.", Nonetry:# Clear any previous figures to avoid overlapping graphsplt.close('all')# Read the uploaded CSV file using Pandasdf = pd.read_csv(uploaded_file.name)4 unmodified linesdata_preview = df.head(3).to_string()data_types = df.dtypes.to_string()# System instructions forcing Gemini to return structured code if a chart is neededsystem_context = (f"You are an expert Python Data Analyst. The user has uploaded a dataset.\n"f"Dataset Statistics:\n"1 unmodified linef"- Total Columns: {col_count}\n"f"- Column Names: {column_names}\n\n"f"Data Types:\n{data_types}\n\n"f"Preview:\n{data_preview}\n\n"f"INSTRUCTIONS:\n"f"1. Answer the user's question clearly.\n"f"2. If the user asks for a chart, graph, or plot, you MUST include a clean Python code block "f"that uses 'matplotlib.pyplot' to build it. Assume the dataframe is already loaded as a variable named 'df'.\n"f"3. Crucial: The LAST line of your chart code block must save the image exactly as: plt.savefig('output_chart.png')\n"f"4. Do not include plt.show(). Only save it to 'output_chart.png'.")# Send the metadata context and user query to Geminiresponse = client.models.generate_content(model='gemini-2.5-flash',contents=[system_context, f"User Question: {user_question}"])text_response = response.textchart_path = None# Extract and execute the python code if Gemini generated a graph scriptif "```python" in text_response:try:# Isolate the code inside the markdown blockscode_block = text_response.split("```python")[1].split("```")[0]# Create a safe execution environment containing the user's datalocal_vars = {'df': df, 'plt': plt}exec(code_block, {}, local_vars)# Check if the file was successfully written by the executed codeif os.path.exists("output_chart.png"):chart_path = "output_chart.png"except Exception as e:text_response += f"\n\n*(Note: There was a background error rendering the chart: {str(e)})*"return text_response, chart_pathexcept Exception as e:return f"❌ An error occurred processing the file: {str(e)}", None# 3. Design the custom layout using Gradio Blockswith gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# 📊 Visual Cloud AI Data Analyst")gr.Markdown("Upload a CSV file, ask a question, or tell the AI exactly what kind of chart to build.")with gr.Row():with gr.Column(scale=1):file_input = gr.File(label="Step 1: Upload CSV Dataset", file_types=[".csv"])question_input = gr.Textbox(label="Step 2: Ask a question or request a graph",placeholder="e.g., 'Make a bar chart of sales by region' or 'Plot a histogram of ages'...")submit_btn = gr.Button("Analyze & Generate Chart", variant="primary")with gr.Column(scale=1):output_text = gr.Markdown(label="AI Written Insights")output_image = gr.Image(label="Generated Data Visualization", type="filepath")# Connect the inputs to the function when clicking the buttonsubmit_btn.click(fn=analyze_and_plot,inputs=[file_input, question_input],outputs=[output_text, output_image])# 4. Launch the public cloud server
app.py+51-20