Spaces:
Sleeping

byte-vortex commited on
Commit
1ec77db
·
verified ·
1 Parent(s): ef3f92d

Deploy Myco from CI

Browse files
Files changed (1) hide show
  1. game/engine.py +96 -177
game/engine.py CHANGED
@@ -1,28 +1,28 @@
1
  """
2
  Core Myco gameplay — LLM is the primary game engine.
3
  """
 
4
  import os
5
- import re
6
  import random
7
  import threading
 
 
8
  import traceback
 
9
  import torch
 
10
  from transformers import AutoModelForCausalLM, AutoTokenizer
11
 
12
- # Local imports
13
  from game.catalog import load_mushrooms
14
- from game.state import collection_contains, welcome_history
15
 
16
- # Global singletons
17
  DEFAULT_MODEL_ID = "google/gemma-3-1b-it"
 
 
18
  _model = None
19
  _tokenizer = None
20
  _lock = threading.Lock()
21
 
22
- # Define device (CPU by default)
23
- DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
24
- print(f"[Myco] Engine initializing on: {DEVICE.upper()}")
25
-
26
  def _get_model_and_tokenizer():
27
  global _model, _tokenizer
28
  if _model is not None and _tokenizer is not None:
@@ -32,45 +32,66 @@ def _get_model_and_tokenizer():
32
  if _model is not None and _tokenizer is not None:
33
  return _model, _tokenizer
34
 
35
- model_id = os.getenv("MYCO_MODEL_ID", DEFAULT_MODEL_ID)
36
  token = os.getenv("HF_BUILD_SMALL_HACKATHON_TOKEN")
37
 
38
  try:
39
- print(f"[Myco] Loading model: {model_id}...")
 
 
40
  _tokenizer = AutoTokenizer.from_pretrained(model_id, token=token)
41
 
42
- # Load with CPU-safe settings
43
  _model = AutoModelForCausalLM.from_pretrained(
44
  model_id,
45
  token=token,
46
- torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,
47
- device_map=DEVICE,
48
  trust_remote_code=True
49
  )
 
50
  return _model, _tokenizer
51
  except Exception as exc:
52
  print(f"[Myco] Load error: {exc}")
53
  return None, None
54
 
55
-
 
 
56
  def _get_pipeline():
57
- """Bridge function to resolve NameError for the pipeline."""
 
 
58
  model, tokenizer = _get_model_and_tokenizer()
59
- return model
60
-
 
 
61
 
 
 
 
 
62
  def _run_pipeline(pipe_ignored, messages):
63
- """Handles inference on the active device (CPU or GPU)."""
64
  model, tokenizer = _get_model_and_tokenizer()
65
- if model is None:
66
  return "The forest is silent. (Model loading failed)"
67
 
 
 
 
 
68
  formatted_prompt = tokenizer.apply_chat_template(
69
- messages, tokenize=False, add_generation_prompt=True
 
 
70
  )
71
 
72
- inputs = tokenizer(formatted_prompt, return_tensors="pt").to(DEVICE)
 
73
 
 
74
  with torch.no_grad():
75
  outputs = model.generate(
76
  **inputs,
@@ -80,16 +101,12 @@ def _run_pipeline(pipe_ignored, messages):
80
  pad_token_id=tokenizer.eos_token_id
81
  )
82
 
 
83
  input_length = inputs.input_ids.shape[1]
84
  generated_tokens = outputs[0][input_length:]
 
85
  return tokenizer.decode(generated_tokens, skip_special_tokens=True)
86
 
87
-
88
- # --- Ensure you have this global list accessible in engine.py ---
89
- POISONOUS_MUSHROOM_NAMES = {
90
- "Ghost Gill", "Pepper Pixie", "Ruby Knuckle", "Clockwork Chanterelle",
91
- }
92
-
93
  # ---------------------------------------------------------------------------
94
  # Template Helper (Fixes the Gemma TemplateError)
95
  # ---------------------------------------------------------------------------
