Spaces:
Runtime error

JoyB's picture
Created app.py
4f5f8ae verified
Raw History Blame Contribute Delete
19.1 kB
import os
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.utils import PlotlyJSONEncoder
import json
from flask import Flask, render_template, request, redirect, url_for, session, flash, jsonify
from werkzeug.security import generate_password_hash, check_password_hash
from functools import wraps
from datetime import datetime
from typing import Dict, List, Any, Optional, Callable
class DashboardConfig:
"""Configuration class for the dashboard"""
def __init__(self):
self.SECRET_KEY = os.environ.get('SECRET_KEY', 'your-secret-key-change-this')
self.USERNAME = os.environ.get('DASHBOARD_USER', 'admin')
self.PASSWORD = os.environ.get('DASHBOARD_PASS', 'admin123')
self.DEBUG = os.environ.get('FLASK_DEBUG', 'True').lower() == 'true'
class DataProcessor:
"""Handle data processing and filtering operations"""
def __init__(self):
self.dataframes = {}
self.filters = {}
def register_dataframe(self, name: str, df: pd.DataFrame):
"""Register a dataframe for use in the dashboard"""
self.dataframes[name] = df.copy()
def get_dataframe(self, name: str, filters: Dict = None) -> pd.DataFrame:
"""Get a filtered dataframe"""
if name not in self.dataframes:
raise ValueError(f"Dataframe '{name}' not found")
df = self.dataframes[name].copy()
if filters:
for column, filter_value in filters.items():
if column in df.columns:
if isinstance(filter_value, list):
df = df[df[column].isin(filter_value)]
elif isinstance(filter_value, dict):
if 'min' in filter_value and 'max' in filter_value:
df = df[(df[column] >= filter_value['min']) &
(df[column] <= filter_value['max'])]
else:
df = df[df[column] == filter_value]
return df
def get_column_values(self, df_name: str, column: str) -> List:
"""Get unique values for a column"""
if df_name in self.dataframes:
return sorted(self.dataframes[df_name][column].dropna().unique().tolist())
return []
class ChartBuilder:
"""Build different types of charts using Plotly"""
@staticmethod
def line_chart(df: pd.DataFrame, x: str, y: str, title: str = "", **kwargs):
"""Create a line chart"""
fig = px.line(df, x=x, y=y, title=title, **kwargs)
fig.update_layout(template='plotly_white')
return json.dumps(fig, cls=PlotlyJSONEncoder)
@staticmethod
def bar_chart(df: pd.DataFrame, x: str, y: str, title: str = "", **kwargs):
"""Create a bar chart"""
fig = px.bar(df, x=x, y=y, title=title, **kwargs)
fig.update_layout(template='plotly_white')
return json.dumps(fig, cls=PlotlyJSONEncoder)
@staticmethod
def scatter_plot(df: pd.DataFrame, x: str, y: str, title: str = "", **kwargs):
"""Create a scatter plot"""
fig = px.scatter(df, x=x, y=y, title=title, **kwargs)
fig.update_layout(template='plotly_white')
return json.dumps(fig, cls=PlotlyJSONEncoder)
@staticmethod
def histogram(df: pd.DataFrame, x: str, title: str = "", **kwargs):
"""Create a histogram"""
fig = px.histogram(df, x=x, title=title, **kwargs)
fig.update_layout(template='plotly_white')
return json.dumps(fig, cls=PlotlyJSONEncoder)
@staticmethod
def pie_chart(df: pd.DataFrame, names: str, values: str, title: str = "", **kwargs):
"""Create a pie chart"""
fig = px.pie(df, names=names, values=values, title=title, **kwargs)
fig.update_layout(template='plotly_white')
return json.dumps(fig, cls=PlotlyJSONEncoder)
@staticmethod
def box_plot(df: pd.DataFrame, x: str, y: str, title: str = "", **kwargs):
"""Create a box plot"""
fig = px.box(df, x=x, y=y, title=title, **kwargs)
fig.update_layout(template='plotly_white')
return json.dumps(fig, cls=PlotlyJSONEncoder)
class FilterWidget:
"""Create filter widgets for the dashboard"""
def __init__(self, name: str, widget_type: str, **kwargs):
self.name = name
self.widget_type = widget_type
self.kwargs = kwargs
class DashboardApp:
"""Main dashboard application class"""
def __init__(self, config: DashboardConfig = None):
self.app = Flask(__name__)
self.config = config or DashboardConfig()
self.data_processor = DataProcessor()
self.chart_builder = ChartBuilder()
# Configure Flask app
self.app.config['SECRET_KEY'] = self.config.SECRET_KEY
# Store dashboard configuration
self.dashboard_title = "Dashboard"
self.dashboard_description = ""
self.widgets = []
self.charts = []
self.filters = []
# Setup routes
self._setup_routes()
def _setup_routes(self):
"""Setup Flask routes"""
@self.app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if (username == self.config.USERNAME and
password == self.config.PASSWORD):
session['logged_in'] = True
return redirect(url_for('dashboard'))
else:
flash('Invalid credentials')
return render_template('login.html')
@self.app.route('/logout')
def logout():
session.pop('logged_in', None)
return redirect(url_for('login'))
@self.app.route('/')
@self._login_required
def dashboard():
return render_template('dashboard.html',
title=self.dashboard_title,
description=self.dashboard_description,
filters=self.filters,
charts=self._generate_charts())
@self.app.route('/api/update_charts', methods=['POST'])
@self._login_required
def update_charts():
filters = request.json.get('filters', {})
charts = self._generate_charts(filters)
return jsonify({'charts': charts})
@self.app.route('/api/filter_options/<df_name>/<column>')
@self._login_required
def get_filter_options(df_name, column):
options = self.data_processor.get_column_values(df_name, column)
return jsonify(options)
def _login_required(self, f):
"""Decorator for login required routes"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get('logged_in'):
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function
def configure(self, title: str = "Dashboard", description: str = ""):
"""Configure dashboard settings"""
self.dashboard_title = title
self.dashboard_description = description
def add_dataframe(self, name: str, df: pd.DataFrame):
"""Add a dataframe to the dashboard"""
self.data_processor.register_dataframe(name, df)
def add_filter(self, name: str, df_name: str, column: str, filter_type: str = "multiselect", **kwargs):
"""Add a filter widget"""
filter_widget = {
'name': name,
'df_name': df_name,
'column': column,
'type': filter_type,
'options': self.data_processor.get_column_values(df_name, column),
**kwargs
}
self.filters.append(filter_widget)
def add_chart(self, chart_type: str, df_name: str, title: str = "", **chart_params):
"""Add a chart to the dashboard"""
chart_config = {
'type': chart_type,
'df_name': df_name,
'title': title,
'params': chart_params
}
self.charts.append(chart_config)
def _generate_charts(self, filters: Dict = None):
"""Generate all charts with applied filters"""
generated_charts = []
for chart_config in self.charts:
try:
df = self.data_processor.get_dataframe(chart_config['df_name'], filters)
chart_method = getattr(self.chart_builder, chart_config['type'])
chart_json = chart_method(df, title=chart_config['title'], **chart_config['params'])
generated_charts.append({
'id': f"chart_{len(generated_charts)}",
'title': chart_config['title'],
'json': chart_json
})
except Exception as e:
print(f"Error generating chart: {e}")
continue
return generated_charts
def run(self, host: str = '0.0.0.0', port: int = 5000, debug: bool = None):
"""Run the dashboard application"""
debug = debug if debug is not None else self.config.DEBUG
# Create templates if they don't exist
self._create_templates()
self.app.run(host=host, port=port, debug=debug)
def _create_templates(self):
"""Create HTML templates"""
os.makedirs('templates', exist_ok=True)
# Login template
login_template = '''<!DOCTYPE html>
<html>
<head>
<title>Dashboard Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background: #f5f5f5; }
.login-container { max-width: 400px; margin: 100px auto; background: white; padding: 40px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
h2 { text-align: center; margin-bottom: 30px; color: #333; }
.form-group { margin-bottom: 20px; }
label { display: block; margin-bottom: 5px; color: #666; }
input[type="text"], input[type="password"] { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
button { width: 100%; padding: 12px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; }
button:hover { background: #0056b3; }
.flash-message { color: red; text-align: center; margin-bottom: 20px; }
</style>
</head>
<body>
<div class="login-container">
<h2>Dashboard Login</h2>
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="flash-message">{{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
<form method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>
<button type="submit">Login</button>
</form>
</div>
</body>
</html>'''
# Dashboard template
dashboard_template = '''<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<style>
body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background: #f5f5f5; }
.header { background: white; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.header h1 { margin: 0; color: #333; }
.header p { margin: 10px 0 0 0; color: #666; }
.logout { float: right; }
.logout a { color: #dc3545; text-decoration: none; }
.filters { background: white; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.filter-row { display: flex; gap: 20px; flex-wrap: wrap; align-items: end; }
.filter-group { flex: 1; min-width: 200px; }
.filter-group label { display: block; margin-bottom: 5px; color: #666; font-weight: bold; }
.filter-group select { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
.charts { display: grid; grid-template-columns: repeat(auto-fit, minmax(500px, 1fr)); gap: 20px; }
.chart-container { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.chart-title { margin-bottom: 15px; color: #333; font-size: 18px; font-weight: bold; }
button { padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
button:hover { background: #0056b3; }
</style>
</head>
<body>
<div class="header">
<div class="logout">
<a href="{{ url_for('logout') }}">Logout</a>
</div>
<h1>{{ title }}</h1>
{% if description %}
<p>{{ description }}</p>
{% endif %}
</div>
{% if filters %}
<div class="filters">
<div class="filter-row">
{% for filter in filters %}
<div class="filter-group">
<label for="filter_{{ loop.index0 }}">{{ filter.name }}:</label>
<select id="filter_{{ loop.index0 }}" data-df="{{ filter.df_name }}" data-column="{{ filter.column }}" multiple>
{% for option in filter.options %}
<option value="{{ option }}">{{ option }}</option>
{% endfor %}
</select>
</div>
{% endfor %}
<div class="filter-group">
<button onclick="updateCharts()">Update Charts</button>
</div>
</div>
</div>
{% endif %}
<div id="charts-container" class="charts">
{% for chart in charts %}
<div class="chart-container">
{% if chart.title %}
<div class="chart-title">{{ chart.title }}</div>
{% endif %}
<div id="{{ chart.id }}"></div>
</div>
{% endfor %}
</div>
<script>
// Render initial charts
{% for chart in charts %}
Plotly.newPlot('{{ chart.id }}', {{ chart.json|safe }}.data, {{ chart.json|safe }}.layout);
{% endfor %}
function updateCharts() {
const filters = {};
// Collect filter values
{% for filter in filters %}
const filter{{ loop.index0 }} = document.getElementById('filter_{{ loop.index0 }}');
const selectedValues{{ loop.index0 }} = Array.from(filter{{ loop.index0 }}.selectedOptions).map(option => option.value);
if (selectedValues{{ loop.index0 }}.length > 0) {
if (!filters['{{ filter.df_name }}']) filters['{{ filter.df_name }}'] = {};
filters['{{ filter.df_name }}']['{{ filter.column }}'] = selectedValues{{ loop.index0 }};
}
{% endfor %}
// Send AJAX request to update charts
fetch('/api/update_charts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({filters: filters})
})
.then(response => response.json())
.then(data => {
// Update each chart
data.charts.forEach((chart, index) => {
const chartData = JSON.parse(chart.json);
Plotly.newPlot(chart.id, chartData.data, chartData.layout);
});
})
.catch(error => console.error('Error updating charts:', error));
}
</script>
</body>
</html>'''
with open('templates/login.html', 'w') as f:
f.write(login_template)
with open('templates/dashboard.html', 'w') as f:
f.write(dashboard_template)
# Example usage
if __name__ == "__main__":
# Create sample data
import numpy as np
# Sample sales data
dates = pd.date_range('2023-01-01', periods=365, freq='D')
sales_data = pd.DataFrame({
'date': dates,
'sales': np.random.normal(1000, 200, 365) + np.sin(np.arange(365) * 2 * np.pi / 365) * 300,
'region': np.random.choice(['North', 'South', 'East', 'West'], 365),
'product': np.random.choice(['Product A', 'Product B', 'Product C'], 365),
'profit': np.random.normal(150, 50, 365)
})
# Sample customer data
customer_data = pd.DataFrame({
'customer_id': range(1, 1001),
'age': np.random.normal(35, 12, 1000),
'segment': np.random.choice(['Premium', 'Standard', 'Basic'], 1000),
'lifetime_value': np.random.exponential(500, 1000)
})
# Create dashboard
dashboard = DashboardApp()
# Configure dashboard
dashboard.configure(
title="Sales Analytics Dashboard",
description="Monitor sales performance and customer metrics"
)
# Add dataframes
dashboard.add_dataframe('sales', sales_data)
dashboard.add_dataframe('customers', customer_data)
# Add filters
dashboard.add_filter('Region', 'sales', 'region', 'multiselect')
dashboard.add_filter('Product', 'sales', 'product', 'multiselect')
dashboard.add_filter('Customer Segment', 'customers', 'segment', 'multiselect')
# Add charts
dashboard.add_chart('line_chart', 'sales', 'Daily Sales Trend', x='date', y='sales')
dashboard.add_chart('bar_chart', 'sales', 'Sales by Region',
x='region', y='sales', color='region')
dashboard.add_chart('scatter_plot', 'sales', 'Sales vs Profit',
x='sales', y='profit', color='product')
dashboard.add_chart('histogram', 'customers', 'Customer Age Distribution', x='age')
dashboard.add_chart('pie_chart', 'customers', 'Customer Segments',
names='segment', values='lifetime_value')
dashboard.add_chart('box_plot', 'customers', 'Lifetime Value by Segment',
x='segment', y='lifetime_value')
# Run the dashboard
print("Dashboard starting...")
print("Default credentials - Username: admin, Password: admin123")
print("Access the dashboard at: http://localhost:5000")
dashboard.run(debug=True)