hemsby commited on
Commit
ec8df18
·
1 Parent(s): f408972

feat: detect reward territories from Excel instead of hardcoding

Browse files

Reads "per reward field" header in row 4 to find territory columns,
then extracts territory names from row 5. Falls back to default list
if detection fails. Removes REWARDS_FACTORS from config.py.

Files changed (4) hide show
  1. CLAUDE.md +6 -6
  2. app.py +14 -3
  3. config.py +0 -14
  4. parse_excel.py +49 -7
CLAUDE.md CHANGED
@@ -40,7 +40,7 @@ A standalone HTML file with a vis-network interactive visualization:
40
 
41
  ```
42
  app.py # Streamlit UI (~180 lines)
43
- config.py # Constants: REWARDS_FACTORS, COLORS
44
  parse_excel.py # Excel detection + data extraction
45
  build_network.py # Network building + HTML template generation
46
  requirements.txt # streamlit, pandas, numpy, openpyxl
@@ -95,11 +95,12 @@ After the "mean across all brands" correlation matrix, each brand gets its own s
95
 
96
  ## Auto-Detection Logic
97
 
98
- The app tries to auto-detect 3 parameters:
99
 
100
  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.
101
  2. **CORR_COL_START** (`detect_correlation_column_start`): Finds the first block of >50 consecutive non-empty cells in row 5. Works reliably.
102
- 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.
 
103
 
104
  ## How to Run
105
 
@@ -135,9 +136,8 @@ streamlit run app.py
135
  ## Known Issues
136
 
137
  1. **Cut-off detection always fails** — none of the real files contain "cut-off used in columns" text
138
- 2. **`REWARDS_FACTORS` hardcoded** — inline list of territory names, not synced with canonical 60-attribute list
139
- 3. **Rewards classification is territory-level** — checks 3rd part of variable code against territory names, not individual attributes
140
- 4. **Per-brand matrices ignored** — only "mean across all brands" is used
141
 
142
  ## Future Feature Ideas
143
 
 
40
 
41
  ```
42
  app.py # Streamlit UI (~180 lines)
43
+ config.py # Constants: COLORS
44
  parse_excel.py # Excel detection + data extraction
45
  build_network.py # Network building + HTML template generation
46
  requirements.txt # streamlit, pandas, numpy, openpyxl
 
95
 
96
  ## Auto-Detection Logic
97
 
98
+ The app auto-detects 4 parameters:
99
 
100
  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.
101
  2. **CORR_COL_START** (`detect_correlation_column_start`): Finds the first block of >50 consecutive non-empty cells in row 5. Works reliably.
102
+ 3. **REWARD_TERRITORIES** (`detect_reward_territories`): Finds "per reward field" header in row 4, reads territory names from row 5 underneath. Works reliably (6 DE territories, 10 EN territories). Falls back to hardcoded defaults.
103
+ 4. **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.
104
 
105
  ## How to Run
106
 
 
136
  ## Known Issues
137
 
138
  1. **Cut-off detection always fails** — none of the real files contain "cut-off used in columns" text
139
+ 2. **Rewards classification is territory-level** — checks 3rd part of variable code against territory names, not individual attributes
140
+ 3. **Per-brand matrices ignored** — only "mean across all brands" is used
 
141
 
142
  ## Future Feature Ideas
143
 
app.py CHANGED
@@ -7,6 +7,7 @@ from parse_excel import (
7
  detect_data_start_row,
8
  detect_cutoff_value,
9
  detect_correlation_column_start,
 
10
  detect_nonrewards_patterns,
11
  extract_network_data,
12
  )
@@ -57,7 +58,10 @@ if uploaded_file is not None:
57
  detected_row, blocks = detect_data_start_row(df)
58
  detected_cutoff = detect_cutoff_value(df)
59
  detected_col = detect_correlation_column_start(df)
60
- patterns = detect_nonrewards_patterns(df, detected_row - 1 if detected_row else 95)
 
 
 
61
 
