ScaleupCFOAI commited on
Commit
5de84a7
·
verified ·
1 Parent(s): 6aad647

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +409 -0
app.py ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ import pandas as pd
4
+ import plotly.graph_objects as go
5
+ import plotly.express as px
6
+ from plotly.subplots import make_subplots
7
+ import json
8
+ from openai import OpenAI
9
+ import os
10
+ from datetime import datetime
11
+ import re
12
+
13
+ # Initialize Grok API client
14
+ client = OpenAI(
15
+ api_key=os.environ.get("XAI_API_KEY", "your-xai-api-key-here"),
16
+ base_url="https://api.x.ai/v1"
17
+ )
18
+
19
+ # Load financial data
20
+ df = pd.read_csv('zero_b_financial_data.csv')
21
+
22
+ # Define system prompt for Zero B CFO
23
+ 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.
24
+
25
+ Key Information About Zero B:
26
+ - Zero B operates in the residential water purifier market in India
27
+ - Primary products: RO systems (45% revenue), Water Softeners (30%), UV systems (15%), Others (10%)
28
+ - Distribution channels: Direct (35%), Retail (40%), E-commerce (25%)
29
+ - Monthly revenue range: ₹110-175 crores
30
+ - Gross margin: ~40% | Operating margin: ~17% | Net margin: ~13%
31
+ - Key metrics tracked: Weekly sales reconciliation, margin trends, channel performance, product mix
32
+
33
+ You have 15+ years of experience in finance and closely work with the CEO on strategic initiatives.
34
+
35
+ When analyzing data:
36
+ 1. Provide crisp, pointed answers first
37
+ 2. Then offer detailed breakdown if asked
38
+ 3. Use actual data from Zero B's financial records
39
+ 4. Make reasonable assumptions where data is unavailable
40
+ 5. Focus on actionable insights
41
+ 6. Flag any concerning trends immediately
42
+ 7. Always relate findings back to business impact
43
+
44
+ Important Guidelines:
45
+ - ONLY analyze Zero B's financial data and similar water purifier market competitors
46
+ - Limit answers to financial metrics and business implications
47
+ - Do not provide information outside Zero B's operations
48
+ - Be specific with numbers and percentages
49
+ - Provide week-on-week or month-on-month comparisons
50
+ - Identify root causes of variances
51
+ """
52
+
53
+ def load_data():
54
+ """Load and process financial data"""
55
+ df_load = pd.read_csv('zero_b_financial_data.csv')
56
+ df_load['Date'] = pd.to_datetime(df_load['Date'], format='%d-%m-%Y')
57
+ return df_load.sort_values('Date')
58
+
59
+ def create_ytd_chart():
60
+ """Create YTD monthly plan vs actual sales chart"""
61
+ df_chart = load_data()
62
+
63
+ fig = go.Figure()
64
+
65
+ fig.add_trace(go.Scatter(
66
+ x=df_chart['Month'],
67
+ y=df_chart['Budget Sales (₹ Cr)'],
68
+ mode='lines+markers',
69
+ name='Budget',
70
+ line=dict(color='#1f77b4', width=3),
71
+ marker=dict(size=8),
72
+ ))
73
+
74
+ fig.add_trace(go.Scatter(
75
+ x=df_chart['Month'],
76
+ y=df_chart['Actual Sales (₹ Cr)'],
77
+ mode='lines+markers',
78
+ name='Actual',
79
+ line=dict(color='#ff7f0e', width=3),
80
+ marker=dict(size=8),
81
+ ))
82
+
83
+ fig.update_layout(
84
+ title='<b>YTD Monthly Plan vs Actual Sales</b>',
85
+ xaxis_title='Month',
86
+ yaxis_title='Sales (₹ Cr)',
87
+ hovermode='x unified',
88
+ template='plotly_white',
89
+ height=300,
90
+ font=dict(size=11),
91
+ margin=dict(l=50, r=50, t=50, b=50),
92
+ )
93
+
94
+ return fig
95
+
96
+ def create_product_mix_chart():
97
+ """Create product mix chart"""
98
+ df_chart = load_data()
99
+ latest_month = df_chart.iloc[-1]
100
+
101
+ products = ['RO Systems', 'Water Softeners', 'UV Systems', 'Others']
102
+ values = [
103
+ latest_month['RO Sales (₹ Cr)'],
104
+ latest_month['Softener Sales (₹ Cr)'],
105
+ latest_month['UV Sales (₹ Cr)'],
106
+ latest_month['Others Sales (₹ Cr)']
107
+ ]
108
+ colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']
109
+
110
+ fig = go.Figure(data=[go.Pie(labels=products, values=values, marker=dict(colors=colors))])
111
+
112
+ fig.update_layout(
113
+ title=f'<b>Product Mix - {latest_month["Month"]}</b>',
114
+ height=300,
115
+ font=dict(size=11),
116
+ margin=dict(l=50, r=50, t=50, b=50),
117
+ )
118
+
119
+ return fig
120
+
121
+ def create_channel_mix_chart():
122
+ """Create channel mix chart"""
123
+ df_chart = load_data()
124
+ latest_month = df_chart.iloc[-1]
125
+
126
+ channels = ['Direct', 'Retail', 'E-commerce']
127
+ values = [
128
+ latest_month['Direct Channel (₹ Cr)'],
129
+ latest_month['Retail Channel (₹ Cr)'],
130
+ latest_month['E-commerce Channel (₹ Cr)']
131
+ ]
132
+ colors = ['#9467bd', '#8c564b', '#e377c2']
133
+
134
+ fig = go.Figure(data=[go.Pie(labels=channels, values=values, marker=dict(colors=colors))])
135
+
136
+ fig.update_layout(
137
+ title=f'<b>Channel Mix - {latest_month["Month"]}</b>',
138
+ height=300,
139
+ font=dict(size=11),
140
+ margin=dict(l=50, r=50, t=50, b=50),
141
+ )
142
+
143
+ return fig
144
+
145
+ def create_margin_view():
146
+ """Create margin view per product"""
147
+ products = ['RO Systems', 'Water Softeners', 'UV Systems', 'Others']
148
+ margins = [42, 38, 40, 35]
149
+
150
+ fig = go.Figure(data=[
151
+ go.Bar(
152
+ x=products,
153
+ y=margins,
154
+ marker=dict(color=['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']),
155
+ text=[f'{m}%' for m in margins],
156
+ textposition='auto',
157
+ )
158
+ ])
159
+
160
+ fig.update_layout(
161
+ title='<b>Gross Margin % by Product</b>',
162
+ xaxis_title='Product',
163
+ yaxis_title='Gross Margin %',
164
+ height=300,
165
+ template='plotly_white',
166
+ font=dict(size=11),
167
+ margin=dict(l=50, r=50, t=50, b=50),
168
+ showlegend=False,
169
+ )
170
+
171
+ return fig
172
+
173
+ def generate_kpi_html():
174
+ """Generate HTML for KPI cards"""
175
+ df_dash = load_data()
176
+ latest = df_dash.iloc[-1]
177
+ prev = df_dash.iloc[-2] if len(df_dash) > 1 else latest
178
+
179
+ sales_growth = ((latest['Actual Sales (₹ Cr)'] - prev['Actual Sales (₹ Cr)']) / prev['Actual Sales (₹ Cr)'] * 100)
180
+ budget_variance = ((latest['Actual Sales (₹ Cr)'] - latest['Budget Sales (₹ Cr)']) / latest['Budget Sales (₹ Cr)'] * 100)
181
+
182
+ html = f"""
183
+ <div style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 12px; margin-bottom: 15px; padding: 10px;">
184
+ <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);">
185
+ <p style="font-size: 11px; opacity: 0.9; margin: 0;">CURRENT MONTH SALES</p>
186
+ <p style="font-size: 20px; font-weight: bold; margin: 5px 0 0 0;">₹{latest['Actual Sales (₹ Cr)']:.1f} Cr</p>
187
+ </div>
188
+ <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);">
189
+ <p style="font-size: 11px; opacity: 0.9; margin: 0;">GROSS MARGIN</p>
190
+ <p style="font-size: 20px; font-weight: bold; margin: 5px 0 0 0;">{latest['Gross Margin %']:.1f}%</p>
191
+ <p style="font-size: 10px; opacity: 0.9; margin: 5px 0 0 0;">₹{latest['Gross Margin (₹ Cr)']:.1f} Cr</p>
192
+ </div>
193
+ <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);">
194
+ <p style="font-size: 11px; opacity: 0.9; margin: 0;">EBITDA MARGIN</p>
195
+ <p style="font-size: 20px; font-weight: bold; margin: 5px 0 0 0;">{latest['EBITDA Margin %']:.1f}%</p>
196
+ </div>
197
+ <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);">
198
+ <p style="font-size: 11px; opacity: 0.9; margin: 0;">BUDGET VARIANCE</p>
199
+ <p style="font-size: 20px; font-weight: bold; margin: 5px 0 0 0;">{'↑' if budget_variance > 0 else '↓'} {abs(budget_variance):.1f}%</p>
200
+ <p style="font-size: 10px; opacity: 0.9; margin: 5px 0 0 0;">{'On Track' if abs(budget_variance) < 5 else 'Needs Review'}</p>
201
+ </div>
202
+ <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);">
203
+ <p style="font-size: 11px; opacity: 0.9; margin: 0;">MoM GROWTH</p>
204
+ <p style="font-size: 20px; font-weight: bold; margin: 5px 0 0 0;">{'↑' if sales_growth > 0 else '↓'} {abs(sales_growth):.1f}%</p>
205
+ </div>
206
+ </div>
207
+ """
208
+
209
+ return html
210
+
211
+ def query_llm(user_question: str) -> str:
212
+ """Query Grok LLM with financial context"""
213
+
214
+ df_context = load_data()
215
+ latest_data = df_context.iloc[-1].to_dict()
216
+
217
+ # Create context with financial data
218
+ financial_context = f"""
219
+ Current Financial Snapshot (Latest Month: {latest_data['Month']}):
220
+ - Sales: ₹{latest_data['Actual Sales (₹ Cr)']} Cr (Budget: ₹{latest_data['Budget Sales (₹ Cr)']} Cr)
221
+ - Product Mix: RO ₹{latest_data['RO Sales (₹ Cr)']} Cr | Softener ₹{latest_data['Softener Sales (₹ Cr)']} Cr | UV ₹{latest_data['UV Sales (₹ Cr)']} Cr
222
+ - Channel Mix: Direct ₹{latest_data['Direct Channel (₹ Cr)']} Cr | Retail ₹{latest_data['Retail Channel (₹ Cr)']} Cr | E-com ₹{latest_data['E-commerce Channel (₹ Cr)']} Cr
223
+ - Gross Margin: {latest_data['Gross Margin %']}% (₹{latest_data['Gross Margin (₹ Cr)']} Cr)
224
+ - EBITDA Margin: {latest_data['EBITDA Margin %']}% | EBIT Margin: {latest_data['EBIT Margin %']}% | PAT Margin: {latest_data['PAT Margin %']}%
225
+ - Working Capital: Inventory Days {latest_data['Inventory Days']}, Receivables Days {latest_data['Receivables Days']}, Payables Days {latest_data['Payables Days']}
226
+
227
+ Recent Trends (Last 3 Months):
228
+ """
229
+
230
+ for idx in range(max(0, len(df_context)-3), len(df_context)):
231
+ row = df_context.iloc[idx]
232
+ financial_context += f"- {row['Month']}: Sales ₹{row['Actual Sales (₹ Cr)']} Cr | PAT ₹{row['PAT (₹ Cr)']} Cr | Margin {row['PAT Margin %']}%\n"
233
+
234
+ user_prompt = f"""{financial_context}
235
+
236
+ User Question: {user_question}
237
+
238
+ Please provide a crisp, data-driven answer focusing on:
239
+ 1. Direct answer to the question (1-2 sentences)
240
+ 2. Key numbers and trends supporting the answer
241
+ 3. Any concerns or opportunities identified
242
+ 4. Recommended action (if applicable)
243
+ """
244
+
245
+ try:
246
+ response = client.chat.completions.create(
247
+ model="grok-beta",
248
+ messages=[
249
+ {"role": "system", "content": SYSTEM_PROMPT},
250
+ {"role": "user", "content": user_prompt}
251
+ ],
252
+ temperature=0.3,
253
+ max_tokens=500
254
+ )
255
+ return response.choices[0].message.content
256
+ except Exception as e:
257
+ return f"Error querying LLM: {str(e)}. Please ensure XAI_API_KEY environment variable is set."
258
+
259
+ def process_chat(question: str, chat_history: list) -> tuple:
260
+ """Process user question and generate response"""
261
+
262
+ if not question.strip():
263
+ return chat_history, ""
264
+
265
+ # Generate LLM response
266
+ llm_response = query_llm(question)
267
+
268
+ # Update chat history
269
+ chat_history.append((question, llm_response))
270
+
271
+ return chat_history, ""
272
+
273
+ def create_app():
274
+ """Create Gradio interface with vertical split (Top 70% / Bottom 30%)"""
275
+
276
+ with gr.Blocks(theme=gr.themes.Soft(), title="Zero B AI CFO Dashboard") as demo:
277
+ gr.Markdown("""
278
+ # 🎯 Zero B AI CFO Dashboard
279
+ ### Financial Intelligence for Consumer Goods Excellence
280
+ """)
281
+
282
+ # TOP 70% - DASHBOARD SECTION
283
+ with gr.Group():
284
+ # KPI Cards
285
+ kpi_html = gr.HTML()
286
+
287
+ # Charts in grid
288
+ with gr.Row():
289
+ chart1 = gr.Plot(label="YTD Sales")
290
+ chart2 = gr.Plot(label="Product Mix")
291
+
292
+ with gr.Row():
293
+ chart3 = gr.Plot(label="Channel Mix")
294
+ chart4 = gr.Plot(label="Margins")
295
+
296
+ # Narrative section
297
+ with gr.Row():
298
+ narrative = gr.Markdown(value="Dashboard Ready")
299
+
300
+ gr.Markdown("---") # Divider
301
+
302
+ # BOTTOM 30% - CHAT SECTION
303
+ with gr.Group():
304
+ gr.Markdown("### 💬 Ask Zero B AI CFO")
305
+
306
+ # Chat interface
307
+ chat_state = gr.State([])
308
+ chatbot = gr.Chatbot(label="Conversation", height=250)
309
+
310
+ with gr.Row():
311
+ question_input = gr.Textbox(
312
+ label="Your Question",
313
+ placeholder="E.g., Why did sales drop? Whats impacting margins? Hows e-commerce performing?",
314
+ lines=2,
315
+ scale=4
316
+ )
317
+ submit_btn = gr.Button("Analyze", variant="primary", scale=1)
318
+
319
+ with gr.Row():
320
+ clear_btn = gr.Button("Clear Chat", scale=1)
321
+
322
+ # Default dashboard on load
323
+ def load_dashboard():
324
+ df_load = load_data()
325
+ kpi_html_content = generate_kpi_html()
326
+
327
+ default_narrative = """### Dashboard Ready
328
+
329
+ Ask me about:
330
+ - Sales trends and budget variance
331
+ - Product performance and margins
332
+ - Channel-wise analysis
333
+ - Profitability drivers"""
334
+
335
+ return (
336
+ kpi_html_content,
337
+ create_ytd_chart(),
338
+ create_product_mix_chart(),
339
+ create_channel_mix_chart(),
340
+ create_margin_view(),
341
+ default_narrative,
342
+ []
343
+ )
344
+
345
+ # Submit handler
346
+ def handle_submit(question, chat_history):
347
+ updated_history, _ = process_chat(question, chat_history)
348
+
349
+ # Generate updated narrative based on question
350
+ if question.strip():
351
+ df_load = load_data()
352
+ latest = df_load.iloc[-1]
353
+
354
+ narrative_text = f"""### AI Analysis Result
355
+
356
+ **Question:** {question}
357
+
358
+ **Key Metrics ({latest['Month']})**
359
+ - Sales: ₹{latest['Actual Sales (₹ Cr)']:.1f} Cr
360
+ - Gross Margin: {latest['Gross Margin %']:.1f}%
361
+ - EBITDA Margin: {latest['EBITDA Margin %']:.1f}%
362
+ - Channels: Direct ₹{latest['Direct Channel (₹ Cr)']:.1f}Cr | Retail ₹{latest['Retail Channel (₹ Cr)']:.1f}Cr | E-com ₹{latest['E-commerce Channel (₹ Cr)']:.1f}Cr
363
+ """
364
+ else:
365
+ narrative_text = "Please enter a question to get AI-powered analysis."
366
+
367
+ return (
368
+ updated_history,
369
+ "",
370
+ narrative_text
371
+ )
372
+
373
+ # Clear handler
374
+ def handle_clear():
375
+ dashboard_data = load_dashboard()
376
+ return (
377
+ [],
378
+ "",
379
+ dashboard_data[5]
380
+ )
381
+
382
+ # Event handlers
383
+ submit_btn.click(
384
+ handle_submit,
385
+ inputs=[question_input, chat_state],
386
+ outputs=[chatbot, question_input, narrative]
387
+ )
388
+
389
+ clear_btn.click(
390
+ handle_clear,
391
+ outputs=[chatbot, question_input, narrative]
392
+ )
393
+
394
+ # Load dashboard on startup
395
+ demo.load(
396
+ load_dashboard,
397
+ outputs=[kpi_html, chart1, chart2, chart3, chart4, narrative, chat_state]
398
+ )
399
+
400
+ return demo
401
+
402
+ if __name__ == "__main__":
403
+ app = create_app()
404
+ app.launch(
405
+ share=True,
406
+ server_name="0.0.0.0",
407
+ server_port=7860,
408
+ debug=True
409
+ )