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
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
# app.py -- AI CFO Demo for Zero B (Consumer Goods Division)
import os
import pandas as pd
import gradio as gr
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
from groq import Groq

# Load data files (from data folder for local, root for Hugging Face)
import os
data_dir = 'data' if os.path.exists('data') else '.'
weekly_sales_df = pd.read_csv(f'{data_dir}/weekly_sales.csv')
monthly_financials_df = pd.read_csv(f'{data_dir}/monthly_financials.csv')
quarterly_financials_df = pd.read_csv(f'{data_dir}/quarterly_financials.csv')
sku_performance_df = pd.read_csv(f'{data_dir}/sku_performance.csv')
channel_sales_df = pd.read_csv(f'{data_dir}/channel_sales.csv')
inventory_df = pd.read_csv(f'{data_dir}/inventory_data.csv')
kpis_df = pd.read_csv(f'{data_dir}/kpi_dashboard.csv')

# Get API key from environment
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
if not GROQ_API_KEY:
    raise RuntimeError("GROQ_API_KEY must be set in Hugging Face secrets.")

client = Groq(api_key=GROQ_API_KEY)
conversation_history = []
drilldown_history = []

# Financial context builder
def create_financial_context(frequency="monthly"):
    if frequency == "weekly":
        df = weekly_sales_df
        latest = df.iloc[-1]
        prev = df.iloc[-2] if len(df) > 1 else latest
        period = f"Week ending {latest['Week_End_Date']}"
        growth = ((latest['Revenue'] - prev['Revenue']) / prev['Revenue'] * 100)
    elif frequency == "quarterly":
        df = quarterly_financials_df
        latest = df.iloc[-1]
        prev = df.iloc[-2] if len(df) > 1 else latest
        period = f"Q{latest['Quarter']} FY{latest['Fiscal_Year']}"
        growth = ((latest['Revenue'] - prev['Revenue']) / prev['Revenue'] * 100)
    else:  # monthly
        df = monthly_financials_df
        latest = df.iloc[-1]
        prev = df.iloc[-2] if len(df) > 1 else latest
        period = latest['Month']
        growth = ((latest['Revenue'] - prev['Revenue']) / prev['Revenue'] * 100)
    
    gross_margin = (latest['Gross_Profit'] / latest['Revenue'] * 100)
    ebitda_margin = (latest['EBITDA'] / latest['Revenue'] * 100)
    
    context = f"""
Zero B (Ion Exchange India Ltd. - Consumer Division) snapshot ({period}):
Revenue: β‚Ή{latest['Revenue']:,.0f} Cr ({growth:+.1f}% growth)
Gross Profit: β‚Ή{latest['Gross_Profit']:,.2f} Cr ({gross_margin:.1f}% margin)
EBITDA: β‚Ή{latest['EBITDA']:,.2f} Cr ({ebitda_margin:.1f}% margin)
Working Capital: β‚Ή{latest['Working_Capital']:,.2f} Cr
Inventory Days: {latest['Inventory_Days']:.0f} days

Top SKUs by Revenue:
{sku_performance_df.nlargest(5,'Revenue')[['SKU_Name','Revenue','Margin_Pct','Inventory_Days']].to_string(index=False)}

Channel Performance:
{channel_sales_df[['Channel','Revenue','Growth_Pct','Contribution_Pct']].to_string(index=False)}

Critical KPIs:
{kpis_df[kpis_df['Status']=="Behind"][['Metric','Current_Value','Target_Value','Variance_Pct']].to_string(index=False)}

Inventory Alerts:
{inventory_df[inventory_df['Stock_Status']!="Optimal"][['SKU_Name','Stock_Status','Days_of_Stock','Reorder_Needed']].to_string(index=False)}
"""
    return context, period

