import sys import os import torch import pandas as pd from tqdm import tqdm sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../flow_moderation_model'))) from src.model import CharCNN from src.tokenizer import CharTokenizer BATCH_SIZE = 128 DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") SRC_DATA_PATH = "trainset/clean_ko_nsmc.txt" OUTPUT_DATA_PATH = "toxic_detection_model/data/train_toxic.txt" MODEL_PATH = "flow_moderation_model/models/char_cnn_model.pth" TOKENIZER_PATH = "flow_moderation_model/models/tokenizer.json" def load_profanity_model(): print(f"Loading Profanity Model from {MODEL_PATH}...") tokenizer = CharTokenizer.load(TOKENIZER_PATH) model = CharCNN( vocab_size=len(tokenizer), num_classes=2, embedding_dim=300, n_filters=384, max_len=150 ).to(DEVICE) model.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE)) model.eval() return model, tokenizer def predict_batch(model, tokenizer, texts): encoded_batch = [tokenizer.encode(text) for text in texts] input_tensor = torch.tensor(encoded_batch, dtype=torch.long).to(DEVICE) with torch.no_grad(): outputs = model(input_tensor) probs = torch.nn.functional.softmax(outputs, dim=1) scores = probs[:, 1].cpu().numpy() return scores def main(): print(f"Device: {DEVICE}") print("Loading raw data...") df = pd.read_csv(SRC_DATA_PATH, sep='\t') df = df.dropna(subset=['document']) print(f"Total samples: {len(df)}") model, tokenizer = load_profanity_model() new_data = [] negative_df = df[df['label'] == 0] positive_df = df[df['label'] == 1] print(f"Processing {len(negative_df)} negative samples for profanity filtering...") documents = negative_df['document'].tolist() filtered_negative = [] for i in tqdm(range(0, len(documents), BATCH_SIZE)): batch_docs = documents[i : i + BATCH_SIZE] scores = predict_batch(model, tokenizer, batch_docs) for doc, score in zip(batch_docs, scores): if score < 0.2: filtered_negative.append({'document': doc, 'label': 1}) print(f"Filtered Negative (Toxic Candidates): {len(filtered_negative)} / {len(negative_df)}") print(f"Processing {len(positive_df)} positive samples...") clean_data = [{'document': doc, 'label': 0} for doc in positive_df['document']] final_df = pd.DataFrame(filtered_negative + clean_data) final_df = final_df.sample(frac=1, random_state=42).reset_index(drop=True) print(f"Saving {len(final_df)} samples to {OUTPUT_DATA_PATH}...") final_df.to_csv(OUTPUT_DATA_PATH, sep='\t', index=False) print("Done.") if __name__ == "__main__": main()