JanviMl commited on
Commit
bd229ab
·
verified ·
1 Parent(s): 4c95418

Create classifier.py

Browse files
Files changed (1) hide show
  1. classifier.py +27 -0
classifier.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # classifier.py
2
+ import torch
3
+ from model_loader import model, tokenizer
4
+
5
+ def classify_toxic_comment(comment):
6
+ """
7
+ Classify a comment as toxic or non-toxic using the fine-tuned XLM-RoBERTa model.
8
+ Returns the prediction label, confidence, and color for UI display.
9
+ """
10
+ if not comment.strip():
11
+ return "Error: Please enter a comment.", None, None
12
+
13
+ # Tokenize the input comment
14
+ inputs = tokenizer(comment, return_tensors="pt", truncation=True, padding=True, max_length=512)
15
+
16
+ # Run inference
17
+ with torch.no_grad():
18
+ outputs = model(**inputs)
19
+ logits = outputs.logits
20
+
21
+ # Get the predicted class (0 = non-toxic, 1 = toxic)
22
+ predicted_class = torch.argmax(logits, dim=1).item()
23
+ label = "Toxic" if predicted_class == 1 else "Non-Toxic"
24
+ confidence = torch.softmax(logits, dim=1)[0][predicted_class].item()
25
+ label_color = "red" if label == "Toxic" else "green"
26
+
27
+ return f"Prediction: {label}", confidence, label_color