@@ -265,7 +282,6 @@ def _llm(prompt: str, context: dict | None = None) -> str | None:
265
  # LLM call — multi-turn chat
266
  # ---------------------------------------------------------------------------
267
  def _llm_with_history(history: list, user_message: str, context: dict) -> str | None:
268
- """Chat function with strict ANTI-JSON guardrails."""
269
  pipe = _get_pipeline()
270
  if not pipe:
271
  return None
@@ -273,35 +289,33 @@ def _llm_with_history(history: list, user_message: str, context: dict) -> str |
273
  ctx = context or {}
274
  mushroom_line = ""
275
  if ctx.get("name"):
276
- poison_flag = " ⚠️ POISONOUS" if ctx.get("name") in POISONOUS_MUSHROOM_NAMES else ""
277
  mushroom_line = (
278
  f"Current mushroom: {ctx['name']} ({ctx.get('rarity','?')}){poison_flag}. "
279
  f"Lore: {ctx.get('lore','?')}. "
280
  f"Edible: {ctx.get('edible','Unknown')}. Magic: {ctx.get('magic','Unknown')}."
281
  )
282
 
283
- # The new strict anti-JSON prompt
284
  system = (
285
  f"{SYSTEM_PROMPT}\n\n"
286
  f"{mushroom_line}\n"
287
  f"MycoDex entries: {ctx.get('collection_count', 0)}. "
288
  f"Mystery: {ctx.get('mystery_title', 'The Wrong Memory')}. "
289
- f"Score: {ctx.get('score', 0)} spores. Health: {ctx.get('health', 3)}/3.\n\n"
290
- "--- CRITICAL CHAT INSTRUCTION ---\n"
291
- "You are chatting organically with the player. Speak ONLY in regular text dialogue.\n"
292
- "❌ DO NOT output any JSON structures, game actions, keys, or thoughts blocks (like {\"action\": ...}).\n"
293
- "❌ NEVER wrap your dialogue in a ```json markdown block.\n"
294
- "Just talk to them like a supportive mushroom companion!"
295
  )
296
 
 
297
  messages = _format_messages_for_template(system, user_message, history[-6:])
298
 
299
  try:
300
  reply = _run_pipeline(pipe, messages)
 
301
  print("========== MYCO OUTPUT ==========")
302
  print(reply)
303
  print("=================================")
 
304
  return reply
 
305
  except Exception as exc:
306
  print(f"[Myco] Inference error: {exc}")
307
  traceback.print_exc()
@@ -382,29 +396,11 @@ def _fallback_chat(current: dict | None) -> str:
382
  # ---------------------------------------------------------------------------
383
  # Mushroom helpers
384
  # ---------------------------------------------------------------------------
385
- def _choose_mushroom(catalog):
386
- """Safely picks a mushroom, with a fallback if the catalog is empty."""
387
- # 1. Ensure catalog is not empty
388
- if not catalog:
389
- print("CRITICAL: Mushroom catalog is empty! Using a fallback mushroom.")
390
- # Create a simple fallback object if none exist
391
- class FallbackMushroom:
392
- def __init__(self):
393
- self.name = "Common Moss Cap"
394
- self.rarity = "common"
395
- self.lore = "A simple mushroom that grew when the forest ran out of ideas."
396
- return FallbackMushroom()
397
-
398
- # 2. Safely get mushrooms and weights
399
- mushrooms = list(catalog.values())
400
- weights = [getattr(m, 'weight', 1.0) for m in mushrooms]
401
-
402
- # 3. Perform the choice
403
- try:
404
- return random.choices(mushrooms, weights=weights, k=1)[0]
405
- except Exception as e:
406
- print(f"Error in random.choices: {e}")
407
- return mushrooms[0] # Return the first available as a last resort
408
 
409
  def _is_poisonous(current: dict) -> bool:
410
  return current.get("name", "") in POISONOUS or current.get("danger") == "Poisonous"
@@ -488,62 +484,26 @@ def _safe_collection(c) -> list:
488
  # ---------------------------------------------------------------------------
