Download scripts/laughgen/splice.py from marcosremar2/prosatts-work: direct link, hf CLI and curl.
- Browser
- Download file 4.09 kB
-
https://huggingface.co/marcosremar2/prosatts-work/resolve/main/scripts/laughgen/splice.py
- Command line
-
hf download hf://marcosremar2/prosatts-work/scripts/laughgen/splice.py
-
curl -L -o splice.py https://huggingface.co/marcosremar2/prosatts-work/resolve/main/scripts/laughgen/splice.py
4.09 kB
| import json, sys | |
| from pathlib import Path | |
| import numpy as np, soundfile as sf, torch, torchaudio | |
| from transformers import pipeline | |
| from voxcpm import VoxCPM | |
| PROMPTS, SOUNDS, OUT = Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3]) | |
| RATE = 24000 | |
| GAP = np.zeros(int(0.08 * RATE), dtype=np.float32) | |
| SENTENCES = [ | |
| ("riso", "Você caiu da cadeira na frente de todo mundo?", "Eu não acredito!"), | |
| ("riso", "Ele chegou na festa com a camisa do avesso.", "Foi muito engraçado."), | |
| ("risinho", "Tá bom, tá bom, eu confesso.", "Fui eu que comi o último pedaço de bolo."), | |
| ("tosse", "Desculpa, eu estou meio gripado.", "Mas pode continuar, estou ouvindo."), | |
| ("tosse", "Então, como eu estava dizendo,", "a reunião começa às nove."), | |
| ] | |
| STYLES = {"riso": "(rindo)", "risinho": "(dando uma risadinha)", "tosse": "(tossindo)"} | |
| OUT.mkdir(parents=True, exist_ok=True) | |
| whisper = pipeline("automatic-speech-recognition", "openai/whisper-large-v3-turbo", torch_dtype=torch.float16, device="cuda") | |
| def energy_bounds(audio, start, end): | |
| frame = int(0.02 * RATE) | |
| piece = audio[start:end] | |
| loud = [i for i in range(0, max(len(piece) - frame, 0), frame) if np.sqrt(np.mean(piece[i:i + frame] ** 2)) > 0.02] | |
| return (start + loud[0], start + loud[-1] + frame) if loud else None | |
| def cut(path): | |
| audio, _ = sf.read(path, dtype="float32") | |
| heard = whisper({"raw": torchaudio.functional.resample(torch.from_numpy(audio), RATE, 16000).numpy(), "sampling_rate": 16000}, return_timestamps="word", generate_kwargs={"language": "en"}) | |
| words = [(int(c["timestamp"][0] * RATE), int((c["timestamp"][1] or c["timestamp"][0]) * RATE), c["text"].strip()) for c in heard["chunks"]] | |
| edges = [0] + [x for start, end, _ in words for x in (start, end)] + [len(audio)] | |
| gaps = sorted(zip(edges[::2], edges[1::2]), key=lambda gap: gap[1] - gap[0], reverse=True) | |
| for start, end in gaps: | |
| bounds = energy_bounds(audio, start, end) | |
| if bounds and bounds[1] - bounds[0] > int(0.25 * RATE): | |
| return audio[bounds[0]:bounds[1]], heard["text"].strip() | |
| return None, heard["text"].strip() | |
| sounds = json.loads((SOUNDS / "sounds.json").read_text()) | |
| for row in sounds: | |
| clip, heard = cut(SOUNDS / row["file"]) | |
| row["heard"] = heard | |
| row["cut_seconds"] = round(len(clip) / RATE, 2) if clip is not None else 0 | |
| if clip is not None: | |
| sf.write(OUT / f"cut_{row['file']}", clip, RATE) | |
| row["cut"] = f"cut_{row['file']}" | |
| print(row["file"], row["cut_seconds"], "s, ouvido:", heard, flush=True) | |
| model = VoxCPM.from_pretrained("openbmb/VoxCPM2", load_denoiser=False) | |
| def speak(text, reference): | |
| audio = model.generate(text=text, reference_wav_path=str(PROMPTS / reference), cfg_value=2.0, inference_timesteps=10) | |
| return torchaudio.functional.resample(torch.as_tensor(np.asarray(audio), dtype=torch.float32), model.tts_model.sample_rate, RATE).numpy() | |
| results = [] | |
| for index, (sound, before, after) in enumerate(SENTENCES): | |
| candidates = [r for r in sounds if r["sound"] == sound and r.get("cut") and 0.3 <= r["cut_seconds"] <= 2.5] | |
| choice = candidates[index % len(candidates)] if candidates else None | |
| reference = choice["reference"] if choice else "animado_00.wav" | |
| torch.manual_seed(index) | |
| parts = [speak(before, reference), GAP] | |
| if choice: | |
| parts += [sf.read(OUT / choice["cut"], dtype="float32")[0], GAP] | |
| parts.append(speak(after, reference)) | |
| sf.write(OUT / f"frase_{index}.wav", np.concatenate(parts), RATE) | |
| sf.write(OUT / f"vox_{index}.wav", speak(f"{STYLES[sound]}{before} {after}", reference), RATE) | |
| results.append({"index": index, "sound": sound, "text": f"{before} <{sound}> {after}", "spliced": f"frase_{index}.wav", "vox_only": f"vox_{index}.wav", "used": choice["cut"] if choice else None, "reference": reference}) | |
| print("frase", index, "com", choice["cut"] if choice else "nenhum som", flush=True) | |
| (OUT / "results.json").write_text(json.dumps({"sounds": sounds, "sentences": results}, ensure_ascii=False, indent=1)) | |
| print("SPLICE_DONE", flush=True) | |