Spaces:
Configuration error
Configuration error
| 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() |