Update app.py
Browse files5 unmodified lines678910111216 unmodified lines29303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461 unmodified line1481491501511521531544 unmodified lines15916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712285 unmodified linesimport osimport gradio as grimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport shap16 unmodified linesfrom sklearn.preprocessing import LabelEncoder, StandardScalerfrom sklearn.pipeline import Pipelinefrom datetime import datetime# from PIL import Image # PIL often implicitly used by matplotlib/wandb, explicit import usually not needed unless manipulating images directlyimport warningsimport joblib # For saving modelsfrom typing import List, Tuple, Optional # <--- ADDED IMPORT# Suppress common warnings (especially from SHAP/LIME/Sklearn)warnings.filterwarnings("ignore")# --- Authentication and Setup ---print("--- Initializing Setup ---")hf_token = os.getenv("HF_TOKEN")wandb_api_key = os.getenv("WANDB_API_KEY")# Initialize wandb run variable globally, helps manage state across functionswandb_run = None # Tracks the *current* active run (e.g., comparison or explainability)if not hf_token:print("Warning: HF_TOKEN environment variable not set. Hugging Face Hub features may fail.")else:try:login(token=hf_token)print("Hugging Face login successful.")except Exception as e:print(f"Hugging Face login failed: {e}")if not wandb_api_key:print("Warning: WANDB_API_KEY environment variable not set. WandB logging will be disabled.")# Initialize wandb in disabled mode if no key and not already initializedif wandb.run is None:try:wandb.init(mode="disabled")print("WandB initialized in disabled mode.")except Exception as e:print(f"Failed to initialize WandB in disabled mode: {e}")else:try:wandb.login(key=wandb_api_key)print("WandB login successful.")except Exception as e:print(f"WandB login failed: {e}. Disabling WandB.")if wandb.run is None:try:wandb.init(mode="disabled")print("WandB initialized in disabled mode due to login failure.")except Exception as e_init:print(f"Failed to initialize WandB in disabled mode: {e_init}")# SmolAgent initializationagent = None # Initialize agent to Nonetry:print("Initializing SmolAgent...")model_api = HfApiModel("mistralai/Mixtral-8x7B-Instruct-v0.1", token=hf_token)agent = CodeAgent(tools=[], model=model_api, additional_authorized_imports=["numpy", "pandas", "matplotlib.pyplot", "seaborn", "sklearn", "json", "os"])print("SmolAgent initialized successfully.")except Exception as e:print(f"Error initializing SmolAgent: {e}. AI Agent features might fail.")# Global variablesdf_global = Nonesplit_data_global = None # To store (X_train, X_test, y_train, y_test, label_encoder)comparison_results_global = None # To store comparison DataFramebest_model_details_global = None # To store {'name': best_name, 'model': best_model_obj, 'params': best_params}print("Global variables initialized.")print("--- Setup Complete ---")# --- Data Handling ---def clean_data(df):"""Cleans the input DataFrame."""print("Starting data cleaning...")df_cleaned = df.copy() # Work on a copy# Drop columns/rows that are entirely emptydf_cleaned = df_cleaned.dropna(how='all', axis=1).dropna(how='all', axis=0)print(f"Shape after dropping fully empty rows/cols: {df_cleaned.shape}")# Encode object columnsobject_cols = df_cleaned.select_dtypes(include='object').columnsif not object_cols.empty:print(f"Encoding object columns: {list(object_cols)}")for col in object_cols:# Convert to string first to handle mixed types or NaN representationsdf_cleaned[col] = df_cleaned[col].astype(str)df_cleaned[col] = LabelEncoder().fit_transform(df_cleaned[col])else:print("No object columns found to encode.")# Impute missing values in numeric columns with the meannumeric_cols = df_cleaned.select_dtypes(include=np.number).columnsif not numeric_cols.empty:cols_with_na = df_cleaned[numeric_cols].isnull().sum()cols_to_impute = cols_with_na[cols_with_na > 0].indexif not cols_to_impute.empty:print(f"Imputing NaNs with mean in columns: {list(cols_to_impute)}")for col in cols_to_impute: # Iterate through columns needing imputationmean_val = df_cleaned[col].mean()df_cleaned[col] = df_cleaned[col].fillna(mean_val)else:print("No NaNs found in numeric columns to impute.")else:print("No numeric columns found for NaN imputation.")print("Data cleaning finished.")return df_cleaneddef upload_file(file):"""Handles file upload, cleaning, and global state update."""global df_global, split_data_global, comparison_results_global, best_model_details_global# Reset all global states when a new file is uploaded or file is cleareddf_global = Nonesplit_data_global = Nonecomparison_results_global = None1 unmodified lineprint("Reset global data states on file change.")if file is None:# No file uploaded or file removed by userreturn pd.DataFrame({"Status": ["No file uploaded or file removed."]})print(f"Uploading file: {file.name}")4 unmodified lineselif ext in [".xls", ".xlsx"]:df = pd.read_excel(file.name)else:return pd.DataFrame({"Error": [f"Unsupported file type: {ext}"]})print(f"Original data shape: {df.shape}")df_cleaned = clean_data(df)print(f"Cleaned data shape: {df_cleaned.shape}")df_global = df_cleaned # Store the cleaned data# dependent globals (split_data_global, etc.) remain None until downstream functions are calledprint("Global DataFrame updated with cleaned data.")return df_global.head() # Return head of CLEANED data for previewexcept Exception as e:print(f"Error processing file {file.name}: {e}")# Ensure globals are None on errordf_global = Nonesplit_data_global = Nonecomparison_results_global = Nonebest_model_details_global = Nonereturn pd.DataFrame({"Error": [f"Failed to process file: {e}"]})# --- AI Agent Analysis ---def format_observations(observations):"""Formats the observations dictionary into HTML list items."""if not isinstance(observations, dict):return f"<p style='color: orange;'>Observations data is not a dictionary: {type(observations)}</p>"items_html = ""for key, value in observations.items():formatted_key = key.replace('_', ' ').title()if isinstance(value, (dict, list)):formatted_value = json.dumps(value, indent=2)value_html = f"<pre style='margin: 0; padding: 8px; background: #ffffff; border: 1px solid #ccc; border-radius: 4px; font-size: 0.9em; white-space: pre-wrap; word-wrap: break-word;'>{formatted_value}</pre>"else:formatted_value = str(value)value_html = f"<p style='margin: 0; padding: 8px; background: #ffffff; border: 1px solid #ccc; border-radius: 4px; font-size: 0.9em;'>{formatted_value}</p>"items_html += f"""<div style="margin-bottom: 12px; padding: 10px; background: #fdfefe; border-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);"><h4 style="margin: 0 0 8px 0; color: #34495e;">{formatted_key}</h4>{value_html}</div>"""return items_html if items_html else "<p>No observations found.</p>"def format_insights(insights, visuals):"""Formats insights and embeds corresponding visuals."""if not isinstance(insights, dict):return f"<p style='color: orange;'>Insights data is not a dictionary: {type(insights)}</p>"items_html = ""visual_idx = 0insight_keys = list(insights.keys())for i, key in enumerate(insight_keys):insight_text = str(insights[key])formatted_key = key.replace('_', ' ').title()items_html += f"""<div style="margin: 20px 0; padding: 15px; background: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);"><h4 style='margin-top: 0; margin-bottom: 10px; color: #16a085;'>Insight {i+1}: {formatted_key}</h4><p style="margin-bottom: 15px;">{insight_text}</p>"""# Embed visual if available for this insight indexif visual_idx < len(visuals):img_path = visuals[visual_idx]# Gradio uses /file= syntax for temporary files# Ensure path is correctly formatted for Gradio's file servingitems_html += f'<img src="/file={img_path}" alt="Visualization for {formatted_key}" style="max-width: 95%; height: auto; display: block; margin-top: 10px; border-radius: 6px; border: 1px solid #eee; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">'visual_idx += 1items_html += "</div>"# Add any remaining visualsif visual_idx < len(visuals):items_html += "<h4 style='margin-top: 25px; color: #2980b9;'>Additional Visualizations:</h4>"for i in range(visual_idx, len(visuals)):img_path = visuals[i]items_html += f"""<div style="margin: 20px 0; padding: 15px; background: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);"><img src="/file={img_path}" alt="Additional Visualization {i+1}" style="max-width: 95%; height: auto; display: block; margin: auto; border-radius: 6px; border: 1px solid #eee; box-shadow: 0 1px 3px rgba(0,0,0,0.1);"></div>"""return items_html if (items_html or visuals) else "<p>No insights or visuals generated/found.</p>" # Show message only if both emptydef format_analysis_report(raw_output, visuals):"""Formats the AI agent's output into readable HTML."""print("Formatting AI analysis report...")report_html = ""analysis_dict = {}parsing_error = Nonetry:# Attempt to parse the output string into a dictionaryif isinstance(raw_output, str):cleaned_output = raw_output.strip()if cleaned_output.startswith("```python"):cleaned_output = cleaned_output[len("```python"):].strip()elif cleaned_output.startswith("```json"):cleaned_output = cleaned_output[len("```json"):].strip()if cleaned_output.endswith("```"):cleaned_output = cleaned_output[:-len("```")].strip()dict_start_index = cleaned_output.find('{')if dict_start_index != -1:# Try parsing from the first bracetry:analysis_dict = ast.literal_eval(cleaned_output[dict_start_index:])except (SyntaxError, ValueError, TypeError) as e:parsing_error = f"Error parsing agent output: {e}\nRaw output:\n{raw_output}"print(parsing_error)else:parsing_error = f"Could not find dictionary start '{{' in agent output.\nRaw output:\n{raw_output}"print(parsing_error)elif isinstance(raw_output, dict):analysis_dict = raw_output # Already a dictelse:parsing_error = f"Output is not a string or dictionary, type: {type(raw_output)}.\nRaw output:\n{str(raw_output)}"print(parsing_error)# --- Build HTML Report ---report_html = """<div style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; padding: 15px; border: 1px solid #ddd; border-radius: 8px; background-color: #f9f9f9;"><h1 style="color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; margin-top: 0;">📊 AI Data Analysis Report</h1>"""# Display parsing error if anyif parsing_error:report_html += f"<div style='background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; padding: 10px; border-radius: 5px; margin-bottom: 15px;'><pre>{parsing_error}</pre></div>"# Observations Sectionobservations = analysis_dict.get('observations', {})report_html += """<div style="margin-top: 20px; background: #ecf0f1; padding: 15px; border-radius: 5px;"><h2 style="color: #2980b9; margin-top: 0;">🔍 Key Observations</h2>"""report_html += format_observations(observations) if observations else "<p>No 'observations' found or parsed.</p>"report_html += "</div>"# Insights Sectioninsights = analysis_dict.get('insights', {})report_html += """<div style="margin-top: 25px;"><h2 style="color: #2980b9;">💡 Insights & Visualizations</h2>"""# Format insights and add visualsreport_html += format_insights(insights, visuals) if (insights or visuals) else "<p>No 'insights' or visuals found or parsed.</p>"report_html += "</div>"report_html += "</div>" # Close main containerprint("Report formatting complete.")return report_html, visualsexcept Exception as e:print(f"Critical error in format_analysis_report: {e}")error_message = f"<p style='color: red; font-weight: bold;'>Error generating report:</p><pre>{str(e)}</pre>"raw_display = f"<p style='font-weight: bold;'>Raw Agent Output:</p><pre>{str(raw_output)}</pre>"return error_message + raw_display, visualsdef analyze_data(csv_file, additional_notes=""):"""Runs the SmolAgent for data analysis and visualization."""global df_global, agent # Need agent globallyif df_global is None:return "<p style='color:red;'>Please upload a file first.</p>", []if agent is None:return "<p style='color:red;'>AI Agent is not available (initialization failed).</p>", []if csv_file is None: # Check if file object existsreturn "<p style='color:red;'>File object missing, please re-upload.</p>", []print("--- Starting AI Agent Analysis ---")start_time = time.time()process = psutil.Process(os.getpid())initial_memory = process.memory_info().rss / 1024 ** 2# Ensure figures directory exists and is emptyfigures_dir = './figures'try:if os.path.exists(figures_dir):shutil.rmtree(figures_dir)print(f"Cleaned existing directory: {figures_dir}")os.makedirs(figures_dir)print(f"Created directory: {figures_dir}")except Exception as e:print(f"Error managing figures directory: {e}")return f"<p style='color:red;'>Error setting up visualization directory: {e}</p>", []# --- WandB Setup for Agent Run ---wandb_run_agent = Nonerun_name = f"AgentAnalysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}"if wandb.run is None or wandb.run.mode != "disabled":try:# Finish any potentially lingering run firstif wandb.run and wandb.run.id:print(f"Finishing potentially active WandB run ({wandb.run.id}) before Agent run.")wandb.finish()wandb_run_agent = wandb.init(project="ai-data-analysis-gradio",name=run_name,config={"model": "mistralai/Mixtral-8x7B-Instruct-v0.1","agent_type": "CodeAgent","task": "EDA and Visualization","additional_notes": additional_notes,"source_file": os.path.basename(csv_file.name) if csv_file else "N/A","data_shape": df_global.shape},reinit=True)print(f"WandB run '{run_name}' initialized for Agent Analysis.")except Exception as e:print(f"Error initializing WandB run for Agent Analysis: {e}")wandb_run_agent = None # Ensure run is None if init failselse:print("WandB disabled, skipping Agent run logging.")# --- Run Agent ---analysis_result = Nonevisuals = []try:prompt = f"""Analyze the provided dataset (available as `df_global`).Focus on generating clear insights and high-quality visualizations.**Tasks:**1. **Load Data:** The data is already loaded into the `df_global` pandas DataFrame. Use this DataFrame directly.2. **Understand Data:** Briefly describe the data (shape, columns, basic types). Put in 'observations'.3. **Generate Observations:** Provide at least 3 key statistical observations (e.g., correlations, value distributions, unique counts). Structure this under an 'observations' key in your output dictionary.4. **Generate Insights:** Extract at least 5 meaningful insights from the data. These should be understandable conclusions or patterns discovered. Structure this under an 'insights' key in your output dictionary.5. **Create Visualizations:** Generate exactly 5 publication-quality visualizations (e.g., histograms, scatter plots, heatmaps, bar charts) that support your insights.* **Save EACH plot** to the './figures/' directory with a unique name (e.g., './figures/plot_1.png', './figures/plot_2.png'). Use `plt.savefig('./figures/unique_name.png', bbox_inches='tight')` and `plt.clf()` after each plot.* Make sure plots have titles and clear labels.* **DO NOT** use `plt.show()`.**Output Format:**Return a Python dictionary strictly following this structure:{{'observations': {{'data_description': 'Brief description...','observation_1_key': 'Description of observation 1.',# ... more observations}},'insights': {{'insight_1_key': 'Description of insight 1.',# ... more insights}}}}**Additional Context/Requests:** {additional_notes}Ensure all code is executable. Access the data using the variable `df_global`."""print("Running AI agent...")# Pass the DataFrame in additional_args# IMPORTANT: Ensure your SmolAgent setup correctly handles passing DataFrames.# If not, you might need to save df_global to a temporary CSV and pass the path.analysis_result = agent.run(prompt, additional_args={"df_global": df_global.copy()}) # Pass a copyprint("AI agent finished.")# print(f"Raw Agent Output:\n{analysis_result}") # For debugging# Check for generated figuresif os.path.exists(figures_dir):visuals = [os.path.join(figures_dir, f) for f in os.listdir(figures_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg'))]print(f"Found {len(visuals)} visualizations in {figures_dir}.")# Filter out invalid paths (e.g., if agent created non-image files)visuals = [v for v in visuals if os.path.isfile(v)]else:print(f"Warning: Figures directory '{figures_dir}' not found after agent run.")except Exception as e:print(f"Error during AI agent execution: {e}")import tracebacktraceback.print_exc()if wandb_run_agent: wandb_run_agent.finish(exit_code=1)return f"<p style='color:red;'>Error running AI agent: {e}</p>", []# --- Logging and Cleanup ---execution_time = time.time() - start_timefinal_memory = process.memory_info().rss / 1024 ** 2memory_usage = final_memory - initial_memoryprint(f"Agent execution time: {execution_time:.2f}s")print(f"Memory usage during agent execution: {memory_usage:.2f} MB")if wandb_run_agent:try:wandb.log({"agent_execution_time_sec": execution_time,"agent_memory_usage_mb": memory_usage,"visualizations_generated": len(visuals)}, commit=False) # Commit later or let finish handle it# Log visualizationslogged_images_count = 0for viz_path in visuals:if os.path.exists(viz_path):try:img_name = os.path.basename(viz_path)wandb.log({f"agent_visualization_{img_name}": wandb.Image(viz_path)}, commit=False)logged_images_count += 1except Exception as log_e:print(f"Warning: Could not log image {viz_path} to WandB: {log_e}")else:print(f"Warning: Visualization path not found for logging: {viz_path}")print(f"Attempted to log {logged_images_count}/{len(visuals)} visualizations to WandB.")# Log the raw analysis result textlog_data = {}if analysis_result:log_data["agent_raw_output"] = str(analysis_result)[:10000] # Truncate long outputwandb.log(log_data, commit=True) # Commit logs hereprint("Logged agent results to WandB.")except Exception as e:print(f"Error logging agent results to WandB: {e}")finally:wandb_run_agent.finish()print(f"WandB run '{run_name}' finished.")# Format reportreturn format_analysis_report(analysis_result, visuals)# --- Model Training and Comparison ---def prepare_data(df, target_column=None):"""Prepares data for modeling (selects target, splits, handles encoding)."""global split_data_global # Allow modification of global stateprint("--- Preparing Data for Modeling ---")if df is None or df.empty:print("Error: DataFrame is None or empty in prepare_data.")raise ValueError("Cannot prepare data: DataFrame is empty.")# Determine target column if not specifiedif target_column is None:target_column = df.columns[-1] # Default to last columnprint(f"Target column automatically selected: '{target_column}'")elif target_column not in df.columns:print(f"Error: Specified target column '{target_column}' not found.")raise ValueError(f"Target column '{target_column}' not found.")else:print(f"Using specified target column: '{target_column}'")X = df.drop(columns=[target_column])y = df[target_column].copy() # Use copy to avoid SettingWithCopyWarning# Ensure target `y` is numeric for classification/regression modelsle = None # LabelEncoder objectif y.dtype == 'object' or pd.api.types.is_categorical_dtype(y):print(f"Encoding target column '{target_column}' with LabelEncoder.")le = LabelEncoder()y = le.fit_transform(y) # Overwrite y with encoded valuesprint(f"Target classes found: {le.classes_}") # Useful for interpretation later# Check for non-numeric features (should be handled by clean_data, but as safeguard)non_numeric_cols = X.select_dtypes(exclude=np.number).columnsif not non_numeric_cols.empty:print(f"Warning: Non-numeric columns found in features after cleaning: {list(non_numeric_cols)}. Dropping them.")X = X.drop(columns=non_numeric_cols)if X.empty:print("Error: No features remaining after dropping non-numeric columns.")raise ValueError("No features remaining to train the model.")# Check if target has only one class after potential encoding/filteringif y.nunique() < 2:print(f"Error: Target column '{target_column}' has fewer than 2 unique values after processing. Cannot stratify or train meaningful classifier.")raise ValueError("Target column must have at least two unique classes for classification.")# Split datatry:X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42, stratify=y # Always try to stratify for classification)print(f"Data split: X_train {X_train.shape}, X_test {X_test.shape}, y_train {y_train.shape}, y_test {y_test.shape}")except ValueError as split_e:# This can happen if a class has too few members (e.g., only 1) for stratificationprint(f"Stratified split failed ({split_e}). Trying non-stratified split.")X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)print(f"Data split (non-stratified): X_train {X_train.shape}, X_test {X_test.shape}, y_train {y_train.shape}, y_test {y_test.shape}")# Store the split data AND the label encoder if usedsplit_data_global = (X_train, X_test, y_train, y_test, le) # Add le to the tupleprint("Data prepared and split stored globally.")return X_train, X_test, y_train, y_testdef train_and_compare_models(tune_rf=True, tune_gb=True, n_trials_optuna=10):"""Trains, (optionally) tunes, evaluates multiple models, and logs comparison."""global df_global, split_data_global, comparison_results_global, best_model_details_global, wandb_runif df_global is None:print("Error: No data loaded for training/comparison.")return pd.DataFrame({"Error": ["Please upload data first."]})print("--- Starting Model Training and Comparison ---")run_name = f"CompareModels_{datetime.now().strftime('%Y%m%d_%H%M%S')}"models_to_compare = {# Use Pipelines for models benefiting from scaling"LogisticRegression": Pipeline([('scaler', StandardScaler()), ('logreg', LogisticRegression(max_iter=1000, random_state=42, class_weight='balanced'))]),"RandomForest": RandomForestClassifier(random_state=42, class_weight='balanced'), # Add class_weight"GradientBoosting": GradientBoostingClassifier(random_state=42) # GB doesn't have class_weight in quite the same way}# Filter models based on input type (add later if needed)# is_classification = True # Assume classification for nowconfig = {"task": "Model Comparison","models": list(models_to_compare.keys()),"tune_rf": tune_rf,"tune_gb": tune_gb,"optuna_trials": n_trials_optuna if (tune_rf or tune_gb) else 0,"data_shape": df_global.shape,"test_size": 0.3,"stratify": True # Assuming stratification was attempted}# --- WandB Setup for Comparison Run ---if wandb.run is None or wandb.run.mode != "disabled":try:# Finish any potentially lingering run firstif wandb.run and wandb.run.id:print(f"Finishing potentially active WandB run ({wandb.run.id}) before Comparison run.")wandb.finish()wandb_run = wandb.init(project="ai-data-analysis-gradio", name=run_name, config=config, reinit=True)print(f"WandB run '{run_name}' initialized for Model Comparison.")except Exception as e:print(f"Error initializing WandB run for Comparison: {e}")wandb_run = None # Ensure it's None if init failselse:print("WandB disabled, skipping Comparison run logging.")wandb_run = None # Explicitly set to None if disabledresults = []best_f1 = -1 # Initialize best F1 scorebest_model_obj = Nonebest_model_name = Nonebest_model_params = Nonetry:# Prepare data if not already splitif split_data_global:print("Using previously split data.")X_train, X_test, y_train, y_test, _ = split_data_global # Unpack (ignore label encoder here)else:print("Preparing data for comparison...")# Use default target (last column) if prepare_data hasn't been runX_train, X_test, y_train, y_test = prepare_data(df_global)# --- Optuna Objective Functions ---# (Ensure X_train, y_train are accessible within objectives)def objective_rf(trial):params = {"n_estimators": trial.suggest_int("n_estimators", 50, 250, step=50),"max_depth": trial.suggest_int("max_depth", 5, 20, log=True), # Log scale for depth"min_samples_split": trial.suggest_int("min_samples_split", 2, 16),"min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 16),"criterion": trial.suggest_categorical("criterion", ["gini", "entropy"]),"class_weight": trial.suggest_categorical("class_weight", ["balanced", "balanced_subsample", None]),"random_state": 42}# Note: class_weight='balanced' might require specific sklearn version or handlingtry:model = RandomForestClassifier(**params)# Use smaller CV during tuning for speedscore = cross_val_score(model, X_train, y_train, cv=3, scoring="f1_weighted", n_jobs=-1).mean() # Tune based on F1 weightedif wandb_run: wandb.log({"optuna_rf_trial": trial.number, "optuna_rf_cv_f1w": score, **params}, commit=False)return scoreexcept ValueError as e:print(f"Optuna RF trial error (params {params}): {e}")return -1 # Return poor score on errordef objective_gb(trial):params = {"n_estimators": trial.suggest_int("n_estimators", 50, 250, step=50),"learning_rate": trial.suggest_float("learning_rate", 0.01, 0.3, log=True),"max_depth": trial.suggest_int("max_depth", 3, 10),"min_samples_split": trial.suggest_int("min_samples_split", 2, 16),"min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 16),"subsample": trial.suggest_float("subsample", 0.6, 1.0),"random_state": 42}try:model = GradientBoostingClassifier(**params)score = cross_val_score(model, X_train, y_train, cv=3, scoring="f1_weighted", n_jobs=-1).mean() # Tune based on F1 weightedif wandb_run: wandb.log({"optuna_gb_trial": trial.number, "optuna_gb_cv_f1w": score, **params}, commit=False)return scoreexcept ValueError as e:print(f"Optuna GB trial error (params {params}): {e}")return -1# --- Model Training Loop ---for name, model_pipeline in models_to_compare.items(): # Use model_pipeline for clarityprint(f"--- Training and Evaluating: {name} ---")start_time = time.time()current_params = model_pipeline.get_params() # Start with default/pipeline paramsfinal_model = model_pipeline # The model/pipeline to be trainedtry:# Optional Tuning with Optunaif name == "RandomForest" and tune_rf:print(f"Tuning {name} with Optuna ({n_trials_optuna} trials)...")study_rf = optuna.create_study(direction="maximize", study_name=f"{name}_tune_{run_name}")study_rf.optimize(objective_rf, n_trials=n_trials_optuna, timeout=300)best_params_rf = study_rf.best_params# Important: Re-initialize the model *without* pipeline for RF tuningfinal_model = RandomForestClassifier(**best_params_rf, random_state=42)current_params = final_model.get_params() # Update params to tuned onesprint(f"Best RF params (CV F1w: {study_rf.best_value:.4f}): {best_params_rf}")if wandb_run: wandb.log({f"{name}_best_cv_f1w": study_rf.best_value, f"{name}_best_params": best_params_rf}, commit=False)elif name == "GradientBoosting" and tune_gb:print(f"Tuning {name} with Optuna ({n_trials_optuna} trials)...")study_gb = optuna.create_study(direction="maximize", study_name=f"{name}_tune_{run_name}")study_gb.optimize(objective_gb, n_trials=n_trials_optuna, timeout=300)best_params_gb = study_gb.best_paramsfinal_model = GradientBoostingClassifier(**best_params_gb, random_state=42)current_params = final_model.get_params()print(f"Best GB params (CV F1w: {study_gb.best_value:.4f}): {best_params_gb}")if wandb_run: wandb.log({f"{name}_best_cv_f1w": study_gb.best_value, f"{name}_best_params": best_params_gb}, commit=False)# Train the final model (tuned or default/pipeline)final_model.fit(X_train, y_train)# Evaluate on the test sety_pred = final_model.predict(X_test)accuracy = accuracy_score(y_test, y_pred)# Use weighted avg for metrics suitable for multi-class and imbalanced datasetsprecision = precision_score(y_test, y_pred, average="weighted", zero_division=0)recall = recall_score(y_test, y_pred, average="weighted", zero_division=0)f1 = f1_score(y_test, y_pred, average="weighted", zero_division=0)duration = time.time() - start_timeprint(f"{name} Test Set - Accuracy: {accuracy:.4f}, F1 (Weighted): {f1:.4f}, Time: {duration:.2f}s")metrics = {"Model": name,"Test Accuracy": accuracy, # Changed key for clarity"Test Precision (Weighted)": precision,"Test Recall (Weighted)": recall,"Test F1 Score (Weighted)": f1,"Training Time (s)": duration,"Tuned": (name == "RandomForest" and tune_rf) or (name == "GradientBoosting" and tune_gb)}results.append(metrics)# Log individual model metrics to WandBif wandb_run:# Create a flat dictionary for logginglog_metrics = {f"{name}_{k.lower().replace(' (weighted)','_w').replace(' ','_')}": vfor k, v in metrics.items() if k not in ["Model", "Tuned"]}log_metrics[f"{name}_tuned_flag"] = metrics["Tuned"]wandb.log(log_metrics, commit=False)# Check if this is the best model so far based on F1 scoreif f1 > best_f1:print(f"*** New best model found: {name} (F1: {f1:.4f}) ***")best_f1 = f1best_model_name = namebest_model_obj = final_model # Store the fitted model/pipeline objectbest_model_params = current_params # Store its parametersexcept Exception as train_e:print(f"ERROR training/evaluating {name}: {train_e}")import tracebacktraceback.print_exc()results.append({"Model": name, "Error": str(train_e)})if wandb_run: wandb.log({f"{name}_error": str(train_e)}, commit=False)# --- Finalize Comparison ---if not results:print("No models were successfully trained.")return pd.DataFrame({"Status": ["Model training failed for all candidates."]})comparison_df = pd.DataFrame(results)# Handle cases where F1 score might be missing due to errorsif "Test F1 Score (Weighted)" in comparison_df.columns:comparison_df = comparison_df.sort_values(by="Test F1 Score (Weighted)", ascending=False).reset_index(drop=True)else:print("Warning: F1 score column missing, cannot sort results.")comparison_results_global = comparison_df # Store globallyprint("\n--- Model Comparison Summary ---")print(comparison_df.to_string())# Store best model details globally if foundif best_model_obj is not None:best_model_details_global = {'name': best_model_name,'model': best_model_obj, # Store the actual fitted model/pipeline'params': best_model_params, # Store params used (tuned or default)'f1_score': best_f1}print(f"Stored details for best model: {best_model_name}")# Optional: Save the best model artifact locally and log to WandBoutput_dir_models = "./saved_models"os.makedirs(output_dir_models, exist_ok=True)model_filename = os.path.join(output_dir_models, f"best_model_{best_model_name.lower().replace(' ','_')}.joblib")try:joblib.dump(best_model_obj, model_filename)print(f"Best model saved locally to {model_filename}")if wandb_run:# Log artifact to WandB# Clean params dict for artifact metadata (remove complex objects if any)clean_params_meta = {k: str(v)[:250] for k, v in best_model_params.items() if isinstance(v, (str, int, float, bool, list, type(None)))} # Truncate long stringsartifact = wandb.Artifact(f'best_model-{wandb_run.id}', type='model',metadata={'model_type': best_model_name, 'test_f1_score': best_f1, **clean_params_meta})artifact.add_file(model_filename)wandb_run.log_artifact(artifact)print("Logged best model artifact to WandB.")except Exception as save_e:print(f"Error saving/logging best model artifact: {save_e}")# Log comparison table to WandBif wandb_run and not comparison_df.empty:try:# Filter out potential error rows before creating tablevalid_comparison_df = comparison_df.dropna(subset=[col for col in comparison_df.columns if col != 'Error'])if not valid_comparison_df.empty:wandb_comparison_table = wandb.Table(dataframe=valid_comparison_df)wandb_run.log({"model_comparison_summary": wandb_comparison_table}, commit=True) # Commit final logsprint("Logged comparison summary table to WandB.")else:print("No valid results to log to WandB table.")except Exception as log_e:print(f"Error logging comparison table to WandB: {log_e}")return comparison_dfexcept Exception as e:print(f"An error occurred during model comparison: {e}")import tracebacktraceback.print_exc()if wandb_run: wandb_run.finish(exit_code=1) # Mark run as failedreturn pd.DataFrame({"Error": [f"Comparison failed: {e}"]})finally:if wandb_run and wandb.run: # Check if wandb_run was initialized and is still active# Ensure logs are committed before finishingtry:wandb.log({}, commit=True)except Exception:pass # Ignore if already finished or other issuewandb_run.finish()print(f"WandB run '{run_name}' finished.")wandb_run = None # Reset global run variable# --- Model Explainability ---# ADDED TYPE HINT HEREdef explainability(_=None) -> Tuple[List[str], Optional[str], str]:"""Generates SHAP and LIME explanations for the best performing model."""global split_data_global, best_model_details_global, wandb_runif split_data_global is None:print("Error: Data not split. Please run 'Train & Compare' first.")# Ensure return matches type hint on errorreturn [], None, "Error: Data not prepared. Run 'Train & Compare' first."if best_model_details_global is None:print("Error: Best model details not found. Please run 'Train & Compare' first.")# Ensure return matches type hint on errorreturn [], None, "Error: Best model not identified. Run 'Train & Compare' first."X_train, X_test, y_train, y_test, label_encoder = split_data_global # Unpack label encoderbest_model_name = best_model_details_global['name']best_model = best_model_details_global['model'] # Use the stored, already fitted best model/pipelineprint(f"--- Generating explanations for the best model: {best_model_name} ---")# Define paths dynamically within a dedicated directoryoutput_dir = "./explainability_plots"if os.path.exists(output_dir): shutil.rmtree(output_dir)os.makedirs(output_dir)shap_summary_path = os.path.join(output_dir, f"shap_summary_{best_model_name}.png")shap_dep_paths = [] # Store paths for dependence plotslime_path = os.path.join(output_dir, f"lime_instance_{best_model_name}.png")status_message = f"Explaining best model: {best_model_name}"all_shap_paths = [] # Initialize empty list for gallery output# --- WandB Setup for Explainability Run ---run_name = f"Explain_{best_model_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"config = {"task": "Explainability", "best_model": best_model_name, "explainers": ["SHAP", "LIME"]}wandb_run_explain = Noneif wandb.run is None or wandb.run.mode != "disabled":try:# Finish any potentially lingering run firstif wandb.run and wandb.run.id:print(f"Finishing potentially active WandB run ({wandb.run.id}) before Explainability run.")wandb.finish()wandb_run_explain = wandb.init(project="ai-data-analysis-gradio", name=run_name, config=config, reinit=True)print(f"WandB run '{run_name}' initialized for Explainability.")except Exception as e:print(f"Error initializing Wandb run for Explainability: {e}")wandb_run_explain = None # Ensure it's None if init failselse:print("WandB disabled, skipping Explainability run logging.")wandb_run_explain = Nonetry:# --- SHAP Explanation ---print("Calculating SHAP values...")shap_values = Noneexplainer = NoneX_test_for_shap = X_test # Data to pass to SHAP (might be transformed)# Determine explainer type and get SHAP valuesif isinstance(best_model, (RandomForestClassifier, GradientBoostingClassifier)):print("Using SHAP TreeExplainer for standalone tree model.")explainer = shap.TreeExplainer(best_model)shap_values = explainer.shap_values(X_test) # Use original X_testelif isinstance(best_model, Pipeline):final_estimator_name, final_estimator = best_model.steps[-1]print(f"Handling Pipeline. Final estimator: {final_estimator_name} ({type(final_estimator)})")pipeline_transforms = Pipeline(best_model.steps[:-1]) # Get all steps EXCEPT the last oneif isinstance(final_estimator, (RandomForestClassifier, GradientBoostingClassifier)):print("Using SHAP TreeExplainer for tree model within Pipeline.")# Need to transform data using the pipeline's transform steps firsttry:print("Transforming data using pipeline steps before TreeExplainer...")# Ensure pipeline_transforms is fitted if it contains steps like StandardScalerif hasattr(pipeline_transforms, 'fit_transform') and len(pipeline_transforms.steps) > 0:X_train_transformed = pipeline_transforms.fit_transform(X_train) # Fit on trainX_test_transformed = pipeline_transforms.transform(X_test) # Transform testelif len(pipeline_transforms.steps) == 0: # No transform stepsX_test_transformed = X_test.copy()else: # Has steps but maybe no fit_transform (unlikely for standard sklearn)print("Warning: Pipeline transform steps might not be fitted/applied correctly.")X_test_transformed = pipeline_transforms.transform(X_test)X_test_for_shap = pd.DataFrame(X_test_transformed, columns=X_test.columns, index=X_test.index) # Keep index/columnsprint("Data transformed.")# Explain the final estimator using the *transformed* dataexplainer = shap.TreeExplainer(final_estimator)shap_values = explainer.shap_values(X_test_for_shap)except Exception as transform_e:print(f"ERROR transforming data for TreeExplainer in Pipeline: {transform_e}. Skipping SHAP.")import tracebacktraceback.print_exc()elif isinstance(final_estimator, LogisticRegression):print("Using SHAP KernelExplainer for Logistic Regression in Pipeline (can be slow)...")# Define the prediction function for the *entire* pipelinepredict_proba_pipeline = lambda x_np: best_model.predict_proba(pd.DataFrame(x_np, columns=X_test.columns))print("Summarizing training data for KernelExplainer background...")# Use original X_train for background summaryX_train_summary = shap.kmeans(X_train.values, min(100, X_train.shape[0]), random_state=42) # Use .valuesexplainer = shap.KernelExplainer(predict_proba_pipeline, X_train_summary)subset_size = min(50, X_test.shape[0])print(f"Calculating SHAP values for {subset_size} test instances...")X_test_subset_np = X_test.sample(subset_size, random_state=42).valuesshap_values = explainer.shap_values(X_test_subset_np, nsamples='auto') # Let SHAP choose nsamples# Create DataFrame from subset for plotting consistencyX_test_for_shap = pd.DataFrame(X_test_subset_np, columns=X_test.columns) # Use subset for plottingprint("SHAP values calculated using KernelExplainer.")else:print(f"Warning: SHAP not implemented for final pipeline step {type(final_estimator)}. Skipping SHAP.")else:print(f"Warning: SHAP not explicitly handled for model type {type(best_model)}. Skipping SHAP.")# --- Generate SHAP Plots (if shap_values exist) ---if shap_values is not None:num_classes = len(np.unique(y_train))class_names = getattr(label_encoder, 'classes_', [f'Class {i}' for i in range(num_classes)]) if label_encoder else [f'Class {i}' for i in range(num_classes)]class_names = [str(cn) for cn in class_names] # Ensure strings# SHAP Summary Plotprint("Generating SHAP summary plot...")plt.figure(figsize=(10, 6))try:plot_shap_values = shap_valuestitle_suffix = f"({best_model_name})"if num_classes == 2 and isinstance(shap_values, list) and len(shap_values) == 2:plot_shap_values = shap_values[1]positive_class_name = class_names[1] if len(class_names) > 1 else "Class 1"title_suffix = f"({best_model_name} - Class: {positive_class_name})"print(f"Plotting SHAP summary for positive class ({positive_class_name})")elif num_classes > 2 and isinstance(shap_values, list):title_suffix = f"({best_model_name} - Multiclass Avg Impact)"print("Plotting SHAP summary for multiclass (average impact)")shap.summary_plot(plot_shap_values, X_test_for_shap, show=False, plot_type="dot", class_names=class_names)plt.title(f"SHAP Feature Importance Summary {title_suffix}")plt.tight_layout()plt.savefig(shap_summary_path, bbox_inches='tight')plt.clf()print(f"SHAP summary plot saved to {shap_summary_path}")all_shap_paths.append(shap_summary_path)if wandb_run_explain: wandb.log({"shap_summary": wandb.Image(shap_summary_path)}, commit=False)except Exception as summary_e:print(f"Error generating SHAP summary plot: {summary_e}")plt.clf()# SHAP Dependence Plotsprint("Calculating global feature importance for dependence plots...")global_shap_values_mean = Nonetry:# Ensure features align between shap_values and X_test_for_shapnum_shap_features = -1if isinstance(shap_values, list) and len(shap_values) > 0 and isinstance(shap_values[0], np.ndarray):num_shap_features = shap_values[0].shape[1]elif isinstance(shap_values, np.ndarray) and shap_values.ndim >= 2:num_shap_features = shap_values.shape[1]if num_shap_features != -1 and num_shap_features != X_test_for_shap.shape[1]:print(f"Warning: Mismatch between SHAP features ({num_shap_features}) and plot data features ({X_test_for_shap.shape[1]}). Dependence plots might fail.")# Attempt to reconcile if possible (e.g., subset X_test_for_shap if SHAP used fewer features?) - complex, skip for now.if isinstance(shap_values, list):abs_shap_arrays = [np.abs(sv) for sv in shap_values if isinstance(sv, np.ndarray) and sv.ndim == 2 and sv.shape[0] == X_test_for_shap.shape[0] and sv.shape[1] == X_test_for_shap.shape[1]]if abs_shap_arrays:stacked_shap = np.stack(abs_shap_arrays, axis=0)global_shap_values_mean = stacked_shap.mean(axis=(0, 1))print(f"Calculated global SHAP values (list input), shape: {global_shap_values_mean.shape}")elif isinstance(shap_values, np.ndarray) and shap_values.ndim == 2 and shap_values.shape[0] == X_test_for_shap.shape[0] and shap_values.shape[1] == X_test_for_shap.shape[1]:global_shap_values_mean = np.abs(shap_values).mean(axis=0)print(f"Calculated global SHAP values (array input), shape: {global_shap_values_mean.shape}")else:print(f"Warning: SHAP values structure not suitable for global importance calculation or dimension mismatch. Shape: {getattr(shap_values, 'shape', 'N/A')}, Type: {type(shap_values)}")except Exception as gsi_e:print(f"Error calculating global SHAP importance: {gsi_e}")if global_shap_values_mean is not None and len(global_shap_values_mean) > 0:try:feature_indices = np.argsort(global_shap_values_mean)[::-1]num_features_to_plot = min(2, len(global_shap_values_mean))if num_features_to_plot > 0:top_feature_indices = feature_indices[:num_features_to_plot]valid_indices = [idx for idx in top_feature_indices if idx < len(X_test_for_shap.columns)]top_features = X_test_for_shap.columns[valid_indices]print(f"Generating SHAP dependence plots for top features: {list(top_features)}")for feature_idx, feature_name in zip(valid_indices, top_features):plt.figure(figsize=(8, 5))shap_values_for_dep = shap_valuesclass_idx_dep = 0if isinstance(shap_values, list):if num_classes == 2 and len(shap_values) == 2:shap_values_for_dep = shap_values[1]class_idx_dep = 1elif len(shap_values) > 0:shap_values_for_dep = shap_values[0]shap.dependence_plot(feature_idx, shap_values_for_dep, X_test_for_shap, interaction_index='auto', show=False)dep_title = f"SHAP Dependence: {feature_name} ({best_model_name})"if isinstance(shap_values, list): dep_title += f" (Class: {class_names[class_idx_dep]})"plt.title(dep_title)plt.tight_layout()dep_path = os.path.join(output_dir, f"shap_dependence_{best_model_name}_{feature_name}.png")plt.savefig(dep_path, bbox_inches='tight')plt.clf()shap_dep_paths.append(dep_path)all_shap_paths.append(dep_path)print(f"Saved dependence plot: {dep_path}")if wandb_run_explain: wandb.log({f"shap_dependence_{feature_name}": wandb.Image(dep_path)}, commit=False)else:print("Skipping dependence plots: Not enough features.")except Exception as dep_e:print(f"Could not generate SHAP dependence plots: {dep_e}")import tracebacktraceback.print_exc()plt.clf()else:print("Skipping dependence plots due to issue calculating global SHAP values.")else:print("Skipping SHAP plots as SHAP values were not generated.")# --- LIME Explanation ---print("Generating LIME explanation for the first test instance...")try:predict_fn_lime = Noneif hasattr(best_model, 'predict_proba'):def predict_proba_wrapper(x_np):x_df = pd.DataFrame(x_np, columns=X_train.columns)return best_model.predict_proba(x_df)predict_fn_lime = predict_proba_wrapperelse:print("Warning: Model lacks predict_proba. LIME results might be unreliable.")num_classes_lime = len(np.unique(y_train))predict_fn_lime = lambda x: np.ones((len(x), num_classes_lime)) / num_classes_limeclass_names_lime = getattr(label_encoder, 'classes_', [str(c) for c in sorted(np.unique(y_train))]) if label_encoder else [str(c) for c in sorted(np.unique(y_train))]class_names_lime = [str(cn) for cn in class_names_lime]lime_explainer = lime.lime_tabular.LimeTabularExplainer(training_data=X_train.values,feature_names=X_train.columns.tolist(),class_names=class_names_lime,mode='classification' if len(class_names_lime) > 1 else 'regression')instance_idx = 0instance_to_explain = X_test.iloc[instance_idx].valuestrue_class_encoded = y_test[instance_idx] if isinstance(y_test, np.ndarray) else y_test.iloc[instance_idx]true_class_label = class_names_lime[true_class_encoded] if label_encoder and true_class_encoded < len(class_names_lime) else str(true_class_encoded)lime_exp = lime_explainer.explain_instance(data_row=instance_to_explain,predict_fn=predict_fn_lime,num_features=10,num_samples=1000)print(f"LIME explanation generated for instance {instance_idx}.")lime_fig = lime_exp.as_pyplot_figure()predicted_class_idx = lime_exp.available_labels()[0]predicted_class_label = class_names_lime[predicted_class_idx] if predicted_class_idx < len(class_names_lime) else f"Index {predicted_class_idx}"lime_fig.suptitle(f"LIME Exp (Inst {instance_idx}, True: {true_class_label}, Pred: {predicted_class_label}, Model: {best_model_name})", y=1.03, fontsize=10)lime_fig.tight_layout(rect=[0, 0, 1, 0.98])lime_fig.savefig(lime_path, bbox_inches='tight')plt.clf()print(f"LIME plot saved to {lime_path}")if wandb_run_explain: wandb.log({"lime_explanation": wandb.Image(lime_path)}, commit=False)except Exception as lime_e:print(f"Error generating LIME explanation: {lime_e}")import tracebacktraceback.print_exc()if wandb_run_explain: wandb.log({"lime_error": str(lime_e)}, commit=False)lime_path = None # Indicate failure# Final status messagestatus_message = f"Explanations generated for {best_model_name}."if not all_shap_paths: status_message += " (SHAP failed/skipped or generated no plots)."if not lime_path or not os.path.exists(lime_path): status_message += " (LIME failed/skipped)." # Check existence# Return paths to the plots and statusvalid_lime_path = lime_path if lime_path and os.path.exists(lime_path) else Nonevalid_shap_paths = [p for p in all_shap_paths if p and os.path.exists(p)] # Filter out non-existent paths# --- Ensure return matches type hint ---return valid_shap_paths, valid_lime_path, status_messageexcept Exception as e:print(f"An error occurred during explainability: {e}")import tracebacktraceback.print_exc()status_message = f"Error during explanation: {e}"if wandb_run_explain: wandb_run_explain.finish(exit_code=1)# --- Ensure return matches type hint ---return [], None, status_messagefinally:plt.close('all') # Close all matplotlib figuresif wandb_run_explain and wandb.run and wandb.run.id == wandb_run_explain.id:try:wandb.log({}, commit=True) # Commit final logs for explain runwandb_run_explain.finish()print(f"WandB run '{run_name}' finished.")except Exception as finish_e:print(f"Error finishing WandB run {run_name}: {finish_e}")wandb_run_explain = None # Reset# --- Gradio Interface ---print("--- Setting up Gradio Interface ---")with gr.Blocks(theme=gr.themes.Soft(), title="AI Data Analysis & Model Comparison") as demo:gr.Markdown("""# 📊 AI Data Analysis, Model Comparison & ExplainabilityUpload data, get AI insights, compare models (Logistic Regression, RF, Gradient Boosting with optional Optuna tuning), and explain the best one.**Requires environment variables:** `HF_TOKEN` and `WANDB_API_KEY`. WandB logging tracks experiments.""")# --- Row 1: File Upload and Data Preview ---with gr.Row():with gr.Column(scale=1):file_input = gr.File(label="1. Upload CSV or Excel File", file_types=[".csv", ".xls", ".xlsx"], type="filepath")with gr.Column(scale=2):df_output = gr.DataFrame(label="Cleaned Data Preview (First 5 Rows)", interactive=False)# --- Row 2: AI Agent Analysis ---with gr.Accordion("🤖 Step 2 (Optional): Run AI Agent for Insights & Visuals", open=False):with gr.Row():with gr.Column(scale=1):agent_notes = gr.Textbox(label="Optional: Specific requests for the AI Agent", placeholder="e.g., 'Focus on correlations with column X'")agent_btn = gr.Button("Run AI Analysis", variant="secondary", interactive=(agent is not None)) # Disable if agent failed initwith gr.Column(scale=2):insights_output = gr.HTML(label="AI Agent Analysis Report")with gr.Row():visual_output = gr.Gallery(label="Visualizations (Generated by AI Agent)", height=350, object_fit="contain", columns=3, preview=True)# --- Row 3: Model Training & Comparison ---with gr.Accordion("⚙️ Step 3: Train & Compare Models", open=True): # Open by defaultwith gr.Row():with gr.Column(scale=1):tune_rf_checkbox = gr.Checkbox(label="Tune RandomForest (Optuna)", value=True)tune_gb_checkbox = gr.Checkbox(label="Tune GradientBoosting (Optuna)", value=True)optuna_trials_slider = gr.Slider(minimum=5, maximum=50, value=10, step=5, label="Optuna Trials per Model")compare_btn = gr.Button("Train & Compare Models", variant="primary")with gr.Column(scale=2):comparison_output = gr.DataFrame(label="Model Comparison Results (Sorted by Test F1 Score)", interactive=False)# --- Row 4: Model Explainability ---with gr.Accordion("💡 Step 4: Explain Best Model (SHAP & LIME)", open=False):with gr.Row():explain_btn = gr.Button("Generate Explanations for Best Model", variant="secondary")explain_status = gr.Textbox(label="Explanation Status", interactive=False)with gr.Row():# Use Gallery for SHAP as there can be multiple plotsshap_gallery = gr.Gallery(label="SHAP Plots (Summary + Top Feature Dependence)", elem_id="shap-gallery", height=450, object_fit="contain", columns=1, preview=True) # Better displaylime_img = gr.Image(label="LIME Explanation (for first test instance)", type="filepath", interactive=False)# --- Connect Components ---print("Connecting Gradio components...")# Link file upload to functionfile_input.change(fn=upload_file,inputs=file_input,outputs=df_output)# Link AI agent buttonagent_btn.click(fn=analyze_data,inputs=[file_input, agent_notes],outputs=[insights_output, visual_output])# Link model comparison buttoncompare_btn.click(fn=train_and_compare_models,inputs=[tune_rf_checkbox, tune_gb_checkbox, optuna_trials_slider],outputs=[comparison_output])# Link explain buttonexplain_btn.click(fn=explainability,inputs=[], # Uses global best model detailsoutputs=[shap_gallery, lime_img, explain_status] # Output list of SHAP plots, one LIME plot, and status)print("Gradio components connected.")# --- Launch the App ---if __name__ == "__main__":print("--- Cleaning up temporary directories/files ---")# Clean up temporary files/dirs from previous runs before launchingtemp_dirs = ['./figures', './explainability_plots', './saved_models', './__pycache__']temp_files = [] # Don't delete pngs automatically if they are inside the cleaned dirsfor d in temp_dirs:if os.path.exists(d):try:shutil.rmtree(d)print(f"Cleaned up directory: {d}")except Exception as e:print(f"Warning: Could not clean up directory {d}: {e}")for f in temp_files:if os.path.exists(f):try:os.remove(f)print(f"Cleaned up file: {f}")except Exception as e:print(f"Warning: Could not clean up file {f}: {e}")print("--- Launching Gradio App ---")demo.launch(debug=False, share=False) # Set debug=True for detailed Gradio errors if neededprint("--- Gradio App Closed ---")5 unmodified lines678910111216 unmodified lines29303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091 unmodified line1111121131141151161174 unmodified lines1221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455 unmodified linesimport osimport gradio as grimport pandas as pd # Make sure pandas is importedimport numpy as npimport matplotlib.pyplot as pltimport shap16 unmodified linesfrom sklearn.preprocessing import LabelEncoder, StandardScalerfrom sklearn.pipeline import Pipelinefrom datetime import datetime# from PIL import Imageimport warningsimport joblib # For saving modelsfrom typing import List, Tuple, Optional # Keep these# Suppress common warningswarnings.filterwarnings("ignore")# --- Authentication and Setup ---# (Keep Authentication and Setup block as before)print("--- Initializing Setup ---")hf_token = os.getenv("HF_TOKEN")wandb_api_key = os.getenv("WANDB_API_KEY")wandb_run = Noneif not hf_token: print("Warning: HF_TOKEN environment variable not set.")else:try: login(token=hf_token); print("Hugging Face login successful.")except Exception as e: print(f"Hugging Face login failed: {e}")if not wandb_api_key:print("Warning: WANDB_API_KEY environment variable not set. WandB logging will be disabled.")if wandb.run is None:try: wandb.init(mode="disabled"); print("WandB initialized in disabled mode.")except Exception as e: print(f"Failed to initialize WandB in disabled mode: {e}")else:try: wandb.login(key=wandb_api_key); print("WandB login successful.")except Exception as e:print(f"WandB login failed: {e}. Disabling WandB.")if wandb.run is None:try: wandb.init(mode="disabled"); print("WandB initialized in disabled mode due to login failure.")except Exception as e_init: print(f"Failed to initialize WandB in disabled mode: {e_init}")agent = Nonetry:print("Initializing SmolAgent...")model_api = HfApiModel("mistralai/Mixtral-8x7B-Instruct-v0.1", token=hf_token)agent = CodeAgent(tools=[], model=model_api, additional_authorized_imports=["numpy", "pandas", "matplotlib.pyplot", "seaborn", "sklearn", "json", "os"])print("SmolAgent initialized successfully.")except Exception as e: print(f"Error initializing SmolAgent: {e}. AI Agent features might fail.")df_global = Nonesplit_data_global = Nonecomparison_results_global = Nonebest_model_details_global = Noneprint("Global variables initialized.")print("--- Setup Complete ---")# --- Data Handling ---def clean_data(df: pd.DataFrame) -> pd.DataFrame: # Added type hints"""Cleans the input DataFrame."""print("Starting data cleaning...")df_cleaned = df.copy()df_cleaned = df_cleaned.dropna(how='all', axis=1).dropna(how='all', axis=0)print(f"Shape after dropping fully empty rows/cols: {df_cleaned.shape}")object_cols = df_cleaned.select_dtypes(include='object').columnsif not object_cols.empty:print(f"Encoding object columns: {list(object_cols)}")for col in object_cols:df_cleaned[col] = df_cleaned[col].astype(str)df_cleaned[col] = LabelEncoder().fit_transform(df_cleaned[col])numeric_cols = df_cleaned.select_dtypes(include=np.number).columnsif not numeric_cols.empty:cols_with_na = df_cleaned[numeric_cols].isnull().sum()cols_to_impute = cols_with_na[cols_with_na > 0].indexif not cols_to_impute.empty:print(f"Imputing NaNs with mean in columns: {list(cols_to_impute)}")for col in cols_to_impute:mean_val = df_cleaned[col].mean()df_cleaned[col] = df_cleaned[col].fillna(mean_val)print("Data cleaning finished.")return df_cleaned# ADDED TYPE HINT HEREdef upload_file(file) -> pd.DataFrame:"""Handles file upload, cleaning, and global state update."""global df_global, split_data_global, comparison_results_global, best_model_details_globaldf_global = Nonesplit_data_global = Nonecomparison_results_global = None1 unmodified lineprint("Reset global data states on file change.")if file is None:# Return an empty DataFrame or one with a status message, matching hintreturn pd.DataFrame({"Status": ["No file uploaded or file removed."]})print(f"Uploading file: {file.name}")4 unmodified lineselif ext in [".xls", ".xlsx"]:df = pd.read_excel(file.name)else:# Return DataFrame matching hintreturn pd.DataFrame({"Error": [f"Unsupported file type: {ext}"]})print(f"Original data shape: {df.shape}")df_cleaned = clean_data(df)print(f"Cleaned data shape: {df_cleaned.shape}")df_global = df_cleanedprint("Global DataFrame updated with cleaned data.")# Return DataFrame matching hintreturn df_global.head()except Exception as e:print(f"Error processing file {file.name}: {e}")df_global = None; split_data_global = None; comparison_results_global = None; best_model_details_global = None# Return DataFrame matching hintreturn pd.DataFrame({"Error": [f"Failed to process file: {e}"]})# --- AI Agent Analysis ---# (Keep format_observations, format_insights, format_analysis_report as before)def format_observations(observations):"""Formats the observations dictionary into HTML list items."""if not isinstance(observations, dict): return f"<p style='color: orange;'>Observations data is not a dictionary: {type(observations)}</p>"items_html = ""for key, value in observations.items():formatted_key = key.replace('_', ' ').title()if isinstance(value, (dict, list)):formatted_value = json.dumps(value, indent=2); value_html = f"<pre style='margin: 0; padding: 8px; background: #ffffff; border: 1px solid #ccc; border-radius: 4px; font-size: 0.9em; white-space: pre-wrap; word-wrap: break-word;'>{formatted_value}</pre>"else: formatted_value = str(value); value_html = f"<p style='margin: 0; padding: 8px; background: #ffffff; border: 1px solid #ccc; border-radius: 4px; font-size: 0.9em;'>{formatted_value}</p>"items_html += f"""<div style="margin-bottom: 12px; padding: 10px; background: #fdfefe; border-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);"><h4 style="margin: 0 0 8px 0; color: #34495e;">{formatted_key}</h4>{value_html}</div>"""return items_html if items_html else "<p>No observations found.</p>"def format_insights(insights, visuals):"""Formats insights and embeds corresponding visuals."""if not isinstance(insights, dict): return f"<p style='color: orange;'>Insights data is not a dictionary: {type(insights)}</p>"items_html = ""; visual_idx = 0; insight_keys = list(insights.keys())for i, key in enumerate(insight_keys):insight_text = str(insights[key]); formatted_key = key.replace('_', ' ').title()items_html += f"""<div style="margin: 20px 0; padding: 15px; background: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);"><h4 style='margin-top: 0; margin-bottom: 10px; color: #16a085;'>Insight {i+1}: {formatted_key}</h4><p style="margin-bottom: 15px;">{insight_text}</p>"""if visual_idx < len(visuals):img_path = visuals[visual_idx]items_html += f'<img src="/file={img_path}" alt="Visualization for {formatted_key}" style="max-width: 95%; height: auto; display: block; margin-top: 10px; border-radius: 6px; border: 1px solid #eee; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">'visual_idx += 1items_html += "</div>"if visual_idx < len(visuals):items_html += "<h4 style='margin-top: 25px; color: #2980b9;'>Additional Visualizations:</h4>"for i in range(visual_idx, len(visuals)):img_path = visuals[i]items_html += f"""<div style="margin: 20px 0; padding: 15px; background: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);"><img src="/file={img_path}" alt="Additional Visualization {i+1}" style="max-width: 95%; height: auto; display: block; margin: auto; border-radius: 6px; border: 1px solid #eee; box-shadow: 0 1px 3px rgba(0,0,0,0.1);"></div>"""return items_html if (items_html or visuals) else "<p>No insights or visuals generated/found.</p>"def format_analysis_report(raw_output, visuals):"""Formats the AI agent's output into readable HTML."""print("Formatting AI analysis report...")report_html = ""; analysis_dict = {}; parsing_error = Nonetry:if isinstance(raw_output, str):cleaned_output = raw_output.strip().removeprefix("```python").removeprefix("```json").removesuffix("```").strip()dict_start_index = cleaned_output.find('{')if dict_start_index != -1:try: analysis_dict = ast.literal_eval(cleaned_output[dict_start_index:])except (SyntaxError, ValueError, TypeError) as e: parsing_error = f"Error parsing agent output: {e}\nRaw output:\n{raw_output}"; print(parsing_error)else: parsing_error = f"Could not find dictionary start '{{' in agent output.\nRaw output:\n{raw_output}"; print(parsing_error)elif isinstance(raw_output, dict): analysis_dict = raw_outputelse: parsing_error = f"Output is not a string or dictionary, type: {type(raw_output)}.\nRaw output:\n{str(raw_output)}"; print(parsing_error)report_html = """<div style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; padding: 15px; border: 1px solid #ddd; border-radius: 8px; background-color: #f9f9f9;"><h1 style="color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; margin-top: 0;">📊 AI Data Analysis Report</h1>"""if parsing_error: report_html += f"<div style='background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; padding: 10px; border-radius: 5px; margin-bottom: 15px;'><pre>{parsing_error}</pre></div>"observations = analysis_dict.get('observations', {}); report_html += """<div style="margin-top: 20px; background: #ecf0f1; padding: 15px; border-radius: 5px;"><h2 style="color: #2980b9; margin-top: 0;">🔍 Key Observations</h2>"""report_html += format_observations(observations) if observations else "<p>No 'observations' found or parsed.</p>"; report_html += "</div>"insights = analysis_dict.get('insights', {}); report_html += """<div style="margin-top: 25px;"><h2 style="color: #2980b9;">💡 Insights & Visualizations</h2>"""report_html += format_insights(insights, visuals) if (insights or visuals) else "<p>No 'insights' or visuals found or parsed.</p>"; report_html += "</div>"report_html += "</div>"; print("Report formatting complete.")return report_html, visualsexcept Exception as e:print(f"Critical error in format_analysis_report: {e}"); error_message = f"<p style='color: red; font-weight: bold;'>Error generating report:</p><pre>{str(e)}</pre>"; raw_display = f"<p style='font-weight: bold;'>Raw Agent Output:</p><pre>{str(raw_output)}</pre>"; return error_message + raw_display, visuals# ADDED TYPE HINT HEREdef analyze_data(csv_file, additional_notes="") -> Tuple[str, List[str]]:"""Runs the SmolAgent for data analysis and visualization."""global df_global, agent# Default return values matching the type hintdefault_error_html = "<p style='color:red;'>An error occurred.</p>"default_visuals = []if df_global is None: return "<p style='color:red;'>Please upload a file first.</p>", default_visualsif agent is None: return "<p style='color:red;'>AI Agent is not available (initialization failed).</p>", default_visualsif csv_file is None: return "<p style='color:red;'>File object missing, please re-upload.</p>", default_visualsprint("--- Starting AI Agent Analysis ---")start_time = time.time(); process = psutil.Process(os.getpid()); initial_memory = process.memory_info().rss / 1024 ** 2figures_dir = './figures'try:if os.path.exists(figures_dir): shutil.rmtree(figures_dir); print(f"Cleaned existing directory: {figures_dir}")os.makedirs(figures_dir); print(f"Created directory: {figures_dir}")except Exception as e: print(f"Error managing figures directory: {e}"); return f"<p style='color:red;'>Error setting up visualization directory: {e}</p>", default_visualswandb_run_agent = None; run_name = f"AgentAnalysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}"# ... (WandB init logic as before) ...if wandb.run is None or wandb.run.mode != "disabled":try:if wandb.run and wandb.run.id: wandb.finish()wandb_run_agent = wandb.init(project="ai-data-analysis-gradio", name=run_name, config={...}, reinit=True) # Simplified config displayprint(f"WandB run '{run_name}' initialized for Agent Analysis.")except Exception as e: print(f"Error initializing WandB run for Agent Analysis: {e}"); wandb_run_agent = Noneelse: print("WandB disabled, skipping Agent run logging.")analysis_result = None; visuals = []try:# ... (prompt definition as before) ...prompt = f"""Analyze `df_global`. Tasks: 3 observations, 5 insights, 5 visualizations saved to './figures/'.Output Format: Python dictionary {{'observations':{{...}}, 'insights':{{...}}}}. Context: {additional_notes}Use `df_global`. Save plots with plt.savefig('./figures/unique_name.png', bbox_inches='tight') and plt.clf(). No plt.show().""" # Simplified prompt displayprint("Running AI agent..."); analysis_result = agent.run(prompt, additional_args={"df_global": df_global.copy()}); print("AI agent finished.")if os.path.exists(figures_dir):visuals = [os.path.join(figures_dir, f) for f in os.listdir(figures_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg'))]visuals = [v for v in visuals if os.path.isfile(v)]; print(f"Found {len(visuals)} visualizations in {figures_dir}.")else: print(f"Warning: Figures directory '{figures_dir}' not found after agent run.")except Exception as e:print(f"Error during AI agent execution: {e}"); import traceback; traceback.print_exc()if wandb_run_agent: wandb_run_agent.finish(exit_code=1)# Return values matching type hint on errorreturn f"<p style='color:red;'>Error running AI agent: {e}</p>", default_visualsexecution_time = time.time() - start_time; final_memory = process.memory_info().rss / 1024 ** 2; memory_usage = final_memory - initial_memoryprint(f"Agent execution time: {execution_time:.2f}s, Memory usage: {memory_usage:.2f} MB")# ... (WandB logging logic as before) ...if wandb_run_agent:try:wandb.log({"agent_execution_time_sec": execution_time, "agent_memory_usage_mb": memory_usage, "visualizations_generated": len(visuals)}, commit=False)# Log visualizations, etc.for viz_path in visuals:if os.path.exists(viz_path):try: wandb.log({f"agent_visualization_{os.path.basename(viz_path)}": wandb.Image(viz_path)}, commit=False)except Exception as log_e: print(f"Wandb img log error: {log_e}")if analysis_result: wandb.log({"agent_raw_output": str(analysis_result)[:10000]}, commit=True)print("Logged agent results to WandB.")except Exception as e: print(f"Error logging agent results to WandB: {e}")finally: wandb_run_agent.finish(); print(f"WandB run '{run_name}' finished.")# Ensure return matches type hintformatted_html, _ = format_analysis_report(analysis_result, visuals) # Get formatted HTMLreturn formatted_html, visuals# --- Model Training and Comparison ---def prepare_data(df, target_column=None): # -> Tuple[pd.DataFrame, pd.DataFrame, pd.Series, pd.Series] - Internal use, hint optional"""Prepares data for modeling (selects target, splits, handles encoding)."""global split_data_globalprint("--- Preparing Data for Modeling ---")if df is None or df.empty: raise ValueError("Cannot prepare data: DataFrame is empty.")# ... (logic for selecting target, dropping, encoding 'y' as before) ...if target_column is None: target_column = df.columns[-1]; print(f"Target column automatically selected: '{target_column}'")elif target_column not in df.columns: raise ValueError(f"Target column '{target_column}' not found.")else: print(f"Using specified target column: '{target_column}'")X = df.drop(columns=[target_column]); y = df[target_column].copy(); le = Noneif y.dtype == 'object' or pd.api.types.is_categorical_dtype(y): le = LabelEncoder(); y = le.fit_transform(y); print(f"Encoded target. Classes: {le.classes_}")non_numeric_cols = X.select_dtypes(exclude=np.number).columnsif not non_numeric_cols.empty: print(f"Warning: Non-numeric columns found in features: {list(non_numeric_cols)}. Dropping them."); X = X.drop(columns=non_numeric_cols)if X.empty: raise ValueError("No features remaining to train the model.")if y.nunique() < 2: raise ValueError("Target column must have at least two unique classes for classification.")try: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42, stratify=y)except ValueError as split_e: print(f"Stratified split failed ({split_e}). Trying non-stratified split."); X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)split_data_global = (X_train, X_test, y_train, y_test, le); print("Data prepared and split stored globally.")return X_train, X_test, y_train, y_test# ADDED TYPE HINT HEREdef train_and_compare_models(tune_rf=True, tune_gb=True, n_trials_optuna=10) -> pd.DataFrame:"""Trains, (optionally) tunes, evaluates multiple models, and logs comparison."""global df_global, split_data_global, comparison_results_global, best_model_details_global, wandb_run# Default return DataFrame matching hintdefault_error_df = pd.DataFrame({"Error": ["Comparison failed."]})if df_global is None: print("Error: No data loaded for training/comparison."); return pd.DataFrame({"Error": ["Please upload data first."]})print("--- Starting Model Training and Comparison ---")# ... (WandB setup, model definitions, Optuna objectives as before) ...run_name = f"CompareModels_{datetime.now().strftime('%Y%m%d_%H%M%S')}"models_to_compare = {"LogisticRegression": Pipeline([('scaler', StandardScaler()), ('logreg', LogisticRegression(max_iter=1000, random_state=42, class_weight='balanced'))]),"RandomForest": RandomForestClassifier(random_state=42, class_weight='balanced'),"GradientBoosting": GradientBoostingClassifier(random_state=42)}config = { ... } # Simplified config display# WandB init logic...if wandb.run is None or wandb.run.mode != "disabled":try:if wandb.run and wandb.run.id: wandb.finish()wandb_run = wandb.init(project="ai-data-analysis-gradio", name=run_name, config=config, reinit=True)print(f"WandB run '{run_name}' initialized for Model Comparison.")except Exception as e: print(f"Error initializing WandB run for Comparison: {e}"); wandb_run = Noneelse: print("WandB disabled, skipping Comparison run logging."); wandb_run = Noneresults = []; best_f1 = -1; best_model_obj = None; best_model_name = None; best_model_params = Nonetry:if split_data_global: print("Using previously split data."); X_train, X_test, y_train, y_test, _ = split_data_globalelse: print("Preparing data for comparison..."); X_train, X_test, y_train, y_test = prepare_data(df_global)# Optuna objectives (objective_rf, objective_gb) as before...def objective_rf(trial): # Simplified displayparams = {"n_estimators": trial.suggest_int("n_estimators", 50, 250), ...}; model = RandomForestClassifier(**params)try: score = cross_val_score(model, X_train, y_train, cv=3, scoring="f1_weighted", n_jobs=-1).mean(); return scoreexcept ValueError: return -1def objective_gb(trial): # Simplified displayparams = {"n_estimators": trial.suggest_int("n_estimators", 50, 250), ...}; model = GradientBoostingClassifier(**params)try: score = cross_val_score(model, X_train, y_train, cv=3, scoring="f1_weighted", n_jobs=-1).mean(); return scoreexcept ValueError: return -1# --- Model Training Loop ---for name, model_pipeline in models_to_compare.items():print(f"--- Training and Evaluating: {name} ---")start_time = time.time(); current_params = model_pipeline.get_params(); final_model = model_pipelinetry:# Optional Tuning as before...if name == "RandomForest" and tune_rf:study_rf = optuna.create_study(direction="maximize"); study_rf.optimize(objective_rf, n_trials=n_trials_optuna, timeout=300)final_model = RandomForestClassifier(**study_rf.best_params, random_state=42); current_params = final_model.get_params()print(f"Best RF params (CV F1w: {study_rf.best_value:.4f})") # Simplified printelif name == "GradientBoosting" and tune_gb:study_gb = optuna.create_study(direction="maximize"); study_gb.optimize(objective_gb, n_trials=n_trials_optuna, timeout=300)final_model = GradientBoostingClassifier(**study_gb.best_params, random_state=42); current_params = final_model.get_params()print(f"Best GB params (CV F1w: {study_gb.best_value:.4f})") # Simplified printfinal_model.fit(X_train, y_train)y_pred = final_model.predict(X_test)# Calculate metrics as before...accuracy = accuracy_score(y_test, y_pred)precision = precision_score(y_test, y_pred, average="weighted", zero_division=0)recall = recall_score(y_test, y_pred, average="weighted", zero_division=0)f1 = f1_score(y_test, y_pred, average="weighted", zero_division=0)duration = time.time() - start_timeprint(f"{name} Test Set - F1 (Weighted): {f1:.4f}, Time: {duration:.2f}s") # Simplified printmetrics = { "Model": name, "Test Accuracy": accuracy, "Test Precision (Weighted)": precision, "Test Recall (Weighted)": recall, "Test F1 Score (Weighted)": f1, "Training Time (s)": duration, "Tuned": (...) } # Simplified displayresults.append(metrics)# Log to WandB if enabled...# Update best model if current f1 is better...if f1 > best_f1: best_f1 = f1; best_model_name = name; best_model_obj = final_model; best_model_params = current_params; print(f"*** New best model: {name} ***")except Exception as train_e: print(f"ERROR training/evaluating {name}: {train_e}"); results.append({"Model": name, "Error": str(train_e)})# --- Finalize Comparison ---if not results: print("No models were successfully trained."); return pd.DataFrame({"Status": ["Model training failed."]})comparison_df = pd.DataFrame(results)if "Test F1 Score (Weighted)" in comparison_df.columns: comparison_df = comparison_df.sort_values(by="Test F1 Score (Weighted)", ascending=False).reset_index(drop=True)comparison_results_global = comparison_dfprint("\n--- Model Comparison Summary ---"); print(comparison_df.to_string())# Store best model details if found...if best_model_obj is not None: best_model_details_global = {'name': best_model_name, 'model': best_model_obj, 'params': best_model_params, 'f1_score': best_f1}; print(f"Stored details for best model: {best_model_name}")# Save artifact locally and log to WandB if enabled...# Log comparison table to WandB if enabled...# Return DataFrame matching type hintreturn comparison_dfexcept Exception as e:print(f"An error occurred during model comparison: {e}"); import traceback; traceback.print_exc()if wandb_run: wandb_run.finish(exit_code=1)# Return DataFrame matching type hintreturn pd.DataFrame({"Error": [f"Comparison failed: {e}"]})finally:# Finish WandB run logic...if wandb_run and wandb.run: wandb_run.finish(); print(f"WandB run '{run_name}' finished.")wandb_run = None# --- Model Explainability ---# TYPE HINT ALREADY ADDED HEREdef explainability(_=None) -> Tuple[List[str], Optional[str], str]:"""Generates SHAP and LIME explanations for the best performing model."""global split_data_global, best_model_details_global, wandb_run# Default returns match hintdefault_shap_paths = []default_lime_path = Nonedefault_status = "Error: Explainability could not run."if split_data_global is None: return default_shap_paths, default_lime_path, "Error: Data not prepared. Run 'Train & Compare' first."if best_model_details_global is None: return default_shap_paths, default_lime_path, "Error: Best model not identified. Run 'Train & Compare' first."# --- Get data and model ---X_train, X_test, y_train, y_test, label_encoder = split_data_globalbest_model_name = best_model_details_global['name']best_model = best_model_details_global['model']print(f"--- Generating explanations for the best model: {best_model_name} ---")# ... (Setup output dir, define paths, WandB init logic as before) ...output_dir = "./explainability_plots";if os.path.exists(output_dir): shutil.rmtree(output_dir)os.makedirs(output_dir)shap_summary_path = os.path.join(output_dir, f"shap_summary_{best_model_name}.png")lime_path = os.path.join(output_dir, f"lime_instance_{best_model_name}.png")all_shap_paths = []; status_message = f"Explaining best model: {best_model_name}" # Initialize gallery list# WandB Init...run_name = f"Explain_{best_model_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"wandb_run_explain = Noneif wandb.run is None or wandb.run.mode != "disabled":try:if wandb.run and wandb.run.id: wandb.finish()wandb_run_explain = wandb.init(project="ai-data-analysis-gradio", name=run_name, config={...}, reinit=True)print(f"WandB run '{run_name}' initialized for Explainability.")except Exception as e: print(f"Error initializing Wandb run for Explainability: {e}"); wandb_run_explain = Noneelse: print("WandB disabled, skipping Explainability run logging."); wandb_run_explain = Nonetry:# --- SHAP Explanation (logic as before) ---print("Calculating SHAP values...")shap_values = None; explainer = None; X_test_for_shap = X_test# ... (logic to determine explainer and calculate shap_values based on model type/pipeline) ...# Simplified example logic:if isinstance(best_model, Pipeline):final_estimator = best_model.steps[-1][1]if isinstance(final_estimator, (RandomForestClassifier, GradientBoostingClassifier)):print("Using TreeExplainer for Pipeline")# ... (transform data, init explainer, get shap_values) ...elif isinstance(final_estimator, LogisticRegression):print("Using KernelExplainer for Pipeline")# ... (init explainer, get shap_values for subset) ...else: print("SHAP not implemented for this pipeline step.")elif isinstance(best_model, (RandomForestClassifier, GradientBoostingClassifier)):print("Using TreeExplainer for standalone model")explainer = shap.TreeExplainer(best_model); shap_values = explainer.shap_values(X_test_for_shap)else: print("SHAP not implemented for this model type.")# --- Generate SHAP Plots (logic as before) ---if shap_values is not None:# ... (Generate summary plot, calculate global importance, generate dependence plots) ...# Important: Ensure generated paths are added to `all_shap_paths`# Example:# if summary plot saved: all_shap_paths.append(shap_summary_path)# if dep plot saved: all_shap_paths.append(dep_path)print("Generating SHAP plots...") # Placeholder print# ... (SHAP plot generation, saving, and appending to all_shap_paths) ...# Example: If summary plot is generated and saved:if os.path.exists(shap_summary_path):all_shap_paths.append(shap_summary_path)# Example: If dependence plots are generated and saved:# for dep_path in shap_dep_paths:# if os.path.exists(dep_path):# all_shap_paths.append(dep_path)# --- LIME Explanation (logic as before) ---print("Generating LIME explanation...")try:# ... (LIME explainer setup, explain_instance, plot saving logic) ...print("LIME explanation generated.") # Placeholder printexcept Exception as lime_e:print(f"Error generating LIME explanation: {lime_e}")lime_path = None # Indicate failure# --- Finalize and Return ---status_message = f"Explanations finished for {best_model_name}." # Update statusvalid_lime_path = lime_path if lime_path and os.path.exists(lime_path) else Nonevalid_shap_paths = [p for p in all_shap_paths if p and os.path.exists(p)]print(f"Returning {len(valid_shap_paths)} SHAP paths, LIME path: {valid_lime_path}")# Ensure return matches type hintreturn valid_shap_paths, valid_lime_path, status_messageexcept Exception as e:print(f"An error occurred during explainability: {e}"); import traceback; traceback.print_exc()status_message = f"Error during explanation: {e}"if wandb_run_explain: wandb_run_explain.finish(exit_code=1)# Ensure return matches type hintreturn [], None, status_messagefinally:plt.close('all')# Finish WandB run logic...if wandb_run_explain and wandb.run and wandb.run.id == wandb_run_explain.id: wandb_run_explain.finish(); print(f"WandB run '{run_name}' finished.")wandb_run_explain = None# --- Gradio Interface ---# (Keep Gradio UI layout and connections exactly as before)print("--- Setting up Gradio Interface ---")with gr.Blocks(theme=gr.themes.Soft(), title="AI Data Analysis & Model Comparison") as demo:gr.Markdown( ... ) # Title markdown# Row 1: File Upload ...with gr.Row():with gr.Column(scale=1): file_input = gr.File(...)with gr.Column(scale=2): df_output = gr.DataFrame(...)# Row 2: AI Agent ...with gr.Accordion("🤖 Step 2 (Optional): Run AI Agent for Insights & Visuals", open=False):with gr.Row():with gr.Column(scale=1): agent_notes = gr.Textbox(...); agent_btn = gr.Button(...)with gr.Column(scale=2): insights_output = gr.HTML(...)with gr.Row(): visual_output = gr.Gallery(...)# Row 3: Model Training ...with gr.Accordion("⚙️ Step 3: Train & Compare Models", open=True):with gr.Row():with gr.Column(scale=1): tune_rf_checkbox = gr.Checkbox(...); tune_gb_checkbox = gr.Checkbox(...); optuna_trials_slider = gr.Slider(...); compare_btn = gr.Button(...)with gr.Column(scale=2): comparison_output = gr.DataFrame(...)# Row 4: Explainability ...with gr.Accordion("💡 Step 4: Explain Best Model (SHAP & LIME)", open=False):with gr.Row(): explain_btn = gr.Button(...); explain_status = gr.Textbox(...)with gr.Row(): shap_gallery = gr.Gallery(...); lime_img = gr.Image(...)# --- Connect Components ---print("Connecting Gradio components...")file_input.change(fn=upload_file, inputs=file_input, outputs=df_output)agent_btn.click(fn=analyze_data, inputs=[file_input, agent_notes], outputs=[insights_output, visual_output])compare_btn.click(fn=train_and_compare_models, inputs=[tune_rf_checkbox, tune_gb_checkbox, optuna_trials_slider], outputs=[comparison_output])explain_btn.click(fn=explainability, inputs=[], outputs=[shap_gallery, lime_img, explain_status])print("Gradio components connected.")# --- Launch the App ---if __name__ == "__main__":print("--- Cleaning up temporary directories/files ---")# (Cleanup logic as before)temp_dirs = ['./figures', './explainability_plots', './saved_models', './__pycache__']for d in temp_dirs:if os.path.exists(d):try: shutil.rmtree(d); print(f"Cleaned up directory: {d}")except Exception as e: print(f"Warning: Could not clean up directory {d}: {e}")print("--- Launching Gradio App ---")demo.launch(debug=False, share=False)print("--- Gradio App Closed ---")
app.py+285-968