sawdah's picture
Update app.py
d49154c verified
Raw
History Blame Contribute Delete
4.97 kB
import gradio as gr
from transformers import pipeline
import time
print("Loading sentiment model...")
classifier = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
print("Model ready!")
def analyze_single(text):
if not text or not text.strip():
return "⚠️ Please enter some text.", "", ""
text = text.strip()
if len(text) > 512:
return "⚠️ Text too long. Max 512 characters.", "", ""
start = time.time()
result = classifier(text)[0]
elapsed = round((time.time() - start) * 1000, 1)
label = result["label"]
score = round(result["score"] * 100, 2)
emoji = "😊" if label == "POSITIVE" else "😔"
sentiment_out = f"{emoji} {label}"
confidence_out = f"{score}%"
time_out = f"{elapsed} ms"
return sentiment_out, confidence_out, time_out
def analyze_batch(texts_input):
if not texts_input or not texts_input.strip():
return "⚠️ Please enter at least one sentence."
lines = [line.strip() for line in texts_input.strip().split("\n") if line.strip()]
if len(lines) > 20:
return "⚠️ Max 20 sentences. Please reduce input."
results = classifier(lines)
output_lines = []
for text, result in zip(lines, results):
label = result["label"]
score = round(result["score"] * 100, 1)
emoji = "😊" if label == "POSITIVE" else "😔"
short_text = text[:60] + "..." if len(text) > 60 else text
output_lines.append(f"{emoji} [{label}{score}%] {short_text}")
summary_pos = sum(1 for r in results if r["label"] == "POSITIVE")
summary_neg = len(results) - summary_pos
output_lines.append("")
output_lines.append(f" Summary: {summary_pos} Positive | {summary_neg} Negative | {len(results)} Total")
return "\n".join(output_lines)
with gr.Blocks(
theme=gr.themes.Soft(primary_hue="blue", secondary_hue="indigo"),
title="Sentiment Analyzer"
) as demo:
gr.Markdown("""
# Sentiment Analyzer
Detects **Positive** or **Negative** sentiment using DistilBERT.
Built with HuggingFace Transformers · Model accuracy ~91% on SST-2 benchmark.
""")
with gr.Tabs():
with gr.TabItem("Single Analysis"):
with gr.Row():
with gr.Column(scale=2):
text_input = gr.Textbox(
lines=4,
placeholder="Type any sentence here...\ne.g. I love building AI projects!",
label="Input Text",
max_lines=6
)
analyze_btn = gr.Button("Analyze Sentiment ", variant="primary", size="lg")
with gr.Column(scale=1):
sentiment_out = gr.Textbox(label="Sentiment", interactive=False)
confidence_out = gr.Textbox(label="Confidence Score", interactive=False)
time_out = gr.Textbox(label="Response Time", interactive=False)
gr.Examples(
examples=[
["I absolutely love building AI projects, it's so rewarding!"],
["This is the worst experience I have ever had."],
["The weather today is absolutely beautiful and I feel great."],
["I am so frustrated and disappointed with this outcome."],
["HuggingFace makes natural language processing incredibly easy!"],
],
inputs=text_input,
label="Try these examples"
)
analyze_btn.click(
fn=analyze_single,
inputs=text_input,
outputs=[sentiment_out, confidence_out, time_out]
)
with gr.TabItem("Batch Analysis"):
gr.Markdown("Enter **one sentence per line** (max 20 sentences)")
with gr.Row():
with gr.Column():
batch_input = gr.Textbox(
lines=8,
placeholder="I love this product!\nThis was a terrible experience.\nGreat service, highly recommend.\nI will never buy this again.",
label="Input Sentences (one per line)"
)
batch_btn = gr.Button("Analyze All 🔍", variant="primary", size="lg")
with gr.Column():
batch_output = gr.Textbox(
lines=12,
label="Results",
interactive=False
)
batch_btn.click(
fn=analyze_batch,
inputs=batch_input,
outputs=batch_output
)
gr.Markdown("""
---
**Model:** distilbert-base-uncased-finetuned-sst-2-english · **Task:** Binary Sentiment Classification
**Developer:** Sawda · BS Computer Engineering Technology · IIU Islamabad
""")
demo.launch()