-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1978 lines (1826 loc) · 88.8 KB
/
app.py
File metadata and controls
1978 lines (1826 loc) · 88.8 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
"""
CEDD — Streamlit Application
Bilingual demo interface: chat + real-time monitoring dashboard.
Interface de démonstration bilingue : chat + dashboard de surveillance en temps réel.
"""
import os
import sys
import json
import time
from datetime import datetime
import streamlit as st
import plotly.graph_objects as go
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from cedd.classifier import CEDDClassifier, LEVEL_LABELS
from cedd.feature_extractor import extract_features
from cedd.response_modulator import (
get_llm_response,
get_level_description,
get_system_prompt,
get_handoff_description,
get_handoff_offer_message,
get_counselor_intro,
get_llm_response_as_counselor,
)
from cedd.session_tracker import SessionTracker
# ─── Configuration ─────────────────────────────────────────────────────────────
MODEL_PATH = "models/cedd_model.joblib"
LEVEL_COLORS = {0: "#2ecc71", 1: "#f1c40f", 2: "#e67e22", 3: "#e74c3c"}
# ─── Themes ─────────────────────────────────────────────────────────────────────
THEMES = {
"light": {
"bg_main": "#c8d6e5",
"bg_card": "#dbe6f0",
"bg_input": "#eaf1f8",
"bg_chat": "#dbe6f0",
"text_main": "#0d1b2a",
"text_muted": "#000000",
"border": "#9bb5cc",
"chat_user": "#a8d5b5",
"chat_bot": "#ccdae6",
"pill_bg": "#b8d4e8",
"pill_bord": "#7aaec8",
"pill_text": "#0d3a5c",
"btn_primary_bg": "#2e86c1",
"btn_primary_text": "#ffffff",
},
"dark": {
"bg_main": "#0e1117",
"bg_card": "#1a1d27",
"bg_input": "#262b38",
"bg_chat": "#161922",
"text_main": "#e2e8f0",
"text_muted": "#ffffff",
"border": "#c0c8d8",
"chat_user": "#1a3d2b",
"chat_bot": "#1e2130",
"pill_bg": "#1e2340",
"pill_bord": "#3b4680",
"pill_text": "#818cf8",
"btn_primary_bg": "#3b82f6",
"btn_primary_text": "#ffffff",
},
}
def get_theme_css(theme: str) -> str:
t = THEMES[theme]
return f"""
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap">
<style>
.stApp {{
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;
}}
.stApp, [data-testid="stAppViewContainer"],
.main .block-container {{
background-color: {t['bg_main']} !important;
}}
[data-testid="stMain"] h1,
[data-testid="stMain"] h2,
[data-testid="stMain"] h3,
[data-testid="stMain"] h4 {{
color: {t['text_main']} !important;
}}
[data-testid="stMain"] p,
[data-testid="stMain"] li,
[data-testid="stMain"] label {{
color: {t['text_main']} !important;
}}
hr {{ border-color: {t['border']} !important; opacity: 0.6; }}
[data-baseweb="input"] {{
border: 1px solid {t['border']} !important;
border-radius: 20px !important;
background-color: {t['bg_input']} !important;
outline: none !important;
box-shadow: none !important;
}}
[data-baseweb="input"] input {{
background-color: {t['bg_input']} !important;
color: {t['text_main']} !important;
border: none !important;
outline: none !important;
box-shadow: none !important;
caret-color: {t['text_main']} !important;
}}
[data-testid="metric-container"] {{
background-color: {t['bg_card']} !important;
border: 1px solid {t['border']} !important;
border-radius: 8px;
}}
[data-testid="stMetricValue"], [data-testid="stMetricLabel"] {{
color: {t['text_main']} !important;
}}
[data-testid="stExpander"] {{
background-color: {t['bg_card']} !important;
border: 1px solid {t['border']} !important;
}}
[data-testid="stExpander"] details {{
border: 1px solid {t['border']} !important;
}}
[data-testid="stExpander"] summary,
[data-testid="stExpander"] details[open] > summary,
[data-testid="stExpander"] summary:hover,
[data-testid="stExpander"] details[open] > summary:hover {{
border: none !important;
background-color: {t['bg_card']} !important;
color: {t['text_main']} !important;
}}
[data-testid="stExpanderDetails"] {{
background-color: {t['bg_card']} !important;
border-color: {t['border']} !important;
}}
[data-testid="stExpander"] [data-testid="stIconMaterial"] {{
color: {t['text_main']} !important;
}}
.stButton > button[kind="secondary"],
[data-testid="stBaseButton-secondary"] {{
background-color: {t['bg_card']} !important;
color: {t['text_main']} !important;
border-color: {t['border']} !important;
font-size: 0.75rem !important;
}}
.stButton > button[kind="secondary"]:hover,
[data-testid="stBaseButton-secondary"]:hover {{
border-color: {t['text_muted']} !important;
}}
[data-testid="stFormSubmitButton"] > button,
.stButton > button[kind="primary"],
[data-testid="stBaseButton-primary"] {{
background-color: {t['btn_primary_bg']} !important;
color: {t['btn_primary_text']} !important;
border-color: {t['btn_primary_bg']} !important;
}}
[data-testid="stFormSubmitButton"] > button:hover,
.stButton > button[kind="primary"]:hover,
[data-testid="stBaseButton-primary"]:hover {{
filter: brightness(1.1);
}}
[data-testid="stMain"] [data-testid="stCaptionContainer"] p {{
color: {t['text_muted']} !important;
}}
[data-testid="stMain"] [data-testid="stAlert"] {{
background-color: {t['bg_card']} !important;
border-color: {t['border']} !important;
}}
[data-testid="stMain"] [data-testid="stAlert"] p {{
color: {t['text_main']} !important;
}}
[data-testid="stForm"],
.stForm,
[data-testid="stForm"] > div {{
border: 1px solid {t['border']} !important;
outline: none !important;
box-shadow: none !important;
border-radius: 12px !important;
background: {t['bg_card']} !important;
padding: 8px !important;
}}
pre, code {{
background-color: {t['bg_input']} !important;
color: {t['text_main']} !important;
border-color: {t['border']} !important;
}}
[data-testid="stProgressBar"] > div {{
background-color: {t['border']} !important;
}}
.chat-bubble-user {{
background-color: {t['chat_user']} !important;
color: {t['text_main']} !important;
}}
.chat-bubble-assistant {{
background-color: {t['chat_bot']} !important;
color: {t['text_main']} !important;
}}
.chat-bubble-counselor {{
background: linear-gradient(135deg, #1a5276, #2471a3) !important;
color: #ffffff !important;
border: 1px solid #2980b9 !important;
}}
.chat-bubble-counselor .llm-badge {{
color: #aed6f1 !important;
}}
.chat-container {{
background: {t['bg_chat']} !important;
border: 1px solid {t['border']} !important;
}}
.feature-pill {{
background: {t['pill_bg']} !important;
border-color: {t['pill_bord']} !important;
color: {t['pill_text']} !important;
}}
.metric-card {{
background: {t['bg_card']} !important;
border-color: {t['border']} !important;
}}
[data-baseweb="select"] > div {{
background-color: {t['bg_card']} !important;
border-color: {t['border']} !important;
color: {t['text_main']} !important;
}}
[data-baseweb="select"] [data-testid="stMarkdownContainer"] p,
[data-baseweb="select"] span {{
color: {t['text_main']} !important;
}}
[data-baseweb="select"] svg {{
fill: {t['text_main']} !important;
}}
[data-baseweb="popover"] {{
background-color: {t['bg_card']} !important;
}}
[data-baseweb="popover"] li {{
background-color: {t['bg_card']} !important;
color: {t['text_main']} !important;
}}
[data-baseweb="popover"] li:hover {{
background-color: {t['bg_input']} !important;
}}
.proba-bar-track {{
background: {t['border']}44 !important;
}}
[data-testid="stMetricValue"] {{
font-size: 1.6rem !important;
font-weight: 700 !important;
}}
[data-testid="stMetricLabel"] {{
text-transform: uppercase;
letter-spacing: 0.05em;
font-size: var(--fs-xs) !important;
}}
hr {{
margin: 8px 0 !important;
}}
[data-testid="stFormSubmitButton"] > button {{
border-radius: 20px !important;
}}
</style>
<script>
(function() {{
const TEXT_COLOR = "{t['text_main']}";
const BG_COLOR = "{t['bg_card']}";
function fixExpanders() {{
document.querySelectorAll('[data-testid="stExpander"] summary').forEach(function(s) {{
s.style.setProperty('color', TEXT_COLOR, 'important');
s.style.setProperty('background-color', BG_COLOR, 'important');
s.querySelectorAll('*').forEach(function(el) {{
if (el.tagName === 'svg') {{
el.style.setProperty('fill', TEXT_COLOR, 'important');
}}
el.style.setProperty('color', TEXT_COLOR, 'important');
}});
}});
}}
fixExpanders();
var obs = new MutationObserver(fixExpanders);
obs.observe(document.body, {{ childList: true, subtree: true, attributes: true }});
}})();
</script>
"""
LLM_SOURCE_INDICATOR = {
"cohere": ("🔵", "#39594d"),
"groq": ("🟠", "#f97316"),
"gemini-flash": ("💎", "#4285f4"),
"claude-haiku": ("🟣", "#7c3aed"),
"fallback-statique": ("⚠️", "#f59e0b"),
"cedd-system": ("🧠", "#2980b9"),
"counselor": ("🧑⚕️", "#1a5276"),
}
LLM_DISPLAY_NAMES = {
"cohere": "Cohere",
"groq": "Groq",
"gemini-flash": "Gemini",
"claude-haiku": "Claude",
"cedd-system": "CEDD",
"counselor": "Alex — KHP",
}
LEVEL_EMOJIS = {0: "🟢", 1: "🟡", 2: "🟠", 3: "🔴"}
DEMO_USERS = {
"fr": [
"Shuchita (stable vert)",
"Priyanka (amélioration)",
"Amanda (fluctuant)",
"Dominic (escalade)",
"Guest (nouveau)",
],
"en": [
"Shuchita (stable green)",
"Priyanka (improving)",
"Amanda (fluctuating)",
"Dominic (escalating)",
"Guest (new)",
],
}
def _user_id_from_display(display_name):
"""Extract user_id from display name: 'Shuchita (stable green)' → 'Shuchita'"""
return display_name.split(" (")[0]
# ─── Demo autopilot scenarios / Scénarios de démo automatisés ─────────────────
DEMO_SCENARIOS = {
"fr": [
"Salut! Ça fait longtemps que j'ai pas parlé à quelqu'un de juste... neutre, tsé? L'école recommence pis là c'est déjà intense. T'as des trucs pour gérer le stress des examens? Parce que je stresse déjà pour la session pis on est même pas rendus aux mi-sessions.",
"Ouais c'est ça, j'essaie de faire des listes. Ça aide un peu. Hier j'ai quand même réussi à finir mon travail de bio pis à voir mes chums le soir, faque c'était correct. Mon chum Mathieu m'a montré une technique de respiration, je sais pas si ça marche vraiment mais on a ri en la faisant haha. C'est quoi les techniques que tu recommandes en général?",
"Ouais, les pauses ça marche bien quand j'y pense. Le truc c'est que des fois je pense même pas à en prendre. Je suis genre scotché à mon bureau pis le temps passe. Mais bon, cette semaine ça devrait mieux aller, j'ai moins de cours jeudi-vendredi. Mathieu pis moi on pense aller au cinéma si on a le temps.",
"Mmh ouais. Cette semaine a été rough. J'ai pas dormi super bien, genre je me réveille à 3h du mat pis j'arrive pu à me rendormir. C'est probablement le stress. J'ai annulé le cinéma avec Mathieu, j'avais trop de trucs à faire.",
"C'est correct, je gère. C'est juste que des fois j'ai l'impression que tout le monde avance pis moi je tourne en rond. Mathieu il a l'air de trouver ça facile lui. Je sais pas trop. Anyway.",
"Honnêtement j'sais plus trop. Chez nous c'est tendu depuis quelques semaines, mes parents sont pas dans leur meilleure forme. J'essaie de pas ramener mes affaires là-dedans mais c'est difficile. J'ai l'impression d'avoir nulle part où décompresser vraiment.",
"Ouais je sais. C'est juste que je me sens fatigué de tout, pas juste de l'école. Comme... fatigué de tenir. Je dis ça pis ça a l'air dramatique mais c'est vraiment comme ça que je me sens ces temps-ci.",
"Je sais pas. Peut-être. J'ai même plus vraiment envie de sortir. Mes chums me textent pis j'réponds même pu vraiment. C'est trop.",
"C'est correct. De toute façon.",
],
"en": [
"Hey, just wanted to talk to someone tonight. Starting university is kind of a lot, honestly? Like it's exciting but also way more intense than I expected. How do people usually handle the adjustment? I feel like everyone else already has their thing figured out.",
"That's actually helpful. I've been trying to go to the study sessions in my building. Made a couple of friends already — Jordan's been showing me around campus which is great. I had a rough week with assignments piling up but I got through it. Any tips for staying on top of things without burning out?",
"Yeah the breaks thing makes sense. I keep telling myself I'll do that but then I just end up at my desk for like five hours straight. It's fine, I'm managing. Jordan and I were supposed to hang out this weekend, looking forward to that at least.",
"Weekend ended up being kind of whatever. Jordan cancelled last minute, it's fine. Been tired lately, not sleeping great. I keep waking up in the middle of the night thinking about stuff. I don't know, probably just adjusting still.",
"I'm okay. Just feel kind of behind on everything. Like everyone else knows what they're doing and I'm still figuring out how to do laundry. It sounds dumb when I say it out loud. Whatever.",
"Honestly, I've just been staying in my room more. Home is kind of far so I can't just go back for the weekend. My roommate has his own friends and I don't really fit in their group. It just feels like there's nowhere to recharge, you know?",
"Yeah, I know. It's just exhausting. Not like tired-exhausted, more like... I don't know how to explain it. Tired of trying to seem okay I guess. I haven't really talked to anyone back home in a while either.",
"I don't know, maybe. I used to like being around people but now it just takes too much energy. Jordan texted me twice this week. Didn't answer. It's easier that way.",
"It's fine. I'll figure it out.",
],
}
# ─── About CEDD content / Contenu À propos de CEDD ───────────────────────────
ABOUT_CEDD = {
"fr": """**CEDD** (Conversational Emotional Drift Detection) est une couche de sécurité en temps réel pour les chatbots de santé mentale jeunesse (16-22 ans).
**Comment ça fonctionne :**
- Analyse **67 caractéristiques** par conversation (lexicales, sémantiques, comportementales)
- Surveille la **trajectoire** émotionnelle — pas juste un message, mais l'évolution complète
- **7 portes de sécurité** : les mots-clés de crise surpassent toujours le ML + détection de délai de réponse
- **Transfert accompagné** en 5 étapes vers Jeunesse, J'écoute au niveau Rouge
**Ce que vous voyez à droite :**
- 🎯 **Jauge** : niveau d'alerte actuel (Vert → Rouge)
- 📊 **Probabilités** : confiance du modèle par classe
- ⚡ **Signaux** : caractéristiques dominantes qui influencent le niveau
- 📈 **Historique** : évolution du niveau au fil des messages
**Philosophie :** Les faux positifs (sur-alerter) sont toujours préférables aux faux négatifs (manquer une crise).""",
"en": """**CEDD** (Conversational Emotional Drift Detection) is a real-time safety layer for youth mental health chatbots (ages 16-22).
**How it works:**
- Analyzes **67 features** per conversation (lexical, semantic, behavioral)
- Monitors the emotional **trajectory** — not just one message, but the full evolution
- **7 safety gates**: crisis keywords always override ML + response delay detection
- **5-step warm handoff** to Kids Help Phone at Red level
**What you see on the right:**
- 🎯 **Gauge**: current alert level (Green → Red)
- 📊 **Probabilities**: model confidence per class
- ⚡ **Signals**: dominant features driving the alert level
- 📈 **History**: alert level evolution across messages
**Philosophy:** False positives (over-alerting) are always preferable to false negatives (missing a crisis).""",
}
# ─── Bilingual UI strings / Chaînes d'interface bilingues ─────────────────────
STRINGS = {
"fr": {
"lang_btn": "🇬🇧 English",
"page_title": "CEDD - Détection de dérive émotionnelle",
"app_title": "🧠 CEDD — Détection de dérive émotionnelle conversationnelle",
"app_subtitle": "Hackathon Mila · Sécurité IA en santé mentale des jeunes · Équipe 404HarmNotFound",
"theme_btn": "🌙 Sombre",
"reset_btn": "🔄 Réinitialiser",
"chat_header": "### 💬 Conversation",
"chat_empty": "Commence la conversation...",
"welcome_title": "Bienvenue sur CEDD",
"welcome_text": "Un système de sécurité en temps réel qui surveille la trajectoire émotionnelle de ta conversation — pas juste un message, mais l'évolution complète.",
"welcome_cta": "Écris ton premier message ci-dessous ⬇️",
"welcome_profiles": "Essaie un profil de démo ↗️",
"welcome_profile_list": "🟢 Shuchita — stable · 🟡 Priyanka — amélioration · 🔀 Amanda — fluctuant · 🔴 Dominic — escalade · ✨ Guest — nouveau",
"input_placeholder": "Écris ton message ici et appuie sur Entrée",
"send_btn": "Envoyer ➤",
"dashboard_header": "### 📊 Dashboard CEDD",
"confidence": "**Confiance**",
"proba_header": "**Probabilités par classe**",
"signals_header": "**Signaux actifs**",
"signals_waiting": "En attente d'analyse...",
"history_header": "**Évolution du niveau**",
"history_waiting": "Historique disponible après 2 messages.",
"streamgraph_header": "**Flux émotionnel**",
"streamgraph_waiting": "Flux disponible après 2 messages.",
"longitudinal_header": "### 📊 Historique longitudinal",
"longitudinal_empty": "Aucun historique — complétez des sessions pour voir la tendance.",
"trend_stable": "→ Stable",
"trend_worsening": "↗ En hausse",
"trend_improving": "↘ En amélioration",
"llm_header": "**LLM conversationnel**",
"llm_last_call": "Dernier appel :",
"mode_header": "**Mode de réponse actif**",
"prompt_expander": "Voir le prompt système complet",
"stats_header": "**Statistiques de session**",
"stat_messages": "Messages",
"stat_exchanges": "Échanges",
"stat_peak": "Pic alerte",
"sessions_caption": "Sessions analysées : {n} • Score longitudinal : {score:.0%}",
"model_not_found": "Modèle introuvable : {path}. Lancez d'abord `python train.py`.",
"gauge_title": "Niveau d'alerte",
"level_labels": {0: "VERT", 1: "JAUNE", 2: "ORANGE", 3: "ROUGE"},
"gauge_ticks": ["Vert", "Jaune", "Orange", "Rouge"],
"proba_names": {
"green": "Verte", "yellow": "Jaune", "orange": "Orange", "red": "Rouge"
},
# Internal recommendation keys from session_tracker (always French)
# → mapped here for display / Clés internes → affichage traduit
"rec_normal": "Suivi normal",
"rec_attention": "Attention soutenue recommandée",
"rec_consultation": "Consultation professionnelle suggérée",
"rec_intervention": "Intervention prioritaire recommandée",
"llm_fallback": "sans LLM",
"handoff_title": "Transfert accompagné",
"handoff_step_label": "Étape {step}/5 : <b>{desc}</b>",
"withdrawal_banner": "Bon retour. Ça fait un moment — comment tu te sens ?",
"withdrawal_badge": "Retour après absence",
"feature_chart_title": "🔍 Signaux détectés",
"feature_chart_note": "Score composite = importance du modèle × valeur normalisée. Les barres montrent ce qui influence le plus le niveau d'alerte actuel.",
"radar_title": "🕸️ Radar des features",
"profile_label": "Profil",
"demo_btn": "▶️ Démo",
"demo_stop_btn": "⏹️ Arrêter",
"demo_character_fr": "Félix, 18 ans, CÉGEP",
"demo_character_en": "Alex, 19, université",
"demo_running": "Démo en cours — message {n}/9",
"about_btn": "ℹ️ À propos",
"about_title": "À propos de CEDD",
"export_btn": "📥 Exporter",
"alert_toast_up": "⚠️ Niveau d'alerte augmenté : {emoji} {label}",
"llm_fallback_toast": "🔄 {failed} a échoué (timeout) → basculé sur {active}",
"compare_btn": "🔀 Comparer",
"compare_btn_off": "🔀 Mode normal",
"compare_left_header": "### 💬 Sans CEDD",
"compare_left_sub": "LLM brut — aucune instruction de sécurité",
"compare_right_header":"### 🧠 Avec CEDD",
"compare_right_sub": "LLM guidé par les instructions CEDD adaptatives",
"handoff_offer_yes": "Oui, connecte-moi",
"handoff_offer_no": "Non merci",
"counselor_banner_name": "Alex — Jeunesse, J'écoute / Kids Help Phone",
"counselor_banner_sub": "Conseiller·ère humain·e • En ligne maintenant",
"counselor_connecting": "Connexion avec Alex en cours...",
"delay_badge": "⏱️ Délai de réponse élevé",
},
"en": {
"lang_btn": "🇫🇷 Français",
"page_title": "CEDD - Conversational Emotional Drift Detection",
"app_title": "🧠 CEDD — Conversational Emotional Drift Detection",
"app_subtitle": "Mila Hackathon · AI Safety in Youth Mental Health · Team 404HarmNotFound",
"theme_btn": "🌙 Dark",
"reset_btn": "🔄 Reset",
"chat_header": "### 💬 Conversation",
"chat_empty": "Start the conversation...",
"welcome_title": "Welcome to CEDD",
"welcome_text": "A real-time safety layer that monitors the emotional trajectory of your conversation — not just one message, but the full evolution.",
"welcome_cta": "Type your first message below ⬇️",
"welcome_profiles": "Try a demo profile ↗️",
"welcome_profile_list": "🟢 Shuchita — stable · 🟡 Priyanka — improving · 🔀 Amanda — fluctuating · 🔴 Dominic — escalating · ✨ Guest — new",
"input_placeholder": "Type your message here and press Enter",
"send_btn": "Send ➤",
"dashboard_header": "### 📊 CEDD Dashboard",
"confidence": "**Confidence**",
"proba_header": "**Class probabilities**",
"signals_header": "**Active signals**",
"signals_waiting": "Waiting for analysis...",
"history_header": "**Alert level history**",
"history_waiting": "History available after 2 messages.",
"streamgraph_header": "**Emotional flow**",
"streamgraph_waiting": "Flow available after 2 messages.",
"longitudinal_header": "### 📊 Longitudinal history",
"longitudinal_empty": "No history yet — complete sessions to see the trend.",
"trend_stable": "→ Stable",
"trend_worsening": "↗ Worsening",
"trend_improving": "↘ Improving",
"llm_header": "**Conversational LLM**",
"llm_last_call": "Last call:",
"mode_header": "**Active response mode**",
"prompt_expander": "View full system prompt",
"stats_header": "**Session statistics**",
"stat_messages": "Messages",
"stat_exchanges": "Exchanges",
"stat_peak": "Alert peak",
"sessions_caption": "Sessions analyzed: {n} • Longitudinal score: {score:.0%}",
"model_not_found": "Model not found: {path}. Run `python train.py` first.",
"gauge_title": "Alert level",
"level_labels": {0: "GREEN", 1: "YELLOW", 2: "ORANGE", 3: "RED"},
"gauge_ticks": ["Green", "Yellow", "Orange", "Red"],
"proba_names": {
"green": "Green", "yellow": "Yellow", "orange": "Orange", "red": "Red"
},
"rec_normal": "Normal monitoring",
"rec_attention": "Sustained attention recommended",
"rec_consultation": "Professional consultation suggested",
"rec_intervention": "Priority intervention recommended",
"llm_fallback": "no LLM",
"handoff_title": "Warm Handoff",
"handoff_step_label": "Step {step}/5: <b>{desc}</b>",
"withdrawal_banner": "Welcome back. It's been a while — how are you feeling?",
"withdrawal_badge": "Returned after absence",
"feature_chart_title": "🔍 Detected signals",
"feature_chart_note": "Composite score = model importance × scaled value. Bars show what drives the current alert level most.",
"radar_title": "🕸️ Feature radar",
"profile_label": "Profile",
"demo_btn": "▶️ Demo",
"demo_stop_btn": "⏹️ Stop",
"demo_character_fr": "Félix, 18, CÉGEP",
"demo_character_en": "Alex, 19, university",
"demo_running": "Demo running — message {n}/9",
"about_btn": "ℹ️ About",
"about_title": "About CEDD",
"export_btn": "📥 Export",
"alert_toast_up": "⚠️ Alert level increased: {emoji} {label}",
"llm_fallback_toast": "🔄 {failed} failed (timeout) → switched to {active}",
"compare_btn": "🔀 Compare",
"compare_btn_off": "🔀 Single mode",
"compare_left_header": "### 💬 Without CEDD",
"compare_left_sub": "Raw LLM — no safety instructions",
"compare_right_header":"### 🧠 With CEDD",
"compare_right_sub": "LLM guided by CEDD adaptive instructions",
"handoff_offer_yes": "Yes, connect me",
"handoff_offer_no": "No thank you",
"counselor_banner_name": "Alex — Jeunesse, J'écoute / Kids Help Phone",
"counselor_banner_sub": "Human Counselor • Online now",
"counselor_connecting": "Connecting you with Alex...",
"delay_badge": "⏱️ High response delay",
},
}
# Maps English recommendation strings (from session_tracker) to STRINGS keys
# Mappe les recommandations anglaises (session_tracker) vers les clés STRINGS
_REC_KEY_MAP = {
"Normal monitoring": "rec_normal",
"Sustained attention recommended": "rec_attention",
"Professional consultation suggested": "rec_consultation",
"Priority intervention recommended": "rec_intervention",
}
# ─── Page config ────────────────────────────────────────────────────────────────
st.set_page_config(
page_title="CEDD",
page_icon="🧠",
layout="wide",
initial_sidebar_state="collapsed",
)
# ─── Static CSS (layout only — colors handled by get_theme_css) ─────────────────
st.markdown("""
<style>
:root {
--fs-xs: 0.72rem;
--fs-sm: 0.8rem;
--fs-base: 0.92rem;
--fs-md: 1.0rem;
--fs-lg: 1.15rem;
--fs-xl: 1.3rem;
--spacing-xs: 4px;
--spacing-sm: 8px;
--spacing-md: 12px;
--spacing-lg: 16px;
--spacing-xl: 24px;
--radius-sm: 6px;
--radius-md: 10px;
--radius-lg: 16px;
--radius-bubble: 18px;
}
.main { padding-top: 1rem; }
.chat-container {
display: flex;
flex-direction: column;
overflow-y: auto;
max-height: 480px;
padding: var(--spacing-md);
border-radius: var(--radius-lg);
margin-bottom: var(--spacing-md);
}
.chat-bubble-user {
border-radius: var(--radius-bubble) var(--radius-bubble) 4px var(--radius-bubble);
padding: var(--spacing-md) 14px;
margin: var(--spacing-xs) 0 var(--spacing-xs) 15%;
max-width: 85%;
align-self: flex-end;
font-size: var(--fs-base);
line-height: 1.5;
word-wrap: break-word;
box-shadow: 0 1px 3px rgba(0,0,0,0.06);
transition: transform 0.15s ease, box-shadow 0.15s ease;
}
.chat-bubble-user:hover {
transform: translateY(-1px);
box-shadow: 0 3px 8px rgba(0,0,0,0.1);
}
.chat-bubble-assistant {
border-radius: var(--radius-bubble) var(--radius-bubble) var(--radius-bubble) 4px;
padding: var(--spacing-md) 14px;
margin: var(--spacing-xs) 15% var(--spacing-xs) 0;
max-width: 85%;
align-self: flex-start;
font-size: var(--fs-base);
line-height: 1.5;
word-wrap: break-word;
box-shadow: 0 1px 3px rgba(0,0,0,0.06);
transition: transform 0.15s ease, box-shadow 0.15s ease;
}
.chat-bubble-assistant:hover {
transform: translateY(-1px);
box-shadow: 0 3px 8px rgba(0,0,0,0.1);
}
.chat-bubble-counselor {
box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}
.chat-bubble-counselor:hover {
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}
.chat-time-user {
font-size: var(--fs-xs);
opacity: 0.5;
text-align: right;
margin: -2px 0 var(--spacing-xs) 0;
align-self: flex-end;
}
.chat-time-assistant {
font-size: var(--fs-xs);
opacity: 0.5;
text-align: left;
margin: -2px 0 var(--spacing-xs) 0;
align-self: flex-start;
}
.llm-badge {
font-size: var(--fs-xs);
opacity: 0.7;
display: block;
margin-top: 2px;
}
.alert-dot {
font-size: var(--fs-xs);
display: inline-block;
align-self: flex-start;
margin: 2px 0 var(--spacing-sm) 0;
}
.alert-badge {
padding: var(--spacing-sm) var(--spacing-lg);
border-radius: 20px;
font-weight: bold;
font-size: var(--fs-lg);
display: inline-block;
}
.metric-card {
border: 1px solid;
border-radius: var(--radius-md);
padding: var(--spacing-md);
margin: var(--spacing-sm) 0;
transition: border-color 0.2s ease, box-shadow 0.2s ease;
}
.feature-pill {
border: 1px solid;
border-radius: var(--radius-md);
padding: var(--spacing-xs) var(--spacing-md);
font-size: var(--fs-sm);
display: inline-block;
margin: 2px;
transition: transform 0.15s ease, box-shadow 0.15s ease;
}
.feature-pill:hover {
transform: translateY(-1px);
box-shadow: 0 2px 6px rgba(0,0,0,0.08);
}
.status-card {
padding: var(--spacing-sm) var(--spacing-md);
border-radius: var(--radius-sm);
margin: var(--spacing-xs) 0;
border-left: 4px solid;
}
.welcome-card {
text-align: center;
margin: 30px var(--spacing-lg);
}
.welcome-card-inner {
border-radius: 14px;
padding: var(--spacing-xl) 20px;
display: inline-block;
max-width: 380px;
border: 1px solid;
}
.welcome-card-icon { font-size: 2rem; margin-bottom: var(--spacing-sm); }
.welcome-card-title { font-size: var(--fs-lg); font-weight: 700; margin-bottom: var(--spacing-sm); }
.welcome-card-text { font-size: 0.88rem; opacity: 0.85; margin-bottom: var(--spacing-md); }
.welcome-card-cta { font-size: var(--fs-sm); opacity: 0.7; }
.welcome-card-profiles-title { font-size: 0.78rem; font-weight: 600; opacity: 0.8; margin-bottom: var(--spacing-xs); }
.welcome-card-profiles { font-size: var(--fs-xs); opacity: 0.7; line-height: 1.6; }
.counselor-banner {
background: linear-gradient(135deg, #1a5276, #2980b9);
border-radius: var(--radius-md);
padding: var(--spacing-md) var(--spacing-lg);
display: flex;
align-items: center;
gap: var(--spacing-md);
margin-bottom: var(--spacing-lg);
}
.counselor-banner-icon { font-size: 1.4rem; }
.counselor-banner-name { color: #fff; font-weight: 700; font-size: 14px; }
.counselor-banner-sub { color: #aed6f1; font-size: 12px; }
@keyframes alert-flash {
0% { opacity: 0; transform: translateY(-10px); }
15% { opacity: 1; transform: translateY(0); }
85% { opacity: 1; transform: translateY(0); }
100% { opacity: 0; transform: translateY(-10px); }
}
.alert-toast {
animation: alert-flash 3s ease-in-out forwards;
position: fixed;
top: 60px;
left: 50%;
transform: translateX(-50%);
z-index: 9999;
padding: var(--spacing-md) var(--spacing-xl);
border-radius: var(--spacing-xl);
font-weight: 700;
font-size: var(--fs-base);
box-shadow: 0 4px 16px rgba(0,0,0,0.2);
pointer-events: none;
}
@keyframes pulse-red {
0%, 100% { box-shadow: 0 0 0 0 rgba(231, 76, 60, 0.4); }
50% { box-shadow: 0 0 0 8px rgba(231, 76, 60, 0); }
}
.alert-badge-pulse {
animation: pulse-red 2s ease-in-out infinite;
}
/* Custom scrollbar for chat / Barre de défilement personnalisée */
.chat-container::-webkit-scrollbar { width: 6px; }
.chat-container::-webkit-scrollbar-track { background: transparent; }
.chat-container::-webkit-scrollbar-thumb {
background: rgba(128, 128, 128, 0.3);
border-radius: 3px;
}
.chat-container::-webkit-scrollbar-thumb:hover { background: rgba(128, 128, 128, 0.5); }
h1 { font-size: var(--fs-xl) !important; letter-spacing: -0.02em; }
h3 { font-size: 1.05rem !important; margin-bottom: 0.4rem !important; letter-spacing: -0.01em; }
</style>
""", unsafe_allow_html=True)
# ─── Model & tracker loading ────────────────────────────────────────────────────
@st.cache_resource
def load_model():
if not os.path.exists(MODEL_PATH):
st.error(f"Model not found / Modèle introuvable : {MODEL_PATH}. Run `python train.py`.")
st.stop()
return CEDDClassifier.load(MODEL_PATH)
@st.cache_resource
def load_tracker():
return SessionTracker()
# ─── Session state initialisation ───────────────────────────────────────────────
def init_state():
defaults = {
"messages": [],
"alert_history": [],
"current_alert": {
"level": 0, "label": "green", "confidence": 0.0,
"dominant_features": [], "probabilities": {},
},
"selected_llm": "cohere",
"last_llm_source": None,
"input_key": 0,
"user_id": "Guest",
"session_id": None,
"lang": "en", # default language / langue par défaut
"theme": "light",
"handoff_step": 0, # 0 = not in handoff, 1-5 = warm handoff steps
"withdrawal_detected": False, # True if user returned after extended absence
"demo_running": False, # True while demo autopilot is active
"demo_step": 0, # Current demo message index (0-8)
"compare_mode": False, # True = side-by-side compare mode
"compare_messages": [], # "Without CEDD" message list (left side)
"chat_mode": "normal", # "normal" | "handoff_offered" | "connecting" | "human_mode"
"handoff_offered": False, # prevents re-offering once offered
}
for k, v in defaults.items():
if k not in st.session_state:
st.session_state[k] = v
def reset_conversation():
st.session_state.messages = []
st.session_state.alert_history = []
st.session_state.current_alert = {
"level": 0, "label": "green", "confidence": 0.0,
"dominant_features": [], "probabilities": {},
}
st.session_state.input_key += 1
st.session_state.handoff_step = 0
st.session_state.withdrawal_detected = False
st.session_state.demo_running = False
st.session_state.demo_step = 0
st.session_state.compare_mode = False
st.session_state.compare_messages = []
st.session_state.chat_mode = "normal"
st.session_state.handoff_offered = False
# ─── UI components / Composants UI ──────────────────────────────────────────────
def render_chat(S: dict, theme: str = "light", messages: list | None = None):
"""Display chat bubbles. / Affiche les bulles de conversation."""
t = THEMES[theme]
if messages is None:
messages = st.session_state.messages
msgs_html = '<div class="chat-container">'
if not messages:
msgs_html += (
f'<div class="welcome-card">'
f'<div class="welcome-card-inner" style="background:{t["bg_card"]};border-color:{t["border"]};">'
f'<div class="welcome-card-icon">🧠</div>'
f'<div class="welcome-card-title" style="color:{t["text_main"]};">'
f'{S["welcome_title"]}</div>'
f'<div class="welcome-card-text" style="color:{t["text_main"]};">'
f'{S["welcome_text"]}</div>'
f'<div class="welcome-card-cta" style="color:{t["text_muted"]};">'
f'{S["welcome_cta"]}</div>'
f'<hr style="border:none;border-top:1px solid {t["border"]};margin:14px 0 10px;">'
f'<div class="welcome-card-profiles-title" style="color:{t["text_main"]};">'
f'{S["welcome_profiles"]}</div>'
f'<div class="welcome-card-profiles" style="color:{t["text_muted"]};">'
f'{S["welcome_profile_list"]}</div>'
f'</div></div>'
)
else:
for msg in messages:
role = msg["role"]
content = (
msg["content"]
.replace("<", "<")
.replace(">", ">")
.replace("\n", "<br>")
)
ts = msg.get("timestamp", "")
if role == "user":
msgs_html += f'<div class="chat-bubble-user">{content}</div>'
if ts:
msgs_html += f'<div class="chat-time-user" style="color:{t["text_muted"]};">{ts}</div>'
else:
# Assistant bubble + optional LLM badge
is_counselor = msg.get("is_counselor", False)
bubble = content
source = msg.get("source")
if source and source in LLM_SOURCE_INDICATOR:
src_emoji, src_color = LLM_SOURCE_INDICATOR[source]
src_name = LLM_DISPLAY_NAMES.get(source, source)
bubble += f'<span class="llm-badge" style="color:{src_color};">{src_emoji} {src_name}</span>'
if is_counselor:
# Blue counselor bubble with avatar / Bulle bleue d'intervenant avec avatar
msgs_html += (
f'<div class="chat-bubble-assistant chat-bubble-counselor">'
f'<span style="font-size:1.1rem;margin-right:6px;">🧑⚕️</span>{bubble}</div>'
)
else:
msgs_html += f'<div class="chat-bubble-assistant">{bubble}</div>'
# Timestamp + alert dot row
meta_parts = []
alert_lvl = msg.get("alert_level")
if alert_lvl is not None:
a_color = LEVEL_COLORS[alert_lvl]
a_emoji = LEVEL_EMOJIS[alert_lvl]
a_label = LEVEL_LABELS[alert_lvl]
meta_parts.append(
f'<span class="alert-dot" style="color:{a_color};">{a_emoji} {a_label.capitalize()}</span>'
)
if ts:
meta_parts.append(f'<span style="opacity:0.5;">{ts}</span>')
if meta_parts:
msgs_html += (
f'<div class="chat-time-assistant" style="color:{t["text_muted"]};">'
f'{" · ".join(meta_parts)}</div>'
)
msgs_html += '</div>'
st.markdown(msgs_html, unsafe_allow_html=True)
def render_gauge(level: int, confidence: float, S: dict, theme: str = "light"):
"""Circular alert-level gauge using Plotly. / Jauge circulaire du niveau d'alerte."""
color = LEVEL_COLORS[level]
label = S["level_labels"][level]
emoji = LEVEL_EMOJIS[level]
font_color = "#000000" if theme == "light" else "#ffffff"
fig = go.Figure(go.Indicator(
mode="gauge+number+delta",
value=level,
number={"suffix": f" {emoji}", "font": {"size": 28, "color": font_color}},
title={"text": f'{S["gauge_title"]}<br><b>{label}</b>', "font": {"size": 14, "color": font_color}},
gauge={
"axis": {
"range": [0, 4],
"tickvals": [0, 1, 2, 3],
"ticktext": S["gauge_ticks"],
"tickfont": {"size": 10, "color": font_color},
},
"bar": {"color": color, "thickness": 0.3},
"bgcolor": "white",
"borderwidth": 2,
"bordercolor": "#ccc",
"steps": [
{"range": [0, 1], "color": "#7dcea0"},
{"range": [1, 2], "color": "#f7dc6f"},
{"range": [2, 3], "color": "#f0a959"},
{"range": [3, 4], "color": "#e74c3c"},
],
"threshold": {
"line": {"color": color, "width": 4},
"thickness": 0.75,
"value": level,
},
},
))
fig.update_layout(
height=220,
margin=dict(t=30, b=10, l=20, r=20),
paper_bgcolor="rgba(0,0,0,0)",
font={"color": font_color},
)
st.plotly_chart(fig, use_container_width=True, config={"displayModeBar": False})
# Confidence bar / Barre de confiance
st.markdown(f'{S["confidence"]} : {confidence:.0%}')
st.progress(confidence)
def render_proba_bars(probabilities: dict, S: dict, level: int = 0):
"""Class probability bars. / Barres de probabilité par classe."""
if not probabilities:
color = LEVEL_COLORS[level]
emoji = LEVEL_EMOJIS[level]
label = S["level_labels"][level]
st.markdown(S["proba_header"])
st.markdown(
f'<div class="status-card" style="background:{color}22;border-left-color:{color};">'
f'{emoji} <b>{label}</b> — safety rule override</div>',
unsafe_allow_html=True,
)
return
st.markdown(S["proba_header"])
for label_name, proba in probabilities.items():
level_num = {"green": 0, "yellow": 1, "orange": 2, "red": 3}[label_name]
color = LEVEL_COLORS[level_num]
emoji = LEVEL_EMOJIS[level_num]
bar_width = int(proba * 100)
display_name = S["proba_names"].get(label_name, label_name.capitalize())
st.markdown(
f'<div style="margin:3px 0;">'
f'{emoji} <b>{display_name}</b> '
f'<span style="float:right">{proba:.0%}</span>'
f'<div class="proba-bar-track" style="border-radius:4px;height:8px;margin-top:2px;">'
f'<div style="background:{color};width:{bar_width}%;height:8px;border-radius:4px;"></div>'
f'</div></div>',
unsafe_allow_html=True,
)
def render_longitudinal_section(tracker: SessionTracker, user_id: str, S: dict, theme: str = "light"):
"""
Longitudinal history section: bar chart + trend + recommendation.
Section historique longitudinal : barres + tendance + recommandation.
"""
history = tracker.get_user_history(user_id, last_n_sessions=7)
risk = tracker.get_longitudinal_risk(user_id)
n = risk["sessions_analyzed"]
if n == 0:
st.caption(S["longitudinal_empty"])
return