| |
| import os |
| from transformers import pipeline |
| import gradio as gr |
|
|
| |
| |
| MODEL_NAME = "distilbert-base-uncased-finetuned-sst-2-english" |
|
|
| |
| 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] |
| label = raw["label"] |
| score = float(raw["score"]) |
|
|
| |
| 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 |
|
|
| |
| 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") |
| |
| out_probs = gr.Label(label="Predicted probabilities") |
| out_pretty = gr.Textbox(label="Predicted label", interactive=False) |
|
|
| submit = gr.Button("Analyze") |
|
|
| |
| submit.click(fn=analyze_sentiment, inputs=txt, outputs=[out_probs, out_pretty]) |
|
|
| |
| if __name__ == "__main__": |
| |
| port = int(os.environ.get("PORT", 7860)) |
| demo.launch(server_name="0.0.0.0", server_port=port) |
|
|