File size: 8,420 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, random_split
from src.tokenizer import CharTokenizer
from src.model import CharCNN
from src.dataset import ProfanityDataset
import os
import glob
import csv
import random
import sys

MAX_LEN = 150 
EMBEDDING_DIM = 300   
N_FILTERS = 384       
BATCH_SIZE = 256      
LR = 0.001
SAVE_DIR = "models"
TRAINSET_DIR = "../trainset"

def load_all_data():
    data_map = {0: [], 1: []} 
    profanity_set = set()

    txt_files = glob.glob(os.path.join(TRAINSET_DIR, "*.txt"))
    for txt_path in txt_files:
        if "clean" in txt_path: continue
        try:
            with open(txt_path, 'r', encoding='utf-8') as f:
                words = [line.strip() for line in f if line.strip()]
                data_map[1].extend(words)
                profanity_set.update(words)
        except:
            with open(txt_path, 'r', encoding='cp949') as f:
                words = [line.strip() for line in f if line.strip()]
                data_map[1].extend(words)
                profanity_set.update(words)

    en_path = os.path.join(TRAINSET_DIR, "en_profanity.csv")
    if os.path.exists(en_path):
        with open(en_path, 'r', encoding='utf-8', errors='ignore') as f:
            reader = csv.DictReader(f)
            for row in reader:
                if row.get('text'):
                    text = row['text'].strip()
                    is_off = (row.get('is_offensive') == '1')
                    if is_off:
                        data_map[1].append(text)
                        profanity_set.add(text)
                    else:
                        pass

    slang_path = os.path.join(TRAINSET_DIR, "slang.csv")
    if os.path.exists(slang_path):
        with open(slang_path, 'r', encoding='utf-8', errors='ignore') as f:
            reader = csv.DictReader(f)
            for row in reader:
                if row.get('slang'): 
                    word = row['slang'].strip()
                    data_map[1].append(word)
                    profanity_set.add(word)

    print(f"Loaded {len(profanity_set)} unique profanity words/sentences for filtering.")

    nsmc_path = os.path.join(TRAINSET_DIR, "clean_ko_nsmc.txt")
    if os.path.exists(nsmc_path):
        print("Loading and filtering NSMC (this might take a moment)...")
        with open(nsmc_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
            count_kept = 0
            count_filtered = 0
            profanity_list = list(profanity_set)
            
            for line in lines[1:]:
                parts = line.split('\t')
                if len(parts) >= 3:
                    text = parts[1].strip()
                    if not text: continue
                    
                    is_clean = True
                    # Heuristic: Check exact words or substrings? 
                    # - Kimjs
                    
                    if "씨발" in text or "개새끼" in text or "병신" in text or "존나" in text:
                        is_clean = False
                    else:
                        # Full check (slower)
                        # We can skip full check if we assume NSMC is mostly clean minus common swears, 
                        # but to be thorough we should check.
                        # However, checking 10k words against 150k sentences is heavy (1.5 billion comparisons).
                        # Let's trust the "Clean" label 0 from NSMC generally, BUT explicitly filter 
                        # known high-frequency profanity found in our profanity list.
                        
                        # Compiling a regex for 10k words is also heavy but faster at inference.
                        # Let's try a subset or just accept the risk of some noise, 
                        # but definitely filter the ones we KNOW are in our profanity set.
                        
                        # Let's only filter if the word from profanity_set is > 1 char to avoid "개", "년" single char false positives
                        # And maybe limit to checking ~1000 most common ones? 
                        # No, let's try the full check. If it's too slow, I'll stop it.
                        # Python `any` is reasonably fast in C.
                        
                        # To avoid O(N*M), let's just check if text contains any word from our 'profanity_set'.
                        # But 'profanity_set' has 10k items.
                        # Let's assume most NSMC 0 labeled items are actually 0, except for obvious ones.
                        # I will simply check for the presence of the keywords collected in data_map[1].
                        
                        # Performance compromise:
                        # Only check words that are length >= 2.
                        # - Kimjs
                        
                        for bad_word in profanity_list:
                            if len(bad_word) >= 2 and bad_word in text:
                                is_clean = False
                                break
                    
                    if is_clean:
                        data_map[0].append(text)
                        count_kept += 1
                    else:
                        count_filtered += 1
                        data_map[1].append(text)

        print(f"NSMC: Kept {count_kept} (Clean), Moved {count_filtered} to Profanity (contained profanity)")

    return data_map

def main():
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    print(f"=== Training with trainset (Device: {device}) ===")
    
    data_map = load_all_data()
    all_texts = []
    all_labels = []
    
    for i in range(2):
        data_map[i] = list(set(data_map[i]))
        print(f"Label {i}: {len(data_map[i])} samples")

    target_count = 40000 
    for lbl in range(2):
        texts = data_map[lbl]
        if not texts: continue
        if len(texts) > target_count:
            sampled = random.sample(texts, target_count)
        else:
            repeats = target_count // len(texts)
            sampled = texts * repeats + texts[:(target_count % len(texts))]
        
        all_texts.extend(sampled)
        all_labels.extend([lbl] * target_count)
            
    print(f"Total balanced dataset: {len(all_texts)}")

    tokenizer = CharTokenizer(max_len=MAX_LEN)
    tokenizer.build_vocab(all_texts)
    if not os.path.exists(SAVE_DIR): os.makedirs(SAVE_DIR)
    tokenizer.save(os.path.join(SAVE_DIR, "tokenizer.json"))

    model = CharCNN(len(tokenizer), 2, EMBEDDING_DIM, N_FILTERS, MAX_LEN).to(device)
    full_dataset = ProfanityDataset(all_texts, all_labels, tokenizer)
    train_size = int(len(full_dataset) * 0.9)
    test_size = len(full_dataset) - train_size
    train_ds, test_ds = random_split(full_dataset, [train_size, test_size])
    
    train_loader = DataLoader(train_ds, batch_size=BATCH_SIZE, shuffle=True)
    test_loader = DataLoader(test_ds, batch_size=BATCH_SIZE)

    criterion = nn.CrossEntropyLoss()
    optimizer = optim.AdamW(model.parameters(), lr=LR)
    scaler = torch.amp.GradScaler('cuda')

    best_acc = 0
    for epoch in range(10):
        model.train()
        for batch in train_loader:
            input_ids = batch['input_ids'].to(device)
            target = batch['label'].to(device)
            optimizer.zero_grad()
            with torch.amp.autocast('cuda'):
                output = model(input_ids)
                loss = criterion(output, target)
            scaler.scale(loss).backward()
            scaler.step(optimizer)
            scaler.update()
            
        model.eval()
        correct, total = 0, 0
        with torch.no_grad():
            for batch in test_loader:
                input_ids = batch['input_ids'].to(device)
                target = batch['label'].to(device)
                output = model(input_ids)
                correct += (output.argmax(1) == target).sum().item()
                total += target.size(0)
        
        acc = 100 * correct / total
        print(f"Epoch {epoch+1} Val Acc: {acc:.2f}%")
        if acc > best_acc:
            best_acc = acc
            torch.save(model.state_dict(), os.path.join(SAVE_DIR, "flow_moderation_oss.pth"))
            
    print(f"Finished. Best Val Acc: {best_acc:.2f}%")

if __name__ == '__main__':
    main()