def ask_ai_cfo(question, frequency="monthly", is_drilldown=False):
    financial_context, period = create_financial_context(frequency)
    
    system_prompt = f"""You are the AI CFO of Zero B, the consumer goods division of Ion Exchange India Ltd. 
Zero B is a leading water purifier brand in India competing with Kent, Aquaguard, and Livpure.

Use the financial data below to answer questions with strategic, actionable insights focused on consumer goods metrics.

{financial_context}

Key Context:
- Zero B operates in high-volume consumer goods with weekly sales tracking
- Focus on SKU performance, channel distribution, inventory turnover, and seasonal trends
- Parent company: Ion Exchange India Ltd (Listed on NSE/BSE)
- Current period: {period} ({frequency} view)

Be CEO-friendly, use specific numbers, highlight risks/opportunities, and provide actionable recommendations.
{"This is a drill-down question on a specific chart area - provide deeper analysis." if is_drilldown else ""}
"""
    
    messages = [{"role": "system", "content": system_prompt}]
    history = drilldown_history if is_drilldown else conversation_history
    for msg in history[-10:]:
        messages.append(msg)
    messages.append({"role": "user", "content": question})
    
    try:
        response = client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=messages,
            temperature=0.7,
            max_tokens=1500,
            top_p=1,
            stream=False
        )
        answer = response.choices[0].message.content
        history.append({"role": "user", "content": question})
        history.append({"role": "assistant", "content": answer})
        return answer
    except Exception as e:
        return f"❌ Error: {str(e)}"

