File size: 3,668 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import torch
import sys
import os

sys.path.append(os.getcwd())

from module_profanity.src.model import CharCNN
from module_profanity.src.tokenizer import CharTokenizer
from module_toxicdetection.src.predict import ToxicDetector

class IntegratedModerator:
    def __init__(self):
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        print(f"Initializing Integrated Moderator on {self.device}...")
        
        # 1. Load Profanity Model (CharCNN)
        print("Loading Profanity Model (CharCNN)...")
        self.profanity_tokenizer = CharTokenizer.load("flow_moderation_model/models/tokenizer.json")
        self.profanity_model = CharCNN(
            vocab_size=len(self.profanity_tokenizer),
            num_classes=2,
            embedding_dim=300,
            n_filters=384,
            max_len=150
        ).to(self.device)
        self.profanity_model.load_state_dict(torch.load("flow_moderation_model/models/char_cnn_model.pth", map_location=self.device))
        self.profanity_model.eval()

        # 2. Load Toxic Model (KcELECTRA)
        print("Loading Toxic Model (KcELECTRA)...")
        self.toxic_detector = ToxicDetector("toxic_detection_model/models/final_model")

    def predict_profanity(self, text):
        encoded = self.profanity_tokenizer.encode(text)
        input_tensor = torch.tensor([encoded], dtype=torch.long).to(self.device)
        with torch.no_grad():
            output = self.profanity_model(input_tensor)
            probs = torch.nn.functional.softmax(output, dim=1)
            score = probs[0][1].item()
        return score

    def predict(self, text):
        profanity_score = self.predict_profanity(text)
        
        toxic_score = self.toxic_detector.predict(text)
        
        result = {
            "text": text,
            "profanity_score": profanity_score,
            "toxic_score": toxic_score,
            "final_label": "Clean",
            "reason": "Normal conversation"
        }

        # Thresholds
        PROFANITY_THRESHOLD = 0.5
        TOXIC_THRESHOLD = 0.5

        if profanity_score >= PROFANITY_THRESHOLD:
            result["final_label"] = "PROFANITY"
            result["reason"] = "Explicit bad language detected"
        elif toxic_score >= TOXIC_THRESHOLD:
            result["final_label"] = "TOXIC"
            result["reason"] = "Toxic context or sarcasm detected (without explicit profanity)"
        
        return result

def main():
    print("\n" + "="*50)
    print("      FLOW MODERATION SYSTEM (Integrated)")
    print("      1. Profanity Detection (CharCNN)")
    print("      2. Toxicity/Sarcasm Detection (KcELECTRA)")
    print("="*50 + "\n")

    moderator = IntegratedModerator()

    print("\nSystem Ready. Type 'q' or 'exit' to quit.\n")

    while True:
        try:
            user_input = input("User > ")
            if user_input.strip().lower() in ['q', 'exit']:
                print("Exiting...")
                break
            
            if not user_input.strip():
                continue

            res = moderator.predict(user_input)
            
            print("-" * 40)
            print(f"Input: {res['text']}")
            print(f"Profanity Score : {res['profanity_score']:.4f}")
            print(f"Toxic Score     : {res['toxic_score']:.4f}")
            print(f"Decision        : [{res['final_label']}]")
            print(f"Reason          : {res['reason']}")
            print("-" * 40 + "\n")

        except KeyboardInterrupt:
            print("\nExiting...")
            break
        except Exception as e:
            print(f"Error: {e}")

if __name__ == "__main__":
    main()