Spaces:
Sleeping
Sleeping
Deploy Myco from CI
Browse filesFiles changed (9)
42 unmodified lines434445464748495051525354555657587 unmodified lines66676842 unmodified lines- Game logic: `game/`- Mushroom model: `models/`- Mushroom catalog: `data/mushrooms.json`- Runtime dependency: `requirements.txt`## Local development```bashpip install -r requirements.txtpython app.py```Then open the local Gradio URL printed in the terminal.## Hugging Face Space7 unmodified lines4. The Space should install `gradio==6.16.0` from `requirements.txt` and start from `app.py`.The required runtime files are `README.md`, `app.py`, `requirements.txt`, `data/`, `game/`, `models/`, and `ui/`.42 unmodified lines4344454647484950515253545556575859606162636465666768697 unmodified lines777879808182838442 unmodified lines- Game logic: `game/`- Mushroom model: `models/`- Mushroom catalog: `data/mushrooms.json`- Regression tests: `tests/test_myco_core.py`- Runtime dependency: `requirements.txt`## Hugging Face AI companionMyco uses the Hugging Face Inference API for both first-discovery reactions and chat replies when a token is configured in the Space. Add these Space variables/secrets:- `HF_TOKEN=<your Hugging Face access token>`- Optional: `MYCO_HF_MODEL_ID=meta-llama/Llama-3.1-8B-Instruct`The default model is set in code as `DEFAULT_HF_MODEL_ID = "meta-llama/Llama-3.1-8B-Instruct"`. The app still has a local safety fallback for development and outage protection: if the token is missing or the selected model errors, Myco answers with the built-in cautious companion response instead of crashing.## Local development```bashpip install -r requirements.txtpython -m unittest discover -vpython app.py```Run tests before launching, then open the local Gradio URL printed in the terminal.## Hugging Face Space7 unmodified lines4. The Space should install `gradio==6.16.0` from `requirements.txt` and start from `app.py`.The required runtime files are `README.md`, `app.py`, `requirements.txt`, `data/`, `game/`, `models/`, and `ui/`.## Optional deploy helper`scripts/deploy_space.py` is optional. It skips safely when `HF_BUILD_SMALL_HACKATHON_TOKEN` is not configured, and uploads to `byte-vortex/Myco` only when that token is present.
3 unmodified lines4567894 unmodified lines1415161718193 unmodified linesos.environ.setdefault("GRADIO_SSR_MODE", "False")import gradio as grfrom ui.gradio_app import build_app4 unmodified linesif __name__ == "__main__":demo.launch(theme=gr.themes.Soft(primary_hue="green", secondary_hue="emerald"),css=APP_CSS,ssr_mode=False,3 unmodified lines456789104 unmodified lines151617181920213 unmodified linesos.environ.setdefault("GRADIO_SSR_MODE", "False")from gradio.themes import Softimport gradio as grfrom ui.gradio_app import build_app4 unmodified linesif __name__ == "__main__":demo.launch(theme=Soft(primary_hue="green", secondary_hue="emerald"),theme=gr.themes.Soft(primary_hue="green", secondary_hue="emerald"),css=APP_CSS,ssr_mode=False,
13 unmodified lines1415161713 unmodified lines"""Load the in-repo mushroom catalog."""raw_mushrooms = json.loads(CATALOG_PATH.read_text(encoding="utf-8"))return tuple(Mushroom.from_dict(item) for item in raw_mushrooms)13 unmodified lines14151613 unmodified lines"""Load the in-repo mushroom catalog."""raw_mushrooms = json.loads(CATALOG_PATH.read_text(encoding="utf-8"))return tuple(Mushroom.from_dict(item) for item in raw_mushrooms)
94 unmodified lines959697989910017 unmodified lines11811912012112212314 unmodified lines1381391401411421431446 unmodified lines15115215315415515615794 unmodified linesmax_tokens=90,temperature=0.8,)except Exception:return None17 unmodified linesdef _hf_token():"""Return the first configured Hugging Face token without exposing it."""for env_name in HF_TOKEN_ENV_VARS:token = os.getenv(env_name)if token:return token14 unmodified linesf"Lore: {mushroom.lore}")return ({"role": "system","content": (6 unmodified lines"role": "user","content": f"{mushroom_context} Player asks: {message}",},)companion_reply = myco_reply94 unmodified lines959697989910010110210310410510610717 unmodified lines12512612712812913013114 unmodified lines1461471481491501511526 unmodified lines15916016116216316416594 unmodified linesmax_tokens=90,temperature=0.8,)content = response.choices[0].message.content or ""answer = content.strip()except (AttributeError, IndexError, TypeError, ValueError):return Noneexcept Exception:return Noneexcept Exception:return None17 unmodified linesdef _hf_token():"""Return the first configured Hugging Face token without exposing it."""for env_name in HF_TOKEN_ENV_VARS:token = os.getenv(env_name, "").strip()token = os.getenv(env_name)if token:return token14 unmodified linesf"Lore: {mushroom.lore}")return [{"role": "system","content": (6 unmodified lines"role": "user","content": f"{mushroom_context} Player asks: {message}",},]companion_reply = myco_reply
21 unmodified lines2223242521 unmodified linesdef collection_contains(collection: CollectionState, mushroom_name: str) -> bool:"""Return whether the MycoDex already has a mushroom by name."""return any(entry["name"] == mushroom_name for entry in collection)21 unmodified lines2223242521 unmodified linesdef collection_contains(collection: CollectionState, mushroom_name: str) -> bool:"""Return whether the MycoDex already has a mushroom by name."""return any(entry.get("name") == mushroom_name for entry in collection)
24 unmodified lines2526272829303124 unmodified linesdef get_ignore_patterns():"""Return upload ignore patterns as a list for huggingface_hub."""return IGNORE_PATTERNS_TEXT.split()def get_hf_token():24 unmodified lines2526272829303124 unmodified linesdef get_ignore_patterns():"""Return upload ignore patterns as a list for huggingface_hub."""return [str(pattern) for pattern in IGNORE_PATTERNS_TEXT.split()]def get_hf_token():
160 unmodified lines1611621631641651666 unmodified lines173174175176177178160 unmodified linesself.assertIn(current["name"], updated_history[-1]["content"])self.assertIn("unknown", updated_history[-1]["content"].lower())def test_collect_current_prevents_duplicates(self):_mushroom, current, history = discover_mushroom([])collection, history = collect_current(current, [], history)6 unmodified linesdef test_study_and_eat_are_safe(self):_mushroom, current, history = discover_mushroom([])studied, study_history = study_current(current, history)eat_history = eat_current(studied, study_history)self.assertEqual(studied["studied"], "Yes")160 unmodified lines1611621631641651661671681691701711721731741751761771781791801811821831841851861876 unmodified lines194195196197198199200201160 unmodified linesself.assertIn(current["name"], updated_history[-1]["content"])self.assertIn("unknown", updated_history[-1]["content"].lower())def test_companion_api_falls_back_on_malformed_response(self):_mushroom, current, history = discover_mushroom([])def broken_client(token):return SimpleNamespace(token=token,chat_completion=lambda **kwargs: SimpleNamespace(choices=()),)api_env = {"HF_TOKEN": " fake-token ","HF_API_TOKEN": "","HF_BUILD_SMALL_HACKATHON_TOKEN": "",}with patch.dict(os.environ, api_env, clear=False):with patch("game.engine.InferenceClient", broken_client):prompt, updated_history = companion_reply("What is this?", history, current)self.assertEqual(prompt, "")self.assertIn(current["name"], updated_history[-1]["content"])def test_collect_current_prevents_duplicates(self):_mushroom, current, history = discover_mushroom([])collection, history = collect_current(current, [], history)6 unmodified linesdef test_study_and_eat_are_safe(self):_mushroom, current, history = discover_mushroom([])studied, study_history = study_current(current, history)self.assertIsNotNone(studied)assert studied is not Noneeat_history = eat_current(studied, study_history)self.assertEqual(studied["studied"], "Yes")
1234516 unmodified lines2223242526272877 unmodified lines10610710810911011111220 unmodified lines133134135136137138139"""Gradio app composition for Myco."""import gradio as grfrom game.engine import (16 unmodified linesworld_map_markdown,)EMPTY_COLLECTION = tuple()HOME_MARKDOWN = """## Welcome to the Myco forest77 unmodified lines"""Build the Gradio interface for Hugging Face Spaces."""with gr.Blocks(title="Myco") as demo:current_mushroom = gr.State(None)collection = gr.State(EMPTY_COLLECTION)gr.HTML(hero_markdown())with gr.Tabs():20 unmodified linesstudy_button = gr.Button("Study")with gr.Column(scale=3):chat = gr.Chatbot(value=welcome_history(),label="Myco Chat",height=360,)123456716 unmodified lines2425262728293077 unmodified lines10810911011111211311420 unmodified lines135136137138139140141"""Gradio app composition for Myco."""from typing import Any, castimport gradio as grfrom game.engine import (16 unmodified linesworld_map_markdown,)EMPTY_COLLECTION = NoneHOME_MARKDOWN = """## Welcome to the Myco forest77 unmodified lines"""Build the Gradio interface for Hugging Face Spaces."""with gr.Blocks(title="Myco") as demo:current_mushroom = gr.State(None)collection = gr.State([])gr.HTML(hero_markdown())with gr.Tabs():20 unmodified linesstudy_button = gr.Button("Study")with gr.Column(scale=3):chat = gr.Chatbot(value=cast(Any, welcome_history()),label="Myco Chat",height=360,)
109 unmodified lines11011111211311411511611743 unmodified lines161162163164165166109 unmodified lines)def world_map_markdown(collection: CollectionState | None) -> str:"""Render a game-like world map with unlocks and achievements."""count = len(_safe_collection(collection))43 unmodified linesicon = "🏅" if unlocked else "◇"return f'<span class="achievement {state}">{icon} {escape(label)}</span>'def dex_markdown(collection: CollectionState | None) -> str:"""Render collected mushrooms as a compact MycoDex."""current_collection = _safe_collection(collection)109 unmodified lines11011111211311411543 unmodified lines159160161162163164165109 unmodified lines)def world_map_markdown(collection: CollectionState | None) -> str:"""Render a game-like world map with unlocks and achievements."""count = len(_safe_collection(collection))43 unmodified linesicon = "🏅" if unlocked else "◇"return f'<span class="achievement {state}">{icon} {escape(label)}</span>'def dex_markdown(collection: CollectionState | None) -> str:"""Render collected mushrooms as a compact MycoDex."""current_collection = _safe_collection(collection)
README.md+17-1
app.py+2
game/catalog.py-1
game/engine.py+10-2
game/state.py+1-1
scripts/deploy_space.py+1-1
tests/test_myco_core.py+23
ui/gradio_app.py+5-3
ui/renderers.py+1-2