from transformers import AutoTokenizer, AutoModelForSequenceClassification import torch # Load the pretrained sentiment model model_name = "distilbert-base-uncased-finetuned-sst-2-english" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSequenceClassification.from_pretrained(model_name) # Function to classify sentiment def analyze_sentiment(text): inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True) outputs = model(**inputs) probs = torch.softmax(outputs.logits, dim=1) prediction = torch.argmax(probs).item() label = "positive" if prediction == 1 else "negative" return label, probs[0][prediction].item() # Try it out! if __name__ == "__main__": print("🧠 Sentiment Analyzer (type 'exit' to quit)\n") while True: sentence = input("Enter a sentence: ").strip() if sentence.lower() in ["exit", "quit"]: print("👋 Goodbye!") break sentiment, confidence = analyze_sentiment(sentence) print(f"🧠 Sentiment: {sentiment.capitalize()} (Confidence: {confidence:.2f})\n")