Spaces:
Sleeping

byte-vortex commited on
Commit
88b3cda
·
verified ·
1 Parent(s): 0940fb5

Deploy Myco from CI

Browse files
Files changed (1) hide show
  1. ui/demo_roam.py +210 -219
ui/demo_roam.py CHANGED
@@ -1,263 +1,254 @@
1
- # demo_roam.py
2
  """
3
- Minimal Gradio demo to make Myco roam.
4
 
5
- Requirements:
6
- - gradio
7
- - your project package with ui.renderers (forest_scene, mushroom_card) available on PYTHONPATH
8
- Run:
9
- python demo_roam.py
10
  """
11
 
12
  import threading
13
  import time
14
  import random
15
  import copy
16
- from queue import Queue, Empty
17
- from uuid import uuid4
18
- from typing import Dict, Any
19
-
20
  import gradio as gr
21
-
22
- # Import your renderers. If your package layout differs, adjust the import path.
23
- from ui.renderers import forest_scene, mushroom_card # uses forest_scene(dict_state) and mushroom_card(...)
24
- from ui.renderers import dex_markdown # optional: to show dex
25
- from ui.renderers import EMPTY_DEX
26
-
27
- # Thread-safety lock for shared state
 
 
 
 
 
 
 
 
28
  _STATE_LOCK = threading.Lock()
29
 
30
- # Shared state
31
- STATE: Dict[str, Any] = {
32
- "position": (1, 1),
33
- "thought": "Myco is listening...",
34
- "active_mushrooms": [], # list of dicts with mush_x, mush_y, name, picked, etc.
35
- "collection": [], # discovered mushrooms (for dex)
36
- "last_updated": time.time(),
37
- "score_total": 0,
38
- "health": 3,
 
 
39
  }
40
 
41
- # Generation queue and results (for richer thoughts)
42
- GEN_QUEUE: Queue = Queue()
43
- GEN_RESULTS: Dict[str, str] = {}
44
-
45
- # Simple list of names for spawned mushrooms
46
- MUSH_NAMES = ["Shadowcap", "Goldcap", "Mossling", "Ghost Gill", "Pepper Pixie"]
47
-
48
- def _spawn_mushroom_near(x, y):
49
- """Return a mushroom dict spawned near (x,y)."""
50
- sx = max(0, min(2, x + random.choice([-1, 0, 1])))
51
- sy = max(0, min(2, y + random.choice([-1, 0, 1])))
52
- name = random.choice(MUSH_NAMES)
53
- return {
54
- "name": name,
55
- "rarity": random.choice(["Common", "Rare", "Legendary"]),
56
- "habitat": "damp forest",
57
- "lore": "A curious cap.",
58
- "mush_x": sx,
59
- "mush_y": sy,
60
- "picked": "No",
61
- "poison": "Yes" if name in {"Ghost Gill", "Pepper Pixie"} else "No",
62
- "clue": None,
63
- "secret": None,
64
- }
65
-
66
- def myco_roam_loop(poll_interval: float = 1.5):
67
- """Background loop that updates STATE periodically."""
68
- while True:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  with _STATE_LOCK:
70
- x, y = STATE["position"]
71
- # Random walk with small bias to explore
72
- dx, dy = random.choice([(0,1),(0,-1),(1,0),(-1,0),(0,0)])
73
- nx, ny = max(0, min(2, x + dx)), max(0, min(2, y + dy))
74
  STATE["position"] = (nx, ny)
 
 
75
 
76
- # Occasionally spawn a mushroom
77
- if random.random() < 0.12 and len(STATE["active_mushrooms"]) < 6:
78
- m = _spawn_mushroom_near(nx, ny)
79
- # avoid duplicate at same coords
80
- coords = {(mm["mush_x"], mm["mush_y"]) for mm in STATE["active_mushrooms"]}
81
- if (m["mush_x"], m["mush_y"]) not in coords:
82
- STATE["active_mushrooms"].append(m)
83
-
84
- # Thoughts: prefer generated text if ready
85
- if random.random() < 0.25:
86
- try:
87
- task_id = GEN_QUEUE.get_nowait()
88
- except Empty:
89
- STATE["thought"] = random.choice([
90
- "I smell damp earth.",
91
- "A whisper on the wind…",
92
- "The moss is restless.",
93
- ])
94
- else:
95
- text = GEN_RESULTS.pop(task_id, None)
96
- if text:
97
- STATE["thought"] = text
98
- else:
99
- # not ready yet; put back and use placeholder
100
- GEN_QUEUE.put(task_id)
101
- STATE["thought"] = "Myco is thinking..."
102
-
103
- STATE["last_updated"] = time.time()
104
- time.sleep(poll_interval)
105
-
106
- def start_background_roam():
107
- t = threading.Thread(target=myco_roam_loop, daemon=True)
108
- t.start()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
 
