flow-moderation / flow_moderation_predict.py
othamoth's picture
Upload 30 files
8016893 verified
Raw History Blame Contribute Delete
3.67 kB
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()