"""Parse IcAT Excel results files. Expected sheet: 'MAT Branding + BPS (per Block)' Layout: Row 0: Project title + column group headers Row 1: Sub-headers (Total, correct brand, Uniqueness, etc.) Row 2: Brand names in columns 1..N Row 3: Number of cases Row 4: relevante Mittelwert Row 5: MAXIMUM (theoretisches Max.) Row 6: Iconic Threshold Row 7: (empty) Row 8+: Data rows — mix of: - Brand means: "REWE mean", "EDEKA mean", ... - Block headers: "#03 Symbole in schwarz-weiß mean" - Properties: "01B03rewe06bonussmilingcoinsw" (individual stimuli) Property naming convention: NNBNNbrandNNdescription ^ ^ ^ ^ ^ | | | | stimulus description | | | stimulus number within block | | brand name (lowercase) | block number brand code (01=rewe, 02=aldi, etc.) Key columns (Total section): 0: Property name / label 1..B: Brand attribution percentages (one column per brand) B+1: correct brand (%) B+2: Uniqueness (correct brand - next highest) B+3: Certainty (sum all brands) B+4: Index inverted B+5: correct brand weighted with certainty B+6: BPS (Brand Property Score) """ import re import unicodedata import openpyxl import pandas as pd def _unmerge_header_rows(excel_path, sheet_name, max_row=4): """Unmerge cells in header rows using openpyxl. For each merged range in the first `max_row` rows (1-based), fills every cell in the range with the top-left cell's value. Only rows 1-2 (group names + level names) are unmerged. Row 3 (brand names) is left alone — brand detection relies on empty cells after the last brand. Returns a pandas DataFrame with clean (unmerged) data. """ wb = openpyxl.load_workbook(excel_path, data_only=True) ws = wb[sheet_name] # Collect merges that touch header rows 1-2 only, then unmerge + fill header_merges = [m for m in list(ws.merged_cells.ranges) if m.min_row <= max_row] for merge_range in header_merges: # Read value before unmerging (only top-left cell has it) val = ws.cell(merge_range.min_row, merge_range.min_col).value ws.unmerge_cells(str(merge_range)) # Fill all cells in the former range for row in range(merge_range.min_row, merge_range.max_row + 1): for col in range(merge_range.min_col, merge_range.max_col + 1): ws.cell(row, col, val) # Convert to pandas DataFrame data = list(ws.values) wb.close() return pd.DataFrame(data) def _slugify(text): """Convert text to a simple slug key (lowercase, ascii-safe).""" # Normalize unicode, strip accents nfkd = unicodedata.normalize('NFKD', text) ascii_text = nfkd.encode('ascii', 'ignore').decode('ascii') # Lowercase, replace non-alnum with underscore, collapse slug = re.sub(r'[^a-z0-9]+', '_', ascii_text.lower()).strip('_') return slug or 'group' def _norm(text): """Normalize for matching: lowercase, unify dashes, collapse ALL unicode whitespace. Real overview sheets contain NBSP (\\xa0) mid-string and mix ASCII '-' with en-dash '–' — str.split() handles every unicode space.""" return ' '.join(re.sub(r'[-–—]', ' ', str(text)).lower().split()) def _clean(text): """Display cleanup: collapse unicode whitespace, keep case and dashes.""" return ' '.join(str(text).split()) # Questionnaire prefixes on group names: 'Q1 3 Geschlecht', 'Q1 7 1 Marken…', 'Q Age' _Q_PREFIX_RE = re.compile(r'^Q\s*\d*(?:\s+\d+)*\s+') def _strip_q_prefix(text): """Strip questionnaire prefixes like 'Q1 3 ', 'Q1 7 1 ', 'Q ' from a group name.""" cleaned = _Q_PREFIX_RE.sub('', _clean(text)).strip() return cleaned or _clean(text) def _warn(severity, code, message, **context): """Build a structured warning (phase-2 UI contract — see plan).""" w = {'severity': severity, 'code': code, 'message': message} ctx = {k: v for k, v in context.items() if v is not None} if ctx: w['context'] = ctx return w def _detect_overview_sheet(excel_path): """Find the breakout-overview sheet ('Übersicht Breakouts', 'Definition Breakouts', 'Breakout Overview', 'BO Overview', ...). Anchored on the word 'breakout'; 'BO' only counts as a standalone token next to 'overview' — never bare ('BO in Rows'/'BO Matrix' are Brand-Owner sheets, not breakouts). """ xls = pd.ExcelFile(excel_path) try: for name in xls.sheet_names: if 'breakout' in _norm(name): return name for name in xls.sheet_names: tokens = _norm(name).split() if 'overview' in tokens and 'bo' in tokens: return name return None finally: xls.close() def _parse_overview_rows(excel_path, sheet_name): """Parse a breakout-overview sheet into ordered (group, {col: label}) rows. Group names come from column A, forward-filled and Q-prefix-stripped. Title rows (project title with newlines) and header rows ('Variable|Codes|Definition', 'Frage|Merkmal|Definition', 'Quest-ID|Codes|…') are skipped. Which column holds the level labels is decided later by match coverage (_cluster_segments). """ df = pd.read_excel(excel_path, sheet_name=sheet_name, header=None) header_a = {'frage', 'variable', 'quest id', 'split', 'breakout'} start = 0 for r in range(min(10, df.shape[0])): norms = [_norm(df.iloc[r, c]) if pd.notna(df.iloc[r, c]) else '' for c in range(min(df.shape[1], 6))] if 'codes' in norms or (norms and norms[0] in header_a): start = r + 1 break rows = [] group = None for r in range(start, df.shape[0]): a = df.iloc[r, 0] if pd.notna(a) and str(a).strip(): if '\n' in str(a) or 'definition breakouts' in _norm(a): continue # title row group = _strip_q_prefix(a) cells = {} for c in range(1, df.shape[1]): v = df.iloc[r, c] if pd.notna(v) and str(v).strip(): cells[c] = _clean(v) if group and cells: rows.append((group, cells)) return rows # Block header in three known shapes, all ending in the word 'mean': # '#03 Symbole ... mean' (old format, leading '#') # '16A Key Visuals mean' (new format, number — maybe letter-suffixed — then a # space and a multi-word label) # '05Colours mean' (new format, number glued straight onto the name) # First alternative = the original spaced/suffixed pattern (number, optional word # chars, whitespace, then label). Second alternative = the glued form: a single # token of digits-then-letters immediately followed by ' mean'. _BLOCK_HEADER_RE = re.compile( r'^#?\s*\d+\w*\s+.+\bmean\s*$' # '05 Colours mean', '16A Key Visuals mean' r'|^#?\s*\d+\w+\s+mean\s*$' # '05Colours mean' (glued number + name) ) def _is_block_header(name, brand_norms=None): """Return True for old/new block header rows, excluding known brand means.""" name = str(name).strip() if name.startswith('#'): return True if not _BLOCK_HEADER_RE.match(name): return False if brand_norms is None: return True label_part = re.sub(r'\s*\bmean\s*$', '', name).strip() return _norm(label_part) not in brand_norms def _find_bps_cols(df, brand_row): """All columns whose header (rows 0..brand_row) reads 'BPS', in column order.""" cols = [] for c in range(df.shape[1]): for r in range(brand_row + 1): val = df.iloc[r, c] if pd.notna(val) and str(val).strip() == 'BPS': cols.append(c) break return cols def _breakout_tier(df, n_brands, brand_row): """Classify the breakout header layout. Returns: 'two' — old format: row 0 = group name, row brand_row-1 = level name 'one' — new format: a single label row; grouping lives in the breakout-overview sheet 'none' — no breakout sections at all Guarded against the degenerate case: for new files brand_row == 1, so a naive row0-vs-row(brand_row-1) comparison would compare row 0 with itself. Two-tier additionally requires the row-0 group value to repeat across >= 2 consecutive sections (real group headers span their levels). """ bps_cols = _find_bps_cols(df, brand_row) if len(bps_cols) <= 1: return 'none' sub_row = brand_row - 1 if sub_row < 1: return 'one' differs = False spans = False prev = None run = 1 for bps_col in bps_cols[1:]: nc = bps_col - (n_brands + 5) if nc < 0: continue g = df.iloc[0, nc] lv = df.iloc[sub_row, nc] gs = _norm(g) if pd.notna(g) else '' ls = _norm(lv) if pd.notna(lv) else '' if gs and ls and gs != ls: differs = True if gs and gs == prev: run += 1 if run >= 2: spans = True else: run = 1 prev = gs return 'two' if (differs and spans) else 'one' def _tokens_contain(haystack, needle): """Word-boundary containment: does needle's token sequence appear contiguously inside haystack's tokens? Returns the residue tokens of haystack (everything outside the match) or None. Both args pre-normalized. Token-based on purpose — character substrings would match 'No' inside 'Non-…' and silently mis-group antonyms. """ ht, nt = haystack.split(), needle.split() if not nt or len(nt) > len(ht): return None for i in range(len(ht) - len(nt) + 1): if ht[i:i + len(nt)] == nt: return ht[:i] + ht[i + len(nt):] return None def _resolve_candidates(cands, seg_norm, group_norms): """Tie-break matcher candidates [(group, display, level_norm)]. Unique group → it; group whose name prefixes the segment → it; unique longest level → it; else 'AMBIG'. None when no candidates. """ if not cands: return None groups = {g for g, _, _ in cands} if len(groups) == 1: return next(iter(groups)) pref = [g for g in groups if seg_norm.startswith(group_norms[g])] if len(pref) == 1: return pref[0] best_len = max(len(ln) for _, _, ln in cands) best = {g for g, _, ln in cands if len(ln) == best_len} if len(best) == 1: return next(iter(best)) return 'AMBIG' def _cluster_segments(segments, overview_rows, brands, warnings): """Cluster flat one-tier breakout segments into groups via the overview sheet. Layers (a per-layer census is appended to warnings as info): 1. exact — normalized equality; adopts the clean overview name 2. substring — word-boundary token containment, and the residue must share a token with the group name 3. type-suffix — brand-aware: learn type tokens ('aware', 'non aware', 'buyer', …) by stripping brand / literal 'Brand X' prefixes off overview labels; match longest suffix. Covers per-brand expansion incl. untested brands. 4. positional — gated: only inside a same-group sandwich, or a run whose length equals exactly one neighbor group's remaining level count. Overview counts are LOWER bounds (Brand X expands), never exact — no global count validation. 5. catch-all — 'Ungrouped' segments: [{'name', 'n', 'bps_col'}] in table order. Returns groups in overview order (+ Ungrouped last): [{'name', 'key', 'levels': [{'name', 'n', 'bps_col'}]}] — 'key' is required downstream (viewer JS keys group lookup off it). """ seg_norms = [_norm(s['name']) for s in segments] # --- choose the label column: best exact coverage, then substring, then rightmost col_ids = sorted({c for _, cells in overview_rows for c in cells}) if not col_ids: return None def coverage(col): labs = [_norm(cells[col]) for _, cells in overview_rows if col in cells] exact = sum(1 for sn in seg_norms if sn in labs) sub = sum(1 for sn in seg_norms if any(_tokens_contain(sn, lv) is not None for lv in labs)) return exact, sub, col scored = sorted((coverage(c) for c in col_ids), reverse=True) if len(scored) > 1 and scored[0][:2] == scored[1][:2]: warnings.append(_warn('warning', 'label_column_tie', 'overview label-column choice tied; picked rightmost')) label_col = scored[0][2] labels = [(g, cells[label_col], _norm(cells[label_col])) for g, cells in overview_rows if label_col in cells] group_order = [] for g, _, _ in labels: if g not in group_order: group_order.append(g) group_norms = {g: _norm(g) for g in group_order} # --- learn type tokens: strip brand / 'Brand X' prefixes off overview labels. # Brands are compared by their alphanumeric form only (ignoring spaces, # dashes, case) so a brand listed as 'OralB' still matches 'Oral B …' in the # overview (and 'Coca-Cola' ↔ 'Coca Cola', etc.). A brand may span several # label tokens ('Oral B'), so test progressively longer leading token-runs # and take the longest one that equals a brand; the remainder is the type. def _compact(text): return re.sub(r'[^a-z0-9]', '', text.lower()) compact_brands = {_compact(b) for b in brands} | {'brandx'} type2groups = {} brandish_rows = 0 for g, _, ln in labels: toks = ln.split() suffix = None for k in range(len(toks), 0, -1): if _compact(''.join(toks[:k])) in compact_brands: suffix = ' '.join(toks[k:]) break if suffix is not None: brandish_rows += 1 if suffix: type2groups.setdefault(suffix, set()).add(g) ambiguous_tokens = {t: gs for t, gs in type2groups.items() if len(gs) > 1} if ambiguous_tokens: warnings.append(_warn('warning', 'ambiguous_type_suffix', 'brand-aware suffix appeared under multiple overview groups; ' 'suffix matching disabled for ambiguous tokens', tokens=sorted(ambiguous_tokens))) type2group = {t: next(iter(gs)) for t, gs in type2groups.items() if len(gs) == 1} if brandish_rows == 0: suffixish = sum(1 for _, _, ln in labels if re.search(r'\b(aware|buyer|bumo|user|käufer)\b', ln)) if suffixish: warnings.append(_warn('warning', 'empty_token_set', 'overview rows look brand-prefixed but no known brand ' '(or "Brand X") prefix matched; type-suffix matching is inactive')) type_tokens = sorted(type2group, key=len, reverse=True) assigned = [None] * len(segments) display = [s['name'] for s in segments] census = {'exact': 0, 'substr': 0, 'suffix': 0, 'positional': 0, 'ungrouped': 0} # --- layer 1: exact (adopt the clean overview display name) for i, sn in enumerate(seg_norms): hits = [(g, disp) for g, disp, ln in labels if ln == sn] if hits: assigned[i] = hits[0][0] display[i] = hits[0][1] census['exact'] += 1 # --- layer 2: word-boundary substring + residue/group-name check for i, sn in enumerate(seg_norms): if assigned[i] is not None: continue cands = [] for g, disp, ln in labels: residue = _tokens_contain(sn, ln) if residue is None: residue = _tokens_contain(ln, sn) if residue is None: continue if not (set(residue) & set(group_norms[g].split())): continue # residue must resemble the group name cands.append((g, disp, ln)) got = _resolve_candidates(cands, sn, group_norms) if got == 'AMBIG': warnings.append(_warn('warning', 'ambiguous_match', f'"{segments[i]["name"]}" matched multiple overview levels; left unmatched', segment=segments[i]['name'])) elif got is not None: assigned[i] = got census['substr'] += 1 warnings.append(_warn('info', 'nonexact_match', f'"{segments[i]["name"]}" grouped under "{got}" by partial label match', segment=segments[i]['name'], group=got)) # --- layer 3: brand-aware type-suffix (word-bounded, longest token wins) for i, sn in enumerate(seg_norms): if assigned[i] is not None: continue tok = next((t for t in type_tokens if sn == t or sn.endswith(' ' + t)), None) if tok: assigned[i] = type2group[tok] census['suffix'] += 1 # --- layer 4: gated positional fallback (warn on every assignment) remaining = {} for g, _, _ in labels: remaining[g] = remaining.get(g, 0) + 1 for g in assigned: if g in remaining: remaining[g] -= 1 i, n = 0, len(segments) while i < n: if assigned[i] is not None: i += 1 continue j = i while j < n and assigned[j] is None: j += 1 run = j - i g_prev = assigned[i - 1] if i > 0 else None g_next = assigned[j] if j < n else None target = None if g_prev is not None and g_prev == g_next: target = g_prev # sandwiched inside one group else: opts = [g for g in {g_prev, g_next} if g is not None and remaining.get(g, 0) == run] if len(opts) == 1: target = opts[0] if target is not None: for k in range(i, j): assigned[k] = target census['positional'] += 1 warnings.append(_warn('warning', 'positional_fallback', f'"{segments[k]["name"]}" assigned to "{target}" by position only — verify', segment=segments[k]['name'], group=target)) remaining[target] = remaining.get(target, 0) - run i = j # --- layer 5: catch-all for i, g in enumerate(assigned): if g is None: assigned[i] = 'Ungrouped' census['ungrouped'] += 1 warnings.append(_warn('warning', 'unmatched_segment', f'"{segments[i]["name"]}" did not match any overview group', segment=segments[i]['name'])) matched = census['exact'] + census['suffix'] warnings.append(_warn('info', 'match_census', f"{matched} matched to definitions, " f"{census['substr']} by partial match, " f"{census['positional']} by position (fallback), " f"{census['ungrouped']} unmatched", matched=matched, nonexact=census['substr'], by_position=census['positional'], unmatched=census['ungrouped'])) # --- assemble groups in overview order (+ Ungrouped last); drop empty order = [g for g in group_order if g in assigned] if 'Ungrouped' in assigned: order.append('Ungrouped') groups = [] used_keys = set() for g in order: levels = [{'name': display[i], 'n': segments[i]['n'], 'bps_col': segments[i]['bps_col']} for i in range(len(segments)) if assigned[i] == g] if not levels: continue key = _slugify(g) k, suffix = key, 2 while k in used_keys: k = f'{key}_{suffix}' suffix += 1 used_keys.add(k) groups.append({'key': k, 'name': g, 'levels': levels}) return groups def _ungrouped_breakout_group(segments): """Preserve one-tier breakout levels when the overview grouping is unavailable.""" if not segments: return [] return [{'key': 'ungrouped', 'name': 'Ungrouped', 'levels': segments}] def _parse_breakout_groups(df, n_brands, brand_row=2): """Parse breakout group structure from the Excel header rows. Scans header rows for all columns with value "BPS". The first is Total (skipped). Remaining BPS columns define breakout levels: group name from row 0, level name from sub_header_row, n from n_cases_row at bps_col - (n_brands + 5). Returns: list of breakout groups, each: { 'key': 'geschlecht', 'name': 'Geschlecht', 'levels': [ {'name': 'Weiblich', 'n': 301, 'bps_col': 24}, ... ] } """ sub_header_row = brand_row - 1 n_cases_row = brand_row + 1 bps_cols = _find_bps_cols(df, brand_row) if len(bps_cols) <= 1: return [] # Only Total, no breakouts # Skip first (Total) breakout_bps_cols = bps_cols[1:] # Build flat list of levels, then group by row-0 label groups = [] current_group_name = None current_group = None for bps_col in breakout_bps_cols: # Names are always at the first column of the section # (works for both merged and non-merged formats after openpyxl unmerge) name_col = bps_col - (n_brands + 5) if name_col < 0: continue # Group name from row 0 — may repeat for continuation levels raw_group = df.iloc[0, name_col] if pd.notna(raw_group) and str(raw_group).strip() and str(raw_group).strip() != 'BPS': group_name = str(raw_group).strip() elif current_group_name: group_name = current_group_name else: group_name = 'Unknown' # Level name from sub_header_row level_name = str(df.iloc[sub_header_row, name_col]).strip() if pd.notna(df.iloc[sub_header_row, name_col]) else '' # Skip if level name looks like a metric header (not a real breakout) if level_name in ('', 'Index inverted all Brands'): continue # n from n_cases_row at the first column of this breakout section n_val = _safe_int(df.iloc[n_cases_row, name_col]) if group_name != current_group_name: # Clean group name: strip questionnaire prefixes ('Q1 7 1 ' etc.) cleaned = _strip_q_prefix(group_name) current_group_name = group_name current_group = { 'key': _slugify(cleaned), 'name': cleaned, 'levels': [], } groups.append(current_group) current_group['levels'].append({ 'name': level_name, 'n': n_val, 'bps_col': bps_col, }) return groups def detect_sheet_name(excel_path): """Find the BPS per Block sheet name. Matches any sheet containing 'bps' and 'block' (case-insensitive). Covers both old ('MAT Branding + BPS (per Block)') and new ('BPS per Block') naming. Returns the first match, or None. """ xls = pd.ExcelFile(excel_path) try: for name in xls.sheet_names: lower = name.lower() if 'bps' in lower and 'block' in lower: return name return None finally: xls.close() def _detect_label_column(df): """Find the column containing property names / labels. Searches for 'All pictures mean' or old/new block headers. Returns the 0-based column index. """ for c in range(min(3, df.shape[1])): for r in range(df.shape[0]): val = df.iloc[r, c] if pd.isna(val): continue s = str(val).strip() if s == 'All pictures mean' or _is_block_header(s): return c return 0 # fallback to column A def _detect_brand_row(df, label_col): """Detect the row index (0-based) containing brand names. Strategy: scan columns 0-2 for a cell containing "number of cases" (case-insensitive). Brand names are in the row immediately above it. Falls back to row 2 (standard layout) if not found. """ for r in range(2, min(10, df.shape[0])): for c in range(min(3, df.shape[1])): val = df.iloc[r, c] if pd.notna(val) and 'number of cases' in str(val).strip().lower(): return r - 1 # brand names one row above return 2 # fallback: standard layout def parse_icat_results(excel_path, sheet_name=None, *, verbose=False): """Parse an IcAT results Excel file. Args: excel_path: Path to the .xlsx file sheet_name: Worksheet name. Auto-detected if None. verbose: If True, echo structured parser warnings to stdout. Returns: dict with keys: project_title: str — from cell A1 brands: list[str] — brand names in column order brand_colors: dict — brand code → brand name mapping n_cases: int — number of respondents thresholds: dict — {correct_brand, uniqueness, bps} blocks: list[dict] — block categories with their properties properties: list[dict] — flat list of all individual properties """ if sheet_name is None: sheet_name = detect_sheet_name(excel_path) if sheet_name is None: raise ValueError("Could not find BPS per Block sheet. " "Available sheets: " + str(pd.ExcelFile(excel_path).sheet_names)) df = _unmerge_header_rows(excel_path, sheet_name) # --- Detect label column (property names) --- label_col = _detect_label_column(df) # --- Detect brand row (handles files with extra header rows) --- brand_row = _detect_brand_row(df, label_col) n_cases_row = brand_row + 1 threshold_row = brand_row + 4 # standard offset: +4 rows after brands # --- Extract metadata from header rows --- # Project title from first cell of row 1 project_title = str(df.iloc[0, 0]).split('\n')[0].strip() if pd.notna(df.iloc[0, 0]) else '' # Brand names start column: first non-empty cell after label_col in brand_row brand_start = label_col + 1 for c in range(label_col + 1, df.shape[1]): if pd.notna(df.iloc[brand_row, c]) and str(df.iloc[brand_row, c]).strip(): brand_start = c break # Find n_brands by locating "correct brand" in any row above n_cases_row n_brands = 0 found_cb = False for r in range(brand_row + 1): for c in range(brand_start, df.shape[1]): val = df.iloc[r, c] if pd.notna(val) and str(val).strip().lower() == 'correct brand': n_brands = c - brand_start found_cb = True break if found_cb: break if not found_cb: # Fallback: count non-empty cells in brand_row for c in range(brand_start, df.shape[1]): if pd.isna(df.iloc[brand_row, c]) or not str(df.iloc[brand_row, c]).strip(): break n_brands += 1 brands = [] for c in range(brand_start, brand_start + n_brands): v = df.iloc[brand_row, c] brands.append(str(v).strip() if pd.notna(v) else f'Brand_{c}') # Column indices: after brands come 6 metric columns # correct brand, Uniqueness, Certainty, Index inverted, cb weighted, BPS col_correct_brand = brand_start + n_brands col_uniqueness = brand_start + n_brands + 1 col_certainty = brand_start + n_brands + 2 col_bps = brand_start + n_brands + 5 # Number of cases n_cases = _safe_int(df.iloc[n_cases_row, brand_start], 0) # Thresholds thresholds = { 'correct_brand': _safe_float(df.iloc[threshold_row, col_correct_brand], 75), 'uniqueness': _safe_float(df.iloc[threshold_row, col_uniqueness], 60), 'bps': _safe_float(df.iloc[threshold_row, col_bps], 70), } # --- Parse breakout groups (explicit old/new branch by header tier) --- warnings = [] tier = _breakout_tier(df, n_brands, brand_row) breakout_groups = _parse_breakout_groups(df, n_brands, brand_row) if tier != 'none' else [] if tier == 'one': # New format: one label row only — grouping lives in the overview sheet. segments = [lvl for grp in breakout_groups for lvl in grp['levels']] overview_sheet = _detect_overview_sheet(excel_path) if overview_sheet is None: warnings.append(_warn('warning', 'overview_sheet_missing', "Excel contains one-level breakout header but no " "breakout-overview sheet found --> breakout segments " "are grouped under 'Ungrouped'. To fix: Ensure that " "breakout-overview sheet is included and contains " "'breakout' in sheet name.")) breakout_groups = _ungrouped_breakout_group(segments) else: overview_rows = _parse_overview_rows(excel_path, overview_sheet) clustered = (_cluster_segments(segments, overview_rows, brands, warnings) if overview_rows else None) if clustered: breakout_groups = clustered else: warnings.append(_warn('warning', 'overview_sheet_missing', f'breakout-overview sheet {overview_sheet!r} yielded no ' f'usable groups; segments grouped under Ungrouped')) breakout_groups = _ungrouped_breakout_group(segments) elif tier == 'two': # Old format: the in-table two-tier grouping is authoritative; the # overview sheet is intentionally ignored (regrouping from it used to # corrupt level names). Sanity check: mostly-singleton output whose # labels match the overview sheet suggests a misclassified one-tier file. singles = sum(1 for g in breakout_groups if len(g['levels']) == 1) if breakout_groups and singles / len(breakout_groups) > 0.5: sheet = _detect_overview_sheet(excel_path) rows = _parse_overview_rows(excel_path, sheet) if sheet else None if rows: level_norms = {_norm(v) for _, cells in rows for v in cells.values()} seg_norms = [_norm(lvl['name']) for g in breakout_groups for lvl in g['levels']] hits = sum(1 for s in seg_norms if s in level_norms) if seg_norms and hits / len(seg_norms) > 0.5: warnings.append(_warn('warning', 'tier_suspect', 'two-tier classification looks suspect (mostly ' 'singleton groups whose labels match the overview ' 'sheet) — breakout grouping may be wrong')) # Build flat list of BPS column indices for breakout extraction breakout_bps_cols = [] for grp in breakout_groups: for lvl in grp['levels']: breakout_bps_cols.append(lvl['bps_col']) # Each breakout section repeats the Total layout: | correct brand | # Uniqueness | ... | BPS. Locate each subgroup's brand-attribution columns # by brand label (section header), falling back to Total's brand order. brand_norm_idx = {_norm(b): i for i, b in enumerate(brands)} breakout_sections = [] for bps_c in breakout_bps_cols: start = bps_c - (n_brands + 5) cols = [start + i for i in range(n_brands)] labels = [_norm(df.iloc[brand_row, c]) if pd.notna(df.iloc[brand_row, c]) else '' for c in cols] if all(lab in brand_norm_idx for lab in labels) and len(set(labels)) == n_brands: by_brand = [None] * n_brands for c, lab in zip(cols, labels): by_brand[brand_norm_idx[lab]] = c cols = by_brand breakout_sections.append({'brand_cols': cols, 'cb_col': start + n_brands, 'uniq_col': start + n_brands + 1}) # --- Parse data rows --- blocks = [] properties = [] current_block = None # Build brand code → brand name mapping from property names brand_code_map = {} # Brand means look like ' mean' — guard against digit-leading # brand names ('7 Days mean') being mistaken for block headers. brand_norms_set = {_norm(b) for b in brands} # Brand lookup keyed on the alphanumeric-only form of each brand, so that # 'Oral B', 'Oral-B' and the asset-code token 'oralb' all compare equal # (case, spaces, dashes and other punctuation are discarded on both sides). # Sorted longest-first so a longer brand wins over a shorter brand it # contains (e.g. 'oralbkids' is matched before 'oralb'). def _brand_key(text): return re.sub(r'[^a-z0-9]', '', str(text).lower()) brand_keys = sorted(((_brand_key(b), b) for b in brands if _brand_key(b)), key=lambda kv: len(kv[0]), reverse=True) # Data rows start after the header block (brands + 6 metadata rows); # old format: brand_row=2 → 8, new format: brand_row=1 → 7. for r in range(brand_row + 6, df.shape[0]): name = df.iloc[r, label_col] if pd.isna(name): continue name = str(name).strip() if not name: continue # Block header: '#NN name mean' (old) or number-led 'NN name mean' (new) if _is_block_header(name, brand_norms_set): block_name = re.sub(r'^#+\s*', '', name).strip() # Remove trailing " mean" if block_name.endswith(' mean'): block_name = block_name[:-5].strip() # Extract block number. Try the spaced form first (handles # letter-suffixed numbers like '12a Foo'); fall back to the glued # form ('05Colours'), splitting digits from the following name. block_match = re.match(r'(\d+\w*?)\s+(.*)', block_name) if not block_match: block_match = re.match(r'(\d+)(\D.*)', block_name) block_num = block_match.group(1) if block_match else '' block_label = block_match.group(2).strip() if block_match else block_name # Block-level BPS mean is in the BPS column block_bps_mean = _safe_float(df.iloc[r, col_bps]) current_block = { 'number': block_num, 'name': block_label, 'bps_mean': block_bps_mean, 'properties': [], } blocks.append(current_block) continue # Brand mean rows: "REWE mean", "All pictures mean", etc. if name.endswith(' mean') and not name.startswith('#'): continue # Individual property row prop = _parse_property_row(df, r, name, brands, n_brands, brand_start, col_correct_brand, col_uniqueness, col_certainty, col_bps) if prop is None: continue # Extract breakout BPS values (one per breakout level, in flat order) if breakout_bps_cols: prop['breakout_bps'] = [_safe_float(df.iloc[r, c]) for c in breakout_bps_cols] # Per subgroup: brand attribution % (Total's brand order), correct brand, uniqueness prop['breakout_brand_pcts'] = [[_safe_float(df.iloc[r, c]) for c in s['brand_cols']] for s in breakout_sections] prop['breakout_correct'] = [_safe_float(df.iloc[r, s['cb_col']]) for s in breakout_sections] prop['breakout_uniqueness'] = [_safe_float(df.iloc[r, s['uniq_col']]) for s in breakout_sections] else: prop['breakout_bps'] = [] prop['breakout_brand_pcts'] = [] prop['breakout_correct'] = [] prop['breakout_uniqueness'] = [] # Assign to current block if current_block is not None: prop['block'] = current_block['name'] prop['block_number'] = current_block['number'] current_block['properties'].append(prop) else: prop['block'] = '' prop['block_number'] = '' # Identify the owning brand from the asset code by matching it against # the known brand list (the brands come from the Excel column headers # and are authoritative — we never guess a brand, we find which known # brand the code carries). The brand sits right after the leading # 'B' stimulus/block prefix: # 05B05stayfree01colorsingleblue -> Stayfree # 01B16aoralb01bathroomsetting -> Oral B (a stray block-suffix # letter 'a' precedes the brand) # Strip that prefix, then find the known brand the remainder begins # with. A few leading block-suffix letters are tolerated by retrying # with them dropped; because skip=0 is tried first and the longest # brand wins, a brand that genuinely starts with such a letter (e.g. # 'Always') is matched whole and never mis-stripped. prefix = re.match(r'\d{2}[Bb]\d*', name) if prefix: remainder = _brand_key(name[prefix.end():]) for skip in range(3): # tolerate up to 2 leading block-suffix letters cand = remainder[skip:] hit = next((b for k, b in brand_keys if cand.startswith(k)), None) if hit: prop['owner_brand'] = hit brand_code_map[name[:2]] = hit break properties.append(prop) # Second pass — resolve assets whose code abbreviates the brand (e.g. # 'ps' = Philips, 'hs' = HiSmile) and so found no name match above. We # never hard-code abbreviations. Instead we LEARN the leading-code -> # brand relationship from the assets that DID match by name, and only if # that relationship is a clean positional index (leading code N -> the # N-th brand in column order) for EVERY name-matched asset do we trust it # to fill the gaps. A study where the leading number is a stimulus counter # rather than a brand index (so the codes don't line up with column order) # fails this check, and its unmatched assets are left unattributed rather # than guessed wrong. At least two distinct codes must agree before the # index is trusted. learned = {} # leading 2-digit code -> set of brands seen via name match for p in properties: if not p['owner_brand']: continue m = re.match(r'(\d{2})', p['name']) if m: learned.setdefault(m.group(1), set()).add(p['owner_brand']) positional_ok = len(learned) >= 2 and all( len(bset) == 1 and 0 <= int(code) - 1 < len(brands) and brands[int(code) - 1] in bset for code, bset in learned.items()) if positional_ok: filled = 0 for p in properties: if p['owner_brand']: continue m = re.match(r'(\d{2})', p['name']) if not m: continue idx = int(m.group(1)) - 1 if 0 <= idx < len(brands): p['owner_brand'] = brands[idx] brand_code_map.setdefault(m.group(1), brands[idx]) filled += 1 if filled: warnings.append(_warn('info', 'brand_filled_by_position', f'{filled} asset(s) had no brand-name match in their ' f'code (likely abbreviated) and were attributed via the ' f'leading code, which matches brand column order for all ' f'name-matched assets in this study.')) if not blocks: warnings.append(_warn('warning', 'no_blocks', 'no block headers detected; assets will be ungrouped')) if verbose: for w in warnings: print(f"[{w['severity']}] {w['code']}: {w['message']}") return { 'project_title': project_title, 'brands': brands, 'brand_code_map': brand_code_map, 'n_cases': n_cases, 'thresholds': thresholds, 'blocks': blocks, 'properties': properties, 'breakout_groups': breakout_groups, 'warnings': warnings, } def _parse_property_row(df, r, name, brands, n_brands, brand_start, col_cb, col_uniq, col_cert, col_bps): """Parse a single property (stimulus) row.""" # Brand attribution percentages brand_pcts = {} for i, brand in enumerate(brands): val = _safe_float(df.iloc[r, brand_start + i]) if val is not None: brand_pcts[brand] = val # Skip rows without brand data (likely not a property row) if not brand_pcts: return None correct_brand = _safe_float(df.iloc[r, col_cb]) uniqueness = _safe_float(df.iloc[r, col_uniq]) certainty = _safe_float(df.iloc[r, col_cert]) bps = _safe_float(df.iloc[r, col_bps]) # Determine BPS zone if bps is not None: if bps >= 70: zone = 'Iconic' elif bps >= 40: zone = 'Potential' elif bps >= 20: zone = 'Explore' else: zone = 'Watch Out' else: zone = 'Unknown' return { 'name': name, 'brand_pcts': brand_pcts, 'correct_brand': correct_brand, 'uniqueness': uniqueness, 'certainty': certainty, 'bps': bps, 'zone': zone, 'owner_brand': None, # set by caller } def _safe_float(val, default=None): """Convert to float, returning default if not numeric.""" if pd.isna(val): return default try: return float(val) except (ValueError, TypeError): return default def _safe_int(val, default=None): """Convert to int, returning default if not numeric.""" if pd.isna(val): return default try: return int(float(val)) except (ValueError, TypeError): return default