yassine123Z commited on
Commit
e7beeb7
Β·
verified Β·
1 Parent(s): bff9df0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +340 -188
app.py CHANGED
@@ -74,26 +74,52 @@ ref_data = pd.DataFrame({
74
  "Metal","Organic materials","Paper and cardboard","Batteries and accumulators","Plastics",
75
  "Fugitive process emissions","Textiles","Glass",
76
  "Electricity for electric vehicles","Renewables","Standard"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  ]
78
  })
79
 
 
 
 
80
  # Get unique categories for dropdowns
81
  unique_cat1 = sorted(ref_data["Cat1EN"].unique().tolist())
82
- cat1_to_cat2 = ref_data.groupby("Cat1EN")["Cat2EN"].apply(list).to_dict()
83
-
84
- ref_data["combined"] = ref_data[["Cat1EN", "Cat2EN"]].agg(" ".join, axis=1)
85
- ref_embeddings = model.encode(ref_data["combined"].tolist())
86
 
87
  # ==================================================
88
  # πŸ’Ύ Storage for batch data and corrections
89
  # ==================================================
90
- batch_results = None
91
  corrections_data = []
92
 
93
  # ==================================================
94
  # πŸ” Core Classification Logic
95
  # ==================================================
96
- def classify_transaction(text: str, top_k=1):
 
97
  if not text or text.strip() == "":
98
  return []
99
 
@@ -113,165 +139,245 @@ def classify_transaction(text: str, top_k=1):
113
 
114
  return results
115
 
 
 
 
 
 
 
 
 
 
 
 
116
  # ==================================================
117
- # πŸ“‚ Batch Processing with Interactive UI
118
  # ==================================================
119
- def process_csv(file):
120
- """Process CSV and create interactive correction UI"""
121
  global batch_results
122
 
123
- if file is None:
124
- return None, "Please upload a CSV file"
125
-
126
  try:
 
 
 
127
  df = pd.read_csv(file.name)
128
  if "transaction" not in df.columns:
129
- return None, "Error: Missing 'transaction' column"
130
 
131
  results = []
132
  for idx, text in enumerate(df["transaction"]):
133
  if pd.isna(text) or str(text).strip() == "":
134
  continue
135
 
136
- matches = classify_transaction(str(text))
137
- if not matches:
138
  continue
139
 
140
  results.append({
141
- "id": idx + 1,
142
- "transaction": str(text)[:100],
143
- "predicted_cat1": matches[0]["cat1"],
144
- "predicted_cat2": matches[0]["cat2"],
145
- "confidence": round(matches[0]["score"], 3)
 
 
 
 
 
 
 
146
  })
147
 
148
  if not results:
149
- return None, "No valid transactions found"
150
 
151
  batch_results = pd.DataFrame(results)
152
- return create_correction_interface(batch_results), f"Processed {len(results)} transactions. Use dropdowns to correct categories."
 
 
153
 
154
  except Exception as e:
