First pass
Browse filesFiles changed (6)
- app.py+250-41
- static/app.jsDeleted-232
- static/index.htmlDeleted-102
- static/storage.jsDeleted-82
- static/style.cssDeleted-171
- theme.cssAdded+169
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""FrogQuest server: gr.Server custom frontend + queued API endpoints (Off-Brand badge).The browser owns all state (localStorage, see static/storage.js). This server is stateless:it serves the pixel-art frontend and exposes two GPU-backed endpoints. The user's photo issent transiently to generate_image and is never written to disk.NOTE: the @spaces.GPU functions live in llm.py / images.py and are imported AT MODULE LEVELbelow. ZeroGPU scans for @spaces.GPU functions during startup by importing this file, so theimport must NOT be deferred into the endpoints (doing so triggers"No @spaces.GPU function detected during startup" and the container stops).Frontend calls endpoints via the Gradio JS Client:client.predict("/generate_quests", { todos, theme })client.predict("/generate_image", { photo_b64, art_style, scene_prompt, seed })"""from __future__ import annotationsimport jsonimport osfrom fastapi.responses import HTMLResponsefrom fastapi.staticfiles import StaticFilesfrom gradio import Serverfrom schema import validate_and_clamp# Top-level imports so ZeroGPU registers the @spaces.GPU functions at startup.from llm import generate_quests_rawfrom images import b64_to_pil, initial_image, pil_to_data_urlSTATIC_DIR = os.path.join(os.path.dirname(__file__), "static")app = Server()app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")@app.get("/", response_class=HTMLResponse)async def homepage():with open(os.path.join(STATIC_DIR, "index.html"), "r", encoding="utf-8") as f:return f.read()@app.api(name="generate_quests")def generate_quests(todos: str, theme: str) -> str:"""Nemotron -> validated quest JSON (returned as a JSON string)."""raw = generate_quests_raw(todos, theme)adventure = validate_and_clamp(raw, theme)return json.dumps(adventure)@app.api(name="generate_image")def generate_image(photo_b64: str, art_style: str, scene_prompt: str, seed: int) -> str:"""FLUX.2 klein initial image with the user as hero -> PNG data URL."""photo = b64_to_pil(photo_b64)img = initial_image(photo, art_style, scene_prompt, int(seed))return pil_to_data_url(img)# Launch at MODULE LEVEL (no __main__ guard) — this matches the working gr.Server+ZeroGPU# reference Space (ysharma/text-behind-image). HF Spaces IMPORTS app.py rather than running it# as __main__, so a `if __name__ == "__main__"` guard would never fire and HF's launcher would# loop trying to find a launchable. There is intentionally NO `demo` variable.app.launch(show_error=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271"""FrogQuest — plain Gradio (gr.Blocks) app.Standard HF Spaces pattern: a module-level `demo` Blocks + `demo.launch()`. The LLM/imagemodules are imported DEFENSIVELY so a bleeding-edge import error (e.g. a diffusers buildmissing Flux2KleinPipeline) surfaces in the UI instead of hanging the Space on a loadingscreen. A module-level @spaces.GPU `_warmup` guarantees ZeroGPU's startup detection even ifthose imports fail.State lives in gr.BrowserState (per-browser localStorage): the resized photo (base64), thechosen theme, and the validated adventure/quests JSON. The photo goes to the GPU onlytransiently during generation and is never persisted server-side."""from __future__ import annotationsimport base64import htmlimport ioimport osimport tracebackimport gradio as grimport spacesfrom PIL import Imagefrom schema import validate_and_clamp# ZeroGPU scans for a @spaces.GPU function at startup; this guarantees detection regardless# of whether the heavy model modules import cleanly.@spaces.GPU(duration=15)def _warmup():return "ok"# Defensive import: never let a model-import error hang the whole app.MODEL_IMPORT_ERROR = Nonetry:from llm import generate_quests_rawfrom images import initial_imageexcept Exception:MODEL_IMPORT_ERROR = traceback.format_exc()# ----------------------------- photo helpers (PIL only) -----------------------------PHOTO_MAX_SIDE = 512def _resize_dataurl(pil: Image.Image, max_side: int = PHOTO_MAX_SIDE) -> str:img = pil.convert("RGB")w, h = img.sizescale = min(1.0, max_side / max(w, h))if scale < 1.0:img = img.resize((round(w * scale), round(h * scale)))buf = io.BytesIO()img.save(buf, format="JPEG", quality=80)return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode("ascii")def _dataurl_to_pil(data_url: str) -> Image.Image:s = data_url.split(",", 1)[1] if "," in data_url else data_urlreturn Image.open(io.BytesIO(base64.b64decode(s))).convert("RGB")def _import_error_message() -> str:last = (MODEL_IMPORT_ERROR or "").strip().splitlines()return "Model failed to load: " + (last[-1] if last else "unknown error")# ----------------------------- quest-card HTML -----------------------------def _card_body(q: dict) -> str:badges = []if q.get("is_frog"):badges.append('<span class="badge frog-badge">🐸 THE FROG</span>')if q.get("type") == "bonus":badges.append('<span class="badge bonus-badge">✦ BONUS · OPTIONAL</span>')if q.get("goal_group"):badges.append(f'<span class="badge group-badge">⛓ {html.escape(str(q["goal_group"]))}</span>')return ('<div class="quest-body">'f'<div class="quest-badges">{"".join(badges)}</div>'f'<h3 class="quest-title">{html.escape(q.get("quest_title", ""))}</h3>'f'<p class="quest-narrative">{html.escape(q.get("narrative", ""))}</p>'f'<p class="quest-task">{html.escape(q.get("task", ""))}</p>'f'<div class="quest-foot"><span class="xp">{int(q.get("xp", 0))} XP</span></div>''</div>')def _title_html(adventure: dict | None) -> str:if not adventure:return ""return f'<div class="adventure-header"><h2>{html.escape(adventure.get("title", ""))}</h2></div>'# ----------------------------- event handlers -----------------------------def boot(state):state = state or {}profile = state.get("profile") or {}has_profile = bool(profile.get("photo") and profile.get("theme"))return (gr.update(visible=not has_profile), # onboard_colgr.update(visible=has_profile), # app_colprofile.get("photo"), # photo_stateprofile.get("theme") or "", # theme_boxstate.get("quests") or [], # quests_statestate.get("adventure"), # adventure_state_title_html(state.get("adventure")), # adventure_title)def begin(photo_pil, theme, state):if photo_pil is None:raise gr.Error("Upload a photo first.")if not theme:raise gr.Error("Pick a theme first.")photo_b64 = _resize_dataurl(photo_pil)state = dict(state or {})state["profile"] = {"photo": photo_b64, "theme": theme}return state, photo_b64, gr.update(visible=False), gr.update(visible=True)def go_settings(photo_b64):preview = _dataurl_to_pil(photo_b64) if photo_b64 else Nonereturn gr.update(visible=True), gr.update(visible=False), previewdef forge(todos, theme, photo_b64, state):if MODEL_IMPORT_ERROR:raise gr.Error(_import_error_message())if not (todos or "").strip():raise gr.Error("Tell the oracle your plans first.")theme = theme or (state or {}).get("profile", {}).get("theme") or "cyberpunk"raw = generate_quests_raw(todos, theme)adventure = validate_and_clamp(raw, theme)state = dict(state or {})state["adventure"] = adventure["adventure"]state["quests"] = adventure["quests"]return adventure["quests"], adventure["adventure"], state, _title_html(adventure["adventure"])def _make_scene_handler(quest_id: str, scene_prompt: str):def _gen(photo_b64, adventure):if MODEL_IMPORT_ERROR:raise gr.Error(_import_error_message())if not photo_b64:raise gr.Error("Add a photo in Settings first.")if not adventure:raise gr.Error("Forge a quest log first.")pil = _dataurl_to_pil(photo_b64)return initial_image(pil, adventure["art_style"], scene_prompt, int(adventure["seed"]))return _gen# ----------------------------- UI -----------------------------_DIR = os.path.dirname(os.path.abspath(__file__))with open(os.path.join(_DIR, "theme.css"), "r", encoding="utf-8") as _f:THEME_CSS = _f.read()HEAD = """<script>function fqSetTheme(t){if(!t){ return; }document.documentElement.setAttribute('data-theme', t);['cyberpunk','fantasy','space'].forEach(function(n){var el = document.getElementById('theme-' + n);if(el){ el.classList.toggle('selected', n === t); }});}</script>"""with gr.Blocks(css=THEME_CSS,head=HEAD,title="FrogQuest",theme=gr.themes.Base(font=[gr.themes.GoogleFont("Press Start 2P"), "monospace"]),) as demo:browser = gr.BrowserState({"profile": {"photo": None, "theme": None}, "adventure": None, "quests": []},storage_key="frogquest",)photo_state = gr.State(None) # resized photo as base64 data URLquests_state = gr.State([]) # drives the quest-log renderadventure_state = gr.State(None) # title / art_style / seedtheme_box = gr.Textbox(visible=False) # canonical theme; .change applies the palettegr.HTML('<div class="fq-topbar"><h1 class="fq-logo">FROG<b>QUEST</b></h1></div>')# ---------- onboarding ----------with gr.Column(visible=True) as onboard_col:with gr.Group(elem_classes=["panel"]):gr.HTML('<h2 class="panel-title">NEW HERO</h2>''<p class="hint">Upload a photo so you become the hero of every quest. ''It stays in your browser — sent to the GPU only to draw your scenes, never stored ''on a server.</p>')photo_image = gr.Image(type="pil", sources=["upload"], show_label=False, height=240,elem_classes=["uploader"],)gr.HTML('<h3 class="panel-subtitle">CHOOSE YOUR WORLD</h3>')with gr.Row():cyber_btn = gr.Button("🌃\nCYBERPUNK", elem_id="theme-cyberpunk", elem_classes=["theme-card"])fantasy_btn = gr.Button("🏰\nFANTASY", elem_id="theme-fantasy", elem_classes=["theme-card"])space_btn = gr.Button("🚀\nSPACE", elem_id="theme-space", elem_classes=["theme-card"])begin_btn = gr.Button("BEGIN ADVENTURE ▶", elem_classes=["pix-btn", "primary"])# ---------- main app ----------with gr.Column(visible=False) as app_col:settings_btn = gr.Button("⚙ SETTINGS", elem_classes=["pix-btn", "small"])with gr.Group(elem_classes=["panel"]):gr.HTML('<h2 class="panel-title">TELL THE ORACLE YOUR PLANS</h2>')todos_box = gr.Textbox(lines=5, show_label=False, elem_classes=["compose"],placeholder=("e.g. Finish the quarterly report (due Friday), reply to 3 emails, ""book dentist, start gym routine, learn one chord on guitar..."),)forge_btn = gr.Button("⚔ FORGE QUEST LOG", elem_classes=["pix-btn", "primary"])adventure_title = gr.HTML("")@gr.render(inputs=[quests_state])def render_quests(quests):for q in quests or []:classes = ["quest-card"]if q.get("is_frog"):classes.append("is-frog")if q.get("type") == "bonus":classes.append("is-bonus")with gr.Group(elem_classes=classes):with gr.Row():with gr.Column(scale=2, min_width=160):scene_img = gr.Image(show_label=False, interactive=False, height=200,container=False, elem_classes=["quest-art"],)gen_btn = gr.Button("GENERATE SCENE", elem_classes=["pix-btn", "small"])with gr.Column(scale=3):gr.HTML(_card_body(q))gen_btn.click(_make_scene_handler(q.get("id", ""), q.get("initial_image_prompt", "")),inputs=[photo_state, adventure_state],outputs=[scene_img],)# ---------- wiring ----------theme_box.change(None, theme_box, None, js="(t) => { fqSetTheme(t); }")cyber_btn.click(lambda: "cyberpunk", None, theme_box)fantasy_btn.click(lambda: "fantasy", None, theme_box)space_btn.click(lambda: "space", None, theme_box)begin_btn.click(begin, [photo_image, theme_box, browser], [browser, photo_state, onboard_col, app_col])settings_btn.click(go_settings, [photo_state], [onboard_col, app_col, photo_image])forge_btn.click(forge, [todos_box, theme_box, photo_state, browser],[quests_state, adventure_state, browser, adventure_title],)demo.load(boot, [browser],[onboard_col, app_col, photo_state, theme_box, quests_state, adventure_state, adventure_title],)if __name__ == "__main__":demo.launch()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232// FrogQuest frontend flow. The browser owns all state; the server is two stateless endpoints.import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client/+esm";import * as store from "/static/storage.js";
const $ = (sel) => document.querySelector(sel);const $$ = (sel) => document.querySelectorAll(sel);
let state = store.load();let pendingPhoto = state.profile.photo; // staged during onboardinglet pendingTheme = state.profile.theme;let _client = null;
async function client() { if (!_client) _client = await Client.connect(window.location.origin); return _client;}
function setTheme(theme) { document.documentElement.dataset.theme = theme || "cyberpunk";}
function show(id) { ["screen-onboard", "screen-app"].forEach((s) => ($("#" + s).hidden = s !== id)); $("#settings-btn").hidden = id !== "screen-app";}
function overlay(msg) { $("#overlay-msg").textContent = msg; $("#overlay").hidden = false;}function hideOverlay() { $("#overlay").hidden = true;}
// ---------------- onboarding ----------------
function refreshBeginEnabled() { $("#begin-btn").disabled = !(pendingPhoto && pendingTheme);}
function initOnboarding() { setTheme(pendingTheme);
if (pendingPhoto) { $("#photo-preview").src = pendingPhoto; $("#photo-preview").hidden = false; $("#photo-placeholder").hidden = true; } $$("#theme-grid .theme-card").forEach((c) => c.classList.toggle("selected", c.dataset.theme === pendingTheme) );
$("#photo-input").addEventListener("change", async (e) => { const file = e.target.files[0]; if (!file) return; try { pendingPhoto = await store.resizePhoto(file); $("#photo-preview").src = pendingPhoto; $("#photo-preview").hidden = false; $("#photo-placeholder").hidden = true; refreshBeginEnabled(); } catch { alert("Could not read that image — try another file."); } });
$$("#theme-grid .theme-card").forEach((card) => card.addEventListener("click", () => { pendingTheme = card.dataset.theme; setTheme(pendingTheme); $$("#theme-grid .theme-card").forEach((c) => c.classList.toggle("selected", c === card) ); refreshBeginEnabled(); }) );
$("#begin-btn").addEventListener("click", () => { state = store.update({ profile: { photo: pendingPhoto, theme: pendingTheme } }); enterApp(); });
refreshBeginEnabled(); show("screen-onboard");}
// ---------------- main app ----------------
function enterApp() { setTheme(state.profile.theme); show("screen-app"); if (state.adventure && state.quests.length) { renderAdventure(); }}
async function onGenerate() { const todos = $("#todos-input").value.trim(); if (!todos) { $("#todos-input").focus(); return; } overlay("THE ORACLE IS WRITING YOUR QUEST LOG…"); try { const c = await client(); const res = await c.predict("/generate_quests", { todos, theme: state.profile.theme, }); const adventure = JSON.parse(res.data[0]); state = store.update({ adventure: adventure.adventure, quests: adventure.quests, images: {}, // new adventure -> drop old image cache }); renderAdventure(); } catch (err) { console.error(err); alert("The oracle stumbled. Please try again.\n\n" + (err?.message || err)); } finally { hideOverlay(); }}
function renderAdventure() { const { adventure, quests, images } = state; $("#adventure-header").hidden = false; $("#adventure-title").textContent = adventure.title || "Your Quest Log";
const log = $("#quest-log"); log.innerHTML = ""; const tpl = $("#quest-card-tpl");
quests.forEach((q) => { const node = tpl.content.firstElementChild.cloneNode(true); node.dataset.questId = q.id; if (q.is_frog) node.classList.add("is-frog"); if (q.type === "bonus") node.classList.add("is-bonus");
node.querySelector(".frog-badge").hidden = !q.is_frog; node.querySelector(".bonus-badge").hidden = q.type !== "bonus"; const group = node.querySelector(".group-badge"); if (q.goal_group) { group.hidden = false; group.textContent = "⛓ " + q.goal_group; }
node.querySelector(".quest-title").textContent = q.quest_title; node.querySelector(".quest-narrative").textContent = q.narrative; node.querySelector(".quest-task").textContent = q.task; node.querySelector(".xp").textContent = q.xp + " XP";
const img = node.querySelector(".quest-img"); const empty = node.querySelector(".quest-art-empty"); const cached = images[q.id]?.initial; if (cached) { img.src = cached; img.hidden = false; empty.hidden = true; } else { node .querySelector(".gen-img-btn") .addEventListener("click", () => generateScene(q, node)); }
log.appendChild(node); });}
async function generateScene(quest, node) { if (!state.profile.photo) { alert("Add a photo in Settings first so you can star in the scene."); return; } const btn = node.querySelector(".gen-img-btn"); btn.disabled = true; btn.textContent = "DRAWING…"; try { const c = await client(); const res = await c.predict("/generate_image", { photo_b64: state.profile.photo, art_style: state.adventure.art_style, scene_prompt: quest.initial_image_prompt, seed: state.adventure.seed, }); const dataUrl = res.data[0]; state = store.cacheImage(quest.id, "initial", dataUrl); const img = node.querySelector(".quest-img"); img.src = dataUrl; img.hidden = false; node.querySelector(".quest-art-empty").hidden = true; } catch (err) { console.error(err); btn.disabled = false; btn.textContent = "RETRY SCENE"; alert("The artist's pixels jammed. Try again.\n\n" + (err?.message || err)); }}
// ---------------- settings ----------------
function initSettings() { $("#settings-btn").addEventListener("click", () => { pendingPhoto = state.profile.photo; pendingTheme = state.profile.theme; // re-seed onboarding UI with current values $("#photo-preview").src = pendingPhoto || ""; $("#photo-preview").hidden = !pendingPhoto; $("#photo-placeholder").hidden = !!pendingPhoto; $$("#theme-grid .theme-card").forEach((c) => c.classList.toggle("selected", c.dataset.theme === pendingTheme) ); refreshBeginEnabled(); show("screen-onboard"); });}
// ---------------- boot ----------------
function boot() { $("#generate-btn").addEventListener("click", onGenerate); initSettings(); initOnboarding();
if (state.profile.photo && state.profile.theme) { enterApp(); } else { show("screen-onboard"); }}
boot();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102<!DOCTYPE html><html lang="en" data-theme="cyberpunk"><head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>FrogQuest</title> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="/static/style.css" /></head><body> <div class="scanlines" aria-hidden="true"></div>
<header class="topbar"> <h1 class="logo">FROG<span>QUEST</span></h1> <button id="settings-btn" class="pix-btn small" hidden>SETTINGS</button> </header>
<!-- FIRST RUN: photo + theme --> <main id="screen-onboard" class="screen" hidden> <div class="panel"> <h2 class="panel-title">NEW HERO</h2> <p class="hint">Upload a photo so you become the hero of every quest. It stays in your browser — sent to the GPU only to draw your scenes, never stored on a server.</p>
<label class="uploader" id="photo-drop"> <input type="file" id="photo-input" accept="image/*" hidden /> <img id="photo-preview" alt="" hidden /> <span id="photo-placeholder">▣ CLICK TO UPLOAD PHOTO</span> </label>
<h3 class="panel-subtitle">CHOOSE YOUR WORLD</h3> <div class="theme-grid" id="theme-grid"> <button class="theme-card" data-theme="cyberpunk"> <span class="theme-emoji">🌃</span><span>CYBERPUNK</span> </button> <button class="theme-card" data-theme="fantasy"> <span class="theme-emoji">🏰</span><span>FANTASY</span> </button> <button class="theme-card" data-theme="space"> <span class="theme-emoji">🚀</span><span>SPACE</span> </button> </div>
<button id="begin-btn" class="pix-btn primary" disabled>BEGIN ADVENTURE ▶</button> </div> </main>
<!-- MAIN: goals -> quest log --> <main id="screen-app" class="screen" hidden> <section class="panel compose"> <h2 class="panel-title">TELL THE ORACLE YOUR PLANS</h2> <textarea id="todos-input" rows="5" placeholder="e.g. Finish the quarterly report (due Friday), reply to 3 emails, book dentist, start gym routine, learn one chord on guitar..."></textarea> <button id="generate-btn" class="pix-btn primary">⚔ FORGE QUEST LOG</button> </section>
<section id="adventure-header" class="adventure-header" hidden> <h2 id="adventure-title"></h2> </section>
<section id="quest-log" class="quest-log" aria-live="polite"></section> </main>
<!-- status / loading overlay --> <div id="overlay" class="overlay" hidden> <div class="overlay-box"> <div class="loader"></div> <p id="overlay-msg">LOADING…</p> </div> </div>
<!-- card template --> <template id="quest-card-tpl"> <article class="quest-card"> <div class="quest-art"> <img class="quest-img" alt="" hidden /> <div class="quest-art-empty"> <span class="art-glyph">🗺</span> <button class="pix-btn small gen-img-btn">GENERATE SCENE</button> </div> </div> <div class="quest-body"> <div class="quest-badges"> <span class="badge frog-badge" hidden>🐸 THE FROG</span> <span class="badge bonus-badge" hidden>✦ BONUS · OPTIONAL</span> <span class="badge group-badge" hidden></span> </div> <h3 class="quest-title"></h3> <p class="quest-narrative"></p> <p class="quest-task"></p> <div class="quest-foot"> <span class="xp"></span> </div> </div> </article> </template>
<script type="module" src="/static/app.js"></script></body></html>12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182// FrogQuest browser-only persistence. Everything lives in localStorage under one key.// The photo is resized client-side BEFORE storing so it fits the ~5MB localStorage cap.
const KEY = "frogquest:v1";const PHOTO_MAX_SIDE = 512;const PHOTO_QUALITY = 0.8;
const EMPTY = { version: 1, profile: { photo: null, theme: null }, adventure: null, quests: [], images: {}, // questId -> { initial, success, failure } (data URLs; best-effort cache)};
export function load() { try { const raw = localStorage.getItem(KEY); if (!raw) return structuredClone(EMPTY); const parsed = JSON.parse(raw); return { ...structuredClone(EMPTY), ...parsed }; } catch { return structuredClone(EMPTY); }}
export function save(state) { // Try to persist everything; if the image cache blows the quota, drop it and keep the // reproducible core (seed + prompts regenerate the images on demand). try { localStorage.setItem(KEY, JSON.stringify(state)); } catch (e) { if (e && e.name === "QuotaExceededError") { const lean = { ...state, images: {} }; try { localStorage.setItem(KEY, JSON.stringify(lean)); } catch { /* give up on persistence; in-memory state still works this session */ } } } return state;}
export function update(patch) { return save({ ...load(), ...patch });}
export function cacheImage(questId, slot, dataUrl) { const state = load(); state.images[questId] = { ...(state.images[questId] || {}), [slot]: dataUrl }; return save(state);}
export function clear() { localStorage.removeItem(KEY);}
// Read an uploaded File, downscale so the longest side <= PHOTO_MAX_SIDE, return a JPEG data URL.export function resizePhoto(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onerror = () => reject(new Error("Could not read file")); reader.onload = () => { const img = new Image(); img.onerror = () => reject(new Error("Could not decode image")); img.onload = () => { let { width, height } = img; const scale = Math.min(1, PHOTO_MAX_SIDE / Math.max(width, height)); width = Math.round(width * scale); height = Math.round(height * scale); const canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; canvas.getContext("2d").drawImage(img, 0, 0, width, height); resolve(canvas.toDataURL("image/jpeg", PHOTO_QUALITY)); }; img.src = reader.result; }; reader.readAsDataURL(file); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171/* FrogQuest — 8-bit / NES-RPG pixel-art theme. */
:root { --bg: #0d0b1a; --bg2: #161228; --panel: #1d1733; --ink: #e8e6ff; --dim: #9b95c9; --accent: #00e5ff; --accent2: #ff2e88; --gold: #ffd23f; --frog: #4ade5b; --shadow: #000; --border: 4px; font-family: "Press Start 2P", monospace;}
/* ---- per-theme palettes (set on <html data-theme>) ---- */[data-theme="cyberpunk"] { --bg:#0d0b1a; --bg2:#161228; --panel:#1d1733; --accent:#00e5ff; --accent2:#ff2e88; --gold:#ffd23f; }[data-theme="fantasy"] { --bg:#10180f; --bg2:#172414; --panel:#1d2e1a; --accent:#7bdc5a; --accent2:#ffae34; --gold:#ffe066; --ink:#eafbe2; --dim:#9ec48c; }[data-theme="space"] { --bg:#070914; --bg2:#0d1124; --panel:#141a36; --accent:#7c5cff; --accent2:#36c5ff; --gold:#ffd23f; --ink:#e6ecff; --dim:#8d97c9; }
* { box-sizing: border-box; }
html, body { margin: 0; background: var(--bg); color: var(--ink); image-rendering: pixelated;}
body { min-height: 100vh; padding-bottom: 48px; font-size: 11px; line-height: 1.7; background-image: repeating-linear-gradient(0deg, transparent 0 38px, rgba(255,255,255,0.015) 38px 39px), repeating-linear-gradient(90deg, transparent 0 38px, rgba(255,255,255,0.015) 38px 39px);}
/* faint CRT scanlines */.scanlines { position: fixed; inset: 0; pointer-events: none; z-index: 9000; background: repeating-linear-gradient(0deg, rgba(0,0,0,0.16) 0 2px, transparent 2px 4px); mix-blend-mode: multiply;}
/* ---------- top bar ---------- */.topbar { display: flex; align-items: center; justify-content: space-between; padding: 16px 20px; border-bottom: var(--border) solid var(--accent); background: var(--bg2);}.logo { margin: 0; font-size: 20px; letter-spacing: 2px; color: var(--accent); text-shadow: 3px 3px 0 var(--shadow); }.logo span { color: var(--accent2); }
/* ---------- screens / panels ---------- */.screen { max-width: 860px; margin: 0 auto; padding: 24px 16px; }.panel { background: var(--panel); border: var(--border) solid var(--ink); box-shadow: 8px 8px 0 var(--shadow); padding: 22px; margin-bottom: 22px;}.panel-title { margin: 0 0 14px; font-size: 13px; color: var(--gold); text-shadow: 2px 2px 0 var(--shadow); }.panel-subtitle { margin: 22px 0 12px; font-size: 11px; color: var(--accent); }.hint { color: var(--dim); font-size: 10px; line-height: 1.9; }
/* ---------- buttons ---------- */.pix-btn { font-family: inherit; font-size: 11px; color: var(--ink); cursor: pointer; background: var(--bg2); border: var(--border) solid var(--ink); box-shadow: 4px 4px 0 var(--shadow); padding: 12px 16px; text-transform: uppercase; transition: transform .05s, box-shadow .05s;}.pix-btn:hover { background: var(--accent); color: var(--bg); }.pix-btn:active { transform: translate(4px, 4px); box-shadow: 0 0 0 var(--shadow); }.pix-btn:disabled { opacity: .4; cursor: not-allowed; }.pix-btn.primary { background: var(--accent2); color: #fff; border-color: #fff; width: 100%; margin-top: 18px; font-size: 12px; padding: 16px; }.pix-btn.primary:hover { background: var(--gold); color: var(--bg); }.pix-btn.small { font-size: 9px; padding: 9px 10px; box-shadow: 3px 3px 0 var(--shadow); }
/* ---------- uploader ---------- */.uploader { display: flex; align-items: center; justify-content: center; width: 100%; min-height: 200px; cursor: pointer; border: var(--border) dashed var(--accent); background: var(--bg2); color: var(--dim); font-size: 10px; text-align: center; overflow: hidden;}.uploader:hover { border-color: var(--gold); color: var(--ink); }#photo-preview { width: 100%; height: 240px; object-fit: cover; display: block; }
/* ---------- theme picker ---------- */.theme-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }.theme-card { font-family: inherit; font-size: 9px; color: var(--ink); cursor: pointer; display: flex; flex-direction: column; align-items: center; gap: 10px; padding: 18px 8px; background: var(--bg2); border: var(--border) solid var(--dim); box-shadow: 4px 4px 0 var(--shadow);}.theme-card:hover { border-color: var(--accent); }.theme-card.selected { border-color: var(--gold); background: var(--panel); box-shadow: 4px 4px 0 var(--accent2); }.theme-emoji { font-size: 26px; line-height: 1; }
/* ---------- compose ---------- */.compose textarea { width: 100%; resize: vertical; font-family: inherit; font-size: 10px; line-height: 1.8; color: var(--ink); background: var(--bg2); border: var(--border) solid var(--accent); padding: 14px; box-shadow: inset 3px 3px 0 var(--shadow);}.compose textarea:focus { outline: none; border-color: var(--gold); }
/* ---------- adventure header ---------- */.adventure-header { max-width: 860px; margin: 0 auto 6px; padding: 0 16px; }.adventure-header h2 { font-size: 14px; color: var(--gold); text-shadow: 2px 2px 0 var(--shadow); }
/* ---------- quest log ---------- */.quest-log { display: flex; flex-direction: column; gap: 20px; }
.quest-card { display: grid; grid-template-columns: 200px 1fr; background: var(--panel); border: var(--border) solid var(--ink); box-shadow: 8px 8px 0 var(--shadow); overflow: hidden;}.quest-card.is-frog { border-color: var(--frog); box-shadow: 8px 8px 0 var(--frog); }.quest-card.is-bonus { border-style: dashed; }.quest-card.done { opacity: .85; }
.quest-art { position: relative; background: var(--bg2); border-right: var(--border) solid var(--ink); min-height: 200px; }.quest-img { width: 100%; height: 100%; object-fit: cover; image-rendering: pixelated; }.quest-art-empty { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 14px; color: var(--dim);}.art-glyph { font-size: 40px; opacity: .6; }
.quest-body { padding: 16px 18px; }.quest-badges { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 10px; }.badge { font-size: 8px; padding: 5px 7px; border: 2px solid currentColor; }.frog-badge { color: var(--frog); }.bonus-badge { color: var(--accent); }.group-badge { color: var(--gold); }.quest-title { margin: 4px 0 10px; font-size: 12px; color: var(--ink); line-height: 1.6; }.quest-narrative { margin: 0 0 12px; font-size: 9px; color: var(--dim); line-height: 1.9; }.quest-task { margin: 0 0 14px; font-size: 9px; color: var(--accent); line-height: 1.8; }.quest-task::before { content: "▸ TASK: "; color: var(--dim); }.quest-foot { display: flex; align-items: center; justify-content: space-between; }.xp { font-size: 9px; color: var(--gold); }.xp::before { content: "★ "; }
/* ---------- overlay ---------- */.overlay { position: fixed; inset: 0; z-index: 9500; display: flex; align-items: center; justify-content: center; background: rgba(5,4,12,0.86);}.overlay-box { text-align: center; color: var(--ink); }.overlay-box p { font-size: 11px; margin-top: 18px; color: var(--accent); }.loader { width: 36px; height: 36px; margin: 0 auto; background: var(--accent2); animation: blink 0.6s steps(2, end) infinite;}@keyframes blink { 0% { opacity: 1; transform: scale(1); } 50% { opacity: .3; transform: scale(.7); } 100% { opacity: 1; transform: scale(1); } }
/* ---------- responsive ---------- */@media (max-width: 620px) { .quest-card { grid-template-columns: 1fr; } .quest-art { border-right: none; border-bottom: var(--border) solid var(--ink); } .theme-grid { grid-template-columns: 1fr; } .logo { font-size: 16px; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169/* FrogQuest — 8-bit / NES-RPG pixel-art theme for plain Gradio (gr.Blocks). Reuses the original static/style.css rules and adds overrides that strip Gradio's default chrome so the app looks identical to the gr.Server build. */
:root { --bg: #0d0b1a; --bg2: #161228; --panel: #1d1733; --ink: #e8e6ff; --dim: #9b95c9; --accent: #00e5ff; --accent2: #ff2e88; --gold: #ffd23f; --frog: #4ade5b; --shadow: #000; --border: 4px;}
/* ---- per-theme palettes (set on <html data-theme> by fqSetTheme) ---- */[data-theme="cyberpunk"] { --bg:#0d0b1a; --bg2:#161228; --panel:#1d1733; --accent:#00e5ff; --accent2:#ff2e88; --gold:#ffd23f; }[data-theme="fantasy"] { --bg:#10180f; --bg2:#172414; --panel:#1d2e1a; --accent:#7bdc5a; --accent2:#ffae34; --gold:#ffe066; --ink:#eafbe2; --dim:#9ec48c; }[data-theme="space"] { --bg:#070914; --bg2:#0d1124; --panel:#141a36; --accent:#7c5cff; --accent2:#36c5ff; --gold:#ffd23f; --ink:#e6ecff; --dim:#8d97c9; }
/* ================= Gradio chrome neutralization ================= */*, *::before, *::after { box-sizing: border-box; }
body, gradio-app, .gradio-container { background: var(--bg) !important; color: var(--ink) !important; font-family: "Press Start 2P", monospace !important; image-rendering: pixelated;}.gradio-container { max-width: 900px !important; margin: 0 auto !important; padding: 0 16px 64px !important; font-size: 11px !important; line-height: 1.7 !important;}/* faint background grid */.gradio-container { background-image: repeating-linear-gradient(0deg, transparent 0 38px, rgba(255,255,255,0.015) 38px 39px), repeating-linear-gradient(90deg, transparent 0 38px, rgba(255,255,255,0.015) 38px 39px) !important;}/* CRT scanlines overlay */body::after { content: ""; position: fixed; inset: 0; pointer-events: none; z-index: 9000; background: repeating-linear-gradient(0deg, rgba(0,0,0,0.16) 0 2px, transparent 2px 4px); mix-blend-mode: multiply;}/* hide Gradio's footer & progress chrome */footer, .gradio-container > .main > .wrap > .contain > div > .built-with,.show-api, .built-with { display: none !important; }
/* strip default block styling so our panels/cards control the look */.block, .form, .gr-box, .gr-block, .panel-fq .block, .styler,.gradio-container .prose { background: transparent !important; border: none !important; box-shadow: none !important; border-radius: 0 !important; }.gr-padded, .block.padded { padding: 0 !important; }.gap, .gradio-container .gap { gap: 0 !important; }
/* ================= original pixel-art rules ================= */.fq-topbar { display: flex; align-items: center; justify-content: space-between; padding: 16px 4px; border-bottom: var(--border) solid var(--accent); background: var(--bg2); margin-bottom: 20px;}.fq-logo { margin: 0; font-size: 20px; letter-spacing: 2px; color: var(--accent); text-shadow: 3px 3px 0 var(--shadow); }.fq-logo b { color: var(--accent2); font-weight: normal; }
.panel { background: var(--panel) !important; border: var(--border) solid var(--ink) !important; box-shadow: 8px 8px 0 var(--shadow) !important; padding: 22px !important; margin-bottom: 22px !important;}.panel-title { margin: 0 0 14px; font-size: 13px; color: var(--gold); text-shadow: 2px 2px 0 var(--shadow); }.panel-subtitle { margin: 18px 0 12px; font-size: 11px; color: var(--accent); }.hint { color: var(--dim); font-size: 10px; line-height: 1.9; }
/* ---------- buttons (Gradio <button> with elem_classes=["pix-btn"]) ---------- */button.pix-btn, .pix-btn button, .pix-btn { font-family: "Press Start 2P", monospace !important; font-size: 11px !important; color: var(--ink) !important; cursor: pointer; background: var(--bg2) !important; border: var(--border) solid var(--ink) !important; box-shadow: 4px 4px 0 var(--shadow) !important; padding: 12px 16px !important; text-transform: uppercase; border-radius: 0 !important; transition: transform .05s, box-shadow .05s; min-width: 0 !important;}button.pix-btn:hover, .pix-btn button:hover { background: var(--accent) !important; color: var(--bg) !important; }button.pix-btn:active, .pix-btn button:active { transform: translate(4px, 4px); box-shadow: 0 0 0 var(--shadow) !important; }.pix-btn.primary, .pix-btn.primary button { background: var(--accent2) !important; color: #fff !important; border-color: #fff !important; width: 100% !important; font-size: 12px !important; padding: 16px !important;}.pix-btn.primary:hover, .pix-btn.primary button:hover { background: var(--gold) !important; color: var(--bg) !important; }.pix-btn.small, .pix-btn.small button { font-size: 9px !important; padding: 9px 10px !important; box-shadow: 3px 3px 0 var(--shadow) !important; }
/* ---------- photo uploader (gr.Image) ---------- */.uploader { border: none !important; }.uploader .image-container, .uploader .upload-container, .uploader [data-testid="image"] { min-height: 220px !important; background: var(--bg2) !important; border: var(--border) dashed var(--accent) !important; border-radius: 0 !important;}.uploader .image-container img { image-rendering: pixelated; object-fit: cover; }.uploader .wrap, .uploader .icon-wrap, .uploader .upload-text { color: var(--dim) !important; font-family: "Press Start 2P", monospace !important; font-size: 9px !important; }
/* ---------- theme picker (3 buttons styled as cards) ---------- */.theme-card, .theme-card button { font-family: "Press Start 2P", monospace !important; font-size: 9px !important; color: var(--ink) !important; cursor: pointer; height: 100%; display: flex !important; flex-direction: column; align-items: center; gap: 10px; padding: 18px 8px !important; background: var(--bg2) !important; border: var(--border) solid var(--dim) !important; box-shadow: 4px 4px 0 var(--shadow) !important; border-radius: 0 !important; white-space: pre-line; line-height: 1.6;}.theme-card:hover, .theme-card button:hover { border-color: var(--accent) !important; background: var(--bg2) !important; }.theme-card.selected, .theme-card.selected button { border-color: var(--gold) !important; background: var(--panel) !important; box-shadow: 4px 4px 0 var(--accent2) !important;}
/* ---------- compose textarea (gr.Textbox) ---------- */.compose textarea { width: 100%; resize: vertical; font-family: "Press Start 2P", monospace !important; font-size: 10px !important; line-height: 1.8 !important; color: var(--ink) !important; background: var(--bg2) !important; border: var(--border) solid var(--accent) !important; padding: 14px !important; box-shadow: inset 3px 3px 0 var(--shadow); border-radius: 0 !important;}.compose textarea:focus { outline: none; border-color: var(--gold) !important; box-shadow: inset 3px 3px 0 var(--shadow) !important; }.compose label, .compose span[data-testid] { display: none !important; }
/* ---------- adventure header ---------- */.adventure-header h2 { font-size: 14px; color: var(--gold); text-shadow: 2px 2px 0 var(--shadow); margin: 6px 0; }
/* ---------- quest cards ---------- */.quest-card { background: var(--panel) !important; border: var(--border) solid var(--ink) !important; box-shadow: 8px 8px 0 var(--shadow) !important; overflow: hidden; margin-bottom: 20px !important; border-radius: 0 !important; padding: 0 !important;}.quest-card.is-frog { border-color: var(--frog) !important; box-shadow: 8px 8px 0 var(--frog) !important; }.quest-card.is-bonus { border-style: dashed !important; }
.quest-art .image-container, .quest-art [data-testid="image"] { min-height: 200px !important; background: var(--bg2) !important; border-radius: 0 !important; border: none !important; border-right: var(--border) solid var(--ink) !important;}.quest-art img { image-rendering: pixelated; object-fit: cover; width: 100%; }
.quest-body { padding: 16px 18px; }.quest-badges { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 10px; }.badge { font-size: 8px; padding: 5px 7px; border: 2px solid currentColor; display: inline-block; }.frog-badge { color: var(--frog); }.bonus-badge { color: var(--accent); }.group-badge { color: var(--gold); }.quest-title { margin: 4px 0 10px; font-size: 12px; color: var(--ink); line-height: 1.6; }.quest-narrative { margin: 0 0 12px; font-size: 9px; color: var(--dim); line-height: 1.9; }.quest-task { margin: 0 0 14px; font-size: 9px; color: var(--accent); line-height: 1.8; }.quest-task::before { content: "▸ TASK: "; color: var(--dim); }.xp { font-size: 9px; color: var(--gold); }.xp::before { content: "★ "; }
@media (max-width: 620px) { .fq-logo { font-size: 16px; }}app.py+250-41
static/app.jsDeleted-232
static/index.htmlDeleted-102
static/storage.jsDeleted-82
static/style.cssDeleted-171
theme.cssAdded+169