ash-coded-it commited on
Commit
1e3f942
Β·
verified Β·
1 Parent(s): 0cbdfc1

Upload folder using huggingface_hub

Browse files
Files changed (8) hide show
  1. .DS_Store +0 -0
  2. ENHANCED_README.md +208 -0
  3. README.md +101 -8
  4. __pycache__/app.cpython-313.pyc +0 -0
  5. app.py +310 -0
  6. config.yaml +163 -0
  7. enhanced_app.py +741 -0
  8. requirements.txt +9 -0
.DS_Store ADDED
Binary file (6.15 kB). View file
 
ENHANCED_README.md ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SOLAI Enhanced Dashboard
2
+
3
+ A comprehensive multi-tab dashboard for Texas residential solar lead scoring and analytics. This enhanced version builds upon the original Gradio dashboard with advanced analytics, lead management, and market intelligence capabilities.
4
+
5
+ ## 🌟 Features
6
+
7
+ ### πŸ“Š Overview Dashboard
8
+ - **Key Performance Metrics**: Total leads, qualified leads, sold leads, conversion rates
9
+ - **Geographic Distribution**: Lead distribution by TDSP (Texas utility territories)
10
+ - **Conversion Funnel**: Visual pipeline from leads to sales
11
+ - **Lead Score Distribution**: Histogram of probability_to_buy scores
12
+
13
+ ### πŸ‘₯ Lead Management
14
+ - **Advanced Search & Filtering**: Search by lead ID, TDSP, or sales status
15
+ - **Detailed Lead Profiles**: Comprehensive view of individual lead data
16
+ - **Demographics & Property Information**: Age, income, property details
17
+ - **Energy Usage & Solar Potential**: Monthly usage, bills, solar projections
18
+ - **Sales Status Tracking**: Win/loss reasons and current status
19
+
20
+ ### ⚑ Utility & Market Intelligence
21
+ - **TDSP Analysis**: Lead volume and conversion rates by utility territory
22
+ - **Rate Structure Impact**: How different rate structures affect conversions
23
+ - **Solar Potential Analysis**: Distribution of solar potential for sold vs not sold leads
24
+ - **Market Summary**: Top performing utility territories
25
+
26
+ ### πŸ€– Enhanced ML Training & Scoring
27
+ - **Improved Model Metrics**: ROC AUC, PR AUC, Brier Score, Precision, Recall, F1-Score
28
+ - **Feature Importance**: Clear breakdown of numeric vs categorical features
29
+ - **Confusion Matrix**: Detailed classification performance
30
+ - **Enhanced Output**: Better formatted results with comprehensive statistics
31
+
32
+ ### πŸ“š Data Dictionary
33
+ - **Interactive Field Browser**: Explore all 100+ fields in the SOLAI schema
34
+ - **Field Descriptions**: Detailed explanations from the data dictionary
35
+ - **PII Identification**: Clear marking of personally identifiable information
36
+ - **Grouped by Category**: Organized by logical field groups (demographics, property, utility, etc.)
37
+
38
+ ## πŸš€ Quick Start
39
+
40
+ ### Prerequisites
41
+ - Python 3.9+ recommended
42
+ - Virtual environment (recommended)
43
+
44
+ ### Installation
45
+
46
+ 1. **Set up virtual environment:**
47
+ ```bash
48
+ python -m venv .venv
49
+ source .venv/bin/activate # On Windows: .venv\Scripts\activate
50
+ ```
51
+
52
+ 2. **Install dependencies:**
53
+ ```bash
54
+ pip install -r dashboard_gradio/requirements.txt
55
+ ```
56
+
57
+ ### Running the Enhanced Dashboard
58
+
59
+ ```bash
60
+ python dashboard_gradio/enhanced_app.py
61
+ ```
62
+
63
+ The dashboard will launch at `http://127.0.0.1:7860` with the following tabs:
64
+ - πŸ“Š Overview Dashboard
65
+ - πŸ‘₯ Lead Management
66
+ - ⚑ Utility & Market Intelligence
67
+ - πŸ€– ML Training & Scoring
68
+ - πŸ“š Data Dictionary
69
+
70
+ ## πŸ“‹ Usage Guide
71
+
72
+ ### Overview Dashboard
73
+ 1. **Automatic Loading**: Key metrics load automatically when you open the tab
74
+ 2. **Refresh Data**: Click "πŸ”„ Refresh Dashboard" to update all charts and metrics
75
+ 3. **Interactive Charts**: Hover over charts for detailed information
76
+
77
+ ### Lead Management
78
+ 1. **Search Leads**:
79
+ - Enter search terms in the search box
80
+ - Filter by TDSP (utility territory)
81
+ - Filter by sales status (Sold/Not Sold)
82
+ - Click "πŸ” Search Leads" to apply filters
83
+
84
+ 2. **View Lead Details**:
85
+ - Enter a specific lead ID
86
+ - Click "πŸ“‹ Get Lead Details" for comprehensive lead profile
87
+ - View demographics, property info, energy usage, and sales status
88
+
89
+ ### Utility & Market Intelligence
90
+ 1. **Market Analysis**: View lead distribution and conversion rates by utility territory
91
+ 2. **Rate Structure Impact**: Understand how different rate structures affect sales
92
+ 3. **Solar Potential**: Compare solar potential between sold and unsold leads
93
+
94
+ ### ML Training & Scoring
95
+ 1. **Choose Data Source**:
96
+ - "Use example synthetic_v2" for demo data
97
+ - "Upload CSVs" to use your own data files
98
+
99
+ 2. **Train Model**: Click "πŸš€ Train + Score Model" to:
100
+ - Train logistic regression model
101
+ - Generate predictions for all leads
102
+ - Download results as CSV files
103
+
104
+ 3. **Review Results**:
105
+ - Enhanced metrics including precision, recall, F1-score
106
+ - Feature importance breakdown
107
+ - Preview of predictions and scored data
108
+
109
+ ### Data Dictionary
110
+ - **Browse Fields**: Explore all available fields in the SOLAI schema
111
+ - **Field Details**: View descriptions, data types, and PII status
112
+ - **Organized Groups**: Fields grouped by category for easy navigation
113
+
114
+ ## πŸ”§ Configuration
115
+
116
+ ### Data Sources
117
+ - **Default Dataset**: `examples/synthetic_v2/leads_features.csv` and `examples/synthetic_v2/outcomes.csv`
118
+ - **Output Directory**: `scores/` (automatically created)
119
+ - **Data Dictionary**: `data_dictionary.yaml`
120
+
121
+ ### Customization
122
+ - **Port**: Default 7860, automatically finds alternative if busy
123
+ - **Theme**: Uses Gradio Soft theme for better aesthetics
124
+ - **Charts**: Plotly-based interactive visualizations
125
+
126
+ ## πŸ“Š Data Requirements
127
+
128
+ ### Features CSV
129
+ Must contain `lead_id` and subset of these fields:
130
+ - **Demographics**: `age_bracket`, `household_income_bracket`, `credit_score_range`
131
+ - **Property**: `living_area_sqft`, `property_age_years`, `roof_material`
132
+ - **Energy**: `average_monthly_kwh`, `average_monthly_bill_usd`, `tdsp`
133
+ - **Solar**: `shading_factor`, `roof_suitability_score`, `solar_potential_kwh_year`
134
+
135
+ ### Outcomes CSV
136
+ Must contain:
137
+ - `lead_id`: Unique identifier matching features CSV
138
+ - `sold`: Boolean (0/1) indicating if lead converted to sale
139
+
140
+ ## πŸ› οΈ Technical Details
141
+
142
+ ### Architecture
143
+ - **Frontend**: Gradio with custom HTML/CSS styling
144
+ - **Backend**: Python with pandas, scikit-learn, plotly
145
+ - **ML Pipeline**: Logistic regression with preprocessing pipeline
146
+ - **Data Processing**: Pandas for data manipulation and analysis
147
+
148
+ ### Performance
149
+ - **Dataset Size**: Optimized for datasets up to 10,000+ leads
150
+ - **Response Time**: Sub-second for most operations
151
+ - **Memory Usage**: Efficient pandas operations with data caching
152
+
153
+ ### Security & Privacy
154
+ - **PII Handling**: Clear identification of personally identifiable information
155
+ - **Data Separation**: Follows SOLAI schema for PII/features separation
156
+ - **Local Processing**: All data processing happens locally
157
+
158
+ ## πŸ” Troubleshooting
159
+
160
+ ### Common Issues
161
+
162
+ 1. **"No data available"**:
163
+ - Ensure `examples/synthetic_v2/` directory exists with CSV files
164
+ - Check file permissions and paths
165
+
166
+ 2. **Charts not loading**:
167
+ - Verify plotly installation: `pip install plotly`
168
+ - Check browser JavaScript console for errors
169
+
170
+ 3. **Upload errors**:
171
+ - Ensure CSV files have required columns (`lead_id`, `sold`)
172
+ - Check file format and encoding (UTF-8 recommended)
173
+
174
+ 4. **Port conflicts**:
175
+ - Gradio will automatically find alternative port
176
+ - Check terminal output for actual URL
177
+
178
+ ### Performance Tips
179
+ - **Large Datasets**: Consider sampling for initial exploration
180
+ - **Memory Usage**: Close unused tabs to free memory
181
+ - **Browser Performance**: Use modern browsers (Chrome, Firefox, Safari)
182
+
183
+ ## πŸš€ Future Enhancements
184
+
185
+ ### Planned Features
186
+ - **Real-time Data**: Database connectivity for live data
187
+ - **Advanced ML**: Additional algorithms and ensemble methods
188
+ - **Export Options**: PDF reports and PowerPoint exports
189
+ - **User Authentication**: Multi-user support with role-based access
190
+ - **API Integration**: REST API for external system integration
191
+
192
+ ### Customization Options
193
+ - **Custom Themes**: Additional color schemes and layouts
194
+ - **Dashboard Builder**: Drag-and-drop dashboard customization
195
+ - **Alert System**: Automated alerts for key metrics
196
+ - **Scheduled Reports**: Automated report generation and distribution
197
+
198
+ ## πŸ“ž Support
199
+
200
+ For issues, questions, or feature requests:
201
+ 1. Check this README for common solutions
202
+ 2. Review the original `dashboard_gradio/README.md` for basic functionality
203
+ 3. Examine the data dictionary (`data_dictionary.yaml`) for field definitions
204
+ 4. Test with the provided synthetic data before using custom datasets
205
+
206
+ ## πŸ“„ License
207
+
208
+ This enhanced dashboard builds upon the original SOLAI project and maintains the same licensing terms.
README.md CHANGED
@@ -1,12 +1,105 @@
1
  ---
