hemsby commited on
Commit
8bfc25e
·
1 Parent(s): 18f3210

feat: client-side connections slider, optional project details

Browse files

Replace pre-computed per-driver node/edge arrays with sparse correlation
matrix embedded in HTML. Networks are now built client-side in JS,
enabling a connections dropdown (2-6, default 5) in the sidebar.

HTML output shrinks from ~1,450 KB to ~55-70 KB.

Project detail fields (client, brand, country, category) are now
optional. When empty, falls back to uploaded filename for title.

Files changed (2) hide show
  1. app.py +8 -20
  2. build_network.py +298 -198
app.py CHANGED
@@ -156,7 +156,7 @@ st.markdown("---")
156
  # 3. PROJECT DETAILS
157
  # =============================================================================
158
  st.header("3. Project Details")
159
- st.caption("Used for output filename")
160
 
161
  col1, col2 = st.columns(2)
162
 
@@ -175,27 +175,10 @@ st.markdown("---")
175
  # =============================================================================
176
  st.header("4. Generate Network")
177
 
178
- can_generate = (
179
- st.session_state.df is not None
180
- and client_name.strip()
181
- and country_name.strip()
182
- and brand_name.strip()
183
- and category_name.strip()
184
- )
185
 
186
  if not can_generate:
187
- missing = []
188
- if st.session_state.df is None:
189
- missing.append("Upload a file")
190
- if not client_name.strip():
191
- missing.append("Client Name")
192
- if not country_name.strip():
193
- missing.append("Country Code")
194
- if not brand_name.strip():
195
- missing.append("Brand Name")
196
- if not category_name.strip():
197
- missing.append("Category")
198
- st.warning(f"⚠️ Please complete: {', '.join(missing)}")
199
 
200
  if st.button("🚀 Generate HTML Network", disabled=not can_generate, type="primary"):
201
  with st.spinner("Generating network..."):
@@ -207,6 +190,10 @@ if st.button("🚀 Generate HTML Network", disabled=not can_generate, type="prim
207
  st.session_state.df, data_start_row, corr_col_start, rewards_factors
208
  )
209
 
 
 
 
 
210
  html_content, stats, filename = generate_network_html(
211
  network_data,
212
  threshold,
@@ -216,6 +203,7 @@ if st.button("🚀 Generate HTML Network", disabled=not can_generate, type="prim
216
  brand_name.strip(),
217
  category_name.strip(),
218
  show_category_index=show_category_index,
 
219
  )
220
 
221
  st.success("✅ Network generated successfully!")
 
156
  # 3. PROJECT DETAILS
157
  # =============================================================================
158
  st.header("3. Project Details")
159
+ st.caption("Optional — used for HTML title and output filename. Falls back to uploaded filename.")
160
 
161
  col1, col2 = st.columns(2)
162
 
 
175
  # =============================================================================
176
  st.header("4. Generate Network")
177
 
178
+ can_generate = st.session_state.df is not None
 
 
 
 
 
 
179
 
180
  if not can_generate:
181
+ st.warning("⚠️ Please upload a file")
 
 
 
 
 
 
 
 
 
 
 
182
 
183
  if st.button("🚀 Generate HTML Network", disabled=not can_generate, type="primary"):
184
  with st.spinner("Generating network..."):
 
190
  st.session_state.df, data_start_row, corr_col_start, rewards_factors
191
  )
192
 
193
+ # Derive fallback name from uploaded filename
194
+ upload_name = uploaded_file.name if uploaded_file else ""
195
+ fallback_name = upload_name.rsplit('.', 1)[0] if upload_name else ""
196
+
197
  html_content, stats, filename = generate_network_html(
198
  network_data,
199
  threshold,
 
203
  brand_name.strip(),
204
  category_name.strip(),
205
  show_category_index=show_category_index,
206
+ fallback_name=fallback_name,
207
  )
208
 
209
  st.success("✅ Network generated successfully!")
build_network.py CHANGED
@@ -2,7 +2,6 @@
2
 
3
  import html
4
  import json
5
- import textwrap
6
  import numpy as np
7
  from config import COLORS
8
 
@@ -14,14 +13,15 @@ def _safe_json(obj):
14
 
