Spaces:
Sleeping
Sleeping
File size: 4,997 Bytes
0b155a4 e0386a7 0b155a4 3ea5938 0b155a4 e0386a7 0b155a4 3ea5938 |
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
import os
import requests
import gradio as gr
# This is the API endpoint for a pre-trained sentiment analysis model.
# This specific model is a DistilBERT model fine-tuned for sentiment analysis.
# The Hugging Face Inference API provides a generous free tier.
# You can find other models here: https://huggingface.co/models?pipeline_tag=text-classification&sort=downloads
API_URL = "https://api-inference.huggingface.co/models/distilbert-base-uncased-finetuned-sst-2-english"
# IMPORTANT: You need a Hugging Face API token to use the Inference API.
# 1. Go to https://huggingface.co/settings/tokens
# 2. Create a new token with "Read" access.
# 3. Copy the token and set it as an environment variable named 'HUGGING_FACE_API_TOKEN'.
# For example, in your terminal, run:
# export HUGGING_FACE_API_TOKEN="YOUR_API_TOKEN_HERE"
# (For Windows, use: set HUGGING_FACE_API_TOKEN="YOUR_API_TOKEN_HERE")
# 4. The script will automatically load this token.
API_TOKEN = os.getenv("HUGGING_FACE_API_TOKEN")
# The headers for the API request, including the authorization token.
headers = {"Authorization": f"Bearer {API_TOKEN}"}
def analyze_sentiment(text):
"""
Analyzes the sentiment of a given text using the Hugging Face Inference API.
Args:
text (str): The input text to analyze.
Returns:
str: A formatted string with the sentiment and confidence score,
or an error message if the API call fails.
"""
if not API_TOKEN:
return "ERROR: Hugging Face API token not found. Please set the HUGGING_FACE_API_TOKEN environment variable."
if not text:
return "Please enter some text to analyze."
payload = {"inputs": text}
try:
response = requests.post(API_URL, headers=headers, json=payload)
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
result = response.json()
# The API response is a list of lists. We'll grab the first item.
# Example response: [[{'label': 'POSITIVE', 'score': 0.9998782}, {'label': 'NEGATIVE', 'score': 0.00012176}]]
sentiment_data = result[0]
# Find the sentiment with the highest score
top_sentiment = max(sentiment_data, key=lambda x: x['score'])
label = top_sentiment['label']
score = top_sentiment['score'] * 100 # Convert to percentage
return f"Sentiment: {label.upper()}\nConfidence: {score:.2f}%"
except requests.exceptions.RequestException as e:
# Handle network or API errors
return f"ERROR: Failed to connect to the API. Check your token and network connection. Details: {e}"
except Exception as e:
# Handle other potential errors
return f"ERROR: An unexpected error occurred. Details: {e}"
# --- Gradio User Interface with Custom Styling ---
# Custom CSS for a cute and aesthetic theme
css = """
body {
background: linear-gradient(135deg, #f7d9e2, #c7e0ff); /* Soft gradient background */
font-family: 'Comic Sans MS', 'Arial', sans-serif;
}
.gradio-container {
background-color: rgba(255, 255, 255, 0.7); /* Semi-transparent white background */
border-radius: 20px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1); /* Soft shadow */
padding: 20px;
}
.gr-button {
background-color: #ff99cc; /* Pink button */
border: none;
color: white;
font-size: 1.1em;
border-radius: 15px;
transition: transform 0.2s ease-in-out;
}
.gr-button:hover {
background-color: #ff66b2; /* Darker pink on hover */
transform: scale(1.05); /* Slight grow effect */
}
.label-text {
font-size: 1.2em;
font-weight: bold;
color: #333;
}
.gr-text-box textarea {
border-radius: 10px;
border: 1px solid #ccc;
background-color: #fefefe;
padding: 10px;
}
"""
# Create the Gradio interface using gr.Blocks for a custom layout
with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
gr.Markdown("# ๐ธ The Happy-Go-Lucky Sentiment Analyzer ๐ธ")
gr.Markdown("A cute little AI friend that tells you the mood of your text!")
with gr.Row():
with gr.Column(scale=1):
gr.Image(
value="https://placehold.co/200x200/ffb3e6/333333?text=Cute+AI",
label="Your AI Friend",
show_label=True,
show_download_button=False
)
with gr.Column(scale=3):
input_textbox = gr.Textbox(
lines=5,
label="Tell me something!",
placeholder="Type your thoughts here, and I'll analyze the sentiment...",
info="I can tell you if your text is positive or negative."
)
analyze_button = gr.Button("๐ Analyze!")
output_label = gr.Label(label="Result")
# Event listener for the button click
analyze_button.click(fn=analyze_sentiment, inputs=input_textbox, outputs=output_label)
# Launch the Gradio app
if __name__ == "__main__":
demo.launch() |