155
- return None, f"Error: {str(e)}"
156
-
157
- def create_correction_interface(df):
158
- """Create interactive correction interface with dropdowns"""
159
- components = []
160
-
161
- for _, row in df.iterrows():
162
- with gr.Group():
163
- with gr.Row():
164
- gr.Textbox(
165
- value=row["transaction"],
166
- label="Transaction",
167
- interactive=False,
168
- scale=2
169
- )
170
-
171
- gr.Textbox(
172
- value=row["predicted_cat1"],
173
- label="Predicted Cat1",
174
- interactive=False
175
- )
176
-
177
- gr.Textbox(
178
- value=row["predicted_cat2"],
179
- label="Predicted Cat2",
180
- interactive=False
181
- )
182
-
183
- gr.Number(
184
- value=row["confidence"],
185
- label="Confidence",
186
- interactive=False
187
- )
188
-
189
- with gr.Row():
190
- cat1_dropdown = gr.Dropdown(
191
- choices=unique_cat1,
192
- value=row["predicted_cat1"],
193
- label="Corrected Cat1",
194
- interactive=True
195
- )
196
-
197
- cat2_dropdown = gr.Dropdown(
198
- choices=cat1_to_cat2.get(row["predicted_cat1"], []),
199
- value=row["predicted_cat2"],
200
- label="Corrected Cat2",
201
- interactive=True
202
- )
203
-
204
- gr.HTML("<hr>")
205
-
206
- # Store original data
207
- cat1_dropdown.original_cat1 = row["predicted_cat1"]
208
- cat1_dropdown.original_cat2 = row["predicted_cat2"]
209
- cat1_dropdown.transaction = row["transaction"]
210
- cat1_dropdown.confidence = row["confidence"]
211
- cat2_dropdown.original_cat1 = row["predicted_cat1"]
212
- cat2_dropdown.original_cat2 = row["predicted_cat2"]
213
- cat2_dropdown.transaction = row["transaction"]
214
- cat2_dropdown.confidence = row["confidence"]
215
-
216
- components.extend([cat1_dropdown, cat2_dropdown])
217
-
218
- return components
219
-
220
- def update_cat2_dropdown(cat1_value):
221
- """Update Cat2 dropdown based on selected Cat1"""
222
- return gr.Dropdown(choices=cat1_to_cat2.get(cat1_value, []), interactive=True)
223
 
224
- def save_all_corrections(*corrected_values):
225
- """Save all corrections from the interactive interface"""
226
- global corrections_data
227
-
228
- corrections = []
229
- saved_count = 0
230
 
231
- # Process pairs of values (cat1, cat2 for each transaction)
232
- for i in range(0, len(corrected_values), 2):
233
- if i + 1 < len(corrected_values):
234
- corrected_cat1 = corrected_values[i]
235
- corrected_cat2 = corrected_values[i + 1]
236
-
237
- # Get original values from component attributes
238
- original_cat1 = getattr(corrected_values[i], 'original_cat1', '')
239
- original_cat2 = getattr(corrected_values[i], 'original_cat2', '')
240
- transaction = getattr(corrected_values[i], 'transaction', '')
241
- confidence = getattr(corrected_values[i], 'confidence', 0)
 
 
 
 
 
 
242
 