def create_chart(chart_type="overview", frequency="monthly", drilldown_data=None):
    if frequency == "weekly":
        df = weekly_sales_df
        x_col = 'Week_End_Date'
        title_suffix = "(Weekly View)"
    elif frequency == "quarterly":
        df = quarterly_financials_df
        x_col = 'Quarter_Label'
        title_suffix = "(Quarterly View)"
    else:
        df = monthly_financials_df
        x_col = 'Month'
        title_suffix = "(Monthly View)"
    
    if chart_type == "revenue_trend":
        fig = make_subplots(specs=[[{"secondary_y": True}]])
        fig.add_trace(go.Scatter(x=df[x_col], y=df['Revenue'],
            name="Revenue", line=dict(color='#1f77b4', width=3),
            mode='lines+markers', marker=dict(size=8)),secondary_y=False)
        fig.add_trace(go.Scatter(x=df[x_col], y=df['EBITDA'],
            name="EBITDA", line=dict(color='#2ca02c', width=3),
            mode='lines+markers', marker=dict(size=8)),secondary_y=False)
        fig.update_layout(title=f"Revenue & EBITDA Trend {title_suffix}",
            height=500,template="plotly_white",hovermode='x unified')
        fig.update_yaxes(title_text="Amount (β‚Ή Cr)", secondary_y=False)
        
    elif chart_type == "margin_analysis":
        df['Gross_Margin'] = (df['Gross_Profit'] / df['Revenue'] * 100)
        df['EBITDA_Margin'] = (df['EBITDA'] / df['Revenue'] * 100)
        fig = go.Figure()
        fig.add_trace(go.Bar(x=df[x_col], y=df['Gross_Margin'],
            name='Gross Margin %', marker_color='#1f77b4'))
        fig.add_trace(go.Bar(x=df[x_col], y=df['EBITDA_Margin'],
            name='EBITDA Margin %', marker_color='#2ca02c'))
        fig.update_layout(title=f"Margin Analysis {title_suffix}",
            yaxis_title="Margin %",height=500,template="plotly_white",barmode='group')
            
    elif chart_type == "sku_performance":
        fig = px.bar(sku_performance_df.sort_values('Revenue', ascending=False),
            x='SKU_Name', y='Revenue', color='Category',
            title="SKU Performance by Revenue",
            color_discrete_sequence=px.colors.qualitative.Set2)
        fig.update_layout(height=500, template="plotly_white", xaxis_tickangle=-45)
        fig.update_yaxes(title_text="Revenue (β‚Ή Cr)")
        
    elif chart_type == "channel_sales":
        fig = px.pie(channel_sales_df, values='Revenue', names='Channel',
            title="Channel-wise Revenue Distribution",
            color_discrete_sequence=px.colors.qualitative.Pastel)
        fig.update_traces(textposition='inside', textinfo='percent+label')
        fig.update_layout(height=500)
        
    elif chart_type == "inventory_status":
        fig = px.bar(inventory_df.sort_values('Days_of_Stock'),
            x='SKU_Name', y='Days_of_Stock', color='Stock_Status',
            color_discrete_map={'Optimal': '#2ca02c', 'Low': '#ff7f0e', 
                               'Critical': '#d62728', 'Excess': '#9467bd'},
            title="Inventory Status - Days of Stock")
        fig.add_hline(y=30, line_dash="dash", line_color="green", 
                     annotation_text="Optimal Level")
        fig.update_layout(height=500, template="plotly_white", xaxis_tickangle=-45)
        
    elif chart_type == "channel_growth":
        fig = px.bar(channel_sales_df.sort_values('Growth_Pct'),
            x='Channel', y='Growth_Pct', color='Growth_Pct',
            color_continuous_scale=['red', 'yellow', 'green'],
            title="Channel-wise Growth Rate")
        fig.add_hline(y=0, line_dash="dash", line_color="black")
        fig.update_layout(height=500, template="plotly_white")
        
    elif chart_type == "working_capital":
        fig = go.Figure()
        fig.add_trace(go.Scatter(x=df[x_col], y=df['Working_Capital'],
            name="Working Capital", fill='tozeroy',
            line=dict(color='#17becf', width=3),
            mode='lines+markers', marker=dict(size=8)))
        fig.update_layout(title=f"Working Capital Trend {title_suffix}",
            yaxis_title="Working Capital (β‚Ή Cr)",height=500,template="plotly_white")
            
    elif chart_type == "kpi_dashboard":
        kpis_behind = kpis_df[kpis_df['Status'] == 'Behind'].copy()
        kpis_behind['Abs_Variance'] = kpis_behind['Variance_Pct'].abs()
        fig = px.bar(kpis_behind.sort_values('Abs_Variance', ascending=True),
            y='Metric', x='Abs_Variance', orientation='h', color='Priority',
            color_discrete_map={'High': '#d62728', 'Medium': '#ff7f0e', 
                               'Critical': '#8B0000', 'Low': '#2ca02c'},
            title="KPIs Behind Target (% Variance)")
        fig.update_layout(height=500, template="plotly_white")
        
    else:  # overview
        fig = make_subplots(rows=2, cols=2,
            subplot_titles=('Revenue Trend', 'Channel Distribution', 
                          'Top SKUs', 'Inventory Status'),
            specs=[[{"type": "scatter"}, {"type": "pie"}],
                   [{"type": "bar"}, {"type": "bar"}]])
        
        fig.add_trace(go.Scatter(x=df[x_col], y=df['Revenue'],
            name="Revenue", line=dict(color='#1f77b4', width=2)),row=1, col=1)
        
        fig.add_trace(go.Pie(labels=channel_sales_df['Channel'],
            values=channel_sales_df['Revenue'], name="Channels"),row=1, col=2)
        
        top5_sku = sku_performance_df.nlargest(5, 'Revenue')
        fig.add_trace(go.Bar(x=top5_sku['SKU_Name'], y=top5_sku['Revenue'],
            name="SKU Revenue", marker_color='#2ca02c', showlegend=False),row=2, col=1)
        
        fig.add_trace(go.Bar(x=inventory_df['SKU_Name'], y=inventory_df['Days_of_Stock'],
            name="Inventory Days", marker_color='#ff7f0e', showlegend=False),row=2, col=2)
        
        fig.update_layout(height=700, showlegend=False, template="plotly_white")
    
    return fig

def create_drilldown_chart(chart_area, frequency="monthly"):
    if "revenue" in chart_area.lower() or "sales" in chart_area.lower():
        return create_chart("revenue_trend", frequency)
    elif "channel" in chart_area.lower():
        return create_chart("channel_growth", frequency)
    elif "sku" in chart_area.lower() or "product" in chart_area.lower():
        return create_chart("sku_performance", frequency)
    elif "inventory" in chart_area.lower() or "stock" in chart_area.lower():
        return create_chart("inventory_status", frequency)
    elif "margin" in chart_area.lower():
        return create_chart("margin_analysis", frequency)
    else:
        return create_chart("overview", frequency)

