Spaces:
Running
Running
File size: 8,151 Bytes
d2c6a20 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 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 |
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()
|