15
  def generate_network_html(network_data, threshold, max_l1_nodes,
16
  client_name, country_name, brand_name, category_name,
17
- show_category_index=True):
18
  """Build the complete HTML file with vis.js network visualization.
19
 
20
  Args:
21
  network_data: Dict from parse_excel.extract_network_data()
22
  threshold: Minimum correlation value to show as a connection
23
- max_l1_nodes: Max number of Level 1 connections per node
24
- client_name, country_name, brand_name, category_name: Project metadata
 
25
 
26
  Returns:
27
  (html_string, stats_dict, filename)
@@ -40,224 +40,120 @@ def generate_network_html(network_data, threshold, max_l1_nodes,
40
  all_positive_corrs.append(val)
41
 
42
  if all_positive_corrs:
43
- avg_corr = np.mean(all_positive_corrs)
44
- max_corr = np.max(all_positive_corrs)
45
- min_corr = threshold
46
  else:
47
- avg_corr = max_corr = min_corr = threshold
48
-
49
- # --- Styling helpers ---
50
-
51
- wrapper = textwrap.TextWrapper(width=15)
52
-
53
- def wrap_label(text):
54
- if len(text.split()) > 2:
55
- return '\n'.join(wrapper.wrap(text=text))
56
- return text
57
-
58
- def is_reward(name):
59
- return name not in nonrewards_attrs
60
-
61
- def get_node_colors(name, is_driver=False):
62
- c = COLORS
63
- if is_driver:
64
- border = c['reward_border'] if is_reward(name) else c['nonreward_border']
65
- return {
66
- 'background': c['driver_bg'], 'border': border,
67
- 'highlight': {'background': '#444444', 'border': border},
68
- 'hover': {'background': '#444444', 'border': border},
69
- }
70
- if not is_reward(name):
71
- return {
72
- 'background': c['nonreward_bg'], 'border': c['nonreward_border'],
73
- 'highlight': {'background': '#D0E4F0', 'border': c['nonreward_border']},
74
- 'hover': {'background': '#D0E4F0', 'border': c['nonreward_border']},
75
- }
76
- return {
77
- 'background': c['reward_bg'], 'border': c['reward_border'],
78
- 'highlight': {'background': '#F8D0D0', 'border': c['reward_border']},
79
- 'hover': {'background': '#F8D0D0', 'border': c['reward_border']},
80
- }
81
-
82
- def get_font_color(name, is_driver=False):
83
- if is_driver:
84
- return COLORS['driver_font']
85
- return '#333333'
86
-
87
- def get_edge_color(name):
88
- return COLORS['reward_color'] if is_reward(name) else COLORS['nonreward_color']
89
-
90
- def scale_edge(corr_val):
91
- if max_corr == min_corr:
92
- return {'width': 3.0, 'opacity': 0.7}
93
- norm = (corr_val - min_corr) / (max_corr - min_corr)
94
- return {'width': round(1 + norm * 7, 2), 'opacity': round(0.3 + norm * 0.7, 2)}
95
-
96
- def make_label(name, cat_idx):
97
- label = wrap_label(name)
98
- if show_category_index:
99
- label += '\n(' + str(int(cat_idx)) + ')'
100
- return label
101
-
102
- # --- Build node/edge data for each driver ---
103
-
104
- def get_nodes_edges(selected):
105
- if selected not in corr_df.columns:
106
- return [], []
107
-
108
- nodes, edges = [], []
109
-
110
- # Level 0: selected driver
111
- cat_idx = attr_to_cat_idx.get(selected, 100)
112
- nodes.append({
113
- 'id': selected,
114
- 'label': make_label(selected, cat_idx),
115
- 'level': 0, 'value': int(cat_idx),
116
- 'title': selected + ' — Category Index: ' + str(int(cat_idx)),
117
- 'color': get_node_colors(selected, is_driver=True),
118
- 'font': {'color': COLORS['driver_font'], 'size': 18, 'bold': True},
119
- 'shape': 'box', 'borderWidth': 3, 'borderWidthSelected': 4,
120
  })
121
 
122
- # Level 1: top correlated attributes
123
- l1_nodes = []
124
- col_data = corr_df[selected]
125
- corrs = [(attr, float(val)) for attr, val in col_data.items()
126
- if attr != selected and float(val) >= threshold]
127
- corrs.sort(key=lambda x: x[1], reverse=True)
128
-
129
- for attr, val in corrs[:max_l1_nodes]:
130
- l1_nodes.append(attr)
131
- cat = attr_to_cat_idx.get(attr, 100)
132
- nodes.append({
133
- 'id': attr, 'label': make_label(attr, cat),
134
- 'level': 1, 'value': int(cat),
135
- 'title': attr + ' — Category Index: ' + str(int(cat)) + ', Correlation: ' + f'{val:.1f}',
136
- 'color': get_node_colors(attr),
137
- 'font': {'color': get_font_color(attr), 'size': 16},
138
- 'borderWidth': 2,
139
- })
140
- ep = scale_edge(val)
141
- edges.append({
142
- 'from': selected, 'to': attr, 'value': float(val),
143
- 'width': ep['width'],
144
- 'color': {'color': get_edge_color(selected), 'opacity': ep['opacity'],
145
- 'highlight': get_edge_color(selected),
146
- 'hover': get_edge_color(selected)},
147
- 'title': f'{selected} \u2194 {attr}: {val:.1f}',
148
- })
149
-
150
- # Level 2: secondary correlations from L1 nodes
151
- l2_added = set()
152
- for l1 in l1_nodes:
153
- if l1 in corr_df.columns:
154
- col_data = corr_df[l1]
155
- l2_corrs = [(attr, float(val)) for attr, val in col_data.items()
156
- if attr != selected and attr not in l1_nodes and float(val) >= threshold]
157
- l2_corrs.sort(key=lambda x: x[1], reverse=True)
158
-
159
- for attr, val in l2_corrs[:max_l1_nodes]:
160
- if attr not in l2_added:
161
- cat = attr_to_cat_idx.get(attr, 100)
162
- nodes.append({
163
- 'id': attr, 'label': make_label(attr, cat),
164
- 'level': 2, 'value': int(cat),
165
- 'title': attr + ' — Category Index: ' + str(int(cat)) + ', Correlation: ' + f'{val:.1f}',
166
- 'color': get_node_colors(attr),
167
- 'font': {'color': get_font_color(attr), 'size': 15},
168
- 'borderWidth': 2,
169
- })
170
- l2_added.add(attr)
171
- ep = scale_edge(val)
172
- edges.append({
173
- 'from': l1, 'to': attr, 'value': float(val),
174
- 'width': ep['width'],
175
- 'color': {'color': get_edge_color(l1), 'opacity': ep['opacity'],
176
- 'highlight': get_edge_color(l1),
177
- 'hover': get_edge_color(l1)},
178
- 'title': f'{l1} \u2194 {attr}: {val:.1f}',
179
- })
180
-
181
- return nodes, edges
182
-
183
- # Generate networks for all drivers
184
- all_nodes, all_edges = [], []
185
- available_drivers = sorted(driver_names, key=lambda x: x.lower())
186
-
187
- for driver in available_drivers:
188
- n, e = get_nodes_edges(driver)
189
- all_nodes.append(n)
190
- all_edges.append(e)
191
-
192
- chart_title = f"DECODE_{client_name}_{country_name}_{brand_name}"
193
-
194
- # Build driver list with metadata for sidebar
195
  driver_list = []
196
- for i, driver in enumerate(available_drivers):
197
- if all_nodes[i]:
198
- cat_idx = attr_to_cat_idx.get(driver, 100)
199
- driver_list.append({
200
- 'name': driver,
201
- 'catIdx': int(cat_idx),
202
- 'isReward': is_reward(driver),
203
- 'index': i,
204
- })
205
-
206
- # Count rewards vs nonrewards in drivers
207
- reward_drivers = sum(1 for d in available_drivers if is_reward(d))
208
- nonreward_drivers = len(available_drivers) - reward_drivers
 
 
 
 
 
 
 
 
 
 
 
 
 
209
 
210
  # --- HTML template ---
211
- html = _build_html_template(
212
  chart_title=chart_title,
213
- client_name=client_name,
214
- country_name=country_name,
215
- brand_name=brand_name,
216
- category_name=category_name,
217
- all_nodes=all_nodes,
218
- all_edges=all_edges,
219
  driver_list=driver_list,
220
  nonrewards_list=sorted(nonrewards_attrs),
221
  threshold=threshold,
 
 
222
  attribute_count=len(attribute_names),
223
  reward_drivers=reward_drivers,
224
  nonreward_drivers=nonreward_drivers,
225
  corr_count=len(all_positive_corrs),
226
  avg_corr=avg_corr,
227
- max_corr=max_corr,
 
228
  )
229
 
230
  stats = {
231
- 'drivers': len(available_drivers),
232
  'attributes': len(attribute_names),
233
  'rewards': len(attribute_names) - len(nonrewards_attrs),
234
  'nonrewards': len(nonrewards_attrs),
235
  'positive_correlations': len(all_positive_corrs),
236
  }
237
 
238
- filename = f"{chart_title}_{category_name}_Correlation_Network_strength_DEVIATION.html"
 
 
 
239
 
240
- return html, stats, filename
241
 
242
 
243
- def _build_html_template(*, chart_title, client_name, country_name, brand_name,
244
- category_name, all_nodes, all_edges, driver_list,
245
- nonrewards_list, threshold, attribute_count,
246
- reward_drivers, nonreward_drivers,
247
- corr_count, avg_corr, max_corr):
248
  """Build the standalone HTML string. Separated for readability."""
249
 
250
  # Escape all user-supplied strings for safe HTML embedding
251
  h = html.escape
252
  safe_title = h(chart_title)
253
- safe_client = h(client_name)
254
- safe_brand = h(brand_name)
255
- safe_country = h(country_name)
256
- safe_category = h(category_name)
257
 
258
  # JSON data for script block (escape </script> sequences)
259
- nodes_json = _safe_json(all_nodes)
260
- edges_json = _safe_json(all_edges)
261
  drivers_json = _safe_json(driver_list)
262
  nonrewards_json = _safe_json(nonrewards_list)
263
 
@@ -304,6 +200,11 @@ body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans
304
  .control-btn:last-child {{ border-radius: 0 4px 4px 0; }}
305
  .control-btn.active {{ background: #283273; color: #fff; border-color: #283273; }}
306
 
 
 
 
 
 
307
  .sidebar-list {{ flex: 1; overflow-y: auto; }}
308
 
309
  .attr-row {{ display: flex; align-items: center; padding: 8px 14px; cursor: pointer; border-bottom: 1px solid #f0f0f0; transition: background 0.1s; gap: 8px; }}
@@ -370,15 +271,32 @@ body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans
370
  .bar-val {{ font-size: 11px; font-weight: 600; color: #888; min-width: 30px; text-align: right; flex-shrink: 0; }}
371
  </style>
372
  <script>
373
- var allNetworkNodes = {nodes_json};
374
- var allNetworkEdges = {edges_json};
 
375
  var driverList = {drivers_json};
376
  var nonrewardsSet = new Set({nonrewards_json});
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
377
  var network = null;
378
  var nodesDS = null;
379
  var edgesDS = null;
380
- var currentSort = 'index'; // 'index' or 'name'
381
- var currentFilter = 'all'; // 'all', 'emotional', 'functional'
382
  var selectedIdx = 0;
383
  var origNodes = {{}};
384
  var clickedNode = null;
@@ -393,6 +311,171 @@ var FADED = {{
393
 
394
  function esc(s) {{ return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }}
395
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
396
  function applyFocus(nodeId) {{
397
  var connected = network.getConnectedNodes(nodeId);
398
  var connEdges = network.getConnectedEdges(nodeId);
@@ -428,10 +511,16 @@ function clearFocus() {{
428
 
429
  function destroy() {{ if (network !== null) {{ network.destroy(); network = null; }} }}
430
 
 
 
 
 
 
431
  function draw(id) {{
432
  destroy();
433
  selectedIdx = id;
434
- var data = {{ nodes: allNetworkNodes[id], edges: allNetworkEdges[id] }};
 
435
  var options = {{
436
  nodes: {{
437
  shape: 'box',
@@ -462,7 +551,6 @@ function draw(id) {{
462
  document.getElementById('nodeCount').textContent = data.nodes.length;
463
  document.getElementById('edgeCount').textContent = data.edges.length;
464
 
465
- // Store original node styling for restore
466
  origNodes = {{}};
467
  nodesDS.forEach(function(n) {{
468
  origNodes[n.id] = {{ color: n.color, font: n.font, borderWidth: n.borderWidth }};
@@ -514,7 +602,6 @@ function showProfile(nodeId) {{
514
  var maxVal = bars.length > 0 ? bars[0].value : 1;
515
  var isNR = nonrewardsSet.has(nodeId);
516
 
517
- // Find category index from driverList or node value
518
  var catIdx = node.value || 0;
519
 
520
  document.getElementById('profileName').textContent = nodeId;
@@ -621,9 +708,12 @@ function toggleDetails() {{
621
  btn.classList.toggle('active');
622
  }}
623
 
 
 
 
 
624
  document.addEventListener('DOMContentLoaded', function() {{
625
  renderSidebar();
626
- // Default: select first by index (highest catIdx)
627
  var sorted = driverList.slice().sort(function(a, b) {{ return b.catIdx - a.catIdx; }});
628
  if (sorted.length > 0) draw(sorted[0].index);
629
  }});
@@ -636,8 +726,8 @@ document.addEventListener('DOMContentLoaded', function() {{
636
  <svg class="decode-logo" viewBox="0 0 160 21" xmlns="http://www.w3.org/2000/svg"><path d="M0,0.69 L0,19.5 L10.2,19.5 C15.83,19.5 19.72,16.02 19.72,9.81 C19.72,2.8 14.52,0.69 10.2,0.69 L0,0.69 Z M3.78,4.47 L10.2,4.47 C13.14,4.47 15.94,5.59 15.94,10.02 C15.94,13.84 13.51,15.72 10.2,15.72 L3.78,15.72 L3.78,4.47 Z M28.69,0.69 L28.69,19.5 L45.82,19.5 L45.82,15.72 L32.46,15.72 L32.46,11.66 L41.98,11.66 L41.98,7.88 L32.46,7.88 L32.46,4.47 L45.39,4.47 L45.39,0.69 L28.69,0.69 Z M73.57,3.67 C71.57,2.25 68.92,0.11 64.05,0.11 C58.82,0.11 52.72,3.45 52.72,10.1 C52.72,16.63 57.95,20.08 64.27,20.08 C67.18,20.08 71.24,19.1 73.89,17.14 L72.19,13.65 C70.63,14.85 67.65,16.31 64.31,16.31 C58.9,16.31 56.5,13 56.5,10.21 C56.5,7.16 59.22,3.89 63.87,3.89 C67.54,3.89 70.12,5.96 71.35,6.97 L73.57,3.67 Z M92.96,20.08 C100.33,20.08 104.5,15.36 104.5,10.1 C104.5,4.79 100.4,0.11 92.96,0.11 C85.55,0.11 81.41,4.83 81.41,10.1 C81.41,15.36 85.59,20.08 92.96,20.08 Z M92.96,16.31 C88.27,16.31 85.19,13.36 85.19,10.1 C85.19,6.86 88.27,3.89 92.96,3.89 C97.64,3.89 100.73,6.83 100.73,10.1 C100.73,13.36 97.64,16.31 92.96,16.31 Z M113.94,0.69 L113.94,19.5 L124.15,19.5 C129.78,19.5 133.66,16.02 133.66,9.81 C133.66,2.8 128.47,0.69 124.15,0.69 L113.94,0.69 Z M117.72,4.47 L124.15,4.47 C127.09,4.47 129.88,5.59 129.88,10.02 C129.88,13.84 127.45,15.72 124.15,15.72 L117.72,15.72 L117.72,4.47 Z M142.63,0.69 L142.63,19.5 L159.77,19.5 L159.77,15.72 L146.41,15.72 L146.41,11.66 L155.93,11.66 L155.93,7.88 L146.41,7.88 L146.41,4.47 L159.33,4.47 L159.33,0.69 L142.63,0.69 Z" fill="#283273"/></svg>
637
  </div>
638
  <div class="header-center">
639
- <h1>{safe_client} &middot; {safe_brand} &middot; {safe_country} &middot; {safe_category}</h1>
640
- <div class="subtitle">Association Network</div>
641
  </div>
642
  <div class="legend-bar">
643
  <div class="legend-item"><div class="legend-dot reward"></div> Emotional</div>
@@ -660,6 +750,16 @@ document.addEventListener('DOMContentLoaded', function() {{
660
  <button class="control-btn filter-btn" data-filter="emotional" onclick="setFilter('emotional')">Emotional</button>
661
  <button class="control-btn filter-btn" data-filter="functional" onclick="setFilter('functional')">Functional</button>
662
  </div>
 
 
 
 
 
 
 
 
 
 
663
  </div>
664
  <div class="sidebar-list" id="sidebarList"></div>
665
  <div class="sidebar-stats"><span id="sidebarCount">{attribute_count}</span> attributes &middot; {reward_drivers} emotional &middot; {nonreward_drivers} functional</div>
 
2
 
3
  import html
4
  import json
 
5
  import numpy as np
6
  from config import COLORS
7
 
 
13
 
14
  def generate_network_html(network_data, threshold, max_l1_nodes,
15
  client_name, country_name, brand_name, category_name,
16
+ show_category_index=True, fallback_name=''):
17
  """Build the complete HTML file with vis.js network visualization.
