Spaces:
Runtime error
Runtime error
Update app.py
Browse files12 unmodified lines131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585 unmodified lines64656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215312 unmodified linesapi_key = os.environ.get('GEMINI_API_KEY')client = genai.Client(api_key=api_key)# 2. Define the core data, plotting, and machine learning logicdef analyze_and_plot(uploaded_file, user_question):if uploaded_file is None:return "⚠️ Please upload a CSV file first.", None, gr.update(visible=False), gr.update(visible=False)try:# Clear previous session filesplt.close('all')for f in ["analysis_report.txt", "output_chart.png", "cleaned_dataset.csv"]:if os.path.exists(f):os.remove(f)# Read the uploaded CSV file using Pandasdf = pd.read_csv(uploaded_file.name)# Gather basic details about the datasetrow_count = len(df)col_count = len(df.columns)column_names = ", ".join(df.columns.tolist())data_preview = df.head(3).to_string()data_types = df.dtypes.to_string()missing_values = df.isnull().sum().to_string()# Comprehensive system instructions enabling advanced Machine Learning taskssystem_context = (f"You are an expert Python Data Scientist and Machine Learning Engineer. The user has uploaded a dataset.\n"f"Dataset Statistics:\n"f"- Total Rows: {row_count}\n"f"- Total Columns: {col_count}\n"f"- Column Names: {column_names}\n\n"f"Data Types:\n{data_types}\n\n"f"Missing Values per column:\n{missing_values}\n\n"f"Preview:\n{data_preview}\n\n"f"INSTRUCTIONS:\n"f"1. Answer the user's question clearly.\n"f"2. You are fully capable of implementing: Linear/Logistic Regression, Random Forests, Decision Trees, K-Means Clustering, and SVMs using 'sklearn'.\n"f"3. CRUCIAL FOR ML: If a model target or feature contains non-numeric text, write code using sklearn's 'LabelEncoder' or pandas 'get_dummies' to encode it to numeric values before fitting the model. Always drop or impute missing values inside the code block before training.\n"f"4. For classification/regression models, explicitly output evaluation metrics (Accuracy, F1-Score, Mean Squared Error, R-squared, etc.) via Python 'print()' or text response.\n"f"5. If a chart is requested (like a Decision Tree visual boundary, Feature Importance bar chart, K-Means scatter plot clusters, or Confusion Matrix), generate Python code using 'matplotlib.pyplot'. The LAST line must be: plt.savefig('output_chart.png')\n"f"6. Do not include plt.show(). Only save outputs to files.")# Send the metadata context and user query to Gemini5 unmodified linestext_response = response.textchart_path = None# Extract and execute the python code block generated by Geminiif "```python" in text_response:try:code_block = text_response.split("```python").split("```")# Setup string buffer to trap code outputs (e.g. classification reports)old_stdout = sys.stdoutredirected_output = sys.stdout = io.StringIO()# Create execution environmentlocal_vars = {'df': df, 'plt': plt}exec(code_block, {}, local_vars)sys.stdout = old_stdoutprinted_results = redirected_output.getvalue()if printed_results:text_response += f"\n\n### 🖥️ Machine Learning Execution Output:\n```text\n{printed_results}\n```"# Check for rendered chart imageif os.path.exists("output_chart.png"):chart_path = "output_chart.png"except Exception as e:# Restore output settings if it crashes during script executionsys.stdout = old_stdouttext_response += f"\n\n*(Note: ML execution script error: {str(e)})*"# Save the text reportwith open("analysis_report.txt", "w", encoding="utf-8") as f:f.write(text_response)# Check if a newly cleaned dataset CSV file was generatedcsv_update = gr.update(visible=False)if os.path.exists("cleaned_dataset.csv"):csv_update = gr.update(value="cleaned_dataset.csv", visible=True)text_response += "\n\n✅ **Success:** A processed dataset file has been generated. Use the download button below to grab it!"return text_response, chart_path, gr.update(value="analysis_report.txt", visible=True), csv_updateexcept Exception as e:return f"❌ An error occurred processing the file: {str(e)}", None, gr.update(visible=False), gr.update(visible=False)# 3. Design the expanded Machine Learning layout using Gradio Blockswith gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# 🤖 Cloud Machine Learning & Data Workspace")gr.Markdown("Upload a CSV file to automatically clean your data, train advanced Machine Learning models, and visually analyze results.")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: Define your Machine Learning or Data workflow",placeholder="e.g., 'Train a Random Forest classifier to predict...' or 'Cluster my data into 3 groups'...")submit_btn = gr.Button("Execute ML Pipeline", variant="primary")# Clickable Example Prompts Section covering brand new modelsgr.Examples(examples=[["Train a Random Forest model to predict [Target Column] using all other columns. Print out the model accuracy and display a feature importance bar chart."],["Run a K-Means clustering algorithm on [Column X] and [Column Y] to group the data into 3 clusters. Plot the clusters in different colors with their centroids."],["Build a Decision Tree classifier to predict [Target Column]. Print the classification report and plot a visual graph of the top nodes of the tree."],["Train a Support Vector Machine (SVM) to classify [Target Column] using [Feature 1] and [Feature 2]. Show model metrics."]],inputs=question_input,label="💡 Advanced Machine Learning Templates")with gr.Column(scale=1):output_text = gr.Markdown(label="AI Analysis & Model Metrics")with gr.Row():download_report_btn = gr.DownloadButton("📥 Download Model Report", visible=False)download_csv_btn = gr.DownloadButton("💾 Download Processed CSV", visible=False, variant="secondary")output_image = gr.Image(label="Model Visualization Chart", type="filepath")# Connect inputs to execution function and distribute interface updatessubmit_btn.click(fn=analyze_and_plot,inputs=[file_input, question_input],outputs=[output_text, output_image, download_report_btn, download_csv_btn])if __name__ == "__main__":demo.launch()12 unmodified lines13141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758595 unmodified lines656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713812 unmodified linesapi_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 error message, hide chart, disable download buttonreturn "⚠️ Please upload a CSV file first.", None, gr.update(visible=False)try:# Clear any previous figures and delete old reports to keep clean statesplt.close('all')if os.path.exists("analysis_report.txt"):os.remove("analysis_report.txt")if os.path.exists("output_chart.png"):os.remove("output_chart.png")# Read the uploaded CSV file using Pandasdf = pd.read_csv(uploaded_file.name)# Gather basic details about the dataset to feed the AI contextrow_count = len(df)col_count = len(df.columns)column_names = ", ".join(df.columns.tolist())data_preview = df.head(3).to_string()data_types = df.dtypes.to_string()# System instructions forcing Gemini to return structured code and metricssystem_context = (f"You are an expert Python Data Analyst. The user has uploaded a dataset.\n"f"Dataset Statistics:\n"f"- Total Rows: {row_count}\n"f"- 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 performing a regression or statistical test, you MUST explicitly state the key numerical metrics "f"(such as R-squared value, Slope/Coefficients, Intercept, or p-values) in your final written text response.\n"f"3. If a chart is requested, include a clean Python code block using 'matplotlib.pyplot' and 'sklearn'. "f"Assume the dataframe is loaded as 'df'.\n"f"4. Crucial: The LAST line of your chart code block must save the image exactly as: plt.savefig('output_chart.png')\n"f"5. Do not include plt.show(). Only save it to 'output_chart.png'.")# Send the metadata context and user query to Gemini5 unmodified linestext_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]# Setup a string buffer to catch anything the executed script tries to print outold_stdout = sys.stdoutredirected_output = sys.stdout = io.StringIO()# Create a safe execution environment containing the user's datalocal_vars = {'df': df, 'plt': plt}exec(code_block, {}, local_vars)# Restore normal system outputsys.stdout = old_stdoutprinted_results = redirected_output.getvalue()# If the script printed extra statistical text, add it to the final displayif printed_results:text_response += f"\n\n### 🖥️ Calculated Execution Output:\n```text\n{printed_results}\n```"# Check if the chart image file was successfully writtenif 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)})*"# Save the finalized text analysis into a downloadable file on the serverwith open("analysis_report.txt", "w", encoding="utf-8") as f:f.write(text_response)# Return text, chart path, and make the download button visible with the report file attachedreturn text_response, chart_path, gr.update(value="analysis_report.txt", visible=True)except Exception as e:return f"❌ An error occurred processing the file: {str(e)}", None, gr.update(visible=False)# 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, and download your final text reports easily.")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 model",placeholder="e.g., 'Run a linear regression between ColumnA and ColumnB'...")submit_btn = gr.Button("Analyze & Generate Chart", variant="primary")with gr.Column(scale=1):output_text = gr.Markdown(label="AI Written Insights")# The download button is hidden until an analysis runs successfullydownload_btn = gr.DownloadButton("📥 Download Text Report", visible=False)output_image = gr.Image(label="Generated Data Visualization", type="filepath")# Connect inputs to the execution function and distribute the 3 outputssubmit_btn.click(fn=analyze_and_plot,inputs=[file_input, question_input],outputs=[output_text, output_image, download_btn])# 4. Launch the public cloud serverif __name__ == "__main__":demo.launch()
app.py+46-61