-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1090 lines (904 loc) · 46.1 KB
/
app.py
File metadata and controls
1090 lines (904 loc) · 46.1 KB
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime
import time
import os
from typing import Dict, List
# Import all our logic functions from the new file
from analysis_logic import (
load_models,
analyze_text_comprehensive,
extract_aspects,
download_youtube_video,
recognize_speech,
extract_audio_from_video,
transcribe_audio,
scrape_webpage_text,
analyze_speech_emotion,
fetch_youtube_metadata,
download_youtube_audio_simple,
convert_to_wav_16k_mono
)
# ----------------------------
# Page Configuration
# ----------------------------
st.set_page_config(
page_title="Advanced Sentiment Analysis",
page_icon="icon.png",
layout="wide",
initial_sidebar_state="expanded"
)
# ----------------------------
# Custom CSS
# ----------------------------
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');
* { font-family: 'Inter', sans-serif; }
/* --- GLOBAL GRADIENT TEXT STYLING --- */
/* Applies only to headers and hero title */
h1, h2, h3, .hero-title {
background: linear-gradient(90deg, #004aad, #cb6ce6);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
color: transparent;
font-weight: 700 !important;
}
/* Make normal text soft white */
p, .stMarkdown, .stText, .hero-subtitle {
color: #e2e8f0 !important; /* Soft slate-white */
}
/* ------------------------------------------------------- */
.main { background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%); color: #f1f5f9; }
[data-testid="stSidebar"] { background: linear-gradient(180deg, #1e293b 0%, #0f172a 100%); border-right: 1px solid #334155; }
[data-testid="stSidebar"] > div:first-child > div:first-child {
padding-top: 1rem;
}
/* FIX: Keep sidebar headers WHITE so they are readable against dark background */
[data-testid="stSidebar"] h1, [data-testid="stSidebar"] h2, [data-testid="stSidebar"] h3 {
background: none !important;
-webkit-text-fill-color: #f1f5f9 !important;
color: #f1f5f9 !important;
}
[data-testid="stSidebar"] > div:first-child > div:first-child > div:nth-child(1) p {
color: #94a3b8 !important;
margin-top: -10px;
}
[data-testid="stSidebar"] hr {
margin-top: 0;
margin-bottom: 20px;
}
.hero-title {
font-size: 3.0rem;
margin-bottom: 1rem;
text-align: center;
}
.hero-subtitle {
font-size: 1.2rem;
text-align: center;
margin-bottom: 2rem;
margin-top: -1rem;
}
.feature-badges { display: flex; justify-content: center; gap: 1rem; flex-wrap: wrap; margin: 2rem 0; }
/* --- RESTORED OLD COLOR FOR BADGES --- */
.badge {
background: rgba(167, 155, 255, 0.1);
border: 1px solid #A79BFF; /* <--- Restored to Original Purple */
color: #f1f5f9;
padding: 0.5rem 1rem;
border-radius: 50px;
font-size: 0.9rem;
font-weight: 500;
}
.sentiment-card { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 16px; padding: 2rem; text-align: center; color: white; margin: 1rem 0; }
.sentiment-score { font-size: 3rem; font-weight: 800; margin-bottom: 0.5rem; }
.sentiment-label { font-size: 1.3rem; text-transform: uppercase; letter-spacing: 2px; }
.stButton>button {
background: linear-gradient(90deg, #004aad, #cb6ce6);
color: #f1f5f9;
border: none;
border-radius: 50px;
padding: 0.75rem 1.5rem;
font-weight: 600;
transition: all 0.3s ease;
width: 100%;
}
/* Style submit button inside forms (🚀 Analyze Text) */
form button[kind="formSubmit"] {
background: linear-gradient(90deg, #004aad, #cb6ce6) !important;
color: #ffffff !important;
border-radius: 50px !important;
padding: 0.75rem 2rem !important;
font-weight: 600 !important;
border: none !important;
transition: all 0.25s ease-in-out !important;
}
form button[kind="formSubmit"]:hover {
transform: translateY(-2px) !important;
box-shadow: 0 6px 18px rgba(203, 108, 230, 0.35) !important;
filter: brightness(1.1) !important;
cursor: pointer !important;
}
.stButton>button:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(203, 108, 230, 0.4);
filter: brightness(1.2);
}
/* --- RESTORED OLD COLOR FOR CARD BORDERS --- */
[data-testid="stVerticalBlock"] > [data-testid="stVerticalBlock"] > [data-testid="stVerticalBlock"] > [data-testid="stVerticalBlock"] > [data-testid="stVerticalBlock"] > div[data-testid="stVerticalBlockBorderWrapper"] {
background-color: rgba(167, 155, 255, 0.05);
border-color: #A79BFF; /* <--- Restored to Original Purple */
border-radius: 12px;
padding: 1.5rem;
margin-bottom: 1rem;
}
/* Sidebar radio button styles */
[data-testid="stRadio"] > div[role="radiogroup"] > label[data-baseweb="radio"] > div:first-child {
display: none;
}
[data-testid="stRadio"] > div[role="radiogroup"] > label {
padding: 10px 12px;
border-radius: 8px;
transition: all 0.2s ease-in-out;
margin-bottom: 5px;
border: 1px solid transparent;
cursor: pointer;
}
/* --- RESTORED OLD COLOR FOR SIDEBAR HOVER --- */
[data-testid="stRadio"] > div[role="radiogroup"] > label:hover {
background-color: rgba(167, 155, 255, 0.25);
border-color: #A79BFF; /* <--- Restored to Original Purple */
}
[data-testid="stRadio"] > div[role="radiogroup"] > label[data-checked="true"] {
background-color: rgba(167, 155, 255, 0.15);
border-color: #A79BFF; /* <--- Restored to Original Purple */
font-weight: 600;
color: #f1f5f9;
}
.emotion-card { background: rgba(15, 23, 42, 0.5); border-radius: 12px; padding: 1.5rem; text-align: center; border: 1px solid #334155; margin: 0.5rem; }
.chat-message { padding: 1rem; border-radius: 8px; margin: 0.5rem 0; }
.user-message { background: rgba(99, 102, 241, 0.2); margin-left: 20%; }
.bot-message { background: rgba(15, 23, 42, 0.5); margin-right: 20%; }
.aspect-card { background: linear-gradient(135deg, #1e293b 0%, #334155 100%); border-radius: 12px; padding: 1rem; margin: 0.5rem 0; border-left: 4px solid; }
.aspect-positive { border-color: #10b981; }
.aspect-negative { border-color: #ef4444; }
.aspect-neutral { border-color: #f59e0b; }
</style>
""", unsafe_allow_html=True)
# ----------------------------
# Load Models
# ----------------------------
bert_analyzer, vader_analyzer, nlp_model, emotion_pipeline, emotion_pipeline_all, whisper_model, sarcasm_pipeline, ser_pipeline = load_models()
if not bert_analyzer or not whisper_model or not sarcasm_pipeline or not ser_pipeline:
st.error("Fatal Error: Could not load AI models. The app cannot start.")
st.stop()
# ----------------------------
# Session State
# ----------------------------
if "history" not in st.session_state:
st.session_state.history = []
if "page" not in st.session_state:
st.session_state.page = "🏠 Home" # Used for navigation
# ----------------------------
# Navigation Callback
# ----------------------------
def set_page(page_name):
st.session_state.page = page_name
# ----------------------------
# Display Functions (UI Logic)
# ----------------------------
def create_sentiment_gauge(score, sentiment_label):
"""
Creates a Plotly gauge chart for the sentiment score.
Score is assumed to be from 0 to 1.
"""
if sentiment_label == 'POSITIVE':
gauge_color = "#4CAF50" # Green
title_color = "#4CAF50"
elif sentiment_label == 'NEGATIVE':
gauge_color = "#F44336" # Red
title_color = "#F44336"
else: # NEUTRAL
gauge_color = "#FBBC05" # Yellow
title_color = "#FBBC05"
title_text = f"Overall Sentiment: <span style='color:{title_color}; font-weight:bold;'>{sentiment_label}</span>"
fig = go.Figure(go.Indicator(
mode="gauge+number",
value=score,
number={'valueformat': '.2f', 'font': {'size': 30}},
domain={'x': [0, 1], 'y': [0, 1]},
title={'text': title_text, 'font': {'size': 24}},
gauge={
'axis': {'range': [0, 1], 'tickwidth': 1, 'tickcolor': "darkblue"},
'bar': {'color': gauge_color},
'bgcolor': "white",
'borderwidth': 2,
'bordercolor': "#CCCCCC",
'steps': [
{'range': [0, 0.4], 'color': '#FFCDD2'}, # Light Red
{'range': [0.4, 0.6], 'color': '#FFF9C4'}, # Light Yellow
{'range': [0.6, 1], 'color': '#C8E6C9'} # Light Green
],
'threshold': {
'line': {'color': "gray", 'width': 4},
'thickness': 0.75,
'value': 0.5 # Neutral line
}
}
))
fig.update_layout(
height=300,
margin=dict(l=20, r=20, t=50, b=20)
)
return fig
def get_multi_modal_insight(text_emotion: str, speech_emotion: str) -> str:
"""
Compares the top text emotion and top speech emotion to provide a multi-modal insight.
"""
text_emotion = text_emotion.lower()
speech_emotion = speech_emotion.lower()
positive_emotions = ['joy', 'love', 'admiration', 'amusement', 'approval', 'caring', 'excitement', 'gratitude',
'optimism', 'relief']
negative_emotions = ['sadness', 'anger', 'annoyance', 'disappointment', 'disapproval', 'disgust', 'fear', 'grief',
'nervousness', 'remorse']
speech_map = {
'hap': 'joy',
'sad': 'sadness',
'ang': 'anger',
'neu': 'neutral',
'dis': 'disgust',
'fea': 'fear',
'sur': 'surprise'
}
speech_emotion = speech_map.get(speech_emotion, 'neutral')
if text_emotion in positive_emotions and speech_emotion in ['anger', 'sadness', 'disgust']:
return f"🚨 **High Conflict Detected:** The words are **{text_emotion.title()}**, but the tone of voice is **{speech_emotion.title()}**. This is a strong indicator of sarcasm or irony."
if text_emotion in negative_emotions and speech_emotion == 'joy':
return f"🚨 **High Conflict Detected:** The words are **{text_emotion.title()}**, but the tone of voice is **Joyful**. This could be sarcastic humor or schadenfreude."
if (text_emotion in positive_emotions and speech_emotion == 'joy') or \
(text_emotion in negative_emotions and speech_emotion in ['sadness', 'anger']):
return f"✅ **High Agreement:** Both the text (**{text_emotion.title()}**) and the tone (**{speech_emotion.title()}**) are aligned, indicating a genuine expression."
if speech_emotion == 'neutral' and text_emotion not in ['neutral', 'realization', 'confusion']:
return f"ℹ️ **Informative Tone:** The text expresses **{text_emotion.title()}**, but the tone of voice is **Neutral**. This often happens when someone is stating a fact or reading a review."
if text_emotion == 'neutral' and speech_emotion != 'neutral':
return f"ℹ️ **Tonal Emphasis:** The words are neutral, but the tone of voice is **{speech_emotion.title()}**. The *how* it's being said is more important than *what* is being said."
return f"**Text Emotion:** {text_emotion.title()}, **Speech Emotion:** {speech_emotion.title()}. The emotional read is mixed."
def show_new_results(result: Dict, aspects: List[Dict] = None, speech_emotion_results: Dict = None):
"""
Display analysis results in a clean one-page layout.
"""
# --- PATCH: defensive validation to avoid None / malformed result access ---
if result is None:
st.error("No analysis result to display.")
return
if not isinstance(result, dict):
st.error(f"Invalid analysis result format: expected dict but got {type(result).__name__}")
return
if 'text' not in result:
st.error("Invalid analysis result: missing key 'text'. Cannot display results.")
return
# Additional required keys check to avoid later KeyErrors
required_keys = [
'combined_score', 'final_sentiment', 'emotions', 'word_count', 'confidence',
'bert_label', 'bert_score', 'vader_compound', 'vader_pos', 'vader_neg', 'vader_neu'
]
missing_keys = [k for k in required_keys if k not in result]
if missing_keys:
st.error(f"Invalid analysis result: missing keys {missing_keys}. Cannot display results.")
# Print the result for debugging in server logs
print("DEBUG: Malformed analysis result returned:", repr(result))
return
# --- end PATCH ---
if aspects is None:
with st.spinner("Extracting aspects..."):
aspects = extract_aspects(
result['text'],
nlp_model,
bert_analyzer,
vader_analyzer,
emotion_pipeline_all,
sarcasm_pipeline
)
st.markdown("---")
st.markdown("### 📊 Analysis Results")
# --- CARD 1: SENTIMENT GAUGE ---
with st.container(border=True):
st.subheader("📈 Hybrid Sentiment Score")
try:
fig_gauge = create_sentiment_gauge(result['combined_score'], result['final_sentiment'])
st.plotly_chart(fig_gauge, use_container_width=True)
except Exception as e:
st.error(f"Could not generate sentiment gauge: {e}")
st.markdown(f"""
<div class="sentiment-card">
<div class="sentiment-score">{result['combined_score']:.2f}</div>
<div class="sentiment-label">{result['final_sentiment']}</div>
</div>
""", unsafe_allow_html=True)
# --- NEW CARD: MULTI-MODAL INSIGHT ---
# Check that it's a dictionary AND not empty
if isinstance(speech_emotion_results, dict) and speech_emotion_results:
with st.container(border=True):
st.subheader("🤖 Multi-Modal Insight")
try:
# Add a check for text emotions too
if result.get('emotions') and speech_emotion_results:
top_text_emotion = \
sorted(result['emotions'].items(), key=lambda item: item[1], reverse=True)[0][0]
top_speech_emotion = \
sorted(speech_emotion_results.items(), key=lambda item: item[1], reverse=True)[0][0]
insight = get_multi_modal_insight(top_text_emotion, top_speech_emotion)
st.markdown(insight)
else:
st.info("Could not generate multi-modal insight (no text or speech emotions found).")
except Exception as e:
st.error(f"Could not generate multi-modal insight: {e}")
# --- CARD 3: TEXT EMOTION ANALYSIS ---
with st.container(border=True):
st.subheader("😊 Text Emotion Analysis (from Words)")
try:
sorted_emotions = sorted(result['emotions'].items(), key=lambda item: item[1], reverse=True)
top_7_emotions = dict(sorted_emotions[:7])
if top_7_emotions:
df_emotions = pd.DataFrame(top_7_emotions.items(), columns=['Emotion', 'Score (%)'])
fig = px.bar(df_emotions, x='Emotion', y='Score (%)', color='Emotion',
title="Detected Emotions (Top 7)", text='Score (%)')
fig.update_traces(texttemplate='%{text:.0f}%', textposition='outside')
fig.update_layout(uniformtext_minsize=8, uniformtext_mode='hide', showlegend=False, margin=dict(t=50))
st.plotly_chart(fig, use_container_width=True)
else:
st.info("No emotions detected.")
except Exception as e:
st.error(f"Could not generate text emotion chart: {e}")
st.write(result['emotions'])
# --- CARD 4: SPEECH EMOTION ANALYSIS ---
if speech_emotion_results:
with st.container(border=True):
st.subheader("🗣 Speech Emotion Analysis (from Audio Tone)")
try:
speech_emotion_data_raw = {label.title(): score for label, score in speech_emotion_results.items() if
score > 1}
sorted_speech_emotions = sorted(speech_emotion_data_raw.items(), key=lambda item: item[1],
reverse=True)[:7]
if sorted_speech_emotions:
df_speech_emotions = pd.DataFrame(sorted_speech_emotions, columns=['Emotion', 'Score (%)'])
fig_speech = px.bar(df_speech_emotions, x='Emotion', y='Score (%)', color='Emotion',
title="Detected Emotions from Voice Tone (Top 7)", text='Score (%)')
fig_speech.update_traces(texttemplate='%{text:.0f}%', textposition='outside')
fig_speech.update_layout(uniformtext_minsize=8, uniformtext_mode='hide', showlegend=False,
margin=dict(t=50))
st.plotly_chart(fig_speech, use_container_width=True)
else:
st.info("No strong speech emotions detected.")
except Exception as e:
st.error(f"Could not generate speech emotion chart: {e}")
st.write(speech_emotion_results)
# --- CARD 5: ASPECT-BASED SENTIMENT ---
with st.container(border=True):
st.subheader("🎯 Aspect-Based Sentiment")
if not aspects:
st.info("No specific aspects were detected in the text.")
else:
sentiment_emoji = {'POSITIVE': '😊', 'NEGATIVE': '😞', 'NEUTRAL': '😐'}
for aspect in aspects:
sentiment_class = f"aspect-{aspect['sentiment'].lower()}"
st.markdown(f"""
<div class="aspect-card {sentiment_class}">
<strong>📌 {aspect['aspect'].title()}</strong><br>
Sentiment: {sentiment_emoji.get(aspect['sentiment'], '😐')} {aspect['sentiment']} (Score: {aspect['score']:.2f})<br>
<em>Context: "{aspect['context'][:100]}..."</em>
</div>
""", unsafe_allow_html=True)
st.write("")
# --- CARD 6: DETAILED BREAKDOWN ---
with st.container(border=True):
st.subheader("🔍 Detailed Breakdown")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Word Count", result['word_count'])
st.metric("Confidence", f"{result['confidence']:.2%}")
sarcasm_score = result.get('sarcasm_score', 0)
# --- NEW LOGIC FOR TEXT LABEL ---
# ... inside show_new_results (Card 6) ...
sarcasm_score = result.get('sarcasm_score', 0)
# Determine Label and Color
if sarcasm_score > 0.5:
sarcasm_label = "Sarcasm Detected"
sarcasm_color = "inverse" # Red arrow/text indicating 'bad'
else:
sarcasm_label = "No Sarcasm Detected"
sarcasm_color = "off" # Grey text indicating 'neutral'
# Use 'delta' to show the label below the number
st.metric(
label="Sarcasm Score",
value=f"{sarcasm_score:.1%}",
delta=sarcasm_label,
delta_color=sarcasm_color
)
# Keep the warning
if sarcasm_score > 0.6:
st.warning("High sarcasm detected! Sentiment may be ironic.")
with col2:
st.markdown("*RoBERTa Analysis (80%)*")
# --- We still display the original, uncorrected label (e.g., 'neutral') for transparency ---
st.write(f"- Label: {result['bert_label']}")
# --- NEW FIX: We use the FINAL_SENTIMENT for the color coding and bold text ---
final_sent = result['final_sentiment']
if final_sent == 'POSITIVE':
st.markdown(f"- Sentiment: <span style='color:#4CAF50; font-weight:bold;'>{final_sent}</span>",
unsafe_allow_html=True)
elif final_sent == 'NEGATIVE':
st.markdown(f"- Sentiment: <span style='color:#F44336; font-weight:bold;'>{final_sent}</span>",
unsafe_allow_html=True)
else: # NEUTRAL
st.markdown(f"- Sentiment: <span style='color:#FBBC05; font-weight:bold;'>{final_sent}</span>",
unsafe_allow_html=True)
st.write(f"- Confidence: {result['bert_score']:.2%}")
with col3:
st.markdown("*VADER Analysis (20%)*")
st.write(f"- Compound: {result['vader_compound']:.3f}")
st.write(f"- Positive: {result['vader_pos']:.2%}")
st.write(f"- Negative: {result['vader_neg']:.2%}")
st.write(f"- Neutral: {result['vader_neu']:.2%}")
def save_to_history(result: Dict):
"""Save to history"""
if result:
st.session_state.history.append(result)
# ----------------------------
# Sidebar
# ----------------------------
with st.sidebar:
st.markdown("### Dashboard")
st.markdown("Advanced Sentiment Analysis")
st.markdown("---")
st.radio(
"Navigation",
["🏠 Home", "📝 Analyzer", "🎬 File Analysis", "📚 History", "ℹ️ About"],
key="page",
label_visibility="collapsed"
)
st.markdown("---")
st.markdown("### 📊 Quick Stats")
st.metric("📊 Total Analyses", len(st.session_state.history))
if st.session_state.history:
avg_score = np.mean([h['combined_score'] for h in st.session_state.history])
st.metric("📈 Avg Score", f"{avg_score:.2f}")
st.markdown("---")
st.caption("Built with RoBERTa + VADER • SpaCy")
# ----------------------------
# Pages
# ----------------------------
if st.session_state.page == "🏠 Home":
st.markdown('<div class="hero-title">Sentiment Analysis Platform</div>', unsafe_allow_html=True)
st.markdown('<div class="hero-subtitle">Advanced Multi-Modal Sentiment Analysis</div>', unsafe_allow_html=True)
st.markdown("""
<div class="feature-badges">
<span class="badge">🤖 RoBERTa + VADER</span>
<span class="badge">🎬 Video Analysis</span>
<span class="badge">🎵 Audio Analysis</span>
<span class="badge">🌐 Webpage Analysis</span>
<span class="badge">🧐 Sarcasm Detection</span>
<span class="badge">🗣️ Speech Emotion</span>
</div>
""", unsafe_allow_html=True)
st.markdown("---")
col1, col2 = st.columns(2)
with col1:
st.button("📝 Text Analysis", on_click=set_page, args=["📝 Analyzer"], use_container_width=True)
st.markdown("<p style='text-align:center;'>Dual-model AI sentiment detection</p>", unsafe_allow_html=True)
with col2:
st.button("🎬 File Analysis", on_click=set_page, args=["🎬 File Analysis"], use_container_width=True)
st.markdown("<p style='text-align:center;'>Transcribe video & audio files</p>", unsafe_allow_html=True)
st.info("👉 Navigate to any section to start analyzing!")
elif st.session_state.page == "📝 Analyzer":
st.markdown("## 📝 Advanced Sentiment Analyzer")
# --- RE-ADDED THE "Voice" TAB ---
tab1, tab2, tab3 = st.tabs(["📝 Text", "🎤 Voice", "🌐 URL"])
with tab1:
st.markdown("### Text Analysis")
# --- NEW: Wrap in a Form ---
with st.form(key="text_analysis_form"):
text_input = st.text_area("Enter text", height=200, key="text_analysis_input",
placeholder="Type or paste your text here... (Press Ctrl+Enter to analyze)")
col_left, col_center, col_right = st.columns([1, 2, 1])
with col_center:
submit_button = st.form_submit_button("🚀 Analyze Text", use_container_width=True)
# Logic executes when form is submitted (Enter key or Click)
if submit_button:
if text_input.strip():
with st.spinner("🔄 Analyzing..."):
result = analyze_text_comprehensive(text_input, bert_analyzer, vader_analyzer,
emotion_pipeline_all, sarcasm_pipeline)
if result:
st.success("✅ Complete!")
show_new_results(result, aspects=None, speech_emotion_results=None)
save_to_history(result)
else:
st.warning("⚠️ Please enter some text")
# Example button (Outside form to prevent conflict)
if st.button("💡 Example", use_container_width=True, key="example_btn"):
st.info("Example: 'I love this product! It's amazing and exceeded my expectations.'")
# --- RE-ADDED THE "Voice" TAB CONTENT ---
with tab2:
st.markdown("### 🎤 Voice Recording")
try:
import pyaudio
pyaudio_available = True
except ImportError:
pyaudio_available = False
if not pyaudio_available:
st.warning("⚠️ *PyAudio not installed.* This is required for microphone access.")
st.info(
"Install PyAudio with: pip install pyaudio")
else:
st.info("🎤 Click to record your voice")
if st.button("🎙️ Start Recording", use_container_width=True, key="record_btn"):
with st.spinner("Initializing...") as spinner:
transcript = recognize_speech(spinner, whisper_model)
# --- PATCH: debug print so server console shows the raw transcript result ---
try:
print("DEBUG: recognize_speech returned (repr):", repr(transcript))
except Exception:
pass
# --- end PATCH ---
# --- PATCH: safe check to avoid NoneType.startswith crash ---
if isinstance(transcript, str) and not transcript.startswith("❌"):
st.success(f"✅ Transcribed: {transcript}")
with st.spinner("🔄 Analyzing..."):
result = analyze_text_comprehensive(transcript, bert_analyzer, vader_analyzer,
emotion_pipeline_all, sarcasm_pipeline)
if result:
# Note: We can't do speech emotion here since we only saved the transcript, not the audio file.
# This is a limitation of the current quick record feature.
show_new_results(result)
save_to_history(result)
else:
# If not a string, show a clearer message
if transcript is None:
st.error(
"❌ Transcription returned None (no audio captured). Try again or check microphone permissions.")
elif isinstance(transcript, str):
st.error(transcript) # an error string like "❌ ..."
else:
st.error(
f"❌ Unexpected transcription result type: {type(transcript).__name__}. See server logs.")
with tab3:
st.markdown("### 🌐 Webpage Analysis")
url_input = st.text_input("Enter a URL to scrape and analyze",
placeholder="e.g., a news article or blog post URL")
if st.button("🌐 Analyze URL", use_container_width=True, key="url_btn"):
if url_input.strip():
scraped_text = ""
with st.spinner(f"Scraping text from {url_input}..."):
scraped_text = scrape_webpage_text(url_input)
if scraped_text.startswith("❌"):
st.error(scraped_text)
else:
st.success("✅ Scraping complete!")
with st.expander("View Scraped Text"):
st.text_area("Scraped Text", scraped_text, height=150, key="url_transcript",
label_visibility="hidden")
with st.spinner("🔄 Analyzing text..."):
result = analyze_text_comprehensive(scraped_text, bert_analyzer, vader_analyzer,
emotion_pipeline_all, sarcasm_pipeline)
if result:
st.success("✅ Analysis Complete!")
show_new_results(result, aspects=None, speech_emotion_results=None)
save_to_history(result)
else:
st.error("Could not analyze the scraped text.")
else:
st.warning("⚠️ Please enter a URL")
elif st.session_state.page == "🎬 File Analysis":
st.markdown("## 🎬 File Analysis (Video/Audio)")
tab1, tab2, tab3 = st.tabs(["🎬 Upload Video", "🎵 Upload Audio", "🔗 YouTube URL"])
with tab1:
st.success("✅ *Recommended* - Upload your video file directly")
uploaded_video = st.file_uploader(
"Choose a video file",
type=['mp4', 'mov', 'avi', 'mkv', 'webm'],
key="video_uploader"
)
if uploaded_video:
col1, col2 = st.columns(2)
with col1:
st.video(uploaded_video)
with col2:
st.info(f"*File:* {uploaded_video.name}")
st.info(f"*Size:* {uploaded_video.size / (1024 * 1024):.2f} MB")
analyze_button_pressed = st.button("🎬 Analyze Video", use_container_width=True, key="analyze_video_btn")
if analyze_button_pressed:
try:
os.makedirs("temp_files", exist_ok=True)
tmp_path = os.path.join("temp_files", f"video_{int(time.time())}.mp4")
with st.spinner("💾 Processing..."):
with open(tmp_path, "wb") as f:
f.write(uploaded_video.read())
audio_path = "" # Initialize
with st.spinner("🎵 Extracting audio..."):
audio_path = extract_audio_from_video(tmp_path)
if audio_path:
st.success("✅ Audio extracted")
st.audio(audio_path)
else:
st.error("Audio extraction failed. Cannot proceed.")
if os.path.exists(tmp_path): os.remove(tmp_path)
st.stop()
transcript = "" # Initialize
with st.spinner("📝 Transcribing with Whisper..."):
transcript = transcribe_audio(audio_path, whisper_model)
# --- PATCH: safe check usage here too ---
if isinstance(transcript, str) and not transcript.startswith("❌"):
st.success("✅ Transcription complete!")
with st.expander("📄 Transcript", expanded=True):
st.text_area("Transcript", transcript, height=200, key="transcript_display",
label_visibility="hidden")
st.download_button(
"💾 Download",
transcript,
f"transcript_{int(time.time())}.txt",
key="download_transcript"
)
with st.spinner("🔄 Analyzing Text & Speech..."):
result = analyze_text_comprehensive(transcript, bert_analyzer, vader_analyzer,
emotion_pipeline_all, sarcasm_pipeline)
speech_emotions = analyze_speech_emotion(audio_path, ser_pipeline)
if result:
st.success("✅ Analysis complete!")
show_new_results(result, aspects=None, speech_emotion_results=speech_emotions)
save_to_history(result)
st.toast('Analysis complete!', icon='✅')
else:
st.error("Could not analyze the transcribed text.")
else:
st.error(transcript if isinstance(transcript,
str) else "❌ Error: Transcription returned unexpected type.")
# --- END PATCH ---
# Cleanup
for f in [tmp_path, audio_path]:
if f and os.path.exists(f):
os.remove(f)
except Exception as e:
st.error(f"❌ Error: {str(e)}")
with tab2:
st.info("Upload an audio file (.mp3, .wav, .m4a) to transcribe and analyze.")
uploaded_audio = st.file_uploader(
"Choose an audio file",
type=['mp3', 'wav', 'm4a'],
key="audio_uploader"
)
if uploaded_audio:
st.audio(uploaded_audio)
analyze_button_pressed = st.button("🎵 Analyze Audio", use_container_width=True, key="analyze_audio_btn")
if analyze_button_pressed:
try:
os.makedirs("temp_files", exist_ok=True)
tmp_path = os.path.join("temp_files", uploaded_audio.name)
with st.spinner("💾 Processing..."):
with open(tmp_path, "wb") as f:
f.write(uploaded_audio.read())
transcript = ""
with st.spinner("📝 Transcribing with Whisper..."):
transcript = transcribe_audio(tmp_path, whisper_model)
# --- PATCH: safe check usage here too ---
if isinstance(transcript, str) and not transcript.startswith("❌"):
st.success("✅ Transcription complete!")
with st.expander("📄 Transcript", expanded=True):
st.text_area("Transcript", transcript, height=200, key="transcript_display_audio",
label_visibility="hidden")
st.download_button(
"💾 Download",
transcript,
f"transcript_{int(time.time())}.txt",
key="download_transcript_audio"
)
with st.spinner("🔄 Analyzing Text & Speech..."):
result = analyze_text_comprehensive(transcript, bert_analyzer, vader_analyzer,
emotion_pipeline_all, sarcasm_pipeline)
speech_emotions = analyze_speech_emotion(tmp_path, ser_pipeline)
if result:
st.success("✅ Analysis complete!")
show_new_results(result, aspects=None, speech_emotion_results=speech_emotions)
save_to_history(result)
st.toast('Analysis complete!', icon='✅')
else:
st.error("Could not analyze the transcribed text.")
else:
st.error(transcript if isinstance(transcript,
str) else "❌ Error: Transcription returned unexpected type.")
# Cleanup
if os.path.exists(tmp_path):
os.remove(tmp_path)
# --- END PATCH ---
except Exception as e:
st.error(f"❌ Error: {str(e)}")
# REPLACE lines 777-898 in app.py with this:
with tab3:
st.info("🔗 YouTube: download audio, transcribe, and analyze.")
youtube_url = st.text_input("YouTube URL", placeholder="https://www.youtube.com/watch?v=...", key="yt_url_main")
prefer_ext = st.selectbox("Audio format", ["m4a", "mp3"], index=0, key="yt_format_select")
if youtube_url.strip():
with st.spinner("Fetching video metadata..."):
meta = fetch_youtube_metadata(youtube_url)
if meta:
st.markdown(
f"**Title:** {meta.get('title')} \n**Uploader:** {meta.get('uploader')} \n**Duration (s):** {meta.get('duration')}")
if meta.get('thumbnail'):
st.image(meta.get('thumbnail'), width=240)
else:
st.warning("Could not fetch metadata; proceeding anyway.")
if st.button("📥 Download & Analyze", use_container_width=True, key="yt_download_btn"):
if not youtube_url.strip():
st.warning("Please enter a YouTube URL first.")
else:
audio_path = ""
with st.spinner(f"Downloading audio as .{prefer_ext}... (This can take a while)"):
audio_path = download_youtube_audio_simple(youtube_url, prefer_ext=prefer_ext)
if isinstance(audio_path, str) and audio_path.startswith("❌"):
st.error(audio_path)
elif not audio_path or not os.path.exists(audio_path):
st.error("❌ Download failed. File path not found.")
else:
st.success("✅ Audio downloaded successfully.")
st.audio(audio_path)
# Define a temp path for the converted WAV
# Use a timestamp to avoid conflicts
wav_path = os.path.join("temp_files", f"yt_audio_{int(time.time())}.wav")
with st.spinner("Converting audio to WAV..."):
conv_result = convert_to_wav_16k_mono(audio_path, wav_path)
if isinstance(conv_result, str) and conv_result.startswith("❌"):
st.error(conv_result)
else:
# Transcribe the WAV file
with st.spinner("Transcribing with Whisper..."):
transcript = transcribe_audio(wav_path, whisper_model)
if isinstance(transcript, str) and not transcript.startswith("❌"):
st.success("✅ Transcription complete")
with st.expander("Transcript", expanded=True):
st.text_area("Transcript", transcript, height=200, key="yt_transcript_area")
st.download_button("Download transcript", transcript, "transcript.txt",
key="yt_download_txt")
# Analyze
with st.spinner("Analyzing text and speech..."):
result = analyze_text_comprehensive(transcript, bert_analyzer, vader_analyzer,
emotion_pipeline_all, sarcasm_pipeline)
speech_emotions = analyze_speech_emotion(wav_path, ser_pipeline)
if result:
show_new_results(result, aspects=None, speech_emotion_results=speech_emotions)
save_to_history(result)
else:
st.error("❌ Analysis failed. See server logs.")
else:
st.error(transcript if isinstance(transcript, str) else "❌ Transcription failed.")
# Cleanup both temp files
try:
if os.path.exists(audio_path):
os.remove(audio_path)
if os.path.exists(wav_path):
os.remove(wav_path)
except Exception as e:
print(f"Error during cleanup: {e}")
st.warning("Could not clean up temporary audio files.")
elif st.session_state.page == "🤖 Chatbot":
st.markdown("### Emotion & Sentiment Feedback")
st.info("Enter a message to analyze its emotional tone and sentiment score.")
# Display chat history
for message in st.session_state.chat_history:
role = message.get("role", "user")
content = message.get("content", "")
if role == "user":
st.markdown(f'<div class="chat-message user-message">👤 {content}</div>', unsafe_allow_html=True)
else:
st.markdown(f'<div class="chat-message bot-message">🤖 {content}</div>', unsafe_allow_html=True)
# Chat input
user_input = st.text_input("Your message:", key="chatbot_input",
placeholder="Type Here...")
if st.button("Send", use_container_width=True, key="send_chat"):
if user_input.strip():
# Add user message to history
st.session_state.chat_history.append({"role": "user", "content": user_input})
# Get bot response
with st.spinner("Thinking..."):
bot_reply = chatbot_response(user_input, bert_analyzer, vader_analyzer, emotion_pipeline)
# Add bot response to history
st.session_state.chat_history.append({"role": "assistant", "content": bot_reply})
st.rerun()
elif st.session_state.page == "📚 History":
st.markdown("### 📚 Analysis History")
if not st.session_state.history:
st.info("No analyses yet. Start analyzing to build your history!")
else:
# --- NEW CODE START: ACCURACY/CONFIDENCE CHART ---
st.markdown("### 📈 Model Confidence Trend")
st.caption("This chart shows how confident the AI was in its predictions over time.")
# Prepare data for the chart
history_df = pd.DataFrame(st.session_state.history)
# Create a Line/Area chart for Confidence
if 'confidence' in history_df.columns:
# Add an index for the X-axis (1, 2, 3...)
history_df['Analysis #'] = range(1, len(history_df) + 1)
fig_conf = px.area(
history_df,
x='Analysis #',
y='confidence',
title='Confidence Score per Analysis',
labels={'confidence': 'Confidence (0-1)'},
markers=True,
color_discrete_sequence=["#A79BFF"] # Your purple theme color
)
# Fix the Y-axis range from 0 to 1 (0% to 100%)
fig_conf.update_layout(yaxis_range=[0, 1.1])