File size: 2,134 Bytes
386a1d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from transformers import pipeline
import matplotlib.pyplot as plt
from collections import Counter
import threading

# Initialize sentiment pipeline
sentiment_analyzer = pipeline(
    "sentiment-analysis",
    model="distilbert-base-uncased-finetuned-sst-2-english"
)

# Thread-safe log storage
log_lock = threading.Lock()
sentiment_log = []

def analyze_and_log(text):
    result = sentiment_analyzer(text)[0]
    label = result['label']
    score = round(result['score'], 3)
    entry = f"Input: {text} --> Sentiment: {label} (Confidence: {score})"
    
    with log_lock:
        sentiment_log.append((text, label))
    
    return label, score, entry, update_chart()

def update_chart():
    with log_lock:
        labels = [label for _, label in sentiment_log]
    counts = Counter(labels)
    
    fig, ax = plt.subplots(figsize=(4, 3))
    ax.bar(counts.keys(), counts.values(), color=['#4CAF50', '#F44336'])
    ax.set_title("Sentiment Distribution")
    ax.set_xlabel("Sentiment")
    ax.set_ylabel("Count")
    plt.tight_layout()
    
    return fig

with gr.Blocks() as demo:
    gr.Markdown("# DistilBERT Sentiment Analysis with Live Logs & Visualization")
    gr.Markdown("Enter your salon feedback or product review below and get instant sentiment analysis, logging, and sentiment summary visualization.")
    
    with gr.Row():
        with gr.Column(scale=3):
            input_text = gr.Textbox(lines=3, placeholder="Type your text here...")
            analyze_btn = gr.Button("Analyze Sentiment")
            sentiment_label = gr.Textbox(label="Sentiment Label", interactive=False)
            confidence_score = gr.Textbox(label="Confidence Score", interactive=False)
            log_output = gr.Textbox(label="Analysis Log", interactive=False, lines=10)
            
        with gr.Column(scale=2):
            sentiment_chart = gr.Plot(label="Sentiment Distribution Chart")
    
    analyze_btn.click(
        analyze_and_log,
        inputs=input_text,
        outputs=[sentiment_label, confidence_score, log_output, sentiment_chart]
    )
    
if __name__ == "__main__":
    demo.launch()