ex / app.py
Sujatha's picture
Create app.py
6b46d32 verified
raw
history blame contribute delete
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()