243
- if corrected_cat1 != original_cat1 or corrected_cat2 != original_cat2:
244
- saved_count += 1
245
- corrections.append({
 
246
  "timestamp": datetime.now().isoformat(),
247
- "transaction": transaction,
248
- "predicted_cat1": original_cat1,
249
- "predicted_cat2": original_cat2,
250
- "corrected_cat1": corrected_cat1,
251
- "corrected_cat2": corrected_cat2,
252
- "confidence": confidence
253
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
 
255
- corrections_data.extend(corrections)
 
 
 
 
 
 
 
 
 
256
 
257
- # Save to files
258
  tmp_dir = tempfile.mkdtemp()
259
- training_file = None
260
-
261
- if corrections:
262
- training_df = pd.DataFrame(corrections)
263
- training_file = os.path.join(tmp_dir, f"training_corrections_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv")
264
- training_df.to_csv(training_file, index=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
 
266
- return f"Saved {saved_count} corrections. Total in memory: {len(corrections_data)}", training_file
 
 
 
267
 
268
  # ==================================================
269
- # πŸ–₯️ Enhanced Gradio UI
270
  # ==================================================
271
  with gr.Blocks(title="Transaction Category Classifier", theme=gr.themes.Soft()) as main_ui:
272
- gr.Markdown("# Transaction Category Classifier")
273
-
274
- with gr.Tab("Single Classification"):
 
275
  with gr.Row():
276
  with gr.Column():
277
  text_input = gr.Textbox(
@@ -279,90 +385,136 @@ with gr.Blocks(title="Transaction Category Classifier", theme=gr.themes.Soft())
279
  placeholder="e.g., Plane ticket to Barcelona",
280
  lines=2
281
  )
282
- btn_submit = gr.Button("Classify", variant="primary")
283
 
284
  with gr.Column():
285
- cat1_out = gr.Textbox(label="Category 1", interactive=False)
286
- cat2_out = gr.Textbox(label="Category 2", interactive=False)
287
  score_out = gr.Number(label="Confidence Score")
288
 
289
  btn_submit.click(
290
- fn=lambda x: classify_transaction(x)[0] if classify_transaction(x) else ("", "", 0),
291
- inputs=text_input,
292
  outputs=[cat1_out, cat2_out, score_out]
293
  )
294
 
295
- with gr.Tab("Batch Correction"):
296
  gr.Markdown("""
297
- **Fast Batch Correction with Dropdowns**
298
- 1. Upload CSV with 'transaction' column
299
- 2. Review predictions and use dropdowns to correct
300
- 3. Save all corrections at once
301
  """)
302
 
303
- with gr.Row():
304
- csv_input = gr.File(label="Upload CSV", file_types=[".csv"])
305
- process_btn = gr.Button("Process & Show Corrections", variant="primary")
306
 
307
- process_status = gr.Textbox(label="Status", interactive=False)
308
 
309
- # Dynamic container for correction interface
310
- correction_components = gr.State([])
311
- correction_interface = gr.Column()
 
 
 
 
 
312
 
313
- save_btn = gr.Button("Save All Corrections", variant="primary")
314
- save_status = gr.Textbox(label="Save Status", interactive=False)
315
- download_training = gr.File(label="Download Training Data")
 
316
 
317
- def update_interface(file):
318
- interface, status = process_csv(file)
319
- return interface, status, gr.Column(interface) if interface else gr.Column()
320
 
321
- process_btn.click(
322
- fn=update_interface,
323
- inputs=csv_input,
324
- outputs=[correction_components, process_status, correction_interface]
325
  )
326
 
327
- save_btn.click(
328
- fn=save_all_corrections,
329
- inputs=correction_components,
330
- outputs=[save_status, download_training]
331
  )
332
 
333
- with gr.Tab("Corrections History"):
334
- gr.Markdown("View and export correction history")
 
 
 
 
335
 
336
  with gr.Row():
337
- refresh_btn = gr.Button("Refresh")
338
- export_btn = gr.Button("Export All", variant="primary")
339
-
340
- corrections_table = gr.DataFrame(interactive=False)
341
- export_status = gr.Textbox(interactive=False)
342
- export_file = gr.File(interactive=False)
343
-
344
- def show_corrections():
345
- if not corrections_data:
346
- return pd.DataFrame({"Message": ["No corrections yet"]}), "No data to export", None
347
- df = pd.DataFrame(corrections_data)
348
- return df, f"Total corrections: {len(corrections_data)}", None
349
-
350
- def export_corrections():
351
- if not corrections_data:
352
- return None, "No corrections to export"
353
- df = pd.DataFrame(corrections_data)
354
- tmp_dir = tempfile.mkdtemp()
355
- file_path = os.path.join(tmp_dir, f"all_corrections_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv")
356
- df.to_csv(file_path, index=False)
357
- return file_path, f"Exported {len(corrections_data)} corrections"
358
-
359
- refresh_btn.click(show_corrections, outputs=[corrections_table, export_status, export_file])
360
- export_btn.click(export_corrections, outputs=[export_file, export_status])
 
 
 
361
 
362
  # ==================================================
363
  # 🌐 Mount Gradio App
364
  # ==================================================
365
  app = gr.mount_gradio_app(app, main_ui, path="/")
366
 
367
- print("Enhanced app initialized with dropdown correction interface!")
368
- print("Access at: /")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  "Metal","Organic materials","Paper and cardboard","Batteries and accumulators","Plastics",
75
  "Fugitive process emissions","Textiles","Glass",
76
  "Electricity for electric vehicles","Renewables","Standard"
77
+ ],
78
+ "DescriptionCat2EN": [
79
+ "Goods purchase - sports","Goods purchase - buildings","Goods purchase - office items","Goods purchase - water",
80
+ "Goods purchase - appliances","Goods purchase - electricals","Goods purchase - machinery","Goods purchase - furniture",
81
+ "Goods purchase - textiles","Goods purchase - vehicles","Material purchase - construction","Material purchase - organic",
82
+ "Material purchase - paper","Material purchase - plastics","Material purchase - chemicals","Material purchase - refrigerants",
83
+ "Service - equipment rental","Service - building rental","Service - furniture rental","Service - vehicles",
84
+ "Service - info/culture","Service - catering","Service - healthcare","Service - crafts",
85
+ "Service - admin/consulting","Service - cleaning","Service - IT","Service - logistics",
86
+ "Service - marketing","Service - technical","Beverages - alcoholic","Beverages - non-alcoholic",
87
+ "Food condiments","Food desserts","Food fruits & vegetables","Food fats & oils","Prepared meals",
88
+ "Animal-based food","Cereal-based food","Dairy products","Heating - heat & steam","Heating - cooling/refrigeration",
89
+ "Fuel - fossil","Fuel - mobile fossil","Fuel - organic","Fuel - gaseous","Fuel - liquid","Fuel - solid",
90
+ "Freight transport - air","Freight transport - ship","Freight transport - truck","Freight transport - combined",
91
+ "Freight transport - train",
92
+ "Passenger transport - air","Passenger transport - bus","Passenger transport - ship",
93
+ "Passenger transport - combined","Passenger transport - e-bike","Passenger transport - accommodation/events",
94
+ "Passenger transport - soft mobility","Passenger transport - scooter/motorbike","Passenger transport - train",
95
+ "Passenger transport - public","Passenger transport - car",
96
+ "Emissions - agriculture","Emissions - warming potential",
97
+ "Emissions - industry",
98
+ "Waste - commercial/industrial","Waste - wastewater","Waste - electricals",
99
+ "Waste - households","Waste - metals","Waste - organics","Waste - paper","Waste - batteries",
100
+ "Waste - plastics","Waste - fugitive","Waste - textiles","Waste - glass",
101
+ "Electricity - EVs","Electricity - renewables","Electricity - standard"
102
  ]
103
  })
