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()