Spaces:
Runtime error
Runtime error
Update financial_analyst_app.py
Browse files1 unmodified line234567891025 unmodified lines3637383940414249 unmodified lines9293949596979816 unmodified lines1151161171181191201216 unmodified lines1281291301311321331346 unmodified lines1411421431441451461474 unmodified lines1521531541551561572 unmodified lines1601611621631641651661671681691701711721731741751761771781791 unmodified lineimport google.generativeai as genaiimport osimport timeimport pandas as pdimport jsonimport re# --- Configuration ---# Securely configure the API key for Hugging Face deployment25 unmodified linesdef add_usage_record():st.session_state.usage_log.append(time.time())# --- Function to clean and parse the AI's JSON output ---def clean_and_parse_json(json_string):"""Cleans the AI's output to extract and parse the JSON object.49 unmodified lines"""extracted_numbers_text = model.generate_content(extractor_prompt).text# Step 2 - The "Chart Data Generator" Agentchart_data_generator_prompt = f"""Act as a data structuring expert. From the KPIs below, identify up to the 8 most important and chartable metrics(e.g., Revenue, Net Income, Gross Profit, Total Assets). Exclude text-heavy or non-numeric KPIs.16 unmodified lines# Clean and parse the JSON outputchart_data = clean_and_parse_json(chart_data_json_str)# Step 3: The "Analyst" Agentanalyst_prompt = f"""Act as a senior financial analyst. Based on these KPIs, write a brief, one-paragraph assessment of the company's financial health.Conclude by classifying its health as: **Strong**, **Moderate**, or **Needs Improvement**.6 unmodified linesst.session_state.financial_analysis = {"numbers": extracted_numbers_text,"analysis": health_analysis_text,"chart_data": chart_data}add_usage_record()6 unmodified linesst.markdown("---")st.success("Financial analysis complete!")col1, col2 = st.columns([1, 1])with col1:st.subheader("Financial Health Assessment")4 unmodified lineswith col2:st.subheader("Visualized KPIs")chart_data = st.session_state.financial_analysis.get("chart_data")if chart_data:try:2 unmodified lines# Ensure 'Metric' and 'Value' columns existif 'Metric' in df.columns and 'Value' in df.columns:# Sort the DataFrame by the 'Value' column for a cleaner chartdf.sort_values(by='Value', inplace=True)# This creates a horizontal bar chart with the sorted datast.bar_chart(df, x="Value", y="Metric")else:st.warning("Could not find 'Metric' or 'Value' keys in the generated data to create a chart.")except Exception as e:st.error(f"An error occurred while creating the chart: {e}")st.write("Raw chart data received from AI:")st.json(chart_data)else:st.info("No chartable data could be generated from the provided document.")1 unmodified line234567891025 unmodified lines3637383940414249 unmodified lines9293949596979816 unmodified lines1151161171181191201216 unmodified lines1281291301311321331346 unmodified lines1411421431441451461474 unmodified lines1521531541551561571582 unmodified lines1611621631641651661671681691701711721731741751761771781 unmodified lineimport google.generativeai as genaiimport osimport timeimport pandas as pd ## --- NEW: Import Pandas for data handling ---import json ## --- NEW: Import JSON for parsing AI output ---import re ## --- NEW: Import re for cleaning the JSON string ---# --- Configuration ---# Securely configure the API key for Hugging Face deployment25 unmodified linesdef add_usage_record():st.session_state.usage_log.append(time.time())## --- NEW: Function to clean and parse the AI's JSON output ---def clean_and_parse_json(json_string):"""Cleans the AI's output to extract and parse the JSON object.49 unmodified lines"""extracted_numbers_text = model.generate_content(extractor_prompt).text## --- NEW: Step 2 - The "Chart Data Generator" Agent ---chart_data_generator_prompt = f"""Act as a data structuring expert. From the KPIs below, identify up to the 8 most important and chartable metrics(e.g., Revenue, Net Income, Gross Profit, Total Assets). Exclude text-heavy or non-numeric KPIs.16 unmodified lines# Clean and parse the JSON outputchart_data = clean_and_parse_json(chart_data_json_str)# Step 3: The "Analyst" Agent (MODIFIED to be step 3)analyst_prompt = f"""Act as a senior financial analyst. Based on these KPIs, write a brief, one-paragraph assessment of the company's financial health.Conclude by classifying its health as: **Strong**, **Moderate**, or **Needs Improvement**.6 unmodified linesst.session_state.financial_analysis = {"numbers": extracted_numbers_text,"analysis": health_analysis_text,"chart_data": chart_data ## --- NEW: Store chart data in session state ---}add_usage_record()6 unmodified linesst.markdown("---")st.success("Financial analysis complete!")col1, col2 = st.columns([1, 1]) # Create two columns for a better layoutwith col1:st.subheader("Financial Health Assessment")4 unmodified lineswith col2:st.subheader("Visualized KPIs")## --- NEW: Chart Display Logic ---chart_data = st.session_state.financial_analysis.get("chart_data")if chart_data:try:2 unmodified lines# Ensure 'Metric' and 'Value' columns existif 'Metric' in df.columns and 'Value' in df.columns:# Set the metric as the index for proper labeling in the chartdf.set_index('Metric', inplace=True)# Display the bar chartst.bar_chart(df['Value'])else:st.warning("Could not find 'Metric' or 'Value' keys in the generated data to create a chart.")except Exception as e:st.error(f"An error occurred while creating the chart: {e}")st.write("Raw chart data received from AI:")st.json(chart_data) # Display the raw data for debuggingelse:st.info("No chartable data could be generated from the provided document.")
financial_analyst_app.py+14-15