Update app.py
Browse files
app.py
CHANGED
@@ -1,529 +1,542 @@
|
|
1 |
-
from fastapi import FastAPI, HTTPException, BackgroundTasks, UploadFile, File, Form
|
2 |
-
from fastapi.responses import FileResponse
|
3 |
-
from pydantic import BaseModel
|
4 |
-
from typing import Optional, Dict, Any, List
|
5 |
-
import uvicorn
|
6 |
-
import torch
|
7 |
-
from torch.utils.data import DataLoader
|
8 |
-
import logging
|
9 |
-
import os
|
10 |
-
import asyncio
|
11 |
-
import pandas as pd
|
12 |
-
from datetime import datetime
|
13 |
-
import shutil
|
14 |
-
from pathlib import Path
|
15 |
-
from sklearn.model_selection import train_test_split
|
16 |
-
import zipfile
|
17 |
-
import io
|
18 |
-
import numpy as np
|
19 |
-
import sys
|
20 |
-
import json
|
21 |
-
|
22 |
-
|
23 |
-
# Import existing utilities
|
24 |
-
from dataset_utils import (
|
25 |
-
ComplianceDataset,
|
26 |
-
ComplianceDatasetWithMetadata,
|
27 |
-
load_and_preprocess_data,
|
28 |
-
get_tokenizer,
|
29 |
-
save_label_encoders,
|
30 |
-
get_num_labels,
|
31 |
-
load_label_encoders
|
32 |
-
)
|
33 |
-
from train_utils import (
|
34 |
-
initialize_criterions,
|
35 |
-
train_model,
|
36 |
-
evaluate_model,
|
37 |
-
save_model,
|
38 |
-
summarize_metrics,
|
39 |
-
predict_probabilities
|
40 |
-
)
|
41 |
-
from models.roberta_model import RobertaMultiOutputModel
|
42 |
-
from config import (
|
43 |
-
TEXT_COLUMN,
|
44 |
-
LABEL_COLUMNS,
|
45 |
-
DEVICE,
|
46 |
-
NUM_EPOCHS,
|
47 |
-
LEARNING_RATE,
|
48 |
-
MAX_LEN,
|
49 |
-
BATCH_SIZE,
|
50 |
-
METADATA_COLUMNS
|
51 |
-
)
|
52 |
-
|
53 |
-
# Configure logging
|
54 |
-
logging.basicConfig(level=logging.INFO)
|
55 |
-
logger = logging.getLogger(__name__)
|
56 |
-
|
57 |
-
app = FastAPI(title="RoBERTa Compliance Predictor API")
|
58 |
-
|
59 |
-
# Create necessary directories
|
60 |
-
UPLOAD_DIR = Path("uploads")
|
61 |
-
MODEL_SAVE_DIR = Path("saved_models")
|
62 |
-
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
63 |
-
MODEL_SAVE_DIR.mkdir(parents=True, exist_ok=True)
|
64 |
-
|
65 |
-
# Global variables to track training status
|
66 |
-
training_status = {
|
67 |
-
"is_training": False,
|
68 |
-
"current_epoch": 0,
|
69 |
-
"total_epochs": 0,
|
70 |
-
"current_loss": 0.0,
|
71 |
-
"start_time": None,
|
72 |
-
"end_time": None,
|
73 |
-
"status": "idle",
|
74 |
-
"metrics": None
|
75 |
-
}
|
76 |
-
|
77 |
-
# Load the model and tokenizer for prediction
|
78 |
-
model_path = "ROBERTA_model.pth"
|
79 |
-
tokenizer = get_tokenizer('roberta-base')
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
raise HTTPException(status_code=400, detail="
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
"
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
status
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
)
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
"""
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
#
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
465 |
-
|
466 |
-
|
467 |
-
|
468 |
-
|
469 |
-
|
470 |
-
|
471 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
|
506 |
-
|
507 |
-
|
508 |
-
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
514 |
-
|
515 |
-
|
516 |
-
|
517 |
-
|
518 |
-
|
519 |
-
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
|
524 |
-
|
525 |
-
|
526 |
-
|
527 |
-
|
528 |
-
|
529 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException, BackgroundTasks, UploadFile, File, Form
|
2 |
+
from fastapi.responses import FileResponse
|
3 |
+
from pydantic import BaseModel
|
4 |
+
from typing import Optional, Dict, Any, List
|
5 |
+
import uvicorn
|
6 |
+
import torch
|
7 |
+
from torch.utils.data import DataLoader
|
8 |
+
import logging
|
9 |
+
import os
|
10 |
+
import asyncio
|
11 |
+
import pandas as pd
|
12 |
+
from datetime import datetime
|
13 |
+
import shutil
|
14 |
+
from pathlib import Path
|
15 |
+
from sklearn.model_selection import train_test_split
|
16 |
+
import zipfile
|
17 |
+
import io
|
18 |
+
import numpy as np
|
19 |
+
import sys
|
20 |
+
import json
|
21 |
+
|
22 |
+
|
23 |
+
# Import existing utilities
|
24 |
+
from dataset_utils import (
|
25 |
+
ComplianceDataset,
|
26 |
+
ComplianceDatasetWithMetadata,
|
27 |
+
load_and_preprocess_data,
|
28 |
+
get_tokenizer,
|
29 |
+
save_label_encoders,
|
30 |
+
get_num_labels,
|
31 |
+
load_label_encoders
|
32 |
+
)
|
33 |
+
from train_utils import (
|
34 |
+
initialize_criterions,
|
35 |
+
train_model,
|
36 |
+
evaluate_model,
|
37 |
+
save_model,
|
38 |
+
summarize_metrics,
|
39 |
+
predict_probabilities
|
40 |
+
)
|
41 |
+
from models.roberta_model import RobertaMultiOutputModel
|
42 |
+
from config import (
|
43 |
+
TEXT_COLUMN,
|
44 |
+
LABEL_COLUMNS,
|
45 |
+
DEVICE,
|
46 |
+
NUM_EPOCHS,
|
47 |
+
LEARNING_RATE,
|
48 |
+
MAX_LEN,
|
49 |
+
BATCH_SIZE,
|
50 |
+
METADATA_COLUMNS
|
51 |
+
)
|
52 |
+
|
53 |
+
# Configure logging
|
54 |
+
logging.basicConfig(level=logging.INFO)
|
55 |
+
logger = logging.getLogger(__name__)
|
56 |
+
|
57 |
+
app = FastAPI(title="RoBERTa Compliance Predictor API")
|
58 |
+
|
59 |
+
# Create necessary directories
|
60 |
+
UPLOAD_DIR = Path("uploads")
|
61 |
+
MODEL_SAVE_DIR = Path("saved_models")
|
62 |
+
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
63 |
+
MODEL_SAVE_DIR.mkdir(parents=True, exist_ok=True)
|
64 |
+
|
65 |
+
# Global variables to track training status
|
66 |
+
training_status = {
|
67 |
+
"is_training": False,
|
68 |
+
"current_epoch": 0,
|
69 |
+
"total_epochs": 0,
|
70 |
+
"current_loss": 0.0,
|
71 |
+
"start_time": None,
|
72 |
+
"end_time": None,
|
73 |
+
"status": "idle",
|
74 |
+
"metrics": None
|
75 |
+
}
|
76 |
+
|
77 |
+
# Load the model and tokenizer for prediction
|
78 |
+
model_path = MODEL_SAVE_DIR / "ROBERTA_model.pth"
|
79 |
+
tokenizer = get_tokenizer('roberta-base')
|
80 |
+
|
81 |
+
# Initialize model and label encoders with error handling
|
82 |
+
try:
|
83 |
+
label_encoders = load_label_encoders()
|
84 |
+
model = RobertaMultiOutputModel([len(label_encoders[col].classes_) for col in LABEL_COLUMNS]).to(DEVICE)
|
85 |
+
if model_path.exists():
|
86 |
+
model.load_state_dict(torch.load(model_path, map_location=DEVICE))
|
87 |
+
model.eval()
|
88 |
+
else:
|
89 |
+
print(f"Warning: Model file {model_path} not found. Model will be initialized but not loaded.")
|
90 |
+
except Exception as e:
|
91 |
+
print(f"Warning: Could not load label encoders or model: {str(e)}")
|
92 |
+
print("Model will be initialized when training starts.")
|
93 |
+
model = None
|
94 |
+
|
95 |
+
class TrainingConfig(BaseModel):
|
96 |
+
model_name: str = "roberta-base"
|
97 |
+
batch_size: int = 8
|
98 |
+
learning_rate: float = 2e-5
|
99 |
+
num_epochs: int = 2
|
100 |
+
max_length: int = 128
|
101 |
+
random_state: int = 42
|
102 |
+
|
103 |
+
class TrainingResponse(BaseModel):
|
104 |
+
message: str
|
105 |
+
training_id: str
|
106 |
+
status: str
|
107 |
+
download_url: Optional[str] = None
|
108 |
+
|
109 |
+
class ValidationResponse(BaseModel):
|
110 |
+
message: str
|
111 |
+
metrics: Dict[str, Any]
|
112 |
+
predictions: List[Dict[str, Any]]
|
113 |
+
|
114 |
+
class TransactionData(BaseModel):
|
115 |
+
Transaction_Id: str
|
116 |
+
Hit_Seq: int
|
117 |
+
Hit_Id_List: str
|
118 |
+
Origin: str
|
119 |
+
Designation: str
|
120 |
+
Keywords: str
|
121 |
+
Name: str
|
122 |
+
SWIFT_Tag: str
|
123 |
+
Currency: str
|
124 |
+
Entity: str
|
125 |
+
Message: str
|
126 |
+
City: str
|
127 |
+
Country: str
|
128 |
+
State: str
|
129 |
+
Hit_Type: str
|
130 |
+
Record_Matching_String: str
|
131 |
+
WatchList_Match_String: str
|
132 |
+
Payment_Sender_Name: Optional[str] = ""
|
133 |
+
Payment_Reciever_Name: Optional[str] = ""
|
134 |
+
Swift_Message_Type: str
|
135 |
+
Text_Sanction_Data: str
|
136 |
+
Matched_Sanctioned_Entity: str
|
137 |
+
Is_Match: int
|
138 |
+
Red_Flag_Reason: str
|
139 |
+
Risk_Level: str
|
140 |
+
Risk_Score: float
|
141 |
+
Risk_Score_Description: str
|
142 |
+
CDD_Level: str
|
143 |
+
PEP_Status: str
|
144 |
+
Value_Date: str
|
145 |
+
Last_Review_Date: str
|
146 |
+
Next_Review_Date: str
|
147 |
+
Sanction_Description: str
|
148 |
+
Checker_Notes: str
|
149 |
+
Sanction_Context: str
|
150 |
+
Maker_Action: str
|
151 |
+
Customer_ID: int
|
152 |
+
Customer_Type: str
|
153 |
+
Industry: str
|
154 |
+
Transaction_Date_Time: str
|
155 |
+
Transaction_Type: str
|
156 |
+
Transaction_Channel: str
|
157 |
+
Originating_Bank: str
|
158 |
+
Beneficiary_Bank: str
|
159 |
+
Geographic_Origin: str
|
160 |
+
Geographic_Destination: str
|
161 |
+
Match_Score: float
|
162 |
+
Match_Type: str
|
163 |
+
Sanctions_List_Version: str
|
164 |
+
Screening_Date_Time: str
|
165 |
+
Risk_Category: str
|
166 |
+
Risk_Drivers: str
|
167 |
+
Alert_Status: str
|
168 |
+
Investigation_Outcome: str
|
169 |
+
Case_Owner_Analyst: str
|
170 |
+
Escalation_Level: str
|
171 |
+
Escalation_Date: str
|
172 |
+
Regulatory_Reporting_Flags: bool
|
173 |
+
Audit_Trail_Timestamp: str
|
174 |
+
Source_Of_Funds: str
|
175 |
+
Purpose_Of_Transaction: str
|
176 |
+
Beneficial_Owner: str
|
177 |
+
Sanctions_Exposure_History: bool
|
178 |
+
|
179 |
+
class PredictionRequest(BaseModel):
|
180 |
+
transaction_data: TransactionData
|
181 |
+
model_name: str = "ROBERTA_model" # Default to RoBERTa_model if not specified
|
182 |
+
|
183 |
+
class BatchPredictionResponse(BaseModel):
|
184 |
+
message: str
|
185 |
+
predictions: List[Dict[str, Any]]
|
186 |
+
metrics: Optional[Dict[str, Any]] = None
|
187 |
+
|
188 |
+
@app.get("/")
|
189 |
+
async def root():
|
190 |
+
return {"message": "RoBERTa Compliance Predictor API"}
|
191 |
+
|
192 |
+
@app.get("/v1/roberta/health")
|
193 |
+
async def health_check():
|
194 |
+
return {"status": "healthy"}
|
195 |
+
|
196 |
+
@app.get("/v1/roberta/training-status")
|
197 |
+
async def get_training_status():
|
198 |
+
return training_status
|
199 |
+
|
200 |
+
@app.post("/v1/roberta/train", response_model=TrainingResponse)
|
201 |
+
async def start_training(
|
202 |
+
config: str = Form(...),
|
203 |
+
background_tasks: BackgroundTasks = None,
|
204 |
+
file: UploadFile = File(...)
|
205 |
+
):
|
206 |
+
if training_status["is_training"]:
|
207 |
+
raise HTTPException(status_code=400, detail="Training is already in progress")
|
208 |
+
|
209 |
+
if not file.filename.endswith('.csv'):
|
210 |
+
raise HTTPException(status_code=400, detail="Only CSV files are allowed")
|
211 |
+
|
212 |
+
try:
|
213 |
+
# Parse the config JSON string into a TrainingConfig object
|
214 |
+
config_dict = json.loads(config)
|
215 |
+
training_config = TrainingConfig(**config_dict)
|
216 |
+
except json.JSONDecodeError:
|
217 |
+
raise HTTPException(status_code=400, detail="Invalid config JSON format")
|
218 |
+
except Exception as e:
|
219 |
+
raise HTTPException(status_code=400, detail=f"Invalid config parameters: {str(e)}")
|
220 |
+
|
221 |
+
file_path = UPLOAD_DIR / file.filename
|
222 |
+
with file_path.open("wb") as buffer:
|
223 |
+
shutil.copyfileobj(file.file, buffer)
|
224 |
+
|
225 |
+
training_id = datetime.now().strftime("%Y%m%d_%H%M%S")
|
226 |
+
|
227 |
+
training_status.update({
|
228 |
+
"is_training": True,
|
229 |
+
"current_epoch": 0,
|
230 |
+
"total_epochs": training_config.num_epochs,
|
231 |
+
"start_time": datetime.now().isoformat(),
|
232 |
+
"status": "starting"
|
233 |
+
})
|
234 |
+
|
235 |
+
background_tasks.add_task(train_model_task, training_config, str(file_path), training_id)
|
236 |
+
|
237 |
+
download_url = f"/v1/roberta/download-model/{training_id}"
|
238 |
+
|
239 |
+
return TrainingResponse(
|
240 |
+
message="Training started successfully",
|
241 |
+
training_id=training_id,
|
242 |
+
status="started",
|
243 |
+
download_url=download_url
|
244 |
+
)
|
245 |
+
|
246 |
+
@app.post("/v1/roberta/validate")
|
247 |
+
async def validate_model(
|
248 |
+
file: UploadFile = File(...),
|
249 |
+
model_name: str = "ROBERTA_model"
|
250 |
+
):
|
251 |
+
"""Validate a RoBERTa model on uploaded data"""
|
252 |
+
if not file.filename.endswith('.csv'):
|
253 |
+
raise HTTPException(status_code=400, detail="Only CSV files are allowed")
|
254 |
+
|
255 |
+
try:
|
256 |
+
file_path = UPLOAD_DIR / file.filename
|
257 |
+
with file_path.open("wb") as buffer:
|
258 |
+
shutil.copyfileobj(file.file, buffer)
|
259 |
+
|
260 |
+
data_df, label_encoders = load_and_preprocess_data(str(file_path))
|
261 |
+
|
262 |
+
model_path = MODEL_SAVE_DIR / f"{model_name}_model.pth"
|
263 |
+
if not model_path.exists():
|
264 |
+
raise HTTPException(status_code=404, detail="RoBERTa model file not found")
|
265 |
+
|
266 |
+
num_labels_list = [len(label_encoders[col].classes_) for col in LABEL_COLUMNS]
|
267 |
+
metadata_df = data_df[METADATA_COLUMNS] if METADATA_COLUMNS and all(col in data_df.columns for col in METADATA_COLUMNS) else None
|
268 |
+
|
269 |
+
if metadata_df is not None:
|
270 |
+
metadata_dim = metadata_df.shape[1]
|
271 |
+
model = RobertaMultiOutputModel(num_labels_list, metadata_dim=metadata_dim).to(DEVICE)
|
272 |
+
else:
|
273 |
+
model = RobertaMultiOutputModel(num_labels_list).to(DEVICE)
|
274 |
+
|
275 |
+
model.load_state_dict(torch.load(model_path, map_location=DEVICE))
|
276 |
+
model.eval()
|
277 |
+
|
278 |
+
texts = data_df[TEXT_COLUMN]
|
279 |
+
labels_array = data_df[LABEL_COLUMNS].values
|
280 |
+
tokenizer = get_tokenizer("roberta-base")
|
281 |
+
|
282 |
+
if metadata_df is not None:
|
283 |
+
dataset = ComplianceDatasetWithMetadata(
|
284 |
+
texts.tolist(),
|
285 |
+
metadata_df.values,
|
286 |
+
labels_array,
|
287 |
+
tokenizer,
|
288 |
+
MAX_LEN
|
289 |
+
)
|
290 |
+
else:
|
291 |
+
dataset = ComplianceDataset(
|
292 |
+
texts.tolist(),
|
293 |
+
labels_array,
|
294 |
+
tokenizer,
|
295 |
+
MAX_LEN
|
296 |
+
)
|
297 |
+
|
298 |
+
dataloader = DataLoader(dataset, batch_size=BATCH_SIZE)
|
299 |
+
metrics, y_true_list, y_pred_list = evaluate_model(model, dataloader)
|
300 |
+
summary_metrics = summarize_metrics(metrics).to_dict()
|
301 |
+
|
302 |
+
all_probs = predict_probabilities(model, dataloader)
|
303 |
+
|
304 |
+
predictions = []
|
305 |
+
for i, (true_labels, pred_labels) in enumerate(zip(y_true_list, y_pred_list)):
|
306 |
+
field = LABEL_COLUMNS[i]
|
307 |
+
label_encoder = label_encoders[field]
|
308 |
+
true_labels_orig = label_encoder.inverse_transform(true_labels)
|
309 |
+
pred_labels_orig = label_encoder.inverse_transform(pred_labels)
|
310 |
+
|
311 |
+
for true, pred, probs in zip(true_labels_orig, pred_labels_orig, all_probs[i]):
|
312 |
+
predictions.append({
|
313 |
+
"field": field,
|
314 |
+
"true_label": true,
|
315 |
+
"predicted_label": pred,
|
316 |
+
"probabilities": probs.tolist()
|
317 |
+
})
|
318 |
+
|
319 |
+
return ValidationResponse(
|
320 |
+
message="Validation completed successfully",
|
321 |
+
metrics=summary_metrics,
|
322 |
+
predictions=predictions
|
323 |
+
)
|
324 |
+
|
325 |
+
except Exception as e:
|
326 |
+
logger.error(f"Validation failed: {str(e)}")
|
327 |
+
raise HTTPException(status_code=500, detail=f"Validation failed: {str(e)}")
|
328 |
+
finally:
|
329 |
+
if os.path.exists(file_path):
|
330 |
+
os.remove(file_path)
|
331 |
+
|
332 |
+
@app.post("/v1/roberta/predict")
|
333 |
+
async def predict(
|
334 |
+
request: Optional[PredictionRequest] = None,
|
335 |
+
file: UploadFile = File(None),
|
336 |
+
model_name: str = "ROBERTA_model"
|
337 |
+
):
|
338 |
+
"""
|
339 |
+
Make predictions on either a single transaction or a batch of transactions from a CSV file.
|
340 |
+
|
341 |
+
You can either:
|
342 |
+
1. Send a single transaction in the request body
|
343 |
+
2. Upload a CSV file with multiple transactions
|
344 |
+
|
345 |
+
Parameters:
|
346 |
+
- file: CSV file containing transactions for batch prediction
|
347 |
+
- model_name: Name of the model to use for prediction (default: "ROBERTA_model")
|
348 |
+
"""
|
349 |
+
try:
|
350 |
+
# Load the model
|
351 |
+
model_path = MODEL_SAVE_DIR / f"{model_name}_model.pth"
|
352 |
+
if not model_path.exists():
|
353 |
+
raise HTTPException(status_code=404, detail=f"Model {model_name} not found")
|
354 |
+
|
355 |
+
# Load label encoders
|
356 |
+
try:
|
357 |
+
label_encoders = load_label_encoders()
|
358 |
+
num_labels_list = [len(label_encoders[col].classes_) for col in LABEL_COLUMNS]
|
359 |
+
except Exception as e:
|
360 |
+
raise HTTPException(status_code=500, detail=f"Could not load label encoders: {str(e)}")
|
361 |
+
|
362 |
+
model = RobertaMultiOutputModel(num_labels_list).to(DEVICE)
|
363 |
+
model.load_state_dict(torch.load(model_path, map_location=DEVICE))
|
364 |
+
model.eval()
|
365 |
+
|
366 |
+
# Handle batch prediction from CSV
|
367 |
+
if file and file.filename:
|
368 |
+
if not file.filename.endswith('.csv'):
|
369 |
+
raise HTTPException(status_code=400, detail="Only CSV files are allowed")
|
370 |
+
|
371 |
+
file_path = UPLOAD_DIR / file.filename
|
372 |
+
with file_path.open("wb") as buffer:
|
373 |
+
shutil.copyfileobj(file.file, buffer)
|
374 |
+
|
375 |
+
try:
|
376 |
+
# Load and preprocess the CSV data
|
377 |
+
data_df, _ = load_and_preprocess_data(str(file_path))
|
378 |
+
texts = data_df[TEXT_COLUMN]
|
379 |
+
|
380 |
+
# Create dataset and dataloader
|
381 |
+
dataset = ComplianceDataset(
|
382 |
+
texts.tolist(),
|
383 |
+
[[0] * len(LABEL_COLUMNS)] * len(texts), # Dummy labels for prediction
|
384 |
+
tokenizer,
|
385 |
+
MAX_LEN
|
386 |
+
)
|
387 |
+
loader = DataLoader(dataset, batch_size=BATCH_SIZE)
|
388 |
+
|
389 |
+
# Get predictions
|
390 |
+
all_probabilities = predict_probabilities(model, loader)
|
391 |
+
|
392 |
+
# Process predictions
|
393 |
+
predictions = []
|
394 |
+
for i, row in data_df.iterrows():
|
395 |
+
transaction_pred = {}
|
396 |
+
for j, (col, probs) in enumerate(zip(LABEL_COLUMNS, all_probabilities)):
|
397 |
+
pred = np.argmax(probs[i])
|
398 |
+
decoded_pred = label_encoders[col].inverse_transform([pred])[0]
|
399 |
+
|
400 |
+
class_probs = {
|
401 |
+
label: float(probs[i][j])
|
402 |
+
for j, label in enumerate(label_encoders[col].classes_)
|
403 |
+
}
|
404 |
+
|
405 |
+
transaction_pred[col] = {
|
406 |
+
"prediction": decoded_pred,
|
407 |
+
"probabilities": class_probs
|
408 |
+
}
|
409 |
+
|
410 |
+
predictions.append({
|
411 |
+
"transaction_id": row.get('Transaction_Id', f"transaction_{i}"),
|
412 |
+
"predictions": transaction_pred
|
413 |
+
})
|
414 |
+
|
415 |
+
return BatchPredictionResponse(
|
416 |
+
message="Batch prediction completed successfully",
|
417 |
+
predictions=predictions
|
418 |
+
)
|
419 |
+
|
420 |
+
finally:
|
421 |
+
if os.path.exists(file_path):
|
422 |
+
os.remove(file_path)
|
423 |
+
|
424 |
+
# Handle single prediction
|
425 |
+
elif request and request.transaction_data:
|
426 |
+
input_data = pd.DataFrame([request.transaction_data.dict()])
|
427 |
+
|
428 |
+
text_input = f"<s>Transaction ID: {input_data['Transaction_Id'].iloc[0]} Origin: {input_data['Origin'].iloc[0]} Designation: {input_data['Designation'].iloc[0]} Keywords: {input_data['Keywords'].iloc[0]} Name: {input_data['Name'].iloc[0]} SWIFT Tag: {input_data['SWIFT_Tag'].iloc[0]} Currency: {input_data['Currency'].iloc[0]} Entity: {input_data['Entity'].iloc[0]} Message: {input_data['Message'].iloc[0]} City: {input_data['City'].iloc[0]} Country: {input_data['Country'].iloc[0]} State: {input_data['State'].iloc[0]} Hit Type: {input_data['Hit_Type'].iloc[0]} Record Matching String: {input_data['Record_Matching_String'].iloc[0]} WatchList Match String: {input_data['WatchList_Match_String'].iloc[0]} Payment Sender: {input_data['Payment_Sender_Name'].iloc[0]} Payment Receiver: {input_data['Payment_Reciever_Name'].iloc[0]} Swift Message Type: {input_data['Swift_Message_Type'].iloc[0]} Text Sanction Data: {input_data['Text_Sanction_Data'].iloc[0]} Matched Sanctioned Entity: {input_data['Matched_Sanctioned_Entity'].iloc[0]} Red Flag Reason: {input_data['Red_Flag_Reason'].iloc[0]} Risk Level: {input_data['Risk_Level'].iloc[0]} Risk Score: {input_data['Risk_Score'].iloc[0]} CDD Level: {input_data['CDD_Level'].iloc[0]} PEP Status: {input_data['PEP_Status'].iloc[0]} Sanction Description: {input_data['Sanction_Description'].iloc[0]} Checker Notes: {input_data['Checker_Notes'].iloc[0]} Sanction Context: {input_data['Sanction_Context'].iloc[0]}</s>"
|
429 |
+
|
430 |
+
dataset = ComplianceDataset(
|
431 |
+
texts=[text_input],
|
432 |
+
labels=[[0] * len(LABEL_COLUMNS)],
|
433 |
+
tokenizer=tokenizer,
|
434 |
+
max_len=MAX_LEN
|
435 |
+
)
|
436 |
+
|
437 |
+
loader = DataLoader(dataset, batch_size=1, shuffle=False)
|
438 |
+
all_probabilities = predict_probabilities(model, loader)
|
439 |
+
|
440 |
+
response = {}
|
441 |
+
for i, (col, probs) in enumerate(zip(LABEL_COLUMNS, all_probabilities)):
|
442 |
+
pred = np.argmax(probs[0])
|
443 |
+
decoded_pred = label_encoders[col].inverse_transform([pred])[0]
|
444 |
+
|
445 |
+
class_probs = {
|
446 |
+
label: float(probs[0][j])
|
447 |
+
for j, label in enumerate(label_encoders[col].classes_)
|
448 |
+
}
|
449 |
+
|
450 |
+
response[col] = {
|
451 |
+
"prediction": decoded_pred,
|
452 |
+
"probabilities": class_probs
|
453 |
+
}
|
454 |
+
|
455 |
+
return response
|
456 |
+
|
457 |
+
else:
|
458 |
+
raise HTTPException(
|
459 |
+
status_code=400,
|
460 |
+
detail="Either provide a transaction in the request body or upload a CSV file"
|
461 |
+
)
|
462 |
+
|
463 |
+
except Exception as e:
|
464 |
+
raise HTTPException(status_code=500, detail=str(e))
|
465 |
+
|
466 |
+
@app.get("/v1/roberta/download-model/{model_id}")
|
467 |
+
async def download_model(model_id: str):
|
468 |
+
"""Download a trained model"""
|
469 |
+
model_path = MODEL_SAVE_DIR / f"{model_id}_model.pth"
|
470 |
+
if not model_path.exists():
|
471 |
+
raise HTTPException(status_code=404, detail="Model not found")
|
472 |
+
|
473 |
+
return FileResponse(
|
474 |
+
path=model_path,
|
475 |
+
filename=f"roberta_model_{model_id}.pth",
|
476 |
+
media_type="application/octet-stream"
|
477 |
+
)
|
478 |
+
|
479 |
+
async def train_model_task(config: TrainingConfig, file_path: str, training_id: str):
|
480 |
+
try:
|
481 |
+
data_df_original, label_encoders = load_and_preprocess_data(file_path)
|
482 |
+
save_label_encoders(label_encoders)
|
483 |
+
|
484 |
+
texts = data_df_original[TEXT_COLUMN]
|
485 |
+
labels_array = data_df_original[LABEL_COLUMNS].values
|
486 |
+
|
487 |
+
metadata_df = data_df_original[METADATA_COLUMNS] if METADATA_COLUMNS and all(col in data_df_original.columns for col in METADATA_COLUMNS) else None
|
488 |
+
|
489 |
+
num_labels_list = get_num_labels(label_encoders)
|
490 |
+
tokenizer = get_tokenizer(config.model_name)
|
491 |
+
|
492 |
+
if metadata_df is not None:
|
493 |
+
metadata_dim = metadata_df.shape[1]
|
494 |
+
dataset = ComplianceDatasetWithMetadata(
|
495 |
+
texts.tolist(),
|
496 |
+
metadata_df.values,
|
497 |
+
labels_array,
|
498 |
+
tokenizer,
|
499 |
+
config.max_length
|
500 |
+
)
|
501 |
+
model = RobertaMultiOutputModel(num_labels_list, metadata_dim=metadata_dim).to(DEVICE)
|
502 |
+
else:
|
503 |
+
dataset = ComplianceDataset(
|
504 |
+
texts.tolist(),
|
505 |
+
labels_array,
|
506 |
+
tokenizer,
|
507 |
+
config.max_length
|
508 |
+
)
|
509 |
+
model = RobertaMultiOutputModel(num_labels_list).to(DEVICE)
|
510 |
+
|
511 |
+
train_loader = DataLoader(dataset, batch_size=config.batch_size, shuffle=True)
|
512 |
+
|
513 |
+
criterions = initialize_criterions(num_labels_list)
|
514 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=config.learning_rate)
|
515 |
+
|
516 |
+
for epoch in range(config.num_epochs):
|
517 |
+
training_status["current_epoch"] = epoch + 1
|
518 |
+
|
519 |
+
train_loss = train_model(model, train_loader, criterions, optimizer)
|
520 |
+
training_status["current_loss"] = train_loss
|
521 |
+
|
522 |
+
# Save model after each epoch
|
523 |
+
save_model(model, training_id, 'pth')
|
524 |
+
|
525 |
+
training_status.update({
|
526 |
+
"is_training": False,
|
527 |
+
"end_time": datetime.now().isoformat(),
|
528 |
+
"status": "completed"
|
529 |
+
})
|
530 |
+
|
531 |
+
except Exception as e:
|
532 |
+
logger.error(f"Training failed: {str(e)}")
|
533 |
+
training_status.update({
|
534 |
+
"is_training": False,
|
535 |
+
"end_time": datetime.now().isoformat(),
|
536 |
+
"status": "failed",
|
537 |
+
"error": str(e)
|
538 |
+
})
|
539 |
+
|
540 |
+
if __name__ == "__main__":
|
541 |
+
port = int(os.environ.get("PORT", 7860))
|
542 |
+
uvicorn.run(app, host="0.0.0.0", port=port)
|