|
import gradio as gr |
|
from transformers import pipeline |
|
import matplotlib.pyplot as plt |
|
from collections import Counter |
|
import threading |
|
|
|
|
|
sentiment_analyzer = pipeline( |
|
"sentiment-analysis", |
|
model="distilbert-base-uncased-finetuned-sst-2-english" |
|
) |
|
|
|
|
|
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() |
|
|