18
 
19
  Args:
20
  network_data: Dict from parse_excel.extract_network_data()
21
  threshold: Minimum correlation value to show as a connection
22
+ max_l1_nodes: Max number of Level 1 connections per node (default for in-HTML dropdown)
23
+ client_name, country_name, brand_name, category_name: Project metadata (all optional)
24
+ fallback_name: Fallback name from uploaded filename (used when no project details entered)
25
 
26
  Returns:
27
  (html_string, stats_dict, filename)
 
40
  all_positive_corrs.append(val)
41
 
42
  if all_positive_corrs:
43
+ avg_corr = float(np.mean(all_positive_corrs))
44
+ max_corr = float(np.max(all_positive_corrs))
45
+ min_corr = float(threshold)
46
  else:
47
+ avg_corr = max_corr = min_corr = float(threshold)
48
+
49
+ # --- Build sparse correlation matrix (only above-threshold pairs) ---
50
+ attr_list = sorted(driver_names, key=lambda x: x.lower())
51
+ attr_to_idx = {name: i for i, name in enumerate(attr_list)}
52
+
53
+ sparse_corr = {}
54
+ for i, a in enumerate(attr_list):
55
+ for j in range(i + 1, len(attr_list)):
56
+ b = attr_list[j]
57
+ if a in corr_df.columns and b in corr_df.index:
58
+ val = float(corr_df.loc[b, a])
59
+ if val >= threshold:
60
+ sparse_corr[f"{i},{j}"] = round(val, 1)
61
+ elif b in corr_df.columns and a in corr_df.index:
62
+ val = float(corr_df.loc[a, b])
63
+ if val >= threshold:
64
+ sparse_corr[f"{i},{j}"] = round(val, 1)
65
+
66
+ # Build attribute metadata array (parallel to attr_list)
67
+ attr_meta = []
68
+ for name in attr_list:
69
+ cat_idx = int(attr_to_cat_idx.get(name, 100))
70
+ is_reward = name not in nonrewards_attrs
71
+ attr_meta.append({
72
+ 'name': name,
73
+ 'catIdx': cat_idx,
74
+ 'isReward': is_reward,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  })
76
 
