fedjumpergaming commited on
Commit
46b12e5
·
verified ·
1 Parent(s): 1511758

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -11
app.py CHANGED
@@ -1,11 +1,67 @@
1
- // REAL AI CALL (requires HF_TOKEN secret)
2
- // const response = await fetch(
3
- // "https://api-inference.huggingface.co/models/gpt2",
4
- // {
5
- // headers: { Authorization: `Bearer ${window.huggingface?.variables?.HF_TOKEN || "YOUR_TOKEN_HERE"}` },
6
- // method: "POST",
7
- // body: JSON.stringify({ inputs: "The future of AI is" }),
8
- // }
9
- // );
10
- // const data = await response.json();
11
- // aiStatus.textContent = "🧠 " + data[0]?.generated_text;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import os
4
+
5
+ # ---------- CONFIG ----------
6
+ # We'll use the free Inference API – no local model downloads.
7
+ # Get your token from https://huggingface.co/settings/tokens
8
+ # Add it as a Space secret named "HF_TOKEN"
9
+ HF_TOKEN = os.getenv("HF_TOKEN")
10
+ API_URL = "https://api-inference.huggingface.co/models/distilbert-base-uncased-finetuned-sst-2-english"
11
+
12
+ headers = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
13
+
14
+ # ---------- FUNCTION ----------
15
+ def analyze_sentiment(text):
16
+ """Send text to the model and return the sentiment label + score."""
17
+ if not text.strip():
18
+ return "⚠️ Please enter some text."
19
+
20
+ # If no token is set, show a friendly error.
21
+ if not HF_TOKEN:
22
+ return "🔑 Please set your HF_TOKEN as a Space secret."
23
+
24
+ payload = {"inputs": text}
25
+
26
+ try:
27
+ response = requests.post(API_URL, headers=headers, json=payload)
28
+ response.raise_for_status() # raise if HTTP error
29
+
30
+ # The API returns a list of predictions: [{'label': 'POSITIVE', 'score': 0.99}, ...]
31
+ result = response.json()
32
+ # The first element is the list of predictions for the first input.
33
+ # For this model, it returns a list of two dicts: one for NEGATIVE, one for POSITIVE.
34
+ # We'll pick the one with highest score.
35
+ predictions = result[0] # list of dicts
36
+ best = max(predictions, key=lambda x: x['score'])
37
+ label = best['label']
38
+ score = best['score']
39
+
40
+ return f"**{label}** (confidence: {score:.2%})"
41
+
42
+ except requests.exceptions.RequestException as e:
43
+ return f"❌ API error: {str(e)}"
44
+
45
+
46
+ # ---------- GRADIO INTERFACE ----------
47
+ demo = gr.Interface(
48
+ fn=analyze_sentiment,
49
+ inputs=gr.Textbox(
50
+ label="Enter your text",
51
+ placeholder="I love Hugging Face Spaces!",
52
+ lines=3
53
+ ),
54
+ outputs=gr.Markdown(label="Sentiment result"),
55
+ title="😊 Sentiment Analyzer",
56
+ description="Enter any text and get a sentiment prediction (positive/negative). Powered by DistilBERT.",
57
+ examples=[
58
+ ["This product is amazing!"],
59
+ ["I'm really disappointed with the service."],
60
+ ["The movie was okay, nothing special."],
61
+ ],
62
+ theme="huggingface",
63
+ )
64
+
65
+ # ---------- RUN ----------
66
+ if __name__ == "__main__":
67
+ demo.launch()