Spaces:
Sleeping
Sleeping
File size: 11,962 Bytes
3670fc5 | 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 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | import gradio as gr
import numpy as np
import logging
from collections import Counter
from config import config
from analyzer import SentimentEngine
from visualizer import PlotFactory, ThemeContext
from utils import HistoryManager, DataHandler, handle_errors, managed_figure
class SentimentApp:
"""Main application orchestrator"""
def __init__(self):
self.engine = SentimentEngine()
self.history = HistoryManager()
self.data_handler = DataHandler()
self.examples = [
["While the film's visual effects were undeniably impressive, the story lacked emotional weight, and the pacing felt inconsistent throughout."],
["An extraordinary achievement in filmmaking — the direction was masterful, the script was sharp, and every performance added depth and realism."],
["Despite a promising start, the film quickly devolved into a series of clichés, with weak character development and an ending that felt rushed and unearned."],
["A beautifully crafted story with heartfelt moments and a soundtrack that perfectly captured the emotional tone of each scene."],
["The movie was far too long, with unnecessary subplots and dull dialogue that made it difficult to stay engaged until the end."]
]
@handle_errors(default_return=("Please enter text", None, None, None))
def analyze_single_fast(self, text: str, theme: str = 'default'):
"""Fast single text analysis without keywords"""
if not text.strip():
return "Please enter text", None, None, None
result = self.engine.analyze_single_fast(text)
self.history.add({
'text': text[:100],
'full_text': text,
**result
})
theme_ctx = ThemeContext(theme)
probs = np.array([result['neg_prob'], result['pos_prob']])
prob_plot = PlotFactory.create_sentiment_bars(probs, theme_ctx)
gauge_plot = PlotFactory.create_confidence_gauge(result['confidence'], result['sentiment'], theme_ctx)
cloud_plot = PlotFactory.create_wordcloud(text, result['sentiment'], theme_ctx)
result_text = f"Sentiment: {result['sentiment']} (Confidence: {result['confidence']:.3f})"
return result_text, prob_plot, gauge_plot, cloud_plot
@handle_errors(default_return=("Please enter text", None, None, None))
def analyze_single_advanced(self, text: str, theme: str = 'default'):
"""Advanced single text analysis with LIME and SHAP explanation"""
if not text.strip():
return "Please enter text", None, None, None
result = self.engine.analyze_single_advanced(text)
self.history.add({
'text': text[:100],
'full_text': text,
**result
})
theme_ctx = ThemeContext(theme)
lime_plot = PlotFactory.create_lime_keyword_chart(result['lime_words'], result['sentiment'], theme_ctx)
shap_plot = PlotFactory.create_shap_keyword_chart(result['shap_words'], result['sentiment'], theme_ctx)
lime_words_str = ", ".join([f"{word}({score:.3f})" for word, score in result['lime_words'][:5]])
shap_words_str = ", ".join([f"{word}({score:.3f})" for word, score in result['shap_words'][:5]])
result_text = (f"Sentiment: {result['sentiment']} (Confidence: {result['confidence']:.3f})\n"
f"LIME Key Words: {lime_words_str}\n"
f"SHAP Key Words: {shap_words_str}")
return result_text, lime_plot, shap_plot, result['heatmap_html']
@handle_errors(default_return=None)
def analyze_batch(self, reviews: str, progress=None):
"""Batch analysis"""
if not reviews.strip():
return None
texts = [r.strip() for r in reviews.split('\n') if r.strip()]
if len(texts) < 2:
return None
results = self.engine.analyze_batch(texts, progress)
for result in results:
self.history.add(result)
theme_ctx = ThemeContext('default')
return PlotFactory.create_batch_analysis(results, theme_ctx)
@handle_errors(default_return=(None, "No history available"))
def plot_history(self, theme: str = 'default'):
"""Plot analysis history"""
history = self.history.get_all()
if len(history) < 2:
return None, f"Need at least 2 analyses for trends. Current: {len(history)}"
theme_ctx = ThemeContext(theme)
with managed_figure(figsize=(12, 8)) as fig:
gs = fig.add_gridspec(2, 1, hspace=0.3)
indices = list(range(len(history)))
pos_probs = [item['pos_prob'] for item in history]
confs = [item['confidence'] for item in history]
# Sentiment trend
ax1 = fig.add_subplot(gs[0, 0])
colors = [theme_ctx.colors['pos'] if p > 0.5 else theme_ctx.colors['neg']
for p in pos_probs]
ax1.scatter(indices, pos_probs, c=colors, alpha=0.7, s=60)
ax1.plot(indices, pos_probs, alpha=0.5, linewidth=2)
ax1.axhline(y=0.5, color='gray', linestyle='--', alpha=0.5)
ax1.set_title('Sentiment History')
ax1.set_ylabel('Positive Probability')
ax1.grid(True, alpha=0.3)
# Confidence trend
ax2 = fig.add_subplot(gs[1, 0])
ax2.bar(indices, confs, alpha=0.7, color='lightblue', edgecolor='navy')
ax2.set_title('Confidence Over Time')
ax2.set_xlabel('Analysis Number')
ax2.set_ylabel('Confidence')
ax2.grid(True, alpha=0.3)
fig.tight_layout()
return fig, f"History: {len(history)} analyses"
def create_interface():
"""Create streamlined Gradio interface"""
app = SentimentApp()
with gr.Blocks(theme=gr.themes.Soft(), title="Movie Sentiment Analyzer") as demo:
gr.Markdown("# 🎬 AI Movie Sentiment Analyzer")
gr.Markdown("Fast sentiment analysis with advanced deep learning explanations")
with gr.Tab("Quick Analysis"):
with gr.Row():
with gr.Column():
text_input = gr.Textbox(
label="Movie Review",
placeholder="Enter your movie review...",
lines=5
)
with gr.Row():
analyze_btn = gr.Button("Analyze", variant="primary")
theme_selector = gr.Dropdown(
choices=list(config.THEMES.keys()),
value="default",
label="Theme"
)
gr.Examples(
examples=app.examples,
inputs=text_input
)
with gr.Column():
result_output = gr.Textbox(label="Result", lines=3)
with gr.Row():
prob_plot = gr.Plot(label="Probabilities")
gauge_plot = gr.Plot(label="Confidence")
with gr.Row():
wordcloud_plot = gr.Plot(label="Word Cloud")
with gr.Tab("Advanced Analysis"):
with gr.Row():
with gr.Column():
adv_text_input = gr.Textbox(
label="Movie Review",
placeholder="Enter your movie review for deep analysis...",
lines=5
)
with gr.Row():
adv_analyze_btn = gr.Button("Deep Analyze", variant="primary")
adv_theme_selector = gr.Dropdown(
choices=list(config.THEMES.keys()),
value="default",
label="Theme"
)
gr.Examples(
examples=app.examples,
inputs=adv_text_input
)
with gr.Column():
adv_result_output = gr.Textbox(label="Analysis Result", lines=4)
with gr.Row():
lime_plot = gr.Plot(label="LIME: Key Contributing Words")
shap_plot = gr.Plot(label="SHAP: Key Contributing Words")
with gr.Row():
heatmap_output = gr.HTML(label="Word Importance Heatmap (LIME-based)")
with gr.Tab("Batch Analysis"):
with gr.Row():
with gr.Column():
file_upload = gr.File(label="Upload File", file_types=[".csv", ".txt"])
batch_input = gr.Textbox(
label="Reviews (one per line)",
lines=8
)
with gr.Column():
load_btn = gr.Button("Load File")
batch_btn = gr.Button("Analyze Batch", variant="primary")
batch_plot = gr.Plot(label="Batch Results")
with gr.Tab("History & Export"):
with gr.Row():
refresh_btn = gr.Button("Refresh")
clear_btn = gr.Button("Clear", variant="stop")
with gr.Row():
csv_btn = gr.Button("Export CSV")
json_btn = gr.Button("Export JSON")
history_status = gr.Textbox(label="Status")
history_plot = gr.Plot(label="History Trends")
csv_file = gr.File(label="CSV Download", visible=True)
json_file = gr.File(label="JSON Download", visible=True)
# Event bindings for Quick Analysis
analyze_btn.click(
app.analyze_single_fast,
inputs=[text_input, theme_selector],
outputs=[result_output, prob_plot, gauge_plot, wordcloud_plot]
)
# Event bindings for Advanced Analysis
adv_analyze_btn.click(
app.analyze_single_advanced,
inputs=[adv_text_input, adv_theme_selector],
outputs=[adv_result_output, lime_plot, shap_plot, heatmap_output]
)
# Event bindings for Batch Analysis
load_btn.click(app.data_handler.process_file, inputs=file_upload, outputs=batch_input)
batch_btn.click(app.analyze_batch, inputs=batch_input, outputs=batch_plot)
# Event bindings for History & Export
refresh_btn.click(
lambda theme: app.plot_history(theme),
inputs=theme_selector,
outputs=[history_plot, history_status]
)
clear_btn.click(
lambda: f"Cleared {app.history.clear()} entries",
outputs=history_status
)
csv_btn.click(
lambda: app.data_handler.export_data(app.history.get_all(), 'csv'),
outputs=[csv_file, history_status]
)
json_btn.click(
lambda: app.data_handler.export_data(app.history.get_all(), 'json'),
outputs=[json_file, history_status]
)
return demo
# Application Entry Point
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
demo = create_interface()
demo.launch(share=True) |