Download module_toxicdetection/src/predict.py from orcheflow/flow-moderation: direct link, hf CLI and curl.
- Browser
- Download file 1.9 kB
-
https://huggingface.co/orcheflow/flow-moderation/resolve/main/module_toxicdetection/src/predict.py
- Command line
-
hf download hf://orcheflow/flow-moderation/module_toxicdetection/src/predict.py
-
curl -L -o predict.py https://huggingface.co/orcheflow/flow-moderation/resolve/main/module_toxicdetection/src/predict.py
1.9 kB
| import torch | |
| from transformers import AutoTokenizer, AutoModelForSequenceClassification | |
| import sys | |
| class ToxicDetector: | |
| def __init__(self, model_path): | |
| self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| print(f"Loading Toxic Detector from {model_path}...") | |
| self.tokenizer = AutoTokenizer.from_pretrained(model_path) | |
| self.model = AutoModelForSequenceClassification.from_pretrained(model_path).to(self.device) | |
| self.model.eval() | |
| def predict(self, text): | |
| inputs = self.tokenizer( | |
| text, | |
| return_tensors="pt", | |
| truncation=True, | |
| padding=True, | |
| max_length=128 | |
| ).to(self.device) | |
| with torch.no_grad(): | |
| outputs = self.model(**inputs) | |
| probs = torch.nn.functional.softmax(outputs.logits, dim=-1) | |
| toxic_score = probs[0][1].item() | |
| return toxic_score | |
| def main(): | |
| model_path = "toxic_detection_model/models/final_model" | |
| try: | |
| detector = ToxicDetector(model_path) | |
| except Exception as e: | |
| import os | |
| base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| model_path = os.path.join(base_path, "models", "final_model") | |
| print(f"Retry loading from: {model_path}") | |
| detector = ToxicDetector(model_path) | |
| print("\n--- Toxic Detector (Profanity-Free Toxicity) ---") | |
| print("Type 'q' or 'exit' to quit.\n") | |
| while True: | |
| try: | |
| user_input = input("Input text: ") | |
| if user_input.lower() in ['q', 'exit']: | |
| break | |
| score = detector.predict(user_input) | |
| print(f"Toxic Score: {score:.4f} ({'Toxic/Negative' if score > 0.5 else 'Clean/Positive'})") | |
| except KeyboardInterrupt: | |
| break | |
| if __name__ == "__main__": | |
| main() |