Spaces:
Running
Running
Download index.html from vedalken/text2scryfall: direct link, hf CLI and curl.
- Browser
- Download file 21.6 kB
-
https://huggingface.co/spaces/vedalken/text2scryfall/resolve/main/index.html
- Command line
-
hf download hf://spaces/vedalken/text2scryfall/index.html
-
curl -L -o index.html https://huggingface.co/spaces/vedalken/text2scryfall/resolve/main/index.html
21.6 kB
| <html lang="en"> | |
| <head> | |
| <meta charset="utf-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1"> | |
| <title>text2scryfall</title> | |
| <style> | |
| :root { | |
| color-scheme: light; color: #212529; background: #fff; | |
| --accent: #e8590c; --muted: #6c757d; --line: #ced4da; --soft: #f1f3f5; | |
| --t0: #e8590c; --t1: #1971c2; --t2: #2f9e44; --t3: #9c36b5; --t4: #c2255c; --t5: #0c8599; | |
| --ease: cubic-bezier(0.16, 1, 0.3, 1); | |
| } | |
| ::selection { background: color-mix(in srgb, var(--accent) 25%, white); } | |
| body { font: 16px/1.5 system-ui, sans-serif; max-width: 46rem; margin: 2rem auto; padding: 0 1rem; } | |
| h1 { margin-bottom: 0.25rem; } | |
| p.lead { margin-top: 0; color: var(--muted); max-width: 65ch; } | |
| a { color: var(--accent); text-underline-offset: 0.15em; } | |
| label, .label { display: block; font-weight: 600; margin: 1.5rem 0 0.4rem; } | |
| :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } | |
| .sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); } | |
| /* Loading: three steps, each with its own state and time */ | |
| #loading { margin-top: 1.25rem; padding: 0.9rem 1rem; border: 1px solid var(--line); border-radius: 12px; } | |
| #loading.ready { padding: 0.5rem 1rem; } | |
| .steps { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.45rem; } | |
| .steps li { display: grid; grid-template-columns: 1.4rem 1fr auto; align-items: center; gap: 0.5rem; color: var(--muted); } | |
| .steps li.active, .steps li.done { color: inherit; } | |
| .steps .time { font-variant-numeric: tabular-nums; font-size: 0.9rem; color: var(--muted); } | |
| .dot { width: 0.9rem; height: 0.9rem; border-radius: 50%; border: 2px solid var(--line); box-sizing: border-box; display: grid; place-items: center; } | |
| .active .dot { border-color: var(--accent); animation: pulse 1.4s var(--ease) infinite; } | |
| .done .dot { border-color: var(--accent); background: var(--accent); } | |
| .dot svg { width: 0.6rem; height: 0.6rem; opacity: 0; } | |
| .done .dot svg { opacity: 1; } | |
| @keyframes pulse { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--accent) 45%, transparent); } 100% { box-shadow: 0 0 0 0.45rem transparent; } } | |
| progress { width: 100%; height: 0.4rem; margin-top: 0.7rem; accent-color: var(--accent); } | |
| #loading.ready .steps, #loading.ready progress { display: none; } | |
| #status { font-size: 0.9rem; color: var(--muted); margin-top: 0.35rem; } | |
| #loading.ready #status { margin: 0; } | |
| #loading.failed { border-color: #c92a2a; } | |
| #loading.failed #status { color: #c92a2a; } | |
| input { box-sizing: border-box; width: 100%; padding: 0.7rem 0.8rem; font: inherit; font-size: 1.05rem; | |
| border: 1px solid var(--muted); border-radius: 8px; caret-color: var(--accent); } | |
| .examples button { margin: 0.4rem 0.3rem 0 0; padding: 0.3rem 0.65rem; border: 1px solid var(--line); | |
| border-radius: 999px; background: none; color: inherit; cursor: pointer; font: inherit; font-size: 0.9rem; } | |
| .examples button:hover { border-color: var(--accent); } | |
| /* Query: state badge, streaming text, then term chips */ | |
| .row { display: flex; align-items: baseline; justify-content: space-between; gap: 1rem; } | |
| .row .label { margin-bottom: 0.4rem; } | |
| #qstate { font-size: 0.9rem; color: var(--muted); font-variant-numeric: tabular-nums; } | |
| #qstate.translating { color: var(--accent); } | |
| #qstate.translating::after { content: ""; display: inline-block; width: 1.2em; text-align: left; animation: dots 1.2s steps(4) infinite; } | |
| @keyframes dots { 0% { content: ""; } 25% { content: "."; } 50% { content: ".."; } 75% { content: "..."; } } | |
| #query { position: relative; display: flex; flex-wrap: wrap; align-items: center; gap: 0.35rem; min-height: 2.9rem; | |
| box-sizing: border-box; padding: 0.55rem 0.8rem; border: 1px solid var(--muted); border-radius: 8px; overflow: hidden; | |
| font-family: ui-monospace, monospace; font-size: 1.05rem; transition: opacity 0.3s var(--ease); } | |
| #query.stale { opacity: 0.45; } | |
| #query.translating::after { content: ""; position: absolute; left: 0; bottom: 0; height: 2px; width: 35%; | |
| background: var(--accent); animation: sweep 1.1s var(--ease) infinite; } | |
| @keyframes sweep { from { transform: translateX(-100%); } to { transform: translateX(290%); } } | |
| .caret { display: inline-block; width: 0.55em; height: 1.1em; background: var(--accent); vertical-align: text-bottom; animation: blink 1s steps(2) infinite; } | |
| @keyframes blink { 50% { opacity: 0; } } | |
| .placeholder { color: var(--muted); font-family: system-ui, sans-serif; font-size: 0.95rem; } | |
| .term { --c: var(--t0); padding: 0.1rem 0.45rem; border-radius: 6px; border: 1px solid color-mix(in srgb, var(--c) 55%, white); | |
| background: color-mix(in srgb, var(--c) 9%, white); cursor: default; animation: rise 0.35s var(--ease) both; } | |
| .term.on { background: color-mix(in srgb, var(--c) 24%, white); border-color: var(--c); } | |
| .op { color: var(--muted); animation: rise 0.35s var(--ease) both; } | |
| @keyframes rise { from { opacity: 0; transform: translateY(0.25rem); } } | |
| /* The request, with each matched word underlined in its term's colour */ | |
| #mapping { margin-top: 0.5rem; font-size: 0.95rem; color: var(--muted); } | |
| #mapping[hidden] { display: none; } | |
| #words { color: #212529; } | |
| .w[data-term] { text-decoration: underline 3px color-mix(in srgb, var(--c) 70%, white); | |
| text-underline-offset: 0.3em; border-radius: 3px; cursor: default; transition: background 0.15s; } | |
| .w.on { background: color-mix(in srgb, var(--c) 22%, white); } | |
| .c0 { --c: var(--t0); } .c1 { --c: var(--t1); } .c2 { --c: var(--t2); } .c3 { --c: var(--t3); } .c4 { --c: var(--t4); } .c5 { --c: var(--t5); } | |
| /* Cards */ | |
| #results { margin-top: 1.5rem; transition: opacity 0.3s var(--ease); } | |
| #results.stale { opacity: 0.45; } | |
| #results p { margin: 0 0 0.6rem; } | |
| .cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 0.6rem; } | |
| .cards a, .cards .skeleton { display: block; aspect-ratio: 488 / 680; border-radius: 4.75% / 3.5%; background: var(--soft); overflow: hidden; } | |
| .cards img { width: 100%; height: 100%; display: block; opacity: 0; transition: opacity 0.4s var(--ease); } | |
| .cards img.loaded { opacity: 1; } | |
| .skeleton { background: linear-gradient(100deg, var(--soft) 40%, #fff 50%, var(--soft) 60%) 0 0 / 300% 100%; animation: shimmer 1.4s linear infinite; } | |
| @keyframes shimmer { to { background-position: -150% 0; } } | |
| @media (prefers-reduced-motion: reduce) { | |
| *, *::before, *::after { animation-duration: 0.01ms ; animation-iteration-count: 1 ; transition-duration: 0.01ms ; } | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <h1>text2scryfall</h1> | |
| <p class="lead">Describe the Magic cards you want in English. A fine-tuned Qwen2.5-0.5B writes the | |
| <a href="https://scryfall.com/docs/syntax">Scryfall query</a> as you type, running entirely in your browser, | |
| and the matching cards appear below.</p> | |
| <section id="loading" aria-label="Model loading"> | |
| <ol class="steps"> | |
| <li data-step="download"><span class="dot"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="M2.5 6.2 5 8.6l4.6-5" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></span> | |
| <span>Download the model <span class="detail" id="dl-detail">(about 490 MB, cached after the first visit)</span></span><span class="time"></span></li> | |
| <li data-step="load"><span class="dot"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="M2.5 6.2 5 8.6l4.6-5" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></span> | |
| <span id="load-name">Load it onto your device</span><span class="time"></span></li> | |
| <li data-step="warmup"><span class="dot"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="M2.5 6.2 5 8.6l4.6-5" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></span> | |
| <span>Run a first translation</span><span class="time"></span></li> | |
| </ol> | |
| <progress id="bar" max="100" value="0"></progress> | |
| <div id="status" aria-live="polite">Starting…</div> | |
| </section> | |
| <label for="text">Request</label> | |
| <input id="text" placeholder="I want all myr that are pauper playable" maxlength="300" autocomplete="off" autofocus> | |
| <div class="examples" id="examples"></div> | |
| <div class="row"><span class="label" id="query-label">Scryfall query</span><span id="qstate"></span></div> | |
| <div id="query" role="group" aria-labelledby="query-label"><span class="placeholder">The query appears here as you type.</span></div> | |
| <div id="mapping" hidden>In your request: <span id="words"></span></div> | |
| <div id="announce" class="sr-only" aria-live="polite"></div> | |
| <div id="results" aria-live="polite"></div> | |
| <script type="module"> | |
| const EXAMPLES = [ | |
| "I want all myr that are pauper playable", | |
| "blue instants that counter spells, 2 or less", | |
| "every printing of lightning bolt", | |
| "goblins or elves for modern", | |
| "lands that produce exactly black and green", | |
| ]; | |
| const $ = (id) => document.getElementById(id); | |
| const el = (tag, props = {}) => Object.assign(document.createElement(tag), props); | |
| const secs = (ms) => `${(ms / 1000).toFixed(1)} s`; | |
| // A blob wrapper, because Cursor's browser won't start a worker from a URL on a cross-origin isolated page. | |
| const src = `import ${JSON.stringify(new URL("worker.js", location.href).href)};`; | |
| const worker = new Worker(URL.createObjectURL(new Blob([src], { type: "text/javascript" })), { type: "module" }); | |
| worker.onerror = (e) => fail(e.message || "see the browser console"); | |
| // ---- Loading steps ---- | |
| const t0 = performance.now(); | |
| let stage = null, stageStart = t0, deviceName = ""; | |
| function setStage(next) { | |
| const now = performance.now(); | |
| for (const li of document.querySelectorAll(".steps li")) { | |
| if (li.dataset.step === stage) { li.classList.replace("active", "done"); li.querySelector(".time").textContent = secs(now - stageStart); } | |
| if (li.dataset.step === next) li.classList.add("active"); | |
| } | |
| stage = next; | |
| stageStart = now; | |
| if (next === "load" || next === "warmup") $("bar").removeAttribute("value"); // indeterminate | |
| $("status").textContent = { | |
| download: "Downloading…", | |
| load: `Loading the model onto your ${deviceName}…`, | |
| warmup: "Running a first translation, which compiles the model for your device…", | |
| }[next] ?? ""; | |
| } | |
| function fail(message) { | |
| $("loading").classList.add("failed"); | |
| $("status").textContent = `Could not load the model: ${message}`; | |
| } | |
| // ---- Requests: the worker drops outdated ones; until the model is ready, only the newest text waits ---- | |
| let ready = false, pending = null, sent = 0; | |
| function request(text) { | |
| setQueryState(text ? (ready ? "translating" : "waiting") : "idle"); | |
| if (!ready) { pending = text; return; } | |
| worker.postMessage({ id: ++sent, text }); | |
| } | |
| function setQueryState(state, detail = "") { | |
| const q = $("query"); | |
| q.classList.toggle("translating", state === "translating"); | |
| q.classList.toggle("stale", state !== "done" && !!q.querySelector(".term")); // the chips are for older text | |
| $("results").classList.toggle("stale", state === "translating" || state === "waiting"); | |
| $("qstate").className = state === "translating" ? "translating" : ""; | |
| $("qstate").textContent = { translating: "Translating", waiting: "Waiting for the model…", done: detail, idle: "" }[state]; | |
| if (state === "idle") { q.replaceChildren(el("span", { className: "placeholder", textContent: "The query appears here as you type." })); $("mapping").hidden = true; } | |
| } | |
| const files = {}; | |
| worker.onmessage = ({ data }) => { | |
| if (data.type === "stage") { | |
| deviceName = data.device === "webgpu" ? "GPU (WebGPU)" : "CPU (WebAssembly)"; | |
| $("load-name").textContent = `Load it onto your ${deviceName}`; | |
| setStage(data.stage); | |
| } else if (data.type === "progress" && data.status === "initiate") { | |
| files[data.file] ??= { loaded: 0, total: 0, done: false }; | |
| } else if (data.type === "progress" && data.status === "progress") { | |
| files[data.file] = { ...files[data.file], loaded: data.loaded, total: data.total }; | |
| const all = Object.values(files); | |
| const loaded = all.reduce((s, f) => s + f.loaded, 0), total = all.reduce((s, f) => s + f.total, 0); | |
| $("bar").value = (100 * loaded) / total; | |
| $("dl-detail").textContent = `(${(loaded / 1e6).toFixed(0)} of ${(total / 1e6).toFixed(0)} MB)`; | |
| } else if (data.type === "progress" && data.status === "done") { | |
| if (files[data.file]) files[data.file].done = true; | |
| if (stage === "download" && Object.values(files).every((f) => f.done)) setStage("load"); | |
| } else if (data.type === "ready") { | |
| setStage(null); | |
| $("loading").classList.add("ready"); | |
| $("status").textContent = `Model ready on your ${deviceName}, loaded in ${secs(performance.now() - t0)}.`; | |
| ready = true; | |
| if (pending !== null) request(pending); | |
| } else if (data.type === "error") { | |
| fail(data.message); | |
| } else if (data.id !== sent) { | |
| // a result for text that has changed since | |
| } else if (data.type === "partial") { | |
| $("query").classList.remove("stale"); | |
| $("query").replaceChildren(el("span", { textContent: data.text }), el("span", { className: "caret" })); | |
| } else if (data.type === "query") { | |
| showQuery(data.query, $("text").value); | |
| setQueryState("done", `Translated in ${secs(data.ms)}`); | |
| $("announce").textContent = `Query: ${data.query}`; | |
| showCards(data.query); | |
| } | |
| }; | |
| // ---- Linking query terms to the words of the request ---- | |
| const COLORS = { w: "white", u: "blue", b: "black", r: "red", g: "green", c: "colorless", m: "multicolor" }; | |
| const RARITIES = { c: "common", u: "uncommon", r: "rare", m: "mythic" }; | |
| const KEY_WORDS = { | |
| f: ["legal", "playable", "format"], banned: ["banned"], restricted: ["restricted"], | |
| mv: ["mana", "cost", "value"], cmc: ["mana", "cost", "value"], m: ["mana", "cost"], | |
| usd: ["dollar", "price", "cheap", "cost"], eur: ["euro", "price"], tix: ["tix", "ticket"], | |
| pow: ["power"], power: ["power"], tou: ["toughness"], loy: ["loyalty"], | |
| r: ["rarity"], lang: ["language", "printed"], a: ["art", "artist", "drawn", "illustrated"], | |
| ft: ["flavor"], wm: ["watermark"], produces: ["produce", "produces", "mana", "tap"], | |
| unique: ["every", "each", "unique", "all"], order: ["sort", "sorted", "order", "by"], | |
| id: ["identity", "commander"], c: ["color", "colored", "colors"], | |
| }; | |
| const OPS = { "<=": ["less", "most", "under", "or", "fewer"], ">=": ["more", "least", "or", "greater"], | |
| "<": ["less", "under", "below", "fewer", "cheaper"], ">": ["more", "over", "above", "greater", "bigger"] }; | |
| const NEGATION = ["non", "not", "no", "without", "except", "isn't", "aren't"]; | |
| const VALUE_WORDS = { prints: ["print", "printing", "version", "edition"], art: ["art", "artwork"], cards: ["card"] }; | |
| // ponytail: keyword and prefix matching, so links are approximate (misses irregular plurals like elf/elves | |
| // and set codes like lea for Alpha). Upgrade path: have the model emit an alignment, or use its attention. | |
| function keywords(term) { | |
| const neg = term.startsWith("-"); | |
| const body = term.replace(/^-/, ""); | |
| const m = body.match(/^([a-z]+)(:|<=|>=|!=|=|<|>)(.*)$/i); | |
| const words = neg ? [...NEGATION] : []; | |
| if (!m) return [...words, ...body.replace(/^!/, "").toLowerCase().match(/[\p{L}\p{N}']+/gu) ?? []]; | |
| const [, key, op, raw] = m; | |
| const k = key.toLowerCase(), value = raw.replace(/^"|"$/g, "").toLowerCase(); | |
| words.push(...(KEY_WORDS[k] ?? []), ...(OPS[op] ?? [])); | |
| if (["c", "color", "id", "identity", "produces"].includes(k) && /^[wubrgcm]+$/.test(value)) words.push(...[...value].map((l) => COLORS[l])); | |
| else if (k === "r" || k === "rarity") words.push(RARITIES[value] ?? value); | |
| else if (k !== "e" && k !== "set") for (const v of value.match(/[\p{L}\p{N}']+/gu) ?? []) words.push(v, ...(VALUE_WORDS[v] ?? [])); | |
| if (["e", "set", "s"].includes(k)) words.push("set", "from", "printed"); | |
| if (k === "t" && value) words.push(value + "s", value + "es", value.replace(/fe?$/, "ves")); | |
| return words; | |
| } | |
| const STOP = new Set(["or", "and", "the", "a", "an", "of", "in", "that", "with", "for", "i", "want", "all", "are", "is", "to"]); | |
| function matches(word, key) { | |
| const w = word.toLowerCase(); | |
| if (w === key) return true; | |
| if (STOP.has(w) || key.length < 3) return false; | |
| return w.startsWith(key) || (key.length >= 5 && key.startsWith(w) && w.length >= 4) || (w.length >= 5 && key.length >= 5 && w.slice(0, 5) === key.slice(0, 5)); | |
| } | |
| function showQuery(query, text) { | |
| const tokens = query.match(/\(|\)|-?!?"[^"]*"|-?[^\s()"]+(?:"[^"]*")?/g) ?? []; | |
| const terms = [], parts = []; | |
| for (const tok of tokens) { | |
| if (tok === "(" || tok === ")" || /^or$/i.test(tok)) { parts.push(el("span", { className: "op", textContent: tok })); continue; } | |
| const i = terms.length; | |
| terms.push(keywords(tok)); | |
| const chip = el("span", { className: `term c${i % 6}`, textContent: tok, tabIndex: 0 }); | |
| chip.dataset.term = i; | |
| parts.push(chip); | |
| } | |
| parts.forEach((p, i) => (p.style.animationDelay = `${i * 40}ms`)); | |
| $("query").replaceChildren(...parts); | |
| // Each request word goes to the first term whose keywords it matches; "or" goes nowhere. | |
| const words = []; | |
| for (const [piece] of text.matchAll(/[\p{L}\p{N}$']+|[^\p{L}\p{N}$']+/gu)) { | |
| const span = el("span", { textContent: piece }); | |
| if (/[\p{L}\p{N}]/u.test(piece)) { | |
| span.className = "w"; | |
| const i = terms.findIndex((kw) => kw.some((k) => matches(piece, k))); | |
| if (i >= 0) { span.dataset.term = i; span.classList.add(`c${i % 6}`); } | |
| } | |
| words.push(span); | |
| } | |
| $("words").replaceChildren(...words); | |
| $("mapping").hidden = !terms.length; | |
| } | |
| function highlight(term) { | |
| for (const n of document.querySelectorAll("#query .term, #words .w")) n.classList.toggle("on", term !== undefined && n.dataset.term === term); | |
| } | |
| for (const id of ["query", "words"]) { | |
| $(id).addEventListener("pointerover", (e) => highlight(e.target.dataset?.term)); | |
| $(id).addEventListener("pointerleave", () => highlight()); | |
| $(id).addEventListener("focusin", (e) => highlight(e.target.dataset?.term)); | |
| $(id).addEventListener("focusout", () => highlight()); | |
| } | |
| // ---- Cards ---- | |
| const SHOWN = 24; | |
| let search = new AbortController(); | |
| async function showCards(q) { | |
| search.abort(); | |
| search = new AbortController(); | |
| const results = $("results"); | |
| results.classList.remove("stale"); | |
| if (!q || q.startsWith("(error")) { results.replaceChildren(); return; } | |
| const grid = el("div", { className: "cards" }); | |
| grid.append(...Array.from({ length: 8 }, () => el("div", { className: "skeleton" }))); | |
| results.replaceChildren(el("p", { textContent: "Searching Scryfall…" }), grid); | |
| const link = `https://scryfall.com/search?q=${encodeURIComponent(q)}`; | |
| try { | |
| const res = await fetch(`https://api.scryfall.com/cards/search?q=${encodeURIComponent(q)}`, { signal: search.signal }); | |
| const body = await res.json(); | |
| const p = el("p"); | |
| if (res.status === 404) p.textContent = "No cards match. "; | |
| else if (!res.ok) p.textContent = `Scryfall: ${body.details} `; | |
| else { | |
| p.textContent = `${body.total_cards} card${body.total_cards === 1 ? "" : "s"}${body.total_cards > SHOWN ? `, showing the first ${SHOWN}` : ""}. `; | |
| if (body.warnings) p.textContent += `Scryfall ignored part of the query: ${body.warnings.join(" ")} `; | |
| } | |
| p.append(el("a", { href: link, textContent: "Open on Scryfall", target: "_blank" })); | |
| grid.replaceChildren(); | |
| for (const card of res.ok ? body.data.slice(0, SHOWN) : []) { | |
| const src = card.image_uris?.normal ?? card.card_faces?.[0]?.image_uris?.normal; | |
| const img = el("img", { alt: card.name, title: card.name, loading: "lazy", crossOrigin: "anonymous" }); | |
| img.onload = () => img.classList.add("loaded"); | |
| if (src) img.src = src; // the page is cross-origin isolated, so images need CORS | |
| const a = el("a", { href: card.scryfall_uri, target: "_blank" }); | |
| a.append(img); | |
| grid.append(a); | |
| } | |
| results.replaceChildren(p, grid); | |
| } catch (e) { | |
| if (e.name !== "AbortError") results.textContent = `Could not reach Scryfall: ${e.message}`; | |
| } | |
| } | |
| $("text").addEventListener("input", (e) => { | |
| const text = e.target.value.trim(); | |
| request(text); | |
| if (!text) showCards(""); | |
| }); | |
| for (const ex of EXAMPLES) { | |
| const b = el("button", { type: "button", textContent: ex }); | |
| b.onclick = () => { $("text").value = ex; $("text").dispatchEvent(new Event("input")); $("text").focus(); }; | |
| $("examples").append(b); | |
| } | |
| </script> | |
| </body> | |
| </html> | |