"""Generate interactive HTML network visualization from parsed correlation data.""" import html import json from pathlib import Path import numpy as np from config import COLORS def _export_js(name): """The PowerPoint export's code, inlined into the HTML (one file, no server).""" js = (Path(__file__).parent / name).read_text(encoding='utf-8') if ' sequences for safe embedding in HTML.""" return json.dumps(obj).replace('= threshold: all_positive_corrs.append(val) if all_positive_corrs: avg_corr = float(np.mean(all_positive_corrs)) max_corr = float(np.max(all_positive_corrs)) min_corr = float(threshold) else: avg_corr = max_corr = min_corr = float(threshold) # --- Build sparse deviation matrix (only above-threshold pairs) --- # Directed: the key is "source,target". The source attribute supplies the COLUMN # and the target supplies the ROW, because the deviation matrix is asymmetric — # an attribute's associations are read down its own column. Storing only one # triangle would let the alphabetical sort above decide which of the two values # is used. See docs/deviation-direction.md. attr_list = sorted(driver_names, key=lambda x: x.lower()) sparse_corr = {} for i, source in enumerate(attr_list): if source not in corr_df.columns: continue for j, target in enumerate(attr_list): if i == j or target not in corr_df.index: continue val = float(corr_df.loc[target, source]) if val >= threshold: sparse_corr[f"{i},{j}"] = round(val, 1) # Build attribute metadata array (parallel to attr_list) attr_meta = [] for name in attr_list: cat_idx = int(attr_to_cat_idx.get(name, 100)) is_reward = name not in nonrewards_attrs attr_meta.append({ 'name': name, 'catIdx': cat_idx, 'isReward': is_reward, }) # Build driver list with index references for sidebar driver_list = [] for i, meta in enumerate(attr_meta): driver_list.append({ 'name': meta['name'], 'catIdx': meta['catIdx'], 'isReward': meta['isReward'], 'index': i, }) # Count rewards vs nonrewards reward_drivers = sum(1 for m in attr_meta if m['isReward']) nonreward_drivers = len(attr_meta) - reward_drivers # Build title from filled-in fields only detail_parts = [p for p in [client_name, brand_name, country_name, category_name] if p] if detail_parts: chart_title = 'DECODE_' + '_'.join(detail_parts) header_title = ' \u00b7 '.join(detail_parts) # · separator elif fallback_name: chart_title = fallback_name header_title = fallback_name.replace('_', ' ') else: chart_title = 'Association_Network' header_title = '' # Clamp default max_l1 to dropdown range (2-6) default_max_l1 = max(2, min(6, max_l1_nodes)) # --- HTML template --- html_out = _build_html_template( chart_title=chart_title, header_title=header_title, sparse_corr=sparse_corr, attr_meta=attr_meta, driver_list=driver_list, nonrewards_list=sorted(nonrewards_attrs), threshold=threshold, min_corr=min_corr, max_corr=max_corr, attribute_count=len(attribute_names), reward_drivers=reward_drivers, nonreward_drivers=nonreward_drivers, corr_count=len(all_positive_corrs), avg_corr=avg_corr, default_max_l1=default_max_l1, show_category_index=show_category_index, project={'client': client_name or '', 'country': country_name or '', 'brand': brand_name or '', 'category': category_name or ''}, ) stats = { 'drivers': len(attr_list), 'attributes': len(attribute_names), 'rewards': len(attribute_names) - len(nonrewards_attrs), 'nonrewards': len(nonrewards_attrs), 'positive_correlations': len(all_positive_corrs), } if detail_parts or fallback_name: filename = f"{chart_title}_Correlation_Network.html" else: filename = "Correlation_Network.html" return html_out, stats, filename def _build_html_template(*, chart_title, header_title, sparse_corr, attr_meta, driver_list, nonrewards_list, threshold, min_corr, max_corr, attribute_count, reward_drivers, nonreward_drivers, corr_count, avg_corr, default_max_l1, show_category_index, project=None): """Build the standalone HTML string. Separated for readability.""" # Escape all user-supplied strings for safe HTML embedding h = html.escape safe_title = h(chart_title) safe_header = h(header_title) # JSON data for script block (escape sequences) corr_json = _safe_json(sparse_corr) meta_json = _safe_json(attr_meta) drivers_json = _safe_json(driver_list) nonrewards_json = _safe_json(nonrewards_list) project_json = _safe_json(project or {}) title_json = _safe_json(chart_title) return f""" {safe_title} — Association Network

{'Association Network' if not safe_header else safe_header}

{'
Association Network
' if safe_header else ''}
Emotional
Functional
Selected
Attributes: 0 Connections: 0

Connections in network

Technical Details

Threshold

{threshold}

Only associations above this deviation value are shown as connections.

Attributes

{attribute_count}

{reward_drivers} emotional (rewards) and {nonreward_drivers} functional (nonrewards) attributes.

Connections

{corr_count}

Total attribute pairs above threshold. Avg: {avg_corr:.1f}, Max: {max_corr:.1f}

How to Read

Each node is a brand association. Lines connect associations that co-occur above average. Thicker lines = stronger co-occurrence. Node size reflects Category Index (importance). Hover over nodes and lines for details.

""".replace('__PPTX_EXPORT_JS__', _export_js('pptx_export.js')).replace('__PPTX_EXPORT_UI_JS__', _export_js('pptx_export_ui.js'))