Russel-Morant commited on
Commit
b851ffc
Β·
verified Β·
1 Parent(s): a350fe4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +302 -390
app.py CHANGED
@@ -1,81 +1,69 @@
1
  #!/usr/bin/env python3
2
- # -*- coding: utf-8 -*-
3
 
4
  """
5
- Flan-SDE Behavioral Profiler (self-contained rewrite)
6
- - Situation is inputable via a JSON textbox (with tolerant fallback parsing).
7
- - Robust to missing optional deps (torch/transformers/datasets).
8
- - Defensive FLAN output parsing and shape checks.
9
- - Proper Gradio launch for container environments.
 
10
  """
11
 
12
- # =========================
13
- # Imports (minimal, complete)
14
- # =========================
15
- from typing import Optional, Dict, Any, List, Tuple
16
  from dataclasses import dataclass
17
  from collections import defaultdict
18
  import os
19
  import json
20
- import time
21
  import random
 
22
  import traceback
23
- import re
24
 
25
- # Core scientific stack
26
  import numpy as np
27
 
28
- # Matplotlib (headless)
29
  import matplotlib
30
- matplotlib.use('Agg')
31
  import matplotlib.pyplot as plt
32
 
33
- # Gradio UI
34
  import gradio as gr
35
 
36
- # Optional: datasets (for pushing logs)
37
- try:
38
- from datasets import Dataset # optional
39
- HAS_DATASETS = True
40
- except Exception:
41
- HAS_DATASETS = False
42
-
43
- # Optional: torch/transformers for FLAN
44
- _HAS_TORCH = False
45
- _HAS_TRANSFORMERS = False
46
  try:
47
  import torch
48
- _HAS_TORCH = True
49
- except Exception:
50
- pass
51
-
52
- try:
53
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
54
  _HAS_TRANSFORMERS = True
55
  except Exception:
56
- pass
57
 
58
- # Optional: sklearn (for KMeans). If missing, fallback to a simple heuristic.
59
- _HAS_SKLEARN = False
60
  try:
61
  from sklearn.cluster import KMeans
62
  _HAS_SKLEARN = True
63
  except Exception:
64
- pass
65
 
66
- # =========================
67
- # Configuration
68
- # =========================
69
- MODEL_ID_DEFAULT = os.environ.get('FLAN_MODEL', 'google/flan-t5-small')
70
- DEVICE = 'cuda' if _HAS_TORCH and getattr(torch, "cuda", None) and torch.cuda.is_available() else 'cpu'
71
- SEED = int(os.environ.get('APP_SEED', 42))
 
 
 
 
 
72
 
73
- np.random.seed(SEED)
74
  random.seed(SEED)
 
 
 
75
 
76
  LABELS = [
77
- "Attention", "Empathy", "Control", "Masking", "Interest", "Relevance", "Strategy",
78
- "Fear", "Trust", "Validation", "DominanceThreshold", "Unpredictability", "RiskAppetite"
79
  ]
80
 
81
  INITIAL_QUESTIONS = [
@@ -86,49 +74,40 @@ INITIAL_QUESTIONS = [
86
  ]
87
 
88
  FALLBACK_QUESTIONS = {
89
- "Attention": "How does your focus shift in demanding situations?",
90
- "Empathy": "What role does understanding others play in your decisions?",
91
- "Control": "How do you maintain influence over a situation?",
92
- "Masking": "When do you hide your true intentions?",
93
- "Interest": "What keeps you engaged in a task?",
94
- "Relevance": "How do you decide what matters most in a scenario?",
95
- "Strategy": "How do you plan your approach to challenges?",
96
- "Fear": "What makes you feel cautious or hesitant?",
97
- "Trust": "When do you feel comfortable relying on others?",
98
- "Validation": "What makes you feel recognized or valued?",
99
- "DominanceThreshold": "How much control do you need to feel secure?",
100
- "Unpredictability": "How do you handle unexpected twists?",
101
- "RiskAppetite": "What drives you to take bold risks?"
102
  }
103
 
104
- # Regex patterns for crude scoring
105
  _PATTERNS = {
106
- "control": (re.compile(r"\b(manipulat|control|dominat|exploit|test|punish|revenge|hurt)\b", re.IGNORECASE),
107
- {"Control": 0.12, "Strategy": 0.08, "Masking": 0.05}),
108
- "empathy": (re.compile(r"\b(trust|like|care|feel|empath|compass)\b", re.IGNORECASE),
109
- {"Empathy": 0.12, "Trust": 0.08}),
110
- "bored": (re.compile(r"\b(bore|boring|meh|dont care|who cares|whatever)\b", re.IGNORECASE),
111
- {"Interest": -0.15, "Relevance": 0.10}),
112
- "happy": (re.compile(r"\b(happy|fun|enjoy|excite|pleasur|thrill)\b", re.IGNORECASE),
113
- {"Validation": 0.08, "Interest": 0.08}),
114
- "mask": (re.compile(r"\b(fake|act|mask|perform|play a role)\b", re.IGNORECASE),
115
- {"Masking": 0.12}),
116
- "fear": (re.compile(r"\b(fear|scared|nervous|anxious|afraid)\b", re.IGNORECASE),
117
- {"Fear": 0.12, "Unpredictability": 0.05}),
118
- "think": (re.compile(r"\b(think|analyse|analyz|calculate|model|simulate|reason)\b", re.IGNORECASE),
119
- {"Strategy": 0.12, "Attention": 0.05}),
120
- "risk_up": (re.compile(r"\b(risk|gamble|bet|danger|reckless|thrill|adventur|dare)\b", re.IGNORECASE),
121
- {"RiskAppetite": 0.12}),
122
- "risk_down": (re.compile(r"\b(cautious|safe|avoid|conservativ|hesitant|secure|careful)\b", re.IGNORECASE),
123
- {"RiskAppetite": -0.12}),
124
  }
125
 
126
  TEMPLATE_UTTERANCES = [
127
- '(calm, structured) I appreciate the question. My approach is... [concise, no personal detail].',
128
- '(guarded) I prefer to focus on the professional aspects.',
129
- '(bold) I\'m willing to take that responsibility and here\'s why...',
130
- '(hesitant) That\'s an interesting point β€” could you clarify?',
131
- '(neutral) I tend to be methodical: step 1..., step 2...'
132
  ]
133
 
134
  PROMPT_TEMPLATE = """INSTRUCTION: Given the profiles and situation, output compact JSON with keys: mu, k, A_lowrank, sigma.
@@ -142,12 +121,10 @@ SITUATION:
142
 
143
  OUTPUT JSON:"""
144
 
145
- # =========================
146
- # State
147
- # =========================
148
  @dataclass
149
  class SessionState:
150
- values: Dict[str, float]
151
  round: int = 0
152
  last_target: Optional[str] = None
153
  last_q: Optional[str] = None
@@ -164,102 +141,85 @@ class SessionState:
164
 
165
  def init_state() -> SessionState:
166
  base = {
167
- "Attention": 0.5, "Empathy": 0.2, "Control": 0.8, "Masking": 0.6, "Interest": 0.5,
168
- "Relevance": 0.5, "Strategy": 0.7, "Fear": 0.5, "Trust": 0.3, "Validation": 0.5,
169
- "DominanceThreshold": 0.4, "Unpredictability": 0.3, "RiskAppetite": 0.5
170
  }
171
- return SessionState(values=defaultdict(lambda: 0.5, base))
172
 
173
  SESSIONS: Dict[str, SessionState] = {}
174
 
175
- # =========================
176
- # Optional FLAN model (lazy)
177
- # =========================
178
  _HF_TOKENIZER = None
179
  _HF_MODEL = None
180
 
181
- def load_flan(model_id: str = MODEL_ID_DEFAULT, device: str = DEVICE):
182
- """Lazy-load FLAN model if torch+transformers available; raise otherwise."""
183
  global _HF_TOKENIZER, _HF_MODEL
184
- if not (_HAS_TORCH and _HAS_TRANSFORMERS):
185
- raise RuntimeError("FLAN unavailable: missing torch/transformers.")
186
  if _HF_MODEL is None:
187
- print(f"[info] Loading Flan model {model_id} on {device}...")
 
188
  _HF_TOKENIZER = AutoTokenizer.from_pretrained(model_id)
189
  _HF_MODEL = AutoModelForSeq2SeqLM.from_pretrained(model_id)
190
- _HF_MODEL.to(torch.device(device))
191
  return _HF_TOKENIZER, _HF_MODEL
192
 
193
- # =========================
194
- # Prompt construction
195
- # =========================
196
- def build_prompt_from_profile(session: SessionState, extra_situation: Optional[Dict[str, Any]] = None) -> str:
197
  profiles_text = "- candidate: role=candidate, trust={:.3f}, dominance={:.3f}, vec=[{}]".format(
198
  session.values['Trust'], session.values['DominanceThreshold'],
199
- ','.join(f"{session.values.get(k, 0.5):.3f}" for k in ["Strategy", "Empathy", "Control", "Masking", "RiskAppetite"])
200
  )
201
- situation = {
202
- 'scenario': 'random_scene',
203
- 'stakes': 0.5,
204
- 'duration_mins': 10,
205
- 'unpredictability': session.values.get('Unpredictability', 0.3)
206
- }
207
  if extra_situation:
208
  situation.update(extra_situation)
209
- scenario_text = ', '.join([f"{k}={v}" for k, v in situation.items()])
210
  return PROMPT_TEMPLATE.format(profiles_text=profiles_text, scenario_text=scenario_text)
211
 
212
- # =========================
213
- # FLAN output parsing / fallbacks
214
- # =========================
215
- def _fallback_theta() -> Dict[str, Any]:
216
- mu = [1.0, 0.9, 0.85, 0.7, 0.35]
217
- k = [0.8, 0.9, 0.6, 0.5, 0.5]
218
- sigma = [0.02, 0.015, 0.03, 0.04, 0.03]
219
- U = [[0.0, 0.0], [0.0, 0.0], [0.0, -0.2], [0.0, 0.05], [0.0, 0.0]]
220
- V = [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, -0.1]]
221
- return {'mu': mu, 'k': k, 'A_lowrank': {'U': U, 'V': V}, 'sigma': sigma}
222
-
223
- def _parse_json_loose(text: str) -> Dict[str, Any]:
224
  try:
