Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import pandas as pd | |
| import numpy as np | |
| import plotly.express as px | |
| import time | |
| import os | |
| # ------------------------------- | |
| # Utility Functions & Data Loading | |
| # ------------------------------- | |
| def load_data(): | |
| """ | |
| Load the dataset. | |
| Update the filename/path based on your uploaded data. | |
| """ | |
| filename = "data.csv" # change this to your dataset filename if needed | |
| if os.path.exists(filename): | |
| try: | |
| data = pd.read_csv(filename) | |
| except Exception as e: | |
| print("Error reading file:", e) | |
| data = pd.DataFrame() | |
| else: | |
| # In case the file is not found, create a dummy dataframe for demonstration | |
| data = pd.DataFrame({ | |
| "Date": pd.date_range(start="2023-01-01", periods=12, freq="M"), | |
| "Branch": np.random.choice(["North", "South", "East", "West"], 12), | |
| "Transactions": np.random.randint(100, 1000, 12), | |
| "Revenue": np.random.uniform(1000, 10000, 12) | |
| }) | |
| return data | |
| # Global load of data (simulate caching for performance) | |
| DATA = load_data() | |
| # ------------------------------- | |
| # Data Modeling and Aggregation | |
| # ------------------------------- | |
| def data_modelling(): | |
| """ | |
| Demonstrates data modeling by performing built-in aggregations. | |
| This function computes aggregates such as total transactions and average revenue per branch. | |
| """ | |
| if DATA.empty: | |
| return "No data loaded." | |
| # Built-in aggregations using pandas (simulate DAX-like functions) | |
| agg_data = DATA.groupby("Branch").agg({ | |
| "Transactions": "sum", | |
| "Revenue": "mean" | |
| }).reset_index() | |
| # Rename columns to simulate DAX-like output formatting | |
| agg_data.rename(columns={ | |
| "Transactions": "Total Transactions", | |
| "Revenue": "Average Revenue" | |
| }, inplace=True) | |
| return agg_data | |
| # ------------------------------- | |
| # Dashboard / Data Visualization | |
| # ------------------------------- | |
| def create_visualization(): | |
| """ | |
| Create interactive charts using Plotly. | |
| Generates two charts: | |
| 1. A bar chart of total transactions per branch. | |
| 2. A line chart of revenue over time. | |
| """ | |
| if DATA.empty: | |
| return "No data available for visualization." | |
| # Bar Chart: Total Transactions by Branch | |
| agg = DATA.groupby("Branch")["Transactions"].sum().reset_index() | |
| bar_fig = px.bar(agg, x="Branch", y="Transactions", title="Total Transactions by Branch", | |
| labels={"Transactions": "Total Transactions"}) | |
| # Line Chart: Revenue over Time (if Date column exists) | |
| if "Date" in DATA.columns: | |
| # Ensure date is in datetime format | |
| DATA["Date"] = pd.to_datetime(DATA["Date"], errors='coerce') | |
| line_fig = px.line(DATA.sort_values("Date"), x="Date", y="Revenue", title="Revenue Over Time", | |
| labels={"Revenue": "Revenue ($)"}) | |
| else: | |
| line_fig = None | |
| return bar_fig, line_fig | |
| # ------------------------------- | |
| # Simulated DAX Simulator | |
| # ------------------------------- | |
| def dax_simulator(dax_command: str): | |
| """ | |
| A simulated DAX command processor. | |
| This function pretends to interpret a DAX command and returns a pseudo-code or explanation. | |
| In a real project, you could integrate a generative AI API to translate DAX to pandas code. | |
| """ | |
| dax_command = dax_command.strip().lower() | |
| if "sum" in dax_command: | |
| response = "DAX SUM detected. In pandas, you can use: df['Column'].sum()" | |
| elif "average" in dax_command or "mean" in dax_command: | |
| response = "DAX AVERAGE detected. In pandas, you can use: df['Column'].mean()" | |
| elif "count" in dax_command: | |
| response = "DAX COUNT detected. In pandas, you can use: df['Column'].count()" | |
| else: | |
| response = "DAX command not recognized. Please use SUM, AVERAGE/MEAN, or COUNT as an example." | |
| return response | |
| # ------------------------------- | |
| # Generative AI Insights Generator | |
| # ------------------------------- | |
| def generate_insights(query: str): | |
| """ | |
| This function simulates generative AI insights. | |
| In a production system, you might integrate an API (e.g., OpenAI's GPT) to generate detailed insights. | |
| Here, we simulate with a simple response based on keywords. | |
| """ | |
| query_lower = query.strip().lower() | |
| if "performance" in query_lower: | |
| insights = ("The data model shows strong performance with efficient aggregations. " | |
| "Consider further analysis on revenue trends across different branches for optimization.") | |
| elif "trend" in query_lower: | |
| insights = ("The revenue trend over time indicates seasonality. Look into the impact of quarterly marketing " | |
| "campaigns to better understand these patterns.") | |
| elif "optimization" in query_lower: | |
| insights = ("Data model performance can be improved by indexing key columns and caching frequently used aggregates. " | |
| "Ensure your queries are optimized for mobile and desktop views.") | |
| else: | |
| insights = ("Based on the provided query, further investigation is recommended. " | |
| "Analyze branch performance, transaction trends, and revenue patterns for actionable insights.") | |
| # Simulate processing time | |
| time.sleep(1) | |
| return insights | |
| # ------------------------------- | |
| # Gradio Interface Layout | |
| # ------------------------------- | |
| with gr.Blocks(css=".gradio-container { max-width: 100%; }") as demo: | |
| gr.Markdown("# 365 Business Bank Dashboard") | |
| gr.Markdown("This application showcases features such as Data Modelling, Dashboard Creation, Mobile Specific layout, Data Visualization, Builtin Aggregations, and simulated DAX commands. It also includes a generative AI insights module.") | |
| with gr.Tabs(): | |
| # --- Data Overview Tab --- | |
| with gr.Tab("Data Overview"): | |
| gr.Markdown("### Data Model & Aggregations") | |
| agg_table = gr.Dataframe(value=data_modelling(), label="Aggregated Data by Branch", interactive=False) | |
| gr.Markdown("The above table shows total transactions and average revenue per branch computed using built-in aggregations.") | |
| # --- Visualization Tab --- | |
| with gr.Tab("Visualization"): | |
| gr.Markdown("### Interactive Charts") | |
| bar_chart = gr.Plot(label="Bar Chart: Total Transactions by Branch") | |
| line_chart = gr.Plot(label="Line Chart: Revenue Over Time") | |
| def update_charts(): | |
| bar_fig, line_fig = create_visualization() | |
| return bar_fig, line_fig | |
| update_btn = gr.Button("Update Charts") | |
| update_btn.click(fn=update_charts, inputs=[], outputs=[bar_chart, line_chart]) | |
| # --- DAX Simulator Tab --- | |
| with gr.Tab("DAX Simulator"): | |
| gr.Markdown("### Simulated DAX to pandas Conversion") | |
| dax_input = gr.Textbox(lines=2, placeholder="Enter a DAX command (e.g., SUM(Transactions))", label="DAX Command") | |
| dax_output = gr.Textbox(label="Pandas Equivalent Explanation") | |
| dax_input.submit(fn=dax_simulator, inputs=dax_input, outputs=dax_output) | |
| gr.Markdown("Enter common DAX functions (SUM, AVERAGE, COUNT) to see how they translate to pandas.") | |
| # --- AI Insights Generator Tab --- | |
| with gr.Tab("Insights Generator"): | |
| gr.Markdown("### Generate Business Insights") | |
| insight_input = gr.Textbox(lines=2, placeholder="Ask a question about business performance or trends", label="Your Query") | |
| insight_output = gr.Textbox(label="Generated Insights") | |
| insight_input.submit(fn=generate_insights, inputs=insight_input, outputs=insight_output) | |
| gr.Markdown("This simulated generative AI tool provides actionable insights based on your query. For a production system, integrate a dedicated AI service.") | |
| # Optional: A footer section | |
| gr.Markdown("© 2025 365 Business Bank Dashboard - Mobile and Desktop Optimized") | |
| if __name__ == "__main__": | |
| demo.launch() | |