DecodeMarketing commited on
Commit
a86665e
·
verified ·
1 Parent(s): ed012ed

Update: REWARDS_FACTORS logic, searchable dropdown, alphabetical order, CORR_COL_START detection

Browse files
Files changed (1) hide show
  1. app.py +69 -30
app.py CHANGED
@@ -18,8 +18,18 @@ st.set_page_config(
18
  # HELPER FUNCTIONS
19
  # =============================================================================
20
 
21
- # Nonrewards factors (both EN and DE) - compared case-insensitively
22
- NONREWARDS_FACTORS = ['features', 'functionalgoals', 'occasions', 'functional']
 
 
 
 
 
 
 
 
 
 
23
 
24
  def detect_data_start_row(df):
25
  """Find DATA_START_ROW by detecting the 2nd text block in column B."""
@@ -60,32 +70,48 @@ def detect_cutoff_value(df):
60
  return None
61
 
62
  def detect_correlation_column_start(df):
63
- """Find CORR_COL_START by searching for first column containing 'BRAND' in row 5."""
 
 
 
 
64
  for col_idx in range(df.shape[1]):
65
  val = df.iloc[4, col_idx]
66
- if pd.notna(val) and isinstance(val, str) and 'BRAND' in val.upper():
67
- return col_idx
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  return None
69
 
70
  def detect_nonrewards_patterns(df, data_start_idx):
71
- """Detect Nonrewards patterns in attribute codes."""
72
- patterns_found = {}
 
73
 
74
  for row_idx in range(data_start_idx, min(data_start_idx + 200, df.shape[0])):
75
  code = df.iloc[row_idx, 1]
76
  if pd.notna(code) and isinstance(code, str):
77
- code_lower = code.lower()
78
- if 'nonrewards' in code_lower:
79
- patterns_found['_Nonrewards_'] = patterns_found.get('_Nonrewards_', 0) + 1
80
- elif '_PA_' in code:
81
  parts = code.split('_')
82
  if len(parts) >= 3:
83
  factor = parts[2]
84
- if factor.lower() in NONREWARDS_FACTORS:
85
- key = f'_{factor}_'
86
- patterns_found[key] = patterns_found.get(key, 0) + 1
 
87
 
88
- return patterns_found
89
 
90
  def generate_network_html(df, data_start_row, corr_col_start, threshold, max_l1_nodes,
91
  client_name, country_name, brand_name, category_name):
@@ -97,7 +123,7 @@ def generate_network_html(df, data_start_row, corr_col_start, threshold, max_l1_
97
  driver_codes = []
98
  for col_idx in range(corr_col_start, df.shape[1]):
99
  driver_code = df.iloc[4, col_idx]
100
- if pd.notna(driver_code) and isinstance(driver_code, str) and 'BRAND' in driver_code.upper():
101
  driver_codes.append(str(driver_code))
102
  elif pd.isna(driver_code) or driver_code == '':
103
  break
@@ -124,13 +150,12 @@ def generate_network_html(df, data_start_row, corr_col_start, threshold, max_l1_
124
  cat_val = 0
125
  category_indices.append(cat_val)
126
 
127
- if 'nonrewards' in code_str.lower():
128
- nonrewards_attrs.add(str(attr_name))
129
- elif '_PA_' in code_str:
130
  parts = code_str.split('_')
131
  if len(parts) >= 3:
132
  factor = parts[2]
133
- if factor.lower() in NONREWARDS_FACTORS:
134
  nonrewards_attrs.add(str(attr_name))
135
  else:
136
  break
@@ -246,7 +271,7 @@ def generate_network_html(df, data_start_row, corr_col_start, threshold, max_l1_
246
 
247
  # Generate all networks
248
  all_nodes, all_edges = [], []
249
- available_drivers = sorted(driver_names)
250
 
251
  for driver in available_drivers:
252
  n, e = get_nodes_edges(driver)
@@ -262,13 +287,18 @@ def generate_network_html(df, data_start_row, corr_col_start, threshold, max_l1_
262
  <html lang="en-US">
263
  <head>
264
  <link type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css" rel="stylesheet" />
 
265
  <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
 
266
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
267
  <style>
268
  #mynetwork { width: 100%; height: 800px; border: 1px solid lightgray; }
269
  body { font-family: Arial, sans-serif; margin: 20px; }
270
- .controls { margin: 20px 0; padding: 10px; background: #f5f5f5; border-radius: 5px; }
271
- select { padding: 5px 10px; font-size: 14px; margin: 0 10px; }
 
 
 
272
  .info { margin: 10px 0; padding: 10px; background: #e8f4f8; border-left: 4px solid #0078d4; }
273
  .legend { margin: 10px 0; padding: 10px; background: #fff3cd; border-left: 4px solid #ffc107; }
274
  </style>
@@ -290,7 +320,16 @@ function draw(id) {
290
  document.getElementById('nodeCount').textContent = data.nodes.length;
291
  document.getElementById('edgeCount').textContent = data.edges.length;
292
  }
293
- window.onload = function() { draw(0); };
 
 
 
 
 
 
 
 
 
294
  </script>
295
  </head>
296
  <body>
@@ -308,7 +347,7 @@ window.onload = function() { draw(0); };
308
  </div>
309
  <div class="controls">
310
  <label>Select Driver:</label>
311
- <select id="driver_select" onchange="draw(this.value)">
312
  """
313
 
314
  for i, nodes_list in enumerate(all_nodes):
@@ -399,17 +438,17 @@ if uploaded_file is not None:
399
  st.caption(f"Text blocks: {blocks_text}")
400
  with col2:
401
  st.markdown(f"**CORR_COL_START:** {detected_col or 'Not detected'}")
402
- st.caption("(First 'BRAND' column in row 5)")
403
 
404
  col3, col4 = st.columns(2)
405
  with col3:
406
  st.markdown(f"**CORR_THRESHOLD:** {detected_cutoff or 'Not detected'}")
407
  st.caption("(From 'Cut-off used in columns')")
408
  with col4:
409
- pattern_text = ', '.join(patterns.keys()) if patterns else 'None'
410
- total = sum(patterns.values()) if patterns else 0
411
- st.markdown(f"**Nonrewards Patterns:** {pattern_text}")
412
- st.caption(f"({total} attributes)")
413
 
414
  except Exception as e:
415
  st.error(f"❌ Error loading file: {str(e)}")
 
18
  # HELPER FUNCTIONS
19
  # =============================================================================
20
 
21
+ # Complete REWARDS_FACTORS list - if NOT in this list -> Nonrewards
22
+ REWARDS_FACTORS = [
23
+ # Core 6 (German)
24
+ 'Abenteuer', 'Autonomie', 'Disziplin', 'Sicherheit', 'Genuss', 'Erregung',
25
+ # Core 6 (English)
26
+ 'Adventure', 'Autonomy', 'Discipline', 'Security', 'Enjoyment', 'Excitement',
27
+ # Compound versions (English)
28
+ 'Adventure & Thrill', 'Autonomy & Dominance', 'Balance & Security',
29
+ 'Discipline & Control', 'Enjoyment & Sensuality', 'Excitement & Playfulness',
30
+ # Extended (MX/other)
31
+ 'GreaterGood', 'Caring', 'Acceptance', 'Control', 'SelfPromotion', 'Achievement', 'Freedom'
32
+ ]
33
 
34
  def detect_data_start_row(df):
35
  """Find DATA_START_ROW by detecting the 2nd text block in column B."""
 
70
  return None
71
 
72
  def detect_correlation_column_start(df):
73
+ """Find CORR_COL_START by detecting first large column block (>50 cols) in row 5."""
74
+ in_block = False
75
+ block_start = None
76
+ col_blocks = []
77
+
78
  for col_idx in range(df.shape[1]):
79
  val = df.iloc[4, col_idx]
80
+ has_data = pd.notna(val) and str(val).strip()
81
+ if has_data and not in_block:
82
+ in_block = True
83
+ block_start = col_idx
84
+ elif not has_data and in_block:
85
+ in_block = False
86
+ col_blocks.append((block_start, col_idx - 1))
87
+ block_start = None
88
+ if in_block:
89
+ col_blocks.append((block_start, df.shape[1] - 1))
90
+
91
+ # Find first large block (>50 columns)
92
+ for start, end in col_blocks:
93
+ if end - start + 1 > 50:
94
+ return start
95
  return None
96
 
97
  def detect_nonrewards_patterns(df, data_start_idx):
98
+ """Detect Nonrewards patterns in attribute codes (NOT in REWARDS_FACTORS)."""
99
+ rewards_count = 0
100
+ nonrewards_count = 0
101
 
102
  for row_idx in range(data_start_idx, min(data_start_idx + 200, df.shape[0])):
103
  code = df.iloc[row_idx, 1]
104
  if pd.notna(code) and isinstance(code, str):
105
+ if '_PA_' in code:
 
 
 
106
  parts = code.split('_')
107
  if len(parts) >= 3:
108
  factor = parts[2]
109
+ if factor in REWARDS_FACTORS:
110
+ rewards_count += 1
111
+ else:
112
+ nonrewards_count += 1
113
 
114
+ return {'Rewards': rewards_count, 'Nonrewards': nonrewards_count}
115
 
116
  def generate_network_html(df, data_start_row, corr_col_start, threshold, max_l1_nodes,
117
  client_name, country_name, brand_name, category_name):
 
123
  driver_codes = []
124
  for col_idx in range(corr_col_start, df.shape[1]):
125
  driver_code = df.iloc[4, col_idx]
126
+ if pd.notna(driver_code) and isinstance(driver_code, str) and driver_code.strip():
127
  driver_codes.append(str(driver_code))
128
  elif pd.isna(driver_code) or driver_code == '':
129
  break
 
150
  cat_val = 0
151
  category_indices.append(cat_val)
152
 
153
+ # NEW LOGIC: If factor NOT in REWARDS_FACTORS -> Nonrewards
154
+ if '_PA_' in code_str:
 
155
  parts = code_str.split('_')
156
  if len(parts) >= 3:
157
  factor = parts[2]
158
+ if factor not in REWARDS_FACTORS:
159
  nonrewards_attrs.add(str(attr_name))
160
  else:
161
  break
 
271
 
272
  # Generate all networks
273
  all_nodes, all_edges = [], []
274
+ available_drivers = sorted(driver_names, key=lambda x: x.lower())
275
 
276
  for driver in available_drivers:
277
  n, e = get_nodes_edges(driver)
 
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>
 
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>
 
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):
 
438
  st.caption(f"Text blocks: {blocks_text}")
439
  with col2:
440
  st.markdown(f"**CORR_COL_START:** {detected_col or 'Not detected'}")
441
+ st.caption("(First large column block >50 cols in row 5)")
442
 
443
  col3, col4 = st.columns(2)
444
  with col3:
445
  st.markdown(f"**CORR_THRESHOLD:** {detected_cutoff or 'Not detected'}")
446
  st.caption("(From 'Cut-off used in columns')")
447
  with col4:
448
+ rewards = patterns.get('Rewards', 0) if patterns else 0
449
+ nonrewards = patterns.get('Nonrewards', 0) if patterns else 0
450
+ st.markdown(f"**Classification:** {rewards} Rewards, {nonrewards} Nonrewards")
451
+ st.caption("(Based on REWARDS_FACTORS list)")
452
 
453
  except Exception as e:
454
  st.error(f"❌ Error loading file: {str(e)}")