Update api.py
Browse files
api.py
CHANGED
|
@@ -1,54 +1,57 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
from
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
model.
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
"
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
os.environ["HF_HOME"] = "/tmp/huggingface"
|
| 3 |
+
|
| 4 |
+
from flask import Blueprint, request, jsonify
|
| 5 |
+
from transformers import DebertaV2Tokenizer, DebertaV2ForSequenceClassification
|
| 6 |
+
import torch
|
| 7 |
+
from utils import mask_pii
|
| 8 |
+
|
| 9 |
+
api_bp = Blueprint("api", __name__)
|
| 10 |
+
|
| 11 |
+
# Repo of Hugging Face Model Hub where Model is Pushed
|
| 12 |
+
REPO_ID = "Nikpatil/Email_classifier"
|
| 13 |
+
MAX_LENGTH = 256
|
| 14 |
+
|
| 15 |
+
tokenizer = DebertaV2Tokenizer.from_pretrained(REPO_ID)
|
| 16 |
+
model = DebertaV2ForSequenceClassification.from_pretrained(REPO_ID)
|
| 17 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 18 |
+
model.to(device)
|
| 19 |
+
model.eval()
|
| 20 |
+
|
| 21 |
+
id2label = {0: "Incident", 1: "Request", 2: "Problem", 3: "Change"}
|
| 22 |
+
|
| 23 |
+
@api_bp.route("/classify", methods=["POST"])
|
| 24 |
+
def classify_email():
|
| 25 |
+
data = request.get_json()
|
| 26 |
+
email_body = data.get("email_body", "")
|
| 27 |
+
|
| 28 |
+
if not email_body:
|
| 29 |
+
return jsonify({"Error": "Email body field is required"}), 400
|
| 30 |
+
|
| 31 |
+
masked_email, entities = mask_pii(email_body)
|
| 32 |
+
|
| 33 |
+
inputs = tokenizer(
|
| 34 |
+
masked_email,
|
| 35 |
+
add_special_tokens=True,
|
| 36 |
+
max_length=MAX_LENGTH,
|
| 37 |
+
padding='max_length',
|
| 38 |
+
truncation=True,
|
| 39 |
+
return_tensors='pt'
|
| 40 |
+
)
|
| 41 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
| 42 |
+
|
| 43 |
+
with torch.no_grad():
|
| 44 |
+
outputs = model(**inputs)
|
| 45 |
+
|
| 46 |
+
probs = torch.nn.functional.softmax(outputs.logits, dim=1)[0]
|
| 47 |
+
predicted_class_id = torch.argmax(probs).item()
|
| 48 |
+
predicted_class = id2label[predicted_class_id]
|
| 49 |
+
|
| 50 |
+
return jsonify({
|
| 51 |
+
"input_email_body": email_body,
|
| 52 |
+
"list_of_masked_entities": entities,
|
| 53 |
+
"masked_email": masked_email,
|
| 54 |
+
"category_of_the_email": predicted_class
|
| 55 |
+
}), 200
|
| 56 |
+
|
| 57 |
+
|