77
+ # Build driver list with index references for sidebar
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  driver_list = []
79
+ for i, meta in enumerate(attr_meta):
80
+ driver_list.append({
81
+ 'name': meta['name'],
82
+ 'catIdx': meta['catIdx'],
83
+ 'isReward': meta['isReward'],
84
+ 'index': i,
85
+ })
86
+
87
+ # Count rewards vs nonrewards
88
+ reward_drivers = sum(1 for m in attr_meta if m['isReward'])
89
+ nonreward_drivers = len(attr_meta) - reward_drivers
90
+
91
+ # Build title from filled-in fields only
92
+ detail_parts = [p for p in [client_name, brand_name, country_name, category_name] if p]
93
+ if detail_parts:
94
+ chart_title = 'DECODE_' + '_'.join(detail_parts)
95
+ header_title = ' \u00b7 '.join(detail_parts) # · separator
96
+ elif fallback_name:
97
+ chart_title = fallback_name
98
+ header_title = fallback_name.replace('_', ' ')
99
+ else:
100
+ chart_title = 'Association_Network'
101
+ header_title = ''
102
+
103
+ # Clamp default max_l1 to dropdown range (2-6)
104
+ default_max_l1 = max(2, min(6, max_l1_nodes))
105
 
106
  # --- HTML template ---
