hemsby commited on
Commit
9e039a4
·
1 Parent(s): a86665e

feat: redesign HTML output for cleaner UX

Browse files

- Light-fill nodes with colored borders instead of solid ellipses
- Emotional (red border), Functional (blue border), Selected (dark)
- Technical details moved to slide-up panel behind Details button
- Clean header bar with inline legend, full-height canvas
- Better edge colors and hover tooltips
- Add CLAUDE.md with full project documentation
- Add .gitignore for sample_data/

Files changed (3) hide show
  1. .gitignore +2 -0
  2. CLAUDE.md +121 -0
  3. app.py +226 -61
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Sample/client data (not committed)
2
+ sample_data/
CLAUDE.md ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # network_html — Correlation Network Generator
2
+
3
+ Streamlit app that generates interactive HTML network visualizations from brand association correlation matrices. Used by DECODE consultants to explore how implicit brand attributes are interconnected.
4
+
5
+ ## What It Does
6
+
7
+ In DECODE's implicit testing (SAT/MAT), respondents associate brands with attributes. The correlation files capture how these associations co-occur across respondents — if people who link a brand to "adventure" also link it to "refreshment", those attributes are correlated. This app visualizes those correlation structures as interactive networks.
8
+
9
+ ### Domain Concepts
10
+
11
+ - **Rewards** (emotional/motivational attributes) — from DECODE's territory system: Adventure, Autonomy, Discipline, Security, Enjoyment, Excitement (6 standard) or extended 10-territory model (GreaterGood, Caring, Acceptance, Control, Security, SelfPromotion, Achievement, Enjoyment, Excitement, Freedom)
12
+ - **Nonrewards** (functional/product attributes) — category-specific like "good taste", "healthy", "affordable"
13
+ - **Category Index** — importance score for each attribute
14
+ - **Deviation values** — differences from expected correlation (positive = above average association). The app uses deviations, not absolute means, because deviations show what's *distinctive*
15
+
16
+ ### Output
17
+
18
+ A standalone HTML file with a vis.js hierarchical network:
19
+ - **Level 0**: Selected driver attribute (user picks from dropdown)
20
+ - **Level 1**: Top N directly correlated attributes (above threshold)
21
+ - **Level 2**: Secondary correlations from L1 nodes
22
+ - **Red nodes** = Rewards (emotional), **Blue nodes** = Nonrewards (functional)
23
+ - **Node size** = Category Index, **Edge thickness** = correlation strength
24
+
25
+ ## Tech Stack
26
+
27
+ - Python 3 / Streamlit 1.28+
28
+ - pandas + openpyxl (Excel parsing)
29
+ - vis.js 4.21 + Select2 + jQuery (in generated HTML output)
30
+ - Deployed on HuggingFace Spaces (DecodeMarketing org)
31
+
32
+ ## Files
33
+
34
+ ```
35
+ app.py # Everything: parsing, classification, HTML generation, Streamlit UI (586 lines)
36
+ requirements.txt # streamlit, pandas, numpy, openpyxl
37
+ Dockerfile # Python 3.13.5-slim, port 8501 (NOTE: entrypoint wrong, see Known Issues)
38
+ README.md # HuggingFace Spaces metadata + brief docs
39
+ src/streamlit_app.py # DEAD CODE — Streamlit template placeholder, not used
40
+ sample_data/ # Test xlsx files (gitignored, client data)
41
+ .gitignore # Excludes sample_data/
42
+ ```
43
+
44
+ ## Excel File Format ("Results Correls" sheet)
45
+
46
+ All correlation files follow the same layout:
47
+
48
+ ```
49
+ Row 4: Section headers — territory names, brand names
50
+ Row 5: Column headers — variable codes (used as correlation matrix column IDs)
51
+
52
+ BLOCK 1 (rows 6–N): Mean values (absolute, centered ~100)
53
+ [7-8 empty rows gap]
54
+ BLOCK 2 (rows N+8–end): DEVIATION values (what the app uses)
55
+ ```
56
+
57
+ Each data row:
58
+ - **Col A**: Row number
59
+ - **Col B**: Variable code (`FCMARKENMAT_PA_Abenteuer_Abenteuer` or `FCBRANDMAT_PA_GreaterGood_carefortheplanet`)
60
+ - **Col C**: Display name (human-readable attribute)
61
+ - **Col D**: Category Index (importance score)
62
+ - **Col E**: Empty gap
63
+ - **Cols F–K/O**: Territory mean/deviation values
64
+ - **Col 25+ (DE) or 33+ (EN)**: Square correlation matrix (attribute x attribute)
65
+
66
+ ### Variable Code Format
67
+
68
+ `PREFIX_PA_Territory_AttributeName` where:
69
+ - Prefix: `FCMARKENMAT` (DE BGO), `FCBRANDMAT` (EN iBHDD), `FCMARKENMODUL` (DE Retailer)
70
+ - Territory: one of the 6 or 10 reward territories, or a functional category
71
+ - Classification: if territory is in `REWARDS_FACTORS` list → Reward (red), otherwise → Nonreward (blue)
72
+
73
+ ### German vs English Files
74
+
75
+ | Aspect | German (Korrelationen) | English (Correlations) |
76
+ |---|---|---|
77
+ | Territories | 6 (Abenteuer, Autonomie, Disziplin, Sicherheit, Genuss, Erregung) | 10 (GreaterGood, Caring, Acceptance, Control, Security, SelfPromotion, Achievement, Enjoyment, Excitement, Freedom) |
78
+ | Correlation matrix starts | Col 25 (Y) | Col 33 (AG) |
79
+ | Code prefix | FCMARKENMAT / FCMARKENMODUL | FCBRANDMAT |
80
+ | Non-reward naming | Explicit categories (funktional, features, Qualitaet, etc.) | Single "Nonrewards" territory |
81
+
82
+ ### Per-Brand Sections
83
+
84
+ After the "mean across all brands" correlation matrix, each brand gets its own section with the same matrix structure. Currently the app only uses "mean across all brands".
85
+
86
+ ## Auto-Detection Logic
87
+
88
+ The app tries to auto-detect 3 parameters:
89
+
90
+ 1. **DATA_START_ROW** (`detect_data_start_row`): Finds the 2nd text block in column B — this is always the deviation data block. Works reliably.
91
+ 2. **CORR_COL_START** (`detect_correlation_column_start`): Finds the first block of >50 consecutive non-empty cells in row 5. Works reliably.
92
+ 3. **CORR_THRESHOLD** (`detect_cutoff_value`): Searches for "cut-off used in columns" text in column B. **Always fails** on real files — defaults to 6.0.
93
+
94
+ ## How to Run
95
+
96
+ ```bash
97
+ pip install -r requirements.txt
98
+ streamlit run app.py
99
+ # Opens at http://localhost:8501
100
+ ```
101
+
102
+ ## Sample Data
103
+
104
+ 4 test files in `sample_data/` (gitignored):
105
+
106
+ | File | Client | Country | Type | Attributes | Brands |
107
+ |---|---|---|---|---|---|
108
+ | `118014-45_Hassia_..._Korrelationen_...xlsx` | Hassia | DE | BGO | 114 | 11 |
109
+ | `126007-400_P&G_MX_..._Correlations_...xlsx` | P&G | MX | iBHDD | 82 | 6 |
110
+ | `126007-401_P&G_..._UK_..._Correlations_...xlsx` | P&G | UK | iBHDD | 83 | 9 |
111
+ | `128003-23_REWE_..._Correlations_...xlsx` | REWE | DE | Retailer BGO | 80 | 8 |
112
+
113
+ ## Known Issues
114
+
115
+ 1. **Dockerfile entrypoint wrong** — references `src/streamlit_app.py` (template demo), should be `app.py`
116
+ 2. **`src/streamlit_app.py` is dead code** — Streamlit template placeholder, should be removed
117
+ 3. **Cut-off detection always fails** — none of the real files contain "cut-off used in columns" text
118
+ 4. **`REWARDS_FACTORS` hardcoded** — inline list of territory names, not synced with canonical 60-attribute list
119
+ 5. **Rewards classification is territory-level** — checks 3rd part of variable code against territory names, not individual attributes
120
+ 6. **Per-brand matrices ignored** — only "mean across all brands" is used
121
+ 7. **All 586 lines in one file** — parsing, classification, HTML generation, and UI all in `app.py`
app.py CHANGED
@@ -201,8 +201,48 @@ def generate_network_html(df, data_start_row, corr_col_start, threshold, max_l1_
201
  return '\n'.join(wrapper.wrap(text=driver))
202
  return driver
203
 
204
- def get_color(name):
205
- return "lightskyblue" if name in nonrewards_attrs else "red"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
 
207
  def scale_edge(corr_val):
208
  if max_corr == min_corr:
@@ -219,9 +259,13 @@ def generate_network_html(df, data_start_row, corr_col_start, threshold, max_l1_
219
  cat_idx = attr_to_cat_idx.get(selected, 100)
220
  nodes.append({
221
  'id': selected,
222
- 'label': wrap_label(selected) + '\n (' + str(int(cat_idx)) + ')',
223
- 'level': 0, 'value': int(cat_idx), 'title': selected,
224
- 'color': get_color(selected), 'font': {'color': 'white'}, 'shape': 'box'
 
 
 
 
225
  })
226
 
227
  l1_nodes = []
@@ -234,14 +278,19 @@ def generate_network_html(df, data_start_row, corr_col_start, threshold, max_l1_
234
  l1_nodes.append(attr)
235
  cat = attr_to_cat_idx.get(attr, 100)
236
  nodes.append({
237
- 'id': attr, 'label': wrap_label(attr) + '\n (' + str(int(cat)) + ')',
238
- 'level': 1, 'value': int(cat), 'title': attr, 'color': get_color(attr)
 
 
 
 
239
  })
240
  ep = scale_edge(val)
241
  edges.append({
242
  'from': selected, 'to': attr, 'value': float(val),
243
- 'width': ep['width'], 'color': {'opacity': ep['opacity']},
244
- 'title': f'normalized value: {val:.2f}'
 
245
  })
246
 
247
  l2_added = set()
@@ -256,15 +305,20 @@ def generate_network_html(df, data_start_row, corr_col_start, threshold, max_l1_
256
  if attr not in l2_added:
257
  cat = attr_to_cat_idx.get(attr, 100)
258
  nodes.append({
259
- 'id': attr, 'label': wrap_label(attr) + '\n (' + str(int(cat)) + ')',
260
- 'level': 2, 'value': int(cat), 'title': attr, 'color': get_color(attr)
 
 
 
 
261
  })
262
  l2_added.add(attr)
263
  ep = scale_edge(val)
264
  edges.append({
265
  'from': l1, 'to': attr, 'value': float(val),
266
- 'width': ep['width'], 'color': {'opacity': ep['opacity']},
267
- 'title': f'normalized value: {val:.2f}'
 
268
  })
269
 
270
  return nodes, edges
@@ -280,88 +334,199 @@ def generate_network_html(df, data_start_row, corr_col_start, threshold, max_l1_
280
 
281
  chart_title = f"DECODE_{client_name}_{country_name}_{brand_name}"
282
 
 
 
 
 
 
 
 
 
 
 
283
  # HTML template
284
- html_template = """
285
- <!DOCTYPE html>
286
- <meta charset="utf-8">
287
- <html lang="en-US">
288
  <head>
 
 
289
  <link type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css" rel="stylesheet" />
290
  <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
291
  <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
292
  <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
293
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
294
  <style>
295
- #mynetwork { width: 100%; height: 800px; border: 1px solid lightgray; }
296
- body { font-family: Arial, sans-serif; margin: 20px; }
297
- .controls { margin: 20px 0; padding: 10px; background: #f5f5f5; border-radius: 5px; display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
298
- .select2-container { min-width: 350px; }
299
- .select2-container .select2-selection--single { height: 36px; padding: 3px 0; }
300
- .select2-container--default .select2-selection--single .select2-selection__rendered { line-height: 30px; }
 
 
 
 
 
 
 
 
 
301
  .select2-container--default .select2-selection--single .select2-selection__arrow { height: 34px; }
302
- .info { margin: 10px 0; padding: 10px; background: #e8f4f8; border-left: 4px solid #0078d4; }
303
- .legend { margin: 10px 0; padding: 10px; background: #fff3cd; border-left: 4px solid #ffc107; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
  </style>
305
  <script>
306
  var nodes = """ + json.dumps(all_nodes) + """;
307
  var edges = """ + json.dumps(all_edges) + """;
308
  var network = null;
 
309
  function destroy() { if (network !== null) { network.destroy(); network = null; } }
 
310
  function draw(id) {
311
  destroy();
312
  var data = { nodes: nodes[id], edges: edges[id] };
313
  var options = {
314
- nodes: { scaling: { min: 20, max: 80, label: { enabled: true, min: 12, max: 24 } }, font: { size: 14 }, margin: 10 },
315
- edges: { smooth: { type: 'cubicBezier', forceDirection: 'vertical', roundness: 0.4 }, shadow: true, color: { inherit: 'from' } },
316
- 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 } },
317
- interaction: { zoomView: true, dragView: true, hover: true, tooltipDelay: 100 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  };
319
  network = new vis.Network(document.getElementById('mynetwork'), data, options);
320
  document.getElementById('nodeCount').textContent = data.nodes.length;
321
  document.getElementById('edgeCount').textContent = data.edges.length;
322
  }
 
 
 
 
 
 
 
 
323
  $(document).ready(function() {
324
- $('#driver_select').select2({
325
- placeholder: 'Search for a driver...',
326
- allowClear: false
327
- });
328
- $('#driver_select').on('change', function() {
329
- draw($(this).val());
330
- });
331
  draw(0);
332
  });
333
  </script>
334
  </head>
335
- <body>
336
- <h1>""" + chart_title + """ - Correlation Network (Threshold: """ + str(threshold) + """)</h1>
337
- <div class="info">
338
- <strong>Info:</strong> Network shows normalized deviation values >= """ + str(threshold) + """.<br>
339
- Red nodes = Rewards (emotional), Blue nodes = Functional/Nonrewards.<br>
340
- Node size based on Category Index.<br>
341
- <strong>Data type:</strong> Deviation from expected value (positive = above average)
342
- </div>
343
- <div class="legend">
344
- <strong>Edge Visualization:</strong> Line thickness and opacity indicate correlation strength.<br>
345
- Thicker/darker lines = stronger correlations. Hover over edges to see exact normalized values.<br>
346
- <strong>Scaling:</strong> Avg: """ + f"{avg_corr:.2f}" + """, Max: """ + f"{max_corr:.2f}" + """
 
 
347
  </div>
348
- <div class="controls">
349
- <label>Select Driver:</label>
350
- <select id="driver_select">
351
- """
352
 
353
- for i, nodes_list in enumerate(all_nodes):
354
- if nodes_list:
355
- html_template += f'<option value="{i}">{nodes_list[0]["id"]} ({len(nodes_list)} nodes)</option>\n'
 
 
 
 
 
356
 
357
- html_template += """
358
- </select>
359
- <span style="margin-left:20px;">Nodes: <strong id="nodeCount">0</strong> | Edges: <strong id="edgeCount">0</strong></span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
360
  </div>
361
- <div id="mynetwork"></div>
362
  </body>
363
- </html>
364
- """
365
 
366
  stats = {
367
  'drivers': len(available_drivers),
 
201
  return '\n'.join(wrapper.wrap(text=driver))
202
  return driver
203
 
204
+ # Color palette — outline-based nodes
205
+ REWARD_COLOR = '#E03E3E' # warm red
206
+ NONREWARD_COLOR = '#2B7AB2' # steel blue
207
+ REWARD_BORDER = '#C02020'
208
+ NONREWARD_BORDER = '#1A5C8A'
209
+ REWARD_BG = '#FDEAEA' # very light red fill
210
+ NONREWARD_BG = '#E8F1F8' # very light blue fill
211
+ DRIVER_BG = '#2B2B2B' # dark background for selected driver
212
+ DRIVER_BORDER = '#000000'
213
+ DRIVER_FONT = '#FFFFFF'
214
+
215
+ def get_node_colors(name, is_driver=False):
216
+ if is_driver:
217
+ is_reward = name not in nonrewards_attrs
218
+ border = REWARD_BORDER if is_reward else NONREWARD_BORDER
219
+ return {
220
+ 'background': DRIVER_BG,
221
+ 'border': border,
222
+ 'highlight': {'background': '#444444', 'border': border},
223
+ 'hover': {'background': '#444444', 'border': border}
224
+ }
225
+ if name in nonrewards_attrs:
226
+ return {
227
+ 'background': NONREWARD_BG,
228
+ 'border': NONREWARD_BORDER,
229
+ 'highlight': {'background': '#D0E4F0', 'border': NONREWARD_BORDER},
230
+ 'hover': {'background': '#D0E4F0', 'border': NONREWARD_BORDER}
231
+ }
232
+ return {
233
+ 'background': REWARD_BG,
234
+ 'border': REWARD_BORDER,
235
+ 'highlight': {'background': '#F8D0D0', 'border': REWARD_BORDER},
236
+ 'hover': {'background': '#F8D0D0', 'border': REWARD_BORDER}
237
+ }
238
+
239
+ def get_font_color(name, is_driver=False):
240
+ if is_driver:
241
+ return DRIVER_FONT
242
+ return REWARD_BORDER if name not in nonrewards_attrs else NONREWARD_BORDER
243
+
244
+ def get_edge_color(name):
245
+ return REWARD_COLOR if name not in nonrewards_attrs else NONREWARD_COLOR
246
 
247
  def scale_edge(corr_val):
248
  if max_corr == min_corr:
 
259
  cat_idx = attr_to_cat_idx.get(selected, 100)
260
  nodes.append({
261
  'id': selected,
262
+ 'label': wrap_label(selected) + '\n(' + str(int(cat_idx)) + ')',
263
+ 'level': 0, 'value': int(cat_idx), 'title': selected + ' — Category Index: ' + str(int(cat_idx)),
264
+ 'color': get_node_colors(selected, is_driver=True),
265
+ 'font': {'color': DRIVER_FONT, 'size': 16, 'bold': True},
266
+ 'shape': 'box',
267
+ 'borderWidth': 3,
268
+ 'borderWidthSelected': 4,
269
  })
270
 
271
  l1_nodes = []
 
278
  l1_nodes.append(attr)
279
  cat = attr_to_cat_idx.get(attr, 100)
280
  nodes.append({
281
+ 'id': attr, 'label': wrap_label(attr) + '\n(' + str(int(cat)) + ')',
282
+ 'level': 1, 'value': int(cat),
283
+ 'title': attr + ' — Category Index: ' + str(int(cat)) + ', Correlation: ' + f'{val:.1f}',
284
+ 'color': get_node_colors(attr),
285
+ 'font': {'color': get_font_color(attr), 'size': 14},
286
+ 'borderWidth': 2,
287
  })
288
  ep = scale_edge(val)
289
  edges.append({
290
  'from': selected, 'to': attr, 'value': float(val),
291
+ 'width': ep['width'],
292
+ 'color': {'color': get_edge_color(selected), 'opacity': ep['opacity'], 'highlight': get_edge_color(selected)},
293
+ 'title': f'{selected} ↔ {attr}: {val:.1f}'
294
  })
295
 
296
  l2_added = set()
 
305
  if attr not in l2_added:
306
  cat = attr_to_cat_idx.get(attr, 100)
307
  nodes.append({
308
+ 'id': attr, 'label': wrap_label(attr) + '\n(' + str(int(cat)) + ')',
309
+ 'level': 2, 'value': int(cat),
310
+ 'title': attr + ' — Category Index: ' + str(int(cat)) + ', Correlation: ' + f'{val:.1f}',
311
+ 'color': get_node_colors(attr),
312
+ 'font': {'color': get_font_color(attr), 'size': 13},
313
+ 'borderWidth': 2,
314
  })
315
  l2_added.add(attr)
316
  ep = scale_edge(val)
317
  edges.append({
318
  'from': l1, 'to': attr, 'value': float(val),
319
+ 'width': ep['width'],
320
+ 'color': {'color': get_edge_color(l1), 'opacity': ep['opacity'], 'highlight': get_edge_color(l1)},
321
+ 'title': f'{l1} ↔ {attr}: {val:.1f}'
322
  })
323
 
324
  return nodes, edges
 
334
 
335
  chart_title = f"DECODE_{client_name}_{country_name}_{brand_name}"
336
 
337
+ # Build driver options HTML
338
+ driver_options = ""
339
+ for i, nodes_list in enumerate(all_nodes):
340
+ if nodes_list:
341
+ driver_options += f'<option value="{i}">{nodes_list[0]["id"]}</option>\n'
342
+
343
+ # Count rewards vs nonrewards in drivers
344
+ reward_drivers = sum(1 for d in available_drivers if d not in nonrewards_attrs)
345
+ nonreward_drivers = len(available_drivers) - reward_drivers
346
+
347
  # HTML template
348
+ html_template = """<!DOCTYPE html>
349
+ <html lang="en">
 
 
350
  <head>
351
+ <meta charset="utf-8">
352
+ <title>""" + chart_title + """ — Association Network</title>
353
  <link type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css" rel="stylesheet" />
354
  <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
355
  <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
356
  <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
357
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
358
  <style>
359
+ * { box-sizing: border-box; margin: 0; padding: 0; }
360
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f8f9fa; color: #333; }
361
+
362
+ /* Header */
363
+ .header { background: #fff; border-bottom: 1px solid #e0e0e0; padding: 16px 24px; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; }
364
+ .header-left h1 { font-size: 18px; font-weight: 600; color: #1a1a1a; }
365
+ .header-left .subtitle { font-size: 13px; color: #888; margin-top: 2px; }
366
+ .header-right { display: flex; align-items: center; gap: 16px; }
367
+
368
+ /* Toolbar */
369
+ .toolbar { background: #fff; border-bottom: 1px solid #e0e0e0; padding: 10px 24px; display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
370
+ .toolbar label { font-size: 13px; font-weight: 500; color: #555; }
371
+ .select2-container { min-width: 320px; }
372
+ .select2-container .select2-selection--single { height: 36px; border-radius: 6px; border-color: #ccc; }
373
+ .select2-container--default .select2-selection--single .select2-selection__rendered { line-height: 34px; font-size: 14px; padding-left: 12px; }
374
  .select2-container--default .select2-selection--single .select2-selection__arrow { height: 34px; }
375
+ .select2-results__option { font-size: 14px; }
376
+ .stat { font-size: 13px; color: #888; }
377
+ .stat strong { color: #333; }
378
+
379
+ /* Legend (inline, compact) */
380
+ .legend-bar { display: flex; align-items: center; gap: 16px; margin-left: auto; }
381
+ .legend-item { display: flex; align-items: center; gap: 5px; font-size: 12px; color: #666; }
382
+ .legend-dot { width: 12px; height: 12px; border-radius: 3px; border: 2px solid; }
383
+ .legend-dot.reward { border-color: #C02020; background: #FDEAEA; }
384
+ .legend-dot.nonreward { border-color: #1A5C8A; background: #E8F1F8; }
385
+ .legend-dot.driver { border-color: #000; background: #2B2B2B; }
386
+
387
+ /* Network canvas */
388
+ #mynetwork { width: 100%; height: calc(100vh - 130px); background: #fff; }
389
+
390
+ /* Tabs */
391
+ .tabs { position: absolute; bottom: 16px; left: 24px; z-index: 10; display: flex; gap: 4px; }
392
+ .tab-btn { padding: 6px 14px; font-size: 12px; font-weight: 500; border: 1px solid #ddd; background: #fff; border-radius: 6px; cursor: pointer; color: #555; transition: all 0.15s; }
393
+ .tab-btn:hover { background: #f0f0f0; }
394
+ .tab-btn.active { background: #333; color: #fff; border-color: #333; }
395
+
396
+ /* Details panel (slide-up) */
397
+ .details-panel { position: absolute; bottom: 0; left: 0; right: 0; z-index: 20; background: #fff; border-top: 1px solid #e0e0e0; box-shadow: 0 -4px 20px rgba(0,0,0,0.08); transform: translateY(100%); transition: transform 0.25s ease; max-height: 45vh; overflow-y: auto; }
398
+ .details-panel.open { transform: translateY(0); }
399
+ .details-header { display: flex; align-items: center; justify-content: space-between; padding: 12px 24px; border-bottom: 1px solid #eee; position: sticky; top: 0; background: #fff; }
400
+ .details-header h3 { font-size: 14px; font-weight: 600; }
401
+ .details-close { background: none; border: none; font-size: 18px; cursor: pointer; color: #888; padding: 4px 8px; border-radius: 4px; }
402
+ .details-close:hover { background: #f0f0f0; }
403
+ .details-body { padding: 16px 24px; }
404
+ .details-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; }
405
+ .detail-card { padding: 12px; border: 1px solid #eee; border-radius: 8px; background: #fafafa; }
406
+ .detail-card h4 { font-size: 12px; font-weight: 600; color: #888; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 6px; }
407
+ .detail-card p { font-size: 13px; line-height: 1.5; color: #444; }
408
+ .detail-card .val { font-size: 20px; font-weight: 600; color: #1a1a1a; }
409
+
410
+ /* Canvas wrapper (for relative positioning of tabs) */
411
+ .canvas-wrap { position: relative; flex: 1; }
412
  </style>
413
  <script>
414
  var nodes = """ + json.dumps(all_nodes) + """;
415
  var edges = """ + json.dumps(all_edges) + """;
416
  var network = null;
417
+
418
  function destroy() { if (network !== null) { network.destroy(); network = null; } }
419
+
420
  function draw(id) {
421
  destroy();
422
  var data = { nodes: nodes[id], edges: edges[id] };
423
  var options = {
424
+ nodes: {
425
+ shape: 'box',
426
+ scaling: { min: 20, max: 80, label: { enabled: true, min: 11, max: 20 } },
427
+ font: { size: 14, face: '-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif', multi: 'md' },
428
+ margin: { top: 8, bottom: 8, left: 12, right: 12 },
429
+ shadow: { enabled: true, color: 'rgba(0,0,0,0.08)', size: 6, x: 0, y: 2 },
430
+ shapeProperties: { borderRadius: 6 }
431
+ },
432
+ edges: {
433
+ smooth: { type: 'cubicBezier', forceDirection: 'vertical', roundness: 0.4 },
434
+ shadow: false,
435
+ hoverWidth: 1.5
436
+ },
437
+ physics: {
438
+ enabled: true,
439
+ solver: 'hierarchicalRepulsion',
440
+ hierarchicalRepulsion: { nodeDistance: 280, centralGravity: 0.0, springLength: 280, springConstant: 0.01, damping: 0.09, avoidOverlap: 1 },
441
+ stabilization: { enabled: true, iterations: 1000 }
442
+ },
443
+ interaction: { zoomView: true, dragView: true, hover: true, tooltipDelay: 200 },
444
+ layout: { hierarchical: false }
445
  };
446
  network = new vis.Network(document.getElementById('mynetwork'), data, options);
447
  document.getElementById('nodeCount').textContent = data.nodes.length;
448
  document.getElementById('edgeCount').textContent = data.edges.length;
449
  }
450
+
451
+ function toggleDetails() {
452
+ var panel = document.getElementById('detailsPanel');
453
+ var btn = document.getElementById('detailsBtn');
454
+ panel.classList.toggle('open');
455
+ btn.classList.toggle('active');
456
+ }
457
+
458
  $(document).ready(function() {
459
+ $('#driver_select').select2({ placeholder: 'Search for an attribute...', allowClear: false });
460
+ $('#driver_select').on('change', function() { draw($(this).val()); });
 
 
 
 
 
461
  draw(0);
462
  });
463
  </script>
464
  </head>
465
+ <body style="display:flex; flex-direction:column; height:100vh; overflow:hidden;">
466
+
467
+ <div class="header">
468
+ <div class="header-left">
469
+ <h1>""" + chart_title + """</h1>
470
+ <div class="subtitle">Association Network</div>
471
+ </div>
472
+ <div class="header-right">
473
+ <div class="legend-bar">
474
+ <div class="legend-item"><div class="legend-dot reward"></div> Emotional</div>
475
+ <div class="legend-item"><div class="legend-dot nonreward"></div> Functional</div>
476
+ <div class="legend-item"><div class="legend-dot driver"></div> Selected</div>
477
+ </div>
478
+ </div>
479
  </div>
 
 
 
 
480
 
481
+ <div class="toolbar">
482
+ <label>Attribute:</label>
483
+ <select id="driver_select">
484
+ """ + driver_options + """
485
+ </select>
486
+ <span class="stat">Nodes: <strong id="nodeCount">0</strong></span>
487
+ <span class="stat">Edges: <strong id="edgeCount">0</strong></span>
488
+ </div>
489
 
490
+ <div class="canvas-wrap">
491
+ <div id="mynetwork"></div>
492
+ <div class="tabs">
493
+ <button class="tab-btn" id="detailsBtn" onclick="toggleDetails()">Details</button>
494
+ </div>
495
+ <div class="details-panel" id="detailsPanel">
496
+ <div class="details-header">
497
+ <h3>Technical Details</h3>
498
+ <button class="details-close" onclick="toggleDetails()">&times;</button>
499
+ </div>
500
+ <div class="details-body">
501
+ <div class="details-grid">
502
+ <div class="detail-card">
503
+ <h4>Threshold</h4>
504
+ <div class="val">""" + str(threshold) + """</div>
505
+ <p>Only associations above this deviation value are shown as connections.</p>
506
+ </div>
507
+ <div class="detail-card">
508
+ <h4>Attributes</h4>
509
+ <div class="val">""" + str(len(attribute_names)) + """</div>
510
+ <p>""" + str(reward_drivers) + """ emotional (rewards) and """ + str(nonreward_drivers) + """ functional (nonrewards) attributes.</p>
511
+ </div>
512
+ <div class="detail-card">
513
+ <h4>Connections</h4>
514
+ <div class="val">""" + str(len(all_positive_corrs)) + """</div>
515
+ <p>Total attribute pairs above threshold. Avg: """ + f"{avg_corr:.1f}" + """, Max: """ + f"{max_corr:.1f}" + """</p>
516
+ </div>
517
+ <div class="detail-card">
518
+ <h4>How to Read</h4>
519
+ <p>Each node is a brand association. Lines connect associations that co-occur above average.
520
+ Thicker lines = stronger co-occurrence. Node size reflects Category Index (importance).
521
+ Hover over nodes and lines for details.</p>
522
+ </div>
523
+ </div>
524
+ </div>
525
+ </div>
526
  </div>
527
+
528
  </body>
529
+ </html>"""
 
530
 
531
  stats = {
532
  'drivers': len(available_drivers),