489
  # Public game actions
490
  # ---------------------------------------------------------------------------
491
- def discover_mushroom(catalog):
492
- """Instantly spawns 2-4 mushrooms with robust fallback fields to prevent UI crashes."""
493
- num_mushrooms = random.randint(2, 4)
494
- active_mushrooms = []
495
- used_tiles = set()
496
-
497
- # Keep track of the last mushroom instance so we can return a valid object
498
- # to any legacy code expecting a real mushroom instance
499
- last_mushroom_obj = None
500
-
501
- for _ in range(num_mushrooms):
502
- mushroom = _choose_mushroom(catalog)
503
- last_mushroom_obj = mushroom
504
-
505
- mush_x, mush_y = random.randint(0, 2), random.randint(0, 2)
506
- while (mush_x, mush_y) in used_tiles:
507
- mush_x, mush_y = random.randint(0, 2), random.randint(0, 2)
508
- used_tiles.add((mush_x, mush_y))
509
-
510
- # We fill EVERY possible key that dex_markdown or status bars might read
511
- active_mushrooms.append({
512
- "name": mushroom.name,
513
- "rarity": mushroom.rarity,
514
- "habitat": getattr(mushroom, "habitat", "Glow Undergrowth"),
515
- "lore": getattr(mushroom, "lore", "A rapid micro-sprout spawned during a bloom."),
516
- "edible": getattr(mushroom, "edible", "Unknown"),
517
- "magic": getattr(mushroom, "magic", "Unknown"),
518
- "danger": getattr(mushroom, "danger", "Unknown"),
519
- "poison": "Yes" if mushroom.name in POISONOUS_MUSHROOM_NAMES else "No",
520
- "mush_x": mush_x,
521
- "mush_y": mush_y,
522
- "picked": "No",
523
- "clue": "Harvested instantly!",
524
- "studied": "No"
525
- })
526
-
527
- # Build a current state dictionary packed with fallback HUD variables
528
- current = {
529
- "name": "Mushroom Patch",
530
- "rarity": "Multiple",
531
- "poison": "No",
532
- "active_mushrooms": active_mushrooms,
533
- "game_over": "No",
534
- "picked": "No",
535
- "studied": "No",
536
- "encounter": f"Boom! {num_mushrooms} mushrooms sprouted! Move Myco to collect them!",
537
- "event_title": "Spore Influx",
538
- "event_emoji": "✨",
539
- "mystery_title": "The Wrong Memory",
540
- "score_total": "0",
541
- "health": "3",
542
- "reward_text": "Run around the map to clear the board!"
543
- }
544
-
545
- # Return the real mushroom object instead of None to prevent 'NoneType' errors
546
- return last_mushroom_obj, current, []
547
 
548
 
549
  def myco_reply(message=None, history=None, current=None, collection=None, position=None):
@@ -732,77 +692,36 @@ def eat_current(current=None, collection=None, history=None):
732
  return coll, _append(hist, "assistant", reply)
733
 
734
 
735
- def check_auto_pickup(new_pos_x, new_pos_y, current, collection):
736
- """Arcade collision rules that cleanly update score text safely."""
737
- if not current or current.get("game_over") == "Yes" or current.get("picked") == "Yes":
738
- return current, collection
739
-
740
- mushrooms = current.get("active_mushrooms", [])
741
- all_picked = True
742
-
743
- for m in mushrooms:
744
- if m.get("picked") == "No":
745
- # Check if Myco stepped on this coordinate
746
- if new_pos_x == m["mush_x"] and new_pos_y == m["mush_y"]:
747
- if m["poison"] == "Yes":
748
- current["game_over"] = "Yes"
749
- current["encounter"] = f"💀 Oh no! Myco stepped directly onto a toxic {m['name']}!"
750
- current["event_title"] = "Poison Shock!"
751
- return current, collection
752
- else:
753
- m["picked"] = "Yes"
754
- current["encounter"] = f"💥 Blip! Collected a rare {m['name']}!"
755
-
756
- # Safely tick up scores inside the state without crashing types
757
- current_score = int(current.get("score_total", "0")) + 15
758
- current["score_total"] = str(current_score)
759
- current["reward_text"] = f"+15 Spores from {m['name']}!"
760
-
761
- collection.append(m)
762
- else:
763
- # This one hasn't been collected yet
764
- all_picked = False
765
-
766
- if all_picked and mushrooms:
767
- current["picked"] = "Yes"
768
- current["encounter"] = "Area clear! Click Search Clearing to spawn the next cluster."
769
- current["event_title"] = "Clearing Purified"
770
-
771
- return current, collection
772
-
773
-
774
  # Myco narrative
 
