| import gradio as gr |
| from transformers import pipeline |
|
|
| |
| classifier = pipeline( |
| "sentiment-analysis", |
| model="distilbert-base-uncased-finetuned-sst-2-english", |
| ) |
|
|
| |
| EXAMPLES = [ |
| "This movie was absolutely incredible! Best I've seen all year.", |
| "Waste of time. Terrible acting, predictable plot.", |
| "It was okay, nothing special but not bad either.", |
| "The cinematography was stunning but the story fell flat.", |
| "I've watched it three times already. Pure masterpiece.", |
| ] |
|
|
| def analyze(text): |
| result = classifier(text[:512])[0] |
| label = result["label"] |
| score = result["score"] |
| emoji = "π" if label == "POSITIVE" else "π" |
| return {emoji: score if label == "POSITIVE" else 1 - score} |
|
|
| with gr.Blocks(theme=gr.themes.Soft(), title="Sentiment Analyzer") as demo: |
| gr.Markdown( |
| """ |
| # π Sentiment Analyzer |
| |
| Tiny model, big opinions. Type any text and see if it's positive or negative. |
| |
| **Model:** DistilBERT fine-tuned on SST-2 (67M params, runs on CPU) |
| """ |
| ) |
| with gr.Row(): |
| text_input = gr.Textbox( |
| label="Your text", |
| placeholder="What's on your mind?", |
| lines=3, |
| ) |
| with gr.Row(): |
| btn = gr.Button("Analyze", variant="primary", scale=0) |
| with gr.Row(): |
| output = gr.Label(label="Sentiment", num_top_classes=2) |
|
|
| btn.click(fn=analyze, inputs=text_input, outputs=output) |
| gr.Examples(examples=EXAMPLES, inputs=text_input) |
|
|
| gr.Markdown( |
| """ |
| --- |
| Built with [DistilBERT](https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english) | [arinbalyan](https://huggingface.co/arinbalyan) |
| """ |
| ) |
|
|
| if __name__ == "__main__": |
| demo.launch() |
|
|