Update app.py
Browse files160 unmodified lines16116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519612 unmodified lines209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248160 unmodified linesreturn Nonedef 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"])prompt = """You are a helpful data analysis agent. Please follow these very strict instructions:1. Load the data from the provided `source_file`.2. Detect numeric and categorical columns.3. Generate at 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. Return your final result as a JSON-formatted Python string using `json.dumps()` like this:```pyimport json12 unmodified linesjson.dumps(result)```<end_code>Be concise and avoid any narrative outside this final dictionary."""analysis_result = agent.run(prompt, 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 = 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()parsed_result = extract_json_from_codeagent_output(analysis_result)if parsed_result:return format_analysis_report(parsed_result, visuals)else:# Fallback to showing the raw string if nothing workedreturn f"<pre>{str(analysis_result)}</pre>", visualsdef compare_models():import seaborn as snsfrom sklearn.model_selection import cross_val_predict160 unmodified lines16116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020112 unmodified lines214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268160 unmodified linesreturn Nonedef analyze_data(csv_file, additional_notes=""):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 None})# Initialize Code Agentagent = CodeAgent(tools=[],model=model,additional_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`.2. Detect numeric and categorical columns.3. Generate at 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. Always wrap code in markdown code blocks like this:```pyimport json12 unmodified linesjson.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 the agentanalysis_result = agent.run(prompt, additional_args={"additional_notes": additional_notes,"source_file": csv_file.name if csv_file 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'))])# Log visuals to WandBfor viz in visuals:wandb.log({os.path.basename(viz): wandb.Image(viz)})run.finish()# 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>", 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 snsfrom sklearn.model_selection import cross_val_predict
app.py+67-47