Spaces:
Sleeping
Sleeping
Deploy Myco from CI
Browse files5 unmodified lines678910111213127 unmodified lines1411421431441451461471481494 unmodified lines15415515615715815916016116216316416516616716816917017117217317417517617717817918018118218 unmodified lines2012022032042052062072082092102112122132142152162172182192202212222232244 unmodified lines2292302312322332342352 unmodified lines23823924024124224324418 unmodified lines2632642652662672682692 unmodified lines27227327427527627727818 unmodified lines29729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933020 unmodified lines35135235335435535635712 unmodified lines37037137237337437537648 unmodified lines42542642742842943043123 unmodified lines45545645745845946046147 unmodified lines50951051151251351451531 unmodified lines54754854955055155255312 unmodified lines56656756856957057157216 unmodified lines58959059159259359459541 unmodified lines63763863964064164264312 unmodified lines6566576586596606616628 unmodified lines6716726736746756766776786796806816826836846856866876886891 unmodified line691692693694695696697698699700701702703704173 unmodified lines8788798808815 unmodified linesfrom game.catalog import load_mushroomsfrom game.state import collection_contains, mushroom_from_state, welcome_historyfrom transformers import pipeline# ---------------------------------------------------------------------------# Model configuration# ---------------------------------------------------------------------------127 unmodified lines# ---------------------------------------------------------------------------_pipeline = Nonedef _get_pipeline():"""Load the local transformers pipeline once and cache it."""global _pipeline# Already loaded successfully4 unmodified linesif _pipeline is False:return Nonetry:import osimport torchfrom transformers import pipelinemodel_id = os.getenv("MYCO_MODEL_ID","google/gemma-3-4b-it")print("\n===================================")print(f"[Myco] Loading model: {model_id}")print("===================================\n")print("HF token found:",bool(os.getenv("HF_BUILD_SMALL_HACKATHON_TOKEN")))_pipeline = pipeline(task="text-generation",model=model_id,token=os.getenv("HF_BUILD_SMALL_HACKATHON_TOKEN"),torch_dtype="auto",device_map="auto",)18 unmodified linesdef companion_model_id():"""Return the model id that will be (or is) loaded."""return os.getenv("MYCO_MODEL_ID", DEFAULT_MODEL_ID)def companion_status():model = companion_model_id()pipe = _get_pipeline()if pipe:return f"🧠 Myco AI: Gemma active ({model})"return (f"⚠️ Myco AI fallback mode "f"(Gemma failed to load: {model})")# Keep the old name so any code that calls hf_companion_status() still works.def hf_companion_status():return companion_status()4 unmodified linesdef choose_mushroom(catalog=None):"""Choose a mushroom discovery from the catalog."""mushrooms = tuple(load_mushrooms() if catalog is None else catalog)if not mushrooms:raise ValueError("Myco needs at least one mushroom in the catalog.")2 unmodified linesdef discover_mushroom(collection=None, catalog=None):"""Discover a mushroom and return the updated discovery state."""current_collection = _safe_collection(collection)mushroom = choose_mushroom(catalog)discovery_count = len(current_collection)18 unmodified linesdef myco_reply(message=None, history=None, current=None, collection=None, position=None):"""Generate Myco's companion reply from the player's current journey context."""current_history = _safe_history(history)clean_message = (message or "").strip()if not clean_message:2 unmodified linesnext_history = [*current_history, {"role": "user", "content": clean_message}]context = _companion_context(current, collection, current_history, position)answer = _companion_answer(clean_message, current, context)return "", [*next_history, _assistant_message(answer)]18 unmodified linesmessages = _build_messages(message, current, context)try:outputs = pipe(messages,max_new_tokens=90,temperature=0.8,do_sample=True,)print("========== MYCO OUTPUT ==========")print(outputs)print("=================================")last = outputs[0]["generated_text"][-1]# The pipeline returns the full generated_text list; the last entry is# the new assistant turn added by the model.last = outputs[0]["generated_text"][-1]# last is either a dict {"role": "assistant", "content": "..."}# or a plain string depending on the transformers version.if isinstance(last, dict):return (last.get("content") or "").strip() or Nonereturn str(last).strip() or Noneexcept Exception as exc:print(f"[Myco] Pipeline inference error: {exc}")return Nonedef _discovery_reaction(current, collection):"""Return Myco's first reaction to a new discovery."""mushroom = mushroom_from_state(current)context = _companion_context(current, collection, welcome_history(), None)prompt = (20 unmodified linesdef _fallback_companion_answer(current, context):"""Return the deterministic fallback companion answer using game context."""if current:mushroom = mushroom_from_state(current)emotion = context["emotion"]12 unmodified linesdef _build_messages(message, current, context):"""Build the chat messages list for the local pipeline."""mushroom_context = "No mushroom is currently discovered."if current:mushroom = mushroom_from_state(current)48 unmodified linesdef collect_current(current=None, collection=None, history=None):"""Add the current mushroom to the MycoDex if it is not already collected."""current_collection = _safe_collection(collection)current_history = _safe_history(history)23 unmodified linesdef pick_current(current=None, collection=None, history=None):"""Pick the current mushroom like a game item; poisonous picks end the run."""current_collection = _safe_collection(collection)current_history = _safe_history(history)if current is None:47 unmodified linesdef follow_whisper(current=None, collection=None, history=None):"""Follow the active story omen for a risk-reward discovery moment."""current_collection = _safe_collection(collection)current_history = _safe_history(history)if current is None:31 unmodified linesdef study_current(current=None, history=None):"""Study the current mushroom to reveal one cautious field observation."""current_history = _safe_history(history)if current is None:return None, _append_assistant(12 unmodified linesdef eat_current(current=None, history=None):"""Handle the Eat choice safely with Myco's companion personality."""current_history = _safe_history(history)if current is None:return _append_assistant(16 unmodified linesdef _companion_context(current, collection, history, position):"""Summarize the current journey so Myco replies like a present companion."""current_collection = _safe_collection(collection)count = len(current_collection)rare_names = [41 unmodified linesdef _location_label(position):"""Return a small in-world label for the grid position."""if position is None:return "center clearing"x, y = position12 unmodified linesdef _pattern_notice(current, collection):"""Return one pattern Myco can comment on from the journey so far."""if current.get("game_over") == "Yes":return "The same poison warning appeared before Myco could say it aloud."if current.get("rarity") == "Legendary":8 unmodified linesdef _recent_conversation(history):"""Return a compact summary of recent player/Myco conversation turns."""turns = []for entry in _safe_history(history)[-6:]:role = entry.get("role", "assistant")content = entry.get("content", "")# 1. Handle Gradio's list format (multimodal messages)if isinstance(content, list):pieces = []for item in content:if isinstance(item, dict):# Extract text from dict, fallback to empty string if it's purely a fileif "text" in item:pieces.append(item["text"])elif isinstance(item, str):1 unmodified lineelif isinstance(item, tuple):pieces.append("[Attachment]")content = " ".join(pieces)# 2. Handle Gradio's tuple format (old-style direct file uploads)elif isinstance(content, tuple):content = "[Attachment]"# 3. Force to string and safely clean upcontent = str(content).replace("\n", " ").strip()if content:turns.append(f"{role}: {content[:120]}")173 unmodified linesdef _safe_history(history):return list(history or welcome_history())5 unmodified lines67891011127 unmodified lines1391401411421431441451461474 unmodified lines15215315415515615715815916016116216316416516616716816917017117217317417517617718 unmodified lines1961971981992002012022032042052062072082092102112122134 unmodified lines2182192202212222232 unmodified lines22622722822923023118 unmodified lines2502512522532542552 unmodified lines25825926026126226318 unmodified lines28228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132220 unmodified lines34334434534634734812 unmodified lines36136236336436536648 unmodified lines41541641741841942023 unmodified lines44444544644744844947 unmodified lines49749849950050150231 unmodified lines53453553653753853912 unmodified lines55255355455555655716 unmodified lines57457557657757857941 unmodified lines62162262362462562612 unmodified lines6396406416426436448 unmodified lines6536546556566576586596606616626636646656666671 unmodified line669670671672673674675676677678173 unmodified lines8528538545 unmodified linesfrom game.catalog import load_mushroomsfrom game.state import collection_contains, mushroom_from_state, welcome_history# ---------------------------------------------------------------------------# Model configuration# ---------------------------------------------------------------------------127 unmodified lines# ---------------------------------------------------------------------------_pipeline = Nonedef _get_pipeline():"""Load the local transformers pipeline once and cache it."""global _pipeline# Already loaded successfully4 unmodified linesif _pipeline is False:return None# Retrieve model id before try/except so it's always in scope for the# except block. BUG FIX: original code referenced `model_id` inside# except but only assigned it inside try, causing NameError on failure.model_id = os.getenv("MYCO_MODEL_ID", DEFAULT_MODEL_ID)try:import torchfrom transformers import pipelineprint("\n===================================")print(f"[Myco] Loading model: {model_id}")print("===================================\n")hf_token = os.getenv("HF_BUILD_SMALL_HACKATHON_TOKEN")print("HF token found:", bool(hf_token))_pipeline = pipeline(task="text-generation",model=model_id,token=hf_token,torch_dtype="auto",device_map="auto",)18 unmodified linesdef companion_model_id():return os.getenv("MYCO_MODEL_ID", DEFAULT_MODEL_ID)def companion_status():model = companion_model_id()pipe = _get_pipeline()if pipe:return f"🧠 Myco AI: Gemma active ({model})"return f"⚠️ Myco AI fallback mode (Gemma failed to load: {model})"# Keep old name for backwards compatibilitydef hf_companion_status():return companion_status()4 unmodified linesdef choose_mushroom(catalog=None):mushrooms = tuple(load_mushrooms() if catalog is None else catalog)if not mushrooms:raise ValueError("Myco needs at least one mushroom in the catalog.")2 unmodified linesdef discover_mushroom(collection=None, catalog=None):current_collection = _safe_collection(collection)mushroom = choose_mushroom(catalog)discovery_count = len(current_collection)18 unmodified linesdef myco_reply(message=None, history=None, current=None, collection=None, position=None):current_history = _safe_history(history)clean_message = (message or "").strip()if not clean_message:2 unmodified linesnext_history = [*current_history, {"role": "user", "content": clean_message}]context = _companion_context(current, collection, current_history, position)answer = _companion_answer(clean_message, current, context)return "", [*next_history, _assistant_message(answer)]18 unmodified linesmessages = _build_messages(message, current, context)try:# BUG FIX: use the chat-template path so the pipeline accepts a list# of dicts correctly. Pass tokenizer=pipe.tokenizer to ensure the# chat template is applied, then decode only the new tokens.outputs = pipe(messages,max_new_tokens=90,temperature=0.8,do_sample=True,return_full_text=False, # BUG FIX: only return newly generated text)print("========== MYCO OUTPUT ==========")print(outputs)print("=================================")# BUG FIX: removed duplicate `last = ...` assignment from original.# With return_full_text=False, generated_text is a plain string.generated = outputs[0].get("generated_text", "")# Handle both string output (return_full_text=False) and list output# (return_full_text=True, older transformers versions).if isinstance(generated, list):last = generated[-1]if isinstance(last, dict):return (last.get("content") or "").strip() or Nonereturn str(last).strip() or Nonereturn str(generated).strip() or Noneexcept Exception as exc:print(f"[Myco] Pipeline inference error: {exc}")return Nonedef _discovery_reaction(current, collection):mushroom = mushroom_from_state(current)context = _companion_context(current, collection, welcome_history(), None)prompt = (20 unmodified linesdef _fallback_companion_answer(current, context):if current:mushroom = mushroom_from_state(current)emotion = context["emotion"]12 unmodified linesdef _build_messages(message, current, context):mushroom_context = "No mushroom is currently discovered."if current:mushroom = mushroom_from_state(current)48 unmodified linesdef collect_current(current=None, collection=None, history=None):current_collection = _safe_collection(collection)current_history = _safe_history(history)23 unmodified linesdef pick_current(current=None, collection=None, history=None):current_collection = _safe_collection(collection)current_history = _safe_history(history)if current is None:47 unmodified linesdef follow_whisper(current=None, collection=None, history=None):current_collection = _safe_collection(collection)current_history = _safe_history(history)if current is None:31 unmodified linesdef study_current(current=None, history=None):current_history = _safe_history(history)if current is None:return None, _append_assistant(12 unmodified linesdef eat_current(current=None, history=None):current_history = _safe_history(history)if current is None:return _append_assistant(16 unmodified linesdef _companion_context(current, collection, history, position):current_collection = _safe_collection(collection)count = len(current_collection)rare_names = [41 unmodified linesdef _location_label(position):if position is None:return "center clearing"x, y = position12 unmodified linesdef _pattern_notice(current, collection):if current.get("game_over") == "Yes":return "The same poison warning appeared before Myco could say it aloud."if current.get("rarity") == "Legendary":8 unmodified linesdef _recent_conversation(history):turns = []for entry in _safe_history(history)[-6:]:role = entry.get("role", "assistant")content = entry.get("content", "")if isinstance(content, list):pieces = []for item in content:if isinstance(item, dict):if "text" in item:pieces.append(item["text"])elif isinstance(item, str):1 unmodified lineelif isinstance(item, tuple):pieces.append("[Attachment]")content = " ".join(pieces)elif isinstance(content, tuple):content = "[Attachment]"content = str(content).replace("\n", " ").strip()if content:turns.append(f"{role}: {content[:120]}")173 unmodified linesdef _safe_history(history):return list(history or welcome_history())
game/engine.py+36-63