62
  st.session_state.detected_values = {
63
  'row': detected_row,
@@ -65,6 +69,7 @@ if uploaded_file is not None:
65
  'cutoff': detected_cutoff,
66
  'blocks': blocks,
67
  'patterns': patterns,
 
68
  }
69
 
70
  st.success(f"✅ File loaded: {df.shape[0]} rows × {df.shape[1]} columns")
@@ -89,7 +94,10 @@ if uploaded_file is not None:
89
  rewards = patterns.get('Rewards', 0) if patterns else 0
90
  nonrewards = patterns.get('Nonrewards', 0) if patterns else 0
91
  st.markdown(f"**Classification:** {rewards} Rewards, {nonrewards} Nonrewards")
92
- st.caption("(Based on REWARDS_FACTORS list)")
 
 
 
93
 
94
  except Exception as e:
95
  st.error(f"❌ Error loading file: {str(e)}")
@@ -191,8 +199,11 @@ if not can_generate:
191
  if st.button("🚀 Generate HTML Network", disabled=not can_generate, type="primary"):
192
  with st.spinner("Generating network..."):
193
  try:
 
 
 
194
  network_data = extract_network_data(
195
- st.session_state.df, data_start_row, corr_col_start
196
  )
197
 
198
  html_content, stats, filename = generate_network_html(
 
7
  detect_data_start_row,
8
  detect_cutoff_value,
9
  detect_correlation_column_start,
10
+ detect_reward_territories,
11
  detect_nonrewards_patterns,
12
  extract_network_data,
13
  )
 
58
  detected_row, blocks = detect_data_start_row(df)
59
  detected_cutoff = detect_cutoff_value(df)
60
  detected_col = detect_correlation_column_start(df)
61
+ rewards_factors = detect_reward_territories(df)
62
+ patterns = detect_nonrewards_patterns(
63
+ df, detected_row - 1 if detected_row else 95, rewards_factors
64
+ )
65
 
66
  st.session_state.detected_values = {
67
  'row': detected_row,
 
69
  'cutoff': detected_cutoff,
70
  'blocks': blocks,
71
  'patterns': patterns,
72
+ 'rewards_factors': rewards_factors,
73
  }
74
 
75
  st.success(f"✅ File loaded: {df.shape[0]} rows × {df.shape[1]} columns")
 
94
  rewards = patterns.get('Rewards', 0) if patterns else 0
95
  nonrewards = patterns.get('Nonrewards', 0) if patterns else 0
96
  st.markdown(f"**Classification:** {rewards} Rewards, {nonrewards} Nonrewards")
97
+ territories_str = ", ".join(rewards_factors[:6])
98
+ if len(rewards_factors) > 6:
99
+ territories_str += f", +{len(rewards_factors) - 6} more"
100
+ st.caption(f"Reward territories: {territories_str}")
101
 
102
  except Exception as e:
103
  st.error(f"❌ Error loading file: {str(e)}")
 
199
  if st.button("🚀 Generate HTML Network", disabled=not can_generate, type="primary"):
200
  with st.spinner("Generating network..."):
201
  try:
202
+ rewards_factors = st.session_state.detected_values.get(
203
+ 'rewards_factors', detect_reward_territories(st.session_state.df)
204
+ )
205
  network_data = extract_network_data(
206
+ st.session_state.df, data_start_row, corr_col_start, rewards_factors
207
  )
208
 
