File size: 1,904 Bytes
8016893
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
55
56
57
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import sys

class ToxicDetector:
    def __init__(self, model_path):
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        print(f"Loading Toxic Detector from {model_path}...")
        self.tokenizer = AutoTokenizer.from_pretrained(model_path)
        self.model = AutoModelForSequenceClassification.from_pretrained(model_path).to(self.device)
        self.model.eval()

    def predict(self, text):
        inputs = self.tokenizer(
            text, 
            return_tensors="pt", 
            truncation=True, 
            padding=True, 
            max_length=128
        ).to(self.device)

        with torch.no_grad():
            outputs = self.model(**inputs)
            probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
            toxic_score = probs[0][1].item()
            
        return toxic_score

def main():
    model_path = "toxic_detection_model/models/final_model"
    
    try:
        detector = ToxicDetector(model_path)
    except Exception as e:
        import os
        base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        model_path = os.path.join(base_path, "models", "final_model")
        print(f"Retry loading from: {model_path}")
        detector = ToxicDetector(model_path)

    print("\n--- Toxic Detector (Profanity-Free Toxicity) ---")
    print("Type 'q' or 'exit' to quit.\n")

    while True:
        try:
            user_input = input("Input text: ")
            if user_input.lower() in ['q', 'exit']:
                break
            
            score = detector.predict(user_input)
            print(f"Toxic Score: {score:.4f} ({'Toxic/Negative' if score > 0.5 else 'Clean/Positive'})")
            
        except KeyboardInterrupt:
            break

if __name__ == "__main__":
    main()