File size: 1,256 Bytes
742d276
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import gradio as gr
from transformers import pipeline

# Load a popular, stable sentiment analysis model
sentiment_pipe = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")

def analyze_sentiment(text):
    """
    This function takes text and returns its sentiment (Positive/Negative) and a confidence score.
    """
    try:
        # The pipeline returns a list with one dictionary, e.g., [{'label': 'POSITIVE', 'score': 0.99}]
        result = sentiment_pipe(text)[0]
        label = result['label']
        score = result['score']
        
        # Format the output into a nice, readable string
        return f"Sentiment: {label} (Confidence Score: {score:.2f})"
    except Exception as e:
        return f"An error occurred: {str(e)}"

# Create the user interface for the app
iface = gr.Interface(
    fn=analyze_sentiment,
    inputs=gr.Textbox(lines=5, label="Enter Your Text Here", placeholder="e.g., I love this product, but the delivery was a bit slow."),
    outputs=gr.Textbox(label="Analysis Result"),
    title="Course Demo: AI Sentiment Analyzer",
    description="A simple tool to analyze the sentiment of a piece of text. Built for the 'Understanding AI' course."
)

# Launch the app
iface.launch()