testing / app.py
new421's picture
Update app.py
071670d verified
# app.py
import os
from transformers import pipeline
import gradio as gr
# Load the sentiment-analysis pipeline once (cached in memory).
# Model: distilBERT fine-tuned on SST-2. Swap this string with another HF model if you want.
MODEL_NAME = "distilbert-base-uncased-finetuned-sst-2-english"
# Instantiate the pipeline (this downloads weights the first time).
sentiment_pipe = pipeline("sentiment-analysis", model=MODEL_NAME, tokenizer=MODEL_NAME)
def analyze_sentiment(text: str):
"""
Analyze sentiment for `text` and return:
- a dict of label probabilities (for gr.Label component)
- a human-readable label + score string
"""
if not text or not text.strip():
return {"POSITIVE": 0.0, "NEGATIVE": 0.0}, "No input provided."
raw = sentiment_pipe(text[:1000])[0] # truncate long text to 1000 chars to keep latency reasonable
label = raw["label"] # "POSITIVE" or "NEGATIVE"
score = float(raw["score"])
# Provide both label probabilities so the Label component can show a nice bar
if label.upper() == "POSITIVE":
probs = {"POSITIVE": score, "NEGATIVE": 1.0 - score}
else:
probs = {"POSITIVE": 1.0 - score, "NEGATIVE": score}
pretty = f"{label} (confidence: {score:.2f})"
return probs, pretty
# Build Gradio UI
title = "Simple Sentiment Classifier (Transformers → Gradio)"
description = "Type some text and the model will predict sentiment (positive/negative). Uses a Hugging Face transformers sentiment model in the backend."
with gr.Blocks() as demo:
gr.Markdown(f"# {title}")
gr.Markdown(description)
with gr.Row():
txt = gr.Textbox(lines=6, placeholder="Enter text to analyze...", label="Input text")
# Left: probabilities shown as bars. Right: human readable label
out_probs = gr.Label(label="Predicted probabilities")
out_pretty = gr.Textbox(label="Predicted label", interactive=False)
submit = gr.Button("Analyze")
# Wire inputs -> function
submit.click(fn=analyze_sentiment, inputs=txt, outputs=[out_probs, out_pretty])
# If you deploy on Hugging Face Spaces, they run the app automatically; otherwise run locally.
if __name__ == "__main__":
# Use environment variable PORT for cloud hosts (Spaces sets it automatically)
port = int(os.environ.get("PORT", 7860))
demo.launch(server_name="0.0.0.0", server_port=port)