SAMPLE_QUESTIONS = [
    "What is our current revenue and EBITDA performance?",
    "Which SKUs are driving growth and which are underperforming?",
    "Show me channel-wise sales distribution and growth trends",
    "What's our inventory position - any stockouts or excess inventory?",
    "Analyze our gross margin trends and identify improvement areas",
    "Which products have the best margins and turnover?",
    "Show me working capital trends and cash conversion cycle",
    "What are the critical KPIs that need immediate attention?",
    "Compare online vs offline channel performance",
    "Which SKUs need inventory replenishment urgently?",
    "Show seasonal trends in our sales data",
    "What's driving the change in EBITDA margin?",
    "Analyze distribution coverage and channel penetration",
    "Show me product category performance breakdown",
    "What recommendations do you have to improve profitability?"
]

def process_query(selected_question, custom_question, frequency):
    if custom_question.strip():
        selected_question = "Not selected"
    
    question = custom_question.strip() if custom_question.strip() else selected_question
    if not question or question == "Not selected":
        return "❌ Please select a sample question or enter your own.", None, "Not selected"
    
    response = ask_ai_cfo(question, frequency)
    q_lower = question.lower()
    
    if any(word in q_lower for word in ["revenue", "sales", "growth", "trend"]):
        chart = create_chart("revenue_trend", frequency)
    elif any(word in q_lower for word in ["margin", "profitability", "gross", "ebitda"]):
        chart = create_chart("margin_analysis", frequency)
    elif any(word in q_lower for word in ["channel", "distribution", "online", "offline"]):
        chart = create_chart("channel_sales", frequency)
    elif any(word in q_lower for word in ["sku", "product", "category"]):
        chart = create_chart("sku_performance", frequency)
    elif any(word in q_lower for word in ["inventory", "stock", "days", "turnover"]):
        chart = create_chart("inventory_status", frequency)
    elif any(word in q_lower for word in ["working capital", "cash", "cycle"]):
        chart = create_chart("working_capital", frequency)
    elif any(word in q_lower for word in ["kpi", "metric", "target", "behind"]):
        chart = create_chart("kpi_dashboard", frequency)
    else:
        chart = create_chart("overview", frequency)
    
    return response, chart, selected_question

def process_drilldown(drilldown_question, chart_area, frequency):
    if not drilldown_question.strip():
        return "❌ Please enter a question.", None
    
    # Use chart_area as context if provided, otherwise treat as regular question
    if chart_area.strip():
        context_question = f"Regarding {chart_area}: {drilldown_question}"
    else:
        context_question = drilldown_question
    
    response = ask_ai_cfo(context_question, frequency, is_drilldown=True)
    
    # Smart chart selection based on question
    q_lower = drilldown_question.lower()
    if any(word in q_lower for word in ["revenue", "sales", "growth"]):
        chart = create_chart("revenue_trend", frequency)
    elif any(word in q_lower for word in ["margin", "profit"]):
        chart = create_chart("margin_analysis", frequency)
    elif any(word in q_lower for word in ["channel", "distribution"]):
        chart = create_chart("channel_growth", frequency)
    elif any(word in q_lower for word in ["sku", "product"]):
        chart = create_chart("sku_performance", frequency)
    elif any(word in q_lower for word in ["inventory", "stock"]):
        chart = create_chart("inventory_status", frequency)
    elif chart_area.strip():
        chart = create_drilldown_chart(chart_area, frequency)
    else:
        chart = create_chart("overview", frequency)
    
    return response, chart

custom_css = """
#main_container {height: 90vh; display: flex; flex-direction: column;}
#dashboard_section {height: 75%; overflow-y: auto; padding: 10px;}
#input_section {height: 25%; border-top: 3px solid #667eea; padding: 15px; background: #f8f9fa;}
.gradio-container {max-width: 100% !important;}
"""