104
 
105
+ ref_data["combined"] = ref_data[["Cat1EN", "Cat2EN", "DescriptionCat2EN"]].agg(" ".join, axis=1)
106
+ ref_embeddings = model.encode(ref_data["combined"].tolist())
107
+
108
  # Get unique categories for dropdowns
109
  unique_cat1 = sorted(ref_data["Cat1EN"].unique().tolist())
110
+ unique_cat2 = sorted(ref_data["Cat2EN"].unique().tolist())
 
 
 
111
 
112
  # ==================================================
113
  # πŸ’Ύ Storage for batch data and corrections
114
  # ==================================================
115
+ batch_results = None # Store current batch for editing
116
  corrections_data = []
117
 
118
  # ==================================================
119
  # πŸ” Core Classification Logic
120
  # ==================================================
121
+ def classify_transaction(text: str, top_k=3):
122
+ """Classify with top-K results"""
123
  if not text or text.strip() == "":
124
  return []
125
 
 
139
 
140
  return results
141
 
142
+ def classify_single(text: str):
143
+ """Single classification"""
144
+ if not text or text.strip() == "":
145
+ return "Please enter a transaction", "", 0.0
146
+
147
+ results = classify_transaction(text, top_k=1)
148
+ if not results:
149
+ return "No results", "", 0.0
150
+
151
+ return results[0]["cat1"], results[0]["cat2"], results[0]["score"]
152
+
153
  # ==================================================
154
+ # πŸ“‚ Batch Mapping with Review Table
155
  # ==================================================
156
+ def map_csv_for_review(file):
157
+ """Process CSV and return editable results"""
158
  global batch_results
159
 
 
 
 
160
  try:
161
+ if file is None:
162
+ return None, "⚠️ Please upload a CSV file"
163
+
164
  df = pd.read_csv(file.name)
165
  if "transaction" not in df.columns:
166
+ return None, "❌ Error: Missing column 'transaction'"
167
 
168
  results = []
169
  for idx, text in enumerate(df["transaction"]):
170
  if pd.isna(text) or str(text).strip() == "":
171
  continue
172
 
