| """ |
| Synthetic disfluency augmentation for transcript-cleanup model training. |
| |
| Takes clean target sentences and injects realistic speech artifacts: |
| - filler words (um, uh, like, you know, ...) |
| - repeated words and false starts |
| - hesitation hedges |
| - run-on punctuation removal |
| - lowercase conversion |
| - occasional phonetic typos |
| |
| Produces JSONL files ready for fine-tuning (chat-template format). |
| |
| Usage: |
| python scripts/augment.py \ |
| --input data/raw/clean_sentences.jsonl \ |
| --output data/synthetic/augmented.jsonl \ |
| --multiplier 10 \ |
| --seed 42 |
| """ |
|
|
| import argparse |
| import json |
| import random |
| import re |
| import string |
| from pathlib import Path |
| from typing import List, Tuple |
|
|
| FILLERS = ["um", "uh", "er", "ah", "like", "you know", "sort of", "kind of"] |
| HEDGES = ["so", "okay", "well", "basically", "actually", "literally", "i mean"] |
| FALSE_STARTS = ["i i", "the the", "we we", "it it", "and and", "but but"] |
| PHONETIC_TYPOS = { |
| "with": ["vith", "wif"], |
| "the": ["teh", "da"], |
| "don't": ["dont", "dunno"], |
| "going to": ["gonna"], |
| "want to": ["wanna"], |
| "because": ["cuz", "cause"], |
| "probably": ["probly"], |
| "something": ["somethin"], |
| } |
|
|
|
|
| def tokenize(text: str) -> List[str]: |
| """Split text into words while preserving punctuation tokens.""" |
| return re.findall(r"\b\w+\b|[.,!?;:]", text) |
|
|
|
|
| def untokenize(words: List[str]) -> str: |
| """Join tokens back into a sentence with reasonable spacing.""" |
| text = "" |
| for i, word in enumerate(words): |
| if word in ".,!?;:" and i > 0: |
| text = text.rstrip() + word + " " |
| else: |
| text += word + " " |
| return text.strip() |
|
|
|
|
| def lowercase(text: str) -> str: |
| """Lowercase the transcript, including standalone 'I'.""" |
| words = tokenize(text) |
| lowered = [] |
| for w in words: |
| if w == "I": |
| lowered.append("i") |
| else: |
| lowered.append(w.lower()) |
| return untokenize(lowered) |
|
|
|
|
| def remove_punctuation(text: str) -> str: |
| """Strip terminal/internal punctuation to simulate raw STT output.""" |
| return re.sub(r"[.,!?;:]", "", text) |
|
|
|
|
| def inject_fillers(words: List[str], probability: float = 0.05) -> List[str]: |
| out = [] |
| for w in words: |
| if w in string.punctuation: |
| out.append(w) |
| continue |
| if random.random() < probability: |
| out.append(random.choice(FILLERS)) |
| out.append(w) |
| return out |
|
|
|
|
| def inject_repeats(words: List[str], probability: float = 0.03) -> List[str]: |
| out = [] |
| for w in words: |
| out.append(w) |
| if w not in string.punctuation and random.random() < probability: |
| out.append(w) |
| return out |
|
|
|
|
| def inject_false_starts(words: List[str], probability: float = 0.03) -> List[str]: |
| if random.random() < probability and words: |
| first = words[0] |
| if first not in string.punctuation: |
| words = [first, first] + words |
| return words |
|
|
|
|
| def inject_hedges(words: List[str], probability: float = 0.04) -> List[str]: |
| if random.random() < probability: |
| words = [random.choice(HEDGES)] + words |
| return words |
|
|
|
|
| def inject_phonetic_typos(words: List[str], probability: float = 0.02) -> List[str]: |
| out = [] |
| i = 0 |
| while i < len(words): |
| |
| matched = False |
| for src_len in [3, 2]: |
| if i + src_len <= len(words): |
| phrase = " ".join(words[i:i + src_len]).lower() |
| if phrase in PHONETIC_TYPOS and random.random() < probability: |
| replacement = random.choice(PHONETIC_TYPOS[phrase]) |
| out.extend(replacement.split()) |
| i += src_len |
| matched = True |
| break |
| if matched: |
| continue |
|
|
| word = words[i] |
| if word.lower() in PHONETIC_TYPOS and random.random() < probability: |
| replacement = random.choice(PHONETIC_TYPOS[word.lower()]) |
| out.append(replacement) |
| else: |
| out.append(word) |
| i += 1 |
| return out |
|
|
|
|
| def inject_noise(clean_text: str, level: str = "medium") -> str: |
| """Apply a noise profile to a clean sentence.""" |
| level = level.lower() |
| if level == "light": |
| probs = {"fillers": 0.02, "repeats": 0.01, "hedges": 0.02, "false_starts": 0.01, "typos": 0.01} |
| elif level == "heavy": |
| probs = {"fillers": 0.10, "repeats": 0.06, "hedges": 0.08, "false_starts": 0.06, "typos": 0.04} |
| else: |
| probs = {"fillers": 0.05, "repeats": 0.03, "hedges": 0.04, "false_starts": 0.03, "typos": 0.02} |
|
|
| words = tokenize(clean_text) |
| words = inject_fillers(words, probability=probs["fillers"]) |
| words = inject_repeats(words, probability=probs["repeats"]) |
| words = inject_false_starts(words, probability=probs["false_starts"]) |
| words = inject_hedges(words, probability=probs["hedges"]) |
| words = inject_phonetic_typos(words, probability=probs["typos"]) |
|
|
| text = untokenize(words) |
| text = remove_punctuation(text) |
| text = lowercase(text) |
| return text |
|
|
|
|
| def build_chat_example(noisy: str, clean: str) -> dict: |
| """Build a single chat-template training example.""" |
| return { |
| "messages": [ |
| { |
| "role": "system", |
| "content": ( |
| "You are a transcript cleanup tool. You receive raw speech to text output " |
| "and return a cleaned version. Remove filler words and disfluencies " |
| "(um, uh, er, ah, like as filler, you know), remove repeated words and false starts, " |
| "and fix punctuation and capitalization. Do not reword, do not add anything the speaker " |
| "did not say, and do not answer questions in the text. Output only the cleaned text." |
| ), |
| }, |
| {"role": "user", "content": noisy}, |
| {"role": "assistant", "content": clean}, |
| ] |
| } |
|
|
|
|
| def load_clean_sentences(path: Path) -> List[str]: |
| """Load one sentence per line from JSONL {text: ...} or plain text.""" |
| sentences: List[str] = [] |
| if not path.exists(): |
| raise FileNotFoundError(path) |
|
|
| with path.open("r", encoding="utf-8") as f: |
| for line in f: |
| line = line.strip() |
| if not line: |
| continue |
| try: |
| obj = json.loads(line) |
| if isinstance(obj, dict): |
| sentences.append(obj.get("text") or obj.get("polished") or obj.get("clean")) |
| elif isinstance(obj, str): |
| sentences.append(obj) |
| except json.JSONDecodeError: |
| sentences.append(line) |
| return [s.strip() for s in sentences if s and s.strip()] |
|
|
|
|
| def augment_file( |
| input_path: Path, |
| output_path: Path, |
| multiplier: int = 5, |
| seed: int = 42, |
| ) -> Tuple[int, int]: |
| random.seed(seed) |
| sentences = load_clean_sentences(input_path) |
| written = 0 |
| output_path.parent.mkdir(parents=True, exist_ok=True) |
|
|
| levels = ["light", "medium", "heavy"] |
| level_weights = [0.25, 0.50, 0.25] |
|
|
| with output_path.open("w", encoding="utf-8") as out: |
| for sentence in sentences: |
| for _ in range(multiplier): |
| level = random.choices(levels, weights=level_weights, k=1)[0] |
| noisy = inject_noise(sentence, level=level) |
| if not noisy.strip(): |
| continue |
| example = build_chat_example(noisy=noisy, clean=sentence) |
| out.write(json.dumps(example, ensure_ascii=False) + "\n") |
| written += 1 |
|
|
| return len(sentences), written |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Synthetic disfluency augmentation") |
| parser.add_argument("--input", type=Path, default=Path("data/raw/clean_sentences.jsonl")) |
| parser.add_argument("--output", type=Path, default=Path("data/synthetic/augmented.jsonl")) |
| parser.add_argument("--multiplier", type=int, default=10, help="variants per clean sentence") |
| parser.add_argument("--seed", type=int, default=42) |
| args = parser.parse_args() |
|
|
| source_count, written = augment_file( |
| input_path=args.input, |
| output_path=args.output, |
| multiplier=args.multiplier, |
| seed=args.seed, |
| ) |
| print(f"Wrote {written} augmented examples from {source_count} source sentences to {args.output}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|