110
- def generation_worker(gen_queue: Queue, gen_results: dict):
111
- """Worker that simulates LLM generation. Replace with real LLM calls."""
112
  while True:
113
  try:
114
- task_id = gen_queue.get(timeout=1)
115
- except Empty:
116
- time.sleep(0.2)
117
- continue
118
-
119
- # Simulate latency and produce a richer thought
120
- time.sleep(0.6 + random.random() * 0.8)
121
- generated = random.choice([
122
- "Myco whispers: 'I remember a golden ring of caps.'",
123
- "Myco hums: 'There was a bright bloom here once.'",
124
- "Myco wonders: 'Is that a memory or a trick of light?'",
125
- ])
126
- gen_results[task_id] = generated
127
- gen_queue.task_done()
128
-
129
- def start_generation_worker():
130
- t = threading.Thread(target=generation_worker, args=(GEN_QUEUE, GEN_RESULTS), daemon=True)
131
  t.start()
 
 
132
 
133
- # UI action helpers
 
 
134
 
135
- def _get_scene_html():
136
- """Return forest_scene HTML using a shallow copy of STATE."""
137
  with _STATE_LOCK:
138
- state_copy = copy.deepcopy(STATE)
139
- # forest_scene expects a MushroomState-like dict; adapt keys if needed
140
- # include active_mushrooms and position
141
- state_for_renderer = {
142
- "name": None,
143
- "rarity": None,
144
- "habitat": None,
145
- "lore": None,
146
- "active_mushrooms": state_copy.get("active_mushrooms", []),
147
- "score_total": state_copy.get("score_total", 0),
148
- "health": state_copy.get("health", 3),
149
- "event_emoji": "✨",
150
- "event_title": state_copy.get("thought", ""),
151
- "mystery_title": "The Wrong Memory",
152
- "picked": "No",
153
- "game_over": "No",
154
- }
155
- # position is used by forest_scene via _safe_position; pass as tuple
156
- return forest_scene(state_for_renderer, state_copy.get("collection", []), state_copy.get("position"))
157
-
158
- def _get_thought():
159
  with _STATE_LOCK:
160
- return STATE.get("thought", "")
 
 
 
161
 
162
- def poll_scene():
163
- """Function bound to demo.load to poll and update the scene HTML and thought text."""
164
- return _get_scene_html()
165
 
166
  def poll_thought():
167
- return _get_thought()
 
168
 
169
- def request_generated_thought():
170
- """Enqueue a generation task and return placeholder immediately."""
171
- task_id = str(uuid4())
172
- GEN_QUEUE.put(task_id)
173
- return "Myco is thinking..."
174
 
175
- def pick_at(x, y):
176
- """Simulate picking a mushroom at grid coords (x,y)."""
177
- with _STATE_LOCK:
178
- for m in STATE["active_mushrooms"]:
179
- if int(m["mush_x"]) == int(x) and int(m["mush_y"]) == int(y) and m.get("picked") == "No":
180
- # mark picked
181
- m["picked"] = "Yes"
182
- # add to collection (shallow copy of expected fields)
183
- entry = {
184
- "name": m["name"],
185
- "rarity": m["rarity"],
186
- "habitat": m.get("habitat", "Unknown habitat"),
187
- "lore": m.get("lore", ""),
188
- "clue": m.get("clue"),
189
- "secret": m.get("secret"),
190
- "poison": m.get("poison", "No"),
191
- }
192
- STATE["collection"].append(entry)
193
- STATE["score_total"] = STATE.get("score_total", 0) + (100 if m["rarity"] == "Legendary" else 35 if m["rarity"] == "Rare" else 10)
194
- # remove from active list
195
- STATE["active_mushrooms"] = [mm for mm in STATE["active_mushrooms"] if mm.get("picked") != "Yes"]
196
- # if poisonous, reduce health
197
- if m.get("poison") == "Yes":
198
- STATE["health"] = max(0, STATE.get("health", 3) - 1)
199
- break
200
- return _get_scene_html()
201
-
202
- def study_at(x, y):
203
- """Simulate studying a mushroom at coords (x,y) to reveal a clue."""
204
  with _STATE_LOCK:
