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()