Spaces:
Sleeping
Sleeping
Deploy Myco from CI
Browse files- game/engine.py +36 -63
game/engine.py
CHANGED
|
@@ -6,8 +6,6 @@ import random
|
|
| 6 |
from game.catalog import load_mushrooms
|
| 7 |
from game.state import collection_contains, mushroom_from_state, welcome_history
|
| 8 |
|
| 9 |
-
from transformers import pipeline
|
| 10 |
-
|
| 11 |
# ---------------------------------------------------------------------------
|
| 12 |
# Model configuration
|
| 13 |
# ---------------------------------------------------------------------------
|
|
@@ -141,9 +139,9 @@ MYSTERY_CHAPTERS = (
|
|
| 141 |
# ---------------------------------------------------------------------------
|
| 142 |
_pipeline = None
|
| 143 |
|
|
|
|
| 144 |
def _get_pipeline():
|
| 145 |
"""Load the local transformers pipeline once and cache it."""
|
| 146 |
-
|
| 147 |
global _pipeline
|
| 148 |
|
| 149 |
# Already loaded successfully
|
|
@@ -154,29 +152,26 @@ def _get_pipeline():
|
|
| 154 |
if _pipeline is False:
|
| 155 |
return None
|
| 156 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
try:
|
| 158 |
-
import os
|
| 159 |
import torch
|
| 160 |
from transformers import pipeline
|
| 161 |
|
| 162 |
-
model_id = os.getenv(
|
| 163 |
-
"MYCO_MODEL_ID",
|
| 164 |
-
"google/gemma-3-4b-it"
|
| 165 |
-
)
|
| 166 |
-
|
| 167 |
print("\n===================================")
|
| 168 |
print(f"[Myco] Loading model: {model_id}")
|
| 169 |
print("===================================\n")
|
| 170 |
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
)
|
| 175 |
-
|
| 176 |
_pipeline = pipeline(
|
| 177 |
task="text-generation",
|
| 178 |
model=model_id,
|
| 179 |
-
token=
|
| 180 |
torch_dtype="auto",
|
| 181 |
device_map="auto",
|
| 182 |
)
|
|
@@ -201,24 +196,18 @@ def _get_pipeline():
|
|
| 201 |
|
| 202 |
|
| 203 |
def companion_model_id():
|
| 204 |
-
"""Return the model id that will be (or is) loaded."""
|
| 205 |
return os.getenv("MYCO_MODEL_ID", DEFAULT_MODEL_ID)
|
| 206 |
|
| 207 |
|
| 208 |
def companion_status():
|
| 209 |
model = companion_model_id()
|
| 210 |
pipe = _get_pipeline()
|
| 211 |
-
|
| 212 |
if pipe:
|
| 213 |
return f"🧠 Myco AI: Gemma active ({model})"
|
| 214 |
-
|
| 215 |
-
return (
|
| 216 |
-
f"⚠️ Myco AI fallback mode "
|
| 217 |
-
f"(Gemma failed to load: {model})"
|
| 218 |
-
)
|
| 219 |
|
| 220 |
|
| 221 |
-
# Keep
|
| 222 |
def hf_companion_status():
|
| 223 |
return companion_status()
|
| 224 |
|
|
@@ -229,7 +218,6 @@ def hf_companion_status():
|
|
| 229 |
|
| 230 |
|
| 231 |
def choose_mushroom(catalog=None):
|
| 232 |
-
"""Choose a mushroom discovery from the catalog."""
|
| 233 |
mushrooms = tuple(load_mushrooms() if catalog is None else catalog)
|
| 234 |
if not mushrooms:
|
| 235 |
raise ValueError("Myco needs at least one mushroom in the catalog.")
|
|
@@ -238,7 +226,6 @@ def choose_mushroom(catalog=None):
|
|
| 238 |
|
| 239 |
|
| 240 |
def discover_mushroom(collection=None, catalog=None):
|
| 241 |
-
"""Discover a mushroom and return the updated discovery state."""
|
| 242 |
current_collection = _safe_collection(collection)
|
| 243 |
mushroom = choose_mushroom(catalog)
|
| 244 |
discovery_count = len(current_collection)
|
|
@@ -263,7 +250,6 @@ def discover_mushroom(collection=None, catalog=None):
|
|
| 263 |
|
| 264 |
|
| 265 |
def myco_reply(message=None, history=None, current=None, collection=None, position=None):
|
| 266 |
-
"""Generate Myco's companion reply from the player's current journey context."""
|
| 267 |
current_history = _safe_history(history)
|
| 268 |
clean_message = (message or "").strip()
|
| 269 |
if not clean_message:
|
|
@@ -272,7 +258,6 @@ def myco_reply(message=None, history=None, current=None, collection=None, positi
|
|
| 272 |
next_history = [*current_history, {"role": "user", "content": clean_message}]
|
| 273 |
context = _companion_context(current, collection, current_history, position)
|
| 274 |
answer = _companion_answer(clean_message, current, context)
|
| 275 |
-
|
| 276 |
return "", [*next_history, _assistant_message(answer)]
|
| 277 |
|
| 278 |
|
|
@@ -297,34 +282,41 @@ def _local_pipeline_answer(message, current, context):
|
|
| 297 |
|
| 298 |
messages = _build_messages(message, current, context)
|
| 299 |
try:
|
|
|
|
|
|
|
|
|
|
| 300 |
outputs = pipe(
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
|
|
|
| 305 |
)
|
| 306 |
-
|
| 307 |
print("========== MYCO OUTPUT ==========")
|
| 308 |
print(outputs)
|
| 309 |
print("=================================")
|
| 310 |
-
|
| 311 |
-
last =
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
#
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 321 |
except Exception as exc:
|
| 322 |
print(f"[Myco] Pipeline inference error: {exc}")
|
| 323 |
return None
|
| 324 |
|
| 325 |
|
| 326 |
def _discovery_reaction(current, collection):
|
| 327 |
-
"""Return Myco's first reaction to a new discovery."""
|
| 328 |
mushroom = mushroom_from_state(current)
|
| 329 |
context = _companion_context(current, collection, welcome_history(), None)
|
| 330 |
prompt = (
|
|
@@ -351,7 +343,6 @@ def _discovery_reaction(current, collection):
|
|
| 351 |
|
| 352 |
|
| 353 |
def _fallback_companion_answer(current, context):
|
| 354 |
-
"""Return the deterministic fallback companion answer using game context."""
|
| 355 |
if current:
|
| 356 |
mushroom = mushroom_from_state(current)
|
| 357 |
emotion = context["emotion"]
|
|
@@ -370,7 +361,6 @@ def _fallback_companion_answer(current, context):
|
|
| 370 |
|
| 371 |
|
| 372 |
def _build_messages(message, current, context):
|
| 373 |
-
"""Build the chat messages list for the local pipeline."""
|
| 374 |
mushroom_context = "No mushroom is currently discovered."
|
| 375 |
if current:
|
| 376 |
mushroom = mushroom_from_state(current)
|
|
@@ -425,7 +415,6 @@ def _build_messages(message, current, context):
|
|
| 425 |
|
| 426 |
|
| 427 |
def collect_current(current=None, collection=None, history=None):
|
| 428 |
-
"""Add the current mushroom to the MycoDex if it is not already collected."""
|
| 429 |
current_collection = _safe_collection(collection)
|
| 430 |
current_history = _safe_history(history)
|
| 431 |
|
|
@@ -455,7 +444,6 @@ def collect_current(current=None, collection=None, history=None):
|
|
| 455 |
|
| 456 |
|
| 457 |
def pick_current(current=None, collection=None, history=None):
|
| 458 |
-
"""Pick the current mushroom like a game item; poisonous picks end the run."""
|
| 459 |
current_collection = _safe_collection(collection)
|
| 460 |
current_history = _safe_history(history)
|
| 461 |
if current is None:
|
|
@@ -509,7 +497,6 @@ def pick_current(current=None, collection=None, history=None):
|
|
| 509 |
|
| 510 |
|
| 511 |
def follow_whisper(current=None, collection=None, history=None):
|
| 512 |
-
"""Follow the active story omen for a risk-reward discovery moment."""
|
| 513 |
current_collection = _safe_collection(collection)
|
| 514 |
current_history = _safe_history(history)
|
| 515 |
if current is None:
|
|
@@ -547,7 +534,6 @@ def follow_whisper(current=None, collection=None, history=None):
|
|
| 547 |
|
| 548 |
|
| 549 |
def study_current(current=None, history=None):
|
| 550 |
-
"""Study the current mushroom to reveal one cautious field observation."""
|
| 551 |
current_history = _safe_history(history)
|
| 552 |
if current is None:
|
| 553 |
return None, _append_assistant(
|
|
@@ -566,7 +552,6 @@ def study_current(current=None, history=None):
|
|
| 566 |
|
| 567 |
|
| 568 |
def eat_current(current=None, history=None):
|
| 569 |
-
"""Handle the Eat choice safely with Myco's companion personality."""
|
| 570 |
current_history = _safe_history(history)
|
| 571 |
if current is None:
|
| 572 |
return _append_assistant(
|
|
@@ -589,7 +574,6 @@ def eat_current(current=None, history=None):
|
|
| 589 |
|
| 590 |
|
| 591 |
def _companion_context(current, collection, history, position):
|
| 592 |
-
"""Summarize the current journey so Myco replies like a present companion."""
|
| 593 |
current_collection = _safe_collection(collection)
|
| 594 |
count = len(current_collection)
|
| 595 |
rare_names = [
|
|
@@ -637,7 +621,6 @@ def _companion_context(current, collection, history, position):
|
|
| 637 |
|
| 638 |
|
| 639 |
def _location_label(position):
|
| 640 |
-
"""Return a small in-world label for the grid position."""
|
| 641 |
if position is None:
|
| 642 |
return "center clearing"
|
| 643 |
x, y = position
|
|
@@ -656,7 +639,6 @@ def _location_label(position):
|
|
| 656 |
|
| 657 |
|
| 658 |
def _pattern_notice(current, collection):
|
| 659 |
-
"""Return one pattern Myco can comment on from the journey so far."""
|
| 660 |
if current.get("game_over") == "Yes":
|
| 661 |
return "The same poison warning appeared before Myco could say it aloud."
|
| 662 |
if current.get("rarity") == "Legendary":
|
|
@@ -671,19 +653,15 @@ def _pattern_notice(current, collection):
|
|
| 671 |
|
| 672 |
|
| 673 |
def _recent_conversation(history):
|
| 674 |
-
"""Return a compact summary of recent player/Myco conversation turns."""
|
| 675 |
turns = []
|
| 676 |
-
|
| 677 |
for entry in _safe_history(history)[-6:]:
|
| 678 |
role = entry.get("role", "assistant")
|
| 679 |
content = entry.get("content", "")
|
| 680 |
|
| 681 |
-
# 1. Handle Gradio's list format (multimodal messages)
|
| 682 |
if isinstance(content, list):
|
| 683 |
pieces = []
|
| 684 |
for item in content:
|
| 685 |
if isinstance(item, dict):
|
| 686 |
-
# Extract text from dict, fallback to empty string if it's purely a file
|
| 687 |
if "text" in item:
|
| 688 |
pieces.append(item["text"])
|
| 689 |
elif isinstance(item, str):
|
|
@@ -691,14 +669,10 @@ def _recent_conversation(history):
|
|
| 691 |
elif isinstance(item, tuple):
|
| 692 |
pieces.append("[Attachment]")
|
| 693 |
content = " ".join(pieces)
|
| 694 |
-
|
| 695 |
-
# 2. Handle Gradio's tuple format (old-style direct file uploads)
|
| 696 |
elif isinstance(content, tuple):
|
| 697 |
content = "[Attachment]"
|
| 698 |
|
| 699 |
-
# 3. Force to string and safely clean up
|
| 700 |
content = str(content).replace("\n", " ").strip()
|
| 701 |
-
|
| 702 |
if content:
|
| 703 |
turns.append(f"{role}: {content[:120]}")
|
| 704 |
|
|
@@ -878,4 +852,3 @@ def _safe_collection(collection):
|
|
| 878 |
|
| 879 |
def _safe_history(history):
|
| 880 |
return list(history or welcome_history())
|
| 881 |
-
|
|
|
|
| 6 |
from game.catalog import load_mushrooms
|
| 7 |
from game.state import collection_contains, mushroom_from_state, welcome_history
|
| 8 |
|
|
|
|
|
|
|
| 9 |
# ---------------------------------------------------------------------------
|
| 10 |
# Model configuration
|
| 11 |
# ---------------------------------------------------------------------------
|
|
|
|
| 139 |
# ---------------------------------------------------------------------------
|
| 140 |
_pipeline = None
|
| 141 |
|
| 142 |
+
|
| 143 |
def _get_pipeline():
|
| 144 |
"""Load the local transformers pipeline once and cache it."""
|
|
|
|
| 145 |
global _pipeline
|
| 146 |
|
| 147 |
# Already loaded successfully
|
|
|
|
| 152 |
if _pipeline is False:
|
| 153 |
return None
|
| 154 |
|
| 155 |
+
# Retrieve model id before try/except so it's always in scope for the
|
| 156 |
+
# except block. BUG FIX: original code referenced `model_id` inside
|
| 157 |
+
# except but only assigned it inside try, causing NameError on failure.
|
| 158 |
+
model_id = os.getenv("MYCO_MODEL_ID", DEFAULT_MODEL_ID)
|
| 159 |
+
|
| 160 |
try:
|
|
|
|
| 161 |
import torch
|
| 162 |
from transformers import pipeline
|
| 163 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
print("\n===================================")
|
| 165 |
print(f"[Myco] Loading model: {model_id}")
|
| 166 |
print("===================================\n")
|
| 167 |
|
| 168 |
+
hf_token = os.getenv("HF_BUILD_SMALL_HACKATHON_TOKEN")
|
| 169 |
+
print("HF token found:", bool(hf_token))
|
| 170 |
+
|
|
|
|
|
|
|
| 171 |
_pipeline = pipeline(
|
| 172 |
task="text-generation",
|
| 173 |
model=model_id,
|
| 174 |
+
token=hf_token,
|
| 175 |
torch_dtype="auto",
|
| 176 |
device_map="auto",
|
| 177 |
)
|
|
|
|
| 196 |
|
| 197 |
|
| 198 |
def companion_model_id():
|
|
|
|
| 199 |
return os.getenv("MYCO_MODEL_ID", DEFAULT_MODEL_ID)
|
| 200 |
|
| 201 |
|
| 202 |
def companion_status():
|
| 203 |
model = companion_model_id()
|
| 204 |
pipe = _get_pipeline()
|
|
|
|
| 205 |
if pipe:
|
| 206 |
return f"🧠 Myco AI: Gemma active ({model})"
|
| 207 |
+
return f"⚠️ Myco AI fallback mode (Gemma failed to load: {model})"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
|
| 209 |
|
| 210 |
+
# Keep old name for backwards compatibility
|
| 211 |
def hf_companion_status():
|
| 212 |
return companion_status()
|
| 213 |
|
|
|
|
| 218 |
|
| 219 |
|
| 220 |
def choose_mushroom(catalog=None):
|
|
|
|
| 221 |
mushrooms = tuple(load_mushrooms() if catalog is None else catalog)
|
| 222 |
if not mushrooms:
|
| 223 |
raise ValueError("Myco needs at least one mushroom in the catalog.")
|
|
|
|
| 226 |
|
| 227 |
|
| 228 |
def discover_mushroom(collection=None, catalog=None):
|
|
|
|
| 229 |
current_collection = _safe_collection(collection)
|
| 230 |
mushroom = choose_mushroom(catalog)
|
| 231 |
discovery_count = len(current_collection)
|
|
|
|
| 250 |
|
| 251 |
|
| 252 |
def myco_reply(message=None, history=None, current=None, collection=None, position=None):
|
|
|
|
| 253 |
current_history = _safe_history(history)
|
| 254 |
clean_message = (message or "").strip()
|
| 255 |
if not clean_message:
|
|
|
|
| 258 |
next_history = [*current_history, {"role": "user", "content": clean_message}]
|
| 259 |
context = _companion_context(current, collection, current_history, position)
|
| 260 |
answer = _companion_answer(clean_message, current, context)
|
|
|
|
| 261 |
return "", [*next_history, _assistant_message(answer)]
|
| 262 |
|
| 263 |
|
|
|
|
| 282 |
|
| 283 |
messages = _build_messages(message, current, context)
|
| 284 |
try:
|
| 285 |
+
# BUG FIX: use the chat-template path so the pipeline accepts a list
|
| 286 |
+
# of dicts correctly. Pass tokenizer=pipe.tokenizer to ensure the
|
| 287 |
+
# chat template is applied, then decode only the new tokens.
|
| 288 |
outputs = pipe(
|
| 289 |
+
messages,
|
| 290 |
+
max_new_tokens=90,
|
| 291 |
+
temperature=0.8,
|
| 292 |
+
do_sample=True,
|
| 293 |
+
return_full_text=False, # BUG FIX: only return newly generated text
|
| 294 |
)
|
| 295 |
+
|
| 296 |
print("========== MYCO OUTPUT ==========")
|
| 297 |
print(outputs)
|
| 298 |
print("=================================")
|
| 299 |
+
|
| 300 |
+
# BUG FIX: removed duplicate `last = ...` assignment from original.
|
| 301 |
+
# With return_full_text=False, generated_text is a plain string.
|
| 302 |
+
generated = outputs[0].get("generated_text", "")
|
| 303 |
+
|
| 304 |
+
# Handle both string output (return_full_text=False) and list output
|
| 305 |
+
# (return_full_text=True, older transformers versions).
|
| 306 |
+
if isinstance(generated, list):
|
| 307 |
+
last = generated[-1]
|
| 308 |
+
if isinstance(last, dict):
|
| 309 |
+
return (last.get("content") or "").strip() or None
|
| 310 |
+
return str(last).strip() or None
|
| 311 |
+
|
| 312 |
+
return str(generated).strip() or None
|
| 313 |
+
|
| 314 |
except Exception as exc:
|
| 315 |
print(f"[Myco] Pipeline inference error: {exc}")
|
| 316 |
return None
|
| 317 |
|
| 318 |
|
| 319 |
def _discovery_reaction(current, collection):
|
|
|
|
| 320 |
mushroom = mushroom_from_state(current)
|
| 321 |
context = _companion_context(current, collection, welcome_history(), None)
|
| 322 |
prompt = (
|
|
|
|
| 343 |
|
| 344 |
|
| 345 |
def _fallback_companion_answer(current, context):
|
|
|
|
| 346 |
if current:
|
| 347 |
mushroom = mushroom_from_state(current)
|
| 348 |
emotion = context["emotion"]
|
|
|
|
| 361 |
|
| 362 |
|
| 363 |
def _build_messages(message, current, context):
|
|
|
|
| 364 |
mushroom_context = "No mushroom is currently discovered."
|
| 365 |
if current:
|
| 366 |
mushroom = mushroom_from_state(current)
|
|
|
|
| 415 |
|
| 416 |
|
| 417 |
def collect_current(current=None, collection=None, history=None):
|
|
|
|
| 418 |
current_collection = _safe_collection(collection)
|
| 419 |
current_history = _safe_history(history)
|
| 420 |
|
|
|
|
| 444 |
|
| 445 |
|
| 446 |
def pick_current(current=None, collection=None, history=None):
|
|
|
|
| 447 |
current_collection = _safe_collection(collection)
|
| 448 |
current_history = _safe_history(history)
|
| 449 |
if current is None:
|
|
|
|
| 497 |
|
| 498 |
|
| 499 |
def follow_whisper(current=None, collection=None, history=None):
|
|
|
|
| 500 |
current_collection = _safe_collection(collection)
|
| 501 |
current_history = _safe_history(history)
|
| 502 |
if current is None:
|
|
|
|
| 534 |
|
| 535 |
|
| 536 |
def study_current(current=None, history=None):
|
|
|
|
| 537 |
current_history = _safe_history(history)
|
| 538 |
if current is None:
|
| 539 |
return None, _append_assistant(
|
|
|
|
| 552 |
|
| 553 |
|
| 554 |
def eat_current(current=None, history=None):
|
|
|
|
| 555 |
current_history = _safe_history(history)
|
| 556 |
if current is None:
|
| 557 |
return _append_assistant(
|
|
|
|
| 574 |
|
| 575 |
|
| 576 |
def _companion_context(current, collection, history, position):
|
|
|
|
| 577 |
current_collection = _safe_collection(collection)
|
| 578 |
count = len(current_collection)
|
| 579 |
rare_names = [
|
|
|
|
| 621 |
|
| 622 |
|
| 623 |
def _location_label(position):
|
|
|
|
| 624 |
if position is None:
|
| 625 |
return "center clearing"
|
| 626 |
x, y = position
|
|
|
|
| 639 |
|
| 640 |
|
| 641 |
def _pattern_notice(current, collection):
|
|
|
|
| 642 |
if current.get("game_over") == "Yes":
|
| 643 |
return "The same poison warning appeared before Myco could say it aloud."
|
| 644 |
if current.get("rarity") == "Legendary":
|
|
|
|
| 653 |
|
| 654 |
|
| 655 |
def _recent_conversation(history):
|
|
|
|
| 656 |
turns = []
|
|
|
|
| 657 |
for entry in _safe_history(history)[-6:]:
|
| 658 |
role = entry.get("role", "assistant")
|
| 659 |
content = entry.get("content", "")
|
| 660 |
|
|
|
|
| 661 |
if isinstance(content, list):
|
| 662 |
pieces = []
|
| 663 |
for item in content:
|
| 664 |
if isinstance(item, dict):
|
|
|
|
| 665 |
if "text" in item:
|
| 666 |
pieces.append(item["text"])
|
| 667 |
elif isinstance(item, str):
|
|
|
|
| 669 |
elif isinstance(item, tuple):
|
| 670 |
pieces.append("[Attachment]")
|
| 671 |
content = " ".join(pieces)
|
|
|
|
|
|
|
| 672 |
elif isinstance(content, tuple):
|
| 673 |
content = "[Attachment]"
|
| 674 |
|
|
|
|
| 675 |
content = str(content).replace("\n", " ").strip()
|
|
|
|
| 676 |
if content:
|
| 677 |
turns.append(f"{role}: {content[:120]}")
|
| 678 |
|
|
|
|
| 852 |
|
| 853 |
def _safe_history(history):
|
| 854 |
return list(history or welcome_history())
|
|
|