brenorb commited on
Commit
aa7ff36
·
verified ·
1 Parent(s): 4403d23

Scripts: v1 corpus and generation

Browse files
generation/build_v1_corpus.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Build the v1 corpus batches from the v0 corpus.
3
+
4
+ batch5 holds the v0 sentences whose audio must be generated again:
5
+
6
+ * every sentence whose spoken form differs from its written form (digits,
7
+ money, dates, symbols, acronyms, loanwords). v0's teacher read the written
8
+ text, and an audit of its clips found it often read amounts digit by digit
9
+ or garbled them ("R$ 7.586,29" -> "resatras 58862919"), so the audio and the
10
+ student's tokens disagreed; v1's teacher reads ``spoken_form()``;
11
+ * every sentence with a template grammar error ("vou à a escola", "na o
12
+ aeroporto", "sobiu", "Moro no Rua"), with the text corrected.
13
+
14
+ The superseded v0 sentences are written to data/corpus/v1_superseded.txt as
15
+ ``b<batch>_<split>_<position>`` keys (corpus ids repeat across splits), so
16
+ that the dataset assembly leaves their v0 clips out.
17
+
18
+ batch4 (new sentences for the v1 coverage gaps) is converted from
19
+ data/corpus/batch4/sentences.jsonl when it exists: a stable hash of the text
20
+ assigns 90% of each category to train and 5% each to validation and test.
21
+
22
+ python scripts/build_v1_corpus.py
23
+ """
24
+ import argparse
25
+ import hashlib
26
+ import json
27
+ import re
28
+ from collections import defaultdict
29
+ from pathlib import Path
30
+
31
+ import pyarrow as pa
32
+ import pyarrow.parquet as pq
33
+
34
+ from tiny_broca.text import spoken_form
35
+
36
+ _PREPOSITIONS = {"na": "n", "no": "n", "nas": "n", "nos": "n", "da": "d", "do": "d", "das": "d", "dos": "d",
37
+ "pela": "pel", "pelo": "pel", "pelas": "pel", "pelos": "pel"}
38
+ _TAILS = ("faz sentido", "não é?", "viu?", "da última vez", "com certeza", "beleza?", "sabe?", "né?", "hein?")
39
+ # v0 template sentences too broken to keep: a CPF with one-digit groups.
40
+ _DROP = re.compile(r"\b\d\.\d\.\d-\d{2}\b")
41
+
42
+
43
+ def fix_template_text(text):
44
+ """Correct the v0 conversational template errors."""
45
+ def contract(m):
46
+ prep, article = m.group(1), m.group(2)
47
+ head = _PREPOSITIONS[prep.lower()]
48
+ word = head + article.lower()
49
+ return word.capitalize() if prep[0].isupper() else word
50
+ text = re.sub(r"\b([Nn]a|[Nn]o|[Nn]as|[Nn]os|[Dd]a|[Dd]o|[Dd]as|[Dd]os|[Pp]ela|[Pp]elo|[Pp]elas|[Pp]elos) (a|o|as|os)\b",
51
+ contract, text)
52
+ text = re.sub(r"\bà a\b", "à", text)
53
+ text = re.sub(r"\bà o\b", "ao", text)
54
+ text = re.sub(r"\bà as\b", "às", text)
55
+ text = re.sub(r"\bà os\b", "aos", text)
56
+ text = re.sub(r"\b([Ss])obiu\b", r"\1ubiu", text)
57
+ text = re.sub(r"\b([Nn])o (Rua|Avenida|Praça|Travessa|Alameda|Estrada)\b", r"\1a \2", text)
58
+ text = re.sub(r"\b([Oo]) o\b", r"\1", text)
59
+ text = re.sub(r"\b([Aa]) a\b", r"\1", text)
60
+ for tail in _TAILS:
61
+ question = tail.endswith("?") or tail in ("faz sentido",)
62
+ ending = "" if tail.endswith("?") else ("?" if question else ".")
63
+ text = re.sub(r"(\w) " + re.escape(tail) + r"$", r"\1, " + tail + ending, text)
64
+ return text
65
+
66
+
67
+ def fold(text):
68
+ return re.sub(r"[^\w]+", " ", text.lower()).strip()
69
+
70
+
71
+ def write_split_files(rows, directory, batch):
72
+ directory.mkdir(parents=True, exist_ok=True)
73
+ schema = pa.schema([pa.field("id", pa.string()), pa.field("batch", pa.int64()), pa.field("split", pa.string()),
74
+ pa.field("text", pa.string()), pa.field("source", pa.string())])
75
+ counts = {}
76
+ for split in ("train", "validation", "test"):
77
+ part = [r for r in rows if r["split"] == split]
78
+ pq.write_table(pa.Table.from_pylist(part, schema=schema), directory / f"{split}.parquet")
79
+ counts[split] = len(part)
80
+ return counts
81
+
82
+
83
+ def main():
84
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
85
+ ap.add_argument("--corpus", type=Path, default=Path("data/corpus"))
86
+ args = ap.parse_args()
87
+
88
+ regen, superseded = [], []
89
+ for batch in (1, 2, 3):
90
+ for path in sorted(args.corpus.glob(f"batch{batch}/*.parquet")):
91
+ for position, row in enumerate(pq.read_table(path).to_pylist()):
92
+ fixed = fix_template_text(row["text"])
93
+ if fixed != row["text"] or fold(spoken_form(row["text"])) != fold(row["text"]):
94
+ superseded.append(f"b{batch}_{path.stem}_{position:05d}")
95
+ if _DROP.search(fixed):
96
+ continue
97
+ regen.append({"id": row["id"] + "r", "batch": 5, "split": path.stem, "text": fixed,
98
+ "source": row["source"] + "+v1"})
99
+ # Append-only: clip ids are row positions, so rows already generated keep
100
+ # their place and sentences that newly qualify go at the end of their split.
101
+ existing = []
102
+ for split in ("train", "validation", "test"):
103
+ path = args.corpus / "batch5" / f"{split}.parquet"
104
+ if path.exists():
105
+ existing += pq.read_table(path).to_pylist()
106
+ known = {(r["split"], r["text"]) for r in existing}
107
+ regen = existing + [r for r in regen if (r["split"], r["text"]) not in known]
108
+ counts = write_split_files(regen, args.corpus / "batch5", 5)
109
+ (args.corpus / "v1_superseded.txt").write_text("\n".join(superseded) + "\n")
110
+ print(json.dumps({"batch5": counts, "superseded": len(superseded)}))
111
+
112
+ sentences = args.corpus / "batch4" / "sentences.jsonl"
113
+ if sentences.exists():
114
+ rows, seen = [], set()
115
+ per_category = defaultdict(int)
116
+ for line in sentences.read_text().splitlines():
117
+ if not line.strip():
118
+ continue
119
+ item = json.loads(line)
120
+ text = item["text"].strip()
121
+ if fold(text) in seen:
122
+ continue
123
+ seen.add(fold(text))
124
+ bucket = int(hashlib.sha256(text.encode()).hexdigest()[:8], 16) % 20
125
+ split = "validation" if bucket == 0 else "test" if bucket == 1 else "train"
126
+ per_category[item.get("category", "other")] += 1
127
+ rows.append({"id": f"broca04_{len(rows):05d}", "batch": 4, "split": split, "text": text,
128
+ "source": "v1-" + item.get("category", "other")})
129
+ print(json.dumps({"batch4": write_split_files(rows, args.corpus / "batch4", 4),
130
+ "categories": dict(per_category)}))
131
+
132
+
133
+ if __name__ == "__main__":
134
+ main()
generation/generate_audio.py CHANGED
@@ -32,14 +32,14 @@ from qwen_tts import Qwen3TTSModel
32
  BASE_MODEL = "Qwen/Qwen3-TTS-12Hz-1.7B-Base"
33
  VOICE_REFS = {"F1": "F1", "M1": "M1"} # selected Common Voice clones (data/refs)
34
 
35
- from tiny_broca.text import wer_normalize
36
 
37
 
38
- def load_corpus(corpus_dir: Path):
39
  import pyarrow.parquet as pq
40
 
41
  sentences = []
42
- for batch in (1, 2, 3):
43
  for path in sorted(corpus_dir.glob(f"batch{batch}/*.parquet")):
44
  table = pq.read_table(path)
45
  for i, (text, source) in enumerate(zip(table.column("text").to_pylist(),
@@ -68,13 +68,29 @@ def main():
68
  ap.add_argument("--threads", type=int, default=12)
69
  ap.add_argument("--batch", type=int, default=8)
70
  ap.add_argument("--seed", type=int, default=20261117)
 
 
 
 
 
 
71
  args = ap.parse_args()
72
 
73
  args.out.mkdir(parents=True, exist_ok=True)
74
  torch.set_num_threads(args.threads)
75
 
76
  refs = json.loads((args.refs / "voices.json").read_text())
77
- sentences = load_corpus(args.corpus)
 
 
 
 
 
 
 
 
 
 
78
  print(f"corpus: {len(sentences)} sentences", flush=True)
79
 
80
  print("loading whisper small ...", flush=True)
@@ -144,9 +160,10 @@ def main():
144
  path = audio_dir / f"{cid}.flac"
145
  sf.write(path, wave, sr)
146
  transcript = transcribe(path)
147
- w = wer(wer_normalize(s["text"]), wer_normalize(transcript)) if transcript else 1.0
148
- ok = (0.5 <= seconds <= 35.0) and (w < 0.15) and transcript
149
- conn.execute("INSERT OR REPLACE INTO clips VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
 
150
  (cid, voice, s["batch"], s["split"], s["text"],
151
  round(seconds, 3), sr, round(gen / len(chunk), 2),
152
  round(gen / len(chunk) / max(seconds, 1e-9), 3),
@@ -204,9 +221,10 @@ def main():
204
  path = audio_dir / f"{cid}.flac"
205
  sf.write(path, wave, sr)
206
  transcript = transcribe(path)
207
- w = wer(wer_normalize(s["text"]), wer_normalize(transcript)) if transcript else 1.0
208
- ok = (0.5 <= seconds <= 35.0) and (w < 0.15) and transcript
209
- conn.execute("INSERT OR REPLACE INTO clips VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
 
210
  (cid, voice, s["batch"], s["split"], s["text"],
211
  round(seconds, 3), sr, round(gen / len(chunk), 2),
212
  round(gen / len(chunk) / max(seconds, 1e-9), 3),
 
32
  BASE_MODEL = "Qwen/Qwen3-TTS-12Hz-1.7B-Base"
33
  VOICE_REFS = {"F1": "F1", "M1": "M1"} # selected Common Voice clones (data/refs)
34
 
35
+ from tiny_broca.text import spoken_form, spoken_normalize, wer_normalize
36
 
37
 
38
+ def load_corpus(corpus_dir: Path, batches=(1, 2, 3)):
39
  import pyarrow.parquet as pq
40
 
41
  sentences = []
42
+ for batch in batches:
43
  for path in sorted(corpus_dir.glob(f"batch{batch}/*.parquet")):
44
  table = pq.read_table(path)
45
  for i, (text, source) in enumerate(zip(table.column("text").to_pylist(),
 
68
  ap.add_argument("--threads", type=int, default=12)
69
  ap.add_argument("--batch", type=int, default=8)
70
  ap.add_argument("--seed", type=int, default=20261117)
71
+ ap.add_argument("--batches", type=int, nargs="+", default=[1, 2, 3], help="Corpus batches to read")
72
+ ap.add_argument("--teacher-text", choices=("raw", "spoken"), default="raw",
73
+ help="raw: the teacher reads the written sentence (v0); spoken: it reads the front end's "
74
+ "spoken_form(), so every number, symbol and loanword is said exactly as the student's "
75
+ "tokens spell it, and quality control compares words without masking numbers")
76
+ ap.add_argument("--max-wer", type=float, default=0.15)
77
  args = ap.parse_args()
78
 
79
  args.out.mkdir(parents=True, exist_ok=True)
80
  torch.set_num_threads(args.threads)
81
 
82
  refs = json.loads((args.refs / "voices.json").read_text())
83
+ sentences = load_corpus(args.corpus, args.batches)
84
+ if args.teacher_text == "spoken":
85
+ for s in sentences:
86
+ s["written"], s["text"] = s["text"], spoken_form(s["text"])
87
+
88
+ def clip_wer(text, transcript):
89
+ if not transcript:
90
+ return 1.0
91
+ if args.teacher_text == "spoken":
92
+ return wer(spoken_normalize(text), spoken_normalize(transcript))
93
+ return wer(wer_normalize(text), wer_normalize(transcript))
94
  print(f"corpus: {len(sentences)} sentences", flush=True)
95
 
96
  print("loading whisper small ...", flush=True)
 
160
  path = audio_dir / f"{cid}.flac"
161
  sf.write(path, wave, sr)
162
  transcript = transcribe(path)
163
+ w = clip_wer(s["text"], transcript)
164
+ ok = (0.5 <= seconds <= 35.0) and (w < args.max_wer) and transcript
165
+ conn.execute("INSERT OR REPLACE INTO clips (clip_id, voice, batch, split, text, seconds, sr, gen_seconds, rtf, "
166
+ "wer, transcript, status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
167
  (cid, voice, s["batch"], s["split"], s["text"],
168
  round(seconds, 3), sr, round(gen / len(chunk), 2),
169
  round(gen / len(chunk) / max(seconds, 1e-9), 3),
 
221
  path = audio_dir / f"{cid}.flac"
222
  sf.write(path, wave, sr)
223
  transcript = transcribe(path)
224
+ w = clip_wer(s["text"], transcript)
225
+ ok = (0.5 <= seconds <= 35.0) and (w < args.max_wer) and transcript
226
+ conn.execute("INSERT OR REPLACE INTO clips (clip_id, voice, batch, split, text, seconds, sr, gen_seconds, rtf, "
227
+ "wer, transcript, status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
228
  (cid, voice, s["batch"], s["split"], s["text"],
229
  round(seconds, 3), sr, round(gen / len(chunk), 2),
230
  round(gen / len(chunk) / max(seconds, 1e-9), 3),
generation/rescue_clips.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Second opinion for clips the generation gate rejected.
3
+
4
+ The gate's ASR (Whisper small) "corrects" colloquial Portuguese ("deixa eu"
5
+ -> "deixe-me", "pra" -> "para") and writes numbers its own way ("seis e meia"
6
+ -> "6,5"), so it rejects many clips in which the teacher said exactly the
7
+ text. A rejected clip is accepted when a second, independent ASR (parakeet-v3
8
+ through ``fscript``) hears the text with a spoken-form WER below the gate.
9
+ The forced alignment that follows is a third, letter-level check.
10
+
11
+ python scripts/rescue_clips.py --audio data/audio-v1
12
+ """
13
+ import argparse
14
+ import sqlite3
15
+ import subprocess
16
+ from pathlib import Path
17
+
18
+ from jiwer import wer
19
+
20
+ from tiny_broca.text import spoken_normalize
21
+
22
+
23
+ def transcribe(path):
24
+ result = subprocess.run(["fscript", str(path), "--text=plain", "-D", "--raw", "--stdout"],
25
+ capture_output=True, text=True)
26
+ if result.returncode: # an empty transcript would reject the clip for good
27
+ raise RuntimeError(f"fscript failed on {path}: {(result.stderr or result.stdout).strip()[:300]}")
28
+ return result.stdout.strip()
29
+
30
+
31
+ def main():
32
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
33
+ ap.add_argument("--audio", type=Path, required=True)
34
+ ap.add_argument("--max-wer", type=float, default=0.15)
35
+ args = ap.parse_args()
36
+ conn = sqlite3.connect(args.audio / "state.db")
37
+ columns = [r[1] for r in conn.execute("PRAGMA table_info(clips)")]
38
+ if "rescue" not in columns:
39
+ conn.execute("ALTER TABLE clips ADD COLUMN rescue TEXT")
40
+ rows = conn.execute("SELECT clip_id, text FROM clips WHERE status='bad' AND rescue IS NULL").fetchall()
41
+ rescued = 0
42
+ for i, (cid, text) in enumerate(rows):
43
+ path = args.audio / "audio" / f"{cid}.flac"
44
+ if not path.exists():
45
+ continue
46
+ heard = transcribe(path)
47
+ score = wer(spoken_normalize(text), spoken_normalize(heard)) if heard else 1.0
48
+ ok = score < args.max_wer
49
+ rescued += ok
50
+ conn.execute("UPDATE clips SET rescue=?, status=? WHERE clip_id=?",
51
+ (f"parakeet {score:.3f}: {heard}", "ok" if ok else "bad", cid))
52
+ conn.commit()
53
+ if i % 25 == 0:
54
+ print(f"{i}/{len(rows)} rescued {rescued}", flush=True)
55
+ print(f"rescued {rescued} of {len(rows)} rejected clips")
56
+
57
+
58
+ if __name__ == "__main__":
59
+ main()