Spaces:
Sleeping
Sleeping
File size: 18,579 Bytes
b627b77 282dc61 b627b77 282dc61 b627b77 8715135 b627b77 8715135 b627b77 18f157e b627b77 18f157e b627b77 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 | #!/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)
|