"""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('','<\\/')
def generate_network_html(network_data, threshold, max_l1_nodes,
client_name, country_name, brand_name, category_name,
show_category_index=True, fallback_name=''):
"""Build the complete HTML file with vis.js network visualization.
Args:
network_data: Dict from parse_excel.extract_network_data()
threshold: Minimum correlation value to show as a connection
max_l1_nodes: Max number of Level 1 connections per node (default for in-HTML dropdown)
client_name, country_name, brand_name, category_name: Project metadata (all optional)
fallback_name: Fallback name from uploaded filename (used when no project details entered)
Returns:
(html_string, stats_dict, filename)
"""
corr_df = network_data['corr_df']
attribute_names = network_data['attribute_names']
nonrewards_attrs = network_data['nonrewards_attrs']
driver_names = network_data['driver_names']
attr_to_cat_idx = network_data['attr_to_cat_idx']
# Calculate statistics
all_positive_corrs = []
for col in corr_df.columns:
for val in corr_df[col]:
if val >= 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}
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.