Download app.py from dgotlieb/AI-Course-Sentiment-Analyzer: direct link, hf CLI and curl.
- Browser
- Download file 1.26 kB
-
https://huggingface.co/spaces/dgotlieb/AI-Course-Sentiment-Analyzer/resolve/main/app.py
- Command line
-
hf download hf://spaces/dgotlieb/AI-Course-Sentiment-Analyzer/app.py
-
curl -L -o app.py https://huggingface.co/spaces/dgotlieb/AI-Course-Sentiment-Analyzer/resolve/main/app.py
1.26 kB
| 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() |