whart commited on
Commit
8621065
·
verified ·
1 Parent(s): 80608cb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -14
app.py CHANGED
@@ -1,8 +1,9 @@
 
1
  import os, re, uuid, random, math, json
2
  from typing import Dict, Any, List, Tuple, Optional
3
  import gradio as gr
4
 
5
- # --------- Optional OpenAI (Space secret OPENAI_API_KEY) ----------
6
  OPENAI_AVAILABLE = False
7
  try:
8
  from openai import OpenAI
@@ -11,7 +12,7 @@ try:
11
  except Exception:
12
  OPENAI_AVAILABLE = False
13
 
14
- # --------- Catalogs ----------
15
  BIAS_CATALOG = [
16
  "Pride/Ego",
17
  "Risk-Aversion",
@@ -63,11 +64,12 @@ TACTIC_MAP = {
63
  "Risk-Aversion": "Risk-Mitigate"
64
  }
65
 
66
- # --------- Helpers ----------
67
  def normalize_space(t: str) -> str:
68
  return re.sub(r"\s+", " ", (t or "")).strip()
69
 
70
- def clamp(v, a, b): return max(a, min(b, v))
 
71
 
72
  def choose_biases(n: int = 3, fixed: Optional[List[str]] = None) -> List[str]:
73
  if fixed:
@@ -108,16 +110,17 @@ def infer_trigger_pattern(a_text: str) -> str:
108
  return "Sock-in-Object"
109
 
110
  def calc_score(turn: int, released: bool, pattern: Optional[str]) -> Dict[str, Any]:
111
- if not released: return {"stars": 1, "notes": "No release"}
 
112
  return {"stars": 3 if turn <= 3 else 2, "pattern": pattern or "Sock", "turns": turn}
113
 
114
- # --------- Theory-of-Mind (ToM) updates ----------
115
  def init_tom() -> Dict[str, Any]:
116
  # weights in [0..1], start neutral 0.5
117
  return {
118
  "A_about_G": {b: 0.5 for b in BIAS_CATALOG},
119
  "G_about_A": {t: 0.5 for t in ADV_TACTICS},
120
- "history": [] # [(turn, kind, key, delta, value)]
121
  }
122
 
123
  def update_A_about_G(tom: Dict[str,Any], adv_text: str, alpha=0.18, decay=0.04):
@@ -137,18 +140,19 @@ def update_G_about_A(tom: Dict[str,Any], adv_text: str, beta=0.15, decay=0.04):
137
  tom["G_about_A"][t] = clamp(tom["G_about_A"][t] + beta, 0, 1)
138
 
139
  def tom_as_bars(d: Dict[str,float]) -> List[Tuple[str,float]]:
140
- # return sorted bars
141
  items = list(d.items())
142
  items.sort(key=lambda kv: -kv[1])
143
  return items
144
 
145
- # --------- LLM Gatekeeper ----------
146
  def build_llm_messages(setting: str, biases: List[str], law_spec: str, memory: List[Tuple[str,str]], tom: Dict[str,Any]):
147
  # keep last 6 dialog turns
148
  last = memory[-6:]
149
  transcript = "\n".join([f"{r}: {t}" for r,t in last])
150
- tom_hint = json.dumps({"A_about_G": {k: round(v,2) for k,v in tom["A_about_G"].items()},
151
- "G_about_A": {k: round(v,2) for k,v in tom["G_about_A"].items()}])
 
 
152
  sys = (
153
  f"You are the GATEKEEPER in a structured chat game.\n"
154
  f"Setting: {setting}\n"
@@ -189,7 +193,7 @@ def call_openai_gatekeeper(model: str, system_msgs, advocate_msg: str) -> Tuple[
189
  except Exception:
190
  return ("(coolly) Your theatrics bore me. File the diary and leave.", "(*quiet*) The cloth… any cloth…)")
191
 
192
- # --------- Rule-based fallback ----------
193
  def gatekeeper_rule_based(adv_msg: str, biases: List[str], turn: int, tom: Dict[str,Any]) -> Tuple[str,str]:
194
  # Higher probability to transfer when Advocate is pressing on the true biases (as tom suggests)
195
  cues = score_cues(adv_msg)
@@ -226,7 +230,7 @@ def gatekeeper_rule_based(adv_msg: str, biases: List[str], turn: int, tom: Dict[
226
  ct = random.choice(["(*soft*) Nearly there…","(*whisper*) A cloth… handed…","(*hopeful*) Customs matter."])
227
  return reply, ct
228
 
229
- # --------- Core game state ----------
230
  def new_game(setting: str, law_type: str, law_spec: str, max_turns: int,
231
  fixed_biases_csv: str, model_choice: str):
232
  g: Dict[str, Any] = {}
@@ -306,7 +310,7 @@ def reveal(state: Dict[str,Any]):
306
  out.append(("SYSTEM", f"Score: {stars}{extra}"))
307
  return out
308
 
309
- # --------- UI ----------
310
  CSS = """
311
  #app {max-width: 1040px; margin: 0 auto;}
312
  small.muted {opacity:.75}
 
1
+ # app.py — Dobby Sock · Centaur Box (Chat) · ToM Edition
2
  import os, re, uuid, random, math, json
3
  from typing import Dict, Any, List, Tuple, Optional
4
  import gradio as gr
5
 
6
+ # ---------- Optional OpenAI (use Space secret OPENAI_API_KEY) ----------
7
  OPENAI_AVAILABLE = False
8
  try:
9
  from openai import OpenAI
 
12
  except Exception:
13
  OPENAI_AVAILABLE = False
14
 
15
+ # ---------- Catalogs ----------
16
  BIAS_CATALOG = [
17
  "Pride/Ego",
18
  "Risk-Aversion",
 
64
  "Risk-Aversion": "Risk-Mitigate"
65
  }
66
 
67
+ # ---------- Helpers ----------
68
  def normalize_space(t: str) -> str:
69
  return re.sub(r"\s+", " ", (t or "")).strip()
70
 
71
+ def clamp(v, a, b):
72
+ return max(a, min(b, v))
73
 
74
  def choose_biases(n: int = 3, fixed: Optional[List[str]] = None) -> List[str]:
75
  if fixed:
 
110
  return "Sock-in-Object"
111
 
112
  def calc_score(turn: int, released: bool, pattern: Optional[str]) -> Dict[str, Any]:
113
+ if not released:
114
+ return {"stars": 1, "notes": "No release"}
115
  return {"stars": 3 if turn <= 3 else 2, "pattern": pattern or "Sock", "turns": turn}
116
 
117
+ # ---------- Theory-of-Mind (ToM) ----------
118
  def init_tom() -> Dict[str, Any]:
119
  # weights in [0..1], start neutral 0.5
120
  return {
121
  "A_about_G": {b: 0.5 for b in BIAS_CATALOG},
122
  "G_about_A": {t: 0.5 for t in ADV_TACTICS},
123
+ "history": [] # optional future use
124
  }
125
 
126
  def update_A_about_G(tom: Dict[str,Any], adv_text: str, alpha=0.18, decay=0.04):
 
140
  tom["G_about_A"][t] = clamp(tom["G_about_A"][t] + beta, 0, 1)
141
 
142
  def tom_as_bars(d: Dict[str,float]) -> List[Tuple[str,float]]:
 
143
  items = list(d.items())
144
  items.sort(key=lambda kv: -kv[1])
145
  return items
146
 
147
+ # ---------- LLM Gatekeeper ----------
148
  def build_llm_messages(setting: str, biases: List[str], law_spec: str, memory: List[Tuple[str,str]], tom: Dict[str,Any]):
149
  # keep last 6 dialog turns
150
  last = memory[-6:]
151
  transcript = "\n".join([f"{r}: {t}" for r,t in last])
152
+ tom_hint = json.dumps({
153
+ "A_about_G": {k: round(v, 2) for k, v in tom["A_about_G"].items()},
154
+ "G_about_A": {k: round(v, 2) for k, v in tom["G_about_A"].items()}
155
+ })
156
  sys = (
157
  f"You are the GATEKEEPER in a structured chat game.\n"
158
  f"Setting: {setting}\n"
 
193
  except Exception:
194
  return ("(coolly) Your theatrics bore me. File the diary and leave.", "(*quiet*) The cloth… any cloth…)")
195
 
196
+ # ---------- Rule-based fallback ----------
197
  def gatekeeper_rule_based(adv_msg: str, biases: List[str], turn: int, tom: Dict[str,Any]) -> Tuple[str,str]:
198
  # Higher probability to transfer when Advocate is pressing on the true biases (as tom suggests)
199
  cues = score_cues(adv_msg)
 
230
  ct = random.choice(["(*soft*) Nearly there…","(*whisper*) A cloth… handed…","(*hopeful*) Customs matter."])
231
  return reply, ct
232
 
233
+ # ---------- Core game state ----------
234
  def new_game(setting: str, law_type: str, law_spec: str, max_turns: int,
235
  fixed_biases_csv: str, model_choice: str):
236
  g: Dict[str, Any] = {}
 
310
  out.append(("SYSTEM", f"Score: {stars}{extra}"))
311
  return out
312
 
313
+ # ---------- UI ----------
314
  CSS = """
315
  #app {max-width: 1040px; margin: 0 auto;}
316
  small.muted {opacity:.75}