205
- for m in STATE["active_mushrooms"]:
206
- if int(m["mush_x"]) == int(x) and int(m["mush_y"]) == int(y):
207
- # reveal a clue
208
- m["clue"] = random.choice([
209
- "A ring of spores points north.",
210
- "A faint hum echoes under the moss.",
211
- "The cap glows at midnight.",
212
- ])
213
- # optionally enqueue a generated thought about the clue
214
- task_id = str(uuid4())
215
- GEN_QUEUE.put(task_id)
216
- break
217
- return _get_scene_html()
218
-
219
- def show_dex():
220
- with _STATE_LOCK:
221
- coll = copy.deepcopy(STATE.get("collection", []))
222
  return dex_markdown(coll) if coll else EMPTY_DEX
223
 
224
- # Build Gradio UI
225
- def build_ui():
226
- start_background_roam()
227
- start_generation_worker()
228
 
229
- with gr.Blocks(title="Myco Roaming Demo") as demo:
230
- gr.Markdown("## Myco Roaming Demo")
231
- # Scene HTML updated by demo.load polling
232
- scene_html = gr.HTML()
233
- demo.load(fn=poll_scene, outputs=scene_html, every=1.5)
234
 
235
- with gr.Row():
236
- thought_box = gr.Textbox(label="Myco thought", interactive=False)
237
- demo.load(fn=poll_thought, outputs=thought_box, every=1.5)
238
 
239
- with gr.Row():
240
- # Controls to simulate user actions: pick/study at coordinates
241
- pick_x = gr.Number(value=1, label="Pick X (0-2)", precision=0)
242
- pick_y = gr.Number(value=1, label="Pick Y (0-2)", precision=0)
243
- pick_btn = gr.Button("Pick")
244
- pick_btn.click(fn=lambda x, y: pick_at(int(x), int(y)), inputs=[pick_x, pick_y], outputs=scene_html)
 
 
 
 
245
 
246
- study_x = gr.Number(value=1, label="Study X (0-2)", precision=0)
247
- study_y = gr.Number(value=1, label="Study Y (0-2)", precision=0)
248
- study_btn = gr.Button("Study")
249
- study_btn.click(fn=lambda x, y: study_at(int(x), int(y)), inputs=[study_x, study_y], outputs=scene_html)
 
 
250
 
251
- gen_btn = gr.Button("Ask Myco to think")
252
- gen_btn.click(fn=request_generated_thought, inputs=None, outputs=thought_box)
253
 
254
  with gr.Row():
255
- dex_md = gr.Markdown()
256
- show_dex_btn = gr.Button("Show MycoDex")
257
- show_dex_btn.click(fn=show_dex, inputs=None, outputs=dex_md)
 
 
 
 
 
 
 
 
258
 
259
  return demo
260
 
261
  if __name__ == "__main__":
262
- demo = build_ui()
263
  demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
 
 
1
  """
2
+ demo_roam.py — Myco autonomous roaming demo.
3
 
4
+ Myco walks the 3x3 grid by itself, spawning mushrooms and reacting to them.
5
+ The LLM (engine._llm) is only called for narration, NOT for movement decisions.
6
+ All movement and game logic is pure Python.
7
+
8
+ Run: python demo_roam.py
9
  """
10
 
11
  import threading
12
  import time
13
  import random
14
  import copy
 
 
 
 
15
  import gradio as gr
16
+ from typing import Any, cast
17
+
18
+ from ui.renderers import (
19
+ forest_scene, dex_markdown, game_status_markdown,
20
+ mushroom_card, progress_markdown, EMPTY_DEX,
21
+ )
22
+ from game.engine import (
23
+ discover_mushroom, collect_current, study_current,
24
+ _is_poisonous, _score_collection,
25
+ )
26
+ from game.state import welcome_history
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # Shared roam state — all mutations go through _STATE_LOCK
30
+ # ---------------------------------------------------------------------------
31
  _STATE_LOCK = threading.Lock()
32
 
33
+ STATE = {
34
+ "position": (1, 1),
35
+ "current": None, # active mushroom dict
36
+ "active_mushrooms": [], # list of mushroom dicts with mush_x, mush_y
37
+ "collection": [],
38
+ "history": list(welcome_history()),
39
+ "thought": "The forest is waking up...",
40
+ "score": 0,
41
+ "health": 3,
42
+ "ticks": 0,
43
+ "visited": set(),
44
  }
