#!/usr/bin/env python3
"""
A simple Python script to classify text using a pre-trained Transformer model from Hugging Face.
This uses the `transformers` library's pipeline for sentiment analysis (binary classification: POSITIVE/NEGATIVE).
Requirements:
- Install with: pip install transformers torch
Usage:
- Interactive mode: python classify_text.py
- Single text: python classify_text.py "Your text here"
- Custom model: python classify_text.py "Your text here" --model "cardiffnlp/twitter-roberta-base-sentiment-latest"
Examples:
$ python classify_text.py "I love this product!"
[{'label': 'POSITIVE', 'score': 0.9998}]
$ python classify_text.py
Enter text (or 'quit' to exit): This is amazing!
[{'label': 'POSITIVE', 'score': 0.9997}]
Enter text (or 'quit' to exit): quit
"""
import argparse
from transformers import pipeline
def main():
parser = argparse.ArgumentParser(description="Classify text sentiment using a Transformer model.")
parser.add_argument("text", nargs="?", default=None, help="Text to classify (optional for interactive mode)")
parser.add_argument(
"--model",
default="distilbert-base-uncased-finetuned-sst-2-english",
help="Hugging Face model name for sentiment-analysis pipeline (default: distilbert sentiment)"
)
args = parser.parse_args()
# Load the pre-trained pipeline
print(f"Loading model: {args.model}")
classifier = pipeline("sentiment-analysis", model=args.model)
if args.text:
# Single classification
result = classifier(args.text)
print(result)
else:
# Interactive mode
print("Interactive mode. Enter text (or 'quit' to exit):")
while True:
user_input = input("> ").strip()
if user_input.lower() in ['quit', 'exit', 'q']:
print("Goodbye!")
break
if not user_input:
continue
result = classifier(user_input)
print(result)
if __name__ == "__main__":
main()
Key Features:
- Pre-trained Model: Uses DistilBERT fine-tuned on SST-2 for sentiment analysis (POSITIVE/NEGATIVE) by default. Easy to swap with
--model.
- Modes:
- CLI Single-shot:
python classify_text.py "I hate this!" → Instant result.
- Interactive: Run without args for a loop to classify multiple texts.
- Efficient: Leverages Hugging Face's
pipeline for zero boilerplate (tokenization, inference handled automatically).
- Customizable: Change model to others like
"nlptown/bert-base-multilingual-uncased-sentiment" for 5-star ratings or zero-shot models.
- Zero-shot Alternative: For open-ended classification (e.g., any labels), replace pipeline with:
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
result = classifier(text, candidate_labels=["spam", "not spam", "urgent"])
Run it directly after pip install transformers torch! 🚀