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