ScaleupCFOAI commited on
Commit
61ecf25
·
verified ·
1 Parent(s): 698b6c8

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -496
app.py DELETED
@@ -1,496 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Zero B AI CFO Dashboard
4
- A production-ready Gradio application for financial analysis using Grok LLM
5
- """
6
-
7
- import os
8
- import sys
9
- import pandas as pd
10
- import traceback
11
- from datetime import datetime
12
-
13
- # Validate required packages
14
- required_packages = ['gradio', 'pandas', 'plotly', 'openai']
15
- missing_packages = []
16
-
17
- for package in required_packages:
18
- try:
19
- __import__(package)
20
- except ImportError:
21
- missing_packages.append(package)
22
-
23
- if missing_packages:
24
- print(f"ERROR: Missing required packages: {', '.join(missing_packages)}")
25
- print(f"Install with: pip install -r requirements.txt")
26
- sys.exit(1)
27
-
28
- import gradio as gr
29
- import plotly.graph_objects as go
30
- from openai import OpenAI
31
-
32
- # Initialize Grok API client
33
- def initialize_client():
34
- """Initialize OpenAI client for Grok API"""
35
- api_key = os.environ.get("GROQ_API_KEY")
36
- if not api_key:
37
- raise ValueError(
38
- "GROQ_API_KEY environment variable not set. "
39
- "Please set it with: export GROQ_API_KEY='your-key-here'"
40
- )
41
-
42
- client = OpenAI(
43
- api_key=api_key,
44
- base_url="https://api.x.ai/v1"
45
- )
46
- return client
47
-
48
- try:
49
- client = initialize_client()
50
- print("✓ Grok API client initialized successfully")
51
- except Exception as e:
52
- print(f"WARNING: Could not initialize Grok client: {e}")
53
- print(" LLM features will not work until API key is set")
54
- client = None
55
-
56
- # System prompt for Zero B CFO
57
- 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.
58
-
59
- Key Information About Zero B:
60
- - Zero B operates in the residential water purifier market in India
61
- - Primary products: RO systems (45% revenue), Water Softeners (30%), UV systems (15%), Others (10%)
62
- - Distribution channels: Direct (35%), Retail (40%), E-commerce (25%)
63
- - Monthly revenue range: ₹110-175 crores
64
- - Gross margin: ~40% | Operating margin: ~17% | Net margin: ~13%
65
-
66
- Experience: 15+ years in finance with deep understanding of business model and financial KPIs.
67
-
68
- Guidelines:
69
- 1. Provide crisp, pointed answers first (1-2 sentences)
70
- 2. Support with key numbers and trends
71
- 3. Identify concerns and opportunities
72
- 4. Suggest actionable recommendations
73
- 5. ONLY analyze Zero B's financial data and competitors
74
- 6. Be specific with numbers and percentages
75
- 7. Identify root causes of variances
76
- """
77
-
78
- # ============================================================================
79
- # Data Loading
80
- # ============================================================================
81
-
82
- def load_data():
83
- """Load and process financial data from CSV"""
84
- try:
85
- if not os.path.exists('zero_b_financial_data.csv'):
86
- raise FileNotFoundError(
87
- "zero_b_financial_data.csv not found in current directory. "
88
- "Please ensure the file is in the same directory as app.py"
89
- )
90
-
91
- df_load = pd.read_csv('zero_b_financial_data.csv')
92
- df_load['Date'] = pd.to_datetime(df_load['Date'], format='%d-%m-%Y')
93
- df_sorted = df_load.sort_values('Date')
94
- print(f"✓ Loaded {len(df_sorted)} months of financial data")
95
- return df_sorted
96
- except Exception as e:
97
- print(f"ERROR loading data: {e}")
98
- raise
99
-
100
- # Load data on startup
101
- try:
102
- df = load_data()
103
- except Exception as e:
104
- print(f"FATAL: Could not load data: {e}")
105
- df = None
106
-
107
- # ============================================================================
108
- # Chart Generation
109
- # ============================================================================
110
-
111
- def create_ytd_chart():
112
- """Create YTD monthly plan vs actual sales chart"""
113
- try:
114
- df_chart = load_data()
115
-
116
- fig = go.Figure()
117
-
118
- fig.add_trace(go.Scatter(
119
- x=df_chart['Month'],
120
- y=df_chart['Budget Sales (₹ Cr)'],
121
- mode='lines+markers',
122
- name='Budget',
123
- line=dict(color='#1f77b4', width=3),
124
- marker=dict(size=8)
125
- ))
126
-
127
- fig.add_trace(go.Scatter(
128
- x=df_chart['Month'],
129
- y=df_chart['Actual Sales (₹ Cr)'],
130
- mode='lines+markers',
131
- name='Actual',
132
- line=dict(color='#ff7f0e', width=3),
133
- marker=dict(size=8)
134
- ))
135
-
136
- fig.update_layout(
137
- title='YTD Monthly Plan vs Actual Sales',
138
- xaxis_title='Month',
139
- yaxis_title='Sales (₹ Cr)',
140
- hovermode='x unified',
141
- template='plotly_white',
142
- height=300,
143
- font=dict(size=11),
144
- margin=dict(l=50, r=50, t=50, b=50)
145
- )
146
-
147
- return fig
148
- except Exception as e:
149
- print(f"Error creating YTD chart: {e}")
150
- return None
151
-
152
- def create_product_mix_chart():
153
- """Create product mix pie chart"""
154
- try:
155
- df_chart = load_data()
156
- latest_month = df_chart.iloc[-1]
157
-
158
- products = ['RO Systems', 'Water Softeners', 'UV Systems', 'Others']
159
- values = [
160
- latest_month['RO Sales (₹ Cr)'],
161
- latest_month['Softener Sales (₹ Cr)'],
162
- latest_month['UV Sales (₹ Cr)'],
163
- latest_month['Others Sales (₹ Cr)']
164
- ]
165
- colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']
166
-
167
- fig = go.Figure(data=[
168
- go.Pie(labels=products, values=values, marker=dict(colors=colors))
169
- ])
170
-
171
- fig.update_layout(
172
- title=f'Product Mix - {latest_month["Month"]}',
173
- height=300,
174
- font=dict(size=11),
175
- margin=dict(l=50, r=50, t=50, b=50)
176
- )
177
-
178
- return fig
179
- except Exception as e:
180
- print(f"Error creating product mix chart: {e}")
181
- return None
182
-
183
- def create_channel_mix_chart():
184
- """Create channel mix pie chart"""
185
- try:
186
- df_chart = load_data()
187
- latest_month = df_chart.iloc[-1]
188
-
189
- channels = ['Direct', 'Retail', 'E-commerce']
190
- values = [
191
- latest_month['Direct Channel (₹ Cr)'],
192
- latest_month['Retail Channel (₹ Cr)'],
193
- latest_month['E-commerce Channel (₹ Cr)']
194
- ]
195
- colors = ['#9467bd', '#8c564b', '#e377c2']
196
-
197
- fig = go.Figure(data=[
198
- go.Pie(labels=channels, values=values, marker=dict(colors=colors))
199
- ])
200
-
201
- fig.update_layout(
202
- title=f'Channel Mix - {latest_month["Month"]}',
203
- height=300,
204
- font=dict(size=11),
205
- margin=dict(l=50, r=50, t=50, b=50)
206
- )
207
-
208
- return fig
209
- except Exception as e:
210
- print(f"Error creating channel mix chart: {e}")
211
- return None
212
-
213
- def create_margin_view():
214
- """Create gross margin by product bar chart"""
215
- try:
216
- products = ['RO Systems', 'Water Softeners', 'UV Systems', 'Others']
217
- margins = [42, 38, 40, 35]
218
-
219
- fig = go.Figure(data=[
220
- go.Bar(
221
- x=products,
222
- y=margins,
223
- marker=dict(color=['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']),
224
- text=[f'{m}%' for m in margins],
225
- textposition='auto'
226
- )
227
- ])
228
-
229
- fig.update_layout(
230
- title='Gross Margin % by Product',
231
- xaxis_title='Product',
232
- yaxis_title='Gross Margin %',
233
- height=300,
234
- template='plotly_white',
235
- font=dict(size=11),
236
- margin=dict(l=50, r=50, t=50, b=50),
237
- showlegend=False
238
- )
239
-
240
- return fig
241
- except Exception as e:
242
- print(f"Error creating margin chart: {e}")
243
- return None
244
-
245
- # ============================================================================
246
- # KPI HTML Generation
247
- # ============================================================================
248
-
249
- def generate_kpi_html():
250
- """Generate HTML for KPI cards"""
251
- try:
252
- df_dash = load_data()
253
- latest = df_dash.iloc[-1]
254
- prev = df_dash.iloc[-2] if len(df_dash) > 1 else latest
255
-
256
- sales_growth = ((latest['Actual Sales (₹ Cr)'] - prev['Actual Sales (₹ Cr)'])
257
- / prev['Actual Sales (₹ Cr)'] * 100)
258
- budget_variance = ((latest['Actual Sales (₹ Cr)'] - latest['Budget Sales (₹ Cr)'])
259
- / latest['Budget Sales (₹ Cr)'] * 100)
260
-
261
- growth_icon = "↑" if sales_growth > 0 else "↓"
262
- variance_icon = "↑" if budget_variance > 0 else "↓"
263
- variance_status = "On Track" if abs(budget_variance) < 5 else "Needs Review"
264
-
265
- html = f"""
266
- <div style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 12px; margin-bottom: 15px; padding: 10px;">
267
- <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 15px; border-radius: 8px; color: white; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
268
- <p style="font-size: 11px; opacity: 0.9; margin: 0;">CURRENT SALES</p>
269
- <p style="font-size: 20px; font-weight: bold; margin: 5px 0 0 0;">Rs {latest['Actual Sales (₹ Cr)']:.1f}Cr</p>
270
- </div>
271
- <div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); padding: 15px; border-radius: 8px; color: white; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
272
- <p style="font-size: 11px; opacity: 0.9; margin: 0;">GROSS MARGIN</p>
273
- <p style="font-size: 20px; font-weight: bold; margin: 5px 0 0 0;">{latest['Gross Margin %']:.1f}%</p>
274
- </div>
275
- <div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); padding: 15px; border-radius: 8px; color: white; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
276
- <p style="font-size: 11px; opacity: 0.9; margin: 0;">EBITDA MARGIN</p>
277
- <p style="font-size: 20px; font-weight: bold; margin: 5px 0 0 0;">{latest['EBITDA Margin %']:.1f}%</p>
278
- </div>
279
- <div style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); padding: 15px; border-radius: 8px; color: white; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
280
- <p style="font-size: 11px; opacity: 0.9; margin: 0;">BUDGET VAR</p>
281
- <p style="font-size: 20px; font-weight: bold; margin: 5px 0 0 0;">{variance_icon} {abs(budget_variance):.1f}%</p>
282
- </div>
283
- <div style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); padding: 15px; border-radius: 8px; color: white; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
284
- <p style="font-size: 11px; opacity: 0.9; margin: 0;">MoM GROWTH</p>
285
- <p style="font-size: 20px; font-weight: bold; margin: 5px 0 0 0;">{growth_icon} {abs(sales_growth):.1f}%</p>
286
- </div>
287
- </div>
288
- """
289
- return html
290
- except Exception as e:
291
- print(f"Error generating KPI HTML: {e}")
292
- return "<p>Error loading KPI data</p>"
293
-
294
- # ============================================================================
295
- # LLM Integration
296
- # ============================================================================
297
-
298
- def query_llm(user_question):
299
- """Query Grok LLM with financial context"""
300
- if not client:
301
- return "LLM not available. Please set GROQ_API_KEY environment variable."
302
-
303
- try:
304
- df_context = load_data()
305
- latest_data = df_context.iloc[-1].to_dict()
306
-
307
- financial_context = f"""
308
- Current Financial Snapshot ({latest_data['Month']}):
309
- - Sales: Rs{latest_data['Actual Sales (₹ Cr)']} Cr (Budget: Rs{latest_data['Budget Sales (₹ Cr)']} Cr)
310
- - 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
311
- - 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
312
- - Margins: Gross {latest_data['Gross Margin %']}% | EBITDA {latest_data['EBITDA Margin %']}% | EBIT {latest_data['EBIT Margin %']}% | PAT {latest_data['PAT Margin %']}%
313
- - Working Capital: Inventory {latest_data['Inventory Days']} days | Receivables {latest_data['Receivables Days']} days | Payables {latest_data['Payables Days']} days
314
- """
315
-
316
- user_prompt = f"""{financial_context}
317
-
318
- Question: {user_question}
319
-
320
- Provide a crisp, data-driven answer focusing on:
321
- 1. Direct answer (1-2 sentences)
322
- 2. Key numbers and trends
323
- 3. Concerns or opportunities
324
- 4. Recommended action
325
- """
326
-
327
- response = client.chat.completions.create(
328
- model="grok-beta",
329
- messages=[
330
- {"role": "system", "content": SYSTEM_PROMPT},
331
- {"role": "user", "content": user_prompt}
332
- ],
333
- temperature=0.3,
334
- max_tokens=500
335
- )
336
-
337
- return response.choices[0].message.content
338
-
339
- except Exception as e:
340
- error_msg = f"LLM Error: {str(e)}"
341
- print(f"ERROR in query_llm: {error_msg}")
342
- print(traceback.format_exc())
343
- return error_msg
344
-
345
- # ============================================================================
346
- # Gradio Interface
347
- # ============================================================================
348
-
349
- def create_app():
350
- """Create Gradio application with vertical split layout"""
351
-
352
- with gr.Blocks(theme=gr.themes.Soft(), title="Zero B AI CFO Dashboard") as demo:
353
- gr.Markdown("""
354
- # 🎯 Zero B AI CFO Dashboard
355
- ### Financial Intelligence Platform | Powered by Grok AI
356
- """)
357
-
358
- # TOP 70% - DASHBOARD
359
- with gr.Group():
360
- kpi_html = gr.HTML()
361
-
362
- with gr.Row():
363
- chart1 = gr.Plot(label="Sales Trend")
364
- chart2 = gr.Plot(label="Product Mix")
365
-
366
- with gr.Row():
367
- chart3 = gr.Plot(label="Channel Mix")
368
- chart4 = gr.Plot(label="Margins")
369
-
370
- with gr.Row():
371
- narrative = gr.Markdown()
372
-
373
- gr.Markdown("---")
374
-
375
- # BOTTOM 30% - CHAT
376
- with gr.Group():
377
- gr.Markdown("### 💬 AI Financial Assistant")
378
-
379
- chat_state = gr.State([])
380
- chatbot = gr.Chatbot(label="Conversation", height=250)
381
-
382
- with gr.Row():
383
- question_input = gr.Textbox(
384
- placeholder="Ask about sales, margins, products, channels, or strategy",
385
- lines=2,
386
- scale=4
387
- )
388
- submit_btn = gr.Button("Analyze", variant="primary", scale=1)
389
-
390
- with gr.Row():
391
- clear_btn = gr.Button("Clear", scale=1)
392
-
393
- # Load dashboard on startup
394
- def load_dashboard():
395
- try:
396
- kpi_content = generate_kpi_html()
397
- chart1_fig = create_ytd_chart()
398
- chart2_fig = create_product_mix_chart()
399
- chart3_fig = create_channel_mix_chart()
400
- chart4_fig = create_margin_view()
401
-
402
- default_text = """
403
- ### Dashboard Ready
404
-
405
- Click below to ask about:
406
- - Sales trends & budget variance
407
- - Product performance
408
- - Channel analysis
409
- - Profitability drivers
410
- """
411
-
412
- return (
413
- kpi_content,
414
- chart1_fig,
415
- chart2_fig,
416
- chart3_fig,
417
- chart4_fig,
418
- default_text,
419
- []
420
- )
421
- except Exception as e:
422
- print(f"Error loading dashboard: {e}")
423
- return ("Error loading dashboard", None, None, None, None, str(e), [])
424
-
425
- # Submit handler
426
- def handle_submit(question, chat_history):
427
- try:
428
- if not question.strip():
429
- return chat_history, "", ""
430
-
431
- # Get LLM response
432
- response = query_llm(question)
433
-
434
- # Update chat history
435
- chat_history.append((question, response))
436
-
437
- # Generate narrative
438
- df_latest = load_data()
439
- latest = df_latest.iloc[-1]
440
-
441
- narrative_text = f"""
442
- ### Analysis for: {question[:50]}...
443
-
444
- **Current Period:** {latest['Month']}
445
- **Sales:** Rs{latest['Actual Sales (₹ Cr)']:.1f} Cr | **Margin:** {latest['Gross Margin %']:.1f}%
446
- """
447
-
448
- return chat_history, "", narrative_text
449
-
450
- except Exception as e:
451
- print(f"Error in handle_submit: {e}")
452
- print(traceback.format_exc())
453
- return chat_history, question, f"Error: {str(e)}"
454
-
455
- # Clear handler
456
- def handle_clear():
457
- dashboard = load_dashboard()
458
- return [], "", dashboard[5]
459
-
460
- # Event handlers
461
- submit_btn.click(
462
- handle_submit,
463
- inputs=[question_input, chat_state],
464
- outputs=[chatbot, question_input, narrative]
465
- )
466
-
467
- clear_btn.click(
468
- handle_clear,
469
- outputs=[chatbot, question_input, narrative]
470
- )
471
-
472
- demo.load(
473
- load_dashboard,
474
- outputs=[kpi_html, chart1, chart2, chart3, chart4, narrative, chat_state]
475
- )
476
-
477
- return demo
478
-
479
- # ============================================================================
480
- # Main
481
- # ============================================================================
482
-
483
- if __name__ == "__main__":
484
- try:
485
- print("Starting Zero B AI CFO Dashboard...")
486
- app = create_app()
487
- app.launch(
488
- share=True,
489
- server_name="0.0.0.0",
490
- server_port=7860,
491
- debug=False
492
- )
493
- except Exception as e:
494
- print(f"FATAL ERROR: {e}")
495
- print(traceback.format_exc())
496
- sys.exit(1)