Update app.py
Browse files30 unmodified lines31323334353637383 unmodified lines424344454647484950515253545556575859606162636465129 unmodified lines1951961971981992002019 unmodified lines2112122132142152162173 unmodified lines22122222322422522622722830 unmodified lines25926026126226326426526626726812 unmodified lines2812822832842852862872882892902912922932942952962972982993003013023033043053 unmodified lines30931031131231331431530 unmodified lines# SmolAgent initializationmodel = HfApiModel("mistralai/Mixtral-8x7B-Instruct-v0.1", token=hf_token)df_global = Nonetarget_column_global = Nonedef clean_data(df):df = df.dropna(how='all', axis=1).dropna(how='all', axis=0)3 unmodified linesdf = df.fillna(df.mean(numeric_only=True))return dfdef upload_file(file):global df_globalif file is None:return pd.DataFrame({"Error": ["No file uploaded."]}), gr.update(choices=[])ext = os.path.splitext(file.name)[-1]df = pd.read_csv(file.name) if ext == ".csv" else pd.read_excel(file.name)df = clean_data(df)df_global = dfreturn df.head(), gr.update(choices=df.columns.tolist())def set_target_column(col_name):global target_column_globaltarget_column_global = col_namereturn f"✅ Target column set to: {col_name}"def format_analysis_report(raw_output, visuals):import json129 unmodified linesdef analyze_data(csv_file, additional_notes=""):try:start_time = time.time()process = psutil.Process(os.getpid())9 unmodified linesrun = wandb.init(project="huggingface-data-analysis", config={"model": "mistralai/Mixtral-8x7B-Instruct-v0.1","additional_notes": additional_notes,"source_file": csv_file.name if csv_file else None})# Initialize Code Agent3 unmodified linesadditional_authorized_imports=["numpy", "pandas", "matplotlib.pyplot", "seaborn", "sklearn", "json"])# Enhanced prompt with strict formatting requirementsprompt = """You are a helpful data analysis agent. Please follow these very strict instructions and formatting:1. Load the data from the provided `source_file`.30 unmodified linesNever use unauthorized imports (only pandas, numpy, matplotlib, seaborn are allowed)"""# Run the agentanalysis_result = agent.run(prompt, additional_args={"additional_notes": additional_notes,"source_file": csv_file.name if csv_file else None})# Performance metrics12 unmodified linesif f.endswith(('.png', '.jpg', '.jpeg'))])# Log visuals to WandBfor viz in visuals:wandb.log({os.path.basename(viz): wandb.Image(viz)})run.finish()print("DEBUG - Raw agent output:", analysis_result[:500] + "...")print("Columns in data:", df_global.columns.tolist())print("Data types:", df_global.dtypes)with open("agent_output.txt", "w") as f:f.write(str(analysis_result))# Parse the agent outputparsed_result = extract_json_from_codeagent_output(analysis_result)print(f"DEBUG - Parsed result: {parsed_result}") # Debug outputif parsed_result:return format_analysis_report(parsed_result, visuals)else:# Fallback to showing raw output if parsing failserror_msg = f"Failed to parse agent output. Showing raw response:\n{str(analysis_result)[:2000]}"print(error_msg)return f"<pre>{error_msg}</pre>", visuals3 unmodified linesprint(error_msg)return f"<pre>{error_msg}</pre>", []def compare_models():import seaborn as snsfrom sklearn.model_selection import cross_val_predict30 unmodified lines313233343536373839403 unmodified lines4445464748495051525354555657585960616263646566676869707172737475767778798081828384858687129 unmodified lines2172182192202212222239 unmodified lines2332342352362372382393 unmodified lines24324424524624724824925025125225325425525625725825926026126226326426530 unmodified lines29629729829930030130230330430530612 unmodified lines3193203213223233243253263273283293303313323333343353363373 unmodified lines34134234334434534634730 unmodified lines# SmolAgent initializationmodel = HfApiModel("mistralai/Mixtral-8x7B-Instruct-v0.1", token=hf_token)# Globalsdf_global = Nonetarget_column_global = Nonedata_summary_global = None # ⬅️ Added for summarized datadef clean_data(df):df = df.dropna(how='all', axis=1).dropna(how='all', axis=0)3 unmodified linesdf = df.fillna(df.mean(numeric_only=True))return dfdef summarize_data(df: pd.DataFrame, max_cols: int = 10, max_rows: int = 5) -> str:summary = []summary.append(f"Dataset shape: {df.shape}")summary.append("\nColumn types:\n" + str(df.dtypes))num_cols = df.select_dtypes(include=[np.number]).columns.tolist()cat_cols = df.select_dtypes(exclude=[np.number]).columns.tolist()summary.append("\nMissing values:\n" + str(df.isnull().sum()))if num_cols:summary.append("\nNumerical summary:\n" + str(df[num_cols].describe().T.head(max_rows)))if cat_cols:summary.append("\nCategorical value counts (top categories):")for col in cat_cols[:max_cols]:summary.append(f"\nColumn: {col}\n{df[col].value_counts().head(max_rows)}")return "\n".join(summary)def upload_file(file):global df_global, data_summary_globalif file is None:return pd.DataFrame({"Error": ["No file uploaded."]}), gr.update(choices=[])ext = os.path.splitext(file.name)[-1]df = pd.read_csv(file.name) if ext == ".csv" else pd.read_excel(file.name)df = clean_data(df)df_global = dfdata_summary_global = summarize_data(df) # ⬅️ Summarize herereturn df.head(), gr.update(choices=df.columns.tolist())def set_target_column(col_name):global target_column_globaltarget_column_global = col_namereturn f"✅ Target column set to: {col_name}"def format_analysis_report(raw_output, visuals):import json129 unmodified linesdef analyze_data(csv_file=None, additional_notes="", use_summary=True):try:start_time = time.time()process = psutil.Process(os.getpid())9 unmodified linesrun = wandb.init(project="huggingface-data-analysis", config={"model": "mistralai/Mixtral-8x7B-Instruct-v0.1","additional_notes": additional_notes,"source_file": csv_file.name if csv_file else "summarized_input"})# Initialize Code Agent3 unmodified linesadditional_authorized_imports=["numpy", "pandas", "matplotlib.pyplot", "seaborn", "sklearn", "json"])# Choose prompt contentif use_summary and data_summary_global:input_data = data_summary_globaldata_instruction = """You are analyzing summarized dataset information from a CSV file. Your job is to:1. Interpret the summary content as if it was produced from a real dataset.2. Derive at least 5 high-level insights based on column types, distributions, missing values, etc.3. Imagine or mock visualizations and describe what they would show. Use synthetic data simulation with numpy/pandas if needed.4. Save plots to './figures/' using matplotlib or seaborn.Always respond in the structured dictionary format below."""else:# Fall back to full file inputinput_data = None # You load file within the agentdata_instruction = """You are a helpful data analysis agent. Please follow these very strict instructions and formatting:1. Load the data from the provided `source_file`.30 unmodified linesNever use unauthorized imports (only pandas, numpy, matplotlib, seaborn are allowed)"""# Run agent with either summarized content or CSVanalysis_result = agent.run(data_instruction, additional_args={"additional_notes": additional_notes,"source_file": csv_file.name if csv_file and not use_summary else None,"data_summary": input_data if use_summary else None})# Performance metrics12 unmodified linesif f.endswith(('.png', '.jpg', '.jpeg'))])for viz in visuals:wandb.log({os.path.basename(viz): wandb.Image(viz)})run.finish()print("DEBUG - Raw agent output:", analysis_result[:500] + "...")with open("agent_output.txt", "w") as f:f.write(str(analysis_result))parsed_result = extract_json_from_codeagent_output(analysis_result)if parsed_result:return format_analysis_report(parsed_result, visuals)else:error_msg = f"Failed to parse agent output. Showing raw response:\n{str(analysis_result)[:2000]}"print(error_msg)return f"<pre>{error_msg}</pre>", visuals3 unmodified linesprint(error_msg)return f"<pre>{error_msg}</pre>", []def compare_models():import seaborn as snsfrom sklearn.model_selection import cross_val_predict
app.py+51-19