Update app.py
Browse files57 unmodified lines58596061626364656667686970717273747576777879808182838485868726 unmodified lines1141151161171181191201211221231244 unmodified lines1291301311321331341351361371381391401411421431441 unmodified line1461471481491501511525 unmodified lines1581591601611621631641651661671681691701713 unmodified lines1751761771781791801811821831841851861871886 unmodified lines19519619719819920020120220320420557 unmodified linesreturn f"✅ Target column set to: {col_name}"def clean_data(df):# Drop rows and columns where all values are NaNdf = df.dropna(how='all', axis=1).dropna(how='all', axis=0)# Convert columns with object (string) data type to stringsfor col in df.select_dtypes(include='object').columns:df[col] = df[col].astype(str)# Ensure that the 'Amount' column is treated as a string before using str accessorif 'Amount' in df.columns:df['Amount'] = df['Amount'].astype(str).str.replace(',', '').str.replace('$', '').str.strip()# Convert categorical columns to numeric using LabelEncoderfor col in df.select_dtypes(include='object').columns:if col != 'Amount': # Skip 'Amount' column as it was already cleaneddf[col] = LabelEncoder().fit_transform(df[col])# Fill missing values in numeric columns with the mean of each columndf = df.fillna(df.mean(numeric_only=True))return df# Add a extraction of JSON if CodeAgent Output is not in formatdef extract_json_from_codeagent_output(raw_output):26 unmodified lines# Return an error if JSON extraction failsreturn {"error": "Failed to extract structured JSON"}def analyze_data(csv_file, additional_notes=""):start_time = time.time()process = psutil.Process(os.getpid())initial_memory = process.memory_info().rss / 1024 ** 2# Clear or create figures folderif os.path.exists('./figures'):shutil.rmtree('./figures')4 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})agent = CodeAgent(tools=[],model=model,additional_authorized_imports=["numpy", "pandas", "matplotlib.pyplot", "seaborn", "sklearn", "json"])# Run the CodeAgentraw_output = agent.run("""You are a data analysis agent. Follow these instructions EXACTLY:1. Load the data from the given `source_file` ONLY. DO NOT create your OWN DATA.1 unmodified line3. Save all figures to `./figures` as PNG using matplotlib or seaborn.4. Use only authorized imports: `pandas`, `numpy`, `matplotlib.pyplot`, `seaborn`, `json`.5. DO NOT return any explanations, thoughts, or narration outside the final JSON block6. Run only 5 iteration and return output quickly.7. Output ONLY the following JSON code block format, exactly:{'observations': {5 unmodified lines...}}""", additional_args={"additional_notes": additional_notes, "source_file": csv_file})# Parse agent outputparsed_result = extract_json_from_codeagent_output(raw_output) or {"error": "Failed to extract structured JSON"}# Record execution time and memory usageexecution_time = time.time() - start_timefinal_memory = process.memory_info().rss / 1024 ** 2memory_usage = final_memory - initial_memory3 unmodified lines"memory_usage_mb": round(memory_usage, 2)})# Collect generated visualizationsvisuals = [os.path.join('./figures', f) for f in os.listdir('./figures') if f.lower().endswith(('.png', '.jpg', '.jpeg'))]for viz in visuals:wandb.log({os.path.basename(viz): wandb.Image(viz)})run.finish()# Generate summary HTMLsummary_html = "<h3>📊 Data Analysis Summary</h3>"if "observations" in parsed_result:summary_html += "<h4>🔍 Observations</h4><ul>" + "".join(6 unmodified linesif "error" in parsed_result:summary_html += f"<p style='color:red'><b>Error:</b> {parsed_result['error']}</p>"# Return summary HTML and visual paths for gr.HTML + gr.Galleryreturn summary_html, visualsdef format_analysis_report(raw_output, visuals):import json57 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192939495969726 unmodified lines1241251261271281291301311321331341351361371381391401411421431441451461471484 unmodified lines1531541551561571581591601611621631641651661671681691 unmodified line1711721731741751761775 unmodified lines1831841851861871881891901911921931941951963 unmodified lines2002012022032042052062072082092102112122136 unmodified lines22022122222322422522622722822923057 unmodified linesreturn f"✅ Target column set to: {col_name}"def clean_data(df):from sklearn.preprocessing import LabelEncoderimport numpy as np# Drop completely empty rows/columnsdf = df.dropna(how='all', axis=1).dropna(how='all', axis=0)# Sanitize 'Amount' or similar money/number-looking columnsfor col in df.columns:if df[col].dtype == 'object':# Attempt cleaning for common currency/number stringstry:cleaned = df[col].str.replace(r'[$,]', '', regex=True).str.strip()df[col] = pd.to_numeric(cleaned, errors='ignore') # Keep original if conversion failsexcept Exception:pass# Encode any remaining object-type columnsfor col in df.select_dtypes(include='object').columns:try:df[col] = df[col].astype(str)df[col] = LabelEncoder().fit_transform(df[col])except Exception:pass# Fill remaining NaNsdf = df.fillna(df.mean(numeric_only=True))return df# Add a extraction of JSON if CodeAgent Output is not in formatdef extract_json_from_codeagent_output(raw_output):26 unmodified lines# Return an error if JSON extraction failsreturn {"error": "Failed to extract structured JSON"}import pandas as pdimport tempfiledef analyze_data(csv_file, additional_notes=""):start_time = time.time()process = psutil.Process(os.getpid())initial_memory = process.memory_info().rss / 1024 ** 2# Load and clean the data BEFORE passing to the agenttry:df = pd.read_csv(csv_file)df = clean_data(df)except Exception as e:return f"<p style='color:red'><b>Error loading or cleaning CSV:</b> {e}</p>", []# Save cleaned data to a temporary filetmp_cleaned = tempfile.NamedTemporaryFile(delete=False, suffix=".csv", mode='w')df.to_csv(tmp_cleaned.name, index=False)# Clear or create figures folderif os.path.exists('./figures'):shutil.rmtree('./figures')4 unmodified linesrun = wandb.init(project="huggingface-data-analysis", config={"model": "mistralai/Mixtral-8x7B-Instruct-v0.1","additional_notes": additional_notes,"source_file": tmp_cleaned.name})# Initialize agentagent = CodeAgent(tools=[],model=model,additional_authorized_imports=["numpy", "pandas", "matplotlib.pyplot", "seaborn", "sklearn", "json"])# Run the agent on the cleaned fileraw_output = agent.run("""You are a data analysis agent. Follow these instructions EXACTLY:1. Load the data from the given `source_file` ONLY. DO NOT create your OWN DATA.1 unmodified line3. Save all figures to `./figures` as PNG using matplotlib or seaborn.4. Use only authorized imports: `pandas`, `numpy`, `matplotlib.pyplot`, `seaborn`, `json`.5. DO NOT return any explanations, thoughts, or narration outside the final JSON block6. Run agent efficiently and remove repetitive task and complete in less than 40 seconds.7. Output ONLY the following JSON code block format, exactly:{'observations': {5 unmodified lines...}}""", additional_args={"additional_notes": additional_notes, "source_file": tmp_cleaned})# Parse outputparsed_result = extract_json_from_codeagent_output(raw_output) or {"error": "Failed to extract structured JSON"}# Log execution statsexecution_time = time.time() - start_timefinal_memory = process.memory_info().rss / 1024 ** 2memory_usage = final_memory - initial_memory3 unmodified lines"memory_usage_mb": round(memory_usage, 2)})# Upload any figuresvisuals = [os.path.join('./figures', f) for f in os.listdir('./figures') if f.lower().endswith(('.png', '.jpg', '.jpeg'))]for viz in visuals:wandb.log({os.path.basename(viz): wandb.Image(viz)})run.finish()# HTML Summarysummary_html = "<h3>📊 Data Analysis Summary</h3>"if "observations" in parsed_result:summary_html += "<h4>🔍 Observations</h4><ul>" + "".join(6 unmodified linesif "error" in parsed_result:summary_html += f"<p style='color:red'><b>Error:</b> {parsed_result['error']}</p>"return summary_html, visualsdef format_analysis_report(raw_output, visuals):import json
app.py+49-24