209
  html_content, stats, filename = generate_network_html(
config.py CHANGED
@@ -1,19 +1,5 @@
1
  """Constants for the correlation network generator."""
2
 
3
- # Territory names used to classify attributes as Rewards vs Nonrewards.
4
- # If the territory part of a variable code is NOT in this list → Nonreward.
5
- REWARDS_FACTORS = [
6
- # Core 6 (German)
7
- 'Abenteuer', 'Autonomie', 'Disziplin', 'Sicherheit', 'Genuss', 'Erregung',
8
- # Core 6 (English)
9
- 'Adventure', 'Autonomy', 'Discipline', 'Security', 'Enjoyment', 'Excitement',
10
- # Compound versions (English)
11
- 'Adventure & Thrill', 'Autonomy & Dominance', 'Balance & Security',
12
- 'Discipline & Control', 'Enjoyment & Sensuality', 'Excitement & Playfulness',
13
- # Extended (MX/other)
14
- 'GreaterGood', 'Caring', 'Acceptance', 'Control', 'SelfPromotion', 'Achievement', 'Freedom',
15
- ]
16
-
17
  # Node color palette — outline-based styling
18
  COLORS = {
19
  'reward_color': '#E03E3E', # warm red (edges)
 
1
  """Constants for the correlation network generator."""
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  # Node color palette — outline-based styling
4
  COLORS = {
5
  'reward_color': '#E03E3E', # warm red (edges)
parse_excel.py CHANGED
@@ -1,7 +1,46 @@
1
  """Excel correlation file parsing and auto-detection."""
2
 
3
  import pandas as pd
4
- from config import REWARDS_FACTORS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
 
7
  def detect_data_start_row(df):
@@ -86,14 +125,15 @@ def detect_correlation_column_start(df):
86
  return None
87
 
88
 
89
- def detect_nonrewards_patterns(df, data_start_idx):
90
  """Count Rewards vs Nonrewards attributes starting from data_start_idx.
91
 
92
  Classification is based on whether the territory part of the variable code
93
- (3rd segment of PREFIX_PA_Territory_Attribute) appears in REWARDS_FACTORS.
94
  """
95
  rewards_count = 0
96
  nonrewards_count = 0
 
97
 
98
  for row_idx in range(data_start_idx, min(data_start_idx + 200, df.shape[0])):
99
  code = df.iloc[row_idx, 1]
@@ -102,7 +142,7 @@ def detect_nonrewards_patterns(df, data_start_idx):
102
  parts = code.split('_')
103
  if len(parts) >= 3:
104
  factor = parts[2]
105
- if factor in REWARDS_FACTORS:
106
  rewards_count += 1
107
  else:
108
  nonrewards_count += 1
@@ -110,19 +150,21 @@ def detect_nonrewards_patterns(df, data_start_idx):
110
  return {'Rewards': rewards_count, 'Nonrewards': nonrewards_count}
111
 
112
 
113
- def extract_network_data(df, data_start_row, corr_col_start):
114
  """Extract attributes, codes, category indices, and correlation matrix from the Excel data.
115
 
116
  Args:
117
  df: Raw DataFrame (no header, 0-indexed)
118
  data_start_row: 1-based row number where deviation data starts
119
  corr_col_start: 0-based column index where correlation matrix starts
 
120
 
121
  Returns:
122
  dict with keys: attribute_names, attribute_codes, category_indices,
123
  nonrewards_attrs, driver_names, corr_df
124
  """
125
  data_start_idx = data_start_row - 1
 
126
 
127
  # Get driver codes from row 5 (0-indexed row 4)
128
  driver_codes = []
@@ -155,12 +197,12 @@ def extract_network_data(df, data_start_row, corr_col_start):
155
  cat_val = 0
156
  category_indices.append(cat_val)
157
 
158
- # Classify: if territory NOT in REWARDS_FACTORS → Nonreward
159
  if '_PA_' in code_str:
160
  parts = code_str.split('_')
161
  if len(parts) >= 3:
162
  factor = parts[2]
163
- if factor not in REWARDS_FACTORS:
164
  nonrewards_attrs.add(str(attr_name))
165
  else:
166
  break
 
1
  """Excel correlation file parsing and auto-detection."""
2
 
3
  import pandas as pd
4
+
5
+ # Fallback if detection fails (covers DE 6-territory and EN 10-territory models)
6
+ _DEFAULT_REWARDS = [
7
+ 'Abenteuer', 'Autonomie', 'Disziplin', 'Sicherheit', 'Genuss', 'Erregung',
8
+ 'Adventure', 'Autonomy', 'Discipline', 'Security', 'Enjoyment', 'Excitement',
9
+ 'GreaterGood', 'Caring', 'Acceptance', 'Control', 'SelfPromotion', 'Achievement', 'Freedom',
10
+ ]
11
+
12
+
13
+ def detect_reward_territories(df):
14
+ """Detect reward territory names from the Excel file.
15
+
16
+ Row 4 (0-indexed row 3) contains section headers. The one with
17
+ 'per reward field' marks the reward territory columns. Row 5 (0-indexed
18
+ row 4) underneath lists the individual territory names.
19
+
20
+ Returns:
21
+ list of territory name strings, or _DEFAULT_REWARDS if detection fails.
22
+ """
23
+ # Find the 'per reward field' header in row 4 (0-indexed row 3)
24
+ reward_col_start = None
25
+ for col_idx in range(df.shape[1]):
26
+ val = df.iloc[3, col_idx]
27
+ if pd.notna(val) and isinstance(val, str) and 'per reward field' in val.lower():
28
+ reward_col_start = col_idx
29
+ break
30
+
31
+ if reward_col_start is None:
32
+ return list(_DEFAULT_REWARDS)
33
+
34
+ # Read territory names from row 5 (0-indexed row 4) under that header
35
+ territories = []
36
+ for col_idx in range(reward_col_start, df.shape[1]):
37
+ val = df.iloc[4, col_idx]
38
+ if pd.notna(val) and isinstance(val, str) and val.strip():
39
+ territories.append(val.strip())
40
+ else:
41
+ break
42
+
43
+ return territories if territories else list(_DEFAULT_REWARDS)
44
 
45
 
46
  def detect_data_start_row(df):
 
125
  return None
126
 
127
 
128
+ def detect_nonrewards_patterns(df, data_start_idx, rewards_factors):
129
  """Count Rewards vs Nonrewards attributes starting from data_start_idx.
130
 
131
  Classification is based on whether the territory part of the variable code
132
+ (3rd segment of PREFIX_PA_Territory_Attribute) appears in rewards_factors.
133
  """
134
  rewards_count = 0
135
  nonrewards_count = 0
136
+ rewards_set = set(rewards_factors)
137
 
138
  for row_idx in range(data_start_idx, min(data_start_idx + 200, df.shape[0])):
139
  code = df.iloc[row_idx, 1]
 
142
  parts = code.split('_')
143
  if len(parts) >= 3:
144
  factor = parts[2]
145
+ if factor in rewards_set:
146
  rewards_count += 1
147
  else:
148
  nonrewards_count += 1
 
150
  return {'Rewards': rewards_count, 'Nonrewards': nonrewards_count}
151
 
152
 
153
+ def extract_network_data(df, data_start_row, corr_col_start, rewards_factors):
154
  """Extract attributes, codes, category indices, and correlation matrix from the Excel data.
155
 
156
  Args:
157
  df: Raw DataFrame (no header, 0-indexed)
158
  data_start_row: 1-based row number where deviation data starts
159
  corr_col_start: 0-based column index where correlation matrix starts
160
+ rewards_factors: list of territory names classified as Rewards
161
 
162
  Returns:
163
  dict with keys: attribute_names, attribute_codes, category_indices,
164
  nonrewards_attrs, driver_names, corr_df
165
  """
166
  data_start_idx = data_start_row - 1
167
+ rewards_set = set(rewards_factors)
168
 
169
  # Get driver codes from row 5 (0-indexed row 4)
170
  driver_codes = []
 
197
  cat_val = 0
198
  category_indices.append(cat_val)
199
 
200
+ # Classify: if territory NOT in rewards → Nonreward
201
  if '_PA_' in code_str:
202
  parts = code_str.split('_')
203
  if len(parts) >= 3:
204
  factor = parts[2]
205
+ if factor not in rewards_set:
206
  nonrewards_attrs.add(str(attr_name))
207
  else:
208
  break