2
- title: Solar Culient Predictor
3
- emoji: 😻
4
- colorFrom: red
5
- colorTo: pink
6
  sdk: gradio
7
- sdk_version: 5.48.0
8
- app_file: app.py
9
- pinned: false
10
  ---
 
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Solar_Culient_Predictor
3
+ app_file: enhanced_app.py
 
 
4
  sdk: gradio
5
+ sdk_version: 4.26.0
 
 
6
  ---
7
+ # SOLAI Scoring Dashboard (Gradio)
8
 
9
+ A lightweight UI to train a baseline logistic regression on your solar leads dataset and generate `probability_to_buy` predictions. Uses the same feature candidates and preprocessing approach as `scripts/batch_scoring.py`.
10
+
11
+ - Default dataset: `examples/synthetic_v2`
12
+ - Outputs are always written to `/Users/git/solai/scores` and are also downloadable from the UI.
13
+
14
+ ## Features
15
+
16
+ - Choose data source:
17
+ - Use preset example data: `examples/synthetic_v2/leads_features.csv` and `examples/synthetic_v2/outcomes.csv`
18
+ - Upload your own CSVs (features and outcomes)
19
+ - Train + score with a single click
20
+ - Evaluation metrics (test split):
21
+ - ROC AUC, PR AUC, Brier score (gracefully handles degenerate label cases)
22
+ - Preview:
23
+ - `predictions.csv` (lead_id, probability_to_buy)
24
+ - `leads_features_scored.csv` (features merged with probability_to_buy)
25
+ - Download both files from the UI in addition to saving to disk (`/Users/git/solai/scores`)
26
+
27
+ ## Requirements
28
+
29
+ - Python 3.9+ recommended
30
+ - macOS (as per environment), should also work on Linux/Windows
31
+
32
+ Install dependencies (ideally in a virtual environment):
33
+
34
+ ```bash
35
+ python -m venv .venv
36
+ source .venv/bin/activate # On Windows: .venv\Scripts\activate
37
+ pip install -r dashboard_gradio/requirements.txt
38
+ ```
39
+
40
+ ## Run the App
41
+
42
+ ```bash
43
+ python dashboard_gradio/app.py
44
+ ```
45
+
46
+ Gradio will launch on a local URL (typically http://127.0.0.1:7860). Open it in your browser.
47
+
48
+ ## Usage
49
+
50
+ 1. Start the app.
51
+ 2. Select a data source:
52
+ - Default: β€œUse example synthetic_v2”
53
+ - Or switch to β€œUpload CSVs” and provide:
54
+ - Features CSV (must include `lead_id` and a subset of feature columns listed below)
55
+ - Outcomes CSV (must include `lead_id` and `sold` columns)
56
+ 3. Click β€œTrain + Score”.
57
+ 4. Review metrics and preview tables.
58
+ 5. Download the generated files or find them on disk under `/Users/git/solai/scores`.
59
+
60
+ ## Expected Columns
61
+
62
+ - Features CSV must contain `lead_id` and some subset of these candidate features:
63
+ - living_area_sqft
64
+ - average_monthly_kwh
65
+ - average_monthly_bill_usd
66
+ - shading_factor
67
+ - roof_suitability_score
68
+ - seasonality_index
69
+ - electric_panel_amperage
70
+ - has_pool
71
+ - is_remote_worker_household
72
+ - tdsp
73
+ - rate_structure
74
+ - credit_score_range
75
+ - household_income_bracket
76
+ - preferred_financing_type
77
+ - neighborhood_type
78
+
79
+ - Outcomes CSV must contain:
80
+ - `lead_id`
81
+ - `sold` (0/1)
82
+
83
+ ## Outputs
84
+
85
+ Saved to `/Users/git/solai/scores` with a timestamp suffix:
86
+
87
+ - `predictions_YYYYMMDD_HHMMSS.csv`
88
+ - Columns: `lead_id`, `probability_to_buy`
89
+ - `leads_features_scored_YYYYMMDD_HHMMSS.csv`
90
+ - Original features merged with `probability_to_buy`
91
+
92
+ Both files are also offered as downloads directly in the UI.
93
+
94
+ ## Notes and Troubleshooting
95
+
96
+ - If the outcomes data has only a single class (all sold=0 or all sold=1), ROC AUC and PR AUC are undefined; the app shows β€œN/A” for those metrics but still computes Brier score and produces predictions.
97
+ - If you see β€œNo candidate features found”, ensure your features CSV contains at least one of the listed feature names.
98
+ - If port 7860 is in use, Gradio will choose another port automatically, displayed in the terminal.
99
+ - For larger datasets, training time may increase but should remain quick for typical CSV sizes.
100
+
101
+ ## Development
102
+
103
+ - Core logic is in `dashboard_gradio/app.py`.
104
+ - The pipeline mirrors `scripts/batch_scoring.py`: ColumnTransformer with passthrough numeric features and OneHotEncoder for categoricals, then LogisticRegression.
105
+ - Extend easily with additional visualizations (e.g., calibration plots), feature importance, or a data dictionary viewer.
__pycache__/app.cpython-313.pyc ADDED
Binary file (12.7 kB). View file
 
app.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import os
3
+ from datetime import datetime
4
+ from pathlib import Path
5
+ from typing import Optional, Tuple, Union
6
+
7
+ import gradio as gr
8
+ import numpy as np
9
+ import pandas as pd
10
+ from sklearn.compose import ColumnTransformer
11
+ from sklearn.linear_model import LogisticRegression
12
+ from sklearn.metrics import (
13
+ average_precision_score,
14
+ brier_score_loss,
15
+ roc_auc_score,
16
+ )
17
+ from sklearn.model_selection import train_test_split
18
+ from sklearn.pipeline import Pipeline
19
+ from sklearn.preprocessing import OneHotEncoder
20
+
21
+
22
+ # Resolve repository root relative to this file
23
+ BASE_DIR = Path(__file__).resolve().parent.parent
24
+
25
+ # Output directory and preset dataset paths relative to repository root
26
+ SCORES_DIR = BASE_DIR / "scores"
27
+
28
+ # Preset example dataset paths
29
+ PRESET_FEATURES = BASE_DIR / "examples" / "synthetic_v2" / "leads_features.csv"
30
+ PRESET_OUTCOMES = BASE_DIR / "examples" / "synthetic_v2" / "outcomes.csv"
31
+
32
+ # Reuse same feature candidates and categorical sets as scripts/batch_scoring.py
33
+ FEATURE_CANDIDATES = [
34
+ "living_area_sqft",
35
+ "average_monthly_kwh",
36
+ "average_monthly_bill_usd",
37
+ "shading_factor",
38
+ "roof_suitability_score",
39
+ "seasonality_index",
40
+ "electric_panel_amperage",
41
+ "has_pool",
42
+ "is_remote_worker_household",
43
+ "tdsp",
44
+ "rate_structure",
45
+ "credit_score_range",
46
+ "household_income_bracket",
47
+ "preferred_financing_type",
48
+ "neighborhood_type",
49
+ ]
50
+
51
+ CATEGORICAL = [
52
+ "tdsp",
53
+ "rate_structure",
54
+ "credit_score_range",
55
+ "household_income_bracket",
56
+ "preferred_financing_type",
57
+ "neighborhood_type",
58
+ ]
59
+
60
+
61
+ def _safe_path(file_or_path: Optional[Union[str, gr.File]]) -> Optional[str]:
62
+ """
63
+ Convert a gradio File object or string path to a usable string path.
64
+ """
65
+ if file_or_path is None:
66
+ return None
67
+ if isinstance(file_or_path, str):
68
+ return file_or_path
69
+ # gradio File component returns a tempfile object-like with .name
70
+ if hasattr(file_or_path, "name"):
71
+ return file_or_path.name
72
+ # Some versions return a dict with 'name'
73
+ if isinstance(file_or_path, dict) and "name" in file_or_path:
74
+ return file_or_path["name"]
75
+ return None
76
+
77
+
78
+ def _validate_inputs(df_features: pd.DataFrame, df_outcomes: pd.DataFrame) -> None:
79
+ if "lead_id" not in df_features.columns:
80
+ raise ValueError("Features CSV must contain a 'lead_id' column.")
81
+ if "lead_id" not in df_outcomes.columns:
82
+ raise ValueError("Outcomes CSV must contain a 'lead_id' column.")
83
+ if "sold" not in df_outcomes.columns:
84
+ raise ValueError("Outcomes CSV must contain a 'sold' column (0/1).")
85
+
86
+
87
+ def _compute_metrics(y_true: np.ndarray, y_prob: np.ndarray) -> Tuple[Optional[float], Optional[float], Optional[float]]:
88
+ """
89
+ Compute ROC AUC, PR AUC, and Brier score with graceful fallbacks.
90
+ """
91
+ auc = None
92
+ pr_auc = None
93
+ brier = None
94
+
95
+ # Brier score is defined for binary labels even if only one class is present
96
+ try:
97
+ brier = float(brier_score_loss(y_true.astype(int), y_prob))
98
+ except Exception:
99
+ brier = None
100
+
101
+ # ROC AUC and PR AUC require both classes to be present in y_true
102
+ try:
103
+ if len(np.unique(y_true.astype(int))) >= 2:
104
+ auc = float(roc_auc_score(y_true.astype(int), y_prob))
105
+ else:
106
+ auc = None
107
+ except Exception:
108
+ auc = None
109
+
110
+ try:
111
+ if len(np.unique(y_true.astype(int))) >= 2:
112
+ pr_auc = float(average_precision_score(y_true.astype(int), y_prob))
113
+ else:
114
+ pr_auc = None
115
+ except Exception:
116
+ pr_auc = None
117
+
118
+ return auc, pr_auc, brier
119
+
120
+
121
+ def train_and_score(
122
+ mode: str,
123
+ features_file: Optional[Union[str, gr.File]],
124
+ outcomes_file: Optional[Union[str, gr.File]],
125
+ ):
126
+ """
127
+ mode: "Use example synthetic_v2" or "Upload CSVs"
128
+ Returns:
129
+ - metrics_markdown (str)
130
+ - preds_preview (pd.DataFrame)
131
+ - scored_preview (pd.DataFrame)
132
+ - predictions_file (str path)
133
+ - scored_file (str path)
134
+ """
135
+ try:
136
+ if mode == "Use example synthetic_v2":
137
+ features_path = PRESET_FEATURES
138
+ outcomes_path = PRESET_OUTCOMES
139
+ if not features_path.exists() or not outcomes_path.exists():
140
+ raise FileNotFoundError(
141
+ f"Preset files not found. Expected:\n- {PRESET_FEATURES}\n- {PRESET_OUTCOMES}"
142
+ )
143
+ else:
144
+ f_path = _safe_path(features_file)
145
+ o_path = _safe_path(outcomes_file)
146
+ if not f_path or not o_path:
147
+ raise ValueError("Please upload BOTH Features CSV and Outcomes CSV.")
148
+ features_path = Path(f_path)
149
+ outcomes_path = Path(o_path)
150
+ if not features_path.exists():
151
+ raise FileNotFoundError(f"Features file not found: {features_path}")
152
+ if not outcomes_path.exists():
153
+ raise FileNotFoundError(f"Outcomes file not found: {outcomes_path}")
154
+
155
+ X = pd.read_csv(features_path)
156
+ y_df = pd.read_csv(outcomes_path)[["lead_id", "sold"]]
157
+
158
+ _validate_inputs(X, y_df)
159
+
160
+ df = X.merge(y_df, on="lead_id", how="inner")
161
+
162
+ # Select features present in this dataset
163
+ available = [c for c in FEATURE_CANDIDATES if c in df.columns]
164
+ if not available:
165
+ raise ValueError(
166
+ "No candidate features found in features CSV. "
167
+ f"Expected any of: {', '.join(FEATURE_CANDIDATES)}"
168
+ )
169
+
170
+ numeric = [c for c in available if c not in CATEGORICAL]
171
+ cat_cols = [c for c in available if c in CATEGORICAL]
172
+
173
+ preproc = ColumnTransformer(
174
+ transformers=[
175
+ ("num", "passthrough", numeric),
176
+ ("cat", OneHotEncoder(handle_unknown="ignore"), cat_cols),
177
+ ],
178
+ remainder="drop",
179
+ )
180
+
181
+ model = LogisticRegression(max_iter=5000)
182
+ pipe = Pipeline(steps=[("pre", preproc), ("clf", model)])
183
+
184
+ y = df["sold"].astype(int)
185
+ # Only stratify if both classes present
186
+ if len(np.unique(y)) >= 2:
187
+ train_df, test_df = train_test_split(
188
+ df, test_size=0.25, random_state=42, stratify=y
189
+ )
190
+ else:
191
+ train_df, test_df = train_test_split(
192
+ df, test_size=0.25, random_state=42, stratify=None
193
+ )
194
+
195
+ pipe.fit(train_df[available], train_df["sold"].astype(int))
196
+
197
+ test_probs = pipe.predict_proba(test_df[available])[:, 1]
198
+ auc, pr_auc, brier = _compute_metrics(test_df["sold"].values, test_probs)
199
+
200
+ # Score all rows
201
+ all_probs = pipe.predict_proba(df[available])[:, 1]
202
+ preds = df[["lead_id"]].copy()
203
+ preds["probability_to_buy"] = np.round(all_probs, 4)
204
+
205
+ # Persist outputs
206
+ SCORES_DIR.mkdir(parents=True, exist_ok=True)
207
+ ts = datetime.now().strftime("%Y%m%d_%H%M%S")
208
+ predictions_path = SCORES_DIR / f"predictions_{ts}.csv"
209
+ scored_path = SCORES_DIR / f"leads_features_scored_{ts}.csv"
210
+
211
+ preds.to_csv(predictions_path, index=False)
212
+
213
+ scored = X.merge(preds, on="lead_id", how="left")
214
+ scored.to_csv(scored_path, index=False)
215
+
216
+ # Prepare outputs
217
+ def fmt(val: Optional[float]) -> str:
218
+ return f"{val:.3f}" if val is not None else "N/A"
219
+
220
+ metrics_md = (
221
+ "### Evaluation Metrics (test split)\n"
222
+ f"- ROC AUC: {fmt(auc)}\n"
223
+ f"- PR AUC: {fmt(pr_auc)}\n"
224
+ f"- Brier Score: {fmt(brier)}\n\n"
225
+ f"Outputs were saved to:\n"
226
+ f"- {predictions_path}\n"
227
+ f"- {scored_path}\n"
228
+ )
229
+
230
+ preds_preview = preds.head(20)
231
+ scored_preview = scored.head(20)
232
+
233
+ return (
234
+ metrics_md,
235
+ preds_preview,
236
+ scored_preview,
237
+ str(predictions_path),
238
+ str(scored_path),
239
+ )
240
+
241
+ except Exception as e:
242
+ # On error, return message and empty placeholders
243
+ metrics_md = f"### Error\n{str(e)}"
244
+ return metrics_md, pd.DataFrame(), pd.DataFrame(), None, None
245
+
246
+
247
+ with gr.Blocks(title="SOLAI Scoring Dashboard") as demo:
248
+ gr.Markdown(
249
+ """
250
+ # SOLAI Scoring Dashboard (Gradio)
251
+ Train a baseline Logistic Regression model on your solar lead dataset and generate probability_to_buy predictions.
252
+
253
+ - Default dataset: examples/synthetic_v2
254
+ - Outputs are always written to /Users/git/solai/scores and are also downloadable below.
255
+ """.strip()
256
+ )
257
+
258
+ with gr.Row():
259
+ mode = gr.Radio(
260
+ choices=["Use example synthetic_v2", "Upload CSVs"],
261
+ value="Use example synthetic_v2",
262
+ label="Data Source",
263
+ )
264
+
265
+ with gr.Row():
266
+ features_upload = gr.File(
267
+ label="Features CSV (for 'Upload CSVs' mode)",
268
+ file_types=[".csv"],
269
+ visible=False,
270
+ )
271
+ outcomes_upload = gr.File(
272
+ label="Outcomes CSV with columns [lead_id, sold] (for 'Upload CSVs' mode)",
273
+ file_types=[".csv"],
274
+ visible=False,
275
+ )
276
+
277
+ def toggle_uploads(selected_mode: str):
278
+ show = selected_mode == "Upload CSVs"
279
+ return [
280
+ gr.update(visible=show),
281
+ gr.update(visible=show),
282
+ ]
283
+
284
+ mode.change(
285
+ toggle_uploads,
286
+ inputs=[mode],
287
+ outputs=[features_upload, outcomes_upload],
288
+ )
289
+
290
+ with gr.Row():
291
+ run_btn = gr.Button("Train + Score", variant="primary")
292
+
293
+ with gr.Row():
294
+ metrics_md = gr.Markdown()
295
+ with gr.Row():
296
+ preds_df = gr.Dataframe(label="predictions.csv (preview)", interactive=False)
297
+ with gr.Row():
298
+ scored_df = gr.Dataframe(label="leads_features_scored.csv (preview)", interactive=False)
299
+ with gr.Row():
300
+ pred_file = gr.File(label="Download predictions.csv")
301
+ scored_file = gr.File(label="Download leads_features_scored.csv")
302
+
303
+ run_btn.click(
304
+ fn=train_and_score,
305
+ inputs=[mode, features_upload, outcomes_upload],
306
+ outputs=[metrics_md, preds_df, scored_df, pred_file, scored_file],
307
+ )
308
+
309
+ if __name__ == "__main__":
310
+ demo.launch()
config.yaml ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SOLAI Enhanced Dashboard Configuration
2
+
3
+ # Application Settings
4
+ app:
5
+ title: "SOLAI Enhanced Dashboard"
6
+ description: "Comprehensive Solar Lead Scoring & Analytics Platform"
7
+ theme: "soft" # gradio theme: default, soft, monochrome, etc.
8
+ port: 7860
9
+ host: "0.0.0.0"
10
+ share: false # set to true to create public shareable link
11
+
12
+ # Data Sources
13
+ data:
14
+ # Default dataset paths (relative to project root)
15
+ features_csv: "examples/synthetic_v2/leads_features.csv"
16
+ outcomes_csv: "examples/synthetic_v2/outcomes.csv"
17
+ data_dictionary: "data_dictionary.yaml"
18
+
19
+ # Output directory for model results
20
+ scores_dir: "scores"
21
+
22
+ # Maximum number of leads to display in search results
23
+ max_search_results: 100
24
+
25
+ # Dashboard Features
26
+ features:
27
+ # Enable/disable specific dashboard tabs
28
+ overview_dashboard: true
29
+ lead_management: true
30
+ utility_intelligence: true
31
+ ml_training: true
32
+ data_dictionary: true
33
+
34
+ # Chart settings
35
+ charts:
36
+ height: 400
37
+ color_scheme: "plotly" # plotly, viridis, plasma, etc.
38
+
39
+ # Lead search settings
40
+ search:
41
+ default_page_size: 20
42
+ enable_export: true
43
+
44
+ # Model Configuration
45
+ model:
46
+ # Feature candidates for ML training
47
+ feature_candidates:
48
+ - "living_area_sqft"
49
+ - "average_monthly_kwh"
50
+ - "average_monthly_bill_usd"
51
+ - "shading_factor"
52
+ - "roof_suitability_score"
53
+ - "seasonality_index"
54
+ - "electric_panel_amperage"
55
+ - "has_pool"
56
+ - "is_remote_worker_household"
57
+ - "tdsp"
58
+ - "rate_structure"
59
+ - "credit_score_range"
60
+ - "household_income_bracket"
61
+ - "preferred_financing_type"
62
+ - "neighborhood_type"
63
+
64
+ # Categorical features (for one-hot encoding)
65
+ categorical_features:
66
+ - "tdsp"
67
+ - "rate_structure"
68
+ - "credit_score_range"
69
+ - "household_income_bracket"
70
+ - "preferred_financing_type"
71
+ - "neighborhood_type"
72
+
73
+ # Model parameters
74
+ logistic_regression:
75
+ max_iter: 1000
76
+ random_state: 42
77
+
78
+ # Train/test split
79
+ test_size: 0.25
80
+ stratify: true
81
+
82
+ # UI Customization
83
+ ui:
84
+ # Color scheme
85
+ colors:
86
+ primary: "#2196F3"
87
+ success: "#4CAF50"
88
+ warning: "#FF9800"
89
+ danger: "#F44336"
90
+ info: "#00BCD4"
91
+
92
+ # Display options
93
+ display:
94
+ show_lead_count_in_title: true
95
+ show_last_updated: true
96
+ compact_mode: false
97
+
98
+ # Table settings
99
+ tables:
100
+ page_size: 20
101
+ show_index: false
102
+ wrap_text: true
103
+
104
+ # Texas-specific settings
105
+ texas:
106
+ # TDSP (Transmission and Distribution Service Provider) options
107
+ tdsp_options:
108
+ - "Oncor"
109
+ - "CenterPoint"
110
+ - "AEP_Texas"
111
+ - "TNMP"
112
+ - "Austin_Energy"
113
+ - "CPS_Energy"
114
+ - "Other_Muni"
115
+ - "Other_Coop"
116
+
117
+ # Rate structure types
118
+ rate_structures:
119
+ - "TOU" # Time of Use
120
+ - "flat"
121
+ - "tiered"
122
+ - "demand"
123
+ - "unknown"
124
+
125
+ # Analytics Settings
126
+ analytics:
127
+ # Metrics to display in overview
128
+ key_metrics:
129
+ - "total_leads"
130
+ - "qualified_leads"
131
+ - "sold_leads"
132
+ - "conversion_rate"
133
+ - "average_score"
134
+
135
+ # Chart types for different analyses
136
+ chart_types:
137
+ geographic: "bar" # bar, pie, map
138
+ funnel: "funnel" # funnel, bar
139
+ distribution: "histogram" # histogram, box, violin
140
+
141
+ # Security & Privacy
142
+ security:
143
+ # PII handling
144
+ mask_pii: false # set to true to mask PII in displays
145
+ pii_fields:
146
+ - "first_name"
147
+ - "last_name"
148
+ - "email"
149
+ - "phone_e164"
150
+ - "address_line1"
151
+ - "latitude"
152
+ - "longitude"
153
+
154
+ # Data export restrictions
155
+ export:
156
+ allow_pii_export: false
157
+ max_export_rows: 10000
158
+
159
+ # Logging
160
+ logging:
161
+ level: "INFO" # DEBUG, INFO, WARNING, ERROR
162
+ log_file: "dashboard.log"
163
+ log_format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
enhanced_app.py ADDED
@@ -0,0 +1,741 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import os
3
+ import json
4
+ import yaml
5
+ from datetime import datetime
6
+ from typing import Optional, Tuple, Union, Dict, List
7
+
8
+ import gradio as gr
9
+ import numpy as np
10
+ import pandas as pd
11
+ import plotly.express as px
12
+ import plotly.graph_objects as go
13
+ from plotly.subplots import make_subplots
14
+ from sklearn.compose import ColumnTransformer
15
+ from sklearn.linear_model import LogisticRegression
16
+ from sklearn.metrics import (
17
+ average_precision_score,
18
+ brier_score_loss,
19
+ roc_auc_score,
20
+ classification_report,
21
+ confusion_matrix,
22
+ )
23
+ from sklearn.model_selection import train_test_split
24
+ from sklearn.pipeline import Pipeline
25
+ from sklearn.preprocessing import OneHotEncoder
26
+
27
+
28
+ # Configuration
29
+ BASE_DIR = os.getcwd()
30
+ SCORES_DIR = "scores"
31
+ PRESET_FEATURES = os.path.join(BASE_DIR, "examples", "synthetic_v2", "leads_features.csv")
32
+ PRESET_OUTCOMES = os.path.join(BASE_DIR, "examples", "synthetic_v2", "outcomes.csv")
33
+ DATA_DICTIONARY_PATH = os.path.join(BASE_DIR, "data_dictionary.yaml")
34
+
35
+ # Feature candidates and categorical sets
36
+ FEATURE_CANDIDATES = [
37
+ "living_area_sqft",
38
+ "average_monthly_kwh",
39
+ "average_monthly_bill_usd",
40
+ "shading_factor",
41
+ "roof_suitability_score",
42
+ "seasonality_index",
43
+ "electric_panel_amperage",
44
+ "has_pool",
45
+ "is_remote_worker_household",
46
+ "tdsp",
47
+ "rate_structure",
48
+ "credit_score_range",
49
+ "household_income_bracket",
50
+ "preferred_financing_type",
51
+ "neighborhood_type",
52
+ ]
53
+
54
+ CATEGORICAL = [
55
+ "tdsp",
56
+ "rate_structure",
57
+ "credit_score_range",
58
+ "household_income_bracket",
59
+ "preferred_financing_type",
60
+ "neighborhood_type",
61
+ ]
62
+
63
+ # Load data dictionary
64
+ def load_data_dictionary():
65
+ """Load the data dictionary for field descriptions"""
66
+ try:
67
+ with open(DATA_DICTIONARY_PATH, 'r') as f:
68
+ return yaml.safe_load(f)
69
+ except:
70
+ return {}
71
+
72
+ DATA_DICT = load_data_dictionary()
73
+
74
+ def get_field_description(field_name: str) -> str:
75
+ """Get field description from data dictionary"""
76
+ for group in DATA_DICT.get('field_groups', []):
77
+ for field in group.get('fields', []):
78
+ if field.get('field_name') == field_name:
79
+ desc = field.get('description', '')
80
+ label = field.get('label', '')
81
+ return f"{label}: {desc}" if label and desc else (label or desc or field_name)
82
+ return field_name
83
+
84
+ def load_sample_data():
85
+ """Load sample data for dashboard"""
86
+ try:
87
+ features_df = pd.read_csv(PRESET_FEATURES)
88
+ outcomes_df = pd.read_csv(PRESET_OUTCOMES)
89
+ merged_df = features_df.merge(outcomes_df, on='lead_id', how='inner')
90
+ return merged_df
91
+ except Exception as e:
92
+ print(f"Error loading sample data: {e}")
93
+ return pd.DataFrame()
94
+
95
+ # Utility functions
96
+ def _safe_path(file_or_path: Optional[Union[str, gr.File]]) -> Optional[str]:
97
+ """Convert a gradio File object or string path to a usable string path."""
98
+ if file_or_path is None:
99
+ return None
100
+ if isinstance(file_or_path, str):
101
+ return file_or_path
102
+ if hasattr(file_or_path, "name"):
103
+ return file_or_path.name
104
+ if isinstance(file_or_path, dict) and "name" in file_or_path:
105
+ return file_or_path["name"]
106
+ return None
107
+
108
+ def _validate_inputs(df_features: pd.DataFrame, df_outcomes: pd.DataFrame) -> None:
109
+ if "lead_id" not in df_features.columns:
110
+ raise ValueError("Features CSV must contain a 'lead_id' column.")
111
+ if "lead_id" not in df_outcomes.columns:
112
+ raise ValueError("Outcomes CSV must contain a 'lead_id' column.")
113
+ if "sold" not in df_outcomes.columns:
114
+ raise ValueError("Outcomes CSV must contain a 'sold' column (0/1).")
115
+
116
+ def _compute_metrics(y_true: np.ndarray, y_prob: np.ndarray) -> Tuple[Optional[float], Optional[float], Optional[float]]:
117
+ """Compute ROC AUC, PR AUC, and Brier score with graceful fallbacks."""
118
+ auc = None
119
+ pr_auc = None
120
+ brier = None
121
+
122
+ try:
123
+ brier = float(brier_score_loss(y_true.astype(int), y_prob))
124
+ except Exception:
125
+ brier = None
126
+
127
+ try:
128
+ if len(np.unique(y_true.astype(int))) >= 2:
129
+ auc = float(roc_auc_score(y_true.astype(int), y_prob))
130
+ else:
131
+ auc = None
132
+ except Exception:
133
+ auc = None
134
+
135
+ try:
136
+ if len(np.unique(y_true.astype(int))) >= 2:
137
+ pr_auc = float(average_precision_score(y_true.astype(int), y_prob))
138
+ else:
139
+ pr_auc = None
140
+ except Exception:
141
+ pr_auc = None
142
+
143
+ return auc, pr_auc, brier
144
+
145
+ # Dashboard functions
146
+ def create_overview_dashboard():
147
+ """Create overview analytics dashboard"""
148
+ df = load_sample_data()
149
+ if df.empty:
150
+ return "No data available", None, None, None
151
+
152
+ # Key metrics
153
+ total_leads = len(df)
154
+ qualified_leads = df['qualified_opportunity'].sum() if 'qualified_opportunity' in df.columns else 0
155
+ sold_leads = df['sold'].sum() if 'sold' in df.columns else 0
156
+ conversion_rate = (sold_leads / total_leads * 100) if total_leads > 0 else 0
157
+
158
+ metrics_html = f"""
159
+ <div style="display: flex; justify-content: space-around; margin: 20px 0;">
160
+ <div style="text-align: center; padding: 20px; border: 1px solid #ddd; border-radius: 8px;">
161
+ <h3 style="margin: 0; color: #2196F3;">{total_leads}</h3>
162
+ <p style="margin: 5px 0;">Total Leads</p>
163
+ </div>
164
+ <div style="text-align: center; padding: 20px; border: 1px solid #ddd; border-radius: 8px;">
165
+ <h3 style="margin: 0; color: #4CAF50;">{qualified_leads}</h3>
166
+ <p style="margin: 5px 0;">Qualified Leads</p>
167
+ </div>
168
+ <div style="text-align: center; padding: 20px; border: 1px solid #ddd; border-radius: 8px;">
169
+ <h3 style="margin: 0; color: #FF9800;">{sold_leads}</h3>
170
+ <p style="margin: 5px 0;">Sold Leads</p>
171
+ </div>
172
+ <div style="text-align: center; padding: 20px; border: 1px solid #ddd; border-radius: 8px;">
173
+ <h3 style="margin: 0; color: #9C27B0;">{conversion_rate:.1f}%</h3>
174
+ <p style="margin: 5px 0;">Conversion Rate</p>
175
+ </div>
176
+ </div>
177
+ """
178
+
179
+ # Geographic distribution
180
+ geo_fig = None
181
+ if 'tdsp' in df.columns:
182
+ tdsp_counts = df['tdsp'].value_counts()
183
+ geo_fig = px.bar(
184
+ x=tdsp_counts.index,
185
+ y=tdsp_counts.values,
186
+ title="Lead Distribution by TDSP (Texas Utility Territory)",
187
+ labels={'x': 'TDSP', 'y': 'Number of Leads'}
188
+ )
189
+ geo_fig.update_layout(height=400)
190
+
191
+ # Conversion funnel
192
+ funnel_fig = None
193
+ if 'qualified_opportunity' in df.columns and 'sold' in df.columns:
194
+ funnel_data = {
195
+ 'Stage': ['Total Leads', 'Qualified', 'Sold'],
196
+ 'Count': [total_leads, qualified_leads, sold_leads]
197
+ }
198
+ funnel_fig = px.funnel(
199
+ funnel_data,
200
+ x='Count',
201
+ y='Stage',
202
+ title="Lead Conversion Funnel"
203
+ )
204
+ funnel_fig.update_layout(height=400)
205
+
206
+ # Lead scoring distribution
207
+ score_fig = None
208
+ if 'probability_to_buy' in df.columns:
209
+ score_fig = px.histogram(
210
+ df,
211
+ x='probability_to_buy',
212
+ title="Distribution of Lead Scores (Probability to Buy)",
213
+ nbins=20
214
+ )
215
+ score_fig.update_layout(height=400)
216
+
217
+ return metrics_html, geo_fig, funnel_fig, score_fig
218
+
219
+ def search_leads(search_term: str, filter_tdsp: str, filter_sold: str):
220
+ """Search and filter leads"""
221
+ df = load_sample_data()
222
+ if df.empty:
223
+ return pd.DataFrame()
224
+
225
+ # Apply filters
226
+ filtered_df = df.copy()
227
+
228
+ if search_term:
229
+ # Search in lead_id and other text fields
230
+ mask = df['lead_id'].str.contains(search_term, case=False, na=False)
231
+ if 'tdsp' in df.columns:
232
+ mask |= df['tdsp'].str.contains(search_term, case=False, na=False)
233
+ filtered_df = df[mask]
234
+
235
+ if filter_tdsp and filter_tdsp != "All":
236
+ filtered_df = filtered_df[filtered_df['tdsp'] == filter_tdsp]
237
+
238
+ if filter_sold and filter_sold != "All":
239
+ sold_value = True if filter_sold == "Sold" else False
240
+ filtered_df = filtered_df[filtered_df['sold'] == sold_value]
241
+
242
+ # Select key columns for display
243
+ display_cols = ['lead_id', 'tdsp', 'household_income_bracket', 'credit_score_range',
244
+ 'living_area_sqft', 'average_monthly_kwh', 'probability_to_buy', 'sold']
245
+ display_cols = [col for col in display_cols if col in filtered_df.columns]
246
+
247
+ return filtered_df[display_cols].head(100)
248
+
249
+ def get_lead_details(lead_id: str):
250
+ """Get detailed information for a specific lead"""
251
+ df = load_sample_data()
252
+ if df.empty or not lead_id:
253
+ return "No data available"
254
+
255
+ lead_data = df[df['lead_id'] == lead_id]
256
+ if lead_data.empty:
257
+ return f"Lead {lead_id} not found"
258
+
259
+ lead = lead_data.iloc[0]
260
+
261
+ # Create detailed lead profile
262
+ details_html = f"""
263
+ <div style="padding: 20px; border: 1px solid #ddd; border-radius: 8px; margin: 10px 0;">
264
+ <h3>Lead Profile: {lead_id}</h3>
265
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
266
+ <div>
267
+ <h4>Demographics</h4>
268
+ <p><strong>Age Bracket:</strong> {lead.get('age_bracket', 'N/A')}</p>
269
+ <p><strong>Income:</strong> {lead.get('household_income_bracket', 'N/A')}</p>
270
+ <p><strong>Credit Score:</strong> {lead.get('credit_score_range', 'N/A')}</p>
271
+ <p><strong>Adults/Children:</strong> {lead.get('adults_count', 'N/A')}/{lead.get('children_count', 'N/A')}</p>
272
+ </div>
273
+ <div>
274
+ <h4>Property</h4>
275
+ <p><strong>Living Area:</strong> {lead.get('living_area_sqft', 'N/A')} sqft</p>
276
+ <p><strong>Property Age:</strong> {lead.get('property_age_years', 'N/A')} years</p>
277
+ <p><strong>Roof Material:</strong> {lead.get('roof_material', 'N/A')}</p>
278
+ <p><strong>Shading Factor:</strong> {lead.get('shading_factor', 'N/A')}</p>
279
+ </div>
280
+ </div>
281
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 20px;">
282
+ <div>
283
+ <h4>Energy Usage</h4>
284
+ <p><strong>Monthly kWh:</strong> {lead.get('average_monthly_kwh', 'N/A')}</p>
285
+ <p><strong>Monthly Bill:</strong> ${lead.get('average_monthly_bill_usd', 'N/A')}</p>
286
+ <p><strong>TDSP:</strong> {lead.get('tdsp', 'N/A')}</p>
287
+ <p><strong>Rate Structure:</strong> {lead.get('rate_structure', 'N/A')}</p>
288
+ </div>
289
+ <div>
290
+ <h4>Solar Potential</h4>
291
+ <p><strong>Solar Potential:</strong> {lead.get('solar_potential_kwh_year', 'N/A')} kWh/year</p>
292
+ <p><strong>Expected Savings:</strong> ${lead.get('expected_savings_usd_year', 'N/A')}/year</p>
293
+ <p><strong>Payback Period:</strong> {lead.get('payback_years', 'N/A')} years</p>
294
+ <p><strong>Probability to Buy:</strong> {lead.get('probability_to_buy', 'N/A')}</p>
295
+ </div>
296
+ </div>
297
+ <div style="margin-top: 20px; padding: 15px; background-color: {'#e8f5e8' if lead.get('sold') else '#fff3cd'}; border-radius: 5px;">
298
+ <h4>Status: {'SOLD' if lead.get('sold') else 'NOT SOLD'}</h4>
299
+ {f"<p><strong>Win Reason:</strong> {lead.get('win_reason', 'N/A')}</p>" if lead.get('sold') else ''}
300
+ {f"<p><strong>Cancel Reason:</strong> {lead.get('cancel_reason', 'N/A')}</p>" if lead.get('cancellation') else ''}
301
+ </div>
302
+ </div>
303
+ """
304
+
305
+ return details_html
306
+
307
+ def create_utility_analysis():
308
+ """Create utility and market intelligence dashboard"""
309
+ df = load_sample_data()
310
+ if df.empty:
311
+ return "No data available", None, None, None
312
+
313
+ # TDSP analysis
314
+ tdsp_fig = None
315
+ if 'tdsp' in df.columns and 'sold' in df.columns:
316
+ tdsp_analysis = df.groupby('tdsp').agg({
317
+ 'lead_id': 'count',
318
+ 'sold': ['sum', 'mean']
319
+ }).round(3)
320
+ tdsp_analysis.columns = ['Total_Leads', 'Sold_Leads', 'Conversion_Rate']
321
+ tdsp_analysis = tdsp_analysis.reset_index()
322
+
323
+ tdsp_fig = px.bar(
324
+ tdsp_analysis,
325
+ x='tdsp',
326
+ y=['Total_Leads', 'Sold_Leads'],
327
+ title="Lead Volume and Sales by TDSP",
328
+ barmode='group'
329
+ )
330
+ tdsp_fig.update_layout(height=400)
331
+
332
+ # Rate structure analysis
333
+ rate_fig = None
334
+ if 'rate_structure' in df.columns and 'sold' in df.columns:
335
+ rate_analysis = df.groupby('rate_structure').agg({
336
+ 'sold': 'mean',
337
+ 'lead_id': 'count'
338
+ }).round(3)
339
+ rate_analysis.columns = ['Conversion_Rate', 'Lead_Count']
340
+ rate_analysis = rate_analysis.reset_index()
341
+
342
+ rate_fig = px.scatter(
343
+ rate_analysis,
344
+ x='Lead_Count',
345
+ y='Conversion_Rate',
346
+ size='Lead_Count',
347
+ color='rate_structure',
348
+ title="Conversion Rate by Rate Structure",
349
+ hover_data=['rate_structure']
350
+ )
351
+ rate_fig.update_layout(height=400)
352
+
353
+ # Solar potential vs actual sales
354
+ solar_fig = None
355
+ if 'solar_potential_kwh_year' in df.columns and 'sold' in df.columns:
356
+ solar_fig = px.box(
357
+ df,
358
+ x='sold',
359
+ y='solar_potential_kwh_year',
360
+ title="Solar Potential Distribution: Sold vs Not Sold",
361
+ labels={'sold': 'Sold Status', 'solar_potential_kwh_year': 'Solar Potential (kWh/year)'}
362
+ )
363
+ solar_fig.update_layout(height=400)
364
+
365
+ # Summary statistics
366
+ summary_html = ""
367
+ if 'tdsp' in df.columns:
368
+ tdsp_stats = df['tdsp'].value_counts()
369
+ summary_html = f"""
370
+ <div style="padding: 20px;">
371
+ <h3>Texas Utility Market Summary</h3>
372
+ <p><strong>Top TDSP by Lead Volume:</strong></p>
373
+ <ul>
374
+ {''.join([f'<li>{tdsp}: {count} leads</li>' for tdsp, count in tdsp_stats.head(5).items()])}
375
+ </ul>
376
+ </div>
377
+ """
378
+
379
+ return summary_html, tdsp_fig, rate_fig, solar_fig
380
+
381
+ def train_and_score(
382
+ mode: str,
383
+ features_file: Optional[Union[str, gr.File]],
384
+ outcomes_file: Optional[Union[str, gr.File]],
385
+ ):
386
+ """Enhanced train and score function with additional metrics"""
387
+ try:
388
+ if mode == "Use example synthetic_v2":
389
+ features_path = PRESET_FEATURES
390
+ outcomes_path = PRESET_OUTCOMES
391
+ if not os.path.exists(features_path) or not os.path.exists(outcomes_path):
392
+ raise FileNotFoundError(
393
+ f"Preset files not found. Expected:\n- {PRESET_FEATURES}\n- {PRESET_OUTCOMES}"
394
+ )
395
+ else:
396
+ f_path = _safe_path(features_file)
397
+ o_path = _safe_path(outcomes_file)
398
+ if not f_path or not o_path:
399
+ raise ValueError("Please upload BOTH Features CSV and Outcomes CSV.")
400
+ features_path = f_path
401
+ outcomes_path = o_path
402
+ if not os.path.exists(features_path):
403
+ raise FileNotFoundError(f"Features file not found: {features_path}")
404
+ if not os.path.exists(outcomes_path):
405
+ raise FileNotFoundError(f"Outcomes file not found: {outcomes_path}")
406
+
407
+ X = pd.read_csv(features_path)
408
+ y_df = pd.read_csv(outcomes_path)[["lead_id", "sold"]]
409
+
410
+ _validate_inputs(X, y_df)
411
+
412
+ df = X.merge(y_df, on="lead_id", how="inner")
413
+
414
+ # Select features present in this dataset
415
+ available = [c for c in FEATURE_CANDIDATES if c in df.columns]
416
+ if not available:
417
+ raise ValueError(
418
+ "No candidate features found in features CSV. "
419
+ f"Expected any of: {', '.join(FEATURE_CANDIDATES)}"
420
+ )
421
+
422
+ numeric = [c for c in available if c not in CATEGORICAL]
423
+ cat_cols = [c for c in available if c in CATEGORICAL]
424
+
425
+ preproc = ColumnTransformer(
426
+ transformers=[
427
+ ("num", "passthrough", numeric),
428
+ ("cat", OneHotEncoder(handle_unknown="ignore"), cat_cols),
429
+ ],
430
+ remainder="drop",
431
+ )
432
+
433
+ model = LogisticRegression(max_iter=1000)
434
+ pipe = Pipeline(steps=[("pre", preproc), ("clf", model)])
435
+
436
+ y = df["sold"].astype(int)
437
+ # Only stratify if both classes present
438
+ if len(np.unique(y)) >= 2:
439
+ train_df, test_df = train_test_split(
440
+ df, test_size=0.25, random_state=42, stratify=y
441
+ )
442
+ else:
443
+ train_df, test_df = train_test_split(
444
+ df, test_size=0.25, random_state=42, stratify=None
445
+ )
446
+
447
+ pipe.fit(train_df[available], train_df["sold"].astype(int))
448
+
449
+ test_probs = pipe.predict_proba(test_df[available])[:, 1]
450
+ test_preds = pipe.predict(test_df[available])
451
+ auc, pr_auc, brier = _compute_metrics(test_df["sold"].values, test_probs)
452
+
453
+ # Score all rows
454
+ all_probs = pipe.predict_proba(df[available])[:, 1]
455
+ preds = df[["lead_id"]].copy()
456
+ preds["probability_to_buy"] = np.round(all_probs, 4)
457
+
458
+ # Persist outputs
459
+ os.makedirs(SCORES_DIR, exist_ok=True)
460
+ ts = datetime.now().strftime("%Y%m%d_%H%M%S")
461
+ predictions_path = os.path.join(SCORES_DIR, f"predictions_{ts}.csv")
462
+ scored_path = os.path.join(SCORES_DIR, f"leads_features_scored_{ts}.csv")
463
+
464
+ preds.to_csv(predictions_path, index=False)
465
+
466
+ scored = X.merge(preds, on="lead_id", how="left")
467
+ scored.to_csv(scored_path, index=False)
468
+
469
+ # Enhanced metrics
470
+ def fmt(val: Optional[float]) -> str:
471
+ return f"{val:.3f}" if val is not None else "N/A"
472
+
473
+ # Confusion matrix
474
+ cm = confusion_matrix(test_df["sold"].values, test_preds) if len(np.unique(y)) >= 2 else None
475
+
476
+ # Classification report
477
+ class_report = classification_report(test_df["sold"].values, test_preds, output_dict=True) if len(np.unique(y)) >= 2 else None
478
+
479
+ metrics_md = (
480
+ "### Enhanced Model Evaluation Metrics\n"
481
+ f"**Dataset:** {len(df)} leads, {len(available)} features\n"
482
+ f"**Train/Test Split:** {len(train_df)}/{len(test_df)} leads\n\n"
483
+ "#### Performance Metrics\n"
484
+ f"- **ROC AUC:** {fmt(auc)}\n"
485
+ f"- **PR AUC:** {fmt(pr_auc)}\n"
486
+ f"- **Brier Score:** {fmt(brier)}\n"
487
+ )
488
+
489
+ if class_report:
490
+ metrics_md += (
491
+ f"- **Precision (Sold):** {fmt(class_report['1']['precision'])}\n"
492
+ f"- **Recall (Sold):** {fmt(class_report['1']['recall'])}\n"
493
+ f"- **F1-Score (Sold):** {fmt(class_report['1']['f1-score'])}\n"
494
+ )
495
+
496
+ metrics_md += (
497
+ f"\n#### Feature Importance\n"
498
+ f"**Numeric Features:** {', '.join(numeric)}\n"
499
+ f"**Categorical Features:** {', '.join(cat_cols)}\n\n"
500
+ f"#### Output Files\n"
501
+ f"- `{predictions_path}`\n"
502
+ f"- `{scored_path}`\n"
503
+ )
504
+
505
+ preds_preview = preds.head(20)
506
+ scored_preview = scored.head(20)
507
+
508
+ return metrics_md, preds_preview, scored_preview, predictions_path, scored_path
509
+
510
+ except Exception as e:
511
+ metrics_md = f"### Error\n{str(e)}"
512
+ return metrics_md, pd.DataFrame(), pd.DataFrame(), None, None
513
+
514
+ # Create the enhanced Gradio interface
515
+ def create_enhanced_dashboard():
516
+ with gr.Blocks(title="SOLAI Enhanced Dashboard", theme=gr.themes.Soft()) as demo:
517
+ gr.Markdown(
518
+ """
519
+ # 🌞 SOLAI Enhanced Dashboard
520
+ ### Comprehensive Solar Lead Scoring & Analytics Platform
521
+
522
+ This enhanced dashboard provides comprehensive analytics, lead management, and ML capabilities for Texas residential solar lead scoring.
523
+ """
524
+ )
525
+
526
+ with gr.Tabs():
527
+ # Tab 1: Overview Dashboard
528
+ with gr.Tab("πŸ“Š Overview Dashboard"):
529
+ gr.Markdown("## Key Performance Metrics & Analytics")
530
+
531
+ refresh_btn = gr.Button("πŸ”„ Refresh Dashboard", variant="secondary")
532
+
533
+ with gr.Row():
534
+ metrics_display = gr.HTML()
535
+
536
+ with gr.Row():
537
+ with gr.Column():
538
+ geo_chart = gr.Plot(label="Geographic Distribution")
539
+ with gr.Column():
540
+ funnel_chart = gr.Plot(label="Conversion Funnel")
541
+
542
+ with gr.Row():
543
+ score_dist_chart = gr.Plot(label="Lead Score Distribution")
544
+
545
+ def refresh_overview():
546
+ return create_overview_dashboard()
547
+
548
+ refresh_btn.click(
549
+ refresh_overview,
550
+ outputs=[metrics_display, geo_chart, funnel_chart, score_dist_chart]
551
+ )
552
+
553
+ # Load initial data
554
+ demo.load(
555
+ refresh_overview,
556
+ outputs=[metrics_display, geo_chart, funnel_chart, score_dist_chart]
557
+ )
558
+
559
+ # Tab 2: Lead Management
560
+ with gr.Tab("πŸ‘₯ Lead Management"):
561
+ gr.Markdown("## Search, Filter & Manage Leads")
562
+
563
+ with gr.Row():
564
+ search_input = gr.Textbox(label="Search Leads", placeholder="Enter lead ID or search term...")
565
+ tdsp_filter = gr.Dropdown(
566
+ choices=["All", "Oncor", "CenterPoint", "AEP_Texas", "TNMP", "Austin_Energy", "CPS_Energy", "Other_Muni"],
567
+ value="All",
568
+ label="Filter by TDSP"
569
+ )
570
+ sold_filter = gr.Dropdown(
571
+ choices=["All", "Sold", "Not Sold"],
572
+ value="All",
573
+ label="Filter by Status"
574
+ )
575
+
576
+ search_btn = gr.Button("πŸ” Search Leads", variant="primary")
577
+
578
+ with gr.Row():
579
+ leads_table = gr.Dataframe(
580
+ label="Lead Search Results",
581
+ interactive=False,
582
+ wrap=True
583
+ )
584
+
585
+ gr.Markdown("## Lead Details")
586
+ with gr.Row():
587
+ lead_id_input = gr.Textbox(label="Lead ID", placeholder="Enter lead ID for detailed view...")
588
+ get_details_btn = gr.Button("πŸ“‹ Get Lead Details", variant="secondary")
589
+
590
+ lead_details_display = gr.HTML()
591
+
592
+ search_btn.click(
593
+ search_leads,
594
+ inputs=[search_input, tdsp_filter, sold_filter],
595
+ outputs=[leads_table]
596
+ )
597
+
598
+ get_details_btn.click(
599
+ get_lead_details,
600
+ inputs=[lead_id_input],
601
+ outputs=[lead_details_display]
602
+ )
603
+
604
+ # Tab 3: Utility & Market Intelligence
605
+ with gr.Tab("⚑ Utility & Market Intelligence"):
606
+ gr.Markdown("## Texas Utility Territory & Market Analysis")
607
+
608
+ refresh_utility_btn = gr.Button("πŸ”„ Refresh Analysis", variant="secondary")
609
+
610
+ with gr.Row():
611
+ utility_summary = gr.HTML()
612
+
613
+ with gr.Row():
614
+ with gr.Column():
615
+ tdsp_analysis_chart = gr.Plot(label="TDSP Analysis")
616
+ with gr.Column():
617
+ rate_structure_chart = gr.Plot(label="Rate Structure Impact")
618
+
619
+ with gr.Row():
620
+ solar_potential_chart = gr.Plot(label="Solar Potential Analysis")
621
+
622
+ def refresh_utility():
623
+ return create_utility_analysis()
624
+
625
+ refresh_utility_btn.click(
626
+ refresh_utility,
627
+ outputs=[utility_summary, tdsp_analysis_chart, rate_structure_chart, solar_potential_chart]
628
+ )
629
+
630
+ # Load initial data
631
+ demo.load(
632
+ refresh_utility,
633
+ outputs=[utility_summary, tdsp_analysis_chart, rate_structure_chart, solar_potential_chart]
634
+ )
635
+
636
+ # Tab 4: Enhanced ML Training & Scoring
637
+ with gr.Tab("πŸ€– ML Training & Scoring"):
638
+ gr.Markdown("## Enhanced Machine Learning Pipeline")
639
+
640
+ with gr.Row():
641
+ mode = gr.Radio(
642
+ choices=["Use example synthetic_v2", "Upload CSVs"],
643
+ value="Use example synthetic_v2",
644
+ label="Data Source",
645
+ )
646
+
647
+ with gr.Row():
648
+ features_upload = gr.File(
649
+ label="Features CSV (for 'Upload CSVs' mode)",
650
+ file_types=[".csv"],
651
+ visible=False,
652
+ )
653
+ outcomes_upload = gr.File(
654
+ label="Outcomes CSV with columns [lead_id, sold] (for 'Upload CSVs' mode)",
655
+ file_types=[".csv"],
656
+ visible=False,
657
+ )
658
+
659
+ def toggle_uploads(selected_mode: str):
660
+ show = selected_mode == "Upload CSVs"
661
+ return [
662
+ gr.update(visible=show),
663
+ gr.update(visible=show),
664
+ ]
665
+
666
+ mode.change(
667
+ toggle_uploads,
668
+ inputs=[mode],
669
+ outputs=[features_upload, outcomes_upload],
670
+ )
671
+
672
+ with gr.Row():
673
+ run_btn = gr.Button("πŸš€ Train + Score Model", variant="primary", size="lg")
674
+
675
+ with gr.Row():
676
+ metrics_md = gr.Markdown()
677
+
678
+ with gr.Row():
679
+ with gr.Column():
680
+ preds_df = gr.Dataframe(label="Predictions Preview", interactive=False)
681
+ with gr.Column():
682
+ scored_df = gr.Dataframe(label="Scored Features Preview", interactive=False)
683
+
684
+ with gr.Row():
685
+ pred_file = gr.File(label="πŸ“₯ Download Predictions CSV")
686
+ scored_file = gr.File(label="πŸ“₯ Download Scored Features CSV")
687
+
688
+ run_btn.click(
689
+ fn=train_and_score,
690
+ inputs=[mode, features_upload, outcomes_upload],
691
+ outputs=[metrics_md, preds_df, scored_df, pred_file, scored_file],
692
+ )
693
+
694
+ # Tab 5: Data Dictionary
695
+ with gr.Tab("πŸ“š Data Dictionary"):
696
+ gr.Markdown("## SOLAI Data Dictionary & Field Descriptions")
697
+
698
+ # Create data dictionary display
699
+ dict_html = """
700
+ <div style="padding: 20px;">
701
+ <h3>Field Groups & Descriptions</h3>
702
+ """
703
+
704
+ for group in DATA_DICT.get('field_groups', []):
705
+ dict_html += f"""
706
+ <div style="margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 8px;">
707
+ <h4 style="color: #2196F3;">{group.get('name', 'Unknown Group')}</h4>
708
+ <p style="color: #666; margin-bottom: 15px;">{group.get('description', '')}</p>
709
+ <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 10px;">
710
+ """
711
+
712
+ for field in group.get('fields', []):
713
+ field_name = field.get('field_name', '')
714
+ label = field.get('label', field_name)
715
+ description = field.get('description', '')
716
+ data_type = field.get('data_type', '')
717
+ is_pii = field.get('is_pii', False)
718
+
719
+ pii_badge = '<span style="background: #ff4444; color: white; padding: 2px 6px; border-radius: 3px; font-size: 10px;">PII</span>' if is_pii else ''
720
+
721
+ dict_html += f"""
722
+ <div style="padding: 10px; background: #f9f9f9; border-radius: 5px;">
723
+ <strong>{label}</strong> {pii_badge}<br>
724
+ <code style="background: #e0e0e0; padding: 2px 4px; border-radius: 3px;">{field_name}</code>
725
+ <span style="color: #666;">({data_type})</span><br>
726
+ <small style="color: #666;">{description}</small>
727
+ </div>
728
+ """
729
+
730
+ dict_html += "</div></div>"
731
+
732
+ dict_html += "</div>"
733
+
734
+ gr.HTML(dict_html)
735
+
736
+ return demo
737
+
738
+ if __name__ == "__main__":
739
+ demo = create_enhanced_dashboard()
740
+ port = int(os.environ.get('GRADIO_SERVER_PORT', 7861))
741
+ demo.launch(server_name="0.0.0.0", server_port=port, share=True)
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ pandas
3
+ numpy
4
+ scikit-learn
5
+ plotly
6
+ pyyaml
7
+ scipy
8
+ joblib
9
+ threadpoolctl