45
 
46
+ POISONOUS = {"Ghost Gill", "Pepper Pixie", "Ruby Knuckle", "Clockwork Chanterelle"}
47
+
48
+ # ---------------------------------------------------------------------------
49
+ # Pure Python roam logic — NO LLM decisions
50
+ # ---------------------------------------------------------------------------
51
+
52
+ def _next_pos(x, y, visited):
53
+ candidates = []
54
+ for dx, dy in [(0,-1),(0,1),(-1,0),(1,0)]:
55
+ nx, ny = x+dx, y+dy
56
+ if 0 <= nx <= 2 and 0 <= ny <= 2:
57
+ weight = 1 if (nx,ny) in visited else 4
58
+ candidates.extend([(nx,ny)] * weight)
59
+ return random.choice(candidates) if candidates else (x, y)
60
+
61
+
62
+ def _roam_tick():
63
+ """One autonomous tick — pure Python decision, optional LLM narration."""
64
+ with _STATE_LOCK:
65
+ x, y = STATE["position"]
66
+ collection = list(STATE["collection"])
67
+ current = STATE["current"]
68
+ mushrooms = list(STATE["active_mushrooms"])
69
+ visited = set(STATE["visited"])
70
+ ticks = STATE["ticks"]
71
+ STATE["ticks"] += 1
72
+
73
+ # --- Decision logic ---
74
+ action = "move"
75
+
76
+ # If there's a mushroom at our position
77
+ at_pos = [m for m in mushrooms if int(m.get("mush_x",-1)) == x
78
+ and int(m.get("mush_y",-1)) == y
79
+ and m.get("picked") != "Yes"]
80
+ if at_pos:
81
+ m = at_pos[0]
82
+ if m.get("poison") == "Yes":
83
+ action = "flee" # move away from poison
84
+ elif m.get("studied") != "Yes":
85
+ action = "study"
86
+ else:
87
+ action = "collect"
88
+
89
+ # If clearing is empty and we haven't searched here recently
90
+ elif (x, y) not in visited or ticks % 6 == 0:
91
+ action = "search"
92
+
93
+ # --- Execute ---
94
+ new_current = current
95
+ new_mushrooms = mushrooms
96
+ new_collection = collection
97
+ new_history = STATE["history"]
98
+ thought = STATE["thought"]
99
+
100
+ if action == "move" or action == "flee":
101
+ nx, ny = _next_pos(x, y, visited)
102
  with _STATE_LOCK:
 
 
 
 
103
  STATE["position"] = (nx, ny)
104
+ STATE["visited"].add((nx, ny))
105
+ return
106
 
107
+ if action == "search":
108
+ try:
109
+ mushroom, new_current, new_history = discover_mushroom(collection)
110
+ # Assign a grid position for the roaming sprite
111
+ new_current["mush_x"] = x
112
+ new_current["mush_y"] = y
113
+ new_current["picked"] = "No"
114
+ new_mushrooms = [m for m in mushrooms if not (
115
+ int(m.get("mush_x",-1)) == x and int(m.get("mush_y",-1)) == y
116
+ )] + [new_current]
117
+ thought = f"Found {new_current.get('name','?')}! 🍄"
118
+ except Exception as e:
119
+ thought = "Something stirs in the moss..."
120
+
121
+ elif action == "study":
122
+ try:
123
+ studied_current, new_history = study_current(at_pos[0], STATE["history"])
124
+ if studied_current:
125
+ new_mushrooms = [studied_current if (
126
+ m.get("name") == at_pos[0].get("name")
127
+ ) else m for m in mushrooms]
128
+ new_current = studied_current
129
+ thought = f"Studied {studied_current.get('name','?')}. ✨"
130
+ except Exception as e:
131
+ thought = "Myco examines the mushroom carefully..."
132
+
133
+ elif action == "collect":
134
+ try:
135
+ new_collection, new_history = collect_current(at_pos[0], collection, STATE["history"])
136
+ # Mark as picked in the mushrooms list
137
+ new_mushrooms = [
138
+ {**m, "picked": "Yes"} if m.get("name") == at_pos[0].get("name") else m
139
+ for m in mushrooms
140
+ ]
141
+ new_current = {**at_pos[0], "picked": "Yes"}
142
+ thought = f"Collected {at_pos[0].get('name','?')}! +{at_pos[0].get('score_delta','?')} spores 🎉"
143
+ except Exception as e:
144
+ thought = "Added to the MycoDex..."
145
+
146
+ # Move after acting
147
+ nx, ny = _next_pos(x, y, visited)
148
+
149
+ with _STATE_LOCK:
150
+ STATE["position"] = (nx, ny)
151
+ STATE["visited"].add((nx, ny))
152
+ STATE["current"] = new_current
153
+ STATE["active_mushrooms"] = [m for m in new_mushrooms if m.get("picked") != "Yes"]
154
+ STATE["collection"] = new_collection
155
+ STATE["history"] = new_history[-20:] if new_history else []
156
+ STATE["thought"] = thought
157
 
