#!/usr/bin/env python3 """ yt-builder: Build a voice-cloning profile from a YouTube video. Downloads a YouTube video, extracts & trims audio, transcribes with faster-whisper, and writes a ready-to-use profile (voice.wav + script.txt) suitable for Qwen-TTS voice cloning. Usage: python build_profile.py [options] Example: python build_profile.py \ "https://www.youtube.com/watch?v=ABC123" my-speaker \ --max-duration 30 --start 10 --end 40 \ --profiles-dir ../profiles """ from __future__ import annotations import argparse import logging import os import re import subprocess import sys import textwrap from pathlib import Path import shutil import numpy as np import soundfile as sf from faster_whisper import WhisperModel, BatchedInferencePipeline log = logging.getLogger("yt-builder") # ─── Constants ──────────────────────────────────────────────────────────────── SAMPLE_RATE = 16_000 # Qwen-TTS expects 16 kHz mono WAV MAX_PROFILE_SECONDS = 30 # sensible default for voice-clone reference # ─── YouTube download ──────────────────────────────────────────────────────── def download_audio(url: str, out_dir: Path, *, cookies: str | None = None) -> Path: """Download best audio from *url* via yt-dlp, return path to file.""" out_dir.mkdir(parents=True, exist_ok=True) out_template = str(out_dir / "source.%(ext)s") cmd = [ "yt-dlp", "--ignore-config", "--no-playlist", "-f", "bestaudio", "-o", out_template, "--print", "after_move:filepath", "--js-runtimes", "node", "--remote-components", "ejs:github", ] if cookies: cmd += ["--cookies", cookies] cmd.append(url) log.info("Downloading audio from %s …", url) result = subprocess.run(cmd, capture_output=True, text=True, check=True) downloaded = result.stdout.strip().splitlines()[-1] log.info("Downloaded: %s", downloaded) return Path(downloaded) # ─── Audio processing ──────────────────────────────────────────────────────── def extract_and_trim( audio_path: Path, out_wav: Path, *, max_duration: float, start: float | None = None, end: float | None = None, ) -> Path: """Convert to 16 kHz mono WAV, optionally trimming to [start, end]. The output is capped to *max_duration* seconds. """ cmd = ["ffmpeg", "-y", "-i", str(audio_path)] if start is not None: cmd += ["-ss", str(start)] if end is not None: cmd += ["-to", str(end)] cmd += [ "-t", str(max_duration), "-ar", str(SAMPLE_RATE), "-ac", "1", "-c:a", "pcm_s16le", str(out_wav), ] log.info("Extracting WAV (sr=%d, mono, max %.1fs) …", SAMPLE_RATE, max_duration) subprocess.run(cmd, check=True, capture_output=True) return out_wav # ─── Noise / music removal ──────────────────────────────────────────────────── def denoise_audio( wav_path: Path, out_wav: Path, *, method: str = "demucs", device: str = "cuda", ) -> Path: """Remove background music or noise from *wav_path*. Methods ------- demucs – Meta's Hybrid Transformer source separation. Isolates vocals from music/instruments. Best when the background is actual music. noisereduce – Lightweight spectral-gating noise reduction. Good for ambient hiss, hum, or light background noise. """ if method == "demucs": return _denoise_demucs(wav_path, out_wav, device=device) if method == "noisereduce": return _denoise_noisereduce(wav_path, out_wav) raise ValueError(f"Unknown denoise method: {method!r} (choose 'demucs' or 'noisereduce')") def _denoise_demucs(wav_path: Path, out_wav: Path, *, device: str = "cuda") -> Path: """Separate vocals using demucs (htdemucs model) via Python API.""" import torch from demucs.apply import apply_model from demucs.pretrained import get_model log.info("Loading demucs htdemucs model …") model = get_model("htdemucs") model.to(device) # Load audio via soundfile (avoids torchcodec dependency) data, sr = sf.read(str(wav_path), dtype="float32") if data.ndim > 1: data = data.mean(axis=1) # Convert to torch tensor [channels, samples] — demucs expects stereo wav = torch.from_numpy(data).unsqueeze(0).repeat(2, 1) ref = wav.mean(0) wav = (wav - ref.mean()) / ref.std() log.info("Running demucs vocal separation …") with torch.no_grad(): sources = apply_model(model, wav[None].to(device), progress=True)[0] # Find the vocals stem index vocal_idx = model.sources.index("vocals") vocals = sources[vocal_idx] # [channels, samples] # Undo normalisation vocals = vocals * ref.std() + ref.mean() # Convert to mono numpy and save via soundfile (avoids torchcodec issue) vocals_np = vocals.cpu().numpy().mean(axis=0) # Resample to target sample rate if needed if sr != SAMPLE_RATE: duration = len(vocals_np) / sr num_samples = int(duration * SAMPLE_RATE) indices = np.linspace(0, len(vocals_np) - 1, num_samples).astype(int) vocals_np = vocals_np[indices] sf.write(str(out_wav), vocals_np, SAMPLE_RATE, subtype="PCM_16") log.info("Demucs vocal isolation → %s", out_wav) return out_wav def _denoise_noisereduce(wav_path: Path, out_wav: Path) -> Path: """Spectral-gating noise reduction via noisereduce.""" import noisereduce as nr data, sr = sf.read(str(wav_path), dtype="float32") if data.ndim > 1: data = data.mean(axis=1) log.info("Running noisereduce spectral gating …") reduced = nr.reduce_noise(y=data, sr=sr, prop_decrease=0.8, stationary=False) sf.write(str(out_wav), reduced, sr, subtype="PCM_16") log.info("Noise reduction → %s", out_wav) return out_wav # ─── Transcription ─────────────────────────────────────────────────────────── def transcribe( wav_path: Path, *, model_size: str = "large-v3", device: str = "cuda", compute_type: str = "float16", language: str | None = None, ) -> tuple[list[dict], str]: """Transcribe *wav_path* with faster-whisper. Returns (segments, detected_language). """ log.info("Loading faster-whisper model %s on %s …", model_size, device) whisper = WhisperModel(model_size, device=device, compute_type=compute_type) pipeline = BatchedInferencePipeline(model=whisper) segments_gen, info = pipeline.transcribe( str(wav_path), batch_size=16, language=language, word_timestamps=True, vad_filter=True, ) detected_lang = info.language or "unknown" log.info("Detected language: %s (p=%.2f)", detected_lang, info.language_probability) segments: list[dict] = [] for seg in segments_gen: segments.append({ "start": seg.start, "end": seg.end, "text": seg.text.strip(), }) log.info("Transcription complete: %d segments", len(segments)) return segments, detected_lang # ─── SRT formatting ───────────────────────────────────────────────────────── def _fmt_ts(s: float) -> str: h = int(s // 3600) m = int((s % 3600) // 60) sec = int(s % 60) ms = int(round((s % 1) * 1000)) return f"{h:02d}:{m:02d}:{sec:02d},{ms:03d}" def build_srt(segments: list[dict]) -> str: lines: list[str] = [] for i, seg in enumerate(segments, 1): lines.append(str(i)) lines.append(f"{_fmt_ts(seg['start'])} --> {_fmt_ts(seg['end'])}") lines.append(seg["text"]) lines.append("") return "\n".join(lines) # ─── Voice postprocessing for Qwen-TTS ────────────────────────────────────── def postprocess_voice(wav_path: Path) -> Path: """Ensure the WAV is optimal for Qwen-TTS voice cloning. Qwen-TTS expects 16 kHz, mono, 16-bit PCM WAV. We also trim leading/trailing silence and normalise peak amplitude. """ data, sr = sf.read(str(wav_path), dtype="float32") # Ensure mono if data.ndim > 1: data = data.mean(axis=1) # Resample if needed (shouldn't be, but safety net) if sr != SAMPLE_RATE: duration = len(data) / sr num_samples = int(duration * SAMPLE_RATE) indices = np.linspace(0, len(data) - 1, num_samples).astype(int) data = data[indices] sr = SAMPLE_RATE # Trim silence (threshold-based) threshold = 0.01 above = np.where(np.abs(data) > threshold)[0] if len(above) > 0: # Keep a small 0.05 s pad on each side pad = int(0.05 * sr) start = max(0, above[0] - pad) end = min(len(data), above[-1] + pad) data = data[start:end] # Peak-normalise to -1 dB peak = np.max(np.abs(data)) if peak > 0: target = 10 ** (-1.0 / 20) # ≈ 0.891 data = data * (target / peak) sf.write(str(wav_path), data, sr, subtype="PCM_16") log.info("Postprocessed voice: %s (%.1fs, %d Hz)", wav_path, len(data) / sr, sr) return wav_path # ─── Profile builder ──────────────────────────────────────────────────────── def _safe_name(name: str) -> str: """Lowercase, ASCII-safe directory name.""" name = re.sub(r"[^\w\s-]", "", name.lower()) return re.sub(r"[\s]+", "-", name).strip("-") def build_profile( segments: list[dict], voice_wav: Path, profile_dir: Path, ) -> Path: """Write voice.wav + script.txt into *profile_dir*.""" profile_dir.mkdir(parents=True, exist_ok=True) # script.txt — plain text, one sentence per line script_lines: list[str] = [] for seg in segments: text = seg["text"].strip() if text: script_lines.append(text) script_text = "\n".join(script_lines) + "\n" script_path = profile_dir / "script.txt" script_path.write_text(script_text, encoding="utf-8") log.info("Wrote script: %s (%d lines)", script_path, len(script_lines)) # voice.wav — copy the postprocessed WAV dest_wav = profile_dir / "voice.wav" if voice_wav.resolve() != dest_wav.resolve(): shutil.copy2(voice_wav, dest_wav) log.info("Wrote voice: %s", dest_wav) # Clean up: remove .work dir and any non-essential files work_dir = profile_dir / ".work" if work_dir.exists(): shutil.rmtree(work_dir) log.info("Cleaned up work directory: %s", work_dir) for f in profile_dir.iterdir(): if f.name not in ("voice.wav", "script.txt"): f.unlink() if f.is_file() else shutil.rmtree(f) log.info("Removed: %s", f) return profile_dir # ─── CLI ───────────────────────────────────────────────────────────────────── def parse_args(argv: list[str] | None = None) -> argparse.Namespace: p = argparse.ArgumentParser( description="Build a Qwen-TTS voice-clone profile from a YouTube video.", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=textwrap.dedent("""\ Example: python build_profile.py \\ "https://www.youtube.com/watch?v=ABC123" my-speaker \\ --max-duration 25 --start 5 --end 35 """), ) p.add_argument("url", help="YouTube video URL") p.add_argument("profile_name", help="Name for the new profile directory") p.add_argument( "--max-duration", type=float, default=MAX_PROFILE_SECONDS, help="Maximum audio duration in seconds (default: %(default)s)", ) p.add_argument("--start", type=float, default=None, help="Start offset in the audio (seconds)") p.add_argument("--end", type=float, default=None, help="End offset in the audio (seconds)") p.add_argument( "--profiles-dir", type=Path, default=Path(__file__).resolve().parent.parent / "profiles", help="Parent directory for profiles (default: ../profiles)", ) p.add_argument("--whisper-model", default="large-v3", help="Whisper model size (default: large-v3)") p.add_argument("--device", default="cuda", choices=["cuda", "cpu"], help="Compute device") p.add_argument("--compute-type", default="float16", help="Whisper compute type (default: float16)") p.add_argument("--language", default=None, help="Force source language code (e.g. en, ar)") # ── Denoise / music removal ── p.add_argument( "--denoise", action="store_true", default=False, help="Remove background music/noise before transcription & profile creation", ) p.add_argument( "--denoise-method", default="demucs", choices=["demucs", "noisereduce"], help="Denoising method: 'demucs' isolates vocals from music (best for music), " "'noisereduce' applies spectral-gating (best for ambient noise). Default: demucs", ) p.add_argument("--cookies", default=None, help="Path to a Netscape cookies.txt file for yt-dlp authentication.") p.add_argument("-v", "--verbose", action="store_true", help="Verbose logging") return p.parse_args(argv) def main(argv: list[str] | None = None) -> None: args = parse_args(argv) logging.basicConfig( level=logging.DEBUG if args.verbose else logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s", ) profile_name = _safe_name(args.profile_name) profile_dir = args.profiles_dir / profile_name work_dir = profile_dir / ".work" log.info("Building profile '%s' → %s", profile_name, profile_dir) # 1) Download raw_audio = download_audio(args.url, work_dir, cookies=args.cookies) # 2) Extract & trim trimmed_wav = work_dir / "voice_trimmed.wav" extract_and_trim( raw_audio, trimmed_wav, max_duration=args.max_duration, start=args.start, end=args.end, ) # 3) Denoise / remove background music (optional) if args.denoise: denoised_wav = work_dir / "voice_denoised.wav" denoise_audio( trimmed_wav, denoised_wav, method=args.denoise_method, device=args.device, ) trimmed_wav = denoised_wav # 4) Transcribe segments, detected_lang = transcribe( trimmed_wav, model_size=args.whisper_model, device=args.device, compute_type=args.compute_type, language=args.language, ) if not segments: log.error("No speech detected — aborting.") sys.exit(1) # 5) Post-process voice postprocess_voice(trimmed_wav) # 6) Build profile build_profile(segments, trimmed_wav, profile_dir) log.info("✓ Profile ready at %s", profile_dir) log.info(" voice.wav — 16 kHz mono PCM, peak-normalised") log.info(" script.txt — %d lines", len(segments)) log.info("") log.info("Use with mazinger-dubber:") log.info(" mazinger-dubber dub