with gr.Blocks(title="AI CFO - Zero B", css=custom_css) as demo:
    gr.Markdown("""
    # 🚰 AI CFO Dashboard - Zero B (Ion Exchange India Ltd.)
    ### *Consumer Goods Division - Water Purifier Business*
    """)
    
    with gr.Row():
        gr.Markdown("### Ask questions about sales, margins, inventory, channels, and KPIs")
        frequency_toggle = gr.Radio(
            choices=["Weekly", "Monthly", "Quarterly"],
            value="Monthly",
            label="πŸ“Š Data Frequency"
        )
    
    with gr.Column(elem_id="main_container"):
        with gr.Row(elem_id="dashboard_section"):
            with gr.Column(scale=6):
                gr.Markdown("## πŸ“ˆ Dashboard & Analytics")
                main_chart = gr.Plot(label="Main Analysis", show_label=False)
                
                with gr.Accordion("πŸ” Ask Follow-Up Questions", open=False):
                    drilldown_question = gr.Textbox(
                        label="Ask any question about the data",
                        placeholder="E.g., 'Why did revenue drop?', 'Which SKU has best margin?', 'Show me inventory trends'",
                        lines=3
                    )
                    drilldown_area = gr.Textbox(
                        label="Optional: Specify focus area",
                        placeholder="E.g., 'Revenue', 'Channels', 'Inventory' (leave blank for general questions)",
                        lines=1
                    )
                    drilldown_btn = gr.Button("πŸ” Get Answer", variant="primary", size="lg")
                    drilldown_chart = gr.Plot(label="Drill-Down Chart")
                    drilldown_response = gr.Textbox(
                        label="Detailed Analysis",
                        lines=6,
                        interactive=False
                    )
            
            with gr.Column(scale=4):
                gr.Markdown("## πŸ’‘ AI CFO Insights")
                response_box = gr.Textbox(
                    label="Analysis & Recommendations",
                    lines=25,
                    interactive=False,
                    show_copy_button=True
                )
        
        with gr.Row(elem_id="input_section"):
            with gr.Column(scale=7):
                sample_dropdown = gr.Dropdown(
                    choices=["Not selected"] + SAMPLE_QUESTIONS,
                    value="Not selected",
                    label="πŸ“‹ Quick Questions",
                    info="Select a question or type your own below"
                )
            with gr.Column(scale=3):
                submit_btn = gr.Button("πŸ” Analyze", variant="primary", size="lg")
                clear_btn = gr.Button("πŸ”„ Clear", variant="secondary")
        
        with gr.Row(elem_id="input_section"):
            custom_input = gr.Textbox(
                label="✍️ Or Ask Your Own Question",
                lines=3,
                placeholder="E.g., What's driving the margin decline in water purifiers?"
            )
    
    submit_btn.click(
        fn=lambda sq, cq, f: process_query(sq, cq, f.lower()),
        inputs=[sample_dropdown, custom_input, frequency_toggle],
        outputs=[response_box, main_chart, sample_dropdown]
    )
    
    drilldown_btn.click(
        fn=lambda dq, da, f: process_drilldown(dq, da, f.lower()),
        inputs=[drilldown_question, drilldown_area, frequency_toggle],
        outputs=[drilldown_response, drilldown_chart]
    )
    
    clear_btn.click(
        fn=lambda: ("", None, "Not selected", "", "", None, ""),
        inputs=[],
        outputs=[response_box, main_chart, sample_dropdown, 
                custom_input, drilldown_response, drilldown_chart, drilldown_question]
    )
    
    gr.Markdown("""
    ---
    **About Zero B**: Part of Ion Exchange India Ltd., Zero B is a leading water purifier brand with presence across retail, e-commerce, and distributor channels.
    
    **Data Security**: All financial data is based on public filings and estimated calculations. API keys are secured in Hugging Face environment variables.
    """)

if __name__ == "__main__":
    demo.launch()