Spaces:
Sleeping
Sleeping
| # μΆλ‘ | |
| import torch | |
| from transformers import RobertaForSequenceClassification, RobertaTokenizer | |
| # μ μ΄νμ΅μ μ¬μ©ν ν ν¬λμ΄μ μ λͺ¨λΈ λ‘λ & κ°μ€μΉ λ‘λ | |
| class ToxcitiyClassifier: | |
| def __init__(self): | |
| self.tokenizer = RobertaTokenizer.from_pretrained("beomi/KcBERT-v2023") | |
| self.model = RobertaForSequenceClassification.from_pretrained( | |
| "beomi/KcBERT-v2023", num_labels=2 | |
| ) | |
| self.model.load_state_dict( | |
| torch.load( | |
| "./src/ai/pytorchmodel_518λ§μΈλΆλ₯_acc8583.bin", | |
| map_location=torch.device("cpu"), | |
| weights_only=True, | |
| ) | |
| ) | |
| # λͺ¨λΈμ νκ° λͺ¨λλ‘ μ€μ | |
| self.model.eval() | |
| # μ λ ₯ ν μ€νΈ μμ | |
| self.class_labels = ["λ¬Έμ μμ/κ΄λ ¨μμ", "λΆμ μ (518 λ§μΈ κ°λ₯)"] | |
| def infer(self, new_text): | |
| inputs = self.tokenizer(new_text, return_tensors="pt") | |
| # μΆλ‘ μν (CPU μ¬μ©) | |
| with torch.no_grad(): | |
| outputs = self.model(**inputs) | |
| logits = outputs.logits | |
| probs = torch.nn.functional.softmax(logits, dim=-1) | |
| toxic_prob = probs[0][1].item() | |
| non_toxic_prob = probs[0][0].item() | |
| print( | |
| f"{self.class_labels[0]}:{non_toxic_prob*100:.2f}%, {self.class_labels[1]}:{toxic_prob*100:.2f}%" | |
| ) | |
| return toxic_prob | |
| if __name__ == "__main__": | |
| classifier = ToxcitiyClassifier() | |
| result = classifier.infer("5.18 μ νλμ νλμ΄μΌ") | |
| print(result) | |