775
  def get_myco_narrative(current=None):
776
- # 1. Personality Prompt - Made more aggressive
777
  prompt = (
778
  "You are Myco, a tiny, emotional mushroom companion. "
779
- "Speak in one or two short sentences about the forest. "
780
- "ABSOLUTELY NO JSON. NO BRACKETS. NO THOUGHT BLOCKS. "
781
- "Speak like a person, not a computer."
782
  )
783
 
784
- context = {"name": current.get("name", "mystery"), "rarity": current.get("rarity", "common")} if current else {}
 
 
785
 
786
  # 2. Get the response
787
  reply = _llm(prompt, context=context)
788
 
789
- if not reply:
790
- return "The forest feels deep today... ✨"
791
-
792
- # 3. Aggressive Clean-up: If it contains JSON, strip it away
793
- # This regex removes anything inside {} or []
794
- cleaned_reply = re.sub(r'\{.*\}|\[.*\]', '', reply)
795
-
796
- # Remove keys like "thought": or "thought"
797
- cleaned_reply = re.sub(r'"thought":|thought:', '', cleaned_reply, flags=re.IGNORECASE)
798
-
799
- # Remove extra quotes and whitespace
800
- cleaned_reply = cleaned_reply.replace('"', '').strip()
801
-
802
- # If the clean-up resulted in an empty string, fallback
803
- if not cleaned_reply:
804
- return "The forest feels deep today... ✨"
805
 
806
- return cleaned_reply
807
-
808
 
 
1
  """
2
  Core Myco gameplay — LLM is the primary game engine.
3
  """
4
+
5
  import os
 
6
  import random
7
  import threading
8
+ import re
9
+ import json
10
  import traceback
11
+
12
  import torch
13
+ import spaces
14
  from transformers import AutoModelForCausalLM, AutoTokenizer
15
 
 
16
  from game.catalog import load_mushrooms
17
+ from game.state import collection_contains, mushroom_from_state, welcome_history
18
 
 
19
  DEFAULT_MODEL_ID = "google/gemma-3-1b-it"
20
+
21
+ # Global singletons
22
  _model = None
23
  _tokenizer = None
24
  _lock = threading.Lock()
25
 
 
 
 
 
26
  def _get_model_and_tokenizer():
27
  global _model, _tokenizer
28
  if _model is not None and _tokenizer is not None:
 
32
  if _model is not None and _tokenizer is not None:
33
  return _model, _tokenizer
34
 
35
+ model_id = os.getenv("MYCO_MODEL_ID", "google/gemma-3-1b-it")
36
  token = os.getenv("HF_BUILD_SMALL_HACKATHON_TOKEN")
37
 
38
  try:
39
+ print(f"\n[Myco] Loading model and tokenizer for {model_id}...")
40
+
41
+ # Load tokenizer
42
  _tokenizer = AutoTokenizer.from_pretrained(model_id, token=token)
43
 
44
+ # Load model strictly on CPU with bfloat16 precision
45
  _model = AutoModelForCausalLM.from_pretrained(
46
  model_id,
47
  token=token,
48
+ torch_dtype=torch.bfloat16,
49
+ device_map=None, # CRITICAL: Must be None so ZeroGPU can hook it safely
50
  trust_remote_code=True
51
  )
