Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import requests | |
| import os | |
| # ---------- CONFIG ---------- | |
| # We'll use the free Inference API – no local model downloads. | |
| # Get your token from https://huggingface.co/settings/tokens | |
| # Add it as a Space secret named "HF_TOKEN" | |
| HF_TOKEN = os.getenv("HF_TOKEN") | |
| API_URL = "https://api-inference.huggingface.co/models/distilbert-base-uncased-finetuned-sst-2-english" | |
| headers = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {} | |
| # ---------- FUNCTION ---------- | |
| def analyze_sentiment(text): | |
| """Send text to the model and return the sentiment label + score.""" | |
| if not text.strip(): | |
| return "⚠️ Please enter some text." | |
| # If no token is set, show a friendly error. | |
| if not HF_TOKEN: | |
| return "🔑 Please set your HF_TOKEN as a Space secret." | |
| payload = {"inputs": text} | |
| try: | |
| response = requests.post(API_URL, headers=headers, json=payload) | |
| response.raise_for_status() # raise if HTTP error | |
| # The API returns a list of predictions: [{'label': 'POSITIVE', 'score': 0.99}, ...] | |
| result = response.json() | |
| # The first element is the list of predictions for the first input. | |
| # For this model, it returns a list of two dicts: one for NEGATIVE, one for POSITIVE. | |
| # We'll pick the one with highest score. | |
| predictions = result[0] # list of dicts | |
| best = max(predictions, key=lambda x: x['score']) | |
| label = best['label'] | |
| score = best['score'] | |
| return f"**{label}** (confidence: {score:.2%})" | |
| except requests.exceptions.RequestException as e: | |
| return f"❌ API error: {str(e)}" | |
| # ---------- GRADIO INTERFACE ---------- | |
| demo = gr.Interface( | |
| fn=analyze_sentiment, | |
| inputs=gr.Textbox( | |
| label="Enter your text", | |
| placeholder="I love Hugging Face Spaces!", | |
| lines=3 | |
| ), | |
| outputs=gr.Markdown(label="Sentiment result"), | |
| title="😊 Sentiment Analyzer", | |
| description="Enter any text and get a sentiment prediction (positive/negative). Powered by DistilBERT.", | |
| examples=[ | |
| ["This product is amazing!"], | |
| ["I'm really disappointed with the service."], | |
| ["The movie was okay, nothing special."], | |
| ], | |
| theme="huggingface", | |
| ) | |
| # ---------- RUN ---------- | |
| if __name__ == "__main__": | |
| demo.launch() |