107
+ html_out = _build_html_template(
108
  chart_title=chart_title,
109
+ header_title=header_title,
110
+ sparse_corr=sparse_corr,
111
+ attr_meta=attr_meta,
 
 
 
112
  driver_list=driver_list,
113
  nonrewards_list=sorted(nonrewards_attrs),
114
  threshold=threshold,
115
+ min_corr=min_corr,
116
+ max_corr=max_corr,
117
  attribute_count=len(attribute_names),
118
  reward_drivers=reward_drivers,
119
  nonreward_drivers=nonreward_drivers,
120
  corr_count=len(all_positive_corrs),
121
  avg_corr=avg_corr,
122
+ default_max_l1=default_max_l1,
123
+ show_category_index=show_category_index,
124
  )
125
 
126
  stats = {
127
+ 'drivers': len(attr_list),
128
  'attributes': len(attribute_names),
129
  'rewards': len(attribute_names) - len(nonrewards_attrs),
130
  'nonrewards': len(nonrewards_attrs),
131
  'positive_correlations': len(all_positive_corrs),
132
  }
133
 
134
+ if detail_parts or fallback_name:
135
+ filename = f"{chart_title}_Correlation_Network.html"
136
+ else:
137
+ filename = "Correlation_Network.html"
138
 
139
+ return html_out, stats, filename
140
 
141
 
142
+ def _build_html_template(*, chart_title, header_title, sparse_corr, attr_meta,
143
+ driver_list, nonrewards_list, threshold, min_corr,
144
+ max_corr, attribute_count, reward_drivers,
145
+ nonreward_drivers, corr_count, avg_corr,
146
+ default_max_l1, show_category_index):
147
  """Build the standalone HTML string. Separated for readability."""
148
 
149
  # Escape all user-supplied strings for safe HTML embedding
150
  h = html.escape
151
  safe_title = h(chart_title)
152
+ safe_header = h(header_title)
 
 
 
153
 
154
  # JSON data for script block (escape </script> sequences)
155
+ corr_json = _safe_json(sparse_corr)
156
+ meta_json = _safe_json(attr_meta)
157
  drivers_json = _safe_json(driver_list)
158
  nonrewards_json = _safe_json(nonrewards_list)