173
+ top_matches = classify_transaction(str(text), top_k=3)
174
+ if not top_matches:
175
  continue
176
 
177
  results.append({
178
+ "ID": idx + 1,
179
+ "Transaction": str(text)[:80], # Truncate long text
180
+ "Predicted_Cat1": top_matches[0]["cat1"],
181
+ "Predicted_Cat2": top_matches[0]["cat2"],
182
+ "Confidence": round(top_matches[0]["score"], 3),
183
+ "Corrected_Cat1": top_matches[0]["cat1"], # Default to predicted
184
+ "Corrected_Cat2": top_matches[0]["cat2"], # Default to predicted
185
+ "Status": "βœ… OK" if top_matches[0]["score"] > 0.8 else "⚠️ Review",
186
+ "Alt1_Cat1": top_matches[1]["cat1"] if len(top_matches) > 1 else "",
187
+ "Alt1_Cat2": top_matches[1]["cat2"] if len(top_matches) > 1 else "",
188
+ "Alt2_Cat1": top_matches[2]["cat1"] if len(top_matches) > 2 else "",
189
+ "Alt2_Cat2": top_matches[2]["cat2"] if len(top_matches) > 2 else "",
190
  })
191
 
192
  if not results:
193
+ return None, "❌ No valid transactions found"
194
 
195
  batch_results = pd.DataFrame(results)
196
+ status_msg = f"βœ… Processed {len(batch_results)} transactions. Review and edit the 'Corrected_Cat1' and 'Corrected_Cat2' columns, then click 'Save Corrections'."
197
+
198
+ return batch_results, status_msg
199
 
200
  except Exception as e:
201
+ return None, f"❌ Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
 
203
+ # ==================================================
204
+ # πŸ’Ύ Save Corrections from Edited Table
205
+ # ==================================================
206
+ def save_batch_corrections(edited_df):
207
+ """Save corrections from the edited dataframe"""
208
+ global corrections_data, batch_results
209
 
210
+ try:
211
+ if edited_df is None or len(edited_df) == 0:
212
+ return "⚠️ No data to save", None, None
213
+
214
+ # Convert to DataFrame if needed
215
+ if not isinstance(edited_df, pd.DataFrame):
216
+ edited_df = pd.DataFrame(edited_df)
217
+
218
+ # Count corrections (where corrected differs from predicted)
219
+ corrections_count = 0
220
+ new_corrections = []
221
+
222
+ for idx, row in edited_df.iterrows():
223
+ pred_cat1 = row.get("Predicted_Cat1", "")
224
+ pred_cat2 = row.get("Predicted_Cat2", "")
225
+ corr_cat1 = row.get("Corrected_Cat1", pred_cat1)
226
+ corr_cat2 = row.get("Corrected_Cat2", pred_cat2)
227
 
228
+ # Check if correction was made
229
+ if corr_cat1 != pred_cat1 or corr_cat2 != pred_cat2:
230
+ corrections_count += 1
231
+ new_corrections.append({
232
  "timestamp": datetime.now().isoformat(),
233
+ "transaction": row["Transaction"],
234
+ "predicted_cat1": pred_cat1,
235
+ "predicted_cat2": pred_cat2,
236
+ "corrected_cat1": corr_cat1,
237
+ "corrected_cat2": corr_cat2,
238
+ "confidence": row.get("Confidence", 0)
239
  })
240
+
241
+ # Add to global corrections
242
+ corrections_data.extend(new_corrections)
243
+
244
+ # Save final CSV with corrections
245
+ tmp_dir = tempfile.mkdtemp()
246
+
247
+ # Save corrected results
248
+ corrected_file = os.path.join(tmp_dir, f"corrected_results_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv")
249
+ edited_df.to_csv(corrected_file, index=False)
250
+
251
+ # Save only corrections (training data)
252
+ training_file = None
253
+ if new_corrections:
254
+ training_df = pd.DataFrame(new_corrections)
255
+ training_file = os.path.join(tmp_dir, f"training_corrections_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv")
256
+ training_df.to_csv(training_file, index=False)
257
+
258
+ status_msg = f"βœ… Saved!\nπŸ“Š Total rows: {len(edited_df)}\n✏️ Corrections made: {corrections_count}\nπŸ’Ύ Total corrections in memory: {len(corrections_data)}"
259
+
260
+ return status_msg, corrected_file, training_file
261
 
