Dwinward commited on
Commit
3e5c4af
·
verified ·
1 Parent(s): 2c03d4c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -114
app.py CHANGED
@@ -4,8 +4,10 @@ import gradio as gr
4
  import re
5
  import tempfile
6
  import os
7
- import itertools
8
- from collections import defaultdict
 
 
9
 
10
  def clean_amount_fixed(val):
11
  """Advanced decimal parser that strips out hidden layout spaces after minus signs."""
@@ -14,7 +16,6 @@ def clean_amount_fixed(val):
14
  if isinstance(val, (int, float)):
15
  return float(val)
16
  val_str = str(val).replace(',', '').replace('GBP', '').strip()
17
- # Strip out all internal blank spaces to ensure clean float conversion
18
  val_str = re.sub(r'\s+', '', val_str)
19
  if val_str.endswith('-'):
20
  val_str = '-' + val_str[:-1]
@@ -37,13 +38,10 @@ def extract_branch_from_assignment(asg_text, valid_set):
37
  if pd.isna(asg_text):
38
  return None
39
  asg_str = str(asg_text).strip()
40
- # Check for a 4-digit sequence matching a valid merchant branch
41
  matches = re.findall(r'\d{4}', asg_str)
42
  for m in matches:
43
  if m in valid_set:
44
  return m
45
-
46
- # Fallback to check for padding on a 3-digit sequence
47
  matches_3 = re.findall(r'\b\d{3}\b|\d{3}', asg_str)
48
  for m in matches_3:
49
  padded = m.zfill(4)