225
  return json.loads(text)
226
  except Exception:
227
- s = text.find('{')
228
- e = text.rfind('}')
229
  if s != -1 and e != -1 and e > s:
230
  try:
231
- return json.loads(text[s:e + 1])
232
  except Exception:
233
  pass
234
- print('[warn] Failed to parse JSON, using fallback')
 
235
  return _fallback_theta()
236
 
237
- def flan_generate_params(prompt: str, model_id: str = MODEL_ID_DEFAULT, device: str = DEVICE, max_length: int = 256) -> Dict[str, Any]:
238
- """Try to get parameters from FLAN; be very tolerant, else fallback."""
 
 
239
  try:
240
  tokenizer, model = load_flan(model_id, device)
241
  inputs = tokenizer(prompt, truncation=True, padding=True, return_tensors='pt', max_length=1024).to(model.device)
242
  outs = model.generate(**inputs, max_length=max_length, do_sample=False)
243
  text = tokenizer.decode(outs[0], skip_special_tokens=True)
244
  parsed = _parse_json_loose(text)
245
- if not isinstance(parsed, dict):
246
- raise ValueError("Parsed FLAN output not dict")
247
- mu = parsed.get('mu') or []
248
- k = parsed.get('k') or []
249
- sigma = parsed.get('sigma') or []
250
- # Minimal sanity
251
- if not (isinstance(mu, list) and isinstance(k, list) and isinstance(sigma, list)):
252
- raise ValueError("Invalid mu/k/sigma types")
253
- if len(mu) < 3 or len(k) < 3 or len(sigma) < 3:
254
- raise ValueError("Insufficient parameter lengths")
255
  return parsed
256
  except Exception as e:
257
- print('[warn] Flan generation failed or invalid shapes:', e)
258
  return _fallback_theta()
259
 
260
- # =========================
261
- # SDE simulation & decoding
262
- # =========================
263
  def _reconstruct_A(U: List[List[float]], V: List[List[float]]):
264
  Ua = np.array(U); Va = np.array(V)
265
  return Ua.dot(Va.T)
