-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1384 lines (1150 loc) Β· 53.9 KB
/
app.py
File metadata and controls
1384 lines (1150 loc) Β· 53.9 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 plotly.express as px
import plotly.graph_objects as go
import plotly.figure_factory as ff
from plotly.subplots import make_subplots
import json
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import re
import numpy as np
st.set_page_config(
page_title="The Language of Rejection",
page_icon="π",
layout="wide",
initial_sidebar_state="expanded"
)
@st.cache_data
def load_data():
df = pd.read_csv('data/rejection_analysis_extended.csv')
df_clean = df[df['status'] != 'ghosted'].copy()
with open('data/shap_results_all.json', 'r') as f:
shap_data = json.load(f)
return df_clean, shap_data
df, shap_results = load_data()
vader = SentimentIntensityAnalyzer()
@st.cache_data
def process_all_shap():
"""Extract all words with their impacts across companies"""
all_negative = []
all_positive = []
for company, data in shap_results.items():
for word, score in data['words']:
if score < 0:
all_negative.append({
'word': word,
'score': score,
'company': company,
'vader': data['vader'],
'roberta': data['roberta']
})
else:
all_positive.append({
'word': word,
'score': score,
'company': company,
'vader': data['vader'],
'roberta': data['roberta']
})
df_neg = pd.DataFrame(all_negative)
df_pos = pd.DataFrame(all_positive)
return df_neg, df_pos
df_negative, df_positive = process_all_shap()
def analyze_text(text):
"""Analyze email text"""
score = vader.polarity_scores(text)['compound']
words = text.lower().split()
joy_keywords = ['hope', 'happy', 'good', 'luck', 'best', 'wish', 'encourage']
apology_keywords = ['sorry', 'unfortunately', 'regret', 'apologies', 'apologize']
positive_keywords = ['thank', 'appreciate', 'grateful', 'impressed', 'value',
'strong', 'excellent', 'great', 'pleased', 'interested']
joy_count = sum(1 for w in words if any(j in w for j in joy_keywords))
apology_count = sum(1 for w in words if any(a in w for a in apology_keywords))
positive_count = sum(1 for w in words if any(p in w for p in positive_keywords))
return {
'score': score,
'joy': joy_count,
'apology': apology_count,
'positive': positive_count,
'word_count': len(words)
}
st.sidebar.title("π Navigation")
if "page" not in st.session_state:
st.session_state.page = "π The Story"
pages = ["π The Story", "π The Data", "π¬ Deep Dive: SHAP", "π§ͺ Try It Yourself"]
for page in pages:
if st.session_state.page == page:
st.sidebar.button(
f"β
{page}",
use_container_width=True,
disabled=True,
type="primary"
)
else:
if st.sidebar.button(page, use_container_width=True):
st.session_state.page = page
st.rerun()
st.sidebar.markdown("---")
st.sidebar.markdown("### π Quick Stats")
st.sidebar.metric("Emails Analyzed", "14")
st.sidebar.metric("Joy Factor", "+0.605")
st.sidebar.metric("The Magic Ratio", "4:1")
st.sidebar.markdown("---")
st.sidebar.markdown("[GitHub](https://github.com/jgchoti/job_rejection_analysis) | [LinkedIn](https://www.linkedin.com/in/chotirat/)")
if st.session_state.page == "π The Story":
st.title("π The Language of Rejection")
st.markdown("### What makes some rejection emails feel warm while others feel crushing?")
st.markdown("---")
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
st.image("assets/ophelia.jpg", caption="*Ophelia* (1851β52) β Sir John Everett Millais",)
# Introduction
st.markdown("""
<div style="background-color: #FEF3E5; padding: 25px; border-radius: 12px; border-left: 6px solid #CC7C60;">
<h2>π How This Started</h2>
<p style="font-size: 1.1rem; line-height: 1.8;">
After receiving many job rejection, something clicked. Instead of feeling frustrated,
I got curious: <b>could I quantify what makes a rejection feel "warm" or "cold"?</b>
</p>
<p style="font-size: 1.1rem; line-height: 1.8;">
I collected all rejection emails (2024-2025), anonymized them, and analyzed them using
Natural Language Processing(NLP).
</p>
<p style="font-size: 1rem; margin-top: 10px;">
For the full code, visit my <a href="https://github.com/jgchoti/job_rejection_analysis" target="_blank" >GitHub repository</a>.
</p>
</div>
""", unsafe_allow_html=True)
st.markdown("---")
st.markdown("")
st.markdown("### π§ The Tale of Two Emails")
col1, col2 = st.columns(2)
with col1:
st.markdown("""
<div style="background-color: #ffebee; padding: 20px; border-radius: 10px; border-left: 5px solid #e53935;">
<h4 style="color: #c62828; margin-top: 0;">β The Coldest Email (0.307)</h4>
<ul style="font-size: 1rem; line-height: 1.6;">
<li>20 words total</li>
<li>2 apologies</li>
<li>2 positive words</li>
<li>0 joy words</li>
</ul>
<p style="font-style: italic; color: #666; margin-bottom: 0;">
"Thanks... Unfortunately... We're sorry..."
</p>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown("""
<div style="background-color: #e8f5e9; padding: 20px; border-radius: 10px; border-left: 5px solid #43a047;">
<h4 style="color: #2e7d32; margin-top: 0;">β
The Warmest Email (0.990)</h4>
<ul style="font-size: 1rem; line-height: 1.6;">
<li>88 words total</li>
<li>0 apologies</li>
<li>17 positive words</li>
<li>2 joy words</li>
</ul>
<p style="font-style: italic; color: #666; margin-bottom: 0;">
"We were impressed... We wish you the best..."
</p>
</div>
""", unsafe_allow_html=True)
st.write("")
st.warning("""***The difference?*** 68 words.
Completely different emotional impact.
""")
# Key Findings
st.markdown("### π What I Discovered")
finding_col1, finding_col2, finding_col3 = st.columns(3)
with finding_col1:
st.markdown("""
<div style="background-color: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); height: 100%;">
<h3 style="color: #3498db; margin-top: 0;">π Finding #1</h3>
<h4>Joy Words Win</h4>
<p style="font-size: 0.95rem; line-height: 1.6;">
Words like "hope," "wish," and "best" correlate <b>+0.605</b> with warmth.
That's 3Γ stronger than any other factor.
</p>
<p style="font-size: 0.9rem; color: #7f8c8d; margin-bottom: 0;">
<i>The warmest emails average 2 joy words. The coldest? Zero.</i>
</p>
</div>
""", unsafe_allow_html=True)
with finding_col2:
st.markdown("""
<div style="background-color: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); height: 100%;">
<h3 style="color: #e74c3c; margin-top: 0;">βοΈ Finding #2</h3>
<h4>The 4:1 Rule</h4>
<p style="font-size: 0.95rem; line-height: 1.6;">
Each apology ("sorry," "unfortunately") needs <b>at least 4 positive words</b>
to maintain warmth.
</p>
<p style="font-size: 0.9rem; color: #7f8c8d; margin-bottom: 0;">
<i>Below 4:1 = guaranteed cold. Above 6:1 = safe zone.</i>
</p>
</div>
""", unsafe_allow_html=True)
with finding_col3:
st.markdown("""
<div style="background-color: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); height: 100%;">
<h3 style="color: #9b59b6; margin-top: 0;">π§ͺ Finding #3</h3>
<h4>Context Matters</h4>
<p style="font-size: 0.95rem; line-height: 1.6;">
Transformers detect <b>empty politeness </b> that simple word-counting overlook.
</p>
<p style="font-size: 0.9rem; color: #7f8c8d; margin-bottom: 0;">
<i>Some emails score 0.97 (lexicon) but -0.17 (transformer).</i>
</p>
</div>
""", unsafe_allow_html=True)
st.markdown("---")
# Why It Matters
st.markdown("""
<div style="background-color: #FEF3E5; padding: 25px; border-radius: 12px; border-left: 6px solid #CC7C60;">
<h2>π‘ Why This Matters</h2>
<div style="font-size: 1.05rem; line-height: 1.8; color: #212121;">
<p><b>For job seekers like me:</b> That sinking feeling after a cold rejection?
It's not personal. It's just a bad template. Some companies accidentally crush spirits.
Others lift them. Neither is intentional.</p>
<p><b>For business:</b> Small improvements to templatesβlike warm language and clear next stepsβarenβt just nice. With AI reading emails first, setting the right tone helps algorithms recognize your intent as positive, influencing how messages are categorized and analyzed. Same automation. Different outcomes.</p>
<p style="margin-bottom: 0;"><b>The bigger point:</b> Rejection is unavoidable in hiring.
Cruelty is optional.</p>
</div>
</div>
""", unsafe_allow_html=True)
st.markdown("---")
st.markdown("π **Explore the data in the next section to see exactly how I measured this.**")
if st.button("Next β π The Data"):
st.session_state.page = "π The Data"
st.rerun()
elif st.session_state.page == "π The Data":
st.title("π The Data Behind the Story")
st.markdown("### Let's look at the numbers that prove these patterns are real")
st.markdown("---")
# Overview metrics
st.markdown("## π Dataset Overview")
metric_col1, metric_col2, metric_col3, metric_col4 = st.columns(4)
with metric_col1:
st.metric("Total Emails", "14", help="Real rejection emails from 2024-2025 job search")
with metric_col2:
st.metric("Warmest Score", "0.990", delta="+0.68 vs coldest")
with metric_col3:
st.metric("Coldest Score", "0.307", delta="-0.68 vs warmest", delta_color="inverse")
with metric_col4:
st.metric("Average Score", f"{df['vader_compound'].mean():.3f}")
st.markdown("---")
# Finding #1: Joy Factor
st.markdown("## π Finding #1: The Joy Factor")
st.markdown("""
**The Question:** Which emotions predict warmth best?
**The Answer:** Joy-based words correlate **+0.605** with warmth. That's:
- 5Γ stronger than trust (+0.116)
- 10Γ stronger than anticipation (+0.057)
""")
with st.expander("### π₯ Emotion-Sentiment Heatmap", expanded=False):
st.markdown("### π₯ Emotion-Sentiment Heatmap: Which Models Respond to Which Emotions?")
st.markdown("""
This heatmap reveals a critical insight: **lexicon-based models** (VADER, AFINN, TextBlob)
respond strongly to joy, while **transformers** (RoBERTa, SST-2) are less influenced by simple emotion counts.
""")
emotion_cols = ['emotion_joy', 'emotion_trust', 'emotion_anticipation', 'emotion_sadness', 'emotion_fear', 'emotion_anger']
emotion_names = ['Joy', 'Trust', 'Anticipation', 'Sadness', 'Fear', 'Anger']
model_cols = ['vader_compound', 'hf_roberta_score', 'textblob_polarity','afinn_score', 'hf_sst2_score']
model_names = ['VADER', 'RoBERTa', 'TextBlob', 'AFINN', 'SST-2']
# Calculate correlation matrix (emotions Γ models)
corr_matrix = np.zeros((len(emotion_cols), len(model_cols)))
for i, emotion in enumerate(emotion_cols):
for j, model in enumerate(model_cols):
corr_matrix[i, j] = df[emotion].corr(df[model])
# Create heatmap
fig3 = go.Figure(data=go.Heatmap(
z=corr_matrix,
x=model_names,
y=emotion_names,
colorscale='RdYlGn',
zmid=0,
text=np.round(corr_matrix, 3),
texttemplate='%{text}',
textfont={"size": 13, "color": "black"},
colorbar=dict(
title='Correlation<br>Strength',
thickness=20,
len=0.7
),
hovertemplate='<b>%{y} β %{x}</b><br>Correlation: %{z:.3f}<extra></extra>'
))
# Highlight Joy-VADER (strongest)
fig3.add_shape(
type='rect',
x0=-0.5, x1=0.5,
y0=-0.5, y1=0.5,
line=dict(color='#2ecc71', width=4)
)
# Highlight Joy row
fig3.add_shape(
type='rect',
x0=-0.5, x1=4.5,
y0=-0.5, y1=0.5,
line=dict(color='#3498db', width=2, dash='dash')
)
fig3.update_layout(
title='How Each Model Responds to Different Emotions',
xaxis_title='Sentiment Model',
yaxis_title='Emotion Type',
template='plotly_white',
height=550,
xaxis={
'side': 'bottom',
'tickangle': 0
},
yaxis={
'autorange': 'reversed'
},
)
st.plotly_chart(fig3, use_container_width=True)
col1, col2 = st.columns(2)
with col1:
st.markdown("""
<div style="background-color: #e8f5e9; padding: 15px; border-radius: 10px; border-left: 4px solid #2ecc71;">
<h4 style="color: #1e8449; margin-top: 0;">π€ Lexicon Models (VADER, AFINN, TextBlob)</h4>
<ul style="font-size: 0.95rem;">
<li><b>Joy: +0.605</b> (very strong)</li>
<li><b>Trust: +0.116</b> (weak)</li>
<li><b>Anticipation: +0.057</b> (very weak)</li>
</ul>
<p style="margin-bottom: 0; font-size: 0.9rem;"><i>These models COUNT words, so joy words = high scores</i></p>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown("""
<div style="background-color: #eef2f7; padding: 15px; border-radius: 10px; border-left: 4px solid #3498db;">
<h4 style="color: #2874a6; margin-top: 0;">π§ Transformer Models (RoBERTa, SST-2)</h4>
<ul style="font-size: 0.95rem;">
<li><b>Joy: +0.38</b> (moderate)</li>
<li><b>Less emotion-driven</b></li>
<li><b>Focus on context/phrases</b></li>
</ul>
<p style="margin-bottom: 0; font-size: 0.9rem;"><i>These models understand rejection PATTERNS, not just word counts</i></p>
</div>
""", unsafe_allow_html=True)
st.markdown("")
fig1 = px.scatter(
df,
x='emotion_joy',
y='vader_compound',
size='afinn_positive_count',
color='vader_compound',
hover_data=['company_id', 'apology_words'],
title="Joy Words Strongly Predict Warmth",
labels={
'emotion_joy': 'Number of Joy Words (hope, wish, best, good luck, etc.)',
'vader_compound': 'Warmth Score',
'afinn_positive_count': 'Total Positive Words'
},
color_continuous_scale='RdYlGn',
height=500
)
fig1.update_traces(marker=dict(line=dict(width=1.5, color='white')))
fig1.update_layout(
template='plotly_white',
font=dict(size=12),
title_font_size=16
)
st.plotly_chart(fig1, use_container_width=True)
st.info("**π‘ Key Insight:** Emails with 2+ joy words score 0.95+. Emails with 0 joy words score below 0.50. The pattern is clear and consistent.")
st.markdown("### π All Emotions Compared")
st.markdown("Joy isn't the only emotion - let's see how all emotions correlate with warmth:")
corr_with_sentiment = []
for col in emotion_cols:
corr = df[col].corr(df['vader_compound'])
corr_with_sentiment.append(corr)
fig2 = go.Figure()
colors = ['#2ecc71' if c > 0.2 else '#95a5a6' for c in corr_with_sentiment]
fig2.add_trace(go.Bar(
x=emotion_names,
y=corr_with_sentiment,
marker_color=colors,
text=[f'{c:+.3f}' for c in corr_with_sentiment],
textposition='outside',
hovertemplate='<b>%{x}</b><br>Correlation: %{y:.3f}<extra></extra>'
))
# Highlight joy
fig2.add_annotation(
x='Joy',
y=corr_with_sentiment[0] + 0.1,
text='<b>5Γ stronger than<br>next best!</b>',
showarrow=True,
arrowhead=2,
arrowcolor='#2ecc71',
font=dict(color='#2ecc71', size=13),
bgcolor='#e8f5e9',
bordercolor='#2ecc71',
borderwidth=2
)
fig2.update_layout(
title='Emotion Correlation with Warmth Score',
xaxis_title='Emotion Type',
yaxis_title='Correlation with Warmth (r)',
template='plotly_white',
height=450,
showlegend=False
)
fig2.add_hline(y=0, line_color='gray', line_width=1)
st.plotly_chart(fig2, use_container_width=True)
st.info("""
**π The Verdict:**
Joy dominates with **+0.605 correlation** - that's:
- 5Γ stronger than trust (+0.116)
- 10Γ stronger than anticipation (+0.057)
- **3Γ stronger than ALL other emotions combined**
This isn't just one of many factors. Joy words are THE factor.
""")
st.markdown("---")
# Finding #2: The 4:1 Rule
st.markdown("## βοΈ Finding #2: The 4:1 Compensation Rule")
st.markdown("""
**The Question:** How many positive words are needed to balance one apology?
**The Answer:** At least **4 positive words per apology**. But the best strategy? **Zero apologies.**
""")
# Separate companies with/without apologies
df_with_apologies = df[df['apology_words'] > 0].copy()
df_no_apologies = df[df['apology_words'] == 0].copy()
# Calculate ratio for those with apologies
df_with_apologies['ratio'] = df_with_apologies['afinn_positive_count'] / df_with_apologies['apology_words']
df_with_apologies['zone'] = pd.cut(
df_with_apologies['ratio'],
bins=[0, 3, 6, 20],
labels=['β Danger (<4:1)', 'β οΈ Minimum (4-6:1)', 'β
Safe (6:1+)']
)
# Show info box about zero-apology companies
if len(df_no_apologies) > 0:
companies_list = ', '.join(df_no_apologies['company_id'].tolist())
avg_score = df_no_apologies['vader_compound'].mean()
st.info(f"""
**π The Ultimate Strategy: {len(df_no_apologies)} companies avoided apologies entirely:**
**{companies_list}**
- Average warmth score: **{avg_score:.3f}** (highest group!)
- No compensation needed - they never triggered the 4:1 rule
- This is the gold standard β¨
The analysis below focuses on companies that DID apologize and whether they compensated enough.
""")
# Create scatter plot for companies WITH apologies
fig3 = px.scatter(
df_with_apologies,
x='ratio',
y='vader_compound',
color='zone',
text='company_id',
title="The 4:1 Rule: Positive-to-Apology Ratio vs Warmth (For Companies That Apologized)",
labels={
'ratio': 'Positives per Apology',
'vader_compound': 'Warmth Score'
},
color_discrete_map={
'β Danger (<4:1)': '#e74c3c',
'β οΈ Minimum (4-6:1)': '#f39c12',
'β
Safe (6:1+)': '#2ecc71'
},
height=500
)
fig3.update_traces(textfont=dict(size=8), textposition='bottom center', marker=dict(size=15, line=dict(width=2, color='white')))
fig3.add_vline(x=4, line_dash="dash", line_color="red", line_width=2,
annotation_text="Critical threshold")
fig3.add_vline(x=6, line_dash="dash", line_color="green", line_width=2,
annotation_text="Safe zone starts")
fig3.add_hline(y=0.85, line_dash="dash", line_color="gray",
annotation_text="Warm threshold (0.85)")
# Add annotation about zero-apology companies
if len(df_no_apologies) > 0:
fig3.add_annotation(
x=0.98, y=1.2,
xref='paper', yref='paper',
text=f'<b>{len(df_no_apologies)} companies with 0 apologies<br>scored {avg_score:.3f} average<br>(not shown - off the chart!)</b>',
showarrow=False,
bgcolor='#e3f2fd',
bordercolor='#2196f3',
borderwidth=2,
font=dict(size=11),
align='left',
xanchor='right',
yanchor='top'
)
fig3.update_layout(template='plotly_white')
st.plotly_chart(fig3, use_container_width=True)
# Zone statistics
st.markdown("### π Success Rate by Zone (Among Companies That Apologized)")
col1, col2, col3 = st.columns(3)
danger_zone = df_with_apologies[df_with_apologies['zone'] == 'β Danger (<4:1)']
minimum_zone = df_with_apologies[df_with_apologies['zone'] == 'β οΈ Minimum (4-6:1)']
safe_zone = df_with_apologies[df_with_apologies['zone'] == 'β
Safe (6:1+)']
with col1:
st.markdown("""
<div style="background-color: #ffebee; padding: 20px; border-radius: 10px;">
<h4 style="color: #c62828;">β Danger Zone</h4>
<p style="font-size: 1.8rem; font-weight: bold; margin: 10px 0;">0%</p>
<p style="margin-bottom: 0;">None are warm (0.85+)</p>
</div>
""", unsafe_allow_html=True)
with col2:
warm_min = (minimum_zone['vader_compound'] >= 0.85).sum()
total_min = len(minimum_zone)
pct_min = (warm_min / total_min * 100) if total_min > 0 else 0
st.markdown(f"""
<div style="background-color: #fff3e0; padding: 20px; border-radius: 10px;">
<h4 style="color: #f57c00;">β οΈ Minimum Zone</h4>
<p style="font-size: 1.8rem; font-weight: bold; margin: 10px 0;">{pct_min:.0f}%</p>
<p style="margin-bottom: 0;">{warm_min} of {total_min} are warm</p>
</div>
""", unsafe_allow_html=True)
with col3:
warm_safe = (safe_zone['vader_compound'] >= 0.85).sum()
total_safe = len(safe_zone)
pct_safe = (warm_safe / total_safe * 100) if total_safe > 0 else 0
st.markdown(f"""
<div style="background-color: #e8f5e9; padding: 20px; border-radius: 10px;">
<h4 style="color: #2e7d32;">β
Safe Zone</h4>
<p style="font-size: 1.8rem; font-weight: bold; margin: 10px 0;">{pct_safe:.0f}%</p>
<p style="margin-bottom: 0;">{warm_safe} of {total_safe} are warm</p>
</div>
""", unsafe_allow_html=True)
st.markdown("")
st.success("""
**π‘ Key Insight:**
- Below 4:1 ratio = 0% success rate
- Above 4:1 = guaranteed warm
- **But the real winners?** The companies that never apologized at all! π
""")
st.markdown("---")
# All companies ranked
st.markdown("## π All 14 Companies Ranked")
st.markdown("From warmest to coldest rejection emails:")
df_sorted = df.sort_values('vader_compound', ascending=False)
fig4 = go.Figure()
colors = ['#2ecc71' if score >= 0.95 else '#3498db' if score >= 0.85 else '#f39c12' if score >= 0.60 else '#e74c3c'
for score in df_sorted['vader_compound']]
fig4.add_trace(go.Bar(
x=df_sorted['company_id'],
y=df_sorted['vader_compound'],
marker_color=colors,
text=[f'{v:.3f}' for v in df_sorted['vader_compound']],
textposition='outside',
hovertemplate='<b>%{x}</b><br>Score: %{y:.3f}<br><extra></extra>'
))
fig4.add_hline(y=0.95, line_dash="dash", line_color="green", annotation_text="Very Warm (0.95+)")
fig4.add_hline(y=0.85, line_dash="dash", line_color="orange", annotation_text="Warm (0.85+)")
fig4.add_hline(y=0.60, line_dash="dash", line_color="gray", annotation_text="Neutral (0.60+)")
fig4.update_layout(
title="Company Warmth Rankings",
xaxis_title="Company",
yaxis_title="Warmth Score (VADER)",
template='plotly_white',
height=500,
showlegend=False,
xaxis={'tickangle': -45}
)
st.plotly_chart(fig4, use_container_width=True)
# Summary table
st.markdown("### π Detailed Breakdown")
summary_df = df_sorted[['company_id', 'vader_compound', 'emotion_joy', 'afinn_positive_count', 'apology_words']].copy()
summary_df.columns = ['Company', 'Warmth Score', 'Joy Words', 'Positive Words', 'Apologies']
summary_df = summary_df.round(3)
st.dataframe(summary_df, use_container_width=True, hide_index=True)
elif st.session_state.page == "π¬ Deep Dive: SHAP":
st.title("π¬ Deep Dive: SHAP Word Analysis")
st.markdown("### Which specific words push sentiment up or down? Let's find out.")
st.markdown("""
**SHAP (SHapley Additive exPlanations)** reveals the exact contribution of each word
to RoBERTa's sentiment decision. This is where I find the **real insights** -
which words companies should use, and which they should avoid.
""")
st.markdown("---")
# Tab structure for different views
shap_tab1, shap_tab2, shap_tab3, shap_tab4 = st.tabs([
"β οΈ Words to Avoid",
"β Words to Use",
"π Substitution Guide",
"π Case Studies"
])
with shap_tab1:
st.markdown("## β οΈ The Most Damaging Words")
st.markdown("These words carry the most negative weight across all emails:")
# Get top 15 most negative
top_negative = df_negative.nsmallest(15, 'score')
fig_neg = go.Figure(data=[
go.Bar(
x=top_negative['score'],
y=[f"{row['word']} ({row['company']})" for _, row in top_negative.iterrows()],
orientation='h',
marker_color='#e74c3c',
text=[f"{score:.3f}" for score in top_negative['score']],
textposition='outside',
hovertemplate='<b>%{y}</b><br>Impact: %{x:.3f}<extra></extra>'
)
])
fig_neg.update_layout(
title="Top 15 Most Damaging Words (Across All Companies)",
xaxis_title="SHAP Value (Negative Impact)",
yaxis_title="Word (Company)",
template='plotly_white',
height=600,
showlegend=False
)
st.plotly_chart(fig_neg, use_container_width=True)
# Insights
st.markdown("### π‘ Key Insights")
col1, col2 = st.columns(2)
with col1:
st.markdown("""
<div style="background-color: #F3EDFA; padding: 20px; border-radius: 10px;>
<h4>π¨ The "Unfortunately" Disaster</h4>
<p><b>Company_C: -0.7727</b> (worst word in dataset!)</p>
<p>This single word crushes sentiment. VADER thinks the email is positive (0.974),
but RoBERTa knows it's negative (-0.168) because transformers have learned
"unfortunately" is a rejection pattern.</p>
<p style="margin-bottom: 0;"><b>Impact:</b> Using "unfortunately" creates a 1.14 point
disagreement between lexicons and transformers.</p>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown("""
<div style="background-color: #F3EDFA; padding: 20px; border-radius: 10px;>
<h4>π The "Regret" Problem</h4>
<p><b>Company_G: -0.7341</b> (second-worst!)</p>
<p>"Regret" sounds polite, but it's actually <b>worse than "sorry"</b> (-0.47)
because it's strongly associated with formal rejections.</p>
<p style="margin-bottom: 0;"><b>Advice:</b> Never use "regret" in rejection emails.
It's a learned rejection signal.</p>
</div>
""", unsafe_allow_html=True)
# Summary statistics
st.markdown("### π Word Frequency Analysis")
# Count how many times each negative word appears
neg_word_counts = df_negative.groupby('word').agg({
'score': ['mean', 'count', 'min']
}).round(3)
neg_word_counts.columns = ['avg_impact', 'frequency', 'worst_impact']
neg_word_counts = neg_word_counts.sort_values('avg_impact').head(10)
st.dataframe(
neg_word_counts.reset_index().rename(columns={
'word': 'Word',
'avg_impact': 'Average Impact',
'frequency': 'Appears in # Emails',
'worst_impact': 'Worst Single Impact'
}),
use_container_width=True,
hide_index=True
)
st.warning("""
**Bottom Line:**
- "Unfortunately" appears in 8 emails with average impact -0.47
- "Sorry" appears in 4 emails with average impact -0.29
- "Regret" appears in 2 emails but has devastating impact (-0.66 average)
**Recommendation:** Avoid all three. If you must acknowledge disappointment, use "disappointing" (-0.17) instead.
""")
with shap_tab2:
st.markdown("## β The Most Helpful Words")
st.markdown("These words consistently boost warmth:")
# Get top 15 most positive
top_positive = df_positive.nlargest(15, 'score')
fig_pos = go.Figure(data=[
go.Bar(
x=top_positive['score'],
y=[f"{row['word']} ({row['company']})" for _, row in top_positive.iterrows()],
orientation='h',
marker_color='#2ecc71',
text=[f"+{score:.3f}" for score in top_positive['score']],
textposition='outside',
hovertemplate='<b>%{y}</b><br>Impact: %{x:.3f}<extra></extra>'
)
])
fig_pos.update_layout(
title="Top 15 Most Helpful Words (Across All Companies)",
xaxis_title="SHAP Value (Positive Impact)",
yaxis_title="Word (Company)",
template='plotly_white',
height=600,
showlegend=False
)
st.plotly_chart(fig_pos, use_container_width=True)
# Insights
st.markdown("### π‘ The Power Trio")
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("""
<div style="background-color: #e8f5e9; padding: 20px; border-radius: 10px;">
<h4>π #1: "Appreciate"</h4>
<p><b>Average Impact: +0.52</b></p>
<p>Appears in 5 emails with consistently strong positive impact.</p>
<p><b>Best Use:</b> Company_M (+0.59)</p>
<p style="margin-bottom: 0;"><i>"We appreciate your interest..."</i></p>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown("""
<div style="background-color: #e8f5e9; padding: 20px; border-radius: 10px;">
<h4>π₯ #2: "Thank"</h4>
<p><b>Average Impact: +0.47</b></p>
<p>Most frequent positive word. Appears in 10+ emails.</p>
<p><b>Best Use:</b> Company_E (+0.56)</p>
<p style="margin-bottom: 0;"><i>"Thank you for your time..."</i></p>
</div>
""", unsafe_allow_html=True)
with col3:
st.markdown("""
<div style="background-color: #e8f5e9; padding: 20px; border-radius: 10px;">
<h4>π₯ #3: "Value"</h4>
<p><b>Average Impact: +0.39</b></p>
<p>Rare but powerful. Shows genuine appreciation.</p>
<p><b>Best Use:</b> Company_F (+0.39)</p>
<p style="margin-bottom: 0;"><i>"We value your effort..."</i></p>
</div>
""", unsafe_allow_html=True)
# Word frequency
st.markdown("### π Positive Word Frequency")
pos_word_counts = df_positive.groupby('word').agg({
'score': ['mean', 'count', 'max']
}).round(3)
pos_word_counts.columns = ['avg_impact', 'frequency', 'best_impact']
pos_word_counts = pos_word_counts.sort_values('avg_impact', ascending=False).head(10)
st.dataframe(
pos_word_counts.reset_index().rename(columns={
'word': 'Word',
'avg_impact': 'Average Impact',
'frequency': 'Appears in # Emails',
'best_impact': 'Best Single Impact'
}),
use_container_width=True,
hide_index=True
)
st.success("""
**Action Items:**
- Use "appreciate" instead of just "thank" for stronger impact
- Include "value" when you mean it (don't overuse)
- "Impressed" (+0.51 peak) is powerful when specific
- "Happy" and "wish" are joy words that boost warmth significantly
""")
with shap_tab3:
st.markdown("## π Word Substitution Guide")
st.markdown("### Simple swaps that make emails warmer:")
# Create substitution table
substitutions = [
{
'avoid': 'Sorry',
'avoid_impact': -0.47,
'use': 'Disappointed',
'use_impact': -0.17,
'improvement': '+64%',
'example': 'We\'re disappointed we can\'t move forward'
},
{
'avoid': 'Regret',
'avoid_impact': -0.73,
'use': 'Disappointing',
'use_impact': -0.17,
'improvement': '+77%',
'example': 'This is disappointing news to share'
},
{
'avoid': 'Unfortunately',
'avoid_impact': -0.77,
'use': '(Skip it!)',
'use_impact': 0.0,
'improvement': '+100%',
'example': 'We\'ve decided to move forward with another candidate'
},
{
'avoid': 'Thanks (generic)',
'avoid_impact': -0.16,
'use': 'Thank you + specific',
'use_impact': +0.42,
'improvement': '+163%',
'example': 'Thank you for your thoughtful approach to the case study'
},
{
'avoid': 'Thank (alone)',
'avoid_impact': +0.13,
'use': 'Appreciate',
'use_impact': +0.54,
'improvement': '+315%',
'example': 'We appreciate your interest in our team'
},
{
'avoid': 'Good luck',
'avoid_impact': +0.12,
'use': 'Wish you the best',
'use_impact': +0.23,
'improvement': '+92%',
'example': 'We wish you the best in your job search'
}
]
df_sub = pd.DataFrame(substitutions)
# Display as formatted table
st.markdown("### π Recommended Substitutions")
for _, row in df_sub.iterrows():
col1, col2, col3 = st.columns([1, 1, 2])
with col1:
st.markdown(f"""
<div style="background-color: #ffebee; padding: 15px; border-radius: 8px; text-align: center;">
<h4 style="color: #c62828; margin: 0;">β Avoid</h4>
<p style="font-size: 1.2rem; font-weight: bold; margin: 10px 0;">{row['avoid']}</p>
<p style="margin: 0; color: #666;">Impact: {row['avoid_impact']:.2f}</p>
</div>
""", unsafe_allow_html=True)
with col2:
use_color = "#e8f5e9" if row['use_impact'] >= 0 else "#fff3e0"
text_color = "#2e7d32" if row['use_impact'] >= 0 else "#f57c00"
st.markdown(f"""
<div style="background-color: {use_color}; padding: 15px; border-radius: 8px; text-align: center;">
<h4 style="color: {text_color}; margin: 0;">β
Use</h4>
<p style="font-size: 1.2rem; font-weight: bold; margin: 10px 0;">{row['use']}</p>
<p style="margin: 0; color: #666;">Impact: {row['use_impact']:+.2f}</p>
</div>
""", unsafe_allow_html=True)
with col3:
st.markdown(f"""
<div style="background-color: white; padding: 15px; border-radius: 8px; border-left: 4px solid #3498db;">
<p style="margin: 0; color: #666;"><b>Improvement:</b> {row['improvement']}</p>
<p style="margin: 5px 0 0 0; font-style: italic;">"{row['example']}"</p>
</div>
""", unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
# Key takeaways
st.info("""
**π‘ Key Takeaway:** Small word changes create massive improvements:
- Dropping "unfortunately" entirely = +100% better
- Swapping "sorry" for "disappointed" = +64% better
- Using "appreciate" instead of "thank" = +315% better
These are ONE-TIME template fixes that improve every rejection forever.
""")
with shap_tab4:
st.markdown("## π Case Studies: Winners & Losers")
st.markdown("### Let's examine why certain companies succeeded or failed:")
# Case Study 1: Company F (Winner)
st.markdown("### π Case Study #1: Company F - The Winner (0.990)")
company_f = shap_results['Company_F']
col1, col2 = st.columns(2)
with col1:
st.markdown("""
<div style="background-color: #e8f5e9; padding: 20px; border-radius: 10px;">
<h4>β
What They Did Right</h4>
<ul>
<li><b>Strong positives:</b> Used powerful words like "appreciate" (+0.54), "value" (+0.39), "happy" (+0.26)</li>
<li><b>Smart apology choice:</b> Used "disappointing" (-0.17) instead of "sorry" (-0.47)</li>
<li><b>Joy words:</b> Included "wish" and "best"</li>
<li><b>No "unfortunately":</b> Avoided the worst word</li>
</ul>
</div>
""", unsafe_allow_html=True)
st.metric("Positive Force", f"+{company_f['words'][0][1] + company_f['words'][1][1]:.2f}")
st.metric("Negative Force", f"{company_f['words'][-1][1] + company_f['words'][-2][1]:.2f}")
with col2:
# SHAP for Company F