Spaces:
Sleeping
Sleeping
| import os | |
| import requests | |
| import gradio as gr | |
| API_URL = "https://router.huggingface.co/hf-inference/models/cardiffnlp/twitter-roberta-base-sentiment-latest" | |
| headers = {"Authorization": f"Bearer {os.environ.get('HF_TOKEN')}"} | |
| def query(payload): | |
| return requests.post(API_URL, headers=headers, json=payload).json() | |
| def colorize(label): | |
| colors = { | |
| "positive": "green", | |
| "negative": "red", | |
| "neutral": "orange" | |
| } | |
| return colors.get(label.lower(), "black") | |
| def predict_sentiment(text): | |
| if not text.strip(): | |
| return "⚠️ Input kosong" | |
| output = query({"inputs": text}) | |
| try: | |
| preds = output[0] | |
| main = max(preds, key=lambda x: x["score"]) | |
| c = colorize(main["label"]) | |
| main_html = f""" | |
| <h3>🎯 Prediksi Utama: <span style='color:{c}'>{main['label']}</span> ({main['score']:.4f})</h3> | |
| """ | |
| details = "" | |
| for p in preds: | |
| col = colorize(p["label"]) | |
| details += f"<div><b style='color:{col}'>{p['label']}</b> → {p['score']:.4f}</div>" | |
| return main_html + "<br>" + details | |
| except: | |
| return str(output) | |
| with gr.Blocks(title="Twitter Sentiment Analysis") as ui: | |
| gr.Markdown("## 🧠 Twitter Sentiment Analysis (RoBERTa)") | |
| gr.Markdown("Masukkan teks untuk dianalisis sentimennya:") | |
| input_box = gr.Textbox(lines=3, label="Teks") | |
| output_box = gr.HTML(label="Hasil Prediksi") | |
| btn = gr.Button("Analisis Sentimen") | |
| btn.click(predict_sentiment, inputs=input_box, outputs=output_box) | |
| ui.launch() | |