File size: 4,971 Bytes
e9b5614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d49154c
e9b5614
 
 
 
 
 
 
 
 
d49154c
e9b5614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d49154c
e9b5614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
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()