@@ -268,40 +228,38 @@ def simulate_sde(mu, k, A, sigma, X0, T=1.0, dt=0.002, n_samps=512, seed: int =
268
  rng = np.random.default_rng(seed)
269
  mu = np.array(mu); k = np.array(k); sigma = np.array(sigma); A = np.array(A)
270
  d = len(X0); steps = int(T/dt)
271
- X = np.tile(X0, (n_samps, 1)).astype(float)
272
- paths = np.zeros((n_samps, d, steps + 1), dtype=float)
273
- paths[:, :, 0] = X
274
  for i in range(steps):
275
  drift_revert = - (X - mu) * k
276
  drift_direct = X.dot(A.T) if A.size else 0.0
277
  drift = drift_revert + drift_direct
278
- dW = rng.normal(scale=np.sqrt(dt), size=(n_samps, d))
279
  diffusion = dW * sigma
280
  X = X + drift * dt + diffusion
281
  X = np.clip(X, 0.0, 1.5)
282
- paths[:, :, i + 1] = X
283
  return paths
284
 
285
  def extract_modes_from_paths(paths: np.ndarray, n_modes: int = 3):
286
  n_samps, d, steps = paths.shape
287
- n_modes = min(n_modes, n_samps) if n_samps > 0 else 0
288
- feats = np.concatenate([paths.mean(axis=2), paths[:, :, -1]], axis=1) if n_samps > 0 else np.zeros((0, 2*d))
 
 
 
 
 
 
 
289
  modes = []
290
- if n_modes <= 1 or not _HAS_SKLEARN or n_samps == 0:
291
- # Fallback: one mode = mean
292
- if n_samps > 0:
293
- mean_path = paths.mean(axis=0)
294
- last_state = mean_path[:, -1]
295
- modes = [{'mode': 0, 'weight': 1.0, 'last_state': last_state.tolist()}]
296
- return modes
297
- kmeans = KMeans(n_clusters=n_modes, random_state=0).fit(feats)
298
- labels = kmeans.labels_
299
  for mode in range(kmeans.n_clusters):
300
- idx = np.where(labels == mode)[0]
301
- weight = len(idx)/n_samps if n_samps > 0 else 0.0
302
- mean_path = paths[idx].mean(axis=0) if len(idx) > 0 else np.zeros((d, steps))
303
  last_state = mean_path[:, -1]
304
- modes.append({'mode': mode, 'weight': float(weight), 'last_state': last_state.tolist()})
305
  modes = sorted(modes, key=lambda m: -m['weight'])
306
  return modes
307
 
@@ -317,60 +275,42 @@ def decode_state(state_arr):
317
  return TEMPLATE_UTTERANCES[3]
318
  return TEMPLATE_UTTERANCES[4]
319
 
320
- def plot_paths(paths: np.ndarray, labels: List[str] = None):
321
- n_samps, d, steps = paths.shape
322
- t = np.linspace(0, 1, steps)
323
- fig, ax = plt.subplots(figsize=(8, 4))
324
- mean = paths.mean(axis=0)
325
- for i in range(d):
326
- ax.plot(t, mean[i], label=(labels[i] if labels else f'dim{i}'))
327
- ax.set_ylim(0, 1.2)
328
- ax.legend(loc='upper right')
329
- ax.set_xlabel('Normalized time'); ax.set_ylabel('State')
330
- plt.tight_layout()
331
- return fig
332
-
333
- # =========================
334
- # Scoring & dialogue control
335
- # =========================
336
  def score_updates(answer: str):
337
  updates = defaultdict(float)
338
  ans = (answer or "").lower()
339
  for _, (pat, upd) in _PATTERNS.items():
340
  if pat.search(ans):
341
- for k, v in upd.items():
342
  updates[k] += v
343
  return updates
344
 
345
- def apply_updates(session: SessionState, updates: Dict[str, float]):
346
- for k, v in updates.items():
347
- session.values[k] = min(1.0, max(0.0, session.values.get(k, 0.5) + v))
348
 
349
  def most_uncertain_dims(session: SessionState, k: int = 5):
350
- uncertainties = [(label, abs(session.values[label] - 0.5)) for label in LABELS]
351
- return [label for label, _ in sorted(uncertainties, key=lambda x: x[1])[:k]]
352
 
353
  def next_target(session: SessionState):
354
- dims = most_uncertain_dims(session)
355
  used = session.used_targets
356
  available = [d for d in dims if d not in used]
357
- if not available or len(used) >= len(LABELS) - 1:
358
  used.clear(); available = dims
359
  last = session.last_target
360
- if last and last in available and len(available) > 1:
361
  available.remove(last)
362
- target = random.choice(available) if available else dims[0]
363
- session.used_targets.add(target)
364
- return target
365
 
366
  def build_followup_prompt(prev_q: Optional[str], prev_a: Optional[str], target: str, session: SessionState):
367
  top3 = most_uncertain_dims(session, k=3)
368
  state_str = " | ".join(f"{d}:{session.values[d]:.2f}" for d in top3)
369
- return (
370
- f"Generate a short, unique question to probe {target.lower()}. "
371
- f"Context: Previous question was '{prev_q or 'None'}' with answer '{prev_a or 'None'}'. "
372
- f"Current state: {state_str}. Avoid repeating prior questions."
373
- )
374
 
375
  def get_initial_question(session: SessionState):
376
  available = [q for q in INITIAL_QUESTIONS if q not in session.used_questions]
@@ -379,218 +319,190 @@ def get_initial_question(session: SessionState):
379
  q = random.choice(available); session.used_questions.add(q)
380
  return q
381
 
382
- # =========================
383
- # Logging
384
- # =========================
385
- LOG_DIR = 'runs'
386
- os.makedirs(LOG_DIR, exist_ok=True)
387
- LOG_PATH = os.path.join(LOG_DIR, 'logs.jsonl')
 
 
388
 
389
- def log_run(entry: Dict[str, Any]):
390
- try:
391
- with open(LOG_PATH, 'a', encoding='utf-8') as f:
392
- f.write(json.dumps(entry, ensure_ascii=False) + '\n')
393
- if HAS_DATASETS and 'HF_TOKEN' in os.environ and 'HF_DATASET_REPO' in os.environ:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
394
  try:
395
- ds = Dataset.from_json(LOG_PATH)
396
- ds.push_to_hub(os.environ['HF_DATASET_REPO'], token=os.environ['HF_TOKEN'])
397
- print("[info] Pushed logs to HF Hub dataset")
 
 
 
 
 
398
  except Exception as e:
399
- print(f"[warn] Failed to push logs to HF Hub: {e}")
400
- except Exception as e:
401
- print(f'Warning: failed to write log: {e}')
402
-
403
- # =========================
404
- # Session lifecycle
405
- # =========================
406
- def start_session() -> Tuple[str, Dict[str, float], str]:
407
- sid = str(int(time.time() * 1000))
408
- SESSIONS[sid] = init_state()
409
- q = get_initial_question(SESSIONS[sid])
410
- return sid, dict(SESSIONS[sid].values), q
411
-
412
- def parse_situation_input(s: Optional[str]) -> Optional[Dict[str, Any]]:
413
- if not s:
414
- return None
415
- s = s.strip()
416
- try:
417
- return json.loads(s)
418
- except Exception:
419
- out: Dict[str, Any] = {}
420
- for part in re.split(r'[,\n]+', s):
421
- if '=' in part:
422
- k, v = part.split('=', 1)
423
- k = k.strip(); v = v.strip()
424
- try:
425
- if v.lower() in ('true', 'false'):
426
- out[k] = v.lower() == 'true'
427
- else:
428
- out[k] = float(v) if re.match(r'^-?\d+(\.\d+)?$', v) else v
429
- except Exception:
430
- out[k] = v
431
- return out if out else None
432
-
433
- def predict_from_session(session: SessionState, use_flan: bool = True, model_id: str = MODEL_ID_DEFAULT,
434
- n_samps: int = 512, extra_situation: Optional[Dict[str, Any]] = None):
435
- prompt = build_prompt_from_profile(session, extra_situation=extra_situation)
436
- use_flan = use_flan and _HAS_TORCH and _HAS_TRANSFORMERS # force off if unavailable
437
- theta = flan_generate_params(prompt, model_id=model_id, device=DEVICE) if use_flan else _fallback_theta()
438
-
439
- mu = theta.get('mu', [])
440
- k = theta.get('k', [])
441
- sigma = theta.get('sigma', [])
442
- A_lowrank = theta.get('A_lowrank', {})
443
- U = A_lowrank.get('U', [])
444
- V = A_lowrank.get('V', [])
445
-
446
- # Safe A reconstruction
447
  try:
448
- A = _reconstruct_A(U, V) if (len(U) > 0 and len(V) > 0 and len(U) == len(mu) and len(V) == len(mu)) else np.zeros((len(mu), len(mu)))
449
  except Exception:
450
- A = np.zeros((len(mu), len(mu)))
451
-
452
- # 5-dim state vector
453
- X0 = np.array([
454
- session.values.get('Strategy', 0.5),
455
- session.values.get('Empathy', 0.5),
456
- session.values.get('Control', 0.5),
457
- session.values.get('Masking', 0.5),
458
- session.values.get('RiskAppetite', 0.5)
459
- ])
460
-
461
- # Pad/trunc for safety
462
- def pad_or_trunc(arr, target_len, fill=0.0):
463
- if arr is None:
464
- return np.array([fill] * target_len)
465
- a = np.array(arr, dtype=float) if len(arr) > 0 else np.array([], dtype=float)
466
- if len(a) < target_len:
467
- return np.concatenate([a, np.full(target_len - len(a), fill)])
468
- return a[:target_len]
469
-
470
- mu = pad_or_trunc(mu, 5, fill=0.5)
471
- k = pad_or_trunc(k, 5, fill=0.5)
472
- sigma = pad_or_trunc(sigma, 5, fill=0.02)
473
-
474
  paths = simulate_sde(mu, k, A, sigma, X0, n_samps=n_samps)
475
  modes = extract_modes_from_paths(paths, n_modes=3)
476
  for m in modes:
477
- m['utterance'] = decode_state(np.array(m['last_state']))
478
- return {'modes': modes, 'prompt': prompt, 'theta': theta, 'paths': paths}
479
-
480
- def user_reply(session_id: str, user_input: str, use_flan: bool = True, model_id: str = MODEL_ID_DEFAULT,
481
- n_samps: int = 256, extra_situation: Optional[Dict[str, Any]] = None):
482
- if session_id not in SESSIONS:
483
- return 'ERROR: unknown session', {}, ''
484
- session = SESSIONS[session_id]
485
- cmd = (user_input or "").strip().upper()
486
-
487
- if cmd == 'RESET':
488
- SESSIONS[session_id] = init_state()
489
- q = get_initial_question(SESSIONS[session_id])
490
- return session_id, dict(SESSIONS[session_id].values), q
491
-
492
- if cmd == 'STOP':
493
- out = predict_from_session(session, use_flan=use_flan, model_id=model_id, n_samps=n_samps, extra_situation=extra_situation)
494
- entry = {
495
- 'timestamp': time.time(),
496
- 'session_id': session_id,
497
- 'profile_start': dict(session.values),
498
- 'situation': out['prompt'],
499
- 'theta': out['theta'],
500
- 'modes': out['modes']
501
- }
502
- log_run(entry)
503
- return session_id, dict(session.values), 'FINAL:' + json.dumps({'modes': out['modes']})
504
-
505
- # Normal flow: score + next question
506
- updates = score_updates(user_input)
507
- apply_updates(session, updates)
508
- target = next_target(session)
509
- session.last_target = target
510
- prompt = build_followup_prompt(session.last_q, user_input, target, session)
511
- question = FALLBACK_QUESTIONS.get(target)
512
-
513
- # Question generation via FLAN if available
514
- if use_flan and _HAS_TORCH and _HAS_TRANSFORMERS:
515
  try:
516
- tokenizer, model = load_flan(model_id, DEVICE)
517
- inputs = tokenizer(prompt, return_tensors='pt', truncation=True, max_length=512).to(model.device)
518
- outs = model.generate(**inputs, max_new_tokens=40, do_sample=False)
519
- q_text = tokenizer.decode(outs[0], skip_special_tokens=True).strip()
520
- if q_text.endswith('?') and q_text not in session.used_questions and 'probe' not in q_text.lower():
521
- question = q_text
522
  except Exception as e:
523
- print('Warn: question-gen failed:', e)
524
-
525
- session.used_questions.add(question)
526
- session.last_q = question
527
- session.round += 1
528
- session.history.append({'user': user_input, 'bot': question})
529
- return session_id, dict(session.values), question
530
-
531
- # =========================
532
- # UI
533
- # =========================
534
- with gr.Blocks(title='Flan-SDE Behavioral Profiler') as demo:
535
- gr.Markdown("# Flan-SDE Behavioral Profiler\nAsk questions, build a profile, and simulate behavior (FLAN-generated SDE).")
 
 
 
 
536
 
 
 
 
537
  with gr.Row():
538
  with gr.Column(scale=1):
539
- start_btn = gr.Button('Start Session')
540
- sid_out = gr.Textbox(label='Session ID')
541
- profile_view = gr.JSON(label='Current Profile')
542
- qbox = gr.Textbox(label='Bot question', interactive=False)
543
- user_in = gr.Textbox(placeholder='Type your answer. Type STOP to finish, RESET to restart.')
544
- send_btn = gr.Button('Send')
545
- use_flan_chk = gr.Checkbox(value=_HAS_TORCH and _HAS_TRANSFORMERS, label='Use real Flan-T5 (may be slow on CPU)')
546
- model_in = gr.Textbox(value=MODEL_ID_DEFAULT, label='Flan model id')
547
- n_samps_slider = gr.Slider(minimum=64, maximum=1024, value=256, step=64, label='Monte Carlo paths')
548
- situation_in = gr.Textbox(label='Situation JSON (optional)', placeholder='{"scenario":"meeting","stakes":0.7,"duration_mins":15}', lines=3)
549
-
550
  with gr.Column(scale=1):
551
- out_console = gr.Textbox(label='Console', interactive=False)
552
- modes_json = gr.JSON(label='Predicted Modes')
553
- plot_out = gr.Plot(label='Trajectory (mean)')
554
-
555
- def on_start():
556
- sid, prof, q = start_session()
557
- return sid, prof, q, ''
558
-
559
- def on_send(sid, user_text, prof, q, use_flan, model_id, n_samps, situation_raw):
 
 
 
 
 
 
 
560
  try:
561
- if not sid:
562
- return gr.update(value=''), {}, '', 'ERROR: start a session first', {}, None
563
- parsed_sit = parse_situation_input(situation_raw)
564
- sid2, profdict, next_q = user_reply(
565
- sid, user_text, use_flan=bool(use_flan), model_id=model_id, n_samps=int(n_samps), extra_situation=parsed_sit
566
- )
567
- if isinstance(next_q, str) and next_q.startswith('FINAL:'):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
568
  try:
569
- out = predict_from_session(SESSIONS[sid2], use_flan=bool(use_flan), model_id=model_id,
570
- n_samps=int(n_samps), extra_situation=parsed_sit)
571
- fig = plot_paths(out['paths'], labels=["Strategy", "Empathy", "Control", "Masking", "RiskAppetite"])
572
- return sid2, profdict, '', 'Prediction complete', out['modes'], fig
573
- except Exception as e:
574
- tb = traceback.format_exc()
575
- print('[error] Prediction failed:', e, tb)
576
- return sid2, profdict, '', f'Prediction failed: {e}\n{tb}', {}, None
 
 
 
 
 
577
  else:
578
- return sid2, profdict, next_q, '', {}, None
579
  except Exception as e:
580
  tb = traceback.format_exc()
581
- print('[error] on_send crashed:', e, tb)
582
- return sid, prof or {}, '', f'Exception: {e}\n{tb}', {}, None
583
-
584
- start_btn.click(on_start, outputs=[sid_out, profile_view, qbox, out_console])
585
- send_btn.click(
586
- on_send,
587
- inputs=[sid_out, user_in, profile_view, qbox, use_flan_chk, model_in, n_samps_slider, situation_in],
588
- outputs=[sid_out, profile_view, qbox, out_console, modes_json, plot_out]
589
- )
590
 
591
- # =========================
592
- # Entrypoint
593
- # =========================
594
  if __name__ == "__main__":
595
- port = int(os.environ.get('PORT', 7860))
596
- demo.launch(server_name='0.0.0.0', server_port=port, share=False)
 
1
  #!/usr/bin/env python3
2
+ # app.py -- Flan-SDE Profiler adapted for Hugging Face Spaces (Gradio UI + optional FastAPI)
3
 
4
  """
5
+ Drop into a HF Space. requirements.txt must include:
6
+ gradio, transformers, torch, scikit-learn, sentence-transformers (optional)
7
+ Environment variables:
8
+ MODEL_ID (optional, default google/flan-t5-small)
9
+ SDE_MODE (if '1' => secure local-only behavior)
10
+ SEED (optional)
11
  """
12
 
13
+ from typing import Dict, Any, List, Optional, Tuple
 
 
 
14
  from dataclasses import dataclass
15
  from collections import defaultdict
16
  import os
17
  import json
18
+ import re
19
  import random
20
+ import time
21
  import traceback
 
22
 
 
23
  import numpy as np
24
 
25
+ # plotting (headless safe)
26
  import matplotlib
27
+ matplotlib.use("Agg")
28
  import matplotlib.pyplot as plt
29
 
 
30
  import gradio as gr
31
 
32
+ # transformers + torch (lazy use)
 
 
 
 
 
 
 
 
 
33
  try:
34
  import torch
35
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
 
 
 
 
 
36
  _HAS_TRANSFORMERS = True
37
  except Exception:
38
+ _HAS_TRANSFORMERS = False
39
 
40
+ # sklearn clustering optional
 
41
  try:
42
  from sklearn.cluster import KMeans
43
  _HAS_SKLEARN = True
44
  except Exception:
45
+ _HAS_SKLEARN = False
46
 
47
+ # optional sentence-transformers for utterance embeddings
48
+ try:
49
+ from sentence_transformers import SentenceTransformer
50
+ _HAS_SENTENCE_TRANSFORMERS = True
51
+ except Exception:
52
+ _HAS_SENTENCE_TRANSFORMERS = False
53
+
54
+ # ---------- Config ----------
55
+ MODEL_ID = os.environ.get("MODEL_ID", "google/flan-t5-small")
56
+ SDE_MODE = os.environ.get("SDE_MODE", "0") == "1"
57
+ SEED = int(os.environ.get("SEED", 42))
58
 
 
59
  random.seed(SEED)
60
+ np.random.seed(SEED)
61
+
62
+ DEFAULT_DEVICE = "cuda" if (_HAS_TRANSFORMERS and torch.cuda.is_available()) else "cpu"
63
 
64
  LABELS = [
65
+ "Attention","Empathy","Control","Masking","Interest","Relevance","Strategy",
66
+ "Fear","Trust","Validation","DominanceThreshold","Unpredictability","RiskAppetite"
67
  ]
68
 
69
  INITIAL_QUESTIONS = [
 
74
  ]
75
 
76
  FALLBACK_QUESTIONS = {
77
+ "Attention":"How does your focus shift in demanding situations?",
78
+ "Empathy":"What role does understanding others play in your decisions?",
79
+ "Control":"How do you maintain influence over a situation?",
80
+ "Masking":"When do you hide your true intentions?",
81
+ "Interest":"What keeps you engaged in a task?",
82
+ "Relevance":"How do you decide what matters most in a scenario?",
83
+ "Strategy":"How do you plan your approach to challenges?",
84
+ "Fear":"What makes you feel cautious or hesitant?",
85
+ "Trust":"When do you feel comfortable relying on others?",
86
+ "Validation":"What makes you feel recognized or valued?",
87
+ "DominanceThreshold":"How much control do you need to feel secure?",
88
+ "Unpredictability":"How do you handle unexpected twists?",
89
+ "RiskAppetite":"What drives you to take bold risks?"
90
  }
91
 
92
+ # fixed regexes (removed stray control characters)
93
  _PATTERNS = {
94
+ "control": (re.compile(r"\b(manipulat|control|dominat|exploit|test|punish|revenge|hurt)\b", re.IGNORECASE), {"Control":0.12,"Strategy":0.08,"Masking":0.05}),
95
+ "empathy": (re.compile(r"\b(trust|like|care|feel|empath|compass)\b", re.IGNORECASE), {"Empathy":0.12,"Trust":0.08}),
96
+ "bored": (re.compile(r"\b(bore|boring|meh|dont care|who cares|whatever)\b", re.IGNORECASE), {"Interest":-0.15,"Relevance":0.10}),
97
+ "happy": (re.compile(r"\b(happy|fun|enjoy|excite|pleasur|thrill)\b", re.IGNORECASE), {"Validation":0.08,"Interest":0.08}),
98
+ "mask": (re.compile(r"\b(fake|act|mask|perform|play a role)\b", re.IGNORECASE), {"Masking":0.12}),
99
+ "fear": (re.compile(r"\b(fear|scared|nervous|anxious|afraid)\b", re.IGNORECASE), {"Fear":0.12,"Unpredictability":0.05}),
100
+ "think": (re.compile(r"\b(think|analyse|analyz|calculate|model|simulate|reason)\b", re.IGNORECASE), {"Strategy":0.12,"Attention":0.05}),
101
+ "risk_up": (re.compile(r"\b(risk|gamble|bet|danger|reckless|thrill|adventur|dare)\b", re.IGNORECASE), {"RiskAppetite":0.12}),
102
+ "risk_down":(re.compile(r"\b(cautious|safe|avoid|conservativ|hesitant|secure|careful)\b", re.IGNORECASE), {"RiskAppetite":-0.12}),
 
 
 
 
 
 
 
 
 
103
  }
104
 
105
  TEMPLATE_UTTERANCES = [
106
+ "(calm, structured) I appreciate the question. My approach is... [concise, no personal detail].",
107
+ "(guarded) I prefer to focus on the professional aspects.",
108
+ "(bold) I'm willing to take that responsibility and here's why...",
109
+ "(hesitant) That's an interesting point β€” could you clarify?",
110
+ "(neutral) I tend to be methodical: step 1..., step 2..."
111
  ]
112
 
113
  PROMPT_TEMPLATE = """INSTRUCTION: Given the profiles and situation, output compact JSON with keys: mu, k, A_lowrank, sigma.
 
121
 
122
  OUTPUT JSON:"""
123
 
124
+ # ---------- state ----------
 
 
125
  @dataclass
126
  class SessionState:
127
+ values: Dict[str,float]
128
  round: int = 0
129
  last_target: Optional[str] = None
130
  last_q: Optional[str] = None
 
141
 
142
  def init_state() -> SessionState:
143
  base = {
144
+ "Attention":0.5,"Empathy":0.2,"Control":0.8,"Masking":0.6,"Interest":0.5,
145
+ "Relevance":0.5,"Strategy":0.7,"Fear":0.5,"Trust":0.3,"Validation":0.5,
146
+ "DominanceThreshold":0.4,"Unpredictability":0.3,"RiskAppetite":0.5
147
  }
148
+ return SessionState(values=defaultdict(lambda:0.5, base))
149
 
150
  SESSIONS: Dict[str, SessionState] = {}
151
 
152
+ # ---------- model lazy loader ----------
 
 
153
  _HF_TOKENIZER = None
154
  _HF_MODEL = None
155
 
156
+ def load_flan(model_id: str = MODEL_ID, device: str = DEFAULT_DEVICE, lazy=True):
157
+ """Lazy load Flan T5; raise informative error if transformers not installed or model fails."""
158
  global _HF_TOKENIZER, _HF_MODEL
159
+ if not _HAS_TRANSFORMERS:
160
+ raise RuntimeError("transformers/torch not available in runtime. Set requirements accordingly.")
161
  if _HF_MODEL is None:
162
+ # cache model artifacts inside /data when SDE_MODE to avoid leaking
163
+ print(f"[info] Loading model {model_id} on device {device} (SDE_MODE={SDE_MODE})")
164
  _HF_TOKENIZER = AutoTokenizer.from_pretrained(model_id)
165
  _HF_MODEL = AutoModelForSeq2SeqLM.from_pretrained(model_id)
166
+ _HF_MODEL.to(torch.device("cuda" if device=="cuda" else "cpu"))
167
  return _HF_TOKENIZER, _HF_MODEL
168
 
169
+ # ---------- prompt builder ----------
170
+ def build_prompt_from_profile(session: SessionState, extra_situation: Optional[Dict[str,Any]]=None) -> str:
 
 
171
  profiles_text = "- candidate: role=candidate, trust={:.3f}, dominance={:.3f}, vec=[{}]".format(
172
  session.values['Trust'], session.values['DominanceThreshold'],
173
+ ','.join(f"{session.values.get(k,0.5):.3f}" for k in ["Strategy","Empathy","Control","Masking","RiskAppetite"])
174
  )
175
+ situation = {'scenario':'random_scene','stakes':0.5,'duration_mins':10,'unpredictability':session.values.get('Unpredictability',0.3)}
 
 
 
 
 
176
  if extra_situation:
177
  situation.update(extra_situation)
178
+ scenario_text = ', '.join([f"{k}={v}" for k,v in situation.items()])
179
  return PROMPT_TEMPLATE.format(profiles_text=profiles_text, scenario_text=scenario_text)
180
 
181
+ # ---------- flan output parsing and fallback ----------
182
+ def _fallback_theta() -> Dict[str,Any]:
183
+ mu = [1.0,0.9,0.85,0.7,0.35]
184
+ k = [0.8,0.9,0.6,0.5,0.5]
185
+ sigma = [0.02,0.015,0.03,0.04,0.03]
186
+ U = [[0.0,0.0],[0.0,0.0],[0.0,-0.2],[0.0,0.05],[0.0,0.0]]
187
+ V = [[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,-0.1]]
188
+ return {'mu':mu,'k':k,'A_lowrank':{'U':U,'V':V},'sigma':sigma}
189
+
190
+ def _parse_json_loose(text: str) -> Dict[str,Any]:
 
 
191
  try:
192
  return json.loads(text)
193
  except Exception:
194
+ s = text.find('{'); e = text.rfind('}')
 
195
  if s != -1 and e != -1 and e > s:
196
  try:
197
+ return json.loads(text[s:e+1])
198
  except Exception:
199
  pass
200
+ # last resort: warn and fallback
201
+ print("[warn] flan output not parseable -> using fallback theta")
202
  return _fallback_theta()
203
 
204
+ def flan_generate_params(prompt: str, model_id: str = MODEL_ID, device: str = DEFAULT_DEVICE, max_length: int = 256) -> Dict[str,Any]:
205
+ # If transformers not present, return fallback
206
+ if not _HAS_TRANSFORMERS:
207
+ return _fallback_theta()
208
  try:
209
  tokenizer, model = load_flan(model_id, device)
210
  inputs = tokenizer(prompt, truncation=True, padding=True, return_tensors='pt', max_length=1024).to(model.device)
211
  outs = model.generate(**inputs, max_length=max_length, do_sample=False)
212
  text = tokenizer.decode(outs[0], skip_special_tokens=True)
213
  parsed = _parse_json_loose(text)
214
+ # some light validation
215
+ if not isinstance(parsed, dict) or 'mu' not in parsed or 'k' not in parsed or 'sigma' not in parsed:
216
+ raise ValueError("Parsed FLAN output missing keys")
 
 
 
 
 
 
 
217
  return parsed
218
  except Exception as e:
219
+ print("[warn] FLAN generation failed:", e)
220
  return _fallback_theta()
221
 
222
+ # ---------- SDE utils ----------
 
 
223
  def _reconstruct_A(U: List[List[float]], V: List[List[float]]):
224
  Ua = np.array(U); Va = np.array(V)
225
  return Ua.dot(Va.T)
 
228
  rng = np.random.default_rng(seed)
229
  mu = np.array(mu); k = np.array(k); sigma = np.array(sigma); A = np.array(A)
230
  d = len(X0); steps = int(T/dt)
231
+ X = np.tile(X0, (n_samps,1)).astype(float)
232
+ paths = np.zeros((n_samps,d,steps+1), dtype=float)
233
+ paths[:,:,0] = X
234
  for i in range(steps):
235
  drift_revert = - (X - mu) * k
236
  drift_direct = X.dot(A.T) if A.size else 0.0
237
  drift = drift_revert + drift_direct
238
+ dW = rng.normal(scale=np.sqrt(dt), size=(n_samps,d))
239
  diffusion = dW * sigma
240
  X = X + drift * dt + diffusion
241
  X = np.clip(X, 0.0, 1.5)
242
+ paths[:,:,i+1] = X
243
  return paths
244
 
245
  def extract_modes_from_paths(paths: np.ndarray, n_modes: int = 3):
246
  n_samps, d, steps = paths.shape
247
+ if n_samps == 0:
248
+ return []
249
+ feats = np.concatenate([paths.mean(axis=2), paths[:,:, -1]], axis=1)
250
+ if not _HAS_SKLEARN or n_samps <= n_modes:
251
+ # fallback: single mode
252
+ mean_path = paths.mean(axis=0)
253
+ last_state = mean_path[:, -1]
254
+ return [{'mode':0,'weight':1.0,'last_state':last_state.tolist()}]
255
+ kmeans = KMeans(n_clusters=n_modes, random_state=SEED).fit(feats)
256
  modes = []
 
 
 
 
 
 
 
 
 
257
  for mode in range(kmeans.n_clusters):
258
+ idx = np.where(kmeans.labels_ == mode)[0]
259
+ weight = len(idx)/n_samps
260
+ mean_path = paths[idx].mean(axis=0) if len(idx)>0 else np.zeros((d,steps))
261
  last_state = mean_path[:, -1]
262
+ modes.append({'mode':mode,'weight':float(weight),'last_state':last_state.tolist()})
263
  modes = sorted(modes, key=lambda m: -m['weight'])
264
  return modes
265
 
 
275
  return TEMPLATE_UTTERANCES[3]
276
  return TEMPLATE_UTTERANCES[4]
277
 
278
+ # ---------- profiler / chat logic ----------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
  def score_updates(answer: str):
280
  updates = defaultdict(float)
281
  ans = (answer or "").lower()
282
  for _, (pat, upd) in _PATTERNS.items():
283
  if pat.search(ans):
284
+ for k,v in upd.items():
285
  updates[k] += v
286
  return updates
287
 
288
+ def apply_updates(session: SessionState, updates: Dict[str,float]):
289
+ for k,v in updates.items():
290
+ session.values[k] = min(1.0, max(0.0, session.values.get(k,0.5) + v))
291
 
292
  def most_uncertain_dims(session: SessionState, k: int = 5):
293
+ uncertainties = [(label, abs(session.values[label]-0.5)) for label in LABELS]
294
+ return [label for label,_ in sorted(uncertainties, key=lambda x: x[1])[:k]]
295
 
296
  def next_target(session: SessionState):
297
+ dims = most_uncertain_dims(session, k=5)
298
  used = session.used_targets
299
  available = [d for d in dims if d not in used]
300
+ if not available or len(used) >= len(LABELS)-1:
301
  used.clear(); available = dims
302
  last = session.last_target
303
+ if last and last in available and len(available)>1:
304
  available.remove(last)
305
+ t = random.choice(available) if available else dims[0]
306
+ session.used_targets.add(t)
307
+ return t
308
 
309
  def build_followup_prompt(prev_q: Optional[str], prev_a: Optional[str], target: str, session: SessionState):
310
  top3 = most_uncertain_dims(session, k=3)
311
  state_str = " | ".join(f"{d}:{session.values[d]:.2f}" for d in top3)
312
+ return (f"Generate a short, unique question to probe {target.lower()}. Context: Previous question was '{prev_q or 'None'}' "
313
+ f"with answer '{prev_a or 'None'}'. Current state: {state_str}. Avoid repeating prior questions.")
 
 
 
314
 
315
  def get_initial_question(session: SessionState):
316
  available = [q for q in INITIAL_QUESTIONS if q not in session.used_questions]
 
319
  q = random.choice(available); session.used_questions.add(q)
320
  return q
321
 
322
+ # ---------- chat / predict endpoints (used by Gradio UI) ----------
323
+ def chat_step(session_id: str, user_input: str, use_flan: bool = True):
324
+ if not session_id:
325
+ # create ephemeral session id
326
+ session_id = str(int(time.time()*1000)) + "_" + str(random.randint(0,9999))
327
+ if session_id not in SESSIONS:
328
+ SESSIONS[session_id] = init_state()
329
+ session = SESSIONS[session_id]
330
 
331
+ cmd = (user_input or "").strip().upper()
332
+ if cmd == "RESET":
333
+ SESSIONS[session_id] = init_state()
334
+ session = SESSIONS[session_id]
335
+ q = get_initial_question(session)
336
+ session.history.append((None, q))
337
+ return session_id, q, session.history
338
+ if cmd == "STOP":
339
+ profile = {k:float(session.values.get(k,0.5)) for k in LABELS}
340
+ session.history.append((user_input, {"final_profile":profile}))
341
+ return session_id, json.dumps(profile, indent=2), session.history
342
+
343
+ if session.round == 0:
344
+ q = get_initial_question(session)
345
+ else:
346
+ updates = score_updates(user_input)
347
+ apply_updates(session, updates)
348
+ target = next_target(session)
349
+ session.last_target = target
350
+ prompt = build_followup_prompt(session.last_q, user_input, target, session)
351
+ # generate a followup question optionally via FLAN
352
+ question = FALLBACK_QUESTIONS[target]
353
+ if use_flan and _HAS_TRANSFORMERS:
354
  try:
355
+ tok, mdl = load_flan(MODEL_ID, DEFAULT_DEVICE)
356
+ # use pipeline wrapper for convenience
357
+ gen_pipe = pipeline("text2text-generation", model=mdl, tokenizer=tok, device=(0 if DEFAULT_DEVICE=="cuda" else -1))
358
+ out = gen_pipe(prompt, max_new_tokens=40, do_sample=False)
359
+ qtxt = out[0].get("generated_text") or out[0].get("summary_text") or str(out[0])
360
+ qtxt = qtxt.strip()
361
+ if qtxt.endswith("?") and qtxt not in session.used_questions and "probe" not in qtxt.lower() and qtxt != session.last_q:
362
+ question = qtxt
363
  except Exception as e:
364
+ # fallback silently to safe question
365
+ print("[warn] followup question generation failed:", e)
366
+ question = FALLBACK_QUESTIONS[target]
367
+
368
+ session.used_questions.add(question)
369
+ q = question
370
+
371
+ session.last_q = q
372
+ session.round += 1
373
+ session.history.append((user_input, q))
374
+ return session_id, q, session.history
375
+
376
+ def predict_from_session(session_id: str, extra_situation: Optional[Dict[str,Any]] = None, use_flan: bool = True, n_samps: int = 512):
377
+ if session_id not in SESSIONS:
378
+ raise ValueError("Unknown session id")
379
+ session = SESSIONS[session_id]
380
+ prompt = build_prompt_from_profile(session, extra_situation)
381
+ theta = flan_generate_params(prompt) if (use_flan and _HAS_TRANSFORMERS) else _fallback_theta()
382
+ mu = theta.get("mu"); k = theta.get("k"); sigma = theta.get("sigma")
383
+ U = theta.get("A_lowrank",{}).get("U",[]); V = theta.get("A_lowrank",{}).get("V",[])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
384
  try:
385
+ A = _reconstruct_A(U,V)
386
  except Exception:
387
+ A = np.zeros((len(mu),len(mu)))
388
+ X0 = np.array([session.values.get('Strategy',0.5), session.values.get('Empathy',0.5), session.values.get('Control',0.5), session.values.get('Masking',0.5), session.values.get('RiskAppetite',0.5)])
389
+ # ensure mu/k/sigma have length 5
390
+ def pad_or_trunc(arr, L, fill=0.5):
391
+ a = np.array(arr) if arr is not None else np.array([])
392
+ if len(a) < L:
393
+ return np.concatenate([a, np.full(L-len(a), fill)])
394
+ return a[:L]
395
+ mu = pad_or_trunc(mu,5,fill=0.5)
396
+ k = pad_or_trunc(k,5,fill=0.5)
397
+ sigma = pad_or_trunc(sigma,5,fill=0.02)
 
 
 
 
 
 
 
 
 
 
 
 
 
398
  paths = simulate_sde(mu, k, A, sigma, X0, n_samps=n_samps)
399
  modes = extract_modes_from_paths(paths, n_modes=3)
400
  for m in modes:
401
+ m["utterance"] = decode_state(np.array(m["last_state"]))
402
+ # optional embeddings (local only)
403
+ if _HAS_SENTENCE_TRANSFORMERS:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
404
  try:
405
+ st = SentenceTransformer("all-MiniLM-L6-v2")
406
+ emb = st.encode([m["utterance"] for m in modes])
407
+ for i,m in enumerate(modes):
408
+ m["embedding"] = emb[i].tolist()
 
 
409
  except Exception as e:
410
+ print("[warn] sentence-transformers embed failed:", e)
411
+ return {"modes":modes, "prompt":prompt, "theta":theta}
412
+
413
+ # ---------- plotting helper ----------
414
+ def plot_paths(paths):
415
+ n_samps,d,steps = paths.shape
416
+ t = np.linspace(0,1,steps)
417
+ fig, ax = plt.subplots(figsize=(8,4))
418
+ mean = paths.mean(axis=0)
419
+ labels = ["Strategy","Empathy","Control","Masking","RiskAppetite"]
420
+ for i in range(d):
421
+ ax.plot(t, mean[i], label=labels[i] if i<len(labels) else f"dim{i}")
422
+ ax.set_ylim(0,1.2)
423
+ ax.legend(loc="upper right")
424
+ ax.set_xlabel("Normalized time"); ax.set_ylabel("State")
425
+ plt.tight_layout()
426
+ return fig
427
 
428
+ # ---------- Gradio UI ----------
429
+ with gr.Blocks(title="Flan-SDE Profiler (Spaces)") as demo:
430
+ gr.Markdown("## Flan-SDE Profiler β€” interactive profiling bot\nSDE-mode (secure local) = **{}**".format(SDE_MODE))
431
  with gr.Row():
432
  with gr.Column(scale=1):
433
+ sid = gr.Textbox(label="Session ID (leave blank to create)")
434
+ user_txt = gr.Textbox(placeholder="Type your answer. 'STOP' to finish, 'RESET' to restart.", lines=2)
435
+ start_btn = gr.Button("Start / New Session")
436
+ send_btn = gr.Button("Send")
437
+ use_flan_chk = gr.Checkbox(value=_HAS_TRANSFORMERS, label="Use FLAN model (may be slow on CPU)")
438
+ model_box = gr.Textbox(value=MODEL_ID, label="Model ID")
439
+ n_samps = gr.Slider(minimum=64, maximum=1024, step=64, value=256, label="Monte Carlo paths")
440
+ extra_sit = gr.Textbox(label="Extra Situation JSON (optional)", placeholder='{"scenario":"meeting","stakes":0.6}')
 
 
 
441
  with gr.Column(scale=1):
442
+ bot_q = gr.Textbox(label="Bot question", interactive=False)
443
+ history_box = gr.JSON(label="Recent history")
444
+ modes_box = gr.JSON(label="Predicted modes (when STOP)")
445
+ plot_out = gr.Plot(label="Trajectory (mean)")
446
+
447
+ def ui_start(_sid):
448
+ # create a new session if blank
449
+ if not _sid:
450
+ _sid = str(int(time.time()*1000)) + "_" + str(random.randint(0,9999))
451
+ if _sid not in SESSIONS:
452
+ SESSIONS[_sid] = init_state()
453
+ q = get_initial_question(SESSIONS[_sid])
454
+ SESSIONS[_sid].history.append((None,q))
455
+ return _sid, q, SESSIONS[_sid].history
456
+
457
+ def ui_send(session_id, user_text, use_flan, model_id, samp_count, extra_situation_raw):
458
  try:
459
+ sid_local = session_id or ""
460
+ # parse extra situation JSON tolerant
461
+ extra_sit = None
462
+ if extra_situation_raw:
463
+ try:
464
+ extra_sit = json.loads(extra_situation_raw)
465
+ except Exception:
466
+ parts = re.split(r'[,\n]+', extra_situation_raw)
467
+ out={}
468
+ for p in parts:
469
+ if '=' in p:
470
+ k,v = p.split('=',1)
471
+ try:
472
+ out[k.strip()] = float(v.strip())
473
+ except Exception:
474
+ out[k.strip()] = v.strip()
475
+ extra_sit = out if out else None
476
+ sid_new, q, history = chat_step(sid_local, user_text, use_flan=bool(use_flan))
477
+ # if STOP returned final profile string in q (we use special), run predict
478
+ if (user_text or "").strip().upper() == "STOP":
479
+ out = predict_from_session(sid_new, extra_situation=extra_sit, use_flan=bool(use_flan), n_samps=int(samp_count))
480
+ fig = plot_paths(np.array(out.get("modes")[0].get("last_state")).reshape(1,-1,1)) if out.get("modes") else None
481
+ # instead, produce full paths to plot if available
482
  try:
483
+ # recompute paths for plotting full trajectories
484
+ session = SESSIONS[sid_new]
485
+ theta = out["theta"]
486
+ mu = theta.get("mu"); k = theta.get("k"); sigma = theta.get("sigma")
487
+ U = theta.get("A_lowrank",{}).get("U",[]); V = theta.get("A_lowrank",{}).get("V",[])
488
+ A = _reconstruct_A(U,V) if U and V else np.zeros((5,5))
489
+ X0 = np.array([session.values.get('Strategy',0.5), session.values.get('Empathy',0.5), session.values.get('Control',0.5), session.values.get('Masking',0.5), session.values.get('RiskAppetite',0.5)])
490
+ mu = np.array(mu); k = np.array(k); sigma = np.array(sigma)
491
+ paths = simulate_sde(mu,k,A,sigma,X0,n_samps=int(samp_count))
492
+ fig = plot_paths(paths)
493
+ except Exception:
494
+ fig = None
495
+ return sid_new, "", history[-10:], out.get("modes"), fig
496
  else:
497
+ return sid_new, q, history[-10:], None, None
498
  except Exception as e:
499
  tb = traceback.format_exc()
500
+ return session_id or "", f"ERROR: {e}", [], None, None
501
+
502
+ start_btn.click(ui_start, inputs=[sid], outputs=[sid, bot_q, history_box])
503
+ send_btn.click(ui_send, inputs=[sid, user_txt, use_flan_chk, model_box, n_samps, extra_sit], outputs=[sid, bot_q, history_box, modes_box, plot_out])
 
 
 
 
 
504
 
505
+ # ---------- launch (Spaces will run this file) ----------
 
 
506
  if __name__ == "__main__":
507
+ # On Spaces, simply run demo; otherwise it will serve via gradio
508
+ demo.launch(server_name="0.0.0.0", share=False)