Update app.py
Browse files12320 unmodified lines24252627282930313233343536373839404142434445464748495051525354555657585960616263646566676811 unmodified lines80818283848579 unmodified lines165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346import osimport reimport gradio as gr20 unmodified linesfrom datetime import datetimefrom PIL import Image# Authenticate with Hugging Facehf_token = os.getenv("HF_TOKEN")login(token=hf_token)# 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)for col in df.select_dtypes(include='object').columns:df[col] = df[col].astype(str)df[col] = LabelEncoder().fit_transform(df[col])df = 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:11 unmodified linestarget_column_global = col_namereturn f"✅ Target column set to: {col_name}"def format_analysis_report(raw_output, visuals):79 unmodified lines### ✅ 2. Add a pre-check fallback for non-compliant agent outputsdef extract_json_from_codeagent_output(raw_output):import re, json, asttry:# Extract code blocks from ```python ... ```code_blocks = re.findall(r"```(?:py|python)?\n(.*?)```", raw_output, re.DOTALL)for block in code_blocks:# Try extracting from print(json.dumps({...}))json_match = re.search(r"print\(\s*json\.dumps\(\s*(\{[\s\S]*?\})\s*\)\s*\)",block,re.DOTALL) or re.search(r"json\.dumps\(\s*(\{[\s\S]*?\})\s*\)",block,re.DOTALL)if json_match:return json.loads(json_match.group(1))# Try extracting from: result = {...}result_match = re.search(r"result\s*=\s*(\{[\s\S]*?\})",block,re.DOTALL)if result_match:raw_dict = result_match.group(1)try:return json.loads(raw_dict) # Try strict JSONexcept json.JSONDecodeError:return ast.literal_eval(raw_dict) # Try Python dict parsing# Final fallback: look for any dict-like thing in entire outputfallback_match = re.search(r"\{[\s\S]+\}", raw_output)if fallback_match:raw_dict = fallback_match.group(0)try:return json.loads(raw_dict)except json.JSONDecodeError:return ast.literal_eval(raw_dict)except Exception as e:print(f"extract_json_from_codeagent_output() failed: {e}")return Nonedef analyze_data(csv_file=None, additional_notes="", use_summary=True):try:start_time = time.time()process = psutil.Process(os.getpid())initial_memory = process.memory_info().rss / 1024 ** 2# Clean up and prepare directoriesif os.path.exists('./figures'):shutil.rmtree('./figures')os.makedirs('./figures', exist_ok=True)# Initialize WandBwandb.login(key=os.environ.get('WANDB_API_KEY'))run = 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 Agentagent = CodeAgent(tools=[],model=model,additional_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`.2. FIRST analyze the data structure (column names and types)3. THEN generate visualizations using EXISTING columns with least 5 visualizations and 5 insights.4. Save all plots to `./figures/` as PNGs using matplotlib or seaborn.5. DO NOT use open() or print() statements.6. Use only authorized imports: `pandas`, `numpy`, `matplotlib.pyplot`, `seaborn`, `json`.7. DO NOT return any explanations, thoughts, or narration outside the final output block.8. DO NOT use `...` in any dictionary values, arrays, or code blocks.9. Use empty lists like [] or strings like "N/A" instead.10.Respond only with a JSON-serializable dictionary in Python syntax. Do not include any thoughts, comments, or explanation.11. Any logging or warnings must be disabled or redirected; the only stdout must be the single print(json.dumps(result)) call.12. FINALLY return ONLY this exact format:```pythonimport jsonresult = {"observations": {"numeric_columns": [...],"categorical_columns": [...],"data_issues": "..."},"insights": [{"category": "Insight A", "insight": "Description of insight A"},{"category": "Insight B", "insight": "Description of insight B"}]}print(json.dumps(result))```<end_code>Be concise and avoid any narrative outside this final dictionary.Never 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 metricsexecution_time = time.time() - start_timefinal_memory = process.memory_info().rss / 1024 ** 2memory_usage = final_memory - initial_memorywandb.log({"execution_time_sec": execution_time,"memory_usage_mb": memory_usage})# Collect visualizationsvisuals = sorted([os.path.join('./figures', f) for f in os.listdir('./figures')if 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>", visualsexcept Exception as e:error_msg = f"Analysis failed with error: {str(e)}"print(error_msg)return f"<pre>{error_msg}</pre>", []def compare_models():import seaborn as sns123420 unmodified lines2526272829303132333435363738394041424344454611 unmodified lines58596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018179 unmodified lines261262263264265266# Initialization and Importsimport osimport reimport gradio as gr20 unmodified linesfrom datetime import datetimefrom PIL import Image# Authenticate with Hugging Facehf_token = os.getenv("HF_TOKEN")login(token=hf_token)# SmolAgent initializationmodel = HfApiModel("mistralai/Mixtral-8x7B-Instruct-v0.1", token=hf_token)# Globalsdf_global = Nonetarget_column_global = None#File Upload and Cleanupdef upload_file(file):global df_global, data_summary_globalif file is None:11 unmodified linestarget_column_global = col_namereturn f"✅ Target column set to: {col_name}"def clean_data(df):df = df.dropna(how='all', axis=1).dropna(how='all', axis=0)for col in df.select_dtypes(include='object').columns:df[col] = df[col].astype(str)df[col] = LabelEncoder().fit_transform(df[col])df = 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):import re, json, asttry:# Extract code blocks from ```python ... ```code_blocks = re.findall(r"```(?:py|python)?\n(.*?)```", raw_output, re.DOTALL)for block in code_blocks:# Try extracting from print(json.dumps({...}))json_match = re.search(r"print\(\s*json\.dumps\(\s*(\{[\s\S]*?\})\s*\)\s*\)",block,re.DOTALL) or re.search(r"json\.dumps\(\s*(\{[\s\S]*?\})\s*\)",block,re.DOTALL)if json_match:return json.loads(json_match.group(1))# Try extracting from: result = {...}result_match = re.search(r"result\s*=\s*(\{[\s\S]*?\})",block,re.DOTALL)if result_match:raw_dict = result_match.group(1)try:return json.loads(raw_dict) # Try strict JSONexcept json.JSONDecodeError:return ast.literal_eval(raw_dict) # Try Python dict parsing# Final fallback: look for any dict-like thing in entire outputfallback_match = re.search(r"\{[\s\S]+\}", raw_output)if fallback_match:raw_dict = fallback_match.group(0)try:return json.loads(raw_dict)except json.JSONDecodeError:return ast.literal_eval(raw_dict)except Exception as e:print(f"extract_json_from_codeagent_output() failed: {e}")return None# Data Analysis Function with CodeAgentdef analyze_data(csv_file, additional_notes=""):start_time = time.time()process = psutil.Process(os.getpid())initial_memory = process.memory_info().rss / 1024 ** 2if os.path.exists('./figures'):shutil.rmtree('./figures')os.makedirs('./figures', exist_ok=True)wandb.login(key=os.environ.get('WANDB_API_KEY'))run = 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"])analysis_result = agent.run("""You are a helpful data analysis agent. Just return insight information and visualization.Load the data that is passed.do not create your own.Automatically detect numeric columns and names.2. 5 data visualizations3. at least 5 insights from data5. Generate publication-quality visualizations and save to './figures/'.Do not use 'open()' or write to files. Just return variables and plots.The dictionary should have the following structure:{'observations': {'observation_1_key': 'observation_1_value','observation_2_key': 'observation_2_value',...},'insights': {'insight_1_key': 'insight_1_value','insight_2_key': 'insight_2_value',...}}""", additional_args={"additional_notes": additional_notes, "source_file": csv_file})execution_time = time.time() - start_timefinal_memory = process.memory_info().rss / 1024 ** 2memory_usage = final_memory - initial_memorywandb.log({"execution_time_sec": execution_time, "memory_usage_mb": memory_usage})visuals = [os.path.join('./figures', f) for f in os.listdir('./figures') if f.endswith(('.png', '.jpg', '.jpeg'))]for viz in visuals:wandb.log({os.path.basename(viz): wandb.Image(viz)})run.finish()return format_analysis_report(analysis_result, visuals)def format_analysis_report(raw_output, visuals):79 unmodified linesdef compare_models():import seaborn as sns
app.py+123-203