159
 
 
200
  .control-btn:last-child {{ border-radius: 0 4px 4px 0; }}
201
  .control-btn.active {{ background: #283273; color: #fff; border-color: #283273; }}
202
 
203
+ .connections-row {{ display: flex; align-items: center; gap: 8px; margin-top: 8px; }}
204
+ .connections-label {{ font-size: 11px; font-weight: 500; color: #777; white-space: nowrap; }}
205
+ .connections-select {{ flex: 1; padding: 4px 6px; font-size: 11px; border: 1px solid #ddd; border-radius: 4px; background: #f8f8f8; color: #555; cursor: pointer; outline: none; }}
206
+ .connections-select:focus {{ border-color: #999; }}
207
+
208
  .sidebar-list {{ flex: 1; overflow-y: auto; }}
209
 
210
  .attr-row {{ display: flex; align-items: center; padding: 8px 14px; cursor: pointer; border-bottom: 1px solid #f0f0f0; transition: background 0.1s; gap: 8px; }}
 
271
  .bar-val {{ font-size: 11px; font-weight: 600; color: #888; min-width: 30px; text-align: right; flex-shrink: 0; }}
272
  </style>
273
  <script>
274
+ // --- Embedded data ---
275
+ var corrMatrix = {corr_json};
276
+ var attrMeta = {meta_json};
277
  var driverList = {drivers_json};
278
  var nonrewardsSet = new Set({nonrewards_json});
279
+ var THRESHOLD = {threshold};
280
+ var MIN_CORR = {min_corr};
281
+ var MAX_CORR = {max_corr};
282
+ var SHOW_CAT_IDX = {'true' if show_category_index else 'false'};
283
+
284
+ var COLORS = {{
285
+ reward_color: '{COLORS["reward_color"]}',
286
+ reward_border: '{COLORS["reward_border"]}',
287
+ reward_bg: '{COLORS["reward_bg"]}',
288
+ nonreward_color: '{COLORS["nonreward_color"]}',
289
+ nonreward_border: '{COLORS["nonreward_border"]}',
290
+ nonreward_bg: '{COLORS["nonreward_bg"]}',
291
+ driver_bg: '{COLORS["driver_bg"]}',
292
+ driver_font: '{COLORS["driver_font"]}'
293
+ }};
294
+
295
  var network = null;
296
  var nodesDS = null;
297
  var edgesDS = null;
298
+ var currentSort = 'index';
299
+ var currentFilter = 'all';
300
  var selectedIdx = 0;
301
  var origNodes = {{}};
302
  var clickedNode = null;
 
311
 
312
  function esc(s) {{ return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }}
313
 
314
+ // --- Correlation lookup ---
315
+ function getCorr(i, j) {{
316
+ if (i === j) return 0;
317
+ var a = Math.min(i, j), b = Math.max(i, j);
318
+ var key = a + ',' + b;
319
+ return corrMatrix[key] || 0;
320
+ }}
321
+
322
+ // --- Styling helpers (ported from Python) ---
323
+ function wrapLabel(text) {{
324
+ var words = text.split(/\s+/);
325
+ if (words.length <= 2) return text;
326
+ var lines = [], line = '';
327
+ for (var w = 0; w < words.length; w++) {{
328
+ if (line.length + words[w].length + 1 > 15 && line.length > 0) {{
329
+ lines.push(line);
330
+ line = words[w];
331
+ }} else {{
332
+ line = line ? line + ' ' + words[w] : words[w];
333
+ }}
334
+ }}
335
+ if (line) lines.push(line);
336
+ return lines.join('\\n');
337
+ }}
338
+
339
+ function makeLabel(name, catIdx) {{
340
+ var label = wrapLabel(name);
341
+ if (SHOW_CAT_IDX) label += '\\n(' + catIdx + ')';
342
+ return label;
343
+ }}
344
+
345
+ function isReward(name) {{ return !nonrewardsSet.has(name); }}
346
+
347
+ function getNodeColors(name, isDriver) {{
348
+ if (isDriver) {{
349
+ var border = isReward(name) ? COLORS.reward_border : COLORS.nonreward_border;
350
+ return {{
351
+ background: COLORS.driver_bg, border: border,
352
+ highlight: {{ background: '#444444', border: border }},
353
+ hover: {{ background: '#444444', border: border }}
354
+ }};
355
+ }}
356
+ if (!isReward(name)) {{
357
+ return {{
358
+ background: COLORS.nonreward_bg, border: COLORS.nonreward_border,
359
+ highlight: {{ background: '#D0E4F0', border: COLORS.nonreward_border }},
360
+ hover: {{ background: '#D0E4F0', border: COLORS.nonreward_border }}
361
+ }};
362
+ }}
363
+ return {{
364
+ background: COLORS.reward_bg, border: COLORS.reward_border,
365
+ highlight: {{ background: '#F8D0D0', border: COLORS.reward_border }},
366
+ hover: {{ background: '#F8D0D0', border: COLORS.reward_border }}
367
+ }};
368
+ }}
369
+
370
+ function getEdgeColor(name) {{
371
+ return isReward(name) ? COLORS.reward_color : COLORS.nonreward_color;
372
+ }}
373
+
374
+ function scaleEdge(val) {{
375
+ if (MAX_CORR === MIN_CORR) return {{ width: 3.0, opacity: 0.7 }};
376
+ var norm = (val - MIN_CORR) / (MAX_CORR - MIN_CORR);
377
+ return {{ width: Math.round((1 + norm * 7) * 100) / 100, opacity: Math.round((0.3 + norm * 0.7) * 100) / 100 }};
378
+ }}
379
+
380
+ // --- Build network for a selected attribute ---
381
+ function buildNetwork(selectedIdx, maxL1) {{
382
+ var selected = attrMeta[selectedIdx].name;
383
+ var nodes = [], edges = [];
384
+
385
+ // Level 0: selected driver
386
+ var catIdx = attrMeta[selectedIdx].catIdx;
387
+ nodes.push({{
388
+ id: selected,
389
+ label: makeLabel(selected, catIdx),
390
+ level: 0, value: catIdx,
391
+ title: selected + ' \\u2014 Category Index: ' + catIdx,
392
+ color: getNodeColors(selected, true),
393
+ font: {{ color: COLORS.driver_font, size: 18, bold: true }},
394
+ shape: 'box', borderWidth: 3, borderWidthSelected: 4
395
+ }});
396
+
397
+ // Level 1: top correlated attributes
398
+ var corrs = [];
399
+ for (var j = 0; j < attrMeta.length; j++) {{
400
+ if (j === selectedIdx) continue;
401
+ var val = getCorr(selectedIdx, j);
402
+ if (val >= THRESHOLD) corrs.push({{ idx: j, val: val }});
403
+ }}
404
+ corrs.sort(function(a, b) {{ return b.val - a.val; }});
405
+
406
+ var l1Names = [];
407
+ var l1Set = new Set();
408
+ for (var k = 0; k < Math.min(corrs.length, maxL1); k++) {{
409
+ var c = corrs[k];
410
+ var m = attrMeta[c.idx];
411
+ l1Names.push(m.name);
412
+ l1Set.add(m.name);
413
+ nodes.push({{
414
+ id: m.name,
415
+ label: makeLabel(m.name, m.catIdx),
416
+ level: 1, value: m.catIdx,
417
+ title: m.name + ' \\u2014 Category Index: ' + m.catIdx + ', Correlation: ' + c.val.toFixed(1),
418
+ color: getNodeColors(m.name, false),
419
+ font: {{ color: '#333333', size: 16 }},
420
+ borderWidth: 2
421
+ }});
422
+ var ep = scaleEdge(c.val);
423
+ var ec = getEdgeColor(selected);
424
+ edges.push({{
425
+ from: selected, to: m.name, value: c.val,
426
+ width: ep.width,
427
+ color: {{ color: ec, opacity: ep.opacity, highlight: ec, hover: ec }},
428
+ title: selected + ' \\u2194 ' + m.name + ': ' + c.val.toFixed(1)
429
+ }});
430
+ }}
431
+
432
+ // Level 2: secondary correlations from L1 nodes
433
+ var l2Added = new Set();
434
+ for (var li = 0; li < l1Names.length; li++) {{
435
+ var l1Name = l1Names[li];
436
+ var l1Idx = null;
437
+ for (var q = 0; q < attrMeta.length; q++) {{
438
+ if (attrMeta[q].name === l1Name) {{ l1Idx = q; break; }}
439
+ }}
440
+ if (l1Idx === null) continue;
441
+
442
+ var l2Corrs = [];
443
+ for (var j2 = 0; j2 < attrMeta.length; j2++) {{
444
+ if (j2 === selectedIdx || l1Set.has(attrMeta[j2].name)) continue;
445
+ var v2 = getCorr(l1Idx, j2);
446
+ if (v2 >= THRESHOLD) l2Corrs.push({{ idx: j2, val: v2 }});
447
+ }}
448
+ l2Corrs.sort(function(a, b) {{ return b.val - a.val; }});
449
+
450
+ for (var k2 = 0; k2 < Math.min(l2Corrs.length, maxL1); k2++) {{
451
+ var c2 = l2Corrs[k2];
452
+ var m2 = attrMeta[c2.idx];
453
+ if (!l2Added.has(m2.name)) {{
454
+ nodes.push({{
455
+ id: m2.name,
456
+ label: makeLabel(m2.name, m2.catIdx),
457
+ level: 2, value: m2.catIdx,
458
+ title: m2.name + ' \\u2014 Category Index: ' + m2.catIdx + ', Correlation: ' + c2.val.toFixed(1),
459
+ color: getNodeColors(m2.name, false),
460
+ font: {{ color: '#333333', size: 15 }},
461
+ borderWidth: 2
462
+ }});
463
+ l2Added.add(m2.name);
464
+ }}
465
+ var ep2 = scaleEdge(c2.val);
466
+ var ec2 = getEdgeColor(l1Name);
467
+ edges.push({{
468
+ from: l1Name, to: m2.name, value: c2.val,
469
+ width: ep2.width,
470
+ color: {{ color: ec2, opacity: ep2.opacity, highlight: ec2, hover: ec2 }},
471
+ title: l1Name + ' \\u2194 ' + m2.name + ': ' + c2.val.toFixed(1)
472
+ }});
473
+ }}
474
+ }}
475
+
476
+ return {{ nodes: nodes, edges: edges }};
477
+ }}
478
+
479
  function applyFocus(nodeId) {{
480
  var connected = network.getConnectedNodes(nodeId);
481
  var connEdges = network.getConnectedEdges(nodeId);
 
511
 
512
  function destroy() {{ if (network !== null) {{ network.destroy(); network = null; }} }}
513
 
514
+ function getMaxL1() {{
515
+ var sel = document.getElementById('maxL1Select');
516
+ return sel ? parseInt(sel.value, 10) : {default_max_l1};
517
+ }}
518
+
519
  function draw(id) {{
520
  destroy();
521
  selectedIdx = id;
522
+ var maxL1 = getMaxL1();
523
+ var data = buildNetwork(id, maxL1);
524
  var options = {{
525
  nodes: {{
526
  shape: 'box',
 
551
  document.getElementById('nodeCount').textContent = data.nodes.length;
552
  document.getElementById('edgeCount').textContent = data.edges.length;
553
 
 
554
  origNodes = {{}};
555
  nodesDS.forEach(function(n) {{
556
  origNodes[n.id] = {{ color: n.color, font: n.font, borderWidth: n.borderWidth }};
 
602
  var maxVal = bars.length > 0 ? bars[0].value : 1;
603
  var isNR = nonrewardsSet.has(nodeId);
604
 
 
605
  var catIdx = node.value || 0;
606
 
607
  document.getElementById('profileName').textContent = nodeId;
 
708
  btn.classList.toggle('active');
709
  }}
710
 
711
+ function onMaxL1Change() {{
712
+ draw(selectedIdx);
713
+ }}
714
+
715
  document.addEventListener('DOMContentLoaded', function() {{
716
  renderSidebar();
 
717
  var sorted = driverList.slice().sort(function(a, b) {{ return b.catIdx - a.catIdx; }});
718
  if (sorted.length > 0) draw(sorted[0].index);
719
  }});
 
726
  <svg class="decode-logo" viewBox="0 0 160 21" xmlns="http://www.w3.org/2000/svg"><path d="M0,0.69 L0,19.5 L10.2,19.5 C15.83,19.5 19.72,16.02 19.72,9.81 C19.72,2.8 14.52,0.69 10.2,0.69 L0,0.69 Z M3.78,4.47 L10.2,4.47 C13.14,4.47 15.94,5.59 15.94,10.02 C15.94,13.84 13.51,15.72 10.2,15.72 L3.78,15.72 L3.78,4.47 Z M28.69,0.69 L28.69,19.5 L45.82,19.5 L45.82,15.72 L32.46,15.72 L32.46,11.66 L41.98,11.66 L41.98,7.88 L32.46,7.88 L32.46,4.47 L45.39,4.47 L45.39,0.69 L28.69,0.69 Z M73.57,3.67 C71.57,2.25 68.92,0.11 64.05,0.11 C58.82,0.11 52.72,3.45 52.72,10.1 C52.72,16.63 57.95,20.08 64.27,20.08 C67.18,20.08 71.24,19.1 73.89,17.14 L72.19,13.65 C70.63,14.85 67.65,16.31 64.31,16.31 C58.9,16.31 56.5,13 56.5,10.21 C56.5,7.16 59.22,3.89 63.87,3.89 C67.54,3.89 70.12,5.96 71.35,6.97 L73.57,3.67 Z M92.96,20.08 C100.33,20.08 104.5,15.36 104.5,10.1 C104.5,4.79 100.4,0.11 92.96,0.11 C85.55,0.11 81.41,4.83 81.41,10.1 C81.41,15.36 85.59,20.08 92.96,20.08 Z M92.96,16.31 C88.27,16.31 85.19,13.36 85.19,10.1 C85.19,6.86 88.27,3.89 92.96,3.89 C97.64,3.89 100.73,6.83 100.73,10.1 C100.73,13.36 97.64,16.31 92.96,16.31 Z M113.94,0.69 L113.94,19.5 L124.15,19.5 C129.78,19.5 133.66,16.02 133.66,9.81 C133.66,2.8 128.47,0.69 124.15,0.69 L113.94,0.69 Z M117.72,4.47 L124.15,4.47 C127.09,4.47 129.88,5.59 129.88,10.02 C129.88,13.84 127.45,15.72 124.15,15.72 L117.72,15.72 L117.72,4.47 Z M142.63,0.69 L142.63,19.5 L159.77,19.5 L159.77,15.72 L146.41,15.72 L146.41,11.66 L155.93,11.66 L155.93,7.88 L146.41,7.88 L146.41,4.47 L159.33,4.47 L159.33,0.69 L142.63,0.69 Z" fill="#283273"/></svg>
727
  </div>
728
  <div class="header-center">
729
+ <h1>{'Association Network' if not safe_header else safe_header}</h1>
730
+ {'<div class="subtitle">Association Network</div>' if safe_header else ''}
731
  </div>
732
  <div class="legend-bar">
733
  <div class="legend-item"><div class="legend-dot reward"></div> Emotional</div>
 
750
  <button class="control-btn filter-btn" data-filter="emotional" onclick="setFilter('emotional')">Emotional</button>
751
  <button class="control-btn filter-btn" data-filter="functional" onclick="setFilter('functional')">Functional</button>
752
  </div>
753
+ <div class="connections-row">
754
+ <span class="connections-label">Connections:</span>
755
+ <select class="connections-select" id="maxL1Select" onchange="onMaxL1Change()">
756
+ <option value="2"{" selected" if default_max_l1 == 2 else ""}>2</option>
757
+ <option value="3"{" selected" if default_max_l1 == 3 else ""}>3</option>
758
+ <option value="4"{" selected" if default_max_l1 == 4 else ""}>4</option>
759
+ <option value="5"{" selected" if default_max_l1 == 5 else ""}>5</option>
760
+ <option value="6"{" selected" if default_max_l1 == 6 else ""}>6</option>
761
+ </select>
762
+ </div>
763
  </div>
764
  <div class="sidebar-list" id="sidebarList"></div>
765
  <div class="sidebar-stats"><span id="sidebarCount">{attribute_count}</span> attributes &middot; {reward_drivers} emotional &middot; {nonreward_drivers} functional</div>