Spaces:
Sleeping

byte-vortex commited on
Commit
267e47e
·
verified ·
1 Parent(s): 9c3e19a

Deploy Myco from CI

Browse files
Files changed (1) hide show
  1. ui/demo_roam.py +263 -0
ui/demo_roam.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)