tinytowns playground: the model runs in your browser
Browse filesFiles changed (11)
- README.md+21-4
- fonts/OFL-atkinson.txtAdded+93
- fonts/OFL-jersey.txtAdded+93
- fonts/OFL-pixelify.txtAdded+93
- fonts/atkinson.woff2Added
- fonts/jersey.woff2Added
- fonts/pixelify.woff2Added
- index.html+59-17
- logo.pngAdded
- playground.jsAdded+258
- style.css+83-23
12345678910---title: Tinytownsemoji: 🦀colorFrom: indigocolorTo: purplesdk: staticpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627---title: tinytownsemoji: 🏘️colorFrom: indigocolorTo: yellowsdk: staticpinned: falselicense: mitmodels:- dave8172/tinytownsshort_description: A tiny GPT that invents town names, in your browsertags:- name-generator- procedural-generation- character-level- from-scratch---# tinytownsA tiny letter-level GPT that makes up new town names in the style of real ones. The model runs inyour browser: this page downloads the weights from[dave8172/tinytowns](https://huggingface.co/dave8172/tinytowns) and does every calculation on yourdevice.Code and build steps: [github.com/dave8172/tinytowns](https://github.com/dave8172/tinytowns).In your own code: `npm install @dave8172/tinytowns`.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293Copyright 2020-2024 The Atkinson Hyperlegible Next Project Authors (https://github.com/googlefonts/atkinson-hyperlegible-next)
This Font Software is licensed under the SIL Open Font License, Version 1.1.This license is copied below, and is also available with a FAQ at:https://openfontlicense.org
-----------------------------------------------------------SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007-----------------------------------------------------------
PREAMBLEThe goals of the Open Font License (OFL) are to stimulate worldwidedevelopment of collaborative font projects, to support the font creationefforts of academic and linguistic communities, and to provide a free andopen framework in which fonts may be shared and improved in partnershipwith others.
The OFL allows the licensed fonts to be used, studied, modified andredistributed freely as long as they are not sold by themselves. Thefonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reservednames are not used by derivative works. The fonts and derivatives,however, cannot be released under any other type of license. Therequirement for fonts to remain under this license does not applyto any document created using the fonts or their derivatives.
DEFINITIONS"Font Software" refers to the set of files released by the CopyrightHolder(s) under this license and clearly marked as such. This mayinclude source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after thecopyright statement(s).
"Original Version" refers to the collection of Font Software components asdistributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,or substituting -- in part or in whole -- any of the components of theOriginal Version, by changing formats or by porting the Font Software to anew environment.
"Author" refers to any designer, engineer, programmer, technicalwriter or other person who contributed to the Font Software.
PERMISSION & CONDITIONSPermission is hereby granted, free of charge, to any person obtaininga copy of the Font Software, to use, study, copy, merge, embed, modify,redistribute, and sell modified and unmodified copies of the FontSoftware, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,redistributed and/or sold with any software, provided that each copycontains the above copyright notice and this license. These can beincluded either as stand-alone text files, human-readable headers orin the appropriate machine-readable metadata fields within text orbinary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved FontName(s) unless explicit written permission is granted by the correspondingCopyright Holder. This restriction only applies to the primary font name aspresented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the FontSoftware shall not be used to promote, endorse or advertise anyModified Version, except to acknowledge the contribution(s) of theCopyright Holder(s) and the Author(s) or with their explicit writtenpermission.
5) The Font Software, modified or unmodified, in part or in whole,must be distributed entirely under this license, and must not bedistributed under any other license. The requirement for fonts toremain under this license does not apply to any document createdusing the Font Software.
TERMINATIONThis license becomes null and void if any of the above conditions arenot met.
DISCLAIMERTHE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENTOF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THECOPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIALDAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISINGFROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROMOTHER DEALINGS IN THE FONT SOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293Copyright 2023 The Soft Type Project Authors (https://github.com/scfried/soft-type-jersey)
This Font Software is licensed under the SIL Open Font License, Version 1.1.This license is copied below, and is also available with a FAQ at:https://openfontlicense.org
-----------------------------------------------------------SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007-----------------------------------------------------------
PREAMBLEThe goals of the Open Font License (OFL) are to stimulate worldwidedevelopment of collaborative font projects, to support the font creationefforts of academic and linguistic communities, and to provide a free andopen framework in which fonts may be shared and improved in partnershipwith others.
The OFL allows the licensed fonts to be used, studied, modified andredistributed freely as long as they are not sold by themselves. Thefonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reservednames are not used by derivative works. The fonts and derivatives,however, cannot be released under any other type of license. Therequirement for fonts to remain under this license does not applyto any document created using the fonts or their derivatives.
DEFINITIONS"Font Software" refers to the set of files released by the CopyrightHolder(s) under this license and clearly marked as such. This mayinclude source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after thecopyright statement(s).
"Original Version" refers to the collection of Font Software components asdistributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,or substituting -- in part or in whole -- any of the components of theOriginal Version, by changing formats or by porting the Font Software to anew environment.
"Author" refers to any designer, engineer, programmer, technicalwriter or other person who contributed to the Font Software.
PERMISSION & CONDITIONSPermission is hereby granted, free of charge, to any person obtaininga copy of the Font Software, to use, study, copy, merge, embed, modify,redistribute, and sell modified and unmodified copies of the FontSoftware, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,redistributed and/or sold with any software, provided that each copycontains the above copyright notice and this license. These can beincluded either as stand-alone text files, human-readable headers orin the appropriate machine-readable metadata fields within text orbinary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved FontName(s) unless explicit written permission is granted by the correspondingCopyright Holder. This restriction only applies to the primary font name aspresented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the FontSoftware shall not be used to promote, endorse or advertise anyModified Version, except to acknowledge the contribution(s) of theCopyright Holder(s) and the Author(s) or with their explicit writtenpermission.
5) The Font Software, modified or unmodified, in part or in whole,must be distributed entirely under this license, and must not bedistributed under any other license. The requirement for fonts toremain under this license does not apply to any document createdusing the Font Software.
TERMINATIONThis license becomes null and void if any of the above conditions arenot met.
DISCLAIMERTHE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENTOF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THECOPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIALDAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISINGFROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROMOTHER DEALINGS IN THE FONT SOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293Copyright 2021 The Pixelify Sans Project Authors (https://github.com/eifetx/Pixelify-Sans)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.12345678910111213141516171819<!doctype html><html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width" /><title>My static Space</title><link rel="stylesheet" href="style.css" /></head><body><div class="card"><h1>Welcome to your static Space!</h1><p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p><p>Also don't forget to check the<a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.</p></div></body></html>12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>tinytowns: a tiny GPT that invents town names</title><meta name="description" content="A tiny letter-level GPT that makes up new town names in the style of real ones. It runs in your browser, with no server and no API key."><link rel="icon" href="logo.png"><link rel="stylesheet" href="style.css"></head><body><main class="prose"><div class="head"><img src="logo.png" alt="" width="56" height="56"><h1>tinytowns</h1></div><p class="lead">A tiny GPT that makes up new town names in the style of real ones. It runs in your browser, with no server and no API key.</p><p>It learned the letter patterns of 128,435 real place names. It does not know which places exist, so most names it writes are new.</p><figure class="widget" data-widget="tinytowns"><figcaption>Type some letters. The bars show the model's guesses for the next letter.</figcaption><script type="application/json">{"start": "tinytowns-small","real": "A place with this name exists. It is in the list of 142,706 real places that the model learned from.","invented": "No place in the list of 142,706 real places has this name. Somebody should start one.","cities": "https://cdn.jsdelivr.net/gh/dave8172/tinytowns@c949422580a494ebd823823d2a95a4b09b328c29/data/cities.txt","models": [{ "id": "tinytowns-nano", "label": "nano", "short": "4.5K numbers", "file": "20 KB" },{ "id": "tinytowns-small", "label": "small", "short": "105K numbers", "file": "424 KB" },{ "id": "tinytowns", "label": "tinytowns", "short": "1M numbers", "file": "4 MB" }]}</script><div class="widget-tables"><p>The playground needs JavaScript.</p></div></figure><h2>Use it in your code</h2><p>For a game, a map maker or a story tool. One file, no dependencies, in a browser or Node 18+.</p><pre>npm install @dave8172/tinytowns</pre><pre>import TinyTowns from "@dave8172/tinytowns";const model = await TinyTowns.load(TinyTowns.url("tinytowns-small"));model.sample(); // a new namemodel.sample("port", { temperature: 0.8 }); // one that starts with "port"</pre><p>Sizes, temperature, repeatable names and offline use: <a href="https://github.com/dave8172/tinytowns#use-it-in-javascript">the guide on GitHub</a>.</p><h2>How small is it?</h2><p>The three sizes have 4,572, 105,052 and about 1 million numbers. A chat model has billions. Every one of them can be read: the code and each build step are public.</p><ul class="links"><li><a href="https://github.com/dave8172/tinytowns">Code and build steps</a></li><li><a href="https://huggingface.co/dave8172/tinytowns">Model weights</a></li><li><a href="https://quirkyagents.com/wizard/projects/small-model-vs-llm-benchmark/">Benchmark against small open language models</a></li></ul><p class="small">Place names: <a href="https://www.geonames.org/">GeoNames</a>, CC BY 4.0. Fonts: Pixelify Sans, Jersey 10 and Atkinson Hyperlegible Next, SIL Open Font License (in <code>fonts/</code>). Made by <a href="https://quirkyagents.com/wizard/">dave8172</a>.</p></main><script src="https://cdn.jsdelivr.net/npm/@dave8172/tinytowns@1.0.0/tinytowns.js" integrity="sha384-Kwuf40e8HOd0goSgOEMwjycn9zmWx3XXzy3kl1x4/G4QloWGXSJ0/Y1XNCngRqsW" crossorigin="anonymous"></script><script src="playground.js"></script></body></html>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258// The tinytowns playground. Type letters, see the model's five likeliest next symbols, tap one to add it, or let// the model finish the name; ending a name checks it against the real list. The model runs in the visitor's browser// (tinytowns.js); the weights come from Hugging Face, the list from the model's GitHub repo through jsDelivr.// The same playground runs at quirkyagents.com/wizard/projects/tinytowns/.(() => { "use strict"; const el = (tag, cls, text) => Object.assign(document.createElement(tag), cls ? { className: cls } : {}, text != null ? { textContent: text } : {}); const pct = (p) => p >= 0.995 ? "99%+" : p < 0.005 ? "<1%" : `${Math.round(p * 100)}%`; const MAX = 20; // the model's context: one '.' plus at most 20 letters
// Weights, kept on the device. Hugging Face's file list (1.3 KB) gives each weights file's SHA-256. A file is // downloaded only when that fingerprint is new to this device, checked against the bytes, and saved in the // browser's Cache Storage under it, replacing the older copy. Editing only the model card changes no fingerprint, // so nothing is downloaded again. If Hugging Face can't be reached (offline, or down), the saved copy is used. // (Hugging Face's own links can't be cached by the browser: each download is a new one-time signed address.) const STORE = "tinytowns-weights"; const TREE = "https://huggingface.co/api/models/dave8172/tinytowns/tree/main"; let fingerprints = null; // one look at the file list per page const keyFor = (file, sha) => new URL(`/tinytowns-weights/${file}/${sha}`, location.origin).href; const hex = (buf) => Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, "0")).join("");
async function weights(id) { const file = `${id}.safetensors`, mine = (r) => r.url.includes(`/tinytowns-weights/${file}/`); let store = null; try { store = await caches.open(STORE); } catch { /* no Cache Storage (some private windows): download every visit */ } fingerprints ??= fetch(TREE, { cache: "no-store", signal: AbortSignal.timeout(5000) }) .then((r) => r.ok ? r.json() : Promise.reject(new Error(r.status))) .then((list) => Object.fromEntries(list.filter((f) => f.lfs).map((f) => [f.path, f.lfs.oid]))) .catch(() => null); const sha = (await fingerprints)?.[file]; if (!sha) { // can't ask Hugging Face: use the copy on this device, if there is one const saved = store && (await store.keys()).find(mine); if (saved) return (await store.match(saved)).arrayBuffer(); throw Object.assign(new Error("offline, not saved"), { offline: true }); } const hit = store && await store.match(keyFor(file, sha)); if (hit) return hit.arrayBuffer(); const res = await fetch(TinyTowns.url(id)); if (!res.ok) throw new Error(`HTTP ${res.status}`); const buffer = await res.arrayBuffer(); if (hex(await crypto.subtle.digest("SHA-256", buffer)) !== sha) { fingerprints = null; // the file changed while we looked: ask again next time throw new Error("download does not match Hugging Face's fingerprint"); } if (store) { for (const old of (await store.keys()).filter(mine)) await store.delete(old); await store.put(keyFor(file, sha), new Response(buffer)).catch(() => {}); // storage full: works, just not saved } return buffer; }
const start = () => { if (!self.TinyTowns) return; // tinytowns.js loads first for (const fig of document.querySelectorAll("figure.widget[data-widget='tinytowns']:not([data-ready])")) mount(fig); };
function mount(fig) { fig.dataset.ready = ""; const d = JSON.parse(fig.querySelector("script[type='application/json']").textContent); const A = TinyTowns.ALPHABET; const ui = el("div", "tt"); const cache = new Map(); // size id -> model promise, so switching back in this visit costs nothing let size = d.start, model = null, temperature = 1, text = "", ended = false, run = 0, cities = null;
// --- model chips ----------------------------------------------------------------------------- const chips = el("div", "tt-models"); chips.setAttribute("role", "group"); chips.setAttribute("aria-label", "Model"); const chipFor = new Map(d.models.map((m) => { const b = el("button", "tt-model"); b.type = "button"; b.append(el("strong", null, m.label), el("small", null, m.short)); b.addEventListener("click", () => use(m.id)); chips.append(b); return [m.id, b]; }));
// --- temperature ------------------------------------------------------------------------------- const temp = el("label", "tt-temp"); const tempOut = el("output", "tt-temp-v", "1.0"); const slider = Object.assign(document.createElement("input"), { type: "range", min: "0.1", max: "2", step: "0.1", value: "1" }); slider.setAttribute("aria-label", "Temperature"); slider.addEventListener("input", () => { temperature = Number(slider.value); tempOut.textContent = temperature.toFixed(1); draw(); }); temp.append(el("span", "tt-temp-k", "Temperature"), tempOut, el("span", "tt-temp-end safe", "safe"), slider, el("span", "tt-temp-end wild", "wild"));
// --- the type bar ------------------------------------------------------------------------------ const bar = el("div", "tt-bar"); const input = Object.assign(document.createElement("input"), { type: "text", placeholder: "type a town…", autocomplete: "off", autocapitalize: "none", spellcheck: false, enterKeyHint: "done", }); input.setAttribute("aria-label", "Letters so far. Type a full stop to end the name."); input.maxLength = MAX + 1; const clear = el("button", "tt-clear", "×"); clear.type = "button"; clear.setAttribute("aria-label", "Clear"); clear.addEventListener("click", () => { set(""); input.focus(); }); bar.append(input, clear);
// Only a-z and space are letters tinytowns knows (its data turned hyphens into spaces and dropped accents and // apostrophes, so the same happens here); a full stop (or Enter) ends the name. input.addEventListener("input", () => { const raw = input.value.toLowerCase(); const stop = raw.includes("."); set(raw.split(".")[0].normalize("NFD").replace(/-/g, " ").replace(/[^a-z ]/g, "").replace(/^ +/, "").replace(/ {2,}/g, " ").slice(0, MAX), stop); }); input.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); finishTyped(); } });
// --- the five bars ----------------------------------------------------------------------------- const hint = el("p", "tt-hint"); const list = el("ol", "tt-next"); const rows = Array.from({ length: 5 }, () => { const li = el("li"), b = el("button", "tt-opt"), sym = el("span", "tt-sym"), track = el("span", "tt-track"), fill = el("span"), num = el("span", "tt-p"); b.type = "button"; track.append(fill); b.append(sym, track, num); li.append(b); list.append(li); return { b, sym, fill, num }; });
// --- finish it, and the verdict ---------------------------------------------------------------- const actions = el("div", "tt-actions"); const finish = el("button", "tt-finish", "Finish it for me"); finish.type = "button"; finish.addEventListener("click", () => autoFinish()); actions.append(finish); const verdict = el("div", "tt-verdict"); verdict.setAttribute("aria-live", "polite"); const status = el("p", "tt-status"); status.setAttribute("aria-live", "polite");
// the two symbols that are not letters, explained once, under the bars const legend = el("dl", "tt-legend"); legend.append(el("dt", null, "end of name"), el("dd", null, "The name is complete. To end a name, tap this bar, type a full stop (.), or press Enter."), el("dt", null, "space"), el("dd", null, "A gap between two words, as in “san jose”."));
ui.append(chips, temp, bar, hint, list, legend, actions, verdict, status); fig.querySelector(".widget-tables").hidden = true; fig.append(ui);
function set(t, stop = false) { run++; // a newer action cancels an older "finish it" mid-way text = t; ended = false; if (input.value !== t) input.value = t; verdict.replaceChildren(); if (stop) finishTyped(); else draw(); }
function draw() { for (const [id, b] of chipFor) b.setAttribute("aria-pressed", String(id === size)); finish.disabled = !model || ended; if (!model) { list.hidden = legend.hidden = true; hint.textContent = ""; return; } list.hidden = legend.hidden = ended; if (ended) { hint.textContent = ""; return; } if (text.length >= MAX) { hint.textContent = "That's 20 letters, the most it can read. Tap end of name."; } else hint.textContent = text ? `After “${text}”, the model would pick…` : "To start a name, the model would pick…"; const p = model.next(text, temperature); const top = p.map((v, i) => [v, i]).filter(([, i]) => text.length < MAX || i === 0) .filter(([, i]) => i !== 1 || (text && !text.endsWith(" "))) // never a space first or twice .sort((a, b) => b[0] - a[0]).slice(0, 5); rows.forEach((r, k) => { const item = top[k]; r.b.parentElement.hidden = !item; if (!item) return; const [v, i] = item; const label = i === 0 ? "end of name" : i === 1 ? "space" : A[i]; r.sym.textContent = label; r.sym.className = `tt-sym${i < 2 ? " word" : ""}`; r.fill.style.width = `${Math.max(v * 100, 0.5)}%`; r.num.textContent = pct(v); r.b.setAttribute("aria-label", `${label}, ${pct(v)}`); r.b.onclick = () => { if (i === 0) finishTyped(); else set(text + A[i]); }; }); }
// The model writes the rest, one letter at a time, at the chosen temperature. async function autoFinish() { if (!model || ended) return; const mine = ++run; finish.disabled = true; while (text.length < MAX) { const p = model.next(text, temperature); let r = Math.random(), i = 0; while (i < p.length - 1 && r >= p[i]) r -= p[i++]; if (text === "" || text.endsWith(" ")) while (i === 0 || i === 1) { // a name can't start or end on a space r = Math.random(); i = 0; while (i < p.length - 1 && r >= p[i]) r -= p[i++]; } if (i === 0) break; text += A[i]; input.value = text; draw(); await new Promise((ok) => setTimeout(ok, matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : 110)); if (mine !== run) return; } text = text.trim(); input.value = text; finishTyped(mine); }
// The name is done: real (in the list of 142,706 places) or invented. async function finishTyped(mine = ++run) { text = text.trim(); if (!text) { draw(); return; } ended = true; input.value = text; draw(); verdict.replaceChildren(el("p", "tt-checking", "Checking the map…")); const places = await loadCities().catch(() => null); if (mine !== run) return; if (!places) { verdict.replaceChildren(el("p", "tt-checking", "Couldn't load the list of real places. Try again in a moment.")); return; } const real = places.has(text); const badge = el("p", `tt-badge ${real ? "real" : "invented"}`, real ? "Real" : "Invented"); const name = el("p", "tt-name", text); const line = el("p", "tt-line", real ? d.real : d.invented); const again = el("button", "tt-again", "Another one"); again.type = "button"; again.addEventListener("click", () => { set(""); autoFinish(); }); verdict.replaceChildren(badge, name, line, again); }
function loadCities() { cities ??= fetch(d.cities).then((r) => { if (!r.ok) throw new Error(r.status); return r.text(); }).then((t) => new Set(t.split("\n").map((s) => s.trim()).filter(Boolean))) .catch((e) => { cities = null; throw e; }); return cities; }
async function use(id) { size = id; const m = d.models.find((x) => x.id === id); model = null; draw(); status.textContent = `Summoning ${m.label} (${m.file})…`; if (!cache.has(id)) cache.set(id, weights(id).then((buffer) => TinyTowns.load(buffer)).catch((e) => { cache.delete(id); throw e; })); try { const loaded = await cache.get(id); if (size !== id) return; model = loaded; status.textContent = ""; draw(); } catch (e) { if (size === id) status.textContent = e.offline ? `You're offline, and ${m.label} isn't saved on this device yet. Try again when you're online.` : `Couldn't fetch ${m.label} from Hugging Face. Tap it to try again.`; } }
use(size); // fetch the list while the visitor types, so the first verdict is quick const idle = self.requestIdleCallback ? (f) => requestIdleCallback(f, { timeout: 4000 }) : (f) => setTimeout(f, 2000); idle(() => loadCities().catch(() => {})); }
start();})();12345678910111213141516171819202122232425262728body {padding: 2rem;font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;}h1 {font-size: 16px;margin-top: 0;}p {color: rgb(107, 114, 128);font-size: 15px;margin-bottom: 10px;margin-top: 5px;}.card {max-width: 620px;margin: 0 auto;padding: 16px;border: 1px solid lightgray;border-radius: 16px;}.card p:last-child {margin-bottom: 0;}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788/* tinytowns on Hugging Face: the page, then the playground's own rules (the same as on quirkyagents.com). */@font-face { font-family: "Pixelify"; src: url("fonts/pixelify.woff2") format("woff2"); font-weight: 400 700; font-display: swap; }/* Pixelify's digits and B, C, Z read as other characters, so they come from Jersey 10, sized to Pixelify's cap height. */@font-face { font-family: "Pixelify"; src: url("fonts/jersey.woff2") format("woff2"); font-weight: 400 700; unicode-range: U+0030-0039, U+0042-0043, U+005A; size-adjust: 118.5%; font-display: swap; }@font-face { font-family: "Atkinson"; src: url("fonts/atkinson.woff2") format("woff2"); font-weight: 200 800; font-display: swap; }:root { color-scheme: light dark; --ink: #231c26; --muted: #6b6258; --line: #e6dccb; --bg: #fbf6ec; --card: #fffdf8;--accent: #3b3a8c; --gold: #d9a441; --tint: #eeedf8; --on-ink: #d8d6f4;--pixel: Pixelify, system-ui, sans-serif; --sans: Atkinson, system-ui, sans-serif; --mono: ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace; }@media (prefers-color-scheme: dark) {:root { --ink: #ece6d8; --muted: #a9a2b6; --line: #34304d; --bg: #13121d; --card: #1c1a2b;--accent: #a5a3f2; --gold: #e2b65a; --tint: #26244a; --on-ink: #4a4566; }}* { box-sizing: border-box; }html { background: var(--bg); overflow-x: clip; }body { margin: 0; background: var(--bg); color: var(--ink); font: 18px/1.6 var(--sans); }a { color: var(--accent); text-underline-offset: 3px; }:focus-visible { outline: 3px solid var(--gold); outline-offset: 2px; }main { max-width: 40rem; margin: 0 auto; padding: 1.5rem 16px 3rem; }.head { display: flex; align-items: center; gap: .8rem; }.head img { width: 56px; height: 56px; image-rendering: pixelated; }h1 { font: 700 2.4rem/1 var(--pixel); margin: 0; }h2 { font: 700 1.5rem/1.2 var(--pixel); margin: 2.2rem 0 .6rem; }.lead { font-size: 1.1rem; margin: 1rem 0 0; }p { margin: .7rem 0; }pre { background: var(--card); border: 2px solid var(--line); padding: .7rem .85rem; overflow-x: auto; font: .88rem/1.5 var(--mono); }code { font-family: var(--mono); font-size: .9em; }.links { display: flex; flex-wrap: wrap; gap: .4rem 1.2rem; padding: 0; list-style: none; }.small { font-size: .9rem; color: var(--muted); }figure.widget { margin: 1.6rem 0 1.8rem; padding: 1rem 1.1rem 1.1rem; border: 2px solid var(--ink); background: var(--card); box-shadow: 5px 5px 0 var(--gold); }figure.widget > figcaption { font: 500 1rem/1.45 var(--sans); color: var(--ink); margin: 0 0 .8rem; }button { font-family: inherit; }/* the tinytowns playground: pick a model, type, tap a letter, end the name */.tt { display: grid; grid-template-columns: minmax(0, 1fr); gap: .85rem; }.tt-models { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .45rem; }.tt-model { display: grid; gap: .2rem; justify-items: center; padding: .55rem .3rem; cursor: pointer; color: var(--ink); background: var(--bg); border: 2px solid var(--line); }.tt-model strong { font: 600 .95rem/1.1 Atkinson, system-ui, sans-serif; }.tt-model small { font: 500 .8rem/1 Atkinson, system-ui, sans-serif; color: var(--muted); }.tt-model[aria-pressed="true"] { border-color: var(--ink); background: var(--ink); color: var(--bg); }.tt-model[aria-pressed="true"] small { color: var(--on-ink); }.tt-temp { display: grid; grid-template-columns: auto 1fr auto; grid-template-areas: "k k v" "a s b"; align-items: center; gap: .3rem .6rem; font: 600 .9rem/1 Atkinson, system-ui, sans-serif; }.tt-temp-k { grid-area: k; }.tt-temp-v { grid-area: v; color: var(--accent); text-align: right; }.tt-temp-end { font: 500 .82rem/1 Atkinson, system-ui, sans-serif; color: var(--muted); }.tt-temp-end.safe { grid-area: a; }.tt-temp-end.wild { grid-area: b; }.tt-temp input { grid-area: s; width: 100%; accent-color: var(--accent); min-height: 32px; margin: 0; }.tt-bar { display: flex; border: 2px solid var(--ink); background: var(--bg); box-shadow: 4px 4px 0 var(--gold); }.tt-bar input { flex: 1; min-width: 0; border: 0; background: transparent; color: var(--ink); padding: .6rem .75rem; font: 600 1.55rem/1.2 var(--pixel); letter-spacing: .04em; }.tt-bar input::placeholder { color: var(--muted); opacity: .6; font-weight: 400; }.tt-bar input:focus { outline: none; }.tt-bar:focus-within { outline: 3px solid var(--gold); outline-offset: 2px; }.tt-clear { border: 0; background: transparent; color: var(--muted); font: 600 1.5rem/1 var(--pixel); padding: 0 .8rem; cursor: pointer; }.tt-hint { font-size: .95rem; color: var(--muted); margin: 0; min-height: 1.5em; }.prose .tt-next { list-style: none; margin: 0; padding: 0; display: grid; gap: .35rem; }.prose .tt-next li { margin: 0; }.tt-opt { width: 100%; display: grid; grid-template-columns: 5.6rem minmax(0, 1fr) 3rem; align-items: center; gap: .6rem; padding: .35rem .5rem; cursor: pointer;color: var(--ink); background: var(--bg); border: 2px solid var(--line); text-align: left; -webkit-tap-highlight-color: transparent; }.tt-opt:hover { border-color: var(--ink); }.tt-opt:active { transform: translate(1px, 1px); }.tt-sym { font: 700 1.3rem/1 var(--mono); }.tt-sym.word { font: 700 .95rem/1.15 Atkinson, system-ui, sans-serif; color: var(--accent); }.tt-track { height: .9rem; background: var(--tint); }.tt-track span { display: block; height: 100%; background: var(--accent); transition: width .15s; }.tt-p { font: 500 .85rem/1 Atkinson, system-ui, sans-serif; text-align: right; }.tt-actions { display: flex; flex-wrap: wrap; gap: .6rem; }.tt-finish, .tt-again { font: 600 .95rem/1 Atkinson, system-ui, sans-serif; color: var(--bg); background: var(--ink); border: 2px solid var(--ink); padding: .7rem 1rem; box-shadow: 3px 3px 0 var(--gold); cursor: pointer; }.tt-finish:active, .tt-again:active { transform: translate(2px, 2px); box-shadow: 1px 1px 0 var(--gold); }.tt-finish:disabled { opacity: .45; cursor: default; }.tt-verdict:empty { display: none; }.tt-verdict { display: grid; justify-items: start; gap: .35rem; padding: .9rem 1rem; border: 2px solid var(--ink); background: var(--bg); }.tt-verdict p { margin: 0; }.tt-badge { font: 700 .85rem/1 Atkinson, system-ui, sans-serif; text-transform: uppercase; letter-spacing: .1em; padding: .4rem .6rem; }.tt-badge.real { background: var(--gold); color: var(--ink); }.tt-badge.invented { background: var(--accent); color: var(--bg); }.tt-name { font: 700 clamp(1.5rem, 7vw, 2rem)/1.15 var(--pixel); overflow-wrap: anywhere; text-transform: capitalize; }.tt-line, .tt-checking { font-size: .98rem; color: var(--muted); }.tt-again { margin-top: .35rem; }.tt-status { font-size: .9rem; color: var(--muted); margin: 0; }.tt-legend { display: grid; grid-template-columns: auto 1fr; gap: .25rem .7rem; margin: 0; padding: .6rem .75rem; background: var(--tint); font-size: .92rem; line-height: 1.4; }.tt-legend[hidden], .prose .tt-next[hidden] { display: none; }.tt-legend dt { font-weight: 700; color: var(--accent); white-space: nowrap; }.tt-legend dd { margin: 0; }.tt-status:empty { display: none; }@media (prefers-reduced-motion: reduce) { .tt-track span { transition: none; } }
README.md+21-4
fonts/OFL-atkinson.txtAdded+93
fonts/OFL-jersey.txtAdded+93
fonts/OFL-pixelify.txtAdded+93
fonts/atkinson.woff2Added
fonts/jersey.woff2Added
fonts/pixelify.woff2Added
index.html+59-17
logo.pngAdded

playground.jsAdded+258
style.css+83-23