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

MAX_LEN = 150 
EMBEDDING_DIM = 300
N_FILTERS = 384
MODEL_PATH = "models/flow_moderation_oss.pth"
TOKENIZER_PATH = "models/tokenizer.json"
INPUT_FILE = "../test.md"
OUTPUT_FILE = "../result.log"

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

def load_artifacts():
    if not os.path.exists(TOKENIZER_PATH):
        print(f"Error: {TOKENIZER_PATH} not found.")
        sys.exit(1)
    tokenizer = CharTokenizer.load(TOKENIZER_PATH)
    
    if not os.path.exists(MODEL_PATH):
        print(f"Error: {MODEL_PATH} not found.")
        sys.exit(1)
    
    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_line(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()
        
    return pred_idx, confidence

def main():
    if not os.path.exists(INPUT_FILE):
        print(f"Error: Input file '{INPUT_FILE}' not found.")
        sys.exit(1)

    print("Loading model...")
    tokenizer, model, device = load_artifacts()
    
    print(f"Processing {INPUT_FILE}...")
    
    with open(INPUT_FILE, 'r', encoding='utf-8') as fin, \
         open(OUTPUT_FILE, 'w', encoding='utf-8') as fout:
        
        lines = fin.readlines()
        total = len(lines)
        
        for i, line in enumerate(lines):
            text = line.strip()
            if not text:
                continue
                
            pred_idx, conf = predict_line(text, tokenizer, model, device)
            if i < 10:
                print(f"DEBUG: Line {i+1} text='{text}' pred_idx={pred_idx}")
            result_str = f"Line {i+1}: [{CATEGORIES[pred_idx]}] (Conf: {conf*100:.2f}%) - {text}\n"
            fout.write(result_str)
            
            if (i+1) % 100 == 0:
                print(f"Processed {i+1}/{total} lines...", end='\r')
                
    print(f"\nDone! Results saved to {OUTPUT_FILE}")

if __name__ == "__main__":
    main()