Download predict.py from Pannuru/Spam-Detection-SLM: direct link, hf CLI and curl.
- Browser
- Download file 1.27 kB
-
https://huggingface.co/Pannuru/Spam-Detection-SLM/resolve/main/predict.py
- Command line
-
hf download hf://Pannuru/Spam-Detection-SLM/predict.py
-
curl -L -o predict.py https://huggingface.co/Pannuru/Spam-Detection-SLM/resolve/main/predict.py
1.27 kB
| import torch | |
| import json | |
| from transformers import AutoTokenizer | |
| from modeling_spam import SpamTransformerClassifier | |
| MODEL_PATH = "/content/spam_slm_export" | |
| # Load configuration | |
| with open(f"{MODEL_PATH}/config.json", "r") as f: | |
| config = json.load(f) | |
| # Load tokenizer | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH) | |
| # Load trained classifier | |
| model = SpamTransformerClassifier(config) | |
| checkpoint = torch.load( | |
| f"{MODEL_PATH}/model_weights.pth", | |
| map_location="cpu", | |
| weights_only=True | |
| ) | |
| model.load_state_dict(checkpoint) | |
| model.eval() | |
| def predict_message(message): | |
| inputs = tokenizer( | |
| message, | |
| max_length=128, | |
| padding="max_length", | |
| truncation=True, | |
| return_tensors="pt" | |
| ) | |
| with torch.no_grad(): | |
| outputs = model( | |
| inputs["input_ids"], | |
| inputs["attention_mask"] | |
| ) | |
| probabilities = torch.softmax(outputs, dim=1)[0] | |
| predicted_class = torch.argmax(probabilities).item() | |
| label = config["labels"][str(predicted_class)] | |
| return label, probabilities[predicted_class].item() * 100 | |
| message = input("Enter a message: ") | |
| label, confidence = predict_message(message) | |
| print("\nPrediction:", label) | |
| print("Confidence:", round(confidence, 2), "%") | |