Spaces:
Sleeping
Sleeping
Download app.py from ScaleupCFOAI/Zero_B_V2: direct link, hf CLI and curl.
- Browser
- Download file 19.8 kB
-
https://huggingface.co/spaces/ScaleupCFOAI/Zero_B_V2/resolve/main/app.py
- Command line
-
hf download hf://spaces/ScaleupCFOAI/Zero_B_V2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ScaleupCFOAI/Zero_B_V2/resolve/main/app.py
19.8 kB
| # 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() | |