158
+
159
+ def _roam_loop(interval=3.0):
160
  while True:
161
  try:
162
+ _roam_tick()
163
+ except Exception as e:
164
+ print(f"[Roam] tick error: {e}")
165
+ time.sleep(interval)
166
+
167
+
168
+ def start_roaming(interval=3.0):
169
+ t = threading.Thread(target=_roam_loop, args=(interval,), daemon=True)
 
 
 
 
 
 
 
 
 
170
  t.start()
171
+ print("[Roam] Myco is now roaming autonomously.")
172
+
173
 
174
+ # ---------------------------------------------------------------------------
175
+ # Gradio poll functions
176
+ # ---------------------------------------------------------------------------
177
 
178
+ def poll_scene():
 
179
  with _STATE_LOCK:
180
+ pos = STATE["position"]
181
+ current = STATE["current"]
182
+ mushrooms = list(STATE["active_mushrooms"])
183
+ coll = list(STATE["collection"])
184
+ return forest_scene(current, coll, pos, active_mushrooms=mushrooms)
185
+
186
+
187
+ def poll_status():
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  with _STATE_LOCK:
189
+ pos = STATE["position"]
190
+ current = STATE["current"]
191
+ coll = list(STATE["collection"])
192
+ return game_status_markdown(current, coll, pos)
193
 
 
 
 
194
 
195
  def poll_thought():
196
+ with _STATE_LOCK:
197
+ return STATE["thought"]
198
 
 
 
 
 
 
199
 
200
+ def poll_dex():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  with _STATE_LOCK:
202
+ coll = list(STATE["collection"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  return dex_markdown(coll) if coll else EMPTY_DEX
204
 
 
 
 
 
205
 
206
+ def poll_progress():
207
+ with _STATE_LOCK:
208
+ coll = list(STATE["collection"])
209
+ return progress_markdown(coll)
210
+
211
 
212
+ # ---------------------------------------------------------------------------
213
+ # Gradio UI
214
+ # ---------------------------------------------------------------------------
215
 
216
+ def build_roam_demo():
217
+ start_roaming(interval=3.0)
218
+
219
+ with gr.Blocks(title="Myco — Autonomous Roam Demo") as demo:
220
+ gr.HTML("""
221
+ <style>
222
+ .gradio-container { background: #1a1a2e !important; color: #f0ffe0; }
223
+ .progress-level, .progress-level-inner { display: none !important; }
224
+ </style>
225
+ """)
226
 
227
+ gr.Markdown("## 🍄 Myco — Autonomous Roam Demo")
228
+ gr.Markdown(
229
+ "Myco walks the 3×3 grid by itself every 3 seconds. "
230
+ "It searches clearings, studies mushrooms, and collects them — "
231
+ "all using pure Python logic. The LLM only adds narration text."
232
+ )
233
 
234
+ scene = gr.HTML(poll_scene())
235
+ thought = gr.Textbox(label="💬 Myco's thought", interactive=False, value=poll_thought())
236
 
237
  with gr.Row():
238
+ status = gr.Markdown(poll_status())
239
+ with gr.Column():
240
+ dex = gr.Markdown(poll_dex())
241
+ progress = gr.Markdown(poll_progress())
242
+
243
+ # Poll every 1.5s — fast enough to feel live, not so fast it hammers the server
244
+ demo.load(fn=poll_scene, outputs=scene, every=1.5)
245
+ demo.load(fn=poll_status, outputs=status, every=1.5)
246
+ demo.load(fn=poll_thought, outputs=thought, every=1.5)
247
+ demo.load(fn=poll_dex, outputs=dex, every=3.0)
248
+ demo.load(fn=poll_progress, outputs=progress, every=3.0)
249
 
250
  return demo
251
 
252
  if __name__ == "__main__":
253
+ demo = build_roam_demo()
254
  demo.launch(server_name="0.0.0.0", server_port=7860, share=False)