Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,19 +1,3 @@
|
|
| 1 |
-
"""
|
| 2 |
-
hf_gradio_flan_sde_app.py
|
| 3 |
-
|
| 4 |
-
Single-file Gradio app (Hugging Face Spaces compatible) that:
|
| 5 |
-
- Runs a conversational profiler (13D) with question-driven probing.
|
| 6 |
-
- Uses a real Hugging Face Flan-T5 model (configurable) to output SDE parameters (mu, k, A_lowrank, sigma).
|
| 7 |
-
- Runs an EulerβMaruyama SDE simulator to produce trajectories and a final predicted state.
|
| 8 |
-
- Displays results and plots in the Gradio UI and logs each run to a local JSONL file for later export.
|
| 9 |
-
|
| 10 |
-
Notes for deployment:
|
| 11 |
-
- Put this file into a Spaces repo and set up `requirements.txt` with `transformers`, `torch`, `gradio`, `scikit-learn`, `numpy`, `matplotlib`.
|
| 12 |
-
- Spaces will run the file and serve the Gradio interface. The file is careful to avoid argparse conflicts in Colab/Spaces.
|
| 13 |
-
- If you want to persist logs to the Hugging Face Hub, set the env var `HF_TOKEN` and the app will try to push `runs/logs.jsonl` to a dataset (optional; requires `datasets` and proper permissions).
|
| 14 |
-
|
| 15 |
-
"""
|
| 16 |
-
|
| 17 |
import os
|
| 18 |
import json
|
| 19 |
import math
|
|
@@ -67,26 +51,26 @@ FALLBACK_QUESTIONS = {
|
|
| 67 |
"RiskAppetite": "What drives you to take bold risks?"
|
| 68 |
}
|
| 69 |
|
| 70 |
-
# Simple regex patterns for scoring (cleaned with
|
| 71 |
import re
|
| 72 |
_PATTERNS = {
|
| 73 |
-
"control": (re.compile(r"
|
| 74 |
{"Control": 0.12, "Strategy": 0.08, "Masking": 0.05}),
|
| 75 |
-
"empathy": (re.compile(r"
|
| 76 |
{"Empathy": 0.12, "Trust": 0.08}),
|
| 77 |
-
"bored": (re.compile(r"
|
| 78 |
{"Interest": -0.15, "Relevance": 0.10}),
|
| 79 |
-
"happy": (re.compile(r"
|
| 80 |
{"Validation": 0.08, "Interest": 0.08}),
|
| 81 |
-
"mask": (re.compile(r"
|
| 82 |
{"Masking": 0.12}),
|
| 83 |
-
"fear": (re.compile(r"
|
| 84 |
{"Fear": 0.12, "Unpredictability": 0.05}),
|
| 85 |
-
"think": (re.compile(r"
|
| 86 |
{"Strategy": 0.12, "Attention": 0.05}),
|
| 87 |
-
"risk_up": (re.compile(r"
|
| 88 |
{"RiskAppetite": 0.12}),
|
| 89 |
-
"risk_down": (re.compile(r"
|
| 90 |
{"RiskAppetite": -0.12}),
|
| 91 |
}
|
| 92 |
|
|
@@ -328,7 +312,7 @@ LOG_PATH = os.path.join(LOG_DIR, 'logs.jsonl')
|
|
| 328 |
def log_run(entry: Dict[str,Any]):
|
| 329 |
try:
|
| 330 |
with open(LOG_PATH, 'a', encoding='utf-8') as f:
|
| 331 |
-
f.write(json.dumps(entry, ensure_ascii=False) + '')
|
| 332 |
except Exception:
|
| 333 |
print('Warning: failed to write log')
|
| 334 |
|
|
@@ -358,7 +342,7 @@ def user_reply(session_id: str, user_input: str, use_flan: bool = True, model_id
|
|
| 358 |
out = predict_from_session(session, use_flan=use_flan, model_id=model_id, n_samps=n_samps)
|
| 359 |
entry = {'timestamp': time.time(), 'session_id': session_id, 'profile_start': dict(session.values), 'situation': out['prompt'], 'theta': out['theta'], 'modes': out['modes']}
|
| 360 |
log_run(entry)
|
| 361 |
-
return session_id, dict(session.values), 'FINAL:' + json.dumps({'modes': out['modes']}
|
| 362 |
|
| 363 |
# normal flow: score, update, generate next question
|
| 364 |
updates = score_updates(user_input)
|
|
@@ -445,23 +429,17 @@ with gr.Blocks(title='Flan-SDE Behavioral Profiler') as demo:
|
|
| 445 |
sid2, profdict, next_q = user_reply(sid, user_text, use_flan=use_flan, model_id=model_id, n_samps=int(n_samps))
|
| 446 |
# if STOP, user_reply returns FINAL:... as question; detect and run predict
|
| 447 |
if next_q.startswith('FINAL:'):
|
| 448 |
-
# extract modes from
|
| 449 |
try:
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
last = json.loads(lines[-1]) if lines else None
|
| 454 |
-
modes = last.get('modes') if last else []
|
| 455 |
-
fig = plot_paths(np.array(modes[0]['paths']) if 'paths' in modes[0] else np.zeros((1,5,2)))
|
| 456 |
except Exception:
|
| 457 |
modes = []
|
| 458 |
fig = None
|
| 459 |
-
return sid2, profdict, '', json.dumps(modes), fig
|
| 460 |
else:
|
| 461 |
return sid2, profdict, next_q, '', None, None
|
| 462 |
|
| 463 |
start_btn.click(on_start, outputs=[sid_out, profile_view, qbox, out_console])
|
| 464 |
-
send_btn.click(on_send, inputs=[sid_out, user_in, profile_view, qbox, use_flan_chk, model_in, n_samps_slider], outputs=[sid_out, profile_view, qbox, out_console, modes_json, plot_out])
|
| 465 |
-
|
| 466 |
-
if __name__ == '__main__':
|
| 467 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
import math
|
|
|
|
| 51 |
"RiskAppetite": "What drives you to take bold risks?"
|
| 52 |
}
|
| 53 |
|
| 54 |
+
# Simple regex patterns for scoring (cleaned with \b boundaries)
|
| 55 |
import re
|
| 56 |
_PATTERNS = {
|
| 57 |
+
"control": (re.compile(r"\b(manipulat|control|dominat|exploit|test|punish|revenge|hurt)\b", re.IGNORECASE),
|
| 58 |
{"Control": 0.12, "Strategy": 0.08, "Masking": 0.05}),
|
| 59 |
+
"empathy": (re.compile(r"\b(trust|like|care|feel|empath|compass)\b", re.IGNORECASE),
|
| 60 |
{"Empathy": 0.12, "Trust": 0.08}),
|
| 61 |
+
"bored": (re.compile(r"\b(bore|boring|meh|dont care|who cares|whatever)\b", re.IGNORECASE),
|
| 62 |
{"Interest": -0.15, "Relevance": 0.10}),
|
| 63 |
+
"happy": (re.compile(r"\b(happy|fun|enjoy|excite|pleasur|thrill)\b", re.IGNORECASE),
|
| 64 |
{"Validation": 0.08, "Interest": 0.08}),
|
| 65 |
+
"mask": (re.compile(r"\b(fake|act|mask|perform|play a role)\b", re.IGNORECASE),
|
| 66 |
{"Masking": 0.12}),
|
| 67 |
+
"fear": (re.compile(r"\b(fear|scared|nervous|anxious|afraid)\b", re.IGNORECASE),
|
| 68 |
{"Fear": 0.12, "Unpredictability": 0.05}),
|
| 69 |
+
"think": (re.compile(r"\b(think|analyse|analyz|calculate|model|simulate|reason)\b", re.IGNORECASE),
|
| 70 |
{"Strategy": 0.12, "Attention": 0.05}),
|
| 71 |
+
"risk_up": (re.compile(r"\b(risk|gamble|bet|danger|reckless|thrill|adventur|dare)\b", re.IGNORECASE),
|
| 72 |
{"RiskAppetite": 0.12}),
|
| 73 |
+
"risk_down": (re.compile(r"\b(cautious|safe|avoid|conservativ|hesitant|secure|careful)\b", re.IGNORECASE),
|
| 74 |
{"RiskAppetite": -0.12}),
|
| 75 |
}
|
| 76 |
|
|
|
|
| 312 |
def log_run(entry: Dict[str,Any]):
|
| 313 |
try:
|
| 314 |
with open(LOG_PATH, 'a', encoding='utf-8') as f:
|
| 315 |
+
f.write(json.dumps(entry, ensure_ascii=False) + '\n')
|
| 316 |
except Exception:
|
| 317 |
print('Warning: failed to write log')
|
| 318 |
|
|
|
|
| 342 |
out = predict_from_session(session, use_flan=use_flan, model_id=model_id, n_samps=n_samps)
|
| 343 |
entry = {'timestamp': time.time(), 'session_id': session_id, 'profile_start': dict(session.values), 'situation': out['prompt'], 'theta': out['theta'], 'modes': out['modes']}
|
| 344 |
log_run(entry)
|
| 345 |
+
return session_id, dict(session.values), 'FINAL:' + json.dumps({'modes': out['modes']})
|
| 346 |
|
| 347 |
# normal flow: score, update, generate next question
|
| 348 |
updates = score_updates(user_input)
|
|
|
|
| 429 |
sid2, profdict, next_q = user_reply(sid, user_text, use_flan=use_flan, model_id=model_id, n_samps=int(n_samps))
|
| 430 |
# if STOP, user_reply returns FINAL:... as question; detect and run predict
|
| 431 |
if next_q.startswith('FINAL:'):
|
| 432 |
+
# extract modes from next_q and re-compute predict for paths/plot
|
| 433 |
try:
|
| 434 |
+
modes = json.loads(next_q[6:])['modes']
|
| 435 |
+
out = predict_from_session(SESSIONS[sid2], use_flan=use_flan, model_id=model_id, n_samps=int(n_samps))
|
| 436 |
+
fig = plot_paths(out['paths'], labels=["Strategy", "Empathy", "Control", "Masking", "RiskAppetite"])
|
|
|
|
|
|
|
|
|
|
| 437 |
except Exception:
|
| 438 |
modes = []
|
| 439 |
fig = None
|
| 440 |
+
return sid2, profdict, '', 'Prediction complete', json.dumps(modes), fig
|
| 441 |
else:
|
| 442 |
return sid2, profdict, next_q, '', None, None
|
| 443 |
|
| 444 |
start_btn.click(on_start, outputs=[sid_out, profile_view, qbox, out_console])
|
| 445 |
+
send_btn.click(on_send, inputs=[sid_out, user_in, profile_view, qbox, use_flan_chk, model_in, n_samps_slider], outputs=[sid_out, profile_view, qbox, out_console, modes_json, plot_out])
|
|
|
|
|
|
|
|
|