Venkatesh Rajagopal commited on
Commit
4ae4ae8
·
1 Parent(s): baa0948

REFRAME: live CBT studio — fine-tuned Gemma 12B on Modal + Cohere voice (ZeroGPU)

Browse files
README.md CHANGED
@@ -1,15 +1,58 @@
1
  ---
2
- title: Reframe
3
- emoji: 🦀
4
- colorFrom: red
5
- colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 6.18.0
8
- python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
11
  license: gemma
12
- short_description: '**Reframe your thinking.** A live cognitive thinking tool.'
 
 
 
 
 
 
 
13
  ---
14
 
15
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: REFRAME
3
+ emoji: 🧠
4
+ colorFrom: purple
5
+ colorTo: indigo
6
  sdk: gradio
 
 
7
  app_file: app.py
8
  pinned: false
9
  license: gemma
10
+ # ⚠️ CONFIRM the exact track/badge tag strings on the Field Guide before submitting:
11
+ # https://build-small-hackathon-field-guide.hf.space/#rules (REQ-06)
12
+ tags:
13
+ - build-small-hackathon
14
+ - track-backyard-ai
15
+ - badge-well-tuned
16
+ - badge-llama-champion
17
+ - badge-off-the-grid
18
  ---
19
 
20
+ # REFRAME — a live CBT studio
21
+
22
+ **Reframe your thinking.** A live cognitive restructuring studio — talk through an unhelpful thought
23
+ (**by voice or text**) and watch it turn into a fairer, kinder one, live. The chat is a **Gemma 4 12B**
24
+ model **fine-tuned on ~42,000 therapy conversations** (QLoRA on **Modal** · H100), running locally via
25
+ **llama.cpp**; your voice is transcribed by **Cohere Transcribe**. Small models, fully on-device — no cloud APIs.
26
+ A Thought Card builds the cognitive-restructuring record in real time (distortion → evidence → your
27
+ balanced reframe), saved to a deck with a pattern tracker.
28
+
29
+ **Track:** Backyard AI — a real problem (rumination / unhelpful thinking), honestly fit to the small-model constraint.
30
+
31
+ ## How it works
32
+ 1. **Speak** a thought → **Cohere Transcribe** turns it into text.
33
+ 2. The **fine-tuned Gemma** reflects it back and asks Socratic questions.
34
+ 3. A **Thought Card** tags the distortion, gathers evidence, and you write the **balanced thought** — it's yours, so it sticks.
35
+ 4. Cards save to your **Deck**; the **Patterns** tab shows what recurs over time.
36
+
37
+ ## Tech (all ≤ 32B, runs locally)
38
+ - **Chat:** `google/gemma-4-12B-it` (12B), **fine-tuned (QLoRA) on mental-health counseling, empathetic-dialogue & crisis-response data** → published on the Hub.
39
+ - **Training:** **Modal**, single **NVIDIA H100 80GB** (unsloth · peft · trl · bitsandbytes).
40
+ - **Inference:** merged **GGUF Q4_K_M**, run by **llama.cpp** (Ollama locally / llama-cpp-python on the Space).
41
+ - **Voice:** **Cohere Transcribe** (`CohereLabs/cohere-transcribe-03-2026`) — on **ZeroGPU** here, Intel Arc XPU locally.
42
+ - **UI:** custom Gradio theme; private by design (no cloud APIs).
43
+
44
+ ## Badges
45
+ - ✅ **Well-Tuned** — fine-tuned, published model
46
+ - ✅ **Llama Champion** — llama.cpp runtime
47
+ - ✅ **Off the Grid** — no cloud APIs; all inference local/self-hosted
48
+ - *(Off-Brand: verify it qualifies — needs custom UI beyond default Gradio)*
49
+
50
+ ## Links
51
+ - 🎥 **Demo video:** <ADD LINK>
52
+ - 📣 **Social post:** <ADD LINK>
53
+ - 🤖 **Model:** https://huggingface.co/emailvenky/gemma4-mentalhealthbuddy-v1
54
+
55
+ ## Note
56
+ A supportive tool, not a replacement for professional care. If a message signals crisis, REFRAME surfaces helplines immediately.
57
+
58
+ — Created with 🍁 in Canada
app.py ADDED
@@ -0,0 +1,607 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """REFRAME — Live cognitive restructuring studio.
2
+
3
+ Main Gradio 6 application. Dual-panel: chat + live thought card.
4
+ """
5
+
6
+ # ZeroGPU: `spaces` MUST be imported before torch (it patches torch for GPU
7
+ # scheduling). On a ZeroGPU Space the real package is present; locally it isn't,
8
+ # so we fall back to a no-op shim and every Space branch becomes dead code.
9
+ try:
10
+ import spaces # noqa: E402 (intentionally first — before torch)
11
+ except ImportError:
12
+ class _SpacesShim:
13
+ @staticmethod
14
+ def GPU(*args, **kwargs):
15
+ # Support both @spaces.GPU and @spaces.GPU(duration=...)
16
+ if len(args) == 1 and callable(args[0]) and not kwargs:
17
+ return args[0]
18
+ def _decorator(fn):
19
+ return fn
20
+ return _decorator
21
+
22
+ spaces = _SpacesShim()
23
+
24
+ import os
25
+ import warnings
26
+ from pathlib import Path
27
+
28
+ import gradio as gr
29
+
30
+ import config
31
+ import inference
32
+ from atmosphere import detect_emotion
33
+ from card_engine import ActiveCard, CardState, reset_card, should_show_card, update_card
34
+ from components.card_deck import render_deck
35
+ from components.thought_card import render_card, render_empty_card, render_intro_card
36
+ from crisis import detect_crisis, get_crisis_banner_html, get_crisis_response
37
+ from patterns import get_patterns_html
38
+ from prompts import build_system_prompt, get_greeting
39
+ from session import (
40
+ Experiment,
41
+ SessionState,
42
+ ThoughtCard,
43
+ deserialize_session,
44
+ get_session_context,
45
+ save_card,
46
+ save_experiment,
47
+ serialize_session,
48
+ start_new_session,
49
+ )
50
+
51
+ # --- Optional STT import (fail-safe) ---
52
+ try:
53
+ import stt
54
+ _stt_available = config.STT_ENABLED and stt.is_available()
55
+ except ImportError:
56
+ _stt_available = False
57
+
58
+ # Silence a noisy (harmless) third-party deprecation: Gradio 6.18 uses Starlette's
59
+ # old HTTP_422_UNPROCESSABLE_ENTITY constant (renamed to *_CONTENT). Fires on every
60
+ # request. Remove once Gradio ships a fix.
61
+ warnings.filterwarnings("ignore", message=r".*HTTP_422_UNPROCESSABLE_ENTITY.*")
62
+
63
+ # Load CSS
64
+ CSS_PATH = Path(__file__).parent / "static" / "theme.css"
65
+ CUSTOM_CSS = CSS_PATH.read_text() if CSS_PATH.exists() else ""
66
+
67
+
68
+ def _model_badges_html() -> str:
69
+ """Header status pills — [label] · [exact id], ordered Modal → Gemma → Cohere."""
70
+ stt_lower = config.STT_MODEL.lower()
71
+ if "cohere" in stt_lower:
72
+ stt_name, stt_cls = "Cohere", "model-badge badge-cohere"
73
+ elif "whisper" in stt_lower:
74
+ stt_name, stt_cls = "Whisper", "model-badge"
75
+ else:
76
+ stt_name, stt_cls = "STT", "model-badge"
77
+ return f"""
78
+ <div class="model-badges">
79
+ <span class="model-badge badge-modal" title="Training platform · single GPU">
80
+ <span class="badge-dot"></span>Modal · NVIDIA H100 80GB
81
+ </span>
82
+ <span class="model-badge" title="Runtime: {config.OLLAMA_MODEL} (Ollama / llama.cpp)">
83
+ <span class="badge-dot"></span>Gemma 4 12B · google/gemma-4-12B-it · QLoRA fine-tuned
84
+ </span>
85
+ <span class="{stt_cls}" title="Speech-to-text (active)">
86
+ <span class="badge-dot"></span>{stt_name} · {config.STT_MODEL}
87
+ </span>
88
+ </div>
89
+ """
90
+
91
+
92
+ def _models_card_html() -> str:
93
+ """Tech-stack / models showcase for the right pane (prize transparency)."""
94
+ return """
95
+ <div class="stack-card">
96
+ <div class="stack-summary">
97
+ A fine-tuned Gemma model that helps you reframe thoughts — trained in the cloud, runs locally.
98
+ </div>
99
+ <div class="stack-line"><b>Gemma 4 12B</b> — Google's open LLM, fine-tuned on mental-health counseling data</div>
100
+ <div class="stack-line"><b>QLoRA + unsloth</b> — efficient, low-cost fine-tuning</div>
101
+ <div class="stack-line"><b>Modal · H100 80GB</b> — cloud GPU the training ran on</div>
102
+ <div class="stack-line"><b>GGUF Q4_K_M</b> — compact, quantized model file</div>
103
+ <div class="stack-line"><b>llama.cpp</b> — runs the model locally, low latency</div>
104
+ <div class="stack-line"><b>Ollama</b> — serves llama.cpp as a local API</div>
105
+ <div class="stack-line"><b>Cohere Transcribe</b> — turns your voice into text</div>
106
+ <div class="stack-line"><b>Gradio</b> — the app's web interface</div>
107
+ <div class="stack-line"><b>Fine-tuning datasets</b> — mental-health counseling, empathetic dialogue &amp; crisis responses
108
+ <ul class="stack-list">
109
+ <li><a href="https://huggingface.co/datasets/ShenLab/MentalChat16K" target="_blank">MentalChat16K</a></li>
110
+ <li><a href="https://huggingface.co/datasets/Amod/mental_health_counseling_conversations" target="_blank">Mental Health Counseling Conversations</a></li>
111
+ <li><a href="https://huggingface.co/datasets/nbertagnolli/counsel-chat" target="_blank">CounselChat</a></li>
112
+ <li><a href="https://huggingface.co/datasets/Estwld/empathetic_dialogues_llm" target="_blank">EmpatheticDialogues</a></li>
113
+ <li><a href="https://huggingface.co/datasets/arnaiztech/llms-mental-health-crisis-responses" target="_blank">Mental-Health Crisis Responses</a></li>
114
+ </ul>
115
+ </div>
116
+ </div>
117
+ """
118
+
119
+ # --- Status animation HTML (wave for STT, dots for thinking) ---
120
+ WAVE_HTML = """
121
+ <div style="display:flex;align-items:center;gap:8px;padding:8px 12px;
122
+ background:#1a1a2e;border-radius:8px;border:1px solid #2a2a4a;">
123
+ <div style="display:flex;gap:3px;align-items:end;height:20px;">
124
+ <span style="width:3px;background:#a78bfa;border-radius:2px;
125
+ animation:wave 0.8s ease-in-out infinite;height:8px;"></span>
126
+ <span style="width:3px;background:#a78bfa;border-radius:2px;
127
+ animation:wave 0.8s ease-in-out 0.1s infinite;height:14px;"></span>
128
+ <span style="width:3px;background:#a78bfa;border-radius:2px;
129
+ animation:wave 0.8s ease-in-out 0.2s infinite;height:20px;"></span>
130
+ <span style="width:3px;background:#a78bfa;border-radius:2px;
131
+ animation:wave 0.8s ease-in-out 0.3s infinite;height:14px;"></span>
132
+ <span style="width:3px;background:#a78bfa;border-radius:2px;
133
+ animation:wave 0.8s ease-in-out 0.4s infinite;height:8px;"></span>
134
+ </div>
135
+ <span style="color:#c4b5fd;font-size:0.85rem;">Transcribing your voice...</span>
136
+ </div>
137
+ <style>
138
+ @keyframes wave{0%,100%{transform:scaleY(0.4)}50%{transform:scaleY(1)}}
139
+ </style>
140
+ """
141
+
142
+ DOTS_HTML = """
143
+ <div style="display:flex;align-items:center;gap:8px;padding:8px 12px;
144
+ background:#1a1a2e;border-radius:8px;border:1px solid #2a2a4a;">
145
+ <div style="display:flex;gap:4px;">
146
+ <span style="width:6px;height:6px;background:#8899aa;border-radius:50%;
147
+ animation:dots 1.2s ease-in-out infinite;"></span>
148
+ <span style="width:6px;height:6px;background:#8899aa;border-radius:50%;
149
+ animation:dots 1.2s ease-in-out 0.2s infinite;"></span>
150
+ <span style="width:6px;height:6px;background:#8899aa;border-radius:50%;
151
+ animation:dots 1.2s ease-in-out 0.4s infinite;"></span>
152
+ </div>
153
+ <span style="color:#8899aa;font-size:0.85rem;">Thinking...</span>
154
+ </div>
155
+ <style>
156
+ @keyframes dots{0%,100%{opacity:0.3;transform:scale(0.8)}50%{opacity:1;transform:scale(1.2)}}
157
+ </style>
158
+ """
159
+
160
+
161
+ def _show_wave():
162
+ return gr.update(value=WAVE_HTML, visible=True)
163
+
164
+
165
+ def _show_dots():
166
+ return gr.update(value=DOTS_HTML, visible=True)
167
+
168
+
169
+ def _hide_status():
170
+ return gr.update(value="", visible=False)
171
+
172
+
173
+ @spaces.GPU(duration=120)
174
+ def _transcribe_and_clear(audio_filepath):
175
+ """Transcribe audio, return (text_for_input, None_to_clear_audio).
176
+
177
+ On a ZeroGPU Space this runs in a GPU-allocated fork (Cohere on CUDA);
178
+ locally @spaces.GPU is a no-op shim and STT runs on XPU/CPU.
179
+ """
180
+ if not audio_filepath or not _stt_available:
181
+ return "Couldn't hear that — try typing instead.", None
182
+ text = stt.transcribe(audio_filepath)
183
+ if not text:
184
+ return "Couldn't hear that — try typing instead.", None
185
+ return text, None
186
+
187
+
188
+ def respond(
189
+ history: list[dict],
190
+ session_json: str,
191
+ card_state_json: str,
192
+ ):
193
+ """Main chat response handler with streaming.
194
+
195
+ Yields: (history, card_html, atmosphere_class, crisis_html, session_json, card_state_json)
196
+ """
197
+ # Get the user message from the last history entry (already added by user_submit)
198
+ if not history:
199
+ yield history, render_empty_card(), "atmosphere-neutral", "", session_json, card_state_json
200
+ return
201
+
202
+ last_entry = history[-1]
203
+ # Handle both dict format and possible list/tuple format
204
+ if isinstance(last_entry, dict):
205
+ raw_content = last_entry.get("content", "")
206
+ elif isinstance(last_entry, (list, tuple)):
207
+ raw_content = last_entry[0] if last_entry else ""
208
+ else:
209
+ raw_content = str(last_entry)
210
+
211
+ # Content may be a list of part-dicts in Gradio 6, e.g. {"text": ..., "type": "text"}.
212
+ # Extract the text field rather than str()-ing the whole dict.
213
+ if isinstance(raw_content, list):
214
+ parts = []
215
+ for part in raw_content:
216
+ if isinstance(part, dict):
217
+ parts.append(str(part.get("text", "")))
218
+ elif part:
219
+ parts.append(str(part))
220
+ user_message = " ".join(p for p in parts if p).strip()
221
+ else:
222
+ user_message = str(raw_content) if raw_content else ""
223
+
224
+ if not user_message.strip():
225
+ yield history, render_empty_card(), "atmosphere-neutral", "", session_json, card_state_json
226
+ return
227
+
228
+ # Deserialize state
229
+ session = deserialize_session(session_json)
230
+ active_card = _deserialize_card_state(card_state_json)
231
+
232
+ # Build system prompt with session context
233
+ context = get_session_context(session)
234
+ system_prompt = build_system_prompt(context)
235
+
236
+ # Check for crisis
237
+ crisis_html = ""
238
+ if detect_crisis(user_message):
239
+ crisis_html = get_crisis_banner_html()
240
+
241
+ # Stream model response (history already has user message from user_submit)
242
+ full_response = ""
243
+ for partial in inference.stream_response(user_message, history[:-1], system_prompt):
244
+ full_response = partial
245
+
246
+ # Update card engine
247
+ active_card = update_card(active_card, full_response, user_message)
248
+ card_html_val = render_card(active_card) if should_show_card(active_card) else render_empty_card()
249
+
250
+ # Detect atmosphere
251
+ atmos = detect_emotion(user_message + " " + full_response)
252
+
253
+ # Build current history with streaming response
254
+ current_history = history + [{"role": "assistant", "content": full_response}]
255
+
256
+ yield (
257
+ current_history,
258
+ card_html_val,
259
+ atmos,
260
+ crisis_html,
261
+ serialize_session(session),
262
+ _serialize_card_state(active_card),
263
+ )
264
+
265
+ # If card completed, save it
266
+ if active_card.state == CardState.COMPLETE:
267
+ session = save_card(session, active_card.card)
268
+ active_card = reset_card()
269
+
270
+ # Final yield
271
+ card_html_val = render_card(active_card) if should_show_card(active_card) else render_empty_card()
272
+ final_history = history + [{"role": "assistant", "content": full_response}]
273
+ yield (
274
+ final_history,
275
+ card_html_val,
276
+ detect_emotion(user_message + " " + full_response),
277
+ crisis_html,
278
+ serialize_session(session),
279
+ _serialize_card_state(active_card),
280
+ )
281
+
282
+
283
+ def initialize_session(session_json: str):
284
+ """Called on app load — initialize or resume session."""
285
+ session = deserialize_session(session_json)
286
+ session = start_new_session(session)
287
+ greeting = get_greeting(get_session_context(session))
288
+ history = [{"role": "assistant", "content": greeting}]
289
+ return history, serialize_session(session)
290
+
291
+
292
+ def get_deck_html(session_json: str) -> str:
293
+ """Render the card deck from session state."""
294
+ session = deserialize_session(session_json)
295
+ return render_deck(session.cards)
296
+
297
+
298
+ def get_progress_html(session_json: str) -> str:
299
+ """Render the patterns/progress panel."""
300
+ session = deserialize_session(session_json)
301
+ return get_patterns_html(session)
302
+
303
+
304
+ def save_current_card(session_json: str, card_state_json: str):
305
+ """Manually save the current card to deck."""
306
+ session = deserialize_session(session_json)
307
+ active_card = _deserialize_card_state(card_state_json)
308
+
309
+ if active_card.state != CardState.IDLE and active_card.card.automatic_thought:
310
+ session = save_card(session, active_card.card)
311
+ active_card = reset_card()
312
+
313
+ return (
314
+ serialize_session(session),
315
+ _serialize_card_state(active_card),
316
+ render_empty_card(),
317
+ render_deck(session.cards),
318
+ )
319
+
320
+
321
+ # --- Card state serialization helpers ---
322
+
323
+ def _serialize_card_state(active: ActiveCard) -> str:
324
+ """Serialize ActiveCard to JSON string."""
325
+ import json
326
+ from dataclasses import asdict
327
+ return json.dumps({
328
+ "state": active.state.value,
329
+ "card": asdict(active.card),
330
+ "turn_count": active.turn_count,
331
+ })
332
+
333
+
334
+ def _deserialize_card_state(data: str | None) -> ActiveCard:
335
+ """Deserialize ActiveCard from JSON string."""
336
+ import json
337
+ if not data:
338
+ return ActiveCard()
339
+ try:
340
+ d = json.loads(data) if isinstance(data, str) else data
341
+ card = ThoughtCard(**d.get("card", {}))
342
+ state = CardState(d.get("state", "idle"))
343
+ return ActiveCard(state=state, card=card, turn_count=d.get("turn_count", 0))
344
+ except (json.JSONDecodeError, TypeError, ValueError):
345
+ return ActiveCard()
346
+
347
+
348
+ # --- Build the Gradio App ---
349
+
350
+ with gr.Blocks(
351
+ title=config.APP_TITLE,
352
+ fill_height=True,
353
+ fill_width=True,
354
+ ) as demo:
355
+
356
+ # Hidden state components
357
+ session_state = gr.BrowserState("", storage_key="reframe_session")
358
+ card_state = gr.State("")
359
+ atmosphere_state = gr.State("atmosphere-neutral")
360
+
361
+ # Top-center credit
362
+ gr.HTML('<div class="app-credit">Created with 🍁 in Canada</div>')
363
+
364
+ # Header — title, subtitle, then model pills (horizontal, after the string)
365
+ with gr.Row():
366
+ gr.HTML(f"""
367
+ <div class="app-header">
368
+ <div class="app-title">{config.APP_TITLE}</div>
369
+ <div class="app-subtitle-row">
370
+ <div class="app-subtitle">{config.APP_SUBTITLE}</div>
371
+ {_model_badges_html()}
372
+ </div>
373
+ </div>
374
+ """)
375
+
376
+ # Main layout: Chat (60%) + Card Panel (40%)
377
+ with gr.Row():
378
+ # Left: Chat
379
+ with gr.Column(scale=3):
380
+ chatbot = gr.Chatbot(
381
+ elem_id="reframe-chat",
382
+ height=430,
383
+ show_label=False,
384
+ placeholder="What's on your mind today?",
385
+ buttons=["copy"],
386
+ )
387
+ msg_input = gr.Textbox(
388
+ placeholder="Type here...",
389
+ show_label=False,
390
+ container=False,
391
+ scale=7,
392
+ submit_btn=True,
393
+ )
394
+ # Voice input (only if STT deps available)
395
+ if _stt_available:
396
+ _voice_label = (
397
+ "🎙️ Speak your thoughts — powered by Cohere"
398
+ if "cohere" in config.STT_MODEL.lower()
399
+ else "🎤 Or speak your thoughts"
400
+ )
401
+ audio_input = gr.Audio(
402
+ sources=["microphone"],
403
+ type="filepath",
404
+ label=_voice_label,
405
+ show_label=True,
406
+ )
407
+ voice_status = gr.HTML(value="", visible=False)
408
+ else:
409
+ audio_input = None
410
+ voice_status = None
411
+
412
+ # Right: tabs at top (How it works default); live card lives in the Deck tab
413
+ with gr.Column(scale=2, min_width=280):
414
+ # Crisis banner (hidden by default) — kept above tabs so it always shows
415
+ crisis_html = gr.HTML(value="")
416
+ with gr.Tabs():
417
+ with gr.Tab("How it works"):
418
+ gr.HTML(value=render_intro_card())
419
+ with gr.Tab("🛠️ Stack"):
420
+ gr.HTML(value=_models_card_html())
421
+ with gr.Tab("Deck"):
422
+ card_html = gr.HTML(value=render_empty_card())
423
+ save_btn = gr.Button("✨ Save to Deck", variant="secondary", size="sm")
424
+ deck_html = gr.HTML(value="")
425
+ with gr.Tab("Patterns"):
426
+ patterns_html_component = gr.HTML(value="")
427
+
428
+ # --- Event Wiring ---
429
+
430
+ # Helper to add user msg to chat immediately and clear input
431
+ def user_submit(message, history):
432
+ """Immediately show user message and clear input."""
433
+ if not message or not message.strip():
434
+ return "", history
435
+ return "", history + [{"role": "user", "content": message}]
436
+
437
+ # Main chat submit: clear input + show msg instantly, then stream response
438
+ submit_event = msg_input.submit(
439
+ fn=user_submit,
440
+ inputs=[msg_input, chatbot],
441
+ outputs=[msg_input, chatbot],
442
+ ).then(
443
+ fn=lambda: gr.update(interactive=False),
444
+ outputs=[msg_input],
445
+ ).then(
446
+ fn=respond,
447
+ inputs=[chatbot, session_state, card_state],
448
+ outputs=[chatbot, card_html, atmosphere_state, crisis_html, session_state, card_state],
449
+ ).then(
450
+ fn=lambda: gr.update(interactive=True),
451
+ outputs=[msg_input],
452
+ )
453
+
454
+ # Voice input: record → transcribe (with wave) → submit → respond (with dots)
455
+ if _stt_available and audio_input is not None:
456
+ audio_input.stop_recording(
457
+ fn=_show_wave,
458
+ outputs=[voice_status],
459
+ ).then(
460
+ fn=_transcribe_and_clear,
461
+ inputs=[audio_input],
462
+ outputs=[msg_input, audio_input],
463
+ ).then(
464
+ fn=user_submit,
465
+ inputs=[msg_input, chatbot],
466
+ outputs=[msg_input, chatbot],
467
+ ).then(
468
+ fn=_show_dots,
469
+ outputs=[voice_status],
470
+ ).then(
471
+ fn=lambda: gr.update(interactive=False),
472
+ outputs=[msg_input],
473
+ ).then(
474
+ fn=respond,
475
+ inputs=[chatbot, session_state, card_state],
476
+ outputs=[chatbot, card_html, atmosphere_state, crisis_html, session_state, card_state],
477
+ ).then(
478
+ fn=lambda: gr.update(interactive=True),
479
+ outputs=[msg_input],
480
+ ).then(
481
+ fn=_hide_status,
482
+ outputs=[voice_status],
483
+ )
484
+
485
+ # Save card button
486
+ save_btn.click(
487
+ fn=save_current_card,
488
+ inputs=[session_state, card_state],
489
+ outputs=[session_state, card_state, card_html, deck_html],
490
+ )
491
+
492
+ # Refresh deck/patterns when tabs are clicked
493
+ deck_html.change(fn=None) # placeholder
494
+
495
+ # Initialize on load
496
+ demo.load(
497
+ fn=initialize_session,
498
+ inputs=[session_state],
499
+ outputs=[chatbot, session_state],
500
+ )
501
+
502
+ # Refresh deck and patterns on session change
503
+ session_state.change(
504
+ fn=get_deck_html,
505
+ inputs=[session_state],
506
+ outputs=[deck_html],
507
+ )
508
+ session_state.change(
509
+ fn=get_progress_html,
510
+ inputs=[session_state],
511
+ outputs=[patterns_html_component],
512
+ )
513
+
514
+
515
+ if __name__ == "__main__":
516
+ # Preload the STT model locally for an instant first response. On a Space we
517
+ # SKIP preload so the app starts immediately (no startup timeout downloading
518
+ # ~4 GB); the model then loads lazily on the first transcription, inside the
519
+ # @spaces.GPU context on ZeroGPU.
520
+ if _stt_available and not os.environ.get("SPACE_ID"):
521
+ stt.preload_model()
522
+
523
+ demo.launch(
524
+ server_name="0.0.0.0",
525
+ server_port=7860,
526
+ share=False,
527
+ css=CUSTOM_CSS,
528
+ head="""
529
+ <style>
530
+ /* Audio device selector — prevent truncation */
531
+ [data-testid="audio"] select,
532
+ [data-testid="audio"] .audio-source-select,
533
+ [data-testid="audio"] button[aria-label*="microphone"],
534
+ .audio-component select {
535
+ min-width: 180px !important;
536
+ max-width: 250px !important;
537
+ }
538
+ #reframe-chat .placeholder {
539
+ font-size: 2.5rem !important;
540
+ font-family: 'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', cursive !important;
541
+ color: #a78bfa !important;
542
+ opacity: 1 !important;
543
+ font-weight: 700 !important;
544
+ background: transparent !important;
545
+ border: none !important;
546
+ box-shadow: none !important;
547
+ }
548
+ #reframe-chat .placeholder * {
549
+ font-size: inherit !important;
550
+ font-family: inherit !important;
551
+ color: inherit !important;
552
+ background: transparent !important;
553
+ }
554
+ </style>
555
+ <script>
556
+ // Force-style placeholder after Gradio renders
557
+ function stylePlaceholder() {
558
+ const el = document.querySelector('#reframe-chat .placeholder');
559
+ if (el) {
560
+ el.style.fontSize = '2.5rem';
561
+ el.style.fontFamily = "'Comic Sans MS', 'Chalkboard SE', cursive";
562
+ el.style.color = '#a78bfa';
563
+ el.style.opacity = '1';
564
+ el.style.fontWeight = '700';
565
+ el.style.background = 'transparent';
566
+ el.style.border = 'none';
567
+ el.style.boxShadow = 'none';
568
+ el.querySelectorAll('*').forEach(c => {
569
+ c.style.fontSize = 'inherit';
570
+ c.style.fontFamily = 'inherit';
571
+ c.style.color = 'inherit';
572
+ c.style.background = 'transparent';
573
+ });
574
+ }
575
+ }
576
+ setTimeout(stylePlaceholder, 500);
577
+ setTimeout(stylePlaceholder, 1500);
578
+ new MutationObserver(stylePlaceholder).observe(document.body, {childList: true, subtree: true});
579
+
580
+ // Explicitly request microphone permission on first user interaction
581
+ let micRequested = false;
582
+ function requestMic() {
583
+ if (micRequested) return;
584
+ micRequested = true;
585
+ if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
586
+ navigator.mediaDevices.getUserMedia({ audio: true })
587
+ .then(stream => {
588
+ console.log('Microphone access granted');
589
+ stream.getTracks().forEach(t => t.stop());
590
+ })
591
+ .catch(err => {
592
+ console.warn('Microphone access denied:', err.message);
593
+ const audioEl = document.querySelector('[data-testid="audio"]');
594
+ if (audioEl) {
595
+ audioEl.style.opacity = '0.5';
596
+ audioEl.title = 'Microphone blocked — check browser permissions';
597
+ }
598
+ });
599
+ }
600
+ }
601
+ // Trigger on first click anywhere (browsers require user gesture)
602
+ document.addEventListener('click', requestMic, { once: true });
603
+ // Also try on page load (works if permission was previously granted)
604
+ setTimeout(requestMic, 2000);
605
+ </script>
606
+ """,
607
+ )
atmosphere.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Atmosphere — maps emotional tone to CSS classes for ambient background."""
2
+
3
+ from __future__ import annotations
4
+
5
+ EMOTION_KEYWORDS: dict[str, list[str]] = {
6
+ "anxious": [
7
+ "anxious", "worried", "nervous", "panic", "dread",
8
+ "scared", "fear", "terrified", "overwhelmed", "racing",
9
+ ],
10
+ "sad": [
11
+ "sad", "depressed", "hopeless", "empty", "lonely",
12
+ "grief", "loss", "crying", "worthless", "numb",
13
+ ],
14
+ "angry": [
15
+ "angry", "furious", "frustrated", "rage", "irritated",
16
+ "resentful", "unfair", "hate",
17
+ ],
18
+ "calm": [
19
+ "calm", "peaceful", "relaxed", "okay", "better",
20
+ "relieved", "content", "grateful",
21
+ ],
22
+ "breakthrough": [
23
+ "realize", "never thought of it", "that makes sense",
24
+ "you're right", "actually", "huh", "wow",
25
+ "i see", "that's true",
26
+ ],
27
+ }
28
+
29
+
30
+ def detect_emotion(text: str) -> str:
31
+ """Detect dominant emotional tone from conversation text.
32
+
33
+ Returns CSS class name for the atmosphere gradient.
34
+ """
35
+ text_lower = text.lower()
36
+ scores: dict[str, int] = {}
37
+
38
+ for emotion, keywords in EMOTION_KEYWORDS.items():
39
+ score = sum(1 for kw in keywords if kw in text_lower)
40
+ if score > 0:
41
+ scores[emotion] = score
42
+
43
+ if not scores:
44
+ return "atmosphere-neutral"
45
+
46
+ dominant = max(scores, key=scores.get)
47
+ return f"atmosphere-{dominant}"
card_engine.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Card engine — state machine that builds a thought card from conversation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from enum import Enum
7
+
8
+ from distortion_parser import detect_distortions
9
+ from phase_detector import detect_phase
10
+ from session import ThoughtCard
11
+
12
+
13
+ class CardState(Enum):
14
+ IDLE = "idle"
15
+ TRIGGERED = "triggered"
16
+ DISTORTION_TAGGED = "distortion_tagged"
17
+ EVIDENCE_GATHERING = "evidence_gathering"
18
+ REFRAMING = "reframing"
19
+ COMPLETE = "complete"
20
+
21
+
22
+ @dataclass
23
+ class ActiveCard:
24
+ """Represents a card being built during conversation."""
25
+ state: CardState = CardState.IDLE
26
+ card: ThoughtCard = field(default_factory=ThoughtCard)
27
+ turn_count: int = 0 # turns since card was triggered
28
+
29
+
30
+ def update_card(active: ActiveCard, model_response: str, user_message: str) -> ActiveCard:
31
+ """Update the active card based on model response and user message.
32
+
33
+ This is called after each model response. It advances the card state machine.
34
+ """
35
+ active.turn_count += 1
36
+
37
+ # Detect distortions in model output
38
+ distortions = detect_distortions(model_response)
39
+ if distortions:
40
+ for d in distortions:
41
+ if d not in active.card.distortions:
42
+ active.card.distortions.append(d)
43
+
44
+ # Detect phase
45
+ phase = detect_phase(model_response)
46
+
47
+ # State transitions
48
+ if active.state == CardState.IDLE:
49
+ # Card triggers when model reflects back a thought or names a distortion
50
+ if distortions or phase in ("automatic_thought", "situation"):
51
+ active.state = CardState.TRIGGERED
52
+ if user_message and not active.card.automatic_thought:
53
+ active.card.automatic_thought = _extract_thought(user_message)
54
+
55
+ elif active.state == CardState.TRIGGERED:
56
+ if distortions:
57
+ active.state = CardState.DISTORTION_TAGGED
58
+ elif phase in ("evidence_for", "evidence_against"):
59
+ active.state = CardState.EVIDENCE_GATHERING
60
+
61
+ elif active.state == CardState.DISTORTION_TAGGED:
62
+ if phase in ("evidence_for", "evidence_against"):
63
+ active.state = CardState.EVIDENCE_GATHERING
64
+
65
+ elif active.state == CardState.EVIDENCE_GATHERING:
66
+ # Accumulate evidence from user messages
67
+ if phase == "evidence_for" and user_message:
68
+ active.card.evidence_for.append(user_message[:120])
69
+ elif phase == "evidence_against" and user_message:
70
+ active.card.evidence_against.append(user_message[:120])
71
+ elif phase == "reframe":
72
+ active.state = CardState.REFRAMING
73
+
74
+ elif active.state == CardState.REFRAMING:
75
+ if user_message and not active.card.balanced_thought:
76
+ active.card.balanced_thought = user_message[:200]
77
+ active.state = CardState.COMPLETE
78
+
79
+ return active
80
+
81
+
82
+ def should_show_card(active: ActiveCard) -> bool:
83
+ """Whether the card should be visible in the UI."""
84
+ return active.state != CardState.IDLE
85
+
86
+
87
+ def reset_card() -> ActiveCard:
88
+ """Reset to a fresh card."""
89
+ return ActiveCard()
90
+
91
+
92
+ def _extract_thought(message: str) -> str:
93
+ """Extract the core thought from a user message (first 150 chars)."""
94
+ return message[:150].strip()
components/.___pycache__ ADDED
Binary file (4.1 kB). View file
 
components/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Components package."""
components/card_deck.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Render the card deck — gallery of completed thought cards."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ def render_deck(cards: list[dict]) -> str:
7
+ """Render the card deck as a scrollable gallery."""
8
+ if not cards:
9
+ return """
10
+ <div style="color:#5a6a7a; font-size:0.85rem; text-align:center; padding:20px;">
11
+ <p>Your deck is empty. Complete a thought record to add your first card.</p>
12
+ </div>
13
+ """
14
+
15
+ card_elements = []
16
+ for card in reversed(cards[-10:]): # Show last 10, newest first
17
+ distortions = card.get("distortions", [])
18
+ tag = distortions[0] if distortions else "—"
19
+ date = card.get("date", "")
20
+ thought = card.get("automatic_thought", "")[:40]
21
+ reframe = card.get("balanced_thought", "")[:40]
22
+
23
+ card_elements.append(f"""
24
+ <div style="flex-shrink:0; width:140px; background:#1e2a3a; border:1px solid rgba(255,255,255,0.08); border-radius:10px; padding:10px; font-size:0.75rem;">
25
+ <div style="color:#a78bfa; font-weight:600; font-size:0.7rem; margin-bottom:4px;">{tag}</div>
26
+ <div style="color:#5a6a7a; font-size:0.65rem; margin-bottom:6px;">{date}</div>
27
+ <div style="color:#8899aa; font-size:0.7rem; margin-bottom:4px;">"{thought}..."</div>
28
+ <div style="color:#22c55e; font-size:0.7rem; font-style:italic;">→ "{reframe}..."</div>
29
+ </div>
30
+ """)
31
+
32
+ return f"""
33
+ <div style="margin-top:16px;">
34
+ <div style="font-size:0.85rem; color:#8899aa; font-weight:600; margin-bottom:10px;">🃏 Your Deck ({len(cards)} cards)</div>
35
+ <div style="display:flex; gap:10px; overflow-x:auto; padding-bottom:8px;">
36
+ {''.join(card_elements)}
37
+ </div>
38
+ </div>
39
+ """
components/thought_card.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Render the live thought card as HTML."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from card_engine import ActiveCard, CardState
6
+
7
+
8
+ def render_card(active: ActiveCard) -> str:
9
+ """Render the thought card HTML based on current state."""
10
+ if active.state == CardState.IDLE:
11
+ return ""
12
+
13
+ card = active.card
14
+ sections = []
15
+
16
+ # Situation + Thought (always visible once triggered)
17
+ if active.state.value != "idle":
18
+ thought_text = card.automatic_thought or "..."
19
+ sections.append(f"""
20
+ <div style="margin-bottom:12px;">
21
+ <div style="font-size:0.7rem; font-weight:700; color:#5a6a7a; letter-spacing:1px; text-transform:uppercase; margin-bottom:4px;">AUTOMATIC THOUGHT</div>
22
+ <div style="font-size:0.9rem; color:#e8edf3; line-height:1.4;">"{thought_text}"</div>
23
+ </div>
24
+ """)
25
+
26
+ # Distortion tags
27
+ if card.distortions:
28
+ tags = "".join(
29
+ f'<span style="display:inline-block; background:rgba(139,92,246,0.2); border:1px solid rgba(139,92,246,0.4); border-radius:20px; padding:4px 12px; font-size:0.75rem; color:#a78bfa; font-weight:500; margin-right:6px; margin-bottom:4px;">{d}</span>'
30
+ for d in card.distortions
31
+ )
32
+ sections.append(f"""
33
+ <div style="margin-bottom:12px; display:flex; flex-wrap:wrap; gap:6px;">
34
+ {tags}
35
+ </div>
36
+ """)
37
+
38
+ # Evidence FOR
39
+ if card.evidence_for:
40
+ items = "".join(f'<li style="font-size:0.85rem; color:#e8edf3; padding:4px 0 4px 12px; border-left:2px solid rgba(255,255,255,0.08); margin-bottom:4px;">{e}</li>' for e in card.evidence_for)
41
+ sections.append(f"""
42
+ <div style="margin-bottom:12px;">
43
+ <div style="font-size:0.7rem; font-weight:700; color:#5a6a7a; letter-spacing:1px; text-transform:uppercase; margin-bottom:4px;">EVIDENCE FOR</div>
44
+ <ul style="list-style:none; padding:0; margin:0;">{items}</ul>
45
+ </div>
46
+ """)
47
+
48
+ # Evidence AGAINST
49
+ if card.evidence_against:
50
+ items = "".join(f'<li style="font-size:0.85rem; color:#e8edf3; padding:4px 0 4px 12px; border-left:2px solid rgba(255,255,255,0.08); margin-bottom:4px;">{e}</li>' for e in card.evidence_against)
51
+ sections.append(f"""
52
+ <div style="margin-bottom:12px;">
53
+ <div style="font-size:0.7rem; font-weight:700; color:#5a6a7a; letter-spacing:1px; text-transform:uppercase; margin-bottom:4px;">EVIDENCE AGAINST</div>
54
+ <ul style="list-style:none; padding:0; margin:0;">{items}</ul>
55
+ </div>
56
+ """)
57
+
58
+ # Balanced thought (reframe)
59
+ if card.balanced_thought:
60
+ sections.append(f"""
61
+ <div style="margin-bottom:12px;">
62
+ <div style="font-size:0.7rem; font-weight:700; color:#5a6a7a; letter-spacing:1px; text-transform:uppercase; margin-bottom:4px;">🔄 BALANCED THOUGHT</div>
63
+ <div style="font-size:0.9rem; color:#22c55e; line-height:1.4; font-style:italic;">"{card.balanced_thought}"</div>
64
+ </div>
65
+ """)
66
+
67
+ # Complete state
68
+ border_style = "border-color:rgba(34,197,94,0.5); box-shadow:0 0 20px rgba(34,197,94,0.15);" if active.state == CardState.COMPLETE else ""
69
+
70
+ return f"""
71
+ <div style="background:#1e2a3a; border:1px solid rgba(255,255,255,0.08); border-radius:12px; padding:16px; {border_style}">
72
+ <div style="font-size:0.85rem; color:#8899aa; margin-bottom:12px; font-weight:600; letter-spacing:0.5px;">📋 Live Thought Card</div>
73
+ {''.join(sections)}
74
+ </div>
75
+ """
76
+
77
+
78
+ def render_empty_card() -> str:
79
+ """Render a minimal waiting state after user starts chatting."""
80
+ return """
81
+ <div style="display:flex; flex-direction:column; align-items:center; justify-content:center; min-height:120px; text-align:center; padding:24px 16px;">
82
+ <div style="font-size:0.82rem; color:#8899aa; line-height:1.5; max-width:260px;">
83
+ Listening... a thought card will appear here once a thinking pattern is detected.
84
+ </div>
85
+ </div>
86
+ """
87
+
88
+
89
+ def render_intro_card() -> str:
90
+ """Render the benefit-focused 'how it helps you' explanation for the How it works tab."""
91
+ return """
92
+ <div style="padding:14px;">
93
+ <div style="font-size:0.95rem; font-weight:700; color:#e8edf3; margin-bottom:10px;">A calmer way to untangle your thoughts</div>
94
+
95
+ <div style="font-size:0.8rem; color:#8899aa; line-height:1.6; margin-bottom:14px;">
96
+ When you're caught in a worry or a harsh thought, it's hard to see it clearly from the inside.
97
+ REFRAME is a gentle, judgment-free space to talk it through — and watch an unhelpful thought
98
+ become a fairer, kinder one.
99
+ </div>
100
+
101
+ <div style="font-size:0.75rem; color:#8899aa; line-height:1.5; margin-bottom:10px;">
102
+ <strong style="color:#e8edf3;">How it helps you:</strong>
103
+ </div>
104
+
105
+ <div style="margin-bottom:8px; padding-left:8px; border-left:2px solid rgba(139,92,246,0.3);">
106
+ <div style="font-size:0.73rem; color:#a78bfa; font-weight:600;">See the thinking trap</div>
107
+ <div style="font-size:0.7rem; color:#8899aa;">It gently names patterns like catastrophizing or all-or-nothing thinking — the ones that are hard to spot in your own head.</div>
108
+ </div>
109
+
110
+ <div style="margin-bottom:8px; padding-left:8px; border-left:2px solid rgba(139,92,246,0.3);">
111
+ <div style="font-size:0.73rem; color:#a78bfa; font-weight:600;">Questions, not lectures</div>
112
+ <div style="font-size:0.7rem; color:#8899aa;">Rather than telling you what to think, it asks — what supports this thought, and what doesn't? You stay in control.</div>
113
+ </div>
114
+
115
+ <div style="margin-bottom:8px; padding-left:8px; border-left:2px solid rgba(139,92,246,0.3);">
116
+ <div style="font-size:0.73rem; color:#a78bfa; font-weight:600;">Reframes you actually believe</div>
117
+ <div style="font-size:0.7rem; color:#8899aa;">The balanced thought is yours, in your own words — which is exactly why it sticks with you.</div>
118
+ </div>
119
+
120
+ <div style="margin-bottom:8px; padding-left:8px; border-left:2px solid rgba(34,197,94,0.3);">
121
+ <div style="font-size:0.73rem; color:#22c55e; font-weight:600;">See yourself grow</div>
122
+ <div style="font-size:0.7rem; color:#8899aa;">Saved cards and your pattern tracker reveal what keeps coming up — and noticing is where change begins.</div>
123
+ </div>
124
+
125
+ <div style="margin-top:12px; padding:8px; background:rgba(139,92,246,0.05); border-radius:8px; font-size:0.7rem; color:#8899aa; line-height:1.5;">
126
+ 💬 Just talk — by voice or text. No jargon, no pressure. It's grounded in
127
+ <strong style="color:#a78bfa;">Cognitive Behavioral Therapy (CBT)</strong>, the most
128
+ evidence-based approach for reshaping unhelpful thinking.
129
+ </div>
130
+
131
+ <div style="margin-top:10px; font-size:0.66rem; color:#5a6a7a; line-height:1.5;">
132
+ A supportive companion — not a replacement for professional care. If you're ever in crisis,
133
+ it will surface helplines right away.
134
+ </div>
135
+ </div>
136
+ """
config.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration for REFRAME app."""
2
+
3
+ import os
4
+
5
+ # --- Backend Selection ---
6
+ # Auto: Ollama locally, llama-cpp-python on HF Spaces (no Ollama daemon there).
7
+ # Override with REFRAME_BACKEND=ollama|llamacpp.
8
+ _ON_SPACE = bool(os.environ.get("SPACE_ID"))
9
+ BACKEND = os.environ.get("REFRAME_BACKEND", "llamacpp" if _ON_SPACE else "ollama")
10
+
11
+ # Optional fully-offline local run (no network) — uses only the HF cache.
12
+ # Set REFRAME_OFFLINE=1 locally. Never applied on a Space (it must download once).
13
+ if os.environ.get("REFRAME_OFFLINE") and not _ON_SPACE:
14
+ os.environ.setdefault("HF_HUB_OFFLINE", "1")
15
+ os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
16
+
17
+ # --- Ollama Config (local) ---
18
+ OLLAMA_MODEL = os.environ.get("OLLAMA_MODEL", "gemma4_mentalhealthbuddy_v1")
19
+ OLLAMA_BASE_URL = os.environ.get("OLLAMA_BASE_URL", "http://localhost:11434")
20
+ # Keep the chat model resident between turns (-1 = never unload). Avoids slow,
21
+ # failure-prone cold reloads when RAM is tight (STT + LLM share system memory).
22
+ OLLAMA_KEEP_ALIVE = os.environ.get("OLLAMA_KEEP_ALIVE", -1)
23
+
24
+ # --- llama-cpp-python Config (HF Spaces) ---
25
+ GGUF_REPO_ID = os.environ.get("GGUF_REPO_ID", "") # e.g. "username/mentalhealthbuddy-gguf"
26
+ GGUF_FILENAME = os.environ.get("GGUF_FILENAME", "mentalhealthbuddy_q4_k_m.gguf")
27
+ GGUF_LOCAL_PATH = os.environ.get("GGUF_LOCAL_PATH", "") # if already downloaded
28
+
29
+ # --- Generation Parameters ---
30
+ MAX_TOKENS = 256
31
+ TEMPERATURE = 0.4
32
+ TOP_P = 0.9
33
+ REPEAT_PENALTY = 1.1
34
+
35
+ # --- App Settings ---
36
+ APP_TITLE = "REFRAME"
37
+ APP_SUBTITLE = "Reframe your thinking."
38
+ RESPONSE_DELAY = 1.5 # seconds before model starts responding (thoughtfulness)
39
+ STREAM_SPEED = 0.02 # seconds between tokens when streaming
40
+
41
+ # --- Session Limits ---
42
+ MAX_CARDS = 50
43
+ MAX_SESSION_SUMMARIES = 20
44
+
45
+ # --- Cognitive Distortions ---
46
+ DISTORTIONS = [
47
+ "catastrophizing",
48
+ "overgeneralization",
49
+ "all-or-nothing thinking",
50
+ "mind-reading",
51
+ "fortune-telling",
52
+ "should-statements",
53
+ "emotional reasoning",
54
+ "labeling",
55
+ "personalization",
56
+ "mental filter",
57
+ "disqualifying the positive",
58
+ ]
59
+
60
+ # --- Crisis Keywords (C-SSRS framework) ---
61
+ CRISIS_KEYWORDS = [
62
+ "kill myself",
63
+ "end my life",
64
+ "suicide",
65
+ "suicidal",
66
+ "want to die",
67
+ "better off dead",
68
+ "no reason to live",
69
+ "can't go on",
70
+ "self-harm",
71
+ "hurt myself",
72
+ "cutting myself",
73
+ "overdose",
74
+ ]
75
+
76
+ # --- Helplines ---
77
+ HELPLINES = [
78
+ {"name": "988 Suicide & Crisis Lifeline (US)", "contact": "Call or text 988"},
79
+ {"name": "Crisis Text Line (US)", "contact": "Text HOME to 741741"},
80
+ {"name": "Samaritans (UK/IE)", "contact": "Call 116 123 (free, 24/7)"},
81
+ {"name": "Befrienders Worldwide", "contact": "befrienders.org"},
82
+ ]
83
+
84
+ # --- Speech-to-Text (optional, requires requirements-stt.txt) ---
85
+ STT_ENABLED = True # Set False to hide mic entirely
86
+ # STT_MODEL = os.environ.get("STT_MODEL", "openai/whisper-small")
87
+ STT_MODEL = os.environ.get("STT_MODEL", "CohereLabs/cohere-transcribe-03-2026") # gated — needs HF login + access request
crisis.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Crisis detection and response."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import config
6
+
7
+
8
+ def detect_crisis(text: str) -> bool:
9
+ """Check if user message contains crisis indicators."""
10
+ text_lower = text.lower()
11
+ return any(kw in text_lower for kw in config.CRISIS_KEYWORDS)
12
+
13
+
14
+ def get_crisis_response() -> str:
15
+ """Get the warm crisis response message."""
16
+ return (
17
+ "I hear you. What you're feeling right now matters, "
18
+ "and you don't have to go through this alone."
19
+ )
20
+
21
+
22
+ def get_crisis_banner_html() -> str:
23
+ """Render crisis helpline banner as HTML."""
24
+ lines = []
25
+ for h in config.HELPLINES:
26
+ lines.append(f"<div class='helpline'><strong>{h['name']}</strong> — {h['contact']}</div>")
27
+
28
+ return f"""
29
+ <div class="crisis-banner">
30
+ <div class="crisis-header">💜 You're not alone. Help is available:</div>
31
+ {''.join(lines)}
32
+ <div class="crisis-footer">I'm still here. We can keep talking, or try a grounding exercise — whatever feels right.</div>
33
+ </div>
34
+ """
distortion_parser.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cognitive distortion parser — detects distortion labels in model output."""
2
+
3
+ from __future__ import annotations
4
+
5
+ # Trigger phrases that indicate the model is naming a distortion
6
+ DISTORTION_TRIGGERS: dict[str, list[str]] = {
7
+ "catastrophizing": [
8
+ "catastrophiz", "worst case", "jumping to the worst",
9
+ "imagining the worst", "end of the world",
10
+ ],
11
+ "overgeneralization": [
12
+ "overgeneraliz", "always", "never", "every time",
13
+ "\"always\"", "\"never\"", "the word 'always'",
14
+ "the word 'never'",
15
+ ],
16
+ "all-or-nothing thinking": [
17
+ "all-or-nothing", "black and white", "black-and-white",
18
+ "either/or", "all or nothing", "binary thinking",
19
+ "no middle ground",
20
+ ],
21
+ "mind-reading": [
22
+ "mind-read", "mind read", "assuming what they think",
23
+ "guessing their", "assuming they",
24
+ "you're reading their mind",
25
+ ],
26
+ "fortune-telling": [
27
+ "fortune-tell", "fortune tell", "predicting",
28
+ "jumping ahead", "you're predicting",
29
+ "crystal ball",
30
+ ],
31
+ "should-statements": [
32
+ "should statement", "shoulding yourself", "'should'",
33
+ "\"should\"", "must/should", "the word 'should'",
34
+ ],
35
+ "emotional reasoning": [
36
+ "emotional reasoning", "feeling it doesn't make it",
37
+ "feeling something doesn't make it true",
38
+ "just because you feel",
39
+ ],
40
+ "labeling": [
41
+ "labeling yourself", "putting a label",
42
+ "you're not a", "that's a label",
43
+ "calling yourself",
44
+ ],
45
+ "personalization": [
46
+ "personaliz", "taking responsibility for",
47
+ "blaming yourself for", "not everything is about",
48
+ "not your fault",
49
+ ],
50
+ "mental filter": [
51
+ "mental filter", "filtering out", "only seeing the negative",
52
+ "ignoring the positive", "focusing only on",
53
+ ],
54
+ "disqualifying the positive": [
55
+ "disqualifying", "dismissing the positive",
56
+ "doesn't count", "that was just luck",
57
+ ],
58
+ }
59
+
60
+
61
+ def detect_distortions(text: str) -> list[str]:
62
+ """Detect cognitive distortions mentioned in model output.
63
+
64
+ Args:
65
+ text: The model's response text.
66
+
67
+ Returns:
68
+ List of distortion names detected (may be empty).
69
+ """
70
+ text_lower = text.lower()
71
+ detected = []
72
+
73
+ for distortion, triggers in DISTORTION_TRIGGERS.items():
74
+ for trigger in triggers:
75
+ if trigger.lower() in text_lower:
76
+ if distortion not in detected:
77
+ detected.append(distortion)
78
+ break
79
+
80
+ return detected
inference.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dual-backend inference: Ollama (local) or llama-cpp-python (HF Spaces)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Generator
7
+
8
+ import config
9
+
10
+
11
+ def _get_ollama_client():
12
+ """Lazy import and create Ollama client."""
13
+ import httpx
14
+ # Large timeout: model cold-load can take 60s+, generation is streamed
15
+ timeout = httpx.Timeout(connect=10.0, read=300.0, write=10.0, pool=10.0)
16
+ return httpx.Client(base_url=config.OLLAMA_BASE_URL, timeout=timeout)
17
+
18
+
19
+ def _get_llamacpp_model():
20
+ """Lazy-load llama-cpp-python model (downloads GGUF if needed)."""
21
+ from llama_cpp import Llama
22
+
23
+ model_path = config.GGUF_LOCAL_PATH
24
+ if not model_path:
25
+ from huggingface_hub import hf_hub_download
26
+ model_path = hf_hub_download(
27
+ repo_id=config.GGUF_REPO_ID,
28
+ filename=config.GGUF_FILENAME,
29
+ )
30
+
31
+ return Llama(
32
+ model_path=model_path,
33
+ n_ctx=4096,
34
+ n_gpu_layers=-1, # Use all available GPU layers
35
+ verbose=False,
36
+ )
37
+
38
+
39
+ # Module-level cache
40
+ _llm_model = None
41
+
42
+
43
+ def _get_model():
44
+ global _llm_model
45
+ if _llm_model is None and config.BACKEND == "llamacpp":
46
+ _llm_model = _get_llamacpp_model()
47
+ return _llm_model
48
+
49
+
50
+ def stream_response(
51
+ user_message: str,
52
+ history: list[dict],
53
+ system_prompt: str,
54
+ ) -> Generator[str, None, None]:
55
+ """Stream model response token by token.
56
+
57
+ Args:
58
+ user_message: The latest user message.
59
+ history: List of {"role": ..., "content": ...} dicts (prior turns).
60
+ system_prompt: Full system prompt with session context.
61
+
62
+ Yields:
63
+ Partial response strings (accumulating).
64
+ """
65
+ if config.BACKEND == "ollama":
66
+ yield from _stream_ollama(user_message, history, system_prompt)
67
+ else:
68
+ yield from _stream_llamacpp(user_message, history, system_prompt)
69
+
70
+
71
+ def _build_messages(user_message: str, history: list[dict], system_prompt: str) -> list[dict]:
72
+ """Build the messages list for the model."""
73
+ messages = [{"role": "system", "content": system_prompt}]
74
+
75
+ for msg in history:
76
+ role = msg.get("role", "user")
77
+ content = msg.get("content", "")
78
+ # Gradio 6 may store content as a list of part-dicts; flatten to text.
79
+ if isinstance(content, list):
80
+ content = " ".join(
81
+ str(p.get("text", "")) if isinstance(p, dict) else str(p)
82
+ for p in content
83
+ ).strip()
84
+ if isinstance(content, str) and content.strip():
85
+ messages.append({"role": role, "content": content})
86
+
87
+ messages.append({"role": "user", "content": user_message})
88
+ return messages
89
+
90
+
91
+ def _stream_ollama(
92
+ user_message: str,
93
+ history: list[dict],
94
+ system_prompt: str,
95
+ ) -> Generator[str, None, None]:
96
+ """Stream from local Ollama instance."""
97
+ messages = _build_messages(user_message, history, system_prompt)
98
+
99
+ client = _get_ollama_client()
100
+ response = ""
101
+
102
+ with client.stream(
103
+ "POST",
104
+ "/api/chat",
105
+ json={
106
+ "model": config.OLLAMA_MODEL,
107
+ "messages": messages,
108
+ "stream": True,
109
+ "keep_alive": config.OLLAMA_KEEP_ALIVE,
110
+ "options": {
111
+ "temperature": config.TEMPERATURE,
112
+ "top_p": config.TOP_P,
113
+ "num_predict": config.MAX_TOKENS,
114
+ "repeat_penalty": config.REPEAT_PENALTY,
115
+ },
116
+ },
117
+ ) as stream:
118
+ for line in stream.iter_lines():
119
+ if not line:
120
+ continue
121
+ try:
122
+ data = json.loads(line)
123
+ token = data.get("message", {}).get("content", "")
124
+ if token:
125
+ response += token
126
+ yield response
127
+ if data.get("done", False):
128
+ break
129
+ except json.JSONDecodeError:
130
+ continue
131
+
132
+
133
+ def _stream_llamacpp(
134
+ user_message: str,
135
+ history: list[dict],
136
+ system_prompt: str,
137
+ ) -> Generator[str, None, None]:
138
+ """Stream from llama-cpp-python (for HF Spaces)."""
139
+ messages = _build_messages(user_message, history, system_prompt)
140
+ model = _get_model()
141
+
142
+ response = ""
143
+ for chunk in model.create_chat_completion(
144
+ messages=messages,
145
+ max_tokens=config.MAX_TOKENS,
146
+ temperature=config.TEMPERATURE,
147
+ top_p=config.TOP_P,
148
+ repeat_penalty=config.REPEAT_PENALTY,
149
+ stream=True,
150
+ ):
151
+ delta = chunk.get("choices", [{}])[0].get("delta", {})
152
+ token = delta.get("content", "")
153
+ if token:
154
+ response += token
155
+ yield response
patterns.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cross-card pattern analysis — distortion frequency, timing, themes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from session import SessionState
6
+
7
+
8
+ def analyze_patterns(state: SessionState) -> dict:
9
+ """Analyze card deck for patterns.
10
+
11
+ Returns dict with:
12
+ - top_distortions: list of (name, count) sorted by frequency
13
+ - total_cards: int
14
+ - card_dates: list of dates
15
+ - insight: str (generated summary)
16
+ """
17
+ if not state.cards:
18
+ return {
19
+ "top_distortions": [],
20
+ "total_cards": 0,
21
+ "card_dates": [],
22
+ "insight": "Complete your first thought record to start seeing patterns.",
23
+ }
24
+
25
+ top = sorted(state.distortion_counts.items(), key=lambda x: x[1], reverse=True)
26
+ dates = [c.get("date", "") for c in state.cards]
27
+
28
+ # Generate insight
29
+ insight = _generate_insight(top, len(state.cards))
30
+
31
+ return {
32
+ "top_distortions": top[:5],
33
+ "total_cards": len(state.cards),
34
+ "card_dates": dates,
35
+ "insight": insight,
36
+ }
37
+
38
+
39
+ def _generate_insight(top_distortions: list[tuple[str, int]], total_cards: int) -> str:
40
+ """Generate a human-readable insight from patterns."""
41
+ if not top_distortions:
42
+ return "Keep going — patterns emerge after a few cards."
43
+
44
+ top_name, top_count = top_distortions[0]
45
+
46
+ if total_cards < 3:
47
+ return f"Early pattern: {top_name} has come up {top_count} time(s). Let's see if it continues."
48
+
49
+ pct = int((top_count / max(total_cards, 1)) * 100)
50
+ return (
51
+ f"Your most common pattern is {top_name} "
52
+ f"({top_count} times across {total_cards} cards — {pct}% of sessions). "
53
+ f"Noticing it is the first step to changing it."
54
+ )
55
+
56
+
57
+ def get_patterns_html(state: SessionState) -> str:
58
+ """Render patterns as HTML for the progress panel."""
59
+ data = analyze_patterns(state)
60
+
61
+ if not data["top_distortions"]:
62
+ return """
63
+ <div style="color:#5a6a7a; font-size:0.85rem; text-align:center; padding:20px;">
64
+ <p>Complete thought records to reveal your thinking patterns.</p>
65
+ </div>
66
+ """
67
+
68
+ bars = ""
69
+ max_count = data["top_distortions"][0][1] if data["top_distortions"] else 1
70
+ for name, count in data["top_distortions"]:
71
+ width = int((count / max_count) * 100)
72
+ bars += f"""
73
+ <div style="display:flex; align-items:center; gap:8px; margin-bottom:8px;">
74
+ <span style="font-size:0.75rem; color:#8899aa; width:120px; flex-shrink:0;">{name}</span>
75
+ <div style="flex:1; height:6px; background:rgba(255,255,255,0.08); border-radius:3px; overflow:hidden;">
76
+ <div style="height:100%; width:{width}%; background:linear-gradient(90deg,#8b5cf6,#a78bfa); border-radius:3px;"></div>
77
+ </div>
78
+ <span style="font-size:0.7rem; color:#5a6a7a; width:30px; text-align:right;">{count}x</span>
79
+ </div>
80
+ """
81
+
82
+ return f"""
83
+ <div style="background:#1e2a3a; border-radius:12px; padding:16px; border:1px solid rgba(255,255,255,0.08);">
84
+ <h3 style="font-size:0.9rem; color:#e8edf3; margin-bottom:12px;">🔍 Your Thinking Patterns</h3>
85
+ <div>{bars}</div>
86
+ <div style="margin-top:12px; font-size:0.8rem; color:#e8edf3; line-height:1.4; padding:10px; background:rgba(139,92,246,0.05); border-radius:8px;">💡 {data['insight']}</div>
87
+ <div style="margin-top:8px; font-size:0.7rem; color:#5a6a7a;">{data['total_cards']} cards completed</div>
88
+ </div>
89
+ """
phase_detector.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Detect CBT phase transitions from model output to drive the card engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ # Phrases the model uses when moving through CBT phases
6
+ PHASE_TRIGGERS: dict[str, list[str]] = {
7
+ "situation": [
8
+ "what happened", "tell me about the situation",
9
+ "what was going on", "what triggered",
10
+ "when did this come up",
11
+ ],
12
+ "automatic_thought": [
13
+ "what went through your mind", "what were you thinking",
14
+ "the thought that came up", "what did you tell yourself",
15
+ "when you say", "i notice you said",
16
+ ],
17
+ "evidence_for": [
18
+ "what evidence supports", "what makes you think",
19
+ "why do you believe", "what backs that up",
20
+ "what supports that thought",
21
+ ],
22
+ "evidence_against": [
23
+ "on the other hand", "what contradicts",
24
+ "any evidence against", "has there been a time",
25
+ "is there anything that doesn't fit",
26
+ "what would you say to a friend",
27
+ "looking at the other side",
28
+ ],
29
+ "reframe": [
30
+ "another way to see", "balanced way",
31
+ "what would you tell a friend",
32
+ "looking at all of this", "more balanced thought",
33
+ "putting it all together", "new perspective",
34
+ "how would you reframe",
35
+ ],
36
+ }
37
+
38
+
39
+ def detect_phase(text: str) -> str | None:
40
+ """Detect which CBT phase the model's response is guiding toward.
41
+
42
+ Args:
43
+ text: The model's full response so far.
44
+
45
+ Returns:
46
+ Phase name or None if no phase detected.
47
+ One of: "situation", "automatic_thought", "evidence_for",
48
+ "evidence_against", "reframe"
49
+ """
50
+ text_lower = text.lower()
51
+
52
+ # Check phases in reverse priority (later phases override earlier)
53
+ detected = None
54
+ for phase, triggers in PHASE_TRIGGERS.items():
55
+ for trigger in triggers:
56
+ if trigger in text_lower:
57
+ detected = phase
58
+ break
59
+ if detected == phase:
60
+ # Don't break outer loop — later phases should override
61
+ pass
62
+
63
+ return detected
prompts.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """System prompts and context injection for REFRAME."""
2
+
3
+ BASE_SYSTEM_PROMPT = """You are a CBT therapist. Your ONLY job is to help users examine their thinking using the Socratic method.
4
+
5
+ RULES (non-negotiable):
6
+ 1. MAX 2 sentences per response. Always end with exactly ONE question.
7
+ 2. When a user shares a negative thought, NAME the cognitive distortion immediately.
8
+ 3. Never give advice. Never reassure. Never say "that's great" or "good idea".
9
+ 4. Never make small talk. If someone shares something positive, pivot: "What brought you here today?"
10
+ 5. Follow this sequence: Identify thought → Name distortion → Examine evidence → Generate reframe.
11
+
12
+ DISTORTIONS (use these exact terms):
13
+ catastrophizing, overgeneralization, all-or-nothing thinking, mind-reading, fortune-telling, should-statements, emotional reasoning, labeling, personalization, mental filter, disqualifying the positive
14
+
15
+ EXAMPLES OF GOOD RESPONSES:
16
+
17
+ User: "I failed my exam, I'm so stupid"
18
+ You: I notice some labeling there — equating one exam result with being "stupid." What evidence do you have that contradicts that label?
19
+
20
+ User: "My back hurts so I can't go for a run, I feel useless"
21
+ You: "I'm useless" sounds like all-or-nothing thinking — one limitation defining your whole worth. What did you accomplish this week despite the pain?
22
+
23
+ User: "I'm feeling happy about the sun"
24
+ You: That's a nice moment to hold onto. What brought you to this conversation today — is there something on your mind?
25
+
26
+ User: "My work is not motivating"
27
+ You: When you say "not motivating," is that about every single task, or are there specific parts? That might be overgeneralization worth examining.
28
+
29
+ User: "Nobody cares about me"
30
+ You: "Nobody" is a strong word — that sounds like overgeneralization. Can you think of one person who showed they cared recently, even in a small way?
31
+
32
+ WHAT YOU NEVER DO:
33
+ - Give advice or suggest activities
34
+ - Be cheerful or encouraging
35
+ - Write more than 2 sentences
36
+ - Skip naming the distortion when one is present
37
+ - Invent facts the user hasn't shared
38
+ - Say "I understand" or "That must be hard" without following up with a question"""
39
+
40
+ CONTEXT_TEMPLATE = """
41
+ PRIOR CONTEXT:
42
+ - Sessions: {session_count} | Cards completed: {card_count}
43
+ - Last session ({days_ago}d ago): {last_summary}
44
+ - Active experiments: {experiments}
45
+ - Recurring patterns: {patterns}
46
+ - Mood trend: {mood_trend}
47
+
48
+ Continue naturally. Follow up on experiments when relevant.
49
+ Reference past insights only when they connect to what's happening now."""
50
+
51
+ FIRST_VISIT_GREETING = "Hey. This is a private space — nothing leaves this device. What's on your mind today?"
52
+
53
+ RETURN_VISIT_TEMPLATE = "Welcome back. {followup}"
54
+
55
+
56
+ def build_system_prompt(session_data: dict | None = None) -> str:
57
+ """Build full system prompt with optional session context."""
58
+ prompt = BASE_SYSTEM_PROMPT
59
+
60
+ if session_data and session_data.get("session_count", 0) > 0:
61
+ context = CONTEXT_TEMPLATE.format(
62
+ session_count=session_data.get("session_count", 0),
63
+ card_count=len(session_data.get("cards", [])),
64
+ days_ago=session_data.get("days_since_last", "?"),
65
+ last_summary=session_data.get("last_summary", "No prior summary."),
66
+ experiments=_format_experiments(session_data.get("experiments", [])),
67
+ patterns=_format_patterns(session_data.get("distortion_counts", {})),
68
+ mood_trend=session_data.get("mood_trend", "Not enough data."),
69
+ )
70
+ prompt += context
71
+
72
+ return prompt
73
+
74
+
75
+ def get_greeting(session_data: dict | None = None) -> str:
76
+ """Get the appropriate greeting based on session history."""
77
+ if not session_data or session_data.get("session_count", 0) == 0:
78
+ return FIRST_VISIT_GREETING
79
+
80
+ followup = ""
81
+ experiments = session_data.get("experiments", [])
82
+ pending = [e for e in experiments if e.get("status") == "pending"]
83
+ if pending:
84
+ exp = pending[0]
85
+ followup = f"Last time you said you'd try: \"{exp['description']}\" — how did it go?"
86
+ elif session_data.get("last_summary"):
87
+ followup = f"Last session we explored: {session_data['last_summary'][:80]}... How have things been?"
88
+ else:
89
+ followup = "How have things been since we last talked?"
90
+
91
+ return RETURN_VISIT_TEMPLATE.format(followup=followup)
92
+
93
+
94
+ def _format_experiments(experiments: list) -> str:
95
+ pending = [e for e in experiments if e.get("status") == "pending"]
96
+ if not pending:
97
+ return "None active."
98
+ return "; ".join(e.get("description", "")[:60] for e in pending[:3])
99
+
100
+
101
+ def _format_patterns(distortion_counts: dict) -> str:
102
+ if not distortion_counts:
103
+ return "Not enough data yet."
104
+ sorted_d = sorted(distortion_counts.items(), key=lambda x: x[1], reverse=True)[:3]
105
+ return ", ".join(f"{name} ({count}x)" for name, count in sorted_d)
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HF Space (ZeroGPU) requirements — rename to requirements.txt inside the Space repo.
2
+ # torch is pinned to a ZeroGPU-supported version (2.8–2.11; NOT 2.12).
3
+ gradio>=6.0
4
+ httpx>=0.27.0
5
+ huggingface-hub>=0.23.0
6
+ spaces
7
+ llama-cpp-python
8
+ transformers>=5.4.0
9
+ torch==2.11.0
10
+ accelerate
11
+ soundfile
12
+ numpy<2
13
+ librosa
14
+ sentencepiece
session.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Session state management for REFRAME — all persisted via gr.BrowserState."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import uuid
7
+ from dataclasses import asdict, dataclass, field
8
+ from datetime import datetime
9
+
10
+
11
+ @dataclass
12
+ class ThoughtCard:
13
+ id: str = field(default_factory=lambda: str(uuid.uuid4())[:8])
14
+ date: str = field(default_factory=lambda: datetime.now().strftime("%Y-%m-%d"))
15
+ situation: str = ""
16
+ automatic_thought: str = ""
17
+ distortions: list[str] = field(default_factory=list)
18
+ evidence_for: list[str] = field(default_factory=list)
19
+ evidence_against: list[str] = field(default_factory=list)
20
+ balanced_thought: str = ""
21
+ emotion_before: tuple[str, int] = ("", 0)
22
+ emotion_after: tuple[str, int] = ("", 0)
23
+
24
+
25
+ @dataclass
26
+ class Experiment:
27
+ description: str = ""
28
+ set_date: str = field(default_factory=lambda: datetime.now().strftime("%Y-%m-%d"))
29
+ status: str = "pending" # pending | completed | skipped
30
+ outcome: str = ""
31
+ insight: str = ""
32
+
33
+
34
+ @dataclass
35
+ class SessionState:
36
+ session_count: int = 0
37
+ cards: list[dict] = field(default_factory=list)
38
+ experiments: list[dict] = field(default_factory=list)
39
+ distortion_counts: dict[str, int] = field(default_factory=dict)
40
+ mood_log: list[tuple[str, int]] = field(default_factory=list)
41
+ last_summary: str = ""
42
+ days_since_last: int = 0
43
+ mood_trend: str = ""
44
+ conversation_summaries: list[str] = field(default_factory=list)
45
+
46
+
47
+ def serialize_session(state: SessionState) -> str:
48
+ """Serialize session to JSON string for BrowserState."""
49
+ return json.dumps(asdict(state))
50
+
51
+
52
+ def deserialize_session(data: str | None) -> SessionState:
53
+ """Deserialize session from BrowserState JSON string."""
54
+ if not data:
55
+ return SessionState()
56
+ try:
57
+ d = json.loads(data) if isinstance(data, str) else data
58
+ return SessionState(**d)
59
+ except (json.JSONDecodeError, TypeError):
60
+ return SessionState()
61
+
62
+
63
+ def save_card(state: SessionState, card: ThoughtCard) -> SessionState:
64
+ """Save a completed thought card to session."""
65
+ state.cards.append(asdict(card))
66
+ # Update distortion counts
67
+ for d in card.distortions:
68
+ state.distortion_counts[d] = state.distortion_counts.get(d, 0) + 1
69
+ # Cap at max
70
+ from config import MAX_CARDS
71
+ if len(state.cards) > MAX_CARDS:
72
+ state.cards = state.cards[-MAX_CARDS:]
73
+ return state
74
+
75
+
76
+ def save_experiment(state: SessionState, experiment: Experiment) -> SessionState:
77
+ """Save a behavioral experiment to session."""
78
+ state.experiments.append(asdict(experiment))
79
+ return state
80
+
81
+
82
+ def start_new_session(state: SessionState) -> SessionState:
83
+ """Increment session count and calculate days since last."""
84
+ state.session_count += 1
85
+ return state
86
+
87
+
88
+ def get_session_context(state: SessionState) -> dict:
89
+ """Get session data formatted for prompt injection."""
90
+ return {
91
+ "session_count": state.session_count,
92
+ "cards": state.cards,
93
+ "card_count": len(state.cards),
94
+ "experiments": state.experiments,
95
+ "distortion_counts": state.distortion_counts,
96
+ "last_summary": state.last_summary,
97
+ "days_since_last": state.days_since_last,
98
+ "mood_trend": state.mood_trend,
99
+ }
static/theme.css ADDED
@@ -0,0 +1,730 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* REFRAME — Master Theme */
2
+ /* Dark, calm, ambient therapy environment */
3
+
4
+ :root {
5
+ --bg-primary: #0f1419;
6
+ --bg-secondary: #1a2332;
7
+ --bg-card: #1e2a3a;
8
+ --text-primary: #e8edf3;
9
+ --text-secondary: #8899aa;
10
+ --text-muted: #5a6a7a;
11
+ --accent: #8b5cf6;
12
+ --accent-glow: rgba(139, 92, 246, 0.2);
13
+ --success: #22c55e;
14
+ --success-glow: rgba(34, 197, 94, 0.15);
15
+ --border: rgba(255, 255, 255, 0.08);
16
+ --shadow: rgba(0, 0, 0, 0.3);
17
+ }
18
+
19
+ /* Main app container */
20
+ .gradio-container {
21
+ background: var(--bg-primary) !important;
22
+ min-height: 100vh;
23
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;
24
+ }
25
+
26
+ /* Atmosphere background — animated gradient */
27
+ .atmosphere-wrapper {
28
+ position: fixed;
29
+ top: 0; left: 0; right: 0; bottom: 0;
30
+ z-index: -1;
31
+ transition: background 5s ease;
32
+ }
33
+
34
+ .atmosphere-neutral {
35
+ background: linear-gradient(135deg, #0f1419 0%, #1a2332 50%, #0f1419 100%);
36
+ background-size: 400% 400%;
37
+ animation: drift 20s ease infinite;
38
+ }
39
+ .atmosphere-anxious {
40
+ background: linear-gradient(135deg, #0f1a2e 0%, #1a2540 30%, #162030 70%, #0f1419 100%);
41
+ background-size: 400% 400%;
42
+ animation: drift 12s ease infinite;
43
+ }
44
+ .atmosphere-sad {
45
+ background: linear-gradient(135deg, #12101f 0%, #1a1535 50%, #0f0f1f 100%);
46
+ background-size: 400% 400%;
47
+ animation: drift 25s ease infinite;
48
+ }
49
+ .atmosphere-angry {
50
+ background: linear-gradient(135deg, #1f1410 0%, #2a1a15 50%, #1a1210 100%);
51
+ background-size: 400% 400%;
52
+ animation: drift 15s ease infinite;
53
+ }
54
+ .atmosphere-calm {
55
+ background: linear-gradient(135deg, #0f1f1a 0%, #152a25 50%, #0f1f1a 100%);
56
+ background-size: 400% 400%;
57
+ animation: drift 30s ease infinite;
58
+ }
59
+ .atmosphere-breakthrough {
60
+ background: linear-gradient(135deg, #1a1a0f 0%, #2a2510 30%, #1f1a0f 70%, #0f1419 100%);
61
+ background-size: 400% 400%;
62
+ animation: expand 8s ease infinite;
63
+ }
64
+
65
+ @keyframes drift {
66
+ 0% { background-position: 0% 50%; }
67
+ 50% { background-position: 100% 50%; }
68
+ 100% { background-position: 0% 50%; }
69
+ }
70
+ @keyframes expand {
71
+ 0% { background-position: 50% 50%; }
72
+ 50% { background-position: 100% 100%; }
73
+ 100% { background-position: 50% 50%; }
74
+ }
75
+
76
+ /* Chatbot styling */
77
+ .chatbot-container .message {
78
+ border-radius: 12px !important;
79
+ padding: 12px 16px !important;
80
+ }
81
+
82
+ /* Chatbot placeholder — big comic style */
83
+ #reframe-chat .placeholder,
84
+ #reframe-chat .placeholder *,
85
+ .placeholder, [data-testid="chatbot"] .placeholder, .chatbot .placeholder {
86
+ font-size: 2.2rem !important;
87
+ font-family: 'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', cursive !important;
88
+ color: #a78bfa !important;
89
+ opacity: 1 !important;
90
+ font-weight: 700 !important;
91
+ text-align: center !important;
92
+ padding: 40px !important;
93
+ background: transparent !important;
94
+ border: none !important;
95
+ }
96
+ [data-testid="chatbot"] .placeholder span,
97
+ [data-testid="chatbot"] .placeholder *,
98
+ #reframe-chat .placeholder span {
99
+ font-size: inherit !important;
100
+ font-family: inherit !important;
101
+ color: inherit !important;
102
+ background: transparent !important;
103
+ }
104
+
105
+ /* Card panel */
106
+ .card-panel {
107
+ background: var(--bg-secondary);
108
+ border-radius: 16px;
109
+ border: 1px solid var(--border);
110
+ padding: 20px;
111
+ min-height: 400px;
112
+ }
113
+
114
+ /* Thought card */
115
+ .thought-card {
116
+ background: var(--bg-card);
117
+ border: 1px solid var(--border);
118
+ border-radius: 12px;
119
+ padding: 16px;
120
+ transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
121
+ }
122
+ .thought-card.card-complete {
123
+ border-color: rgba(34, 197, 94, 0.5);
124
+ box-shadow: 0 0 20px var(--success-glow);
125
+ }
126
+ .card-header {
127
+ font-size: 0.85rem;
128
+ color: var(--text-secondary);
129
+ margin-bottom: 12px;
130
+ font-weight: 600;
131
+ letter-spacing: 0.5px;
132
+ }
133
+ .card-section {
134
+ margin-bottom: 12px;
135
+ opacity: 0;
136
+ transform: translateY(-8px);
137
+ transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
138
+ }
139
+ .card-section.active {
140
+ opacity: 1;
141
+ transform: translateY(0);
142
+ }
143
+ .card-section-label {
144
+ font-size: 0.7rem;
145
+ font-weight: 700;
146
+ color: var(--text-muted);
147
+ letter-spacing: 1px;
148
+ text-transform: uppercase;
149
+ margin-bottom: 4px;
150
+ }
151
+ .card-section-content {
152
+ font-size: 0.9rem;
153
+ color: var(--text-primary);
154
+ line-height: 1.4;
155
+ }
156
+ .card-section-content.reframe {
157
+ color: var(--success);
158
+ font-style: italic;
159
+ }
160
+ .card-evidence {
161
+ list-style: none;
162
+ padding: 0;
163
+ margin: 0;
164
+ }
165
+ .card-evidence li {
166
+ font-size: 0.85rem;
167
+ color: var(--text-primary);
168
+ padding: 4px 0;
169
+ padding-left: 12px;
170
+ border-left: 2px solid var(--border);
171
+ margin-bottom: 4px;
172
+ }
173
+
174
+ /* Distortion tags */
175
+ .card-tags {
176
+ display: flex;
177
+ flex-wrap: wrap;
178
+ gap: 6px;
179
+ }
180
+ .distortion-tag {
181
+ display: inline-block;
182
+ background: var(--accent-glow);
183
+ border: 1px solid rgba(139, 92, 246, 0.4);
184
+ border-radius: 20px;
185
+ padding: 4px 12px;
186
+ font-size: 0.75rem;
187
+ color: #a78bfa;
188
+ font-weight: 500;
189
+ animation: pop-in 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
190
+ }
191
+ @keyframes pop-in {
192
+ 0% { transform: scale(0); opacity: 0; }
193
+ 100% { transform: scale(1); opacity: 1; }
194
+ }
195
+
196
+ /* Placeholder */
197
+ .thought-card-placeholder {
198
+ display: flex;
199
+ flex-direction: column;
200
+ align-items: center;
201
+ justify-content: center;
202
+ min-height: 200px;
203
+ color: var(--text-muted);
204
+ text-align: center;
205
+ padding: 40px 20px;
206
+ }
207
+ .placeholder-icon {
208
+ font-size: 2.5rem;
209
+ margin-bottom: 12px;
210
+ opacity: 0.5;
211
+ }
212
+ .placeholder-text {
213
+ font-size: 0.85rem;
214
+ line-height: 1.5;
215
+ max-width: 280px;
216
+ }
217
+
218
+ /* Card deck */
219
+ .deck-container {
220
+ margin-top: 16px;
221
+ }
222
+ .deck-header {
223
+ font-size: 0.85rem;
224
+ color: var(--text-secondary);
225
+ font-weight: 600;
226
+ margin-bottom: 10px;
227
+ }
228
+ .deck-scroll {
229
+ display: flex;
230
+ gap: 10px;
231
+ overflow-x: auto;
232
+ padding-bottom: 8px;
233
+ }
234
+ .deck-card {
235
+ flex-shrink: 0;
236
+ width: 140px;
237
+ background: var(--bg-card);
238
+ border: 1px solid var(--border);
239
+ border-radius: 10px;
240
+ padding: 10px;
241
+ font-size: 0.75rem;
242
+ transition: transform 0.2s;
243
+ }
244
+ .deck-card:hover {
245
+ transform: translateY(-2px);
246
+ }
247
+ .deck-card-tag {
248
+ color: #a78bfa;
249
+ font-weight: 600;
250
+ font-size: 0.7rem;
251
+ margin-bottom: 4px;
252
+ }
253
+ .deck-card-date {
254
+ color: var(--text-muted);
255
+ font-size: 0.65rem;
256
+ margin-bottom: 6px;
257
+ }
258
+ .deck-card-thought {
259
+ color: var(--text-secondary);
260
+ font-size: 0.7rem;
261
+ margin-bottom: 4px;
262
+ }
263
+ .deck-card-reframe {
264
+ color: var(--success);
265
+ font-size: 0.7rem;
266
+ font-style: italic;
267
+ }
268
+
269
+ /* Crisis banner */
270
+ .crisis-banner {
271
+ background: rgba(139, 92, 246, 0.1);
272
+ border: 1px solid rgba(139, 92, 246, 0.3);
273
+ border-radius: 12px;
274
+ padding: 16px;
275
+ margin-top: 12px;
276
+ }
277
+ .crisis-header {
278
+ font-weight: 600;
279
+ color: #a78bfa;
280
+ margin-bottom: 8px;
281
+ }
282
+ .helpline {
283
+ font-size: 0.85rem;
284
+ color: var(--text-primary);
285
+ margin: 4px 0;
286
+ }
287
+ .crisis-footer {
288
+ font-size: 0.8rem;
289
+ color: var(--text-secondary);
290
+ margin-top: 10px;
291
+ font-style: italic;
292
+ }
293
+
294
+ /* Patterns panel */
295
+ .patterns-panel {
296
+ background: var(--bg-card);
297
+ border-radius: 12px;
298
+ padding: 16px;
299
+ border: 1px solid var(--border);
300
+ }
301
+ .patterns-panel h3 {
302
+ font-size: 0.9rem;
303
+ color: var(--text-primary);
304
+ margin-bottom: 12px;
305
+ }
306
+ .pattern-row {
307
+ display: flex;
308
+ align-items: center;
309
+ gap: 8px;
310
+ margin-bottom: 8px;
311
+ }
312
+ .pattern-name {
313
+ font-size: 0.75rem;
314
+ color: var(--text-secondary);
315
+ width: 120px;
316
+ flex-shrink: 0;
317
+ }
318
+ .pattern-bar-bg {
319
+ flex: 1;
320
+ height: 6px;
321
+ background: var(--border);
322
+ border-radius: 3px;
323
+ overflow: hidden;
324
+ }
325
+ .pattern-bar {
326
+ height: 100%;
327
+ background: linear-gradient(90deg, #8b5cf6, #a78bfa);
328
+ border-radius: 3px;
329
+ transition: width 0.5s ease;
330
+ }
331
+ .pattern-count {
332
+ font-size: 0.7rem;
333
+ color: var(--text-muted);
334
+ width: 30px;
335
+ text-align: right;
336
+ }
337
+ .patterns-insight {
338
+ margin-top: 12px;
339
+ font-size: 0.8rem;
340
+ color: var(--text-primary);
341
+ line-height: 1.4;
342
+ padding: 10px;
343
+ background: rgba(139, 92, 246, 0.05);
344
+ border-radius: 8px;
345
+ }
346
+ .patterns-meta {
347
+ margin-top: 8px;
348
+ font-size: 0.7rem;
349
+ color: var(--text-muted);
350
+ }
351
+ .deck-empty, .patterns-empty {
352
+ color: var(--text-muted);
353
+ font-size: 0.85rem;
354
+ text-align: center;
355
+ padding: 20px;
356
+ }
357
+
358
+ /* Title */
359
+ .app-title {
360
+ font-size: 1.4rem;
361
+ font-weight: 700;
362
+ color: var(--text-primary);
363
+ letter-spacing: -0.5px;
364
+ }
365
+ .app-subtitle {
366
+ font-size: 1rem;
367
+ color: #a78bfa;
368
+ margin-top: 2px;
369
+ font-family: 'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', cursive;
370
+ font-weight: 600;
371
+ }
372
+
373
+ /* === Force dark on all Gradio internals === */
374
+
375
+ /* Override Gradio body/root */
376
+ body, .dark {
377
+ background: var(--bg-primary) !important;
378
+ }
379
+
380
+ /* Chatbot wrapper and messages */
381
+ .chatbot, [data-testid="chatbot"] {
382
+ background: var(--bg-secondary) !important;
383
+ border: 1px solid var(--border) !important;
384
+ border-radius: 12px !important;
385
+ }
386
+ /* Force all text inside chatbot to be light */
387
+ [data-testid="chatbot"] * {
388
+ color: var(--text-primary) !important;
389
+ }
390
+ [data-testid="chatbot"] .message-bubble-border {
391
+ background: var(--bg-card) !important;
392
+ border-color: var(--border) !important;
393
+ }
394
+ [data-testid="chatbot"] .user .message-bubble-border {
395
+ background: rgba(139, 92, 246, 0.12) !important;
396
+ border-color: rgba(139, 92, 246, 0.25) !important;
397
+ }
398
+ .message-row .message {
399
+ background: var(--bg-card) !important;
400
+ color: var(--text-primary) !important;
401
+ border: 1px solid var(--border) !important;
402
+ }
403
+ .message-row.user-row .message {
404
+ background: rgba(139, 92, 246, 0.12) !important;
405
+ border-color: rgba(139, 92, 246, 0.25) !important;
406
+ }
407
+ /* Bot/assistant bubble */
408
+ .bot .message-content, .assistant .message-content,
409
+ .bot p, .assistant p, .message p, .message span {
410
+ color: var(--text-primary) !important;
411
+ }
412
+ .user .message-content, .user p, .user span {
413
+ color: var(--text-primary) !important;
414
+ }
415
+
416
+ /* Textbox / input */
417
+ textarea, input[type="text"], .textbox {
418
+ background: var(--bg-secondary) !important;
419
+ color: var(--text-primary) !important;
420
+ border: 1px solid var(--border) !important;
421
+ border-radius: 8px !important;
422
+ }
423
+ textarea::placeholder, input::placeholder {
424
+ color: var(--text-muted) !important;
425
+ }
426
+
427
+ /* All panels, columns, blocks */
428
+ .block, .panel, .form, .wrap {
429
+ background: transparent !important;
430
+ border-color: var(--border) !important;
431
+ }
432
+
433
+ /* Buttons */
434
+ button.primary {
435
+ background: var(--accent) !important;
436
+ color: white !important;
437
+ border: none !important;
438
+ }
439
+ button.secondary, button[variant="secondary"] {
440
+ background: var(--bg-card) !important;
441
+ color: var(--text-primary) !important;
442
+ border: 1px solid var(--border) !important;
443
+ }
444
+ button.secondary:hover {
445
+ background: var(--bg-secondary) !important;
446
+ }
447
+
448
+ /* Tabs */
449
+ .tabs, .tabitem {
450
+ background: transparent !important;
451
+ }
452
+ .tab-nav button,
453
+ .tabs button[role="tab"],
454
+ button[role="tab"] {
455
+ color: var(--text-primary) !important;
456
+ opacity: 0.7 !important; /* visible but muted when not selected */
457
+ background: transparent !important;
458
+ border: none !important;
459
+ font-weight: 600 !important;
460
+ }
461
+ .tab-nav button:hover,
462
+ button[role="tab"]:hover {
463
+ opacity: 1 !important;
464
+ }
465
+ .tab-nav button.selected,
466
+ .tabs button[role="tab"].selected,
467
+ button[role="tab"][aria-selected="true"] {
468
+ color: var(--accent) !important;
469
+ opacity: 1 !important;
470
+ border-bottom: 2px solid var(--accent) !important;
471
+ }
472
+
473
+ /* HTML component containers — force light text everywhere */
474
+ .html-container {
475
+ background: transparent !important;
476
+ color: var(--text-primary) !important;
477
+ }
478
+ .html-container * {
479
+ color: inherit !important;
480
+ }
481
+ .html-container .thought-card-placeholder,
482
+ .html-container .placeholder-text,
483
+ .html-container .deck-empty,
484
+ .html-container .deck-empty p,
485
+ .html-container .patterns-empty {
486
+ color: var(--text-muted) !important;
487
+ }
488
+ .html-container .thought-card,
489
+ .html-container .card-section-content,
490
+ .html-container .card-evidence li,
491
+ .html-container .deck-card-thought,
492
+ .html-container .patterns-panel h3 {
493
+ color: var(--text-primary) !important;
494
+ }
495
+ .html-container .card-section-label,
496
+ .html-container .card-header,
497
+ .html-container .deck-header {
498
+ color: var(--text-secondary) !important;
499
+ }
500
+ .html-container .card-section-content.reframe,
501
+ .html-container .deck-card-reframe {
502
+ color: var(--success) !important;
503
+ }
504
+ .html-container .distortion-tag {
505
+ color: #a78bfa !important;
506
+ }
507
+
508
+ /* Row/column backgrounds */
509
+ .row, .column {
510
+ background: transparent !important;
511
+ }
512
+
513
+ /* Scrollbar styling */
514
+ ::-webkit-scrollbar {
515
+ width: 6px;
516
+ height: 6px;
517
+ }
518
+ ::-webkit-scrollbar-track {
519
+ background: var(--bg-primary);
520
+ }
521
+ ::-webkit-scrollbar-thumb {
522
+ background: var(--text-muted);
523
+ border-radius: 3px;
524
+ }
525
+ ::-webkit-scrollbar-thumb:hover {
526
+ background: var(--text-secondary);
527
+ }
528
+
529
+ /* Submit button inside textbox */
530
+ .submit-btn, button[title="Submit"] {
531
+ color: var(--accent) !important;
532
+ background: transparent !important;
533
+ }
534
+
535
+ /* === Header + model status badges === */
536
+ .app-header {
537
+ padding: 12px 0;
538
+ }
539
+ .app-subtitle-row {
540
+ display: flex;
541
+ justify-content: space-between;
542
+ align-items: center;
543
+ gap: 16px;
544
+ flex-wrap: wrap;
545
+ }
546
+ .model-badges {
547
+ display: flex;
548
+ flex-direction: row;
549
+ flex-wrap: wrap;
550
+ gap: 8px;
551
+ align-items: center;
552
+ margin-left: auto; /* right-align the pills on the subtitle line */
553
+ }
554
+ .model-badge {
555
+ display: inline-flex;
556
+ align-items: center;
557
+ gap: 6px;
558
+ font-size: 0.72rem;
559
+ font-weight: 600;
560
+ padding: 4px 11px;
561
+ border-radius: 20px;
562
+ background: var(--bg-card);
563
+ border: 1px solid var(--border);
564
+ color: var(--text-secondary);
565
+ white-space: nowrap;
566
+ }
567
+ .model-badge .badge-dot {
568
+ width: 7px;
569
+ height: 7px;
570
+ border-radius: 50%;
571
+ background: var(--success);
572
+ box-shadow: 0 0 6px rgba(34, 197, 94, 0.6);
573
+ }
574
+ /* Cohere badge — emphasized with accent color + glow */
575
+ .model-badge.badge-cohere {
576
+ color: #c4b5fd;
577
+ background: var(--accent-glow);
578
+ border-color: rgba(139, 92, 246, 0.5);
579
+ box-shadow: 0 0 10px rgba(139, 92, 246, 0.15);
580
+ }
581
+ /* Modal training-platform badge — green tint */
582
+ .model-badge.badge-modal {
583
+ color: #86efac;
584
+ background: rgba(34, 197, 94, 0.08);
585
+ border-color: rgba(34, 197, 94, 0.4);
586
+ }
587
+
588
+ /* === Tighter chat spacing (reduce whitespace between bubbles) === */
589
+ #reframe-chat .message-wrap,
590
+ #reframe-chat .message-wrap > div {
591
+ gap: 6px !important;
592
+ }
593
+ #reframe-chat .message-row {
594
+ margin: 2px 0 !important;
595
+ padding: 0 !important;
596
+ position: relative !important; /* anchor for copy button */
597
+ }
598
+ #reframe-chat .message {
599
+ padding: 0 !important;
600
+ margin: 0 !important;
601
+ border: none !important; /* drop inner border -> no double-box */
602
+ }
603
+ /* Real Gradio 6.18 classes — collapse the tall bubble height */
604
+ #reframe-chat .message-content {
605
+ min-height: 0 !important; /* removes var(--size-8) tall box */
606
+ padding: 7px 13px !important;
607
+ align-items: flex-start !important;
608
+ }
609
+ #reframe-chat .bubble {
610
+ margin: 4px 8px !important; /* was calc(spacing-xl * 2) */
611
+ }
612
+ #reframe-chat .bubble-wrap {
613
+ padding-top: 8px !important;
614
+ }
615
+ #reframe-chat .message-row:first-child {
616
+ padding-top: 8px !important;
617
+ }
618
+ #reframe-chat .message p {
619
+ margin: 0 !important;
620
+ line-height: 1.4 !important;
621
+ }
622
+ /* User messages in the playful comic font */
623
+ #reframe-chat .user .message,
624
+ #reframe-chat .message-row.user-row .message,
625
+ #reframe-chat .user .message p,
626
+ #reframe-chat .message-row.user-row .message p {
627
+ font-family: 'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', cursive !important;
628
+ }
629
+
630
+ /* === Move copy icon to top-right of each message === */
631
+ #reframe-chat .message-buttons,
632
+ #reframe-chat .message-row .icon-buttons,
633
+ #reframe-chat [class*="message-buttons"],
634
+ #reframe-chat button[aria-label="Copy"],
635
+ #reframe-chat button[title="Copy"] {
636
+ position: absolute !important;
637
+ top: 4px !important;
638
+ right: 6px !important;
639
+ bottom: auto !important;
640
+ left: auto !important;
641
+ margin: 0 !important;
642
+ z-index: 5 !important;
643
+ }
644
+
645
+ /* Cap chat height to the viewport on short screens (keeps input + mic visible) */
646
+ #reframe-chat {
647
+ max-height: 46vh !important;
648
+ }
649
+
650
+ /* Compact the microphone recorder so Record/Stop stays on-screen (no scroll) */
651
+ [data-testid="audio"] {
652
+ min-height: unset !important;
653
+ }
654
+ [data-testid="audio"] .wrap,
655
+ [data-testid="audio"] .empty,
656
+ [data-testid="audio"] .controls,
657
+ [data-testid="audio"] .waveform-container {
658
+ min-height: unset !important;
659
+ }
660
+ [data-testid="audio"] .waveform-container {
661
+ max-height: 72px !important;
662
+ }
663
+ /* Slim the audio label row */
664
+ [data-testid="audio"] .label-wrap,
665
+ [data-testid="audio"] label {
666
+ padding: 2px 0 !important;
667
+ }
668
+
669
+ /* === Stack / models showcase card === */
670
+ .stack-card { font-size: 0.78rem; line-height: 1.4; }
671
+ .stack-summary {
672
+ background: var(--accent-glow);
673
+ border: 1px solid rgba(139, 92, 246, 0.3);
674
+ border-radius: 10px;
675
+ padding: 10px 12px;
676
+ margin-bottom: 14px;
677
+ line-height: 1.5;
678
+ font-size: 0.8rem;
679
+ }
680
+ .stack-section { margin-bottom: 12px; }
681
+ .stack-label {
682
+ font-size: 0.7rem;
683
+ font-weight: 700;
684
+ letter-spacing: 0.5px;
685
+ text-transform: uppercase;
686
+ margin-bottom: 5px;
687
+ }
688
+ .stack-item { padding: 2px 0; }
689
+ .stack-note {
690
+ font-size: 0.7rem;
691
+ font-style: italic;
692
+ margin-top: 6px;
693
+ padding-top: 8px;
694
+ border-top: 1px solid var(--border);
695
+ }
696
+ /* Colors — override `.html-container * { color: inherit !important }` above */
697
+ .stack-line { padding: 3px 0; font-size: 0.76rem; line-height: 1.4; }
698
+ .stack-sub { font-size: 0.7rem; margin-top: 2px; line-height: 1.45; }
699
+ .stack-list { margin: 4px 0 0; padding-left: 18px; }
700
+ .stack-list li { font-size: 0.72rem; padding: 1px 0; }
701
+ .html-container .stack-line { color: var(--text-secondary) !important; }
702
+ .html-container .stack-line b { color: var(--text-primary) !important; }
703
+ .html-container .stack-sub { color: var(--text-muted) !important; }
704
+ .html-container .stack-list li { color: var(--text-muted) !important; }
705
+ .html-container .stack-list a { color: #a78bfa !important; text-decoration: none; }
706
+ .html-container .stack-list a:hover { text-decoration: underline; }
707
+ .html-container .stack-summary { color: var(--text-primary) !important; }
708
+ .html-container .stack-summary b { color: #c4b5fd !important; }
709
+ .html-container .stack-label { color: var(--text-muted) !important; }
710
+ .html-container .stack-item { color: var(--text-primary) !important; }
711
+ .html-container .stack-item b { color: var(--text-secondary) !important; }
712
+ .html-container .stack-muted { color: var(--text-muted) !important; }
713
+ .html-container .stack-note { color: var(--text-muted) !important; }
714
+
715
+ /* App credit (top center) */
716
+ .app-credit {
717
+ text-align: center;
718
+ color: var(--text-muted) !important;
719
+ font-size: 0.75rem;
720
+ padding: 4px 0 8px;
721
+ opacity: 0.85;
722
+ }
723
+
724
+ /* Hide Gradio footer and settings */
725
+ footer {
726
+ display: none !important;
727
+ }
728
+ .settings-modal, .settings-button, [aria-label="Settings"] {
729
+ display: none !important;
730
+ }
stt.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Speech-to-text module for REFRAME.
2
+
3
+ Modular, fail-safe STT using Cohere Transcribe (primary) or Whisper (fallback).
4
+ If dependencies are missing or model fails to load, the app continues without voice.
5
+ """
6
+
7
+ import logging
8
+ import os
9
+
10
+ import config
11
+
12
+ logging.basicConfig(level=logging.INFO)
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def _on_zerogpu() -> bool:
17
+ """True on an HF ZeroGPU Space (the `spaces` package is present only there).
18
+
19
+ On ZeroGPU we must target CUDA and load the model on `cuda` at startup — a
20
+ CUDA-emulation layer makes that work without a real GPU, and the real GPU is
21
+ used inside @spaces.GPU functions.
22
+ """
23
+ if not os.environ.get("SPACE_ID"):
24
+ return False
25
+ try:
26
+ import spaces # noqa: F401
27
+ return True
28
+ except Exception:
29
+ return False
30
+
31
+ _model = None
32
+ _processor = None
33
+ _pipeline = None
34
+ _fallback_pipeline = None
35
+ _load_attempted = False
36
+ _is_cohere = False
37
+ _FALLBACK_MODEL = "openai/whisper-small"
38
+
39
+
40
+ def is_available() -> bool:
41
+ """Check if STT dependencies are installed."""
42
+ try:
43
+ import torch # noqa: F401
44
+ import transformers # noqa: F401
45
+ return True
46
+ except ImportError:
47
+ return False
48
+
49
+
50
+ def _get_device() -> str:
51
+ """Best device: ZeroGPU cuda (forced) > xpu (Intel) > mps (Mac) > cuda > cpu."""
52
+ if _on_zerogpu():
53
+ # Load on cuda at module level (emulated); real GPU inside @spaces.GPU.
54
+ # Don't call cuda.is_available() here — it's False at startup on ZeroGPU.
55
+ return "cuda"
56
+ try:
57
+ import torch
58
+ if hasattr(torch, "xpu") and torch.xpu.is_available():
59
+ return "xpu"
60
+ if torch.backends.mps.is_available():
61
+ return "mps"
62
+ if torch.cuda.is_available():
63
+ return "cuda"
64
+ except Exception:
65
+ pass
66
+ return "cpu"
67
+
68
+
69
+ def _dtype_for(device: str):
70
+ """Pick a sensible compute dtype for the device."""
71
+ import torch
72
+ if device == "cpu":
73
+ return torch.float32
74
+ if device in ("xpu", "cuda"):
75
+ return torch.bfloat16 # checkpoint's native dtype; supported on Intel GPU + ZeroGPU
76
+ return torch.float16 # mps
77
+
78
+
79
+ def _load_whisper_fallback(device: str, dtype):
80
+ """Load Whisper fallback pipeline once and reuse it."""
81
+ global _fallback_pipeline
82
+ if _fallback_pipeline is not None:
83
+ return
84
+
85
+ from transformers import pipeline
86
+
87
+ logger.warning(f"[STT] Falling back to {_FALLBACK_MODEL}")
88
+ _fallback_pipeline = pipeline(
89
+ "automatic-speech-recognition",
90
+ model=_FALLBACK_MODEL,
91
+ dtype=dtype,
92
+ device=device,
93
+ generate_kwargs={"language": "en", "task": "transcribe"},
94
+ )
95
+
96
+
97
+ def _run_pipeline(pipe, audio_filepath: str) -> str:
98
+ """Run an ASR pipeline on a file path, decoding to a 16 kHz array first.
99
+
100
+ Passing a bare file path can fail with 'Soundfile ... malformed' (no ffmpeg
101
+ on PATH / unsupported WAV encoding); a decoded array via load_audio is
102
+ reliable and is how the Cohere path already loads audio.
103
+ """
104
+ from transformers.audio_utils import load_audio
105
+
106
+ audio = load_audio(audio_filepath, sampling_rate=16000)
107
+ result = pipe({"raw": audio, "sampling_rate": 16000})
108
+ return result.get("text", "") if isinstance(result, dict) else str(result)
109
+
110
+
111
+ def _load_model():
112
+ """Load the ASR model. Retries on failure (only locks after success)."""
113
+ global _model, _processor, _pipeline, _load_attempted, _is_cohere
114
+ if _load_attempted:
115
+ return
116
+
117
+ try:
118
+ import transformers
119
+
120
+ device = _get_device()
121
+ dtype = _dtype_for(device)
122
+ _is_cohere = "cohere" in config.STT_MODEL.lower()
123
+
124
+ if _is_cohere:
125
+ major = int(transformers.__version__.split(".")[0])
126
+ if major < 5:
127
+ logger.warning(
128
+ "[STT] Cohere Transcribe needs transformers>=5.4.0. "
129
+ f"Current version is {transformers.__version__}. Using Whisper fallback."
130
+ )
131
+ _load_whisper_fallback(device=device, dtype=dtype)
132
+ _load_attempted = True
133
+ return
134
+
135
+ logger.info(f"[STT] Loading model: {config.STT_MODEL} on {device} ({dtype})")
136
+
137
+ if _is_cohere:
138
+ from transformers import AutoProcessor, AutoModelForSpeechSeq2Seq
139
+
140
+ # Use transformers' built-in (native) cohere_asr implementation, NOT the
141
+ # Hub remote code. The remote-code path (trust_remote_code=True) produces
142
+ # garbage output on transformers>=5.3 and is deprecated by the model
143
+ # authors; the native path is the recommended way going forward.
144
+ # (See model discussion #28.)
145
+ _processor = AutoProcessor.from_pretrained(config.STT_MODEL)
146
+ _model = AutoModelForSpeechSeq2Seq.from_pretrained(config.STT_MODEL, dtype=dtype)
147
+ _model = _model.to(device)
148
+ else:
149
+ from transformers import pipeline
150
+
151
+ _pipeline = pipeline(
152
+ "automatic-speech-recognition",
153
+ model=config.STT_MODEL,
154
+ dtype=dtype,
155
+ device=device,
156
+ generate_kwargs={"language": "en", "task": "transcribe"},
157
+ )
158
+
159
+ _load_attempted = True # Only lock after success
160
+ logger.info("[STT] Model loaded successfully.")
161
+ except Exception:
162
+ logger.exception("[STT] Failed to load model")
163
+ _model = None
164
+ _processor = None
165
+ _pipeline = None
166
+
167
+
168
+ def preload_model():
169
+ """Eagerly download and load the model at startup (blocks until done)."""
170
+ global _pipeline, _model, _fallback_pipeline
171
+ if not is_available():
172
+ logger.warning("[STT] Cannot preload — dependencies not available")
173
+ return
174
+ logger.info(f"[STT] Preloading model: {config.STT_MODEL}")
175
+ _load_model()
176
+ if _pipeline is not None or _model is not None or _fallback_pipeline is not None:
177
+ logger.info("[STT] Model preloaded and ready.")
178
+ else:
179
+ logger.error("[STT] Preload failed — voice input will not work.")
180
+
181
+
182
+ def transcribe(audio_filepath: str) -> str:
183
+ """Transcribe audio file to text.
184
+
185
+ Args:
186
+ audio_filepath: Path to WAV/MP3 file from Gradio.
187
+
188
+ Returns:
189
+ Transcribed text, or empty string on any failure.
190
+ """
191
+ if not audio_filepath:
192
+ logger.warning("[STT] No audio filepath provided")
193
+ return ""
194
+
195
+ if not is_available():
196
+ logger.warning("[STT] Dependencies not available")
197
+ return ""
198
+
199
+ logger.info(f"[STT] Transcribing: {audio_filepath}")
200
+ _load_model()
201
+
202
+ try:
203
+ if _is_cohere and _model is not None and _processor is not None:
204
+ from transformers.audio_utils import load_audio
205
+
206
+ audio = load_audio(audio_filepath, sampling_rate=16000)
207
+ inputs = _processor(audio, sampling_rate=16000, return_tensors="pt", language="en")
208
+ model_dtype = next(_model.parameters()).dtype
209
+ inputs = inputs.to(device=_model.device, dtype=model_dtype)
210
+ outputs = _model.generate(**inputs, max_new_tokens=256)
211
+ # batch_decode returns one string per batch item; we have a batch of 1.
212
+ text = _processor.batch_decode(outputs, skip_special_tokens=True)
213
+ elif _fallback_pipeline is not None:
214
+ text = _run_pipeline(_fallback_pipeline, audio_filepath)
215
+ elif _pipeline is not None:
216
+ text = _run_pipeline(_pipeline, audio_filepath)
217
+ else:
218
+ logger.error("[STT] Model not loaded — cannot transcribe")
219
+ return ""
220
+
221
+ # Some processors return a list of strings (one per batch item).
222
+ if isinstance(text, (list, tuple)):
223
+ text = text[0] if text else ""
224
+ logger.info(f"[STT] Result: '{text.strip()}'")
225
+ return text.strip()
226
+ except Exception as e:
227
+ logger.error(f"[STT] Transcription failed: {e}")
228
+ if _is_cohere:
229
+ try:
230
+ device = _get_device()
231
+ dtype = _dtype_for(device)
232
+ _load_whisper_fallback(device=device, dtype=dtype)
233
+ text = _run_pipeline(_fallback_pipeline, audio_filepath)
234
+ logger.info(f"[STT] Fallback result: '{text.strip()}'")
235
+ return text.strip()
236
+ except Exception as fallback_err:
237
+ logger.error(f"[STT] Whisper fallback failed: {fallback_err}")
238
+ return ""