Spaces:
Configuration error
Configuration error
File size: 1,764 Bytes
1db0c1f | 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 | from typing import Any
import gradio as gr
from transformers import Pipeline, pipeline
MODEL_NAME = "distilbert/distilbert-base-uncased-finetuned-sst-2-english"
classifier: Pipeline = pipeline(
task="sentiment-analysis",
model=MODEL_NAME,
)
def analyze_sentiment(text: str) -> dict[str, float]:
"""Analyze text and return probabilities for Gradio's Label component."""
cleaned_text = text.strip()
if not cleaned_text:
raise gr.Error("Please enter a sentence before analyzing.")
if len(cleaned_text) > 1000:
raise gr.Error("Please keep the text below 1,000 characters.")
predictions: list[dict[str, Any]] = classifier(
cleaned_text,
top_k=None,
)
return {
prediction["label"].title(): float(prediction["score"])
for prediction in predictions
}
examples = [
["I loved working on this machine-learning project."],
["The application was confusing and frustrating."],
["The workshop was useful, but it was quite long."],
]
demo = gr.Interface(
fn=analyze_sentiment,
inputs=gr.Textbox(
lines=5,
max_lines=10,
label="Your text",
placeholder="Example: Learning Hugging Face is exciting!",
),
outputs=gr.Label(
label="Sentiment prediction",
num_top_classes=2,
),
examples=examples,
title="🤗 Beginner Sentiment Analyzer",
description=(
"Enter an English sentence and let a pretrained Hugging Face "
"model classify its sentiment."
),
article=(
"This beginner project uses DistilBERT, Transformers, "
"PyTorch, and Gradio."
),
submit_btn="Analyze sentiment",
clear_btn="Clear",
)
if __name__ == "__main__":
demo.launch() |