262
+ except Exception as e:
263
+ return f"❌ Error saving: {str(e)}", None, None
264
+
265
+ # ==================================================
266
+ # πŸ“₯ Export All Corrections
267
+ # ==================================================
268
+ def export_all_corrections():
269
+ """Export all accumulated corrections"""
270
+ if not corrections_data:
271
+ return None, "⚠️ No corrections to export yet"
272
 
273
+ df = pd.DataFrame(corrections_data)
274
  tmp_dir = tempfile.mkdtemp()
275
+ output_path = os.path.join(tmp_dir, f"all_corrections_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv")
276
+ df.to_csv(output_path, index=False)
277
+ return output_path, f"βœ… Exported {len(corrections_data)} total corrections for model training"
278
+
279
+ def show_corrections():
280
+ """Display current corrections"""
281
+ if not corrections_data:
282
+ return pd.DataFrame({"message": ["No corrections saved yet. Upload a CSV and make corrections!"]})
283
+ return pd.DataFrame(corrections_data)
284
+
285
+ # ==================================================
286
+ # πŸ”§ Model Comparison
287
+ # ==================================================
288
+ def compare_models_fixed(hf_model_url, file):
289
+ """Compare models"""
290
+ try:
291
+ if not hf_model_url or not hf_model_url.strip():
292
+ return "❌ Please provide a HuggingFace model ID", None
293
+
294
+ if file is None:
295
+ return "❌ Please upload a CSV file", None
296
+
297
+ df = pd.read_csv(file.name)
298
+ if "transaction" not in df.columns:
299
+ return "❌ Missing column 'transaction' in CSV", None
300
+
301
+ print(f"Loading comparison model: {hf_model_url}")
302
+ try:
303
+ hf_model = SetFitModel.from_pretrained(hf_model_url.strip())
304
+ except Exception as e:
305
+ return f"❌ Failed to load model '{hf_model_url}': {str(e)}", None
306
+
307
+ print("Encoding reference data...")
308
+ local_embs = model.encode(ref_data["combined"].tolist())
309
+ hf_embs = hf_model.encode(ref_data["combined"].tolist())
310
+
311
+ results = []
312
+ max_samples = min(50, len(df))
313
+
314
+ print(f"Comparing {max_samples} samples...")
315
+ for idx, text in enumerate(df["transaction"][:max_samples]):
316
+ if pd.isna(text) or str(text).strip() == "":
317
+ continue
318
+
319
+ text = str(text)
320
+
321
+ trans_emb_local = model.encode([text])[0]
322
+ scores_local = util.pytorch_cos_sim(
323
+ torch.tensor(trans_emb_local),
324
+ torch.tensor(local_embs)
325
+ ).flatten()
326
+ best_idx_local = scores_local.argmax().item()
327
+
328
+ trans_emb_hf = hf_model.encode([text])[0]
329
+ scores_hf = util.pytorch_cos_sim(
330
+ torch.tensor(trans_emb_hf),
331
+ torch.tensor(hf_embs)
332
+ ).flatten()
333
+ best_idx_hf = scores_hf.argmax().item()
334
+
335
+ local_cat1 = ref_data.iloc[best_idx_local]["Cat1EN"]
336
+ local_cat2 = ref_data.iloc[best_idx_local]["Cat2EN"]
337
+ hf_cat1 = ref_data.iloc[best_idx_hf]["Cat1EN"]
338
+ hf_cat2 = ref_data.iloc[best_idx_hf]["Cat2EN"]
339
+
340
+ match = "βœ…" if (local_cat1 == hf_cat1 and local_cat2 == hf_cat2) else "❌"
341
+
342
+ results.append({
343
+ "Transaction": text[:50] + "..." if len(text) > 50 else text,
344
+ "Local_Cat1": local_cat1,
345
+ "Local_Cat2": local_cat2,
346
+ "Local_Conf": round(float(scores_local[best_idx_local]), 3),
347
+ "HF_Cat1": hf_cat1,
348
+ "HF_Cat2": hf_cat2,
349
+ "HF_Conf": round(float(scores_hf[best_idx_hf]), 3),
350
+ "Match": match
351
+ })
352
+
353
+ if not results:
354
+ return "❌ No valid transactions to compare", None
355
+
356
+ result_df = pd.DataFrame(results)
357
+ matches = (result_df["Match"] == "βœ…").sum()
358
+ match_rate = round(matches / len(result_df) * 100, 2)
359
+
360
+ summary = f"""βœ… Comparison Complete!
361
+ πŸ“Š Analyzed: {len(result_df)} transactions
362
+ 🎯 Match Rate: {match_rate}% ({matches}/{len(result_df)} matches)
363
+ πŸ“ Your Model: yassine123Z/EmissionFactor-mapper2-v2
364
+ πŸ“ Compared with: {hf_model_url}"""
365
+
366
+ return summary, result_df
367
 
