Spaces:
Running
Running
# Import required libraries | |
import gradio as gr | |
from transformers import pipeline | |
def create_sentiment_analyzer(): | |
"""Initialize the BERT sentiment analyzer""" | |
return pipeline("sentiment-analysis", model="zavora/bert-sentiment-imdb") | |
def analyze_sentiment(text, classifier): | |
""" | |
Analyze sentiment of input text using BERT model | |
Returns sentiment and confidence score | |
""" | |
try: | |
if not text.strip(): | |
return "Please enter some text" | |
result = classifier(text)[0] | |
label = result['label'] | |
confidence = result['score'] | |
sentiment = "Positive" if label == "LABEL_1" else "Negative" | |
# Format the output | |
return f"Sentiment: {sentiment}\nConfidence: {confidence:.2%}" | |
except Exception as e: | |
return f"Error: {str(e)}" | |
# Create and cache the classifier | |
classifier = create_sentiment_analyzer() | |
# Create the Gradio interface | |
demo = gr.Interface( | |
fn=lambda text: analyze_sentiment(text, classifier), | |
inputs=[ | |
gr.Textbox( | |
lines=4, | |
placeholder="Enter your movie review here...", | |
label="Movie Review" | |
) | |
], | |
outputs=[ | |
gr.Textbox( | |
label="Analysis Result" | |
) | |
], | |
title="Movie Review Sentiment Analysis", | |
description="""This app uses a BERT model fine-tuned on IMDB movie reviews to analyze sentiment. | |
Enter your movie review and get an analysis of whether it's positive or negative.""", | |
examples=[ | |
["This movie was absolutely fantastic! The acting was superb and the plot kept me engaged throughout."], | |
["I couldn't sit through this movie. The plot was confusing and the acting was terrible."], | |
["While the movie had some good moments, overall it was just average."] | |
], | |
theme=gr.themes.Soft() | |
) | |
# Launch the app | |
if __name__ == "__main__": | |
demo.launch() |