Edwin Salguero
commited on
Commit
·
712bf79
1
Parent(s):
5ebd76e
Optimize Streamlit app performance with lazy imports and loading indicators
Browse files- frontend/app.py +97 -48
- streamlit_app.py +5 -4
frontend/app.py
CHANGED
|
@@ -6,19 +6,9 @@ Professional think tank interface for comprehensive economic data analysis
|
|
| 6 |
|
| 7 |
import streamlit as st
|
| 8 |
import pandas as pd
|
| 9 |
-
import plotly.express as px
|
| 10 |
-
import plotly.graph_objects as go
|
| 11 |
-
from plotly.subplots import make_subplots
|
| 12 |
-
import boto3
|
| 13 |
-
import json
|
| 14 |
-
from datetime import datetime, timedelta
|
| 15 |
-
import requests
|
| 16 |
import os
|
| 17 |
import sys
|
| 18 |
from typing import Dict, List, Optional
|
| 19 |
-
from pathlib import Path
|
| 20 |
-
|
| 21 |
-
DEMO_MODE = False
|
| 22 |
|
| 23 |
# Page configuration - MUST be first Streamlit command
|
| 24 |
st.set_page_config(
|
|
@@ -28,55 +18,90 @@ st.set_page_config(
|
|
| 28 |
initial_sidebar_state="expanded"
|
| 29 |
)
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
# Add src to path for analytics modules
|
| 32 |
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
|
| 33 |
|
| 34 |
-
#
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
# Get FRED API key from environment
|
| 43 |
FRED_API_KEY = os.getenv('FRED_API_KEY', '')
|
| 44 |
-
CONFIG_IMPORTED = False
|
| 45 |
|
| 46 |
-
#
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
FRED_API_AVAILABLE
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
except ImportError:
|
| 58 |
-
CONFIG_AVAILABLE = False
|
| 59 |
|
| 60 |
-
#
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
# Fallback to demo data
|
| 74 |
try:
|
| 75 |
from demo_data import get_demo_data
|
| 76 |
DEMO_DATA = get_demo_data()
|
| 77 |
DEMO_MODE = True
|
|
|
|
| 78 |
except ImportError:
|
| 79 |
DEMO_MODE = False
|
|
|
|
| 80 |
|
| 81 |
# Custom CSS for enterprise styling
|
| 82 |
st.markdown("""
|
|
@@ -175,6 +200,8 @@ st.markdown("""
|
|
| 175 |
def init_aws_clients():
|
| 176 |
"""Initialize AWS clients for S3 and Lambda with proper error handling"""
|
| 177 |
try:
|
|
|
|
|
|
|
| 178 |
# Use default AWS configuration
|
| 179 |
try:
|
| 180 |
# Try default credentials
|
|
@@ -199,8 +226,9 @@ def init_aws_clients():
|
|
| 199 |
return None, None
|
| 200 |
|
| 201 |
return s3_client, lambda_client
|
|
|
|
| 202 |
except Exception as e:
|
| 203 |
-
#
|
| 204 |
return None, None
|
| 205 |
|
| 206 |
# Load configuration
|
|
@@ -265,6 +293,8 @@ def trigger_lambda_analysis(lambda_client, function_name: str, payload: Dict) ->
|
|
| 265 |
|
| 266 |
def create_time_series_plot(df: pd.DataFrame, title: str = "Economic Indicators"):
|
| 267 |
"""Create interactive time series plot"""
|
|
|
|
|
|
|
| 268 |
fig = go.Figure()
|
| 269 |
|
| 270 |
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b']
|
|
@@ -297,6 +327,8 @@ def create_time_series_plot(df: pd.DataFrame, title: str = "Economic Indicators"
|
|
| 297 |
|
| 298 |
def create_correlation_heatmap(df: pd.DataFrame):
|
| 299 |
"""Create correlation heatmap"""
|
|
|
|
|
|
|
| 300 |
corr_matrix = df.corr()
|
| 301 |
|
| 302 |
fig = px.imshow(
|
|
@@ -319,6 +351,8 @@ def create_correlation_heatmap(df: pd.DataFrame):
|
|
| 319 |
|
| 320 |
def create_forecast_plot(historical_data, forecast_data, title="Forecast"):
|
| 321 |
"""Create forecast plot with confidence intervals"""
|
|
|
|
|
|
|
| 322 |
fig = go.Figure()
|
| 323 |
|
| 324 |
# Historical data
|
|
@@ -383,9 +417,24 @@ def create_forecast_plot(historical_data, forecast_data, title="Forecast"):
|
|
| 383 |
def main():
|
| 384 |
"""Main Streamlit application"""
|
| 385 |
|
| 386 |
-
#
|
| 387 |
-
|
| 388 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 389 |
|
| 390 |
# Sidebar
|
| 391 |
with st.sidebar:
|
|
|
|
| 6 |
|
| 7 |
import streamlit as st
|
| 8 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
import os
|
| 10 |
import sys
|
| 11 |
from typing import Dict, List, Optional
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
# Page configuration - MUST be first Streamlit command
|
| 14 |
st.set_page_config(
|
|
|
|
| 18 |
initial_sidebar_state="expanded"
|
| 19 |
)
|
| 20 |
|
| 21 |
+
# Lazy imports for better performance
|
| 22 |
+
def get_plotly():
|
| 23 |
+
"""Lazy import plotly to reduce startup time"""
|
| 24 |
+
import plotly.express as px
|
| 25 |
+
import plotly.graph_objects as go
|
| 26 |
+
from plotly.subplots import make_subplots
|
| 27 |
+
return px, go, make_subplots
|
| 28 |
+
|
| 29 |
+
def get_boto3():
|
| 30 |
+
"""Lazy import boto3 to reduce startup time"""
|
| 31 |
+
import boto3
|
| 32 |
+
return boto3
|
| 33 |
+
|
| 34 |
+
def get_requests():
|
| 35 |
+
"""Lazy import requests to reduce startup time"""
|
| 36 |
+
import requests
|
| 37 |
+
return requests
|
| 38 |
+
|
| 39 |
+
# Initialize flags
|
| 40 |
+
DEMO_MODE = False
|
| 41 |
+
ANALYTICS_AVAILABLE = False
|
| 42 |
+
FRED_API_AVAILABLE = False
|
| 43 |
+
CONFIG_AVAILABLE = False
|
| 44 |
+
REAL_DATA_MODE = False
|
| 45 |
+
|
| 46 |
# Add src to path for analytics modules
|
| 47 |
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
|
| 48 |
|
| 49 |
+
# Lazy import analytics modules
|
| 50 |
+
def load_analytics():
|
| 51 |
+
"""Load analytics modules only when needed"""
|
| 52 |
+
global ANALYTICS_AVAILABLE
|
| 53 |
+
try:
|
| 54 |
+
from src.analysis.comprehensive_analytics import ComprehensiveAnalytics
|
| 55 |
+
from src.core.enhanced_fred_client import EnhancedFREDClient
|
| 56 |
+
ANALYTICS_AVAILABLE = True
|
| 57 |
+
return True
|
| 58 |
+
except ImportError:
|
| 59 |
+
ANALYTICS_AVAILABLE = False
|
| 60 |
+
return False
|
| 61 |
|
| 62 |
# Get FRED API key from environment
|
| 63 |
FRED_API_KEY = os.getenv('FRED_API_KEY', '')
|
|
|
|
| 64 |
|
| 65 |
+
# Lazy import FRED API client
|
| 66 |
+
def load_fred_client():
|
| 67 |
+
"""Load FRED API client only when needed"""
|
| 68 |
+
global FRED_API_AVAILABLE
|
| 69 |
+
try:
|
| 70 |
+
from fred_api_client import get_real_economic_data, generate_real_insights
|
| 71 |
+
FRED_API_AVAILABLE = True
|
| 72 |
+
return True
|
| 73 |
+
except ImportError:
|
| 74 |
+
FRED_API_AVAILABLE = False
|
| 75 |
+
return False
|
|
|
|
|
|
|
| 76 |
|
| 77 |
+
# Lazy import configuration
|
| 78 |
+
def load_config():
|
| 79 |
+
"""Load configuration only when needed"""
|
| 80 |
+
global CONFIG_AVAILABLE, FRED_API_KEY, REAL_DATA_MODE
|
| 81 |
+
try:
|
| 82 |
+
from config import Config
|
| 83 |
+
CONFIG_AVAILABLE = True
|
| 84 |
+
FRED_API_KEY = Config.get_fred_api_key()
|
| 85 |
+
REAL_DATA_MODE = Config.validate_fred_api_key()
|
| 86 |
+
return True
|
| 87 |
+
except ImportError:
|
| 88 |
+
CONFIG_AVAILABLE = False
|
| 89 |
+
FRED_API_KEY = os.getenv('FRED_API_KEY')
|
| 90 |
+
REAL_DATA_MODE = FRED_API_KEY and FRED_API_KEY != 'your-fred-api-key-here'
|
| 91 |
+
return False
|
| 92 |
|
| 93 |
+
# Lazy load demo data
|
| 94 |
+
def load_demo_data():
|
| 95 |
+
"""Load demo data only when needed"""
|
| 96 |
+
global DEMO_MODE
|
|
|
|
|
|
|
| 97 |
try:
|
| 98 |
from demo_data import get_demo_data
|
| 99 |
DEMO_DATA = get_demo_data()
|
| 100 |
DEMO_MODE = True
|
| 101 |
+
return DEMO_DATA
|
| 102 |
except ImportError:
|
| 103 |
DEMO_MODE = False
|
| 104 |
+
return None
|
| 105 |
|
| 106 |
# Custom CSS for enterprise styling
|
| 107 |
st.markdown("""
|
|
|
|
| 200 |
def init_aws_clients():
|
| 201 |
"""Initialize AWS clients for S3 and Lambda with proper error handling"""
|
| 202 |
try:
|
| 203 |
+
boto3 = get_boto3()
|
| 204 |
+
|
| 205 |
# Use default AWS configuration
|
| 206 |
try:
|
| 207 |
# Try default credentials
|
|
|
|
| 226 |
return None, None
|
| 227 |
|
| 228 |
return s3_client, lambda_client
|
| 229 |
+
|
| 230 |
except Exception as e:
|
| 231 |
+
# AWS not available
|
| 232 |
return None, None
|
| 233 |
|
| 234 |
# Load configuration
|
|
|
|
| 293 |
|
| 294 |
def create_time_series_plot(df: pd.DataFrame, title: str = "Economic Indicators"):
|
| 295 |
"""Create interactive time series plot"""
|
| 296 |
+
px, go, make_subplots = get_plotly()
|
| 297 |
+
|
| 298 |
fig = go.Figure()
|
| 299 |
|
| 300 |
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b']
|
|
|
|
| 327 |
|
| 328 |
def create_correlation_heatmap(df: pd.DataFrame):
|
| 329 |
"""Create correlation heatmap"""
|
| 330 |
+
px, go, make_subplots = get_plotly()
|
| 331 |
+
|
| 332 |
corr_matrix = df.corr()
|
| 333 |
|
| 334 |
fig = px.imshow(
|
|
|
|
| 351 |
|
| 352 |
def create_forecast_plot(historical_data, forecast_data, title="Forecast"):
|
| 353 |
"""Create forecast plot with confidence intervals"""
|
| 354 |
+
px, go, make_subplots = get_plotly()
|
| 355 |
+
|
| 356 |
fig = go.Figure()
|
| 357 |
|
| 358 |
# Historical data
|
|
|
|
| 417 |
def main():
|
| 418 |
"""Main Streamlit application"""
|
| 419 |
|
| 420 |
+
# Show loading indicator
|
| 421 |
+
with st.spinner("🚀 Initializing FRED ML Platform..."):
|
| 422 |
+
# Load configuration
|
| 423 |
+
load_config()
|
| 424 |
+
|
| 425 |
+
# Initialize AWS clients
|
| 426 |
+
s3_client, lambda_client = init_aws_clients()
|
| 427 |
+
config = load_config()
|
| 428 |
+
|
| 429 |
+
# Load demo data if needed
|
| 430 |
+
if not REAL_DATA_MODE:
|
| 431 |
+
demo_data = load_demo_data()
|
| 432 |
+
|
| 433 |
+
# Show data mode info
|
| 434 |
+
if REAL_DATA_MODE:
|
| 435 |
+
st.success("🎯 Using real FRED API data for live economic insights.")
|
| 436 |
+
else:
|
| 437 |
+
st.info("📊 Using demo data for demonstration. Get a free FRED API key for real data.")
|
| 438 |
|
| 439 |
# Sidebar
|
| 440 |
with st.sidebar:
|
streamlit_app.py
CHANGED
|
@@ -13,8 +13,9 @@ frontend_dir = os.path.join(current_dir, 'frontend')
|
|
| 13 |
if frontend_dir not in sys.path:
|
| 14 |
sys.path.insert(0, frontend_dir)
|
| 15 |
|
| 16 |
-
# Import
|
| 17 |
-
import
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
|
|
|
|
|
|
| 13 |
if frontend_dir not in sys.path:
|
| 14 |
sys.path.insert(0, frontend_dir)
|
| 15 |
|
| 16 |
+
# Import only the main function to avoid loading unnecessary modules
|
| 17 |
+
from app import main
|
| 18 |
|
| 19 |
+
# Run the main function directly
|
| 20 |
+
if __name__ == "__main__":
|
| 21 |
+
main()
|