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//') @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 = ''' Dashboard Login ''' # Dashboard template dashboard_template = ''' {{ title }}

{{ title }}

{% if description %}

{{ description }}

{% endif %}
{% if filters %}
{% for filter in filters %}
{% endfor %}
{% endif %}
{% for chart in charts %}
{% if chart.title %}
{{ chart.title }}
{% endif %}
{% endfor %}
''' 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)