sathish2352 commited on
Commit
4628d0e
·
verified ·
1 Parent(s): 47b3c18

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +113 -0
app.py CHANGED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from pydantic import BaseModel
3
+ from typing import List, Dict, Any
4
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline, AutoModelForTokenClassification
5
+ import torch
6
+ import re
7
+
8
+ # --- Load your fine-tuned model from Hugging Face Hub ---
9
+ MODEL_REPO = "sathish2352/email-classifier-model"
10
+ PII_MODEL = "Davlan/xlm-roberta-base-ner-hrl"
11
+
12
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO)
13
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL_REPO)
14
+ ner_tokenizer = AutoTokenizer.from_pretrained(PII_MODEL)
15
+ ner_model = AutoModelForTokenClassification.from_pretrained(PII_MODEL)
16
+ ner_pipe = pipeline("token-classification", model=ner_model, tokenizer=ner_tokenizer, aggregation_strategy="simple")
17
+ model.eval()
18
+
19
+ app = FastAPI()
20
+
21
+ class EmailInput(BaseModel):
22
+ input_email_body: str
23
+
24
+ # --- PII Masking Function ---
25
+ import re
26
+ from transformers import pipeline, AutoModelForTokenClassification, AutoTokenizer
27
+ def mask_pii_multilingual(text: str):
28
+
29
+ # Load model only once globally if needed
30
+ model_name = "Davlan/xlm-roberta-base-ner-hrl"
31
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
32
+ model = AutoModelForTokenClassification.from_pretrained(model_name)
33
+ ner_pipe = pipeline("token-classification", model=model, tokenizer=tokenizer, aggregation_strategy="simple")
34
+
35
+ regex_patterns = {
36
+ "email": r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b",
37
+ "phone_number": r"(?:\+?\d{1,3})?[-.\s]?\(?\d{1,4}\)?[-.\s]?\d{2,4}[-.\s]?\d{2,4}[-.\s]?\d{2,4}",
38
+ "dob": r"\b(0?[1-9]|[12][0-9]|3[01])[-/](0?[1-9]|1[012])[-/](19[5-9]\d|20[0-3]\d)\b",
39
+ "aadhar_num": r"\b\d{4}[\s-]?\d{4}[\s-]?\d{4}\b",
40
+ "credit_debit_no": r"\b(?:\d{4}[\s-]?){3}\d{4}\b",
41
+ "cvv_no": r"\b\d{3,4}\b",
42
+ "expiry_no": r"\b(0[1-9]|1[0-2])[/-]?(?:\d{2}|\d{4})\b"
43
+ }
44
+
45
+ entities = []
46
+ masked_text = text
47
+ offsets = []
48
+
49
+ # Step 1: Apply regex PII masking first
50
+ for entity_type, pattern in regex_patterns.items():
51
+ for match in re.finditer(pattern, text):
52
+ start, end = match.start(), match.end()
53
+ if any(start < e[1] and end > e[0] for e in offsets):
54
+ continue
55
+ token = f"[{entity_type}]"
56
+ entity_val = text[start:end]
57
+ masked_text = masked_text[:start] + token + masked_text[end:]
58
+ offsets.append((start, end))
59
+ entities.append({
60
+ "position": [start, end],
61
+ "classification": entity_type,
62
+ "entity": entity_val
63
+ })
64
+
65
+ # Step 2: Run NER on updated masked_text to avoid overlap
66
+ ner_results = ner_pipe(masked_text)
67
+ for ent in ner_results:
68
+ start, end = ent["start"], ent["end"]
69
+ if ent["entity_group"] != "PER":
70
+ continue
71
+ if any(start < e[1] and end > e[0] for e in offsets):
72
+ continue
73
+ token = "[full_name]"
74
+ entity_val = text[start:end]
75
+ masked_text = masked_text[:start] + token + masked_text[end:]
76
+ entities.append({
77
+ "position": [start, end],
78
+ "classification": "full_name",
79
+ "entity": entity_val
80
+ })
81
+ offsets.append((start, end))
82
+
83
+ # Sort final result
84
+ entities.sort(key=lambda x: x["position"][0])
85
+ return masked_text, entities
86
+
87
+
88
+ # --- API Endpoint ---
89
+ @app.post("/classify")
90
+ def classify_email(input: EmailInput):
91
+ original_text = input.input_email_body
92
+
93
+ # Step 1: Mask PII
94
+ masked_text, masked_entities = mask_pii_multilingual(original_text)
95
+
96
+ # Step 2: Classification
97
+ inputs = tokenizer(masked_text, return_tensors="pt", truncation=True, padding=True)
98
+ with torch.no_grad():
99
+ logits = model(**inputs).logits
100
+ pred = torch.argmax(logits, dim=1).item()
101
+
102
+ label_map = {0: "Incident", 1: "Request", 2: "Change", 3: "Problem"}
103
+
104
+ return {
105
+ "input_email_body": original_text,
106
+ "list_of_masked_entities": masked_entities,
107
+ "masked_email": masked_text,
108
+ "category_of_the_email": label_map[pred]
109
+ }
110
+ if __name__ == "__main__":
111
+ import uvicorn
112
+ uvicorn.run("app:app", host="0.0.0.0", port=7860)
113
+