Download module_profanity/train.py from orcheflow/flow-moderation: direct link, hf CLI and curl.
- Browser
- Download file 8.42 kB
-
https://huggingface.co/orcheflow/flow-moderation/resolve/main/module_profanity/train.py
- Command line
-
hf download hf://orcheflow/flow-moderation/module_profanity/train.py
-
curl -L -o train.py https://huggingface.co/orcheflow/flow-moderation/resolve/main/module_profanity/train.py
8.42 kB
| 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() |