Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

sign language: numbers, LLM transcription cleanup, decode confidence

nirholas249ed125ca39
diff --git a/api/asl-recognition.js b/api/asl-recognition.js
index db4bb733e..f51953c4e 100644
--- a/api/asl-recognition.js
+++ b/api/asl-recognition.js
@@ -81,5 +81,40 @@ export default wrap(async (req, res) => {
message: out.detail || out.message || `worker returned ${r.status}`,
});
}
+ out.raw = out.text ?? '';
+ if (out.raw && body.clean !== false) {
+ out.text = await cleanTranscription(out.raw);
+ out.cleaned = out.text !== out.raw;
+ }
return json(res, 200, out);
});
+
+/**
+ * Webcam fingerspelling decodes at a 10–20% character error rate; a
+ * constrained LLM pass recovers most of it ("esteredouble" → intended word).
+ * Fail-open: any LLM problem returns the raw decode untouched.
+ */
+async function cleanTranscription(raw) {
+ try {
+ const { llmComplete, llmConfigured } = await import('./_lib/llm.js');
+ if (!llmConfigured()) return raw;
+ const cleaned = await llmComplete({
+ system:
+ 'You correct noisy ASL fingerspelling transcriptions. The input is a ' +
+ 'machine decode of someone spelling letter by letter into a webcam; ' +
+ 'roughly 1 in 6 characters may be wrong, split, or merged. Return ONLY ' +
+ 'the most likely intended text, preserving meaning and proper nouns. ' +
+ 'No explanations, no quotes. If the input already looks right, return it unchanged.',
+ user: raw,
+ maxTokens: 120,
+ timeoutMs: 8_000,
+ });
+ const text = (cleaned || '').trim();
+ // Guard against LLM refusals/essays: a cleanup should stay in the same
+ // size class as the input.
+ if (!text || text.length > raw.length * 2 + 20) return raw;
+ return text;
+ } catch {
+ return raw;
+ }
+}
diff --git a/docs/animation-studio.md b/docs/animation-studio.md
index 3580fcd94..06af93699 100644
--- a/docs/animation-studio.md
+++ b/docs/animation-studio.md
@@ -83,7 +83,7 @@ curl -X POST 'https://three.ws/api/animations/clips' \
- **Saving and selling need an account.** Export and download are open to everyone; saving to the library and listing for sale require sign-in.
- **The sellable artifact is the baked GLB.** A marketplace listing sells the baked animated GLB, so the buyer gets a self-contained, playable file.
- **Mannequin-only controls.** Build, skin color, and joint constraints apply to the primitive mannequin; on a loaded GLB avatar those controls are disabled.
-- **Fingerspelling spells A to Z.** The Spell box keeps letters and spaces and drops everything else (digits and punctuation have distinct signs that are not letter handshapes). It needs a loaded rigged avatar with finger bones; the mannequin and finger-less rigs are refused with an explanation.
+- **Fingerspelling spells letters and numbers.** The Spell box keeps A to Z, the ASL number handshapes 0 to 9, and spaces, and drops punctuation. It needs a loaded rigged avatar with finger bones; the mannequin and finger-less rigs are refused with an explanation.
## Related
diff --git a/docs/sign-language.md b/docs/sign-language.md
index db8592b38..57bb8bfec 100644
--- a/docs/sign-language.md
+++ b/docs/sign-language.md
@@ -6,7 +6,7 @@ three.ws avatars can communicate in American Sign Language. Today that means ASL
## What works today
-- **Fingerspell any word.** All 26 ASL handshapes, the traced J and Z motions, and the double-letter bounce, compiled on-device into a standard animation clip that plays on any rigged avatar with finger bones. Try it at [/pose](https://three.ws/pose), or share a spelled word: `https://three.ws/pose?spell=HELLO`.
+- **Fingerspell any word or number.** All 26 ASL letter handshapes, the number handshapes 0–9, the traced J and Z motions, and the double-letter bounce, compiled on-device into a standard animation clip that plays on any rigged avatar with finger bones. Try it at [/pose](https://three.ws/pose), or share a spelled word: `https://three.ws/pose?spell=HELLO`.
- **Signed chat replies.** In the [/app](https://three.ws/app) agent chat, the 🤟 button in the chat header turns on sign-language mode: the avatar signs every assistant reply. Embedders get the same with one attribute on the web component:
```html
diff --git a/src/animation-library.js b/src/animation-library.js
index b90c51833..67497d1a1 100644
--- a/src/animation-library.js
+++ b/src/animation-library.js
@@ -701,7 +701,7 @@ export class AnimationLibrary {
spellWord(word) {
const letters = normalizeWord(word);
if (!letters) {
- this.setStatus('Type a word to fingerspell — letters A–Z.', 'error');
+ this.setStatus('Type a word to fingerspell — letters and numbers.', 'error');
return false;
}
// Reflect the (normalized) word in the input so deep links read back.
diff --git a/src/fingerspelling.js b/src/fingerspelling.js
index eb4d180ae..36b094823 100644
--- a/src/fingerspelling.js
+++ b/src/fingerspelling.js
@@ -198,6 +198,18 @@ export const LETTER_SHAPES = {
X: { curl: { Index: [15, 95, 80], Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side' },
Y: { curl: { Index: 1, Middle: 1, Ring: 1 }, thumb: 'out' },
Z: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side', motion: 'Z' },
+ // ASL number handshapes 0–9 (static). 6–9 touch the thumb to one
+ // fingertip; the touched finger half-curls to meet the opposing thumb.
+ 0: { curl: { Index: 0.55, Middle: 0.55, Ring: 0.55, Pinky: 0.55 }, thumb: 'oppose' },
+ 1: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'across' },
+ 2: { curl: { Ring: 1, Pinky: 1 }, splay: { Index: 9, Middle: -9 }, thumb: 'across' },
+ 3: { curl: { Ring: 1, Pinky: 1 }, splay: { Index: 9, Middle: -9 }, thumb: 'out' },
+ 4: { curl: {}, splay: { Index: 10, Middle: 3, Ring: -4, Pinky: -12 }, thumb: 'across' },
+ 5: { curl: {}, splay: { Index: 10, Middle: 3, Ring: -4, Pinky: -12 }, thumb: 'out' },
+ 6: { curl: { Pinky: 0.55 }, splay: { Index: 9, Middle: 0, Ring: -8 }, thumb: 'oppose' },
+ 7: { curl: { Ring: 0.55 }, splay: { Index: 9, Middle: 0, Pinky: -10 }, thumb: 'oppose' },
+ 8: { curl: { Middle: 0.55 }, splay: { Index: 9, Ring: -6, Pinky: -12 }, thumb: 'oppose' },
+ 9: { curl: { Index: 0.55 }, splay: { Middle: 4, Ring: -4, Pinky: -12 }, thumb: 'oppose' },
};
// Wrist paths for the traced letters, keyed 0..1 across the letter window —
@@ -282,7 +294,7 @@ export const DEFAULT_TIMING = Object.freeze({
export function normalizeWord(word) {
const cleaned = String(word ?? '')
.toUpperCase()
- .replace(/[^A-Z ]+/g, '')
+ .replace(/[^A-Z0-9 ]+/g, '')
.replace(/ +/g, ' ')
.trim();
return cleaned;
@@ -306,14 +318,15 @@ function stableUuid(seed) {
/**
* Build an AnimationClip JSON document that fingerspells `word` on the right
- * hand. Only A–Z and spaces survive normalization; anything else is dropped.
+ * hand. Letters A–Z, digits 0–9, and spaces survive normalization; anything
+ * else is dropped.
* Returns the same document shape the animation library serves, ready for
* THREE.AnimationClip.parse + the platform retarget engine.
*/
export function buildFingerspellingClip(word, opts = {}) {
const timing = { ...DEFAULT_TIMING, ...opts };
const letters = normalizeWord(word);
- if (!letters) throw new Error('word has no spellable characters (A-Z)');
+ if (!letters) throw new Error('word has no spellable characters (A-Z, 0-9)');
const pose = signingPose();
const restHand = pose.RightHand;
diff --git a/src/nich-agent.js b/src/nich-agent.js
index 523329022..b474f591a 100644
--- a/src/nich-agent.js
+++ b/src/nich-agent.js
@@ -867,11 +867,18 @@ export class NichAgent {
if (this._signInput?.capturing) {
btn.disabled = true;
try {
- const { text } = await this._signInput.stop();
+ const { text, confidence } = await this._signInput.stop();
const input = this.panel.querySelector('.nich-input');
if (text) {
input.value = (input.value ? `${input.value} ` : '') + text;
input.focus();
+ if (confidence != null && confidence < 0.4) {
+ this._addMessage(
+ 'agent',
+ 'I wasn’t confident about that one — check the text before sending, or try signing with your hand a bit closer to the camera.',
+ 'status',
+ );
+ }
} else {
this._addMessage('agent', 'I couldn’t read any fingerspelling there — face the camera and spell a little slower.', 'status');
}
diff --git a/src/sign-input.js b/src/sign-input.js
index 9612040b9..d36e99208 100644
--- a/src/sign-input.js
+++ b/src/sign-input.js
@@ -167,7 +167,14 @@ export class SignInput {
});
const out = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(out.message || `transcription failed (${res.status})`);
- return { text: out.text ?? '', frames: frames.length, ms: out.ms };
+ return {
+ text: out.text ?? '',
+ raw: out.raw ?? out.text ?? '',
+ confidence: out.confidence ?? null,
+ cleaned: !!out.cleaned,
+ frames: frames.length,
+ ms: out.ms,
+ };
} finally {
this.onState('idle');
}
diff --git a/src/sign-speech.js b/src/sign-speech.js
index 2f81b3df0..f138fb86a 100644
--- a/src/sign-speech.js
+++ b/src/sign-speech.js
@@ -29,8 +29,9 @@ const WORD_GAP_SECONDS = 0.18;
const NORMAL_BLEND_MODE = 2500;
/**
- * Split text into the word sequence the signer will perform. Only A–Z words
- * survive (fingerspelling has no digit/punctuation handshapes in this v1).
+ * Split text into the word sequence the signer will perform. Letters and
+ * digits survive (A–Z fingerspelling plus the ASL number handshapes 0–9);
+ * punctuation is dropped.
*/
export function utteranceWords(text) {
return normalizeWord(text).split(' ').filter(Boolean);
@@ -112,7 +113,7 @@ export function compileUtterance(text, opts = {}) {
typeof opts.signs === 'function' ? opts.signs : (w) => (opts.signs ? opts.signs.get(w) : null) ?? null;
const words = utteranceWords(text);
- if (!words.length) throw new Error('text has no signable characters (A-Z)');
+ if (!words.length) throw new Error('text has no signable characters (A-Z, 0-9)');
const merged = new Map();
let cursor = 0;
diff --git a/tests/fingerspelling.test.js b/tests/fingerspelling.test.js
index 6a8f76225..cc0953ca9 100644
--- a/tests/fingerspelling.test.js
+++ b/tests/fingerspelling.test.js
@@ -17,10 +17,13 @@ function quatAngleDeg(q) {
}
describe('letter shapes', () => {
- it('defines all 26 letters', () => {
+ it('defines all 26 letters and 10 digits', () => {
for (let c = 65; c <= 90; c++) {
expect(LETTER_SHAPES[String.fromCharCode(c)], String.fromCharCode(c)).toBeTruthy();
}
+ for (let d = 0; d <= 9; d++) {
+ expect(LETTER_SHAPES[String(d)], String(d)).toBeTruthy();
+ }
});
it('produces unit quaternions for every finger bone of every letter', () => {
@@ -42,12 +45,15 @@ describe('letter shapes', () => {
const seen = new Map();
for (const letter of Object.keys(LETTER_SHAPES)) {
const key = flat(letter);
- // Some letters share a base handshape by design and differ only by
- // wrist orientation or motion, which live in the clip: I/J, K/P,
- // and the G/Q/Z family.
+ // Some signs share a base handshape by design and differ only by
+ // wrist orientation, motion, or context: I/J, K/P, the G/Q/Z
+ // family, and in real ASL digit 0 ≡ O and digit 2 ≡ V.
const clash = seen.get(key);
if (clash) {
- expect(['I:J', 'G:Q', 'Q:Z', 'K:P'].includes(`${clash}:${letter}`), `${clash} vs ${letter}`).toBe(true);
+ expect(
+ ['I:J', 'G:Q', 'Q:Z', 'K:P', '0:O', '2:V'].includes(`${clash}:${letter}`),
+ `${clash} vs ${letter}`,
+ ).toBe(true);
}
seen.set(key, letter);
}
@@ -68,14 +74,16 @@ describe('letter shapes', () => {
expect(left.LeftHandRing2[2]).toBeCloseTo(-right.RightHandRing2[2], 6);
});
- it('rejects unknown letters', () => {
- expect(() => handshapeLocals('7', 'Right')).toThrow();
+ it('rejects unknown characters', () => {
+ expect(() => handshapeLocals('@', 'Right')).toThrow();
+ expect(handshapeLocals('7', 'Right')).toBeTruthy();
});
});
describe('normalizeWord', () => {
it('uppercases, strips non-letters, collapses spaces', () => {
expect(normalizeWord(' héllo, world! ')).toBe('HLLO WORLD');
+ expect(normalizeWord('room 42')).toBe('ROOM 42');
expect(normalizeWord('three.ws')).toBe('THREEWS');
expect(normalizeWord('$$$')).toBe('');
});
@@ -147,7 +155,8 @@ describe('buildFingerspellingClip', () => {
});
it('rejects unspellable input', () => {
- expect(() => buildFingerspellingClip('123')).toThrow();
+ expect(() => buildFingerspellingClip('...')).toThrow();
expect(() => buildFingerspellingClip('')).toThrow();
+ expect(buildFingerspellingClip('42').duration).toBeGreaterThan(0);
});
});
diff --git a/tests/sign-speech.test.js b/tests/sign-speech.test.js
index 49f50c8d5..f59d506a0 100644
--- a/tests/sign-speech.test.js
+++ b/tests/sign-speech.test.js
@@ -11,7 +11,7 @@ import {
describe('utteranceWords', () => {
it('normalizes to signable words', () => {
- expect(utteranceWords('Hey, three.ws! 42')).toEqual(['HEY', 'THREEWS']);
+ expect(utteranceWords('Hey, three.ws! 42')).toEqual(['HEY', 'THREEWS', '42']);
expect(utteranceWords('$$$')).toEqual([]);
});
});
@@ -70,7 +70,8 @@ describe('compileUtterance', () => {
});
it('throws on unsignable text', () => {
- expect(() => compileUtterance('12345')).toThrow();
+ expect(() => compileUtterance('!!!')).toThrow();
+ expect(compileUtterance('12345').clip.duration).toBeGreaterThan(0);
});
});
diff --git a/workers/model-asl-recognition/decode.py b/workers/model-asl-recognition/decode.py
index a167d17cf..39c4a25c1 100644
--- a/workers/model-asl-recognition/decode.py
+++ b/workers/model-asl-recognition/decode.py
@@ -37,12 +37,26 @@ MIN_FRAMES = 8
def decode_logits(logits: np.ndarray) -> str:
"""(tokens, vocab) logits → text. Ids outside the printable character map
(BOS/EOS/PAD) terminate or are dropped, matching the competition decode."""
- logits = np.asarray(logits)
+ return decode_with_confidence(logits)[0]
+
+
+def decode_with_confidence(logits: np.ndarray) -> tuple[str, float]:
+ """(tokens, vocab) logits → (text, confidence).
+
+ Confidence is the mean softmax probability of the argmax character over
+ the decoded (printable) positions — 1.0 for a certain decode, near 1/vocab
+ for noise. 0.0 when nothing decodes.
+ """
+ logits = np.asarray(logits, dtype=np.float64)
if logits.ndim != 2:
raise ValueError(f"logits must be 2D (tokens, vocab); got {logits.shape}")
ids = np.argmax(logits, axis=-1)
+ shifted = logits - logits.max(axis=-1, keepdims=True)
+ probs = np.exp(shifted)
+ probs /= probs.sum(axis=-1, keepdims=True)
chars = []
- for i in ids:
+ confidences = []
+ for pos, i in enumerate(ids):
ch = ID_TO_CHAR.get(int(i))
if ch is None:
# First special token after any output ends the sequence; leading
@@ -51,7 +65,11 @@ def decode_logits(logits: np.ndarray) -> str:
break
continue
chars.append(ch)
- return "".join(chars).strip()
+ confidences.append(float(probs[pos, int(i)]))
+ text = "".join(chars).strip()
+ if not text or not confidences:
+ return "", 0.0
+ return text, float(np.mean(confidences))
def validate_frames(frames) -> np.ndarray:
diff --git a/workers/model-asl-recognition/main.py b/workers/model-asl-recognition/main.py
index 057015e09..4f518d56a 100644
--- a/workers/model-asl-recognition/main.py
+++ b/workers/model-asl-recognition/main.py
@@ -24,7 +24,7 @@ import numpy as np
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel
-from decode import FEATURE_COLUMNS, MAX_FRAMES, MIN_FRAMES, decode_logits, validate_frames
+from decode import FEATURE_COLUMNS, MAX_FRAMES, MIN_FRAMES, decode_with_confidence, validate_frames
MODEL_PATH = os.environ.get("MODEL_PATH", "/models/model.tflite")
API_KEY = os.environ.get("API_KEY", "")
@@ -81,8 +81,13 @@ async def transcribe(body: TranscribeBody, request: Request):
t0 = time.time()
async with _lock:
logits = await asyncio.to_thread(_infer, arr)
- text = decode_logits(logits)
- return {"text": text, "frames": int(arr.shape[0]), "ms": int((time.time() - t0) * 1000)}
+ text, confidence = decode_with_confidence(logits)
+ return {
+ "text": text,
+ "confidence": round(confidence, 3),
+ "frames": int(arr.shape[0]),
+ "ms": int((time.time() - t0) * 1000),
+ }
def _infer(arr: np.ndarray) -> np.ndarray:
diff --git a/workers/model-asl-recognition/test_decode.py b/workers/model-asl-recognition/test_decode.py
index 5da9719a2..684091a7d 100644
--- a/workers/model-asl-recognition/test_decode.py
+++ b/workers/model-asl-recognition/test_decode.py
@@ -74,3 +74,29 @@ def test_validate_frames_caps():
validate_frames([[0.0] * 10 for _ in range(10)])
with pytest.raises(ValueError):
validate_frames([])
+
+
+def test_confidence_high_for_peaked_logits():
+ from decode import decode_with_confidence
+
+ text, conf = decode_with_confidence(one_hot(ids_for("hello")))
+ assert text == "hello"
+ assert conf > 0.95
+
+
+def test_confidence_low_for_flat_logits():
+ from decode import decode_with_confidence
+
+ flat = np.zeros((10, 63), dtype=np.float32)
+ flat[:, 5] += 0.01 # a barely-preferred char so something decodes
+ text, conf = decode_with_confidence(flat)
+ assert text != ""
+ assert conf < 0.05
+
+
+def test_confidence_zero_when_nothing_decodes():
+ from decode import decode_with_confidence
+
+ text, conf = decode_with_confidence(one_hot([60, 61, 62]))
+ assert text == ""
+ assert conf == 0.0