@@ -60,7 +58,6 @@ def extract_branch_advanced(text, assignment, assignment_clean, till_map, mid_ma
60
  text_str = str(text).strip() if pd.notna(text) else ""
61
  asg_clean_str = str(assignment_clean).strip() if pd.notna(assignment_clean) else ""
62
 
63
- # --- PRISTINE ORIGINAL EXTRACTION HIERARCHY ---
64
  if asg_clean_str in till_map:
65
  return till_map[asg_clean_str]
66
 
@@ -79,7 +76,6 @@ def extract_branch_advanced(text, assignment, assignment_clean, till_map, mid_ma
79
  parts = text_str.split('*')
80
  if len(parts) > 2: return normalize_branch_string(parts[2])
81
 
82
- # Direct Start-of-String Pattern Match (e.g. "4154 CPSTOR" or "0350 CPSTEL")
83
  match_start_four = re.match(r'^(\d{4})\b', text_str)
84
  if match_start_four: return normalize_branch_string(match_start_four.group(1))
85
  match_sa = re.search(r'-000(\d{3,4})', text_str)
@@ -91,40 +87,55 @@ def extract_branch_advanced(text, assignment, assignment_clean, till_map, mid_ma
91
  match_generic = re.search(r'\b(\d{3,4})\b', text_str)
92
  if match_generic: return normalize_branch_string(match_generic.group(1))
93
 
94
- # --- NON-DESTRUCTIVE FALLBACKS (ONLY RUNS IF ORIGINAL STEPS RETURNED NONE) ---
95
  if text_str:
96
  if text_str in till_map:
97
  return till_map[text_str]
98
-
99
  digit_sequences = re.findall(r'\d+', text_str)
100
  for seq in digit_sequences:
101
  if seq in till_map:
102
  return till_map[seq]
103
-
104
- # Padded check for short references
105
  padded_seq = seq.zfill(8)
106
  if padded_seq in till_map:
107
  return till_map[padded_seq]
108
 
109
- # Scan Item Text for embedded branch codes using assignment rules
110
  text_asg_br = extract_branch_from_assignment(text, valid_set)
111
  if text_asg_br:
112
  return text_asg_br
113
 
114
- # Dash Fix Fallback: Captures standalone variations like -4114 safely
115
  match_dash_sa = re.search(r'-(\d{3,4})\b', text_str)
116
  if match_dash_sa:
117
  return normalize_branch_string(match_dash_sa.group(1))
118
 
119
  return None
120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  def process_reconciliation(file_main, file_mapping, file_mid, start_match_id):
122
- """High-speed multi-pass reconciliation engine featuring space correction and cross-day combinations."""
123
  try:
124
  if file_main is None or file_mapping is None:
125
  raise ValueError("Missing file upload. Please provide both the Ledger and TILL mapping files.")
126
 
127
- # Gradio Version Resilient File Paths
128
  main_path = file_main.path if hasattr(file_main, 'path') else file_main.name
129
  mapping_path = file_mapping.path if hasattr(file_mapping, 'path') else file_mapping.name
130
 
@@ -165,7 +176,7 @@ def process_reconciliation(file_main, file_mapping, file_mid, start_match_id):
165
  except Exception as e:
166
  print(f"BPS Header Shift Handled: {str(e)}")
167
 
168
- # Core advanced extraction loop
169
  extracted_branches = []
170
  for idx, row in main_df.iterrows():
171
  br_res = extract_branch_advanced(
@@ -241,18 +252,15 @@ def process_reconciliation(file_main, file_mapping, file_mid, start_match_id):
241
  used_statement_indices = set()
242
  used_cashbook_indices = set()
243
 
244
- cb_daily_map = defaultdict(list)
245
- cb_branch_window_pool = defaultdict(list)
246
-
247
  for cb_row in cashbook.to_dict('records'):
248
  br = str(cb_row['Extracted_Branch'])
249
- dt = cb_row['Journal Entry Date']
250
- if br and br != 'None' and pd.notna(dt):
251
- cb_daily_map[(br, dt)].append(cb_row)
252
- cb_branch_window_pool[br].append(cb_row)
253
 
254
  # -------------------------------------------------------------------------
255
- # REVISED PASS 2: STANDARD LOOKBACK WITH CROSS-DAY COMBOS
256
  # -------------------------------------------------------------------------
257
  for idx, sa_row in statements.iterrows():
258
  branch = str(sa_row['Extracted_Branch'])
@@ -264,62 +272,34 @@ def process_reconciliation(file_main, file_mapping, file_mid, start_match_id):
264
  sa_text = str(sa_row['Item Text']).upper()
265
 
266
  is_barclaycard = "BARCLAYCARD" in sa_text
267
- days_span = 6 if is_barclaycard else 3
268
  lookback_start = sa_date - pd.offsets.BDay(days_span)
269
 
270
  matched_subset = None
271
  match_type = ''
272
 
273
- # Step A: Scan single-day perfect aggregate nets first (Preserves precise matching)
274
- curr_date = sa_date
275
- while curr_date >= lookback_start:
276
- day_key = (branch, curr_date)
277
- if day_key in cb_daily_map:
278
- day_rows = [r for r in cb_daily_map[day_key] if r['orig_index'] not in used_cashbook_indices]
279
- if day_rows:
280
- day_sum = round(sum(r['Amount'] for r in day_rows), 2)
281
-
282
- if day_sum == target_cb_sum:
283
- matched_subset = day_rows
284
- match_type = 'Pass (Daily Agg)'
285
- break
286
- elif day_sum == round(2 * target_cb_sum, 2):
287
- freq_map = defaultdict(list)
288
- for r in day_rows:
289
- freq_map[round(r['Amount'], 2)].append(r)
290
- if all(len(v) % 2 == 0 for v in freq_map.values()):
291
- halved_subset = []
292
- for amt, r_list in freq_map.items():
293
- halved_subset.extend(r_list[:len(r_list) // 2])
294
- matched_subset = halved_subset
295
- match_type = 'Pass (Duplicate Day Split)'
296
- break
297
- curr_date -= pd.Timedelta(days=1)
298
-
299
- # Step B: Cross-Day Bounded Combinations (Accounts for multi-day settlement roll-ups)
300
- if not matched_subset:
301
- all_branch_rows = cb_branch_window_pool.get(branch, [])
302
- # Pool all active cashbook records across the entire lookback window
303
- window_rows = [
304
- r for r in all_branch_rows
305
- if lookback_start <= r['Journal Entry Date'] <= sa_date and r['orig_index'] not in used_cashbook_indices
306
- ]
307
- if window_rows:
308
- total_window_sum = round(sum(r['Amount'] for r in window_rows), 2)
309
- if total_window_sum == target_cb_sum:
310
- matched_subset = window_rows
311
- match_type = 'Pass (Many-to-One Window Pool)'
312
- elif len(window_rows) <= 35: # Safe computational limit for combinations
313
- matched_combo = None
314
- for r_len in range(2, 4):
315
- for combo in itertools.combinations(window_rows, r_len):
316
- if round(sum(x['Amount'] for x in combo), 2) == target_cb_sum:
317
- matched_combo = list(combo)
318
- break
319
- if matched_combo: break
320
- if matched_combo:
321
- matched_subset = matched_combo
322
- match_type = 'Pass (Cross-Day Bounded Combo)'
323
 
324
  if matched_subset:
325
  match_id = f"SAP_MATCH_{str(match_counter).zfill(5)}"
@@ -340,7 +320,7 @@ def process_reconciliation(file_main, file_mapping, file_mid, start_match_id):
340
  match_counter += 1
341
 
342
  # -------------------------------------------------------------------------
343
- # REVISED PASS 2B: SAP BACKLOG RESCUE PASS WITH CROSS-DAY COMBOS
344
  # -------------------------------------------------------------------------
345
  unreconciled_statements = statements[~statements.index.isin(used_statement_indices)]
346
 
@@ -359,43 +339,23 @@ def process_reconciliation(file_main, file_mapping, file_mid, start_match_id):
359
  matched_subset = None
360
  match_type = ''
361
 
362
- # Step A: Extended single-day aggregates
363
- curr_date = sa_date
364
- while curr_date >= lookback_start_extended:
365
- day_key = (branch, curr_date)
366
- if day_key in cb_daily_map:
367
- day_rows = [r for r in cb_daily_map[day_key] if r['orig_index'] not in used_cashbook_indices]
368
- if day_rows:
369
- day_sum = round(sum(r['Amount'] for r in day_rows), 2)
370
- if day_sum == target_cb_sum:
371
- matched_subset = day_rows
372
- match_type = 'Pass (Extended Backlog Agg)'
373
- break
374
- curr_date -= pd.Timedelta(days=1)
375
-
376
- # Step B: Extended Cross-day window combos
377
- if not matched_subset:
378
- all_branch_rows = cb_branch_window_pool.get(branch, [])
379
- window_rows = [
380
- r for r in all_branch_rows
381
- if lookback_start_extended <= r['Journal Entry Date'] <= sa_date and r['orig_index'] not in used_cashbook_indices
382
- ]
383
- if window_rows:
384
- total_window_sum = round(sum(r['Amount'] for r in window_rows), 2)
385
- if total_window_sum == target_cb_sum:
386
- matched_subset = window_rows
387
- match_type = 'Pass (Extended Backlog Pool)'
388
- elif len(window_rows) <= 35:
389
- matched_combo = None
390
- for r_len in range(2, 4):
391
- for combo in itertools.combinations(window_rows, r_len):
392
- if round(sum(x['Amount'] for x in combo), 2) == target_cb_sum:
393
- matched_combo = list(combo)
394
- break
395
- if matched_combo: break
396
- if matched_combo:
397
- matched_subset = matched_combo
398
- match_type = 'Pass (Extended Cross-Day Combo)'
399
 
400
  if matched_subset:
401
  match_id = f"SAP_MATCH_{str(match_counter).zfill(5)}"
 
4
  import re
5
  import tempfile
6
  import os
7
+ import sys
8
+
9
+ # Increase recursion depth for deep combinatorial matching pools safely
10
+ sys.setrecursionlimit(5000)
11
 
12
  def clean_amount_fixed(val):
13
  """Advanced decimal parser that strips out hidden layout spaces after minus signs."""
 
16
  if isinstance(val, (int, float)):
17
  return float(val)
18
  val_str = str(val).replace(',', '').replace('GBP', '').strip()
 
19
  val_str = re.sub(r'\s+', '', val_str)
20
  if val_str.endswith('-'):
21
  val_str = '-' + val_str[:-1]
 
38
  if pd.isna(asg_text):
39
  return None
40
  asg_str = str(asg_text).strip()
 
41
  matches = re.findall(r'\d{4}', asg_str)
42
  for m in matches:
43
  if m in valid_set:
44
  return m
 
 
45
  matches_3 = re.findall(r'\b\d{3}\b|\d{3}', asg_str)
46
  for m in matches_3:
47
  padded = m.zfill(4)
 
58
  text_str = str(text).strip() if pd.notna(text) else ""
59
  asg_clean_str = str(assignment_clean).strip() if pd.notna(assignment_clean) else ""
60
 
 
61
  if asg_clean_str in till_map:
62
  return till_map[asg_clean_str]
63
 
 
76
  parts = text_str.split('*')
77
  if len(parts) > 2: return normalize_branch_string(parts[2])
78
 
 
79
  match_start_four = re.match(r'^(\d{4})\b', text_str)
80
  if match_start_four: return normalize_branch_string(match_start_four.group(1))
81
  match_sa = re.search(r'-000(\d{3,4})', text_str)
 
87
  match_generic = re.search(r'\b(\d{3,4})\b', text_str)
88
  if match_generic: return normalize_branch_string(match_generic.group(1))
89
 
 
90
  if text_str:
91
  if text_str in till_map:
92
  return till_map[text_str]
 
93
  digit_sequences = re.findall(r'\d+', text_str)
94
  for seq in digit_sequences:
95
  if seq in till_map:
96
  return till_map[seq]
 
 
97
  padded_seq = seq.zfill(8)
98
  if padded_seq in till_map:
99
  return till_map[padded_seq]
100
 
 
101
  text_asg_br = extract_branch_from_assignment(text, valid_set)
102
  if text_asg_br:
103
  return text_asg_br
104
 
 
105
  match_dash_sa = re.search(r'-(\d{3,4})\b', text_str)
106
  if match_dash_sa:
107
  return normalize_branch_string(match_dash_sa.group(1))
108
 
109
  return None
110
 
111
+ def backtrack_subset_sum(remaining_items, target, current_selection=[], current_sum=0.0, start_index=0):
112
+ """High-speed recursive financial solver that finds combinations of any length with early pruning."""
113
+ if round(current_sum, 2) == target:
114
+ return current_selection
115
+ if current_sum > target + 0.01 or start_index >= len(remaining_items):
116
+ return None
117
+
118
+ for i in range(start_index, len(remaining_items)):
119
+ item = remaining_items[i]
120
+ if item['Amount'] <= 0: # Skip direct negative accounting corrections to prevent loops
121
+ continue
122
+ result = backtrack_subset_sum(
123
+ remaining_items,
124
+ target,
125
+ current_selection + [item],
126
+ current_sum + item['Amount'],
127
+ i + 1
128
+ )
129
+ if result is not None:
130
+ return result
131
+ return None
132
+
133
  def process_reconciliation(file_main, file_mapping, file_mid, start_match_id):
134
+ """High-speed multi-pass reconciliation engine featuring unrestricted-length multi-day matching solvers."""
135
  try:
136
  if file_main is None or file_mapping is None:
137
  raise ValueError("Missing file upload. Please provide both the Ledger and TILL mapping files.")
138
 
 
139
  main_path = file_main.path if hasattr(file_main, 'path') else file_main.name
140
  mapping_path = file_mapping.path if hasattr(file_mapping, 'path') else file_mapping.name
141
 
 
176
  except Exception as e:
177
  print(f"BPS Header Shift Handled: {str(e)}")
178
 
179
+ # Core branch extraction loop
180
  extracted_branches = []
181
  for idx, row in main_df.iterrows():
182
  br_res = extract_branch_advanced(
 
252
  used_statement_indices = set()
253
  used_cashbook_indices = set()
254
 
255
+ # Pre-pool active cashbook files by branch for multi-day windows
256
+ cb_by_branch_pool = defaultdict(list)
 
257
  for cb_row in cashbook.to_dict('records'):
258
  br = str(cb_row['Extracted_Branch'])
259
+ if br and br != 'None' and pd.notna(cb_row['Journal Entry Date']):
260
+ cb_by_branch_pool[br].append(cb_row)
 
 
261
 
262
  # -------------------------------------------------------------------------
263
+ # PASS 2: WINDOW-POOLED ADVANCED RECONCILIATION (UNRESTRICTED COMBOS)
264
  # -------------------------------------------------------------------------
265
  for idx, sa_row in statements.iterrows():
266
  branch = str(sa_row['Extracted_Branch'])
 
272
  sa_text = str(sa_row['Item Text']).upper()
273
 
274
  is_barclaycard = "BARCLAYCARD" in sa_text
275
+ days_span = 6 if is_barclaycard else 4
276
  lookback_start = sa_date - pd.offsets.BDay(days_span)
277
 
278
  matched_subset = None
279
  match_type = ''
280
 
281
+ # Gather available open items in the entire multi-day window pool
282
+ all_branch_rows = cb_by_branch_pool.get(branch, [])
283
+ window_rows = [
284
+ r for r in all_branch_rows
285
+ if lookback_start <= r['Journal Entry Date'] <= sa_date and r['orig_index'] not in used_cashbook_indices
286
+ ]
287
+
288
+ if window_rows:
289
+ # 1. Check if the entire multi-day window equals the bank statement
290
+ total_window_sum = round(sum(r['Amount'] for r in window_rows), 2)
291
+ if total_window_sum == target_cb_sum:
292
+ matched_subset = window_rows
293
+ match_type = 'Pass (Many-to-One Window Pool)'
294
+ else:
295
+ # 2. Run the advanced backtracking solver (unrestricted length matching)
296
+ # Sort descending to find matches and prune impossible paths quickly
297
+ sorted_window = sorted(window_rows, key=lambda x: x['Amount'], reverse=True)
298
+ # Cap the pool to the best 40 items to ensure lightning-fast browser speeds
299
+ result_combo = backtrack_subset_sum(sorted_window[:40], target_cb_sum)
300
+ if result_combo:
301
+ matched_subset = result_combo
302
+ match_type = 'Pass (Cross-Day Bounded Combo)'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
303
 
304
  if matched_subset:
305
  match_id = f"SAP_MATCH_{str(match_counter).zfill(5)}"
 
320
  match_counter += 1
321
 
322
  # -------------------------------------------------------------------------
323
+ # PASS 2B: SAP BACKLOG RESCUE PASS (EXTENDED 90-DAY UNRESTRICTED SEARCH)
324
  # -------------------------------------------------------------------------
325
  unreconciled_statements = statements[~statements.index.isin(used_statement_indices)]
326
 
 
339
  matched_subset = None
340
  match_type = ''
341
 
342
+ all_branch_rows = cb_by_branch_pool.get(branch, [])
343
+ window_rows = [
344
+ r for r in all_branch_rows
345
+ if lookback_start_extended <= r['Journal Entry Date'] <= sa_date and r['orig_index'] not in used_cashbook_indices
346
+ ]
347
+
348
+ if window_rows:
349
+ total_window_sum = round(sum(r['Amount'] for r in window_rows), 2)
350
+ if total_window_sum == target_cb_sum:
351
+ matched_subset = window_rows
352
+ match_type = 'Pass (Extended Backlog Pool)'
353
+ else:
354
+ sorted_window = sorted(window_rows, key=lambda x: x['Amount'], reverse=True)
355
+ result_combo = backtrack_subset_sum(sorted_window[:40], target_cb_sum)
356
+ if result_combo:
357
+ matched_subset = result_combo
358
+ match_type = 'Pass (Extended Cross-Day Combo)'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
359
 
360
  if matched_subset:
361
  match_id = f"SAP_MATCH_{str(match_counter).zfill(5)}"