368
+ except Exception as e:
369
+ import traceback
370
+ error_details = traceback.format_exc()
371
+ return f"❌ Error: {str(e)}\n\nDetails:\n{error_details}", None
372
 
373
  # ==================================================
374
+ # πŸ–₯️ Main Gradio UI
375
  # ==================================================
376
  with gr.Blocks(title="Transaction Category Classifier", theme=gr.themes.Soft()) as main_ui:
377
+ gr.Markdown("# 🧾 Transaction Category Classifier")
378
+ gr.Markdown("Upload CSV β†’ Review predictions in editable table β†’ Make corrections β†’ Save for training")
379
+
380
+ with gr.Tab("πŸ”Ή Single Transaction"):
381
  with gr.Row():
382
  with gr.Column():
383
  text_input = gr.Textbox(
 
385
  placeholder="e.g., Plane ticket to Barcelona",
386
  lines=2
387
  )
388
+ btn_submit = gr.Button("πŸ” Classify", variant="primary")
389
 
390
  with gr.Column():
391
+ cat1_out = gr.Textbox(label="Predicted Category 1", interactive=False)
392
+ cat2_out = gr.Textbox(label="Predicted Category 2", interactive=False)
393
  score_out = gr.Number(label="Confidence Score")
394
 
395
  btn_submit.click(
396
+ fn=classify_single,
397
+ inputs=text_input,
398
  outputs=[cat1_out, cat2_out, score_out]
399
  )
400
 
401
+ with gr.Tab("πŸ“‚ Batch Review & Correct"):
402
  gr.Markdown("""
403
+ ## πŸ“‹ How to use:
404
+ 1. **Upload CSV** with 'transaction' column
405
+ 2. **Review & Edit** the table below - modify 'Corrected_Cat1' and 'Corrected_Cat2' columns
406
+ 3. **Save** corrections for model training
407
  """)
408
 
409
+ csv_input = gr.File(label="πŸ“ Upload CSV file", file_types=[".csv"])
410
+ btn_process = gr.Button("πŸš€ Process & Load for Review", variant="primary", size="lg")
 
411
 
412
+ process_status = gr.Textbox(label="Status", lines=3, interactive=False)
413
 
414
+ gr.Markdown("### ✏️ Editable Results - Modify corrections directly in the table:")
415
+ review_table = gr.DataFrame(
416
+ label="Review & Edit Predictions (Edit 'Corrected_Cat1' and 'Corrected_Cat2' columns)",
417
+ interactive=True,
418
+ wrap=True
419
+ )
420
+
421
+ gr.Markdown("**Instructions:** Click any cell in 'Corrected_Cat1' or 'Corrected_Cat2' to edit. Use alternatives (Alt1, Alt2) as reference.")
422
 
423
+ with gr.Row():
424
+ btn_save = gr.Button("πŸ’Ύ Save All Corrections", variant="primary", size="lg")
425
+ btn_download_corrected = gr.File(label="πŸ“₯ Download Corrected Results")
426
+ btn_download_training = gr.File(label="πŸ“₯ Download Training Data (Corrections Only)")
427
 
