Upload 3 files
Browse files- README.md +27 -20
- app.py +545 -0
- requirements.txt +4 -3
README.md
CHANGED
|
@@ -1,20 +1,27 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: Correlation Network
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo: red
|
| 6 |
-
sdk:
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: DECODE Correlation Network Generator
|
| 3 |
+
emoji: π
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: red
|
| 6 |
+
sdk: streamlit
|
| 7 |
+
sdk_version: 1.28.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# DECODE Correlation Network Generator
|
| 13 |
+
|
| 14 |
+
Generate interactive HTML network visualizations from correlation matrices.
|
| 15 |
+
|
| 16 |
+
## Features
|
| 17 |
+
- Upload Excel correlation files
|
| 18 |
+
- Auto-detects data parameters (start row, threshold, column start)
|
| 19 |
+
- Generates interactive vis.js network visualization
|
| 20 |
+
- Download HTML file for offline viewing
|
| 21 |
+
|
| 22 |
+
## Usage
|
| 23 |
+
1. Upload your Excel correlation file
|
| 24 |
+
2. Select the worksheet name
|
| 25 |
+
3. Review/adjust auto-detected parameters
|
| 26 |
+
4. Enter project details (Client, Country, Brand, Category)
|
| 27 |
+
5. Click Generate and download the HTML file
|
app.py
ADDED
|
@@ -0,0 +1,545 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import textwrap
|
| 5 |
+
import json
|
| 6 |
+
import io
|
| 7 |
+
|
| 8 |
+
# =============================================================================
|
| 9 |
+
# PAGE CONFIG
|
| 10 |
+
# =============================================================================
|
| 11 |
+
st.set_page_config(
|
| 12 |
+
page_title="DECODE Correlation Network Generator",
|
| 13 |
+
page_icon="π",
|
| 14 |
+
layout="wide"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
# =============================================================================
|
| 18 |
+
# HELPER FUNCTIONS
|
| 19 |
+
# =============================================================================
|
| 20 |
+
|
| 21 |
+
NONREWARDS_FACTORS = ['Features', 'FunctionalGoals', 'Occasions']
|
| 22 |
+
|
| 23 |
+
def detect_data_start_row(df):
|
| 24 |
+
"""Find DATA_START_ROW by detecting the 2nd text block in column B."""
|
| 25 |
+
in_block = False
|
| 26 |
+
block_start = None
|
| 27 |
+
blocks = []
|
| 28 |
+
|
| 29 |
+
for row_idx in range(df.shape[0]):
|
| 30 |
+
val = df.iloc[row_idx, 1]
|
| 31 |
+
has_text = pd.notna(val) and isinstance(val, str) and len(str(val).strip()) > 0
|
| 32 |
+
|
| 33 |
+
if has_text and not in_block:
|
| 34 |
+
in_block = True
|
| 35 |
+
block_start = row_idx + 1
|
| 36 |
+
elif not has_text and in_block:
|
| 37 |
+
in_block = False
|
| 38 |
+
blocks.append((block_start, row_idx))
|
| 39 |
+
block_start = None
|
| 40 |
+
|
| 41 |
+
if in_block:
|
| 42 |
+
blocks.append((block_start, df.shape[0]))
|
| 43 |
+
|
| 44 |
+
if len(blocks) >= 2:
|
| 45 |
+
return blocks[1][0], blocks
|
| 46 |
+
elif blocks:
|
| 47 |
+
return blocks[0][0], blocks
|
| 48 |
+
return None, []
|
| 49 |
+
|
| 50 |
+
def detect_cutoff_value(df):
|
| 51 |
+
"""Find CORR_THRESHOLD by searching for 'Cut-off used in columns' in column B."""
|
| 52 |
+
for row_idx in range(df.shape[0]):
|
| 53 |
+
val = df.iloc[row_idx, 1]
|
| 54 |
+
if pd.notna(val) and isinstance(val, str) and 'cut-off used in columns' in val.lower():
|
| 55 |
+
for col_idx in range(df.shape[1]):
|
| 56 |
+
cell_val = df.iloc[row_idx, col_idx]
|
| 57 |
+
if pd.notna(cell_val) and isinstance(cell_val, (int, float)):
|
| 58 |
+
return round(float(cell_val), 2)
|
| 59 |
+
return None
|
| 60 |
+
|
| 61 |
+
def detect_correlation_column_start(df):
|
| 62 |
+
"""Find CORR_COL_START by searching for first column containing 'BRAND' in row 5."""
|
| 63 |
+
for col_idx in range(df.shape[1]):
|
| 64 |
+
val = df.iloc[4, col_idx]
|
| 65 |
+
if pd.notna(val) and isinstance(val, str) and 'BRAND' in val.upper():
|
| 66 |
+
return col_idx
|
| 67 |
+
return None
|
| 68 |
+
|
| 69 |
+
def detect_nonrewards_patterns(df, data_start_idx):
|
| 70 |
+
"""Detect Nonrewards patterns in attribute codes."""
|
| 71 |
+
patterns_found = {}
|
| 72 |
+
|
| 73 |
+
for row_idx in range(data_start_idx, min(data_start_idx + 200, df.shape[0])):
|
| 74 |
+
code = df.iloc[row_idx, 1]
|
| 75 |
+
if pd.notna(code) and isinstance(code, str):
|
| 76 |
+
code_lower = code.lower()
|
| 77 |
+
if 'nonrewards' in code_lower:
|
| 78 |
+
patterns_found['_Nonrewards_'] = patterns_found.get('_Nonrewards_', 0) + 1
|
| 79 |
+
elif '_PA_' in code:
|
| 80 |
+
parts = code.split('_')
|
| 81 |
+
if len(parts) >= 3:
|
| 82 |
+
factor = parts[2]
|
| 83 |
+
if factor in NONREWARDS_FACTORS:
|
| 84 |
+
key = f'_{factor}_'
|
| 85 |
+
patterns_found[key] = patterns_found.get(key, 0) + 1
|
| 86 |
+
|
| 87 |
+
return patterns_found
|
| 88 |
+
|
| 89 |
+
def generate_network_html(df, data_start_row, corr_col_start, threshold, max_l1_nodes,
|
| 90 |
+
client_name, country_name, brand_name, category_name):
|
| 91 |
+
"""Generate the HTML network visualization."""
|
| 92 |
+
|
| 93 |
+
data_start_idx = data_start_row - 1
|
| 94 |
+
|
| 95 |
+
# Get driver codes from row 5
|
| 96 |
+
driver_codes = []
|
| 97 |
+
for col_idx in range(corr_col_start, df.shape[1]):
|
| 98 |
+
driver_code = df.iloc[4, col_idx]
|
| 99 |
+
if pd.notna(driver_code) and isinstance(driver_code, str) and 'BRAND' in driver_code.upper():
|
| 100 |
+
driver_codes.append(str(driver_code))
|
| 101 |
+
elif pd.isna(driver_code) or driver_code == '':
|
| 102 |
+
break
|
| 103 |
+
|
| 104 |
+
# Get attributes from rows
|
| 105 |
+
attribute_names = []
|
| 106 |
+
attribute_codes = []
|
| 107 |
+
category_indices = []
|
| 108 |
+
nonrewards_attrs = set()
|
| 109 |
+
|
| 110 |
+
for row_idx in range(data_start_idx, df.shape[0]):
|
| 111 |
+
attr_code = df.iloc[row_idx, 1]
|
| 112 |
+
attr_name = df.iloc[row_idx, 2]
|
| 113 |
+
cat_idx = df.iloc[row_idx, 3]
|
| 114 |
+
|
| 115 |
+
if pd.notna(attr_name) and attr_name != '':
|
| 116 |
+
code_str = str(attr_code) if pd.notna(attr_code) else ''
|
| 117 |
+
attribute_codes.append(code_str)
|
| 118 |
+
attribute_names.append(str(attr_name))
|
| 119 |
+
|
| 120 |
+
try:
|
| 121 |
+
cat_val = float(cat_idx) if pd.notna(cat_idx) else 0
|
| 122 |
+
except (ValueError, TypeError):
|
| 123 |
+
cat_val = 0
|
| 124 |
+
category_indices.append(cat_val)
|
| 125 |
+
|
| 126 |
+
if 'nonrewards' in code_str.lower():
|
| 127 |
+
nonrewards_attrs.add(str(attr_name))
|
| 128 |
+
elif '_PA_' in code_str:
|
| 129 |
+
parts = code_str.split('_')
|
| 130 |
+
if len(parts) >= 3:
|
| 131 |
+
factor = parts[2]
|
| 132 |
+
if factor in NONREWARDS_FACTORS:
|
| 133 |
+
nonrewards_attrs.add(str(attr_name))
|
| 134 |
+
else:
|
| 135 |
+
break
|
| 136 |
+
|
| 137 |
+
# Map codes to names
|
| 138 |
+
code_to_name = dict(zip(attribute_codes, attribute_names))
|
| 139 |
+
driver_names = [code_to_name.get(code, code) for code in driver_codes]
|
| 140 |
+
attr_to_cat_idx = dict(zip(attribute_names, category_indices))
|
| 141 |
+
|
| 142 |
+
# Build correlation matrix
|
| 143 |
+
corr_data = []
|
| 144 |
+
for row_idx in range(data_start_idx, data_start_idx + len(attribute_names)):
|
| 145 |
+
row_data = []
|
| 146 |
+
for col_idx in range(corr_col_start, corr_col_start + len(driver_codes)):
|
| 147 |
+
val = df.iloc[row_idx, col_idx]
|
| 148 |
+
try:
|
| 149 |
+
row_data.append(float(val) if pd.notna(val) else 0)
|
| 150 |
+
except (ValueError, TypeError):
|
| 151 |
+
row_data.append(0)
|
| 152 |
+
corr_data.append(row_data)
|
| 153 |
+
|
| 154 |
+
corr_df = pd.DataFrame(corr_data, index=attribute_names, columns=driver_names)
|
| 155 |
+
|
| 156 |
+
# Calculate statistics
|
| 157 |
+
all_positive_corrs = []
|
| 158 |
+
for col in corr_df.columns:
|
| 159 |
+
for val in corr_df[col]:
|
| 160 |
+
if val >= threshold:
|
| 161 |
+
all_positive_corrs.append(val)
|
| 162 |
+
|
| 163 |
+
if all_positive_corrs:
|
| 164 |
+
avg_corr = np.mean(all_positive_corrs)
|
| 165 |
+
max_corr = np.max(all_positive_corrs)
|
| 166 |
+
min_corr = threshold
|
| 167 |
+
else:
|
| 168 |
+
avg_corr = max_corr = min_corr = threshold
|
| 169 |
+
|
| 170 |
+
# Helper functions
|
| 171 |
+
wrapper = textwrap.TextWrapper(width=15)
|
| 172 |
+
|
| 173 |
+
def wrap_label(driver):
|
| 174 |
+
if len(driver.split()) > 2:
|
| 175 |
+
return '\n'.join(wrapper.wrap(text=driver))
|
| 176 |
+
return driver
|
| 177 |
+
|
| 178 |
+
def get_color(name):
|
| 179 |
+
return "lightskyblue" if name in nonrewards_attrs else "red"
|
| 180 |
+
|
| 181 |
+
def scale_edge(corr_val):
|
| 182 |
+
if max_corr == min_corr:
|
| 183 |
+
return {'width': 3.0, 'opacity': 0.7}
|
| 184 |
+
norm = (corr_val - min_corr) / (max_corr - min_corr)
|
| 185 |
+
return {'width': round(1 + norm * 7, 2), 'opacity': round(0.3 + norm * 0.7, 2)}
|
| 186 |
+
|
| 187 |
+
def get_nodes_edges(selected):
|
| 188 |
+
if selected not in corr_df.columns:
|
| 189 |
+
return [], []
|
| 190 |
+
|
| 191 |
+
nodes, edges = [], []
|
| 192 |
+
|
| 193 |
+
cat_idx = attr_to_cat_idx.get(selected, 100)
|
| 194 |
+
nodes.append({
|
| 195 |
+
'id': selected,
|
| 196 |
+
'label': wrap_label(selected) + '\n (' + str(int(cat_idx)) + ')',
|
| 197 |
+
'level': 0, 'value': int(cat_idx), 'title': selected,
|
| 198 |
+
'color': get_color(selected), 'font': {'color': 'white'}, 'shape': 'box'
|
| 199 |
+
})
|
| 200 |
+
|
| 201 |
+
l1_nodes = []
|
| 202 |
+
col_data = corr_df[selected]
|
| 203 |
+
corrs = [(attr, float(val)) for attr, val in col_data.items()
|
| 204 |
+
if attr != selected and float(val) >= threshold]
|
| 205 |
+
corrs.sort(key=lambda x: x[1], reverse=True)
|
| 206 |
+
|
| 207 |
+
for attr, val in corrs[:max_l1_nodes]:
|
| 208 |
+
l1_nodes.append(attr)
|
| 209 |
+
cat = attr_to_cat_idx.get(attr, 100)
|
| 210 |
+
nodes.append({
|
| 211 |
+
'id': attr, 'label': wrap_label(attr) + '\n (' + str(int(cat)) + ')',
|
| 212 |
+
'level': 1, 'value': int(cat), 'title': attr, 'color': get_color(attr)
|
| 213 |
+
})
|
| 214 |
+
ep = scale_edge(val)
|
| 215 |
+
edges.append({
|
| 216 |
+
'from': selected, 'to': attr, 'value': float(val),
|
| 217 |
+
'width': ep['width'], 'color': {'opacity': ep['opacity']},
|
| 218 |
+
'title': f'normalized value: {val:.2f}'
|
| 219 |
+
})
|
| 220 |
+
|
| 221 |
+
l2_added = set()
|
| 222 |
+
for l1 in l1_nodes:
|
| 223 |
+
if l1 in corr_df.columns:
|
| 224 |
+
col_data = corr_df[l1]
|
| 225 |
+
l2_corrs = [(attr, float(val)) for attr, val in col_data.items()
|
| 226 |
+
if attr != selected and attr not in l1_nodes and float(val) >= threshold]
|
| 227 |
+
l2_corrs.sort(key=lambda x: x[1], reverse=True)
|
| 228 |
+
|
| 229 |
+
for attr, val in l2_corrs[:max_l1_nodes]:
|
| 230 |
+
if attr not in l2_added:
|
| 231 |
+
cat = attr_to_cat_idx.get(attr, 100)
|
| 232 |
+
nodes.append({
|
| 233 |
+
'id': attr, 'label': wrap_label(attr) + '\n (' + str(int(cat)) + ')',
|
| 234 |
+
'level': 2, 'value': int(cat), 'title': attr, 'color': get_color(attr)
|
| 235 |
+
})
|
| 236 |
+
l2_added.add(attr)
|
| 237 |
+
ep = scale_edge(val)
|
| 238 |
+
edges.append({
|
| 239 |
+
'from': l1, 'to': attr, 'value': float(val),
|
| 240 |
+
'width': ep['width'], 'color': {'opacity': ep['opacity']},
|
| 241 |
+
'title': f'normalized value: {val:.2f}'
|
| 242 |
+
})
|
| 243 |
+
|
| 244 |
+
return nodes, edges
|
| 245 |
+
|
| 246 |
+
# Generate all networks
|
| 247 |
+
all_nodes, all_edges = [], []
|
| 248 |
+
available_drivers = sorted(driver_names)
|
| 249 |
+
|
| 250 |
+
for driver in available_drivers:
|
| 251 |
+
n, e = get_nodes_edges(driver)
|
| 252 |
+
all_nodes.append(n)
|
| 253 |
+
all_edges.append(e)
|
| 254 |
+
|
| 255 |
+
chart_title = f"DECODE_{client_name}_{country_name}_{brand_name}"
|
| 256 |
+
|
| 257 |
+
# HTML template
|
| 258 |
+
html_template = """
|
| 259 |
+
<!DOCTYPE html>
|
| 260 |
+
<meta charset="utf-8">
|
| 261 |
+
<html lang="en-US">
|
| 262 |
+
<head>
|
| 263 |
+
<link type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css" rel="stylesheet" />
|
| 264 |
+
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
|
| 265 |
+
<script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
|
| 266 |
+
<style>
|
| 267 |
+
#mynetwork { width: 100%; height: 800px; border: 1px solid lightgray; }
|
| 268 |
+
body { font-family: Arial, sans-serif; margin: 20px; }
|
| 269 |
+
.controls { margin: 20px 0; padding: 10px; background: #f5f5f5; border-radius: 5px; }
|
| 270 |
+
select { padding: 5px 10px; font-size: 14px; margin: 0 10px; }
|
| 271 |
+
.info { margin: 10px 0; padding: 10px; background: #e8f4f8; border-left: 4px solid #0078d4; }
|
| 272 |
+
.legend { margin: 10px 0; padding: 10px; background: #fff3cd; border-left: 4px solid #ffc107; }
|
| 273 |
+
</style>
|
| 274 |
+
<script>
|
| 275 |
+
var nodes = """ + json.dumps(all_nodes) + """;
|
| 276 |
+
var edges = """ + json.dumps(all_edges) + """;
|
| 277 |
+
var network = null;
|
| 278 |
+
function destroy() { if (network !== null) { network.destroy(); network = null; } }
|
| 279 |
+
function draw(id) {
|
| 280 |
+
destroy();
|
| 281 |
+
var data = { nodes: nodes[id], edges: edges[id] };
|
| 282 |
+
var options = {
|
| 283 |
+
nodes: { scaling: { min: 20, max: 80, label: { enabled: true, min: 12, max: 24 } }, font: { size: 14 }, margin: 10 },
|
| 284 |
+
edges: { smooth: { type: 'cubicBezier', forceDirection: 'vertical', roundness: 0.4 }, shadow: true, color: { inherit: 'from' } },
|
| 285 |
+
physics: { enabled: true, solver: 'hierarchicalRepulsion', hierarchicalRepulsion: { nodeDistance: 250, centralGravity: 0.0, springLength: 250, springConstant: 0.01, damping: 0.09, avoidOverlap: 1 }, stabilization: { enabled: true, iterations: 1000 } },
|
| 286 |
+
interaction: { zoomView: true, dragView: true, hover: true, tooltipDelay: 100 }
|
| 287 |
+
};
|
| 288 |
+
network = new vis.Network(document.getElementById('mynetwork'), data, options);
|
| 289 |
+
document.getElementById('nodeCount').textContent = data.nodes.length;
|
| 290 |
+
document.getElementById('edgeCount').textContent = data.edges.length;
|
| 291 |
+
}
|
| 292 |
+
window.onload = function() { draw(0); };
|
| 293 |
+
</script>
|
| 294 |
+
</head>
|
| 295 |
+
<body>
|
| 296 |
+
<h1>""" + chart_title + """ - Correlation Network (Threshold: """ + str(threshold) + """)</h1>
|
| 297 |
+
<div class="info">
|
| 298 |
+
<strong>Info:</strong> Network shows normalized deviation values >= """ + str(threshold) + """.<br>
|
| 299 |
+
Red nodes = Rewards (emotional), Blue nodes = Functional/Nonrewards.<br>
|
| 300 |
+
Node size based on Category Index.<br>
|
| 301 |
+
<strong>Data type:</strong> Deviation from expected value (positive = above average)
|
| 302 |
+
</div>
|
| 303 |
+
<div class="legend">
|
| 304 |
+
<strong>Edge Visualization:</strong> Line thickness and opacity indicate correlation strength.<br>
|
| 305 |
+
Thicker/darker lines = stronger correlations. Hover over edges to see exact normalized values.<br>
|
| 306 |
+
<strong>Scaling:</strong> Avg: """ + f"{avg_corr:.2f}" + """, Max: """ + f"{max_corr:.2f}" + """
|
| 307 |
+
</div>
|
| 308 |
+
<div class="controls">
|
| 309 |
+
<label>Select Driver:</label>
|
| 310 |
+
<select id="driver_select" onchange="draw(this.value)">
|
| 311 |
+
"""
|
| 312 |
+
|
| 313 |
+
for i, nodes_list in enumerate(all_nodes):
|
| 314 |
+
if nodes_list:
|
| 315 |
+
html_template += f'<option value="{i}">{nodes_list[0]["id"]} ({len(nodes_list)} nodes)</option>\n'
|
| 316 |
+
|
| 317 |
+
html_template += """
|
| 318 |
+
</select>
|
| 319 |
+
<span style="margin-left:20px;">Nodes: <strong id="nodeCount">0</strong> | Edges: <strong id="edgeCount">0</strong></span>
|
| 320 |
+
</div>
|
| 321 |
+
<div id="mynetwork"></div>
|
| 322 |
+
</body>
|
| 323 |
+
</html>
|
| 324 |
+
"""
|
| 325 |
+
|
| 326 |
+
stats = {
|
| 327 |
+
'drivers': len(available_drivers),
|
| 328 |
+
'attributes': len(attribute_names),
|
| 329 |
+
'rewards': len(attribute_names) - len(nonrewards_attrs),
|
| 330 |
+
'nonrewards': len(nonrewards_attrs),
|
| 331 |
+
'positive_correlations': len(all_positive_corrs)
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
filename = f"{chart_title}_{category_name}_Correlation_Network_strength_DEVIATION.html"
|
| 335 |
+
|
| 336 |
+
return html_template, stats, filename
|
| 337 |
+
|
| 338 |
+
# =============================================================================
|
| 339 |
+
# STREAMLIT UI
|
| 340 |
+
# =============================================================================
|
| 341 |
+
|
| 342 |
+
st.title("π DECODE Correlation Network Generator")
|
| 343 |
+
st.markdown("**Generate interactive HTML network visualizations from correlation matrices (DEVIATION data)**")
|
| 344 |
+
|
| 345 |
+
st.markdown("---")
|
| 346 |
+
|
| 347 |
+
# Section 1: File Upload
|
| 348 |
+
st.header("1. Upload Excel File")
|
| 349 |
+
|
| 350 |
+
uploaded_file = st.file_uploader(
|
| 351 |
+
"Choose your correlation Excel file",
|
| 352 |
+
type=['xlsx', 'xls'],
|
| 353 |
+
help="Upload the Excel file containing your correlation matrix"
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
worksheet_name = st.text_input(
|
| 357 |
+
"Worksheet Name",
|
| 358 |
+
value="Results Correls",
|
| 359 |
+
help="Name of the worksheet containing the correlation data"
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
# Initialize session state
|
| 363 |
+
if 'df' not in st.session_state:
|
| 364 |
+
st.session_state.df = None
|
| 365 |
+
if 'detected_values' not in st.session_state:
|
| 366 |
+
st.session_state.detected_values = {}
|
| 367 |
+
|
| 368 |
+
# Load and analyze file
|
| 369 |
+
if uploaded_file is not None:
|
| 370 |
+
try:
|
| 371 |
+
df = pd.read_excel(uploaded_file, sheet_name=worksheet_name, header=None)
|
| 372 |
+
st.session_state.df = df
|
| 373 |
+
|
| 374 |
+
# Auto-detect parameters
|
| 375 |
+
detected_row, blocks = detect_data_start_row(df)
|
| 376 |
+
detected_cutoff = detect_cutoff_value(df)
|
| 377 |
+
detected_col = detect_correlation_column_start(df)
|
| 378 |
+
patterns = detect_nonrewards_patterns(df, detected_row - 1 if detected_row else 95)
|
| 379 |
+
|
| 380 |
+
st.session_state.detected_values = {
|
| 381 |
+
'row': detected_row,
|
| 382 |
+
'col': detected_col,
|
| 383 |
+
'cutoff': detected_cutoff,
|
| 384 |
+
'blocks': blocks,
|
| 385 |
+
'patterns': patterns
|
| 386 |
+
}
|
| 387 |
+
|
| 388 |
+
st.success(f"β
File loaded: {df.shape[0]} rows Γ {df.shape[1]} columns")
|
| 389 |
+
|
| 390 |
+
# Show detected values
|
| 391 |
+
with st.expander("π Auto-detected Values", expanded=True):
|
| 392 |
+
col1, col2 = st.columns(2)
|
| 393 |
+
with col1:
|
| 394 |
+
st.markdown(f"**DATA_START_ROW:** {detected_row or 'Not detected'}")
|
| 395 |
+
st.caption("(2nd text block = DEVIATION data)")
|
| 396 |
+
if blocks:
|
| 397 |
+
blocks_text = ", ".join([f"Block {i+1}: Row {s}-{e}" for i, (s, e) in enumerate(blocks)])
|
| 398 |
+
st.caption(f"Text blocks: {blocks_text}")
|
| 399 |
+
with col2:
|
| 400 |
+
st.markdown(f"**CORR_COL_START:** {detected_col or 'Not detected'}")
|
| 401 |
+
st.caption("(First 'BRAND' column in row 5)")
|
| 402 |
+
|
| 403 |
+
col3, col4 = st.columns(2)
|
| 404 |
+
with col3:
|
| 405 |
+
st.markdown(f"**CORR_THRESHOLD:** {detected_cutoff or 'Not detected'}")
|
| 406 |
+
st.caption("(From 'Cut-off used in columns')")
|
| 407 |
+
with col4:
|
| 408 |
+
pattern_text = ', '.join(patterns.keys()) if patterns else 'None'
|
| 409 |
+
total = sum(patterns.values()) if patterns else 0
|
| 410 |
+
st.markdown(f"**Nonrewards Patterns:** {pattern_text}")
|
| 411 |
+
st.caption(f"({total} attributes)")
|
| 412 |
+
|
| 413 |
+
except Exception as e:
|
| 414 |
+
st.error(f"β Error loading file: {str(e)}")
|
| 415 |
+
st.session_state.df = None
|
| 416 |
+
|
| 417 |
+
st.markdown("---")
|
| 418 |
+
|
| 419 |
+
# Section 2: Parameters
|
| 420 |
+
st.header("2. Data Parameters")
|
| 421 |
+
st.caption("Adjust auto-detected values if needed")
|
| 422 |
+
|
| 423 |
+
col1, col2 = st.columns(2)
|
| 424 |
+
|
| 425 |
+
with col1:
|
| 426 |
+
data_start_row = st.number_input(
|
| 427 |
+
"Data Start Row",
|
| 428 |
+
min_value=1,
|
| 429 |
+
value=st.session_state.detected_values.get('row', 97) or 97,
|
| 430 |
+
help="Excel row number where data starts (1-based)"
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
threshold = st.number_input(
|
| 434 |
+
"Correlation Threshold",
|
| 435 |
+
min_value=0.0,
|
| 436 |
+
value=float(st.session_state.detected_values.get('cutoff', 6.0) or 6.0),
|
| 437 |
+
step=0.1,
|
| 438 |
+
format="%.2f",
|
| 439 |
+
help="Higher = fewer connections, Lower = more connections"
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
with col2:
|
| 443 |
+
corr_col_start = st.number_input(
|
| 444 |
+
"Correlation Column Start",
|
| 445 |
+
min_value=0,
|
| 446 |
+
value=st.session_state.detected_values.get('col', 32) or 32,
|
| 447 |
+
help="Column index where correlation data starts (0-based)"
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
max_l1_nodes = st.number_input(
|
| 451 |
+
"Max L1 Connections",
|
| 452 |
+
min_value=1,
|
| 453 |
+
max_value=20,
|
| 454 |
+
value=5,
|
| 455 |
+
help="Maximum number of Level 1 connections per node"
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
st.markdown("---")
|
| 459 |
+
|
| 460 |
+
# Section 3: Project Details
|
| 461 |
+
st.header("3. Project Details")
|
| 462 |
+
st.caption("Used for output filename")
|
| 463 |
+
|
| 464 |
+
col1, col2 = st.columns(2)
|
| 465 |
+
|
| 466 |
+
with col1:
|
| 467 |
+
client_name = st.text_input("Client Name", placeholder="e.g., P&G")
|
| 468 |
+
brand_name = st.text_input("Brand Name", placeholder="e.g., Oral-B")
|
| 469 |
+
|
| 470 |
+
with col2:
|
| 471 |
+
country_name = st.text_input("Country Code", placeholder="e.g., UK, MX, US")
|
| 472 |
+
category_name = st.text_input("Category", placeholder="e.g., OralCare")
|
| 473 |
+
|
| 474 |
+
st.markdown("---")
|
| 475 |
+
|
| 476 |
+
# Section 4: Generate
|
| 477 |
+
st.header("4. Generate Network")
|
| 478 |
+
|
| 479 |
+
# Validation
|
| 480 |
+
can_generate = (
|
| 481 |
+
st.session_state.df is not None and
|
| 482 |
+
client_name.strip() and
|
| 483 |
+
country_name.strip() and
|
| 484 |
+
brand_name.strip() and
|
| 485 |
+
category_name.strip()
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
if not can_generate:
|
| 489 |
+
missing = []
|
| 490 |
+
if st.session_state.df is None:
|
| 491 |
+
missing.append("Upload a file")
|
| 492 |
+
if not client_name.strip():
|
| 493 |
+
missing.append("Client Name")
|
| 494 |
+
if not country_name.strip():
|
| 495 |
+
missing.append("Country Code")
|
| 496 |
+
if not brand_name.strip():
|
| 497 |
+
missing.append("Brand Name")
|
| 498 |
+
if not category_name.strip():
|
| 499 |
+
missing.append("Category")
|
| 500 |
+
|
| 501 |
+
st.warning(f"β οΈ Please complete: {', '.join(missing)}")
|
| 502 |
+
|
| 503 |
+
if st.button("π Generate HTML Network", disabled=not can_generate, type="primary"):
|
| 504 |
+
with st.spinner("Generating network..."):
|
| 505 |
+
try:
|
| 506 |
+
html_content, stats, filename = generate_network_html(
|
| 507 |
+
st.session_state.df,
|
| 508 |
+
data_start_row,
|
| 509 |
+
corr_col_start,
|
| 510 |
+
threshold,
|
| 511 |
+
max_l1_nodes,
|
| 512 |
+
client_name.strip(),
|
| 513 |
+
country_name.strip(),
|
| 514 |
+
brand_name.strip(),
|
| 515 |
+
category_name.strip()
|
| 516 |
+
)
|
| 517 |
+
|
| 518 |
+
st.success("β
Network generated successfully!")
|
| 519 |
+
|
| 520 |
+
# Show stats
|
| 521 |
+
col1, col2, col3, col4 = st.columns(4)
|
| 522 |
+
col1.metric("Drivers", stats['drivers'])
|
| 523 |
+
col2.metric("Rewards (red)", stats['rewards'])
|
| 524 |
+
col3.metric("Nonrewards (blue)", stats['nonrewards'])
|
| 525 |
+
col4.metric("Correlations", stats['positive_correlations'])
|
| 526 |
+
|
| 527 |
+
# Download button
|
| 528 |
+
st.download_button(
|
| 529 |
+
label="π₯ Download HTML File",
|
| 530 |
+
data=html_content,
|
| 531 |
+
file_name=filename,
|
| 532 |
+
mime="text/html",
|
| 533 |
+
type="primary"
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
st.caption(f"Filename: `{filename}`")
|
| 537 |
+
|
| 538 |
+
except Exception as e:
|
| 539 |
+
st.error(f"β Error generating network: {str(e)}")
|
| 540 |
+
import traceback
|
| 541 |
+
st.code(traceback.format_exc())
|
| 542 |
+
|
| 543 |
+
# Footer
|
| 544 |
+
st.markdown("---")
|
| 545 |
+
st.caption("DECODE Correlation Network Generator | Uses DEVIATION data (normalized values)")
|
requirements.txt
CHANGED
|
@@ -1,3 +1,4 @@
|
|
| 1 |
-
|
| 2 |
-
pandas
|
| 3 |
-
|
|
|
|
|
|
| 1 |
+
streamlit>=1.28.0
|
| 2 |
+
pandas>=1.5.0
|
| 3 |
+
numpy>=1.23.0
|
| 4 |
+
openpyxl>=3.0.0
|