AndrewRqy commited on
Commit Β·
f9490c0
1
Parent(s): fd741cf
Clean-Space pass: drop self-test, legacy unused handler, BISECT_MINIMAL branch, duplicate banner PNG, stale comments
Browse filesFiles changed (4)
- .env.example+14-5
- app.py+2-241
- assets/sprites/banner_near.pngDeleted
- run.sh-1
12345678910111213141516# Copy to .env.local and fill in. Without these, the app runs in mock mode.# Modal-hosted OpenAI-compatible endpoint (vLLM serving Qwen2.5-32B or similar).# Leave empty to force mock mode for the LLM calls.MODAL_URL=# Modal proxy auth (optional, only if the endpoint requires headers).MODAL_KEY=MODAL_SECRET=# Force mock mode for the LLM even if MODAL_URL is set.ORACLES_FORCE_MOCK=0# Klein-4B image generation endpoint (separate from the LLM URL).# Leave empty to disable live image gen; mock SVG cards are used.KLEIN_URL=12345678910111213141516171819202122232425# Copy to .env.local and fill in. Without these, the app runs in mock mode.# Modal-hosted OpenAI-compatible endpoint (vLLM serving Qwen2.5-14B + LoRA).# Leave empty to force mock mode for the LLM calls.MODAL_URL=# Modal proxy auth (Modal-Key and Modal-Secret headers).MODAL_KEY=MODAL_SECRET=# Force mock mode for the LLM even if MODAL_URL is set.ORACLES_FORCE_MOCK=0# Override the served-model alias. Defaults to "oracle-wizard-lora" which# the deployed vLLM serves as Qwen2.5-14B + the custom humor LoRA. Set# to "llm" to request the bare base model.# ORACLES_LLM_MODEL=oracle-wizard-lora# Disable LLM-call trace recording. Tracing is default-on; remove or set# to 0 to keep it on. Set to 1 to opt out.# ORACLES_TRACE_DISABLE=0# Visual mode: "lean" (default; minimal PNGs for fast load) or "full"# (parallax banner, scene landscapes, all decorative assets).# ORACLES_VISUAL_MODE=lean
7 unmodified lines891011121314154082 unmodified lines409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414984 unmodified lines4234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276755 unmodified lines503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051713 unmodified lines51755176517751785179518051815182518351847 unmodified lines5192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752187 unmodified linesinscribe β send_off β trial (1..5) β epilogue β doneRun:python app.py # launches Gradiopython app.py --self-test # scripted walkthrough; exits 0 on pass"""from __future__ import annotations4082 unmodified linesreturn _ui_bundle(state)def _legacy_handle_grimoire_lang_unused(state, language_label, theme_label="", narration_label=""):"""Kept only to satisfy any stale call sites; identical to the refactor.DO NOT USE β call _apply_spread0_choices via handle_grimoire_lang instead."""if state.mode != "inscribe" or state.inscribe_step != 0:return _ui_bundle(state)state.lang = _label_to_lang_code(language_label)# Resolve theme label back to its key; default to fantasy on miss.from oracles.themes import THEMES, DEFAULT_THEMEchosen_key = DEFAULT_THEMEfor key, theme in THEMES.items():if theme.display_name == theme_label:chosen_key = keybreakstate.theme = chosen_key# Resolve narration-length label back to its key; default to medium.# Label is now a `{"en": ..., "zh": ...}` dict β match against either# language so the lookup is robust to whichever tongue the dropdown# was rendered in when the click happened.from oracles.state import NARRATION_LENGTHS as _NLchosen_nl = "medium"for key, (label, *_rest) in _NL.items():if isinstance(label, dict):if narration_label in label.values():chosen_nl = keybreakelif label == narration_label:chosen_nl = keybreakstate.narration_length = chosen_nl# Refresh hero/village defaults to the theme's archetypes, if the user# hasn't customized them yet (so the next spread's prompt shows themed# defaults like "Wren" / "Bunker 7" instead of "Tobin" / "the Hollow").theme_obj = THEMES[chosen_key]if state.hero_name in ("", "Tobin"):state.hero_name = theme_obj.hero_defaultif state.village_name in ("", "the Hollow"):state.village_name = theme_obj.village_defaultstate.grimoire_error = ""state.inscribe_step = 1return _ui_bundle(state)def handle_grimoire_name(state: GameState, hero_name: str):"""Step 1 β 2: inscribe the hero's name."""if state.mode != "inscribe" or state.inscribe_step != 1:84 unmodified linesyield _ui_bundle(state, trial_substate=TRIAL_STATE_AWAIT)# Back-compat shim for the e2e test and self-test that still call the# original "seal everything in one shot" function.def handle_seal_oracles(state: GameState,hero_name: str,village_name: str,language_label: str,o1: str,o2: str,o3: str,o4: str,o5: str,):if state.mode != "inscribe":return _ui_bundle(state)texts = [o1 or "", o2 or "", o3 or "", o4 or "", o5 or ""]missing = [i + 1 for i, t in enumerate(texts) if not t.strip()]if missing:roman = ", ".join(_ROMAN.get(i, str(i)) for i in missing)err = (f"The parchment is blank β Oracle{'s' if len(missing) > 1 else ''} "f"{roman} must hold at least one word.")# Surface error in the legacy slot AND on the grimoire so tests can find it.state.grimoire_error = errreturn _ui_bundle(state, inscribe_error=err)state.hero_name = (hero_name or "Tobin").strip() or "Tobin"state.village_name = (village_name or "the Hollow").strip() or "the Hollow"state.lang = _label_to_lang_code(language_label)for o, text in zip(state.oracles, texts):o.text = textstate.inscribe_step = 8 # consider all spreads "passed"state.mode = "send_off"state.grimoire_error = ""return _ui_bundle(state, inscribe_error="")def handle_send_off(state: GameState):"""send_off β trial 1. Generates the 5 obstacles AND kicks off thebackground precompute so trial reveals are instant in live mode."""755 unmodified linesreturn demo# ---------------------------------------------------------------------------# Self-test# ---------------------------------------------------------------------------def _drain(gen_or_value):"""Drain a generator handler to its final yielded bundle.Several click handlers (handle_open_oracle, handle_continue,handle_grimoire_begin, handle_send_off) are generators that yieldintermediate "walking-hero" UI states then a terminal bundle. Theself-test only cares about the terminal bundle. Pass-through anynon-generator return value untouched so the helper works forregular handlers too."""import inspect as _inspectif _inspect.isgenerator(gen_or_value):last = Nonefor b in gen_or_value:last = breturn lastreturn gen_or_valuedef run_self_test() -> int:"""Scripted walkthrough that doesn't launch the server.Returns 0 on success, non-zero on failure."""# Force mock mode then rebuild the module-level CLIENT.os.environ["ORACLES_FORCE_MOCK"] = "1"global CLIENTCLIENT = LLMClient()assert CLIENT.using_mock, "self-test requires mock mode"# Fresh state β and seed the inputs as scripted.state = fresh_state()oracle_texts = ["be patient","pizza is square","π","wooden spoon","42",]# --- inscribe β send_off ---bundle = handle_seal_oracles(state,"Tobin","the Hollow",LANG_LABELS["en"],*oracle_texts,)state = bundle[0]assert state.mode == "send_off", f"expected send_off, got {state.mode!r}"assert all(state.oracles[i].text == oracle_texts[i] for i in range(NUM_ORACLES)), \"oracle texts not persisted"# --- send_off β trial 1 (also generates obstacles) ---bundle = _drain(handle_send_off(state))state = bundle[0]assert state.mode == "trial", f"expected trial, got {state.mode!r}"assert state.current_trial == 1, f"expected current_trial=1, got {state.current_trial}"assert len(state.obstacles) == NUM_TRIALS, (f"expected {NUM_TRIALS} obstacles, got {len(state.obstacles)}")assert state.obstacles[-1].is_dragon, "trial 5 should be dragon"# --- trials 1..5 ---for trial_n in range(1, NUM_TRIALS + 1):assert state.mode == "trial", f"trial {trial_n}: bad mode {state.mode!r}"assert state.current_trial == trial_n, (f"trial {trial_n}: bad current_trial {state.current_trial}")# Open oracle (await -> reveal).bundle = _drain(handle_open_oracle(state, TRIAL_STATE_AWAIT))state = bundle[0]substate = bundle[1]assert substate == TRIAL_STATE_REVEAL, (f"trial {trial_n}: expected reveal substate, got {substate!r}")res = state.resolutions[-1]assert res.trial_index == trial_n, (f"trial {trial_n}: resolution.trial_index mismatch")assert res.narration and len(res.narration.strip()) > 0, (f"trial {trial_n}: empty narration")assert res.tactic and len(res.tactic.strip()) > 0, (f"trial {trial_n}: empty tactic")# Image file should exist on disk and have non-zero size (mock SVG/PNG).assert res.image_path, f"trial {trial_n}: empty image_path"assert os.path.exists(res.image_path), (f"trial {trial_n}: image_path {res.image_path!r} not on disk")assert os.path.getsize(res.image_path) > 0, (f"trial {trial_n}: image_path {res.image_path!r} is empty")# Continue.bundle = _drain(handle_continue(state, TRIAL_STATE_REVEAL))state = bundle[0]# After trial 5 continue: epilogue.assert state.mode == "epilogue", (f"expected epilogue after trial {NUM_TRIALS}, got {state.mode!r}")assert state.epilogue and state.epilogue.strip(), "epilogue empty"# Restart should land us back in inscribe with a fresh state, names preserved.bundle = handle_restart(state)new_state = bundle[0]assert new_state.mode == "inscribe", (f"after restart expected inscribe, got {new_state.mode!r}")assert new_state.hero_name == "Tobin", "hero name should be preserved"assert new_state.village_name == "the Hollow", "village name should be preserved"assert all(o.text == "" for o in new_state.oracles), ("oracles should be blank after restart")assert new_state.resolutions == [], "resolutions should be cleared"# Also exercise build_app() once.demo = build_app()assert demo is not None, "build_app returned None"print("SELF TEST PASSED")return 0# ---------------------------------------------------------------------------# Entry point# ---------------------------------------------------------------------------3 unmodified lines# to its own ``.launch()`` with DEFAULT settings β which means everything we# pass to ``demo.launch(...)`` below would be ignored (no theme, no css, no# ssr_mode=False, no allowed_paths). So we build the demo at module scope.## To keep --self-test fast (it doesn't need a Blocks instance, and building# one base64-encodes ~30 sprites), we skip the eager build when the flag is# present.# Register the assets directory with Gradio's static file router so# /gradio_api/file=<absolute-path> URLs served at runtime resolve to actual7 unmodified linespassif "--self-test" in sys.argv:demo = Noneelif os.environ.get("BISECT_MINIMAL") == "1":# Diagnostic bisect: if the App tab shows this minimal page, then the# full build_app() Blocks tree is what breaks iframe rendering. If it# ALSO shows nothing, the problem is outside build_app (Docker, port# routing, allowed_paths, etc).with gr.Blocks(title="The Apprentice β bisect probe") as demo:gr.Markdown("# BISECT PROBE")gr.Markdown("If you can read this, the Docker + Gradio + iframe layers work. ""The full build_app() Blocks tree is what's breaking rendering.")gr.Button("Click me").click(lambda: "ok", outputs=gr.Textbox())else:demo = build_app()def main() -> int:if "--self-test" in sys.argv:return run_self_test()# Local entry point β uses the module-level ``demo`` so the local run# matches the HF Space behavior exactly.# ssr_mode is Gradio 5+ only. The local dev env may still be on7 unmodified lines8910111213144082 unmodified lines40974098409941004101410284 unmodified lines418741884189419041914192755 unmodified lines4948494949504951495249533 unmodified lines4957495849594960496149627 unmodified lines49704971497249734974497549764977497849797 unmodified linesinscribe β send_off β trial (1..5) β epilogue β doneRun:python app.py # launches Gradio (uses ./run.sh for full setup)"""from __future__ import annotations4082 unmodified linesreturn _ui_bundle(state)def handle_grimoire_name(state: GameState, hero_name: str):"""Step 1 β 2: inscribe the hero's name."""if state.mode != "inscribe" or state.inscribe_step != 1:84 unmodified linesyield _ui_bundle(state, trial_substate=TRIAL_STATE_AWAIT)def handle_send_off(state: GameState):"""send_off β trial 1. Generates the 5 obstacles AND kicks off thebackground precompute so trial reveals are instant in live mode."""755 unmodified linesreturn demo# ---------------------------------------------------------------------------# Entry point# ---------------------------------------------------------------------------3 unmodified lines# to its own ``.launch()`` with DEFAULT settings β which means everything we# pass to ``demo.launch(...)`` below would be ignored (no theme, no css, no# ssr_mode=False, no allowed_paths). So we build the demo at module scope.# Register the assets directory with Gradio's static file router so# /gradio_api/file=<absolute-path> URLs served at runtime resolve to actual7 unmodified linespassdemo = build_app()def main() -> int:# Local entry point β uses the module-level ``demo`` so the local run# matches the HF Space behavior exactly.# ssr_mode is Gradio 5+ only. The local dev env may still be on
24 unmodified lines2526272829303124 unmodified lines# Sharing-is-Caring badge.# --no-trace Disable trace writing for this run (sets# ORACLES_TRACE_DISABLE=1).# --self-test Pass-through to app.py for the scripted walkthrough.# --full Enable ALL decorative PNGs (parallax banner,# parchment, phase backdrops, scene landscapes,# wizard-desk, open-book, demo-card backdrop).24 unmodified lines25262728293024 unmodified lines# Sharing-is-Caring badge.# --no-trace Disable trace writing for this run (sets# ORACLES_TRACE_DISABLE=1).# --full Enable ALL decorative PNGs (parallax banner,# parchment, phase backdrops, scene landscapes,# wizard-desk, open-book, demo-card backdrop).
.env.example+14-5
app.py+2-241
assets/sprites/banner_near.pngDeleted
Large File Pointer Details
- SHA256: 5cafce547a9e222b8216396bdebc2b496cc3dc6526dd9e0aaf4840c62d0456c2
- Pointer size: 132 Bytes
- Size of remote file: 1.22 MB
run.sh-1