Update app.py
Browse files94 unmodified lines959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717894 unmodified linesreturn {"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# Load and trim datasetdf = pd.read_csv(csv_file)df_trimmed = df.iloc[:300, :10] # Limit rows and columns for performancetemp_path = tempfile.NamedTemporaryFile(delete=False, suffix=".csv").namedf_trimmed.to_csv(temp_path, index=False)# Clear figuresif os.path.exists('./figures'):shutil.rmtree('./figures')os.makedirs('./figures', exist_ok=True)# Start W&Bwandb.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})# Create CodeAgent instanceagent = CodeAgent(tools=[],model=model,additional_authorized_imports=["numpy", "pandas", "matplotlib.pyplot", "seaborn", "sklearn", "json"])prompt = f"""You are a helpful data analysis agent. Follow these instructions EXACTLY:1. Load the data from `source_file` ONLY.2. Generate up to 3 observations and 3 visualizations.3. Save all figures to ./figures as PNGs using matplotlib/seaborn.4. Use only: pandas, numpy, matplotlib.pyplot, seaborn, json.5. ⚠️ Output ONLY the following JSON format inside a single code block:{{"observations": {{"key": "value"}},"insights": {{"key": "value"}}}}6. Do not include comments or narration.7. Complete the analysis quickly (limit iterations)."""try:raw_output = agent.run(prompt, additional_args={"source_file": open(temp_path, "rb"),"additional_notes": additional_notes})parsed_result = extract_json_from_codeagent_output(raw_output)except Exception as e:print(f"[analyze_data] Agent failed: {e}")parsed_result = {"error": str(e)}# Log performanceexecution_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})# Upload visualsvisuals = [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()return {"summary": parsed_result,"visuals": visuals,"execution_time_sec": round(execution_time, 2),"memory_usage_mb": round(memory_usage, 2)}94 unmodified lines959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218394 unmodified linesreturn {"error": "Failed to extract structured JSON"}def analyze_data(csv_file, additional_notes=""):import time, os, shutil, psutil, jsonfrom pathlib import Pathstart_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')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"])# Run the CodeAgentraw_output = agent.run("""You are a helpful data analysis agent. Follow these instructions EXACTLY:1. Load the data from the given `source_file` ONLY.2. Analyze the data structure and generate up to 5 visualizations and 5 insights.3. 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 output block.6. Run only 5 iteration and return output quickly.⚠️ Output ONLY the following code block format, exactly:{'observations': {'observation_1_key': 'observation_1_value',...},'insights': {'insight_1_key': 'insight_1_value',...}}""", 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"}execution_time = time.time() - start_timefinal_memory = process.memory_info().rss / 1024 ** 2memory_usage = final_memory - initial_memorywandb.log({"execution_time_sec": round(execution_time, 2),"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(f"<li><b>{k}:</b> {v}</li>" for k, v in parsed_result["observations"].items()) + "</ul>"if "insights" in parsed_result:summary_html += "<h4>💡 Insights</h4><ul>" + "".join(f"<li><b>{k}:</b> {v}</li>" for k, v in parsed_result["insights"].items()) + "</ul>"if "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, visuals
app.py+51-46