ZeroBAICFO / app.py
ScaleupCFOAI's picture
Update app.py
18f157e verified
Raw History Blame Contribute Delete
18.6 kB
#!/usr/bin/env python3
"""
Zero B AI CFO Dashboard
A production-ready Gradio application for financial analysis using Groq LLM
"""
import os
import sys
import pandas as pd
import traceback
from datetime import datetime
# Validate required packages
required_packages = ['gradio', 'pandas', 'plotly', 'groq']
missing_packages = []
for package in required_packages:
try:
__import__(package)
except ImportError:
missing_packages.append(package)
if missing_packages:
print(f"ERROR: Missing required packages: {', '.join(missing_packages)}")
print(f"Install with: pip install -r requirements.txt")
sys.exit(1)
import gradio as gr
import plotly.graph_objects as go
from groq import Groq
# Initialize Groq API client
def initialize_client():
"""Initialize Groq client"""
api_key = os.environ.get("GROQ_API_KEY")
if not api_key:
return None, "GROQ_API_KEY environment variable not set. Please set it with: export GROQ_API_KEY='your-key-here'"
try:
# Correct Groq client initialization (without proxies parameter)
client = Groq(api_key=api_key)
return client, None
except Exception as e:
return None, f"Error initializing Groq client: {str(e)}"
client, client_error = initialize_client()
if client_error:
print(f"WARNING: {client_error}")
else:
print("✓ Groq API client initialized successfully")
# System prompt for Zero B CFO
SYSTEM_PROMPT = """You are a highly experienced CFO of Zero B, a leading consumer goods water purification company operating as part of Ion Exchange India Limited.
Key Information About Zero B:
- Zero B operates in the residential water purifier market in India
- Primary products: RO systems (45% revenue), Water Softeners (30%), UV systems (15%), Others (10%)
- Distribution channels: Direct (35%), Retail (40%), E-commerce (25%)
- Monthly revenue range: ₹110-175 crores
- Gross margin: ~40% | Operating margin: ~17% | Net margin: ~13%
Experience: 15+ years in finance with deep understanding of business model and financial KPIs.
Guidelines:
1. Provide crisp, pointed answers first (1-2 sentences)
2. Support with key numbers and trends
3. Identify concerns and opportunities
4. Suggest actionable recommendations
5. ONLY analyze Zero B's financial data and competitors
6. Be specific with numbers and percentages
7. Identify root causes of variances
"""
# ============================================================================
# Data Loading
# ============================================================================
def load_data():
"""Load and process financial data from CSV"""
try:
if not os.path.exists('zero_b_financial_data.csv'):
raise FileNotFoundError(
"zero_b_financial_data.csv not found in current directory. "
"Please ensure the file is in the same directory as app.py"
)
df_load = pd.read_csv('zero_b_financial_data.csv')
df_load['Date'] = pd.to_datetime(df_load['Date'], format='%d-%m-%Y')
df_sorted = df_load.sort_values('Date')
return df_sorted
except Exception as e:
print(f"ERROR loading data: {e}")
raise
# Load data on startup
try:
df = load_data()
except Exception as e:
print(f"FATAL: Could not load data: {e}")
df = None
# ============================================================================
# Chart Generation
# ============================================================================
def create_ytd_chart():
"""Create YTD monthly plan vs actual sales chart"""
try:
df_chart = load_data()
fig = go.Figure()
fig.add_trace(go.Scatter(
x=df_chart['Month'],
y=df_chart['Budget Sales (₹ Cr)'],
mode='lines+markers',
name='Budget',
line=dict(color='#1f77b4', width=3),
marker=dict(size=8)
))
fig.add_trace(go.Scatter(
x=df_chart['Month'],
y=df_chart['Actual Sales (₹ Cr)'],
mode='lines+markers',
name='Actual',
line=dict(color='#ff7f0e', width=3),
marker=dict(size=8)
))
fig.update_layout(
title='YTD Monthly Plan vs Actual Sales',
xaxis_title='Month',
yaxis_title='Sales (₹ Cr)',
hovermode='x unified',
template='plotly_white',
height=350,
font=dict(size=10),
margin=dict(l=50, r=50, t=50, b=50)
)
return fig
except Exception as e:
print(f"Error creating YTD chart: {e}")
return None
def create_product_mix_chart():
"""Create product mix pie chart"""
try:
df_chart = load_data()
latest_month = df_chart.iloc[-1]
products = ['RO Systems', 'Water Softeners', 'UV Systems', 'Others']
values = [
latest_month['RO Sales (₹ Cr)'],
latest_month['Softener Sales (₹ Cr)'],
latest_month['UV Sales (₹ Cr)'],
latest_month['Others Sales (₹ Cr)']
]
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']
fig = go.Figure(data=[
go.Pie(labels=products, values=values, marker=dict(colors=colors))
])
fig.update_layout(
title=f'Product Mix - {latest_month["Month"]}',
height=350,
font=dict(size=10),
margin=dict(l=50, r=50, t=50, b=50)
)
return fig
except Exception as e:
print(f"Error creating product mix chart: {e}")
return None
def create_channel_mix_chart():
"""Create channel mix pie chart"""
try:
df_chart = load_data()
latest_month = df_chart.iloc[-1]
channels = ['Direct', 'Retail', 'E-commerce']
values = [
latest_month['Direct Channel (₹ Cr)'],
latest_month['Retail Channel (₹ Cr)'],
latest_month['E-commerce Channel (₹ Cr)']
]
colors = ['#9467bd', '#8c564b', '#e377c2']
fig = go.Figure(data=[
go.Pie(labels=channels, values=values, marker=dict(colors=colors))
])
fig.update_layout(
title=f'Channel Mix - {latest_month["Month"]}',
height=350,
font=dict(size=10),
margin=dict(l=50, r=50, t=50, b=50)
)
return fig
except Exception as e:
print(f"Error creating channel mix chart: {e}")
return None
def create_margin_view():
"""Create gross margin by product bar chart"""
try:
products = ['RO Systems', 'Water Softeners', 'UV Systems', 'Others']
margins = [42, 38, 40, 35]
fig = go.Figure(data=[
go.Bar(
x=products,
y=margins,
marker=dict(color=['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']),
text=[f'{m}%' for m in margins],
textposition='auto'
)
])
fig.update_layout(
title='Gross Margin % by Product',
xaxis_title='Product',
yaxis_title='Gross Margin %',
height=350,
template='plotly_white',
font=dict(size=10),
margin=dict(l=50, r=50, t=50, b=50),
showlegend=False
)
return fig
except Exception as e:
print(f"Error creating margin chart: {e}")
return None
# ============================================================================
# KPI HTML Generation
# ============================================================================
def generate_kpi_html():
"""Generate HTML for KPI cards"""
try:
df_dash = load_data()
latest = df_dash.iloc[-1]
prev = df_dash.iloc[-2] if len(df_dash) > 1 else latest
sales_growth = ((latest['Actual Sales (₹ Cr)'] - prev['Actual Sales (₹ Cr)'])
/ prev['Actual Sales (₹ Cr)'] * 100)
budget_variance = ((latest['Actual Sales (₹ Cr)'] - latest['Budget Sales (₹ Cr)'])
/ latest['Budget Sales (₹ Cr)'] * 100)
growth_icon = "↑" if sales_growth > 0 else "↓"
variance_icon = "↑" if budget_variance > 0 else "↓"
html = f"""
<div style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 10px; margin-bottom: 10px; padding: 8px;">
<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 12px; border-radius: 6px; color: white; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<p style="font-size: 10px; opacity: 0.9; margin: 0;">SALES</p>
<p style="font-size: 18px; font-weight: bold; margin: 3px 0 0 0;">₹{latest['Actual Sales (₹ Cr)']:.1f}Cr</p>
</div>
<div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); padding: 12px; border-radius: 6px; color: white; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<p style="font-size: 10px; opacity: 0.9; margin: 0;">MARGIN</p>
<p style="font-size: 18px; font-weight: bold; margin: 3px 0 0 0;">{latest['Gross Margin %']:.1f}%</p>
</div>
<div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); padding: 12px; border-radius: 6px; color: white; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<p style="font-size: 10px; opacity: 0.9; margin: 0;">EBITDA</p>
<p style="font-size: 18px; font-weight: bold; margin: 3px 0 0 0;">{latest['EBITDA Margin %']:.1f}%</p>
</div>
<div style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); padding: 12px; border-radius: 6px; color: white; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<p style="font-size: 10px; opacity: 0.9; margin: 0;">VAR</p>
<p style="font-size: 18px; font-weight: bold; margin: 3px 0 0 0;">{variance_icon} {abs(budget_variance):.1f}%</p>
</div>
<div style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); padding: 12px; border-radius: 6px; color: white; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<p style="font-size: 10px; opacity: 0.9; margin: 0;">MoM</p>
<p style="font-size: 18px; font-weight: bold; margin: 3px 0 0 0;">{growth_icon} {abs(sales_growth):.1f}%</p>
</div>
</div>
"""
return html
except Exception as e:
print(f"Error generating KPI HTML: {e}")
return "<p>Error loading KPI data</p>"
# ============================================================================
# LLM Integration - GROQ
# ============================================================================
def query_llm(user_question):
"""Query Groq LLM with financial context"""
if not client:
return f"LLM not available. {client_error}"
try:
df_context = load_data()
latest_data = df_context.iloc[-1].to_dict()
financial_context = f"""
Current Financial Snapshot ({latest_data['Month']}):
- Sales: Rs{latest_data['Actual Sales (₹ Cr)']} Cr (Budget: Rs{latest_data['Budget Sales (₹ Cr)']} Cr)
- Product Mix: RO Rs{latest_data['RO Sales (₹ Cr)']} Cr | Softener Rs{latest_data['Softener Sales (₹ Cr)']} Cr | UV Rs{latest_data['UV Sales (₹ Cr)']} Cr
- Channel Mix: Direct Rs{latest_data['Direct Channel (₹ Cr)']} Cr | Retail Rs{latest_data['Retail Channel (₹ Cr)']} Cr | E-com Rs{latest_data['E-commerce Channel (₹ Cr)']} Cr
- Margins: Gross {latest_data['Gross Margin %']}% | EBITDA {latest_data['EBITDA Margin %']}% | EBIT {latest_data['EBIT Margin %']}% | PAT {latest_data['PAT Margin %']}%
- Working Capital: Inventory {latest_data['Inventory Days']} days | Receivables {latest_data['Receivables Days']} days | Payables {latest_data['Payables Days']} days
"""
user_prompt = f"""{financial_context}
Question: {user_question}
Provide a crisp, data-driven answer focusing on:
1. Direct answer (1-2 sentences)
2. Key numbers and trends
3. Concerns or opportunities
4. Recommended action
"""
message = client.chat.completions.create(
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_prompt}
],
model="mixtral-8x7b-32768",
temperature=0.3,
max_tokens=500
)
return message.choices[0].message.content
except Exception as e:
error_msg = f"LLM Error: {str(e)}"
print(f"ERROR in query_llm: {error_msg}")
print(traceback.format_exc())
return error_msg
# ============================================================================
# Gradio Interface
# ============================================================================
def create_app():
"""Create Gradio application with proper vertical split layout"""
with gr.Blocks(
theme=gr.themes.Soft(),
title="Zero B AI CFO Dashboard",
css="""
#main_container { height: 100vh; display: flex; flex-direction: column; }
#top_section { flex: 1; overflow-y: auto; padding: 10px; }
#bottom_section { flex: 0 0 20%; padding: 10px; background: #f8f9fa; border-top: 2px solid #e0e0e0; overflow-y: auto; }
.chart_container { min-height: 350px; }
.kpi_row { margin-bottom: 10px; }
"""
) as demo:
with gr.Column(elem_id="main_container"):
# HEADER
gr.Markdown("# 🎯 Zero B AI CFO Dashboard | Financial Intelligence Platform")
# TOP 80% - SCROLLABLE DASHBOARD
with gr.Group(elem_id="top_section"):
# KPI Row
kpi_html = gr.HTML(elem_classes="kpi_row")
# Charts in 2x2 grid - Left 70%
with gr.Row():
# LEFT 70% - Charts
with gr.Column(scale=7):
with gr.Row():
chart1 = gr.Plot(label="YTD Sales", elem_classes="chart_container")
chart2 = gr.Plot(label="Product Mix", elem_classes="chart_container")
with gr.Row():
chart3 = gr.Plot(label="Channel Mix", elem_classes="chart_container")
chart4 = gr.Plot(label="Margins", elem_classes="chart_container")
# RIGHT 30% - Analysis Narrative
with gr.Column(scale=3):
gr.Markdown("### 📊 Analysis")
narrative = gr.Markdown(value="""**Ready for questions**
Ask about:
- Sales trends
- Profitability
- Product/Channel performance
- Cash flow""")
gr.Markdown("---")
# BOTTOM 20% - FIXED INPUT SECTION
with gr.Group(elem_id="bottom_section"):
gr.Markdown("### 💬 Ask Zero B AI CFO")
chat_state = gr.State([])
chatbot = gr.Chatbot(label="Chat History", height=120)
with gr.Row():
question_input = gr.Textbox(
placeholder="Ask about sales, margins, products, channels, strategy...",
lines=2,
scale=4,
label="Question"
)
submit_btn = gr.Button("Analyze", variant="primary", scale=1, size="lg")
with gr.Row():
clear_btn = gr.Button("Clear Chat", scale=1)
# LOAD DASHBOARD
def load_dashboard():
try:
kpi_content = generate_kpi_html()
chart1_fig = create_ytd_chart()
chart2_fig = create_product_mix_chart()
chart3_fig = create_channel_mix_chart()
chart4_fig = create_margin_view()
default_text = """**Dashboard Loaded**
- Top KPI cards
- 4 Charts
- Ready for analysis"""
return (
kpi_content,
chart1_fig,
chart2_fig,
chart3_fig,
chart4_fig,
default_text,
[]
)
except Exception as e:
print(f"Error loading dashboard: {e}")
return ("Error", None, None, None, None, str(e), [])
# SUBMIT HANDLER
def handle_submit(question, chat_history):
try:
if not question.strip():
return chat_history, "", ""
response = query_llm(question)
chat_history.append((question, response))
df_latest = load_data()
latest = df_latest.iloc[-1]
narrative_text = f"""**Q:** {question[:40]}...
**Period:** {latest['Month']}
**Sales:** ₹{latest['Actual Sales (₹ Cr)']:.1f}Cr
**Margin:** {latest['Gross Margin %']:.1f}%"""
return chat_history, "", narrative_text
except Exception as e:
print(f"Error in handle_submit: {e}")
return chat_history, question, f"Error: {str(e)}"
# CLEAR HANDLER
def handle_clear():
dashboard = load_dashboard()
return [], "", dashboard[5]
# EVENT HANDLERS
submit_btn.click(
handle_submit,
inputs=[question_input, chat_state],
outputs=[chatbot, question_input, narrative]
)
clear_btn.click(
handle_clear,
outputs=[chatbot, question_input, narrative]
)
demo.load(
load_dashboard,
outputs=[kpi_html, chart1, chart2, chart3, chart4, narrative, chat_state]
)
return demo
# ============================================================================
# Main
# ============================================================================
if __name__ == "__main__":
try:
print("Starting Zero B AI CFO Dashboard...")
app = create_app()
app.launch(
share=True,
server_name="0.0.0.0",
server_port=7860,
debug=False
)
except Exception as e:
print(f"FATAL ERROR: {e}")
print(traceback.format_exc())
sys.exit(1)