asleepyhimiko commited on
Commit
e15aacc
·
verified ·
1 Parent(s): 8dd7cca

Upload 4 files

Browse files
Files changed (4) hide show
  1. README.md +52 -3
  2. baseline.py +97 -0
  3. encode.py +106 -0
  4. score.py +47 -0
README.md CHANGED
@@ -1,3 +1,52 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ task_categories:
4
+ - automatic-speech-recognition
5
+ language:
6
+ - en
7
+ tags:
8
+ - benchmark
9
+ - deterministic
10
+ - audio-to-text
11
+ - codec
12
+ pretty_name: loomspeech
13
+ size_categories:
14
+ - n<1K
15
+ ---
16
+
17
+ # loomspeech — a decode benchmark
18
+
19
+ **Can a model listen to deterministically-encoded audio and recover the text it came from?**
20
+
21
+ loom is a ~10KB, model-free codec: it turns text into sung audio by mapping each **word to a fixed
22
+ musical motif** (1-3 notes on a pentatonic scale) sung on the word's own vowels. Same word -> same
23
+ sound, forever, on any machine. So `(text -> audio)` labels are **free and unlimited** — this repo
24
+ is a *generator-backed* benchmark, not a static dump.
25
+
26
+ ## The task
27
+ Given a `.wav`, predict the source `text`. Metrics: exact-line accuracy and position-wise word
28
+ accuracy (`score.py`).
29
+
30
+ ## What's here
31
+ - `data/` — a playable sample (`metadata.jsonl` + wavs: `file_name`, `text`, `motif`).
32
+ - `encode.py` — the encoder. Mint more: `python encode.py --builtin --n 5000 --out data`.
33
+ - `baseline.py` — a non-ML floor: pitch-only, vocabulary-aware (~43% word accuracy). Beat it.
34
+ - `score.py` — the scorer.
35
+
36
+ ```python
37
+ from datasets import load_dataset
38
+ ds = load_dataset("asleepyhimiko/loomspeech") # audio + text + motif
39
+ ```
40
+
41
+ ## Baseline & headroom
42
+ Pitch-only + known lexicon ~= **43% word / 20% exact-line.** It throws the **vowels** away (which
43
+ carry out-of-vocabulary words), assumes the lexicon, and dies under noise. A real model should beat
44
+ all three.
45
+
46
+ ## The question
47
+ Near-100% decode proves a **lossless, model-free code** — meaning survives sound and returns.
48
+ Whether a recoverable code is a **language** (human-learnable, conventional, productive) is the open
49
+ question, not the claim. This benchmark measures the necessary condition.
50
+
51
+ - Hear it: <https://asleepyhimiko-loom.static.hf.space/booth.html> (set *pitch -> word = note*)
52
+ - Source: <https://github.com/evengineer1ng/loom>
baseline.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """A non-ML baseline decoder for loomspeech — pitch-only, vocabulary-aware (the FLOOR).
3
+
4
+ Reads each audio file, splits it into note segments by silence, detects each note's pitch (FFT),
5
+ snaps to a scale degree, then greedily segments the degree sequence into words using the known
6
+ lexicon. It ignores vowels and timbre entirely — so the vowel signal (which carries out-of-
7
+ vocabulary words) is thrown away. The open challenge: beat this with a model that needs no
8
+ lexicon, survives noise, and recovers words this baseline can't.
9
+
10
+ python bench/encode.py --builtin --n 300 --out data/ls
11
+ python bench/baseline.py data/ls/manifest.jsonl data/ls > preds.jsonl
12
+ python bench/score.py data/ls/manifest.jsonl preds.jsonl
13
+ """
14
+ import json
15
+ import os
16
+ import sys
17
+
18
+ import numpy as np
19
+
20
+ try:
21
+ import soundfile as sf
22
+ except ImportError:
23
+ raise SystemExit("needs soundfile: pip install soundfile numpy")
24
+
25
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
26
+ from encode import SCALE_HZ, WORDS, word_motif # noqa: E402
27
+
28
+ VOCAB = {}
29
+ for _w in WORDS:
30
+ VOCAB.setdefault(tuple(word_motif(_w)), _w) # motif -> word (first wins on collision)
31
+
32
+
33
+ def segments(audio, sr, thr=0.02, min_s=0.05):
34
+ env = np.abs(audio).astype(np.float64)
35
+ win = max(1, int(0.006 * sr))
36
+ env = np.convolve(env, np.ones(win) / win, "same")
37
+ voiced = env > thr
38
+ segs, i, n = [], 0, len(audio)
39
+ while i < n:
40
+ if voiced[i]:
41
+ j = i
42
+ while j < n and voiced[j]:
43
+ j += 1
44
+ if j - i >= int(min_s * sr):
45
+ segs.append((i, j))
46
+ i = j
47
+ else:
48
+ i += 1
49
+ return segs
50
+
51
+
52
+ def degree(seg, sr):
53
+ a = seg * np.hanning(len(seg))
54
+ spec = np.abs(np.fft.rfft(a))
55
+ fr = np.fft.rfftfreq(len(a), 1.0 / sr)
56
+ band = (fr >= 200) & (fr <= 560)
57
+ if not band.any() or not spec[band].size:
58
+ return 0
59
+ f = fr[band][int(np.argmax(spec[band]))]
60
+ return min(range(len(SCALE_HZ)), key=lambda d: abs(SCALE_HZ[d] - f))
61
+
62
+
63
+ def decode(audio, sr):
64
+ degs = [degree(audio[a:b], sr) for a, b in segments(audio, sr)]
65
+ out, i = [], 0
66
+ while i < len(degs):
67
+ hit = None
68
+ for length in (3, 2, 1):
69
+ t = tuple(degs[i:i + length])
70
+ if len(t) == length and t in VOCAB:
71
+ hit = (VOCAB[t], length)
72
+ break
73
+ if hit:
74
+ out.append(hit[0])
75
+ i += hit[1]
76
+ else:
77
+ i += 1
78
+ return " ".join(out)
79
+
80
+
81
+ def main():
82
+ if len(sys.argv) < 3:
83
+ raise SystemExit("usage: baseline.py <manifest.jsonl> <data_dir> > preds.jsonl")
84
+ manifest, root = sys.argv[1], sys.argv[2]
85
+ for line in open(manifest, encoding="utf-8"):
86
+ line = line.strip()
87
+ if not line:
88
+ continue
89
+ d = json.loads(line)
90
+ audio, sr = sf.read(os.path.join(root, d["wav"]))
91
+ if getattr(audio, "ndim", 1) > 1:
92
+ audio = audio.mean(axis=1)
93
+ print(json.dumps({"id": d["id"], "text": decode(np.asarray(audio, dtype=np.float64), sr)}))
94
+
95
+
96
+ if __name__ == "__main__":
97
+ main()
encode.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """loomspeech benchmark — the ENCODER. Deterministic text -> sung audio.
3
+
4
+ Each word hashes to a short musical MOTIF (1-3 notes) on a fixed pentatonic scale, sung on the
5
+ word's own vowels. Same word -> same motif -> same sound, forever. That makes (text, audio) an
6
+ *unlimited, free, perfectly-labeled* dataset — no human, no licensing, no model.
7
+
8
+ THE TASK (see README): given the audio, recover the text. If a model can, the codec carries the
9
+ meaning losslessly — it is a language. Generate as much as you want:
10
+
11
+ python bench/encode.py --builtin --n 2000 --out data/loomspeech
12
+ python bench/encode.py --corpus my_lines.txt --out data/loomspeech
13
+
14
+ Writes <out>/*.wav + <out>/manifest.jsonl ({id, text, wav, motif}).
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import json
20
+ import os
21
+ import random
22
+ import sys
23
+
24
+ import numpy as np
25
+
26
+ sys.path.insert(0, os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")))
27
+ import voicesynth # noqa: E402 (repo root)
28
+
29
+ try:
30
+ import soundfile as sf
31
+ except ImportError:
32
+ raise SystemExit("loomspeech encode needs soundfile: pip install soundfile numpy")
33
+
34
+ SCALE_HZ = [220.00, 261.63, 293.66, 329.63, 392.00, 440.00, 523.25] # A-minor pentatonic
35
+ VOWELS = set("aeiou")
36
+ # a small built-in lexicon so anyone can mint data with zero input.
37
+ WORDS = ("the a red fast car heart beats high low you move stop go win lose three dunk lap race "
38
+ "night city loom echo brah turn brake speed lead fall rise hold open close left right up "
39
+ "down now then fan rival crew pit fastest clean sharp gap apex throttle").split()
40
+
41
+
42
+ def word_motif(word: str) -> list:
43
+ """A word -> a deterministic 1..3 note motif (degrees into SCALE_HZ). Clean uint32 hash —
44
+ this is the canonical benchmark mapping (booth.html is its interactive cousin)."""
45
+ h = 2166136261
46
+ for c in word.lower():
47
+ h = ((h ^ ord(c)) * 16777619) & 0xFFFFFFFF
48
+ n = 1 + (len(word) % 3)
49
+ out = []
50
+ for _ in range(n):
51
+ out.append(h % len(SCALE_HZ))
52
+ h = (h * 16777619 + 2654435761) & 0xFFFFFFFF
53
+ return out
54
+
55
+
56
+ def _words(text: str) -> list:
57
+ return ["".join(c for c in w if c.isalpha()) for w in text.lower().split() if any(ch.isalpha() for ch in w)]
58
+
59
+
60
+ def encode_line(text: str, *, dur: float = 0.26, gap: float = 0.05, sr: int = 22050):
61
+ notes, motifs = [], []
62
+ for w in _words(text):
63
+ deg = word_motif(w)
64
+ motifs.append(deg)
65
+ vs = [c for c in w if c in VOWELS] or ["a"]
66
+ for i, d in enumerate(deg):
67
+ notes.append({"hz": SCALE_HZ[d], "dur": dur, "vowel": vs[i % len(vs)]})
68
+ audio = voicesynth.render_tape(notes, sr=sr, gap=gap) if notes else np.zeros(1, dtype=np.float32)
69
+ return audio, motifs
70
+
71
+
72
+ def builtin_corpus(n: int, seed: int = 0) -> list:
73
+ rng = random.Random(seed)
74
+ return [" ".join(rng.choice(WORDS) for _ in range(rng.randint(2, 6))) for _ in range(n)]
75
+
76
+
77
+ def main() -> None:
78
+ ap = argparse.ArgumentParser(description="loomspeech encoder — text to sung audio")
79
+ ap.add_argument("--corpus", help="text file, one line per utterance")
80
+ ap.add_argument("--builtin", action="store_true", help="mint random utterances from the built-in lexicon")
81
+ ap.add_argument("--n", type=int, default=500)
82
+ ap.add_argument("--seed", type=int, default=0)
83
+ ap.add_argument("--out", default="data/loomspeech")
84
+ ap.add_argument("--sr", type=int, default=22050)
85
+ args = ap.parse_args()
86
+
87
+ if args.corpus:
88
+ lines = [ln.strip() for ln in open(args.corpus, encoding="utf-8") if ln.strip()]
89
+ else:
90
+ lines = builtin_corpus(args.n, args.seed)
91
+
92
+ os.makedirs(args.out, exist_ok=True)
93
+ with open(os.path.join(args.out, "manifest.jsonl"), "w", encoding="utf-8") as man:
94
+ for i, line in enumerate(lines):
95
+ audio, motifs = encode_line(line, sr=args.sr)
96
+ wav = f"{i:06d}.wav"
97
+ sf.write(os.path.join(args.out, wav), audio, args.sr)
98
+ man.write(json.dumps({"id": i, "text": line, "wav": wav, "motif": motifs}) + "\n")
99
+
100
+ print(f"wrote {len(lines)} (text,audio) pairs -> {args.out}/ (sr={args.sr})")
101
+ print("task: predict 'text' from 'wav'. score: python bench/score.py "
102
+ f"{args.out}/manifest.jsonl preds.jsonl")
103
+
104
+
105
+ if __name__ == "__main__":
106
+ main()
score.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Score a decoder against the loomspeech benchmark.
3
+
4
+ python bench/score.py <manifest.jsonl> <predictions.jsonl>
5
+
6
+ predictions.jsonl: one {"id": N, "text": "..."} per line. Reports exact-line accuracy and
7
+ position-wise word accuracy. The task: recover the source text from the audio alone.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import sys
13
+
14
+
15
+ def load(path: str) -> dict:
16
+ out = {}
17
+ for line in open(path, encoding="utf-8"):
18
+ line = line.strip()
19
+ if not line:
20
+ continue
21
+ d = json.loads(line)
22
+ out[d["id"]] = d.get("text", "")
23
+ return out
24
+
25
+
26
+ def norm(text: str) -> list:
27
+ return ["".join(c for c in w if c.isalpha()) for w in str(text).lower().split() if any(ch.isalpha() for ch in w)]
28
+
29
+
30
+ def main() -> None:
31
+ if len(sys.argv) < 3:
32
+ raise SystemExit("usage: score.py <manifest.jsonl> <predictions.jsonl>")
33
+ gold, pred = load(sys.argv[1]), load(sys.argv[2])
34
+ n, exact, w_tot, w_ok = len(gold), 0, 0, 0
35
+ for i, g in gold.items():
36
+ gw, pw = norm(g), norm(pred.get(i, ""))
37
+ if gw == pw:
38
+ exact += 1
39
+ w_tot += len(gw)
40
+ w_ok += sum(1 for a, b in zip(gw, pw) if a == b)
41
+ print(f"pairs: {n}")
42
+ print(f"exact-line accuracy: {exact}/{n} = {100 * exact / max(1, n):.1f}%")
43
+ print(f"word accuracy: {w_ok}/{w_tot} = {100 * w_ok / max(1, w_tot):.1f}%")
44
+
45
+
46
+ if __name__ == "__main__":
47
+ main()