File size: 2,534 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
import torch
from src.tokenizer import CharTokenizer
from src.model import CharCNN
import os

MAX_LEN = 150 
EMBEDDING_DIM = 300
N_FILTERS = 384
MODEL_PATH = "models/flow_moderation_oss.pth"
TOKENIZER_PATH = "models/tokenizer.json"

THRESHOLD = 0.90

CATEGORIES = {
    0: "정상 (Clean)",
    1: "비정상 (Abnormal/Profanity)"
}

def load_artifacts():
    if not os.path.exists(TOKENIZER_PATH):
        raise FileNotFoundError("Tokenizer not found. Run train.py first.")
    tokenizer = CharTokenizer.load(TOKENIZER_PATH)
    
    if not os.path.exists(MODEL_PATH):
        raise FileNotFoundError("Model not found. Run train.py first.")
    
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model = CharCNN(
        vocab_size=len(tokenizer),
        num_classes=2,
        embedding_dim=EMBEDDING_DIM,
        n_filters=N_FILTERS,
        max_len=MAX_LEN
    ).to(device)
    
    model.load_state_dict(torch.load(MODEL_PATH, map_location=device))
    model.eval()
    
    return tokenizer, model, device

def predict(text, tokenizer, model, device):
    encoded = tokenizer.encode(text)
    input_tensor = torch.tensor([encoded], dtype=torch.long).to(device)
    
    with torch.no_grad():
        output = model(input_tensor)
        probs = torch.nn.functional.softmax(output, dim=1)
        
        pred_idx = torch.argmax(probs, dim=1).item()
        confidence = probs[0][pred_idx].item()
        
        original_pred = pred_idx
        
        if pred_idx != 0 and confidence < THRESHOLD:
            pred_idx = 0
            
    return pred_idx, confidence, original_pred

if __name__ == "__main__":
    try:
        tokenizer, model, device = load_artifacts()
        print(f"Model loaded successfully. (Threshold: {THRESHOLD*100}%)")
        print("Enter text to classify (type 'q' to quit):")
        
        while True:
            text = input("> ")
            if text.lower() == 'q':
                break
            
            if not text.strip():
                continue
                
            final_idx, conf, original_idx = predict(text, tokenizer, model, device)
            
            print(f"Final Decision: {CATEGORIES[final_idx]}")
            
            if final_idx != original_idx:
                print(f"  (Filtered: Originally {CATEGORIES[original_idx]} with {conf*100:.2f}%)")
            else:
                print(f"  Confidence: {conf*100:.2f}%")
            print("-" * 20)
            
    except Exception as e:
        print(f"Error: {e}")