reportsautomatetech commited on
Commit
338531f
Β·
verified Β·
1 Parent(s): 68a6fa5

Create fraudlogseparator.py

Browse files
Files changed (1) hide show
  1. fraudlogseparator.py +414 -0
fraudlogseparator.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =============================================================================
2
+ # Fraud Log Publisher Resolver β€” Hugging Face Spaces (Gradio) App
3
+ # =============================================================================
4
+ # Drop your Excel file β†’ get fraud_resolved_*.xlsx + publisher_files_*.zip
5
+ # =============================================================================
6
+
7
+ import gradio as gr
8
+ import pandas as pd
9
+ import re, os, zipfile, time, math, tempfile, shutil
10
+ import xlsxwriter
11
+
12
+ # ── Colour constants ──────────────────────────────────────────────────────────
13
+ C_HDR="1F4E79"; C_HF="FFFFFF"
14
+ C_PRI="E2EFDA"; C_FB="FCE4D6"; C_UN="FFE0E0"
15
+ C_SUM="2E75B6"; C_ZEB="EBF3FB"; C_TOT="D6E4F0"; C_REMOVED="F2F2F2"
16
+
17
+ # ── Helpers ───────────────────────────────────────────────────────────────────
18
+ def parse_cols(v):
19
+ return [c.strip().strip('"').strip("'") for c in str(v).split(',') if c.strip()]
20
+
21
+ def extract_pub_id(val):
22
+ if val is None or str(val).strip() in ('', 'nan', 'None'):
23
+ return None
24
+ try:
25
+ return int(float(str(val).strip()))
26
+ except Exception:
27
+ m = re.match(r'^(\d+)', str(val).strip())
28
+ return int(m.group(1)) if m else None
29
+
30
+ def safe_val(v):
31
+ if v is None:
32
+ return ''
33
+ if isinstance(v, float) and math.isnan(v):
34
+ return ''
35
+ return v
36
+
37
+ def resolve(df, pid_col, fl_cols, pub_map, ms_map):
38
+ names = pd.Series('', index=df.index)
39
+ src = pd.Series('unresolved', index=df.index)
40
+ mask = pd.Series(True, index=df.index)
41
+ if pid_col in df.columns:
42
+ pri = df[pid_col].apply(extract_pub_id).map(pub_map)
43
+ ok = pri.notna()
44
+ names[ok] = pri[ok]; src[ok] = 'primary'; mask &= ~ok
45
+ for col in fl_cols:
46
+ if col in df.columns and mask.any():
47
+ fb = df.loc[mask, col].astype(str).str.strip().str.lower().map(ms_map)
48
+ ok2 = fb.notna()
49
+ names.loc[ok2[ok2].index] = fb[ok2]
50
+ src.loc[ok2[ok2].index] = 'fallback'
51
+ mask.loc[ok2[ok2].index] = False
52
+ if mask.any():
53
+ raw = df.get(pid_col, pd.Series('', index=df.index))
54
+ names[mask] = 'UNRESOLVED (id=' + raw[mask].astype(str) + ')'
55
+ return names, src
56
+
57
+ def sort_and_dedup(df, sort_cols, dedup_cols, tab_name, log):
58
+ original_len = len(df)
59
+ working = df.copy()
60
+ valid_sort = [c for c in sort_cols if c in working.columns]
61
+ valid_dedup = [c for c in dedup_cols if c in working.columns]
62
+ for c in sort_cols:
63
+ if c not in working.columns:
64
+ log.append(f" ⚠️ {tab_name}: sort col not found: '{c}'")
65
+ for c in dedup_cols:
66
+ if c not in working.columns:
67
+ log.append(f" ⚠️ {tab_name}: dedup col not found: '{c}'")
68
+ if valid_sort:
69
+ sort_keys = []
70
+ for col in valid_sort:
71
+ try:
72
+ working[f'__s_{col}'] = pd.to_datetime(working[col], errors='coerce')
73
+ sort_keys.append(f'__s_{col}')
74
+ except Exception:
75
+ sort_keys.append(col)
76
+ working = working.sort_values(sort_keys, ascending=True, na_position='last')
77
+ working = working.drop(columns=[k for k in sort_keys if k.startswith('__s_')], errors='ignore')
78
+ log.append(f" βœ“ {tab_name}: sorted ascending by {valid_sort}")
79
+ removed_df = pd.DataFrame(columns=df.columns)
80
+ if valid_dedup:
81
+ dup_mask = working.duplicated(subset=valid_dedup, keep='first')
82
+ removed_df = working[dup_mask].copy()
83
+ working = working[~dup_mask].copy()
84
+ log.append(f" βœ“ {tab_name}: deduped on {valid_dedup} β†’ "
85
+ f"kept {len(working):,}, removed {len(removed_df):,}")
86
+ return (working.reset_index(drop=True), removed_df.reset_index(drop=True),
87
+ {'original': original_len, 'kept': len(working), 'removed': len(removed_df),
88
+ 'sort_cols': valid_sort, 'dedup_cols': valid_dedup})
89
+
90
+ def build_summary(grp):
91
+ gb = (grp.groupby(['publishername', 'Media Source', '_tab'], sort=True)
92
+ .size().reset_index(name='Rows'))
93
+ pivot = gb.pivot_table(index=['publishername', 'Media Source'],
94
+ columns='_tab', values='Rows', aggfunc='sum', fill_value=0).reset_index()
95
+ pivot.columns.name = None
96
+ for c in ['pat', 'rtb']:
97
+ if c not in pivot.columns: pivot[c] = 0
98
+ pivot = pivot[['publishername', 'Media Source', 'pat', 'rtb']]
99
+ pivot.rename(columns={'pat': 'PAT Rows', 'rtb': 'RTB Rows'}, inplace=True)
100
+ pivot['Total Rows'] = pivot['PAT Rows'] + pivot['RTB Rows']
101
+ totals = pd.DataFrame([{'publishername': '── TOTAL ──', 'Media Source': '',
102
+ 'PAT Rows': pivot['PAT Rows'].sum(),
103
+ 'RTB Rows': pivot['RTB Rows'].sum(),
104
+ 'Total Rows': pivot['Total Rows'].sum()}])
105
+ return pd.concat([pivot, totals], ignore_index=True)
106
+
107
+ # ── xlsxwriter writers ────────────────────────────────────────────────────────
108
+ def xw_write_sheet(wb, name, df, src_list=None, src_fmts=None, hdr_fmt=None, def_fmt=None):
109
+ ws = wb.add_worksheet(name[:31])
110
+ ws.freeze_panes(1, 0); ws.set_column(0, len(df.columns)-1, 18)
111
+ for ci, cn in enumerate(df.columns): ws.write(0, ci, cn, hdr_fmt)
112
+ pub_ci = list(df.columns).index('publishername') if 'publishername' in df.columns else None
113
+ for ri, row_vals in enumerate(df.itertuples(index=False), 1):
114
+ for ci, val in enumerate(row_vals):
115
+ fmt = (src_fmts.get(src_list[ri-1], src_fmts['unresolved'])
116
+ if (src_list and pub_ci == ci) else def_fmt)
117
+ ws.write(ri, ci, safe_val(val), fmt)
118
+
119
+ def xw_write_tab_with_dedup(wb, sheet_name, kept_df, removed_df, stats,
120
+ src_list, src_fmts, hdr_fmt, def_fmt, rmvd_fmt):
121
+ ws = wb.add_worksheet(sheet_name[:31])
122
+ ws.freeze_panes(2, 0); ws.set_column(0, len(kept_df.columns)-1, 18)
123
+ nc = len(kept_df.columns)
124
+ stats_fmt = wb.add_format({'bold': True, 'italic': True, 'font_name': 'Arial', 'font_size': 9,
125
+ 'bg_color': '#D9E1F2', 'font_color': '#1F4E79'})
126
+ zeb = wb.add_format({'font_name': 'Arial', 'font_size': 9, 'bg_color': '#' + C_ZEB})
127
+ banner = (f"Sort: {stats['sort_cols']} | Dedup on: {stats['dedup_cols']} | "
128
+ f"Original: {stats['original']:,} βœ“ Kept: {stats['kept']:,} "
129
+ f"βœ— Removed: {stats['removed']:,}")
130
+ ws.merge_range(0, 0, 0, min(nc-1, 15), banner, stats_fmt)
131
+ for ci, cn in enumerate(kept_df.columns): ws.write(1, ci, cn, hdr_fmt)
132
+ pub_ci = list(kept_df.columns).index('publishername') if 'publishername' in kept_df.columns else None
133
+ row = 2
134
+ for ri, row_vals in enumerate(kept_df.itertuples(index=False)):
135
+ for ci, val in enumerate(row_vals):
136
+ if pub_ci == ci and src_list:
137
+ fmt = src_fmts.get(src_list[ri], src_fmts['unresolved'])
138
+ else:
139
+ fmt = zeb if ri % 2 == 0 else def_fmt
140
+ ws.write(row, ci, safe_val(val), fmt)
141
+ row += 1
142
+ if len(removed_df) > 0:
143
+ sep_fmt = wb.add_format({'bold': True, 'font_name': 'Arial', 'font_size': 10,
144
+ 'bg_color': '#' + C_UN, 'font_color': '#78281F'})
145
+ ws.merge_range(row, 0, row, min(nc-1, 15),
146
+ f"β–Ό REMOVED DUPLICATES ({stats['removed']:,} rows"
147
+ f" β€” duplicate {stats['dedup_cols']})", sep_fmt)
148
+ row += 1
149
+ for row_vals in removed_df.itertuples(index=False):
150
+ for ci, val in enumerate(row_vals): ws.write(row, ci, safe_val(val), rmvd_fmt)
151
+ row += 1
152
+
153
+ def xw_write_summary(wb, df, hdr_fmt, def_fmt):
154
+ ws = wb.add_worksheet('Summary')
155
+ ws.freeze_panes(1, 0); ws.set_column(0, 0, 24); ws.set_column(1, 1, 30); ws.set_column(2, 4, 14)
156
+ for ci, cn in enumerate(df.columns): ws.write(0, ci, cn, hdr_fmt)
157
+ zeb = wb.add_format({'font_name': 'Arial', 'font_size': 9, 'bg_color': '#' + C_ZEB})
158
+ tot = wb.add_format({'font_name': 'Arial', 'font_size': 9, 'bg_color': '#' + C_TOT, 'bold': True})
159
+ for ri, rv in enumerate(df.itertuples(index=False), 1):
160
+ rf = tot if str(rv[0]).startswith('──') else (zeb if ri % 2 == 0 else def_fmt)
161
+ for ci, val in enumerate(rv): ws.write(ri, ci, safe_val(val), rf)
162
+
163
+ def xw_legend(wb, fmts):
164
+ ws = wb.add_worksheet('Legend')
165
+ ws.set_column(0, 0, 26); ws.set_column(1, 1, 54)
166
+ for r, (a, b) in enumerate([
167
+ ('Colour', 'Meaning'),
168
+ ('Green β€” Primary', 'Sub Param 4 β†’ publisher tab lookup succeeded'),
169
+ ('Orange β€” Fallback', 'Media Source β†’ media source tab (fallback used)'),
170
+ ('Red β€” Unresolved','Publisher could not be resolved β€” review manually')
171
+ ]):
172
+ ws.write(r, 0, a, fmts[r]); ws.write(r, 1, b, fmts[r])
173
+
174
+ # ── Core processing function ──────────────────────────────────────────────────
175
+ def process_file(input_file):
176
+ if input_file is None:
177
+ return None, None, "❌ No file uploaded."
178
+
179
+ log = []
180
+ t0 = time.time()
181
+ def elapsed(): return f"[{time.time()-t0:.0f}s]"
182
+
183
+ # Create a temp working directory
184
+ work_dir = tempfile.mkdtemp()
185
+ INPUT_FILE = input_file.name
186
+ INPUT_STEM = os.path.splitext(os.path.basename(INPUT_FILE))[0]
187
+ OUTPUT_MAIN = os.path.join(work_dir, f"fraud_resolved_{INPUT_STEM}.xlsx")
188
+ OUTPUT_ZIP = os.path.join(work_dir, f"publisher_files_{INPUT_STEM}.zip")
189
+ TMP_DIR = os.path.join(work_dir, "publisher_exports")
190
+ os.makedirs(TMP_DIR, exist_ok=True)
191
+
192
+ try:
193
+ # ── Load ────────��─────────────────────────────────────────────────────
194
+ log.append(f"{elapsed()} πŸ“Š Loading workbook…")
195
+ try:
196
+ all_sheets = pd.read_excel(INPUT_FILE, sheet_name=None, dtype=str, engine='calamine')
197
+ except Exception:
198
+ all_sheets = pd.read_excel(INPUT_FILE, sheet_name=None, dtype=str)
199
+
200
+ missing = [t for t in ['input', 'pat', 'rtb', 'publisher', 'media source']
201
+ if t not in all_sheets]
202
+ if missing:
203
+ log.append(f"⚠️ Missing tabs: {missing}")
204
+
205
+ config = {}
206
+ for _, r in all_sheets.get('input', pd.DataFrame()).iterrows():
207
+ n = str(r.get('Name', '')).strip()
208
+ v = str(r.get('Value', '')).strip().strip('"').strip("'")
209
+ if n and n != 'nan': config[n] = v
210
+
211
+ pid_col = config.get('column to fetch publisher id from fraud logs- both rtb and pat', 'Sub Param 4')
212
+ fl_cols = parse_cols(config.get('fallback column in fraud logs to look for publisher name. If multiple then comma separated', 'Media Source'))
213
+ ms_cols = parse_cols(config.get('fallback column in media source TAB which should be used in case , publisher name cannot be resolved in fraud logs.. If multiple then comma separated', 'Media Source'))
214
+ sort_cols = parse_cols(config.get('Sort by column for fraud logs, if multiple then comma separated', ''))
215
+ dedup_cols= parse_cols(config.get('Remove Duplicate basis this column name from fraud logs , if multiple then comma separated', ''))
216
+
217
+ log.append(f" sort_cols={sort_cols} | dedup_cols={dedup_cols} | pid_col={pid_col}")
218
+
219
+ pub_map = {}
220
+ for _, r in all_sheets.get('publisher', pd.DataFrame()).iterrows():
221
+ pid = extract_pub_id(r.get('id')); pn = str(r.get('name', '')).strip()
222
+ if pid and pn and pn != 'nan': pub_map[pid] = pn
223
+
224
+ ms_map = {}
225
+ for _, r in all_sheets.get('media source', pd.DataFrame()).iterrows():
226
+ for col in ms_cols:
227
+ k = str(r.get(col, '')).strip().lower()
228
+ pv = str(r.get('Publisher', '')).strip()
229
+ if k and k != 'nan' and pv and pv != 'nan': ms_map[k] = pv
230
+
231
+ log.append(f" publisher_map={len(pub_map)} | ms_map={len(ms_map)}")
232
+ if not ms_map:
233
+ log.append(" ℹ️ media source tab is empty β€” fallback will not resolve any rows")
234
+
235
+ # ── Sort β†’ Dedup β†’ Resolve ────────────────────────────────────────────
236
+ log.append(f"\n{elapsed()} πŸ”„ Sort β†’ Dedup β†’ Resolve…")
237
+ resolved = {}; srcs = {}; removed = {}; dedup_stats = {}
238
+
239
+ for tab in ['pat', 'rtb']:
240
+ if tab not in all_sheets:
241
+ log.append(f" ⚠️ '{tab}' tab missing"); continue
242
+ df = all_sheets[tab].copy()
243
+ log.append(f"\n [{tab.upper()}] {len(df):,} rows")
244
+ df_clean, df_removed, stats = sort_and_dedup(df, sort_cols, dedup_cols, tab.upper(), log)
245
+ removed[tab] = df_removed; dedup_stats[tab] = stats
246
+ df_clean['publishername'], s = resolve(df_clean, pid_col, fl_cols, pub_map, ms_map)
247
+ resolved[tab] = df_clean; srcs[tab] = s
248
+ log.append(f" βœ“ publisher: 🟒primary={(s=='primary').sum():,} "
249
+ f"🟠fallback={(s=='fallback').sum():,} "
250
+ f"πŸ”΄unresolved={(s=='unresolved').sum():,}")
251
+
252
+ frames = []
253
+ for tab in ['pat', 'rtb']:
254
+ if tab in resolved:
255
+ d = resolved[tab].copy(); d.insert(0, '_tab', tab)
256
+ d['_src'] = srcs[tab].values; frames.append(d)
257
+ pub_groups = {}
258
+ if frames:
259
+ comb = pd.concat(frames, ignore_index=True)
260
+ for pn, grp in comb.groupby('publishername', sort=True):
261
+ pub_groups[pn] = grp
262
+
263
+ log.append(f"\n Publishers ({len(pub_groups)}):")
264
+ for p, g in sorted(pub_groups.items()):
265
+ log.append(f" β€’ {p:<32} {len(g):>6,} "
266
+ f"(PAT={(g['_tab']=='pat').sum():,} RTB={(g['_tab']=='rtb').sum():,})")
267
+
268
+ # ── Main Excel ────────────────────────────────────────────────────────
269
+ log.append(f"\n{elapsed()} πŸ“ Writing main Excel…")
270
+ wb_m = xlsxwriter.Workbook(OUTPUT_MAIN, {'constant_memory': True, 'strings_to_urls': False})
271
+ hdr_m = wb_m.add_format({'bold': True, 'font_name': 'Arial', 'font_size': 10,
272
+ 'bg_color': '#'+C_HDR, 'font_color': '#'+C_HF,
273
+ 'align': 'center', 'valign': 'vcenter', 'text_wrap': True})
274
+ def_m = wb_m.add_format({'font_name': 'Arial', 'font_size': 9})
275
+ srf_m = {k: wb_m.add_format({'font_name': 'Arial', 'font_size': 9, 'bg_color': '#'+bg})
276
+ for k, bg in [('primary', C_PRI), ('fallback', C_FB), ('unresolved', C_UN)]}
277
+ rmvd_fmt = wb_m.add_format({'font_name': 'Arial', 'font_size': 9,
278
+ 'bg_color': '#'+C_REMOVED, 'font_color': '#888888', 'italic': True})
279
+ leg_fmts = [wb_m.add_format({'bold': True, 'font_name': 'Arial', 'font_size': 10,
280
+ 'bg_color': '#'+bg, 'font_color': '#'+fg})
281
+ for bg, fg in [(C_HDR, C_HF), (C_PRI, '000000'), (C_FB, '000000'), (C_UN, '000000')]]
282
+
283
+ for tab in ['input', 'media source', 'publisher']:
284
+ df = all_sheets.get(tab)
285
+ if df is not None:
286
+ xw_write_sheet(wb_m, tab, df, hdr_fmt=hdr_m, def_fmt=def_m)
287
+ log.append(f" βœ“ '{tab}'")
288
+
289
+ for tab in ['pat', 'rtb']:
290
+ if tab in resolved:
291
+ xw_write_tab_with_dedup(wb_m, tab,
292
+ kept_df=resolved[tab], removed_df=removed[tab], stats=dedup_stats[tab],
293
+ src_list=srcs[tab].tolist(), src_fmts=srf_m,
294
+ hdr_fmt=hdr_m, def_fmt=def_m, rmvd_fmt=rmvd_fmt)
295
+ s = dedup_stats[tab]
296
+ log.append(f" βœ“ '{tab}' (kept={s['kept']:,} + removed={s['removed']:,})")
297
+
298
+ xw_legend(wb_m, leg_fmts)
299
+ wb_m.close()
300
+ log.append(f" βœ… fraud_resolved_{INPUT_STEM}.xlsx "
301
+ f"({os.path.getsize(OUTPUT_MAIN)/1024/1024:.1f} MB)")
302
+
303
+ # ── Publisher ZIP ─────────────────────────────────────────────────────
304
+ log.append(f"\n{elapsed()} πŸ“¦ Building publisher ZIP…")
305
+ pub_files = []
306
+ for pn, grp in sorted(pub_groups.items()):
307
+ safe = re.sub(r'[\\/*?:\[\]]', '_', pn)
308
+ fname = f"publisher_{safe}_{INPUT_STEM}.xlsx"
309
+ fpath = os.path.join(TMP_DIR, fname)
310
+ pat_s = grp[grp['_tab']=='pat'].drop(columns=['_tab','_src']).reset_index(drop=True)
311
+ rtb_s = grp[grp['_tab']=='rtb'].drop(columns=['_tab','_src']).reset_index(drop=True)
312
+ pat_src = grp.loc[grp['_tab']=='pat', '_src'].tolist()
313
+ rtb_src = grp.loc[grp['_tab']=='rtb', '_src'].tolist()
314
+ summary = build_summary(grp)
315
+ wb_p = xlsxwriter.Workbook(fpath, {'constant_memory': True, 'strings_to_urls': False})
316
+ hdr_s = wb_p.add_format({'bold': True, 'font_name': 'Arial', 'font_size': 10,
317
+ 'bg_color': '#'+C_SUM, 'font_color': '#'+C_HF,
318
+ 'align': 'center', 'valign': 'vcenter', 'text_wrap': True})
319
+ hdr_d = wb_p.add_format({'bold': True, 'font_name': 'Arial', 'font_size': 10,
320
+ 'bg_color': '#'+C_HDR, 'font_color': '#'+C_HF,
321
+ 'align': 'center', 'valign': 'vcenter', 'text_wrap': True})
322
+ def_p = wb_p.add_format({'font_name': 'Arial', 'font_size': 9})
323
+ srf_p = {k: wb_p.add_format({'font_name': 'Arial', 'font_size': 9, 'bg_color': '#'+bg})
324
+ for k, bg in [('primary', C_PRI), ('fallback', C_FB), ('unresolved', C_UN)]}
325
+
326
+ def move_pub_last(df, src):
327
+ if 'publishername' not in df.columns: return df, src
328
+ cols = [c for c in df.columns if c != 'publishername'] + ['publishername']
329
+ return df[cols], src
330
+
331
+ pat_s, pat_src = move_pub_last(pat_s, pat_src)
332
+ rtb_s, rtb_src = move_pub_last(rtb_s, rtb_src)
333
+ xw_write_summary(wb_p, summary, hdr_s, def_p)
334
+ if len(pat_s): xw_write_sheet(wb_p, 'pat', pat_s, src_list=pat_src, src_fmts=srf_p, hdr_fmt=hdr_d, def_fmt=def_p)
335
+ if len(rtb_s): xw_write_sheet(wb_p, 'rtb', rtb_s, src_list=rtb_src, src_fmts=srf_p, hdr_fmt=hdr_d, def_fmt=def_p)
336
+ wb_p.close()
337
+ pub_files.append(fpath)
338
+ log.append(f" β€’ {fname} ({os.path.getsize(fpath)//1024:,} KB)")
339
+
340
+ with zipfile.ZipFile(OUTPUT_ZIP, 'w', zipfile.ZIP_DEFLATED) as zf:
341
+ for fp in pub_files: zf.write(fp, os.path.basename(fp))
342
+ log.append(f" βœ… publisher_files_{INPUT_STEM}.zip "
343
+ f"({os.path.getsize(OUTPUT_ZIP)/1024/1024:.1f} MB)")
344
+ log.append(f"\n{elapsed()} πŸŽ‰ Done!")
345
+
346
+ return OUTPUT_MAIN, OUTPUT_ZIP, "\n".join(log)
347
+
348
+ except Exception as e:
349
+ import traceback
350
+ log.append(f"\n❌ ERROR: {e}")
351
+ log.append(traceback.format_exc())
352
+ return None, None, "\n".join(log)
353
+
354
+ # ── Gradio UI ─────────────────────────────────────────────────────────────────
355
+ with gr.Blocks(title="Fraud Log Publisher Resolver", theme=gr.themes.Soft()) as demo:
356
+
357
+ gr.Markdown("""
358
+ # πŸ” Fraud Log Publisher Resolver
359
+ Upload your Excel file to sort, deduplicate, and resolve publisher names across **PAT** and **RTB** fraud log tabs.
360
+
361
+ ### Expected Excel tabs
362
+ | Tab | Purpose |
363
+ |-----|---------|
364
+ | `input` | Configuration (Name / Value pairs) |
365
+ | `pat` | PAT fraud log rows |
366
+ | `rtb` | RTB fraud log rows |
367
+ | `publisher` | Publisher ID β†’ Name mapping |
368
+ | `media source` | Media source fallback mapping |
369
+
370
+ ### Colour key in output
371
+ 🟒 **Green** β€” resolved via Sub Param 4 β†’ publisher tab
372
+ 🟠 **Orange** β€” resolved via Media Source fallback
373
+ πŸ”΄ **Red** β€” unresolved
374
+ """)
375
+
376
+ with gr.Row():
377
+ with gr.Column(scale=1):
378
+ file_input = gr.File(
379
+ label="πŸ“‚ Upload Excel File (.xlsx)",
380
+ file_types=[".xlsx", ".xls"],
381
+ type="filepath"
382
+ )
383
+ run_btn = gr.Button("▢️ Process", variant="primary", size="lg")
384
+
385
+ with gr.Column(scale=1):
386
+ out_main = gr.File(label="πŸ“„ Download: fraud_resolved_*.xlsx")
387
+ out_zip = gr.File(label="πŸ“¦ Download: publisher_files_*.zip")
388
+
389
+ log_box = gr.Textbox(
390
+ label="πŸ“‹ Processing Log",
391
+ lines=20,
392
+ max_lines=40,
393
+ interactive=False,
394
+ placeholder="Processing log will appear here after you click ▢️ Process…"
395
+ )
396
+
397
+ # Wire up
398
+ class FileWrapper:
399
+ def __init__(self, path): self.name = path
400
+
401
+ def run(filepath):
402
+ if filepath is None:
403
+ return None, None, "❌ Please upload a file first."
404
+ return process_file(FileWrapper(filepath))
405
+
406
+ run_btn.click(fn=run, inputs=[file_input], outputs=[out_main, out_zip, log_box])
407
+
408
+ gr.Markdown("""
409
+ ---
410
+ *Built with [Gradio](https://gradio.app) Β· Deploy on [Hugging Face Spaces](https://huggingface.co/spaces)*
411
+ """)
412
+
413
+ if __name__ == "__main__":
414
+ demo.launch()