fiato / generate.py
cfahlgren1's picture
cfahlgren1 HF Staff
Upload generate.py with huggingface_hub
7a91706 verified
Raw History Blame Contribute Delete
23.7 kB
# /// script
# requires-python = "==3.12.*"
# dependencies = [
# "vllm",
# "snac",
# "datasets",
# "huggingface_hub",
# "pyarrow",
# "soundfile",
# "scipy",
# "jiwer",
# "numpy",
# ]
# ///
"""Generate a two-voice synthetic speech corpus with Maya-1.
Every sentence of n4ze3m/tiny-voca is read by both voices. Each voice is held by
prefilling its anchor clip: the prompt is "anchor text + sentence" and the anchor's
audio tokens, so the model continues in the anchor's voice. Clips are screened
with Whisper and a speaker model, retried once with a new seed, then pushed.
With --expressions, some sentences are read a second time with one of Maya-1's
nonverbal tags written inline ("Well, <sigh> I tried."). An audio event classifier
checks that the sound is really there.
"""
import argparse
import hashlib
import io
import json
import re
from collections import Counter
from dataclasses import dataclass, field
import jiwer
import numpy as np
import pyarrow.dataset as pads
import soundfile as sf
import torch
from datasets import Audio, Dataset, DatasetDict, concatenate_datasets
from huggingface_hub import HfApi, HfFileSystem
from scipy.signal import resample_poly
from snac import SNAC
from transformers import (
ASTFeatureExtractor,
ASTForAudioClassification,
AutoFeatureExtractor,
AutoTokenizer,
WavLMForXVector,
pipeline,
)
from vllm import LLM, SamplingParams
MODEL_ID = "maya-research/maya1"
TEXT_REPO = "n4ze3m/tiny-voca"
TEXT_COLUMNS = ["text_id", "text", "split", "category", "origin", "source_id", "source_license", "source_url"]
SAMPLE_RATE = 24000
SAMPLES_PER_FRAME = 2048
TOKENS_PER_FRAME = 7
SOH_ID = 128259
EOH_ID = 128260
SOA_ID = 128261
BOS_ID = 128000
TEXT_EOT_ID = 128009
CODE_START_ID = 128257
CODE_END_ID = 128258
CODE_OFFSET = 128266
CODE_MAX_ID = 156937
# Position of each of a frame's 7 tokens in the three SNAC levels.
LEVEL_SLOTS = [[0], [1, 4], [2, 3, 5, 6]]
MAX_NEW_TOKENS = 2520 # 360 frames, about 30 s
MAX_WER = 0.15
MIN_SIM_TO_ANCHOR = 0.85
MIN_WORDS_PER_SEC = 1.5
MIN_WORDS_PER_SEC_EXPRESSIVE = 0.8 # the nonverbal sound takes time but adds no word
MAX_WORDS_PER_SEC = 5.5
MAX_INNER_SILENCE_SEC = 1.5
MIN_SECONDS = 0.3
MAX_SECONDS = 30.0 # Whisper reads 30 s at a time, and the model being trained takes 32 s at most
MAX_ATTEMPTS = 2
SILENCE_DB = -40
SILENCE_HOP = SAMPLE_RATE // 100
LEAD_PAD_SEC = 0.05
TRAIL_PAD_SEC = 0.10
EVENT_MODEL_ID = "MIT/ast-finetuned-audioset-10-10-0.4593"
LAUGHTER = ["Laughter", "Giggle", "Chuckle, chortle", "Snicker", "Belly laugh"]
# AudioSet classes that count as hearing each Maya-1 tag.
EVENT_LABELS = {
"laugh": LAUGHTER,
"laugh_harder": LAUGHTER,
"chuckle": LAUGHTER,
"giggle": LAUGHTER,
"sigh": ["Sigh", "Breathing"],
"exhale": ["Sigh", "Breathing"],
"gasp": ["Gasp", "Breathing"],
"cry": ["Crying, sobbing", "Whimper"],
"snort": ["Snort"],
}
EXPRESSION_POSITIONS = ["middle", "middle", "middle", "start", "end"]
EXPRESSIVE_WORDS = range(5, 19)
TAG = re.compile(r"<[a-z_]+>")
@dataclass
class Voice:
voice_id: str
description: str
anchor_text: str
anchor_codes: list[int]
anchor_embedding: np.ndarray
@dataclass
class Clip:
sentence: dict
voice: Voice
attempt: int
seed: int
audio: np.ndarray = field(default_factory=lambda: np.zeros(0, dtype=np.float32))
duration: float = 0.0
inner_silence: float = 0.0
hit_token_limit: bool = False
asr_transcript: str = ""
wer: float = 1.0
sim_to_anchor: float = 0.0
event_scores: dict[str, float] = field(default_factory=dict)
@property
def clip_id(self) -> str:
return f"{self.sentence['text_id']}_{self.voice.voice_id}"
@property
def expression(self) -> str | None:
return self.sentence["expression"]
@property
def event_score(self) -> float | None:
return self.event_scores.get(self.expression) if self.expression else None
def qc_reasons(self, min_event_score: float) -> list[str]:
if self.duration < MIN_SECONDS:
return ["no_audio"]
if self.duration > MAX_SECONDS:
return ["too_long"]
words_per_sec = len(spoken_text(self.sentence["text"]).split()) / self.duration
min_words_per_sec = MIN_WORDS_PER_SEC_EXPRESSIVE if self.expression else MIN_WORDS_PER_SEC
checks = {
"token_limit": self.hit_token_limit,
"wer": self.wer > MAX_WER,
"speaker": self.sim_to_anchor < MIN_SIM_TO_ANCHOR,
"too_slow": words_per_sec < min_words_per_sec,
"too_fast": words_per_sec > MAX_WORDS_PER_SEC,
"inner_silence": self.inner_silence > MAX_INNER_SILENCE_SEC,
"expression_missing": self.expression is not None and self.event_score < min_event_score,
}
return [reason for reason, failed in checks.items() if failed]
def load_sentences() -> list[dict]:
"""Unique sentences of tiny-voca, read without downloading its audio."""
fs = HfFileSystem()
files = fs.glob(f"datasets/{TEXT_REPO}/data/*.parquet") + fs.glob(f"datasets/{TEXT_REPO}/batch2/data/*.parquet")
rows = pads.dataset(files, filesystem=fs, format="parquet").to_table(columns=TEXT_COLUMNS).to_pylist()
plain = {"expression": None, "expression_position": None, "plain_text_id": None}
unique = {row["text_id"]: {**row, **plain} for row in rows}
return sorted(unique.values(), key=lambda row: row["text_id"])
def spoken_text(text: str) -> str:
"""The words of a sentence, without expression tags."""
return " ".join(TAG.sub(" ", text).split())
def with_expression(text: str, tag: str, position: str) -> str | None:
if position == "start":
return f"<{tag}> {text}"
if position == "end":
return f"{text} <{tag}>"
for comma in re.finditer(", ", text):
before, after = text[: comma.start()], text[comma.end() :]
if len(before.split()) >= 2 and len(after.split()) >= 2:
return f"{before}, <{tag}> {after}"
return None
def expressive_sentences(sentences: list[dict], tags: list[str], per_tag: int) -> list[dict]:
"""`per_tag` sentences for each tag: a plain sentence with the tag written after
a comma, at the start or at the end. Each keeps the plain sentence's split."""
eligible = [s for s in sentences if len(s["text"].split()) in EXPRESSIVE_WORDS]
if len(eligible) < per_tag * len(tags):
raise ValueError(f"only {len(eligible)} sentences for {per_tag} per tag and {len(tags)} tags")
rows = []
for index, sentence in enumerate(eligible[: per_tag * len(tags)]):
tag = tags[index % len(tags)]
position = EXPRESSION_POSITIONS[index // len(tags) % len(EXPRESSION_POSITIONS)]
text = with_expression(sentence["text"], tag, position)
if text is None:
position = "start" if index % 2 else "end"
text = with_expression(sentence["text"], tag, position)
rows.append(
{
**sentence,
"text_id": hashlib.sha256(text.encode()).hexdigest()[:16],
"text": text,
"category": "expressive",
"expression": tag,
"expression_position": position,
"plain_text_id": sentence["text_id"],
}
)
return rows
def to_16k(audio: np.ndarray) -> np.ndarray:
return resample_poly(audio, 2, 3).astype(np.float32)
def speaker_embedding(audio: np.ndarray, speaker_model, speaker_features) -> np.ndarray:
features = speaker_features(to_16k(audio), sampling_rate=16000, return_tensors="pt")
with torch.inference_mode():
embedding = speaker_model(**features.to(speaker_model.device)).embeddings[0]
return torch.nn.functional.normalize(embedding, dim=-1).cpu().numpy()
def encode_codes(snac_model, audio: np.ndarray) -> list[int]:
"""Audio to Maya-1 audio tokens, 7 per SNAC frame."""
with torch.inference_mode():
levels = snac_model.encode(torch.from_numpy(audio).float().view(1, 1, -1).to("cuda"))
frames = levels[0].shape[1]
packed = np.zeros((frames, TOKENS_PER_FRAME), dtype=np.int64)
for level, slots in zip(levels, LEVEL_SLOTS, strict=True):
packed[:, slots] = level[0].cpu().numpy().reshape(frames, len(slots))
packed += CODE_OFFSET + 4096 * np.arange(TOKENS_PER_FRAME)
return packed.reshape(-1).tolist()
def decode_audio(snac_model, code_ids: list[int], skip_frames: int) -> np.ndarray:
"""Decode 7-token SNAC frames and drop the first `skip_frames` frames of audio."""
frames = (np.array(code_ids, dtype=np.int64).reshape(-1, TOKENS_PER_FRAME) - CODE_OFFSET) % 4096
codes = [torch.from_numpy(frames[:, slots].reshape(1, -1)).to("cuda") for slots in LEVEL_SLOTS]
with torch.inference_mode():
audio = snac_model.decoder(snac_model.quantizer.from_codes(codes))[0, 0]
return audio[skip_frames * SAMPLES_PER_FRAME :].float().cpu().numpy()
def keep_whole_frames(token_ids: list[int]) -> list[int]:
codes = []
for token_id in token_ids:
if token_id == CODE_END_ID:
break
if CODE_OFFSET <= token_id <= CODE_MAX_ID:
codes.append(token_id)
return codes[: len(codes) // TOKENS_PER_FRAME * TOKENS_PER_FRAME]
def trim_silence(audio: np.ndarray) -> tuple[np.ndarray, float]:
"""Cut leading and trailing silence. Returns the audio and its longest inner silence in seconds."""
hops = len(audio) // SILENCE_HOP
if hops == 0:
return audio[:0], 0.0
rms = np.sqrt((audio[: hops * SILENCE_HOP].reshape(hops, SILENCE_HOP) ** 2).mean(axis=1))
loud = np.flatnonzero(rms > rms.max() * 10 ** (SILENCE_DB / 20))
if len(loud) == 0:
return audio[:0], 0.0
start = max(0, loud[0] * SILENCE_HOP - int(LEAD_PAD_SEC * SAMPLE_RATE))
end = min(len(audio), (loud[-1] + 1) * SILENCE_HOP + int(TRAIL_PAD_SEC * SAMPLE_RATE))
inner_silence = (np.diff(loud).max() - 1) * SILENCE_HOP / SAMPLE_RATE if len(loud) > 1 else 0.0
return audio[start:end], float(inner_silence)
def load_voices(anchor_repo: str, snac_model, speaker_model, speaker_features) -> list[Voice]:
anchors = Dataset.from_parquet(f"hf://datasets/{anchor_repo}/data/train-00000-of-00001.parquet")
anchors = anchors.cast_column("audio", Audio(decode=False)).filter(lambda row: row["is_chosen_anchor"])
voices = []
for row in sorted(anchors, key=lambda row: row["voice_id"]):
audio, sample_rate = sf.read(io.BytesIO(row["audio"]["bytes"]), dtype="float32")
if sample_rate != SAMPLE_RATE:
raise RuntimeError(f"anchor {row['id']} is {sample_rate} Hz, expected {SAMPLE_RATE}")
codes = encode_codes(snac_model, audio)
embedding = speaker_embedding(audio, speaker_model, speaker_features)
voices.append(Voice(row["voice_id"], row["description"], row["text"], codes, embedding))
print(f"voice {row['voice_id']}: anchor {row['id']}, {len(audio) / SAMPLE_RATE:.1f}s")
return voices
def prompt_ids(tokenizer, clip: Clip) -> list[int]:
voice = clip.voice
text = f'<description="{voice.description}"> {voice.anchor_text} {clip.sentence["text"]}'
body = tokenizer.encode(text, add_special_tokens=False)
return [SOH_ID, BOS_ID, *body, TEXT_EOT_ID, EOH_ID, SOA_ID, CODE_START_ID, *voice.anchor_codes]
def generate(llm, tokenizer, snac_model, clips: list[Clip]) -> None:
params = [
SamplingParams(
temperature=0.4,
top_p=0.9,
repetition_penalty=1.1,
max_tokens=MAX_NEW_TOKENS,
min_tokens=4 * TOKENS_PER_FRAME,
stop_token_ids=[CODE_END_ID],
seed=clip.seed,
detokenize=False,
)
for clip in clips
]
prompts = [{"prompt_token_ids": prompt_ids(tokenizer, clip)} for clip in clips]
for clip, result in zip(clips, llm.generate(prompts, params), strict=True):
completion = result.outputs[0]
clip.hit_token_limit = completion.finish_reason == "length"
new_codes = keep_whole_frames(list(completion.token_ids))
if not new_codes:
continue
# Decode together with the anchor frames so the codec has context, then drop them.
anchor_codes = clip.voice.anchor_codes
audio = decode_audio(snac_model, anchor_codes + new_codes, len(anchor_codes) // TOKENS_PER_FRAME)
clip.audio, clip.inner_silence = trim_silence(audio)
clip.duration = len(clip.audio) / SAMPLE_RATE
def score_events(clips: list[Clip], event_model, event_features) -> None:
"""Probability that each tag's sound is somewhere in the clip."""
label_ids = {tag: [event_model.config.label2id[label] for label in labels] for tag, labels in EVENT_LABELS.items()}
for start in range(0, len(clips), 32):
batch = clips[start : start + 32]
inputs = event_features([to_16k(clip.audio) for clip in batch], sampling_rate=16000, return_tensors="pt")
with torch.inference_mode():
probabilities = event_model(**inputs.to(event_model.device)).logits.sigmoid().cpu().numpy()
for clip, row in zip(batch, probabilities, strict=True):
clip.event_scores = {tag: float(row[ids].max()) for tag, ids in label_ids.items()}
def score(clips: list[Clip], asr, speaker_model, speaker_features, event_model, event_features) -> None:
normalize = asr.tokenizer.normalize
audible = [clip for clip in clips if MIN_SECONDS <= clip.duration <= MAX_SECONDS]
inputs = [{"raw": to_16k(clip.audio), "sampling_rate": 16000} for clip in audible]
# Greedy decoding: beam search multiplies Whisper's memory by the beam count.
transcripts = asr(inputs, batch_size=16, generate_kwargs={"num_beams": 1})
for clip, result in zip(audible, transcripts, strict=True):
clip.asr_transcript = result["text"].strip()
truth = normalize(spoken_text(clip.sentence["text"]))
clip.wer = jiwer.wer(truth or "-", normalize(clip.asr_transcript) or "-")
embedding = speaker_embedding(clip.audio, speaker_model, speaker_features)
clip.sim_to_anchor = float(embedding @ clip.voice.anchor_embedding)
score_events(audible, event_model, event_features)
def seed_for(sentence: dict, attempt: int) -> int:
return int(sentence["text_id"][:7], 16) + attempt
def flac_bytes(audio: np.ndarray) -> bytes:
buffer = io.BytesIO()
sf.write(buffer, audio * (0.95 / np.abs(audio).max()), SAMPLE_RATE, format="FLAC", subtype="PCM_16")
return buffer.getvalue()
def clip_scores(clip: Clip) -> dict:
return {
"duration_seconds": round(clip.duration, 3),
"asr_transcript": clip.asr_transcript,
"normalized_wer": round(clip.wer, 4),
"sim_to_anchor": round(clip.sim_to_anchor, 4),
"event_score": None if clip.event_score is None else round(clip.event_score, 4),
"attempt": clip.attempt,
"seed": clip.seed,
}
def accepted_row(clip: Clip) -> dict:
return {
"id": clip.clip_id,
"audio": {"bytes": flac_bytes(clip.audio), "path": f"{clip.clip_id}.flac"},
"voice_id": clip.voice.voice_id,
**clip.sentence,
"sample_rate": SAMPLE_RATE,
**clip_scores(clip),
"teacher_model": MODEL_ID,
}
def review_row(clip: Clip, reasons: list[str]) -> dict:
return {"id": clip.clip_id, "text": clip.sentence["text"], "qc_reasons": reasons, **clip_scores(clip)}
def expression_stats(first_attempts: list[Clip], min_event_score: float) -> list[dict]:
"""Per tag and voice: how often the first attempt passed and how clearly the sound is heard,
next to the same classifier on the same sentences read without the tag."""
scored = [c for c in first_attempts if c.event_scores]
plain = {(c.sentence["text_id"], c.voice.voice_id): c for c in scored if not c.expression}
stats = []
for tag in sorted({c.expression for c in scored if c.expression}):
for voice_id in sorted({c.voice.voice_id for c in scored}):
clips = [c for c in scored if c.expression == tag and c.voice.voice_id == voice_id]
pairs = [(c, plain.get((c.sentence["plain_text_id"], voice_id))) for c in clips]
pairs = [(c, p) for c, p in pairs if p is not None]
if not clips or not pairs:
continue
reasons = Counter(reason for c in clips for reason in c.qc_reasons(min_event_score))
stats.append(
{
"tag": tag,
"voice": voice_id,
"clips": len(clips),
"passed": round(float(np.mean([not c.qc_reasons(min_event_score) for c in clips])), 2),
"wer_ok": round(float(np.mean([c.wer <= MAX_WER for c in clips])), 2),
"event_score": round(float(np.mean([c.event_score for c in clips])), 3),
"event_score_plain": round(float(np.mean([p.event_scores[tag] for _, p in pairs])), 3),
"heard_at_0.1": round(float(np.mean([c.event_score >= 0.1 for c in clips])), 2),
"heard_at_0.3": round(float(np.mean([c.event_score >= 0.3 for c in clips])), 2),
"plain_heard_at_0.1": round(float(np.mean([p.event_scores[tag] >= 0.1 for _, p in pairs])), 2),
"extra_seconds": round(float(np.mean([c.duration - p.duration for c, p in pairs])), 2),
"reasons": dict(reasons),
}
)
return stats
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--repo", required=True, help="dataset repo to push to, e.g. user/name")
parser.add_argument("--anchor-repo", required=True, help="spike dataset holding the chosen anchor clips")
parser.add_argument("--limit", type=int, help="only the first N sentences")
parser.add_argument("--expressions", default="", help="comma-separated Maya-1 tags, e.g. laugh,sigh")
parser.add_argument("--expressive-per-tag", type=int, default=0, help="sentences read with each tag")
parser.add_argument("--min-event-score", type=float, default=0.0, help="reject a tagged clip heard below this")
parser.add_argument("--chunk", type=int, default=1500, help="sentences per generation round")
parser.add_argument("--dry-run", action="store_true", help="print statistics without pushing")
args = parser.parse_args()
tags = [tag for tag in args.expressions.split(",") if tag]
unknown = [tag for tag in tags if tag not in EVENT_LABELS]
if unknown:
raise ValueError(f"no event labels for {unknown}")
sentences = load_sentences()[: args.limit]
sentences += expressive_sentences(sentences, tags, args.expressive_per_tag) if tags else []
print(f"{len(sentences)} sentences, {sum(1 for s in sentences if s['expression'])} with an expression")
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
llm = LLM(model=MODEL_ID, dtype="bfloat16", max_model_len=4096, gpu_memory_utilization=0.45)
snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz").eval().to("cuda")
asr = pipeline("automatic-speech-recognition", model="openai/whisper-small.en", device="cuda")
speaker_features = AutoFeatureExtractor.from_pretrained("microsoft/wavlm-base-plus-sv")
speaker_model = WavLMForXVector.from_pretrained("microsoft/wavlm-base-plus-sv").eval().to("cuda")
event_features = ASTFeatureExtractor.from_pretrained(EVENT_MODEL_ID)
event_model = ASTForAudioClassification.from_pretrained(EVENT_MODEL_ID).eval().to("cuda")
voices = load_voices(args.anchor_repo, snac_model, speaker_model, speaker_features)
shards, review, first_attempts = [], [], []
seconds_by_split: dict[str, float] = {}
reasons_count: Counter[str] = Counter()
for start in range(0, len(sentences), args.chunk):
pending = [(sentence, voice) for sentence in sentences[start : start + args.chunk] for voice in voices]
rows = []
for attempt in range(1, MAX_ATTEMPTS + 1):
clips = [Clip(sentence, voice, attempt, seed_for(sentence, attempt)) for sentence, voice in pending]
generate(llm, tokenizer, snac_model, clips)
score(clips, asr, speaker_model, speaker_features, event_model, event_features)
pending = []
for clip in clips:
reasons = clip.qc_reasons(args.min_event_score)
if reasons:
review.append(review_row(clip, reasons))
reasons_count.update(reasons)
pending.append((clip.sentence, clip.voice))
else:
rows.append(accepted_row(clip))
split = clip.sentence["split"]
seconds_by_split[split] = seconds_by_split.get(split, 0.0) + clip.duration
clip.audio = clip.audio[:0] # the statistics below need the scores, not the samples
if attempt == 1:
first_attempts += clips
print(f"sentences {start}+ attempt {attempt}: {len(clips)} clips, {len(pending)} rejected")
shards.append(Dataset.from_list(rows).cast_column("audio", Audio(sampling_rate=SAMPLE_RATE)))
dataset = concatenate_datasets(shards)
splits = DatasetDict(
{
name: dataset.filter(lambda split, name=name: split == name, input_columns="split")
for name in seconds_by_split
}
)
retried = sum(1 for row in review if row["attempt"] == 1)
columns = dataset.select_columns(["voice_id", "sim_to_anchor", "text", "duration_seconds", "expression"]).to_list()
plain_rows = [row for row in columns if not row["expression"]]
stats = {
"generated": len(sentences) * len(voices),
"clips": len(dataset),
"hours": sum(seconds_by_split.values()) / 3600,
"retried": retried,
"dropped": len(review) - retried,
"rejection_reasons": dict(reasons_count),
"splits": {
name: {"clips": len(splits[name]), "hours": seconds / 3600} for name, seconds in seconds_by_split.items()
},
"by_voice": {
voice.voice_id: {
"clips": sum(1 for row in columns if row["voice_id"] == voice.voice_id),
"sim_to_anchor_mean": round(
float(np.mean([row["sim_to_anchor"] for row in columns if row["voice_id"] == voice.voice_id])), 3
),
}
for voice in voices
},
"words_per_sec_mean": round(
float(np.mean([len(row["text"].split()) / row["duration_seconds"] for row in plain_rows])), 2
),
"expression_clips": dict(Counter(row["expression"] for row in columns if row["expression"])),
"expressions_first_attempt": expression_stats(first_attempts, args.min_event_score),
}
print(json.dumps(stats, indent=2))
if args.dry_run:
return
splits.push_to_hub(args.repo, private=True, max_shard_size="500MB")
api = HfApi()
files = {
"review.jsonl": "".join(json.dumps(row) + "\n" for row in review),
"voices.json": json.dumps(
{v.voice_id: {"description": v.description, "anchor_text": v.anchor_text} for v in voices}, indent=2
),
"stats.json": json.dumps(stats, indent=2),
}
for path, content in files.items():
api.upload_file(path_or_fileobj=content.encode(), path_in_repo=path, repo_id=args.repo, repo_type="dataset")
print(f"pushed {len(dataset)} clips to https://huggingface.co/datasets/{args.repo}")
if __name__ == "__main__":
main()