Spaces:
Build error
Build error
Upload 5 files
Browse files- Dockerfile +14 -0
- bert_model (1) (1).pkl +3 -0
- main.py +33 -0
- model_utils.py +94 -0
- requirements.txt +8 -0
Dockerfile
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
FROM python:3.9-slim
|
| 3 |
+
|
| 4 |
+
WORKDIR /app
|
| 5 |
+
|
| 6 |
+
COPY ./app ./app
|
| 7 |
+
COPY requirements.txt .
|
| 8 |
+
|
| 9 |
+
RUN pip install --upgrade pip
|
| 10 |
+
RUN pip install -r requirements.txt
|
| 11 |
+
|
| 12 |
+
EXPOSE 7860
|
| 13 |
+
|
| 14 |
+
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
|
bert_model (1) (1).pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:59f5c013010fa19f1d2a3c62557c0c619098f9482ea6ef8b521ad2efd853dc07
|
| 3 |
+
size 438871819
|
main.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from fastapi import FastAPI
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
import torch
|
| 5 |
+
from app.model_utils import train_and_save_model, load_model, LABEL_COLUMNS
|
| 6 |
+
|
| 7 |
+
app = FastAPI()
|
| 8 |
+
model, tokenizer, label_encoders = load_model()
|
| 9 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 10 |
+
MAX_LEN = 128
|
| 11 |
+
|
| 12 |
+
class PredictRequest(BaseModel):
|
| 13 |
+
text: str
|
| 14 |
+
|
| 15 |
+
class TrainRequest(BaseModel):
|
| 16 |
+
csv_path: str
|
| 17 |
+
|
| 18 |
+
@app.post("/predict")
|
| 19 |
+
def predict(req: PredictRequest):
|
| 20 |
+
inputs = tokenizer(req.text, return_tensors="pt", truncation=True, padding=True, max_length=MAX_LEN).to(DEVICE)
|
| 21 |
+
with torch.no_grad():
|
| 22 |
+
outputs = model(inputs['input_ids'], inputs['attention_mask'])
|
| 23 |
+
predictions = {}
|
| 24 |
+
for i, output in enumerate(outputs):
|
| 25 |
+
pred = torch.argmax(output, dim=1).item()
|
| 26 |
+
decoded = label_encoders[LABEL_COLUMNS[i]].inverse_transform([pred])[0]
|
| 27 |
+
predictions[LABEL_COLUMNS[i]] = decoded
|
| 28 |
+
return {"text": req.text, "predictions": predictions}
|
| 29 |
+
|
| 30 |
+
@app.post("/train")
|
| 31 |
+
def train_model(req: TrainRequest):
|
| 32 |
+
train_and_save_model(req.csv_path)
|
| 33 |
+
return {"message": "Model trained and saved successfully"}
|
model_utils.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import torch
|
| 4 |
+
import pickle
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
from sklearn.preprocessing import LabelEncoder
|
| 7 |
+
from sklearn.model_selection import train_test_split
|
| 8 |
+
from transformers import BertTokenizer, BertModel
|
| 9 |
+
from torch.optim import AdamW
|
| 10 |
+
from tqdm import tqdm
|
| 11 |
+
|
| 12 |
+
TEXT_COLUMN = 'Sanction_Context'
|
| 13 |
+
LABEL_COLUMNS = [
|
| 14 |
+
'Red_Flag_Reason', 'Maker_Action', 'Escalation_Level',
|
| 15 |
+
'Risk_Category', 'Risk_Drivers', 'Investigation_Outcome'
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
PRETRAINED_MODEL_NAME = 'bert-base-uncased'
|
| 19 |
+
MAX_LEN = 128
|
| 20 |
+
BATCH_SIZE = 16
|
| 21 |
+
EPOCHS = 1
|
| 22 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 23 |
+
|
| 24 |
+
class BertMultiOutput(nn.Module):
|
| 25 |
+
def __init__(self, num_labels_per_output):
|
| 26 |
+
super().__init__()
|
| 27 |
+
self.bert = BertModel.from_pretrained(PRETRAINED_MODEL_NAME)
|
| 28 |
+
self.dropout = nn.Dropout(0.3)
|
| 29 |
+
self.classifiers = nn.ModuleList([
|
| 30 |
+
nn.Linear(self.bert.config.hidden_size, n_labels)
|
| 31 |
+
for n_labels in num_labels_per_output
|
| 32 |
+
])
|
| 33 |
+
def forward(self, input_ids, attention_mask):
|
| 34 |
+
outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask)
|
| 35 |
+
pooled_output = self.dropout(outputs.pooler_output)
|
| 36 |
+
return [classifier(pooled_output) for classifier in self.classifiers]
|
| 37 |
+
|
| 38 |
+
def train_and_save_model(csv_path, output_path='app/bert_model.pkl'):
|
| 39 |
+
df = pd.read_csv(csv_path)
|
| 40 |
+
X = df[TEXT_COLUMN].tolist()
|
| 41 |
+
y = df[LABEL_COLUMNS]
|
| 42 |
+
|
| 43 |
+
label_encoders = {}
|
| 44 |
+
y_encoded = pd.DataFrame()
|
| 45 |
+
for col in LABEL_COLUMNS:
|
| 46 |
+
le = LabelEncoder()
|
| 47 |
+
y_encoded[col] = le.fit_transform(y[col])
|
| 48 |
+
label_encoders[col] = le
|
| 49 |
+
|
| 50 |
+
X_train, _, y_train, _ = train_test_split(X, y_encoded, test_size=0.2, random_state=42)
|
| 51 |
+
tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)
|
| 52 |
+
|
| 53 |
+
def tokenize_texts(texts):
|
| 54 |
+
return tokenizer(texts, padding=True, truncation=True, max_length=MAX_LEN, return_tensors="pt")
|
| 55 |
+
|
| 56 |
+
train_encodings = tokenize_texts(X_train)
|
| 57 |
+
labels = [torch.tensor(y_train[col].values) for col in LABEL_COLUMNS]
|
| 58 |
+
|
| 59 |
+
num_labels_list = [len(le.classes_) for le in label_encoders.values()]
|
| 60 |
+
model = BertMultiOutput(num_labels_list).to(DEVICE)
|
| 61 |
+
optimizer = AdamW(model.parameters(), lr=2e-5)
|
| 62 |
+
loss_fn = nn.CrossEntropyLoss()
|
| 63 |
+
|
| 64 |
+
model.train()
|
| 65 |
+
for epoch in range(EPOCHS):
|
| 66 |
+
for i in tqdm(range(0, len(X_train), BATCH_SIZE)):
|
| 67 |
+
input_ids = train_encodings['input_ids'][i:i+BATCH_SIZE].to(DEVICE)
|
| 68 |
+
attention_mask = train_encodings['attention_mask'][i:i+BATCH_SIZE].to(DEVICE)
|
| 69 |
+
batch_labels = [label[i:i+BATCH_SIZE].to(DEVICE) for label in labels]
|
| 70 |
+
|
| 71 |
+
optimizer.zero_grad()
|
| 72 |
+
outputs = model(input_ids, attention_mask)
|
| 73 |
+
loss = sum([loss_fn(o, l) for o, l in zip(outputs, batch_labels)])
|
| 74 |
+
loss.backward()
|
| 75 |
+
optimizer.step()
|
| 76 |
+
|
| 77 |
+
model_bundle = {
|
| 78 |
+
'model_state_dict': model.state_dict(),
|
| 79 |
+
'tokenizer': tokenizer,
|
| 80 |
+
'label_encoders': label_encoders
|
| 81 |
+
}
|
| 82 |
+
with open(output_path, 'wb') as f:
|
| 83 |
+
pickle.dump(model_bundle, f)
|
| 84 |
+
|
| 85 |
+
def load_model(path='app/bert_model.pkl'):
|
| 86 |
+
with open(path, 'rb') as f:
|
| 87 |
+
bundle = pickle.load(f)
|
| 88 |
+
tokenizer = bundle['tokenizer']
|
| 89 |
+
label_encoders = bundle['label_encoders']
|
| 90 |
+
num_labels_list = [len(le.classes_) for le in label_encoders.values()]
|
| 91 |
+
model = BertMultiOutput(num_labels_list).to(DEVICE)
|
| 92 |
+
model.load_state_dict(bundle['model_state_dict'])
|
| 93 |
+
model.eval()
|
| 94 |
+
return model, tokenizer, label_encoders
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
fastapi
|
| 3 |
+
uvicorn
|
| 4 |
+
torch
|
| 5 |
+
transformers
|
| 6 |
+
scikit-learn
|
| 7 |
+
pandas
|
| 8 |
+
tqdm
|