DexterSptizu's picture
Update app.py
9e282fb verified
import gradio as gr
from transformers import pipeline
# Load the sentiment analysis pipeline with a specific model
sentiment_pipeline = pipeline("sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment")
# Define a function for sentiment analysis
def analyze_sentiment(text):
result = sentiment_pipeline(text)
label = result[0]['label'] # Get the label, e.g., "1 star", "5 stars"
score = int(label.split()[0]) # Extract the numerical part of the label (e.g., 1, 2, ..., 5)
# Map the score from 1-5 to -1 to 1:
# 1 star -> -1.0, 2 stars -> -0.5, 3 stars -> 0.0, 4 stars -> 0.5, 5 stars -> 1.0
sentiment_score = (score - 3) / 2
return sentiment_score
# Create a list of example sentences for users to select from
examples = [
["I love using Hugging Face Transformers!"],
["The product is terrible and I will never buy it again."],
["This is the best experience I've ever had!"],
["The movie was okay, not great but not bad either."],
["I am extremely disappointed with the service."]
]
# Create a Gradio interface
interface = gr.Interface(
fn=analyze_sentiment,
inputs=gr.Textbox(label="Enter text for sentiment analysis", placeholder="Type your text here..."),
outputs=gr.Number(label="Sentiment Score (-1 to 1)"),
examples=examples,
title="Sentiment Analysis with Hugging Face Transformers",
description="""
Enter a sentence to analyze its sentiment. The model will output a sentiment score between -1 and 1:
- **-1**: Extremely Negative
- **0**: Neutral
- **+1**: Extremely Positive
This uses the `nlptown/bert-base-multilingual-uncased-sentiment` model.
"""
)
# Launch the Gradio app
if __name__ == "__main__":
interface.launch()