428
+ save_status = gr.Textbox(label="Save Status", lines=4, interactive=False)
 
 
429
 
430
+ btn_process.click(
431
+ fn=map_csv_for_review,
432
+ inputs=csv_input,
433
+ outputs=[review_table, process_status]
434
  )
435
 
436
+ btn_save.click(
437
+ fn=save_batch_corrections,
438
+ inputs=review_table,
439
+ outputs=[save_status, btn_download_corrected, btn_download_training]
440
  )
441
 
442
+ with gr.Tab("πŸ“Š All Corrections History"):
443
+ gr.Markdown("### πŸ“œ View All Saved Corrections")
444
+ gr.Markdown("All corrections from all batches are stored here for model retraining.")
445
+
446
+ btn_refresh = gr.Button("πŸ”„ Refresh List")
447
+ corrections_table = gr.DataFrame(label="All Corrections", interactive=False)
448
 
449
  with gr.Row():
450
+ btn_export_all = gr.Button("πŸ“€ Export All Corrections", variant="primary")
451
+ export_all_file = gr.File(label="πŸ“₯ Download All Corrections CSV")
452
+ export_status = gr.Textbox(label="Export Status", interactive=False)
453
+
454
+ btn_refresh.click(fn=show_corrections, outputs=corrections_table)
455
+ btn_export_all.click(fn=export_all_corrections, outputs=[export_all_file, export_status])
456
+
457
+ with gr.Tab("πŸ”¬ Compare Models"):
458
+ gr.Markdown("## πŸ” Model Comparison Tool")
459
+ gr.Markdown("Compare your model with any HuggingFace SetFit model.")
460
+
461
+ hf_model_url = gr.Textbox(
462
+ label="HuggingFace Model ID",
463
+ placeholder="e.g., sentence-transformers/all-MiniLM-L6-v2"
464
+ )
465
+
466
+ compare_file = gr.File(label="Upload Test CSV", file_types=[".csv"])
467
+ compare_btn = gr.Button("πŸ”¬ Compare Models", variant="primary")
468
+
469
+ compare_summary = gr.Textbox(label="Comparison Summary", lines=6, interactive=False)
470
+ compare_results = gr.DataFrame(label="Detailed Results", interactive=False)
471
+
472
+ compare_btn.click(
473
+ fn=compare_models_fixed,
474
+ inputs=[hf_model_url, compare_file],
475
+ outputs=[compare_summary, compare_results]
476
+ )
477
 
478
  # ==================================================
479
  # 🌐 Mount Gradio App
480
  # ==================================================
481
  app = gr.mount_gradio_app(app, main_ui, path="/")
482
 
483
+ # ==================================================
484
+ # 🧾 REST API Endpoints
485
+ # ==================================================
486
+ class TransactionsRequest(BaseModel):
487
+ transactions: List[str]
488
+
489
+ @app.get("/health")
490
+ def health_check():
491
+ return {
492
+ "status": "healthy",
493
+ "model_loaded": model is not None,
494
+ "corrections_count": len(corrections_data)
495
+ }
496
+
497
+ @app.post("/map_categories")
498
+ def map_categories(request: TransactionsRequest):
499
+ results = []
500
+ for text in request.transactions:
501
+ cat1, cat2, score = classify_single(text)
502
+ results.append({
503
+ "input_text": text,
504
+ "best_Cat1": cat1,
505
+ "best_Cat2": cat2,
506
+ "similarity": score
507
+ })
508
+ return {"matches": results}
509
+
510
+ @app.get("/corrections")
511
+ def get_corrections():
512
+ return {
513
+ "corrections": corrections_data,
514
+ "count": len(corrections_data)
515
+ }
516
+
517
+ print("βœ… App initialized successfully!")
518
+ print("πŸ“ All features in one interface: /")
519
+ print("πŸ₯ Health Check: /health")
520
+ print("πŸ”Œ API: /map_categories, /corrections")