jonathanagustin's picture
Sync from deploy tool: tutorials/01-sentiment-explorer
7738ab0 verified
import os
import logging
import gradio as gr
from huggingface_hub import InferenceClient
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger(__name__)
# Environment variables for configuration
HF_TOKEN = os.environ.get("HF_TOKEN", "")
MODEL_ID = os.environ.get("MODEL_ID", "distilbert/distilbert-base-uncased-finetuned-sst-2-english")
logger.info(f"HF_TOKEN configured: {bool(HF_TOKEN)}")
logger.info(f"MODEL_ID: {MODEL_ID}")
client = InferenceClient(token=HF_TOKEN) if HF_TOKEN else InferenceClient()
logger.info("InferenceClient initialized")
def analyze(text: str) -> tuple[str, dict]:
"""Return emoji + label and confidence scores."""
logger.info(f"analyze() called | text_len={len(text)}")
if not text.strip():
logger.warning("Empty text received")
return "πŸ€” Enter some text!", {}
try:
logger.info(f"Calling text_classification | model={MODEL_ID}")
result = client.text_classification(text, model=MODEL_ID)[0]
label = result.label
score = result.score
logger.info(f"Result: {label} ({score:.1%})")
emoji = "😊" if label == "POSITIVE" else "😞"
return f"{emoji} {label} ({score:.1%})", {label: score, "OTHER": 1 - score}
except Exception as e:
logger.error(f"API error: {e}")
return f"❌ Error: {e}", {}
logger.info("Building Gradio interface...")
with gr.Blocks(title="Sentiment Explorer") as demo:
gr.Markdown("# 🎭 Sentiment Explorer\nType anything and see if it's positive or negative!")
inp = gr.Textbox(
label="Your text",
placeholder="I absolutely love learning about AI!",
lines=3,
autofocus=True,
)
with gr.Row(equal_height=True):
result_label = gr.Textbox(label="Verdict", interactive=False)
confidence = gr.Label(label="Confidence")
btn = gr.Button("Analyze", variant="primary")
btn.click(analyze, inputs=inp, outputs=[result_label, confidence])
inp.submit(analyze, inputs=inp, outputs=[result_label, confidence])
gr.Examples(
examples=[
["This tutorial is amazing and super helpful!"],
["I'm frustrated, nothing works today."],
["The weather is okay, I guess."],
],
inputs=inp,
)
demo.queue()
logger.info("Starting Gradio server...")
demo.launch()