Spaces:
Sleeping
Sleeping
File size: 2,499 Bytes
c827d89 5b3d768 c827d89 5b3d768 c40c386 c827d89 c40c386 5b3d768 c40c386 5b3d768 c827d89 5b3d768 c827d89 c40c386 5b3d768 c827d89 5b3d768 c827d89 c40c386 c827d89 5b3d768 c827d89 5b3d768 c827d89 5b3d768 7738ab0 c827d89 5b3d768 c827d89 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | 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()
|