Download app.py from Sujatha/ex: direct link, hf CLI and curl.
- Browser
- Download file 990 Bytes
-
https://huggingface.co/spaces/Sujatha/ex/resolve/main/app.py
- Command line
-
hf download hf://spaces/Sujatha/ex/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Sujatha/ex/resolve/main/app.py
990 Bytes
| import gradio as gr | |
| import torch | |
| from transformers import AutoModelForSequenceClassification, AutoTokenizer | |
| # Load model and tokenizer | |
| model_name = "distilbert-base-uncased-finetuned-sst-2-english" | |
| model = AutoModelForSequenceClassification.from_pretrained(model_name) | |
| tokenizer = AutoTokenizer.from_pretrained(model_name) | |
| # Function to classify text (sentiment analysis) | |
| def analyze_sentiment(text): | |
| inputs = tokenizer(text, return_tensors='pt') | |
| outputs = model(**inputs) | |
| prediction = torch.argmax(outputs.logits) | |
| # Map prediction to sentiment (0 == Negative, 1 == Positive) | |
| sentiment = "Positive" if prediction.item() == 1 else "Negative" | |
| return sentiment | |
| # Create Gradio interface | |
| demo = gr.Interface( | |
| fn=analyze_sentiment, | |
| inputs="text", | |
| outputs="text", | |
| title="Sentiment Analysis with DistilBERT", | |
| description="Enter text to analyze its sentiment (Positive/Negative)", | |
| ) | |
| # Launch the interface | |
| if __name__ == "__main__": | |
| demo.launch() |