52
+ print(f"[Myco] Successfully loaded: {model_id}")
53
  return _model, _tokenizer
54
  except Exception as exc:
55
  print(f"[Myco] Load error: {exc}")
56
  return None, None
57
 
58
+ # ---------------------------------------------------------------------------
59
+ # Pipeline loader
60
+ # ---------------------------------------------------------------------------
61
  def _get_pipeline():
62
+ """ Legacy compatibility wrapper so companion_status() and other
63
+ startup hooks don't throw a NameError.
64
+ """
65
  model, tokenizer = _get_model_and_tokenizer()
66
+ if model is not None and tokenizer is not None:
67
+ # Return the model instance so 'if pipe is not None' checks pass successfully
68
+ return model
69
+ return None
70
 
71
+ # ---------------------------------------------------------------------------
72
+ # GPU runner — ONLY this function gets the @spaces.GPU decorator.
73
+ # ---------------------------------------------------------------------------
74
+ @spaces.GPU
75
  def _run_pipeline(pipe_ignored, messages):
76
+ # 1. Fetch our raw model and tokenizer singletons
77
  model, tokenizer = _get_model_and_tokenizer()
78
+ if model is None or tokenizer is None:
79
  return "The forest is silent. (Model loading failed)"
80
 
81
+ # CRITICAL: Do NOT call model.to("cuda") manually here.
82
+ # ZeroGPU's @spaces.GPU decorator handles the weight migration automatically.
83
+
84
+ # 2. Build the chat template structure natively
85
  formatted_prompt = tokenizer.apply_chat_template(
86
+ messages,
87
+ tokenize=False,
88
+ add_generation_prompt=True
89
  )
90
 
91
+ # 3. Tokenize and dynamically map inputs to the exact device the model is currently using
92
+ inputs = tokenizer(formatted_prompt, return_tensors="pt").to(model.device)
93
 
94
+ # 4. Generate clean text without any configuration conflicts
95
  with torch.no_grad():
96
  outputs = model.generate(
97
  **inputs,
 
101
  pad_token_id=tokenizer.eos_token_id
102
  )
103
 
104
+ # 5. Extract only the newly generated text tokens
105
  input_length = inputs.input_ids.shape[1]
106
  generated_tokens = outputs[0][input_length:]
107
+
108
  return tokenizer.decode(generated_tokens, skip_special_tokens=True)
109
 
 
 
 
 
 
 
110
  # ---------------------------------------------------------------------------
111
  # Template Helper (Fixes the Gemma TemplateError)
112
  # ---------------------------------------------------------------------------
 
282
  # LLM call — multi-turn chat
283
  # ---------------------------------------------------------------------------
284
  def _llm_with_history(history: list, user_message: str, context: dict) -> str | None:
 
285
  pipe = _get_pipeline()
286
  if not pipe:
287
  return None
 
289
  ctx = context or {}
290
  mushroom_line = ""
291
  if ctx.get("name"):
292
+ poison_flag = " ⚠️ POISONOUS" if ctx.get("name") in POISONOUS else ""
293
  mushroom_line = (
294
  f"Current mushroom: {ctx['name']} ({ctx.get('rarity','?')}){poison_flag}. "
295
  f"Lore: {ctx.get('lore','?')}. "
296
  f"Edible: {ctx.get('edible','Unknown')}. Magic: {ctx.get('magic','Unknown')}."
297
  )
298
 
 
299
  system = (
300
  f"{SYSTEM_PROMPT}\n\n"
301
  f"{mushroom_line}\n"
302
  f"MycoDex entries: {ctx.get('collection_count', 0)}. "
303
  f"Mystery: {ctx.get('mystery_title', 'The Wrong Memory')}. "
304
+ f"Score: {ctx.get('score', 0)} spores. Health: {ctx.get('health', 3)}/3."
 
 
 
 
 
305
  )
306
 
307
+ # Safe structure formatting running history securely through template checks
308
  messages = _format_messages_for_template(system, user_message, history[-6:])
309
 
310
  try:
311
  reply = _run_pipeline(pipe, messages)
312
+
313
  print("========== MYCO OUTPUT ==========")
314
  print(reply)
315
  print("=================================")
316
+
317
  return reply
318
+
319
  except Exception as exc:
320
  print(f"[Myco] Inference error: {exc}")
321
  traceback.print_exc()
 
396
  # ---------------------------------------------------------------------------
397
  # Mushroom helpers
398
  # ---------------------------------------------------------------------------
399
+ def _choose_mushroom(catalog=None):
400
+ mushrooms = tuple(load_mushrooms() if catalog is None else catalog)
401
+ weights = [RARITY_WEIGHTS.get(m.rarity, 12) for m in mushrooms]
402
+ return random.choices(mushrooms, weights=weights, k=1)[0]
403
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
404
 
405
  def _is_poisonous(current: dict) -> bool:
406
  return current.get("name", "") in POISONOUS or current.get("danger") == "Poisonous"
 
484
  # ---------------------------------------------------------------------------
485
  # Public game actions
486
  # ---------------------------------------------------------------------------
487
+ def discover_mushroom(collection=None, catalog=None):
488
+ """Discover a new mushroom. LLM narrates the moment."""
489
+ coll = _safe_collection(collection)
490
+ mushroom = _choose_mushroom(catalog)
491
+ current = _build_current(mushroom, coll)
492
+ ctx = _ctx(current, coll)
493
+
494
+ prompt = (
495
+ f"The player just discovered a {mushroom.rarity} mushroom called {mushroom.name} "
496
+ f"near {mushroom.habitat}. "
497
+ f"{'WARNING: this mushroom is POISONOUS! React with fear and urgency.' if mushroom.name in POISONOUS else ''}"
498
+ f"{'This is LEGENDARY — react with awe and excitement!' if mushroom.rarity == 'Legendary' else ''}"
499
+ f"{'This is RARE — react with wonder and curiosity.' if mushroom.rarity == 'Rare' else ''}"
500
+ f"Forest event: {current['event_title']}. Myco mood: {current['myco_mood']}. "
501
+ f"Mystery chapter: {current['mystery_title']}. "
502
+ "React in character. Hint at what to do next (Study, Pick, Follow Whisper, or Collect)."
503
+ )
504
+ reply = _llm(prompt, ctx) or _fallback_discover(current)
505
+ history = _append(welcome_history(), "assistant", reply)
506
+ return mushroom, current, history
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
507
 
508
 
509
  def myco_reply(message=None, history=None, current=None, collection=None, position=None):
 
692
  return coll, _append(hist, "assistant", reply)
693
 
694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
695
  # Myco narrative
696
+
697
  def get_myco_narrative(current=None):
698
+ # 1. Personality Prompt
699
  prompt = (
700
  "You are Myco, a tiny, emotional mushroom companion. "
701
+ "Write a whimsical, mysterious thought about the forest. "
702
+ "DO NOT use JSON. Do NOT use action tags. Just speak naturally."
 
703
  )
704
 
705
+ context = {}
706
+ if current:
707
+ context = {"name": current.get("name"), "rarity": current.get("rarity")}
708
 
709
  # 2. Get the response
710
  reply = _llm(prompt, context=context)
711
 
712
+ # 3. CRITICAL: Aggressive Clean-up
713
+ # If the LLM ignored our "no JSON" instruction, we parse it ourselves.
714
+ if reply:
715
+ # If it's wrapped in JSON, extract the 'thought'
716
+ if reply.strip().startswith("{"):
717
+ try:
718
+ data = json.loads(reply)
719
+ return data.get("thought", "The forest feels deep today... ✨")
720
+ except:
721
+ pass # If it's broken JSON, just return the reply
722
+
723
+ # If it's just raw text, return it
724
+ return reply
 
 
 
725
 
726
+ return "The forest feels deep today... ✨"
 
727