Skip to content

Voice isolation — separating clean speech from background noise and mixed audio.

Python
10.5 KB
Raw Blame
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cell-00",
   "metadata": {},
   "source": [
    "# Clean up a noisy recording with Inworld Voice Isolator\n",
    "\n",
    "This notebook takes a noisy speech recording, removes what is around the voice, and lets you hear the result next to the original. It then does the same for a recording of your own.\n",
    "\n",
    "You will:\n",
    "\n",
    "1. Install the package and check this machine.\n",
    "2. Load the offline model (its weights download on first use).\n",
    "3. Run the bundled noisy sample through it.\n",
    "4. Listen to the original and the cleaned audio side by side.\n",
    "5. Swap in your own recording and save the output.\n",
    "\n",
    "**What you need**\n",
    "\n",
    "- Python 3.10 or later and PyTorch 2.1 or later.\n",
    "- About 260 MB of disk for the offline model.\n",
    "- A GPU is optional. The model is tested on NVIDIA A100, H100, B200 and B300 GPUs and on CPU; smaller GPUs are not tested yet. On an Apple-silicon Mac it uses the Metal GPU with PyTorch 2.6 or later. On CPU it works, more slowly.\n",
    "\n",
    "This notebook covers offline cleanup of recorded audio. For live audio, see the streaming section of the [README](https://github.com/inworld-ai/voice-isolator#streaming)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-01",
   "metadata": {},
   "source": [
    "## 1. Install and check the machine\n",
    "\n",
    "Inside a clone of the repository this installs the checkout. Anywhere else (Colab, for example) it installs the release from PyPI. If the package is already installed in this environment, the cell leaves it alone."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-02",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pathlib\n",
    "\n",
    "REPO = pathlib.Path.cwd().parent\n",
    "IN_CLONE = (REPO / \"src\" / \"inworld\" / \"voice_isolation\").is_dir()\n",
    "\n",
    "try:\n",
    "    from inworld import voice_isolation\n",
    "    print(f\"inworld-voice-isolation {voice_isolation.__version__} is already installed.\")\n",
    "except ImportError:\n",
    "    if IN_CLONE:\n",
    "        %pip install -q \"{REPO}\"\n",
    "    else:\n",
    "        %pip install -q inworld-voice-isolation"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-03",
   "metadata": {},
   "source": [
    "`voice-isolate-doctor` reports the Python and PyTorch versions and the device inference will use. It prints one line per check, starting with `OK`, `INFO`, `WARN` or `FAIL`; a `FAIL` line names what to fix. This quick form uses no network and loads no model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-04",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "\n",
    "!\"{sys.executable}\" -m inworld.voice_isolation.doctor"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-05",
   "metadata": {},
   "source": [
    "## 2. Load the model\n",
    "\n",
    "The first run downloads the offline model, `voice-isolator-v1` (256 MB), from [huggingface.co/inworld/voice-isolator](https://huggingface.co/inworld/voice-isolator) into the Hugging Face cache and verifies its checksum. No account or sign-in is needed. Later runs load it from the cache.\n",
    "\n",
    "Code and weights are Apache-2.0."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-06",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "import torch\n",
    "from IPython.display import Audio, display\n",
    "\n",
    "from inworld import voice_isolation\n",
    "\n",
    "isolator = voice_isolation.VoiceIsolator(\"inworld/voice-isolator\")\n",
    "print(f\"Model loaded on: {isolator.device}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-07",
   "metadata": {},
   "source": [
    "## 3. Clean the bundled sample\n",
    "\n",
    "The sample is 9 seconds of read speech (from LibriSpeech, CC BY 4.0) mixed with a low electrical hum and three sharp taps.\n",
    "\n",
    "`isolate` returns the voice at the input's sample rate, length and level. Subtracting it from the input gives what the model removed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-08",
   "metadata": {},
   "outputs": [],
   "source": [
    "SAMPLE_URL = (\"https://raw.githubusercontent.com/inworld-ai/voice-isolator/\"\n",
    "              \"main/demo/examples/sample_15.wav\")\n",
    "\n",
    "sample = REPO / \"demo\" / \"examples\" / \"sample_15.wav\"\n",
    "if not sample.is_file():\n",
    "    import urllib.request\n",
    "    sample = pathlib.Path(\"sample_15.wav\")\n",
    "    urllib.request.urlretrieve(SAMPLE_URL, sample)\n",
    "\n",
    "\n",
    "def clean(path):\n",
    "    \"\"\"Returns (original, voice, background, sample_rate) for one file.\"\"\"\n",
    "    wav, sample_rate = voice_isolation.load_audio(str(path))\n",
    "    start = time.perf_counter()\n",
    "    voice = isolator.isolate(wav, sample_rate).cpu()\n",
    "    elapsed = time.perf_counter() - start\n",
    "    seconds = len(wav) / sample_rate\n",
    "    print(f\"{pathlib.Path(path).name}: {seconds:.1f} s of audio cleaned in \"\n",
    "          f\"{elapsed:.1f} s ({seconds / elapsed:.1f}x real time)\")\n",
    "    return wav, voice, wav - voice, sample_rate\n",
    "\n",
    "\n",
    "original, voice, background, sample_rate = clean(sample)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-09",
   "metadata": {},
   "source": [
    "The first call on a GPU includes one-time warm-up, so run the cell again for a representative speed.\n",
    "\n",
    "## 4. Listen side by side\n",
    "\n",
    "The players keep the true levels (no normalization), so loudness is comparable between them.\n",
    "\n",
    "What to listen for:\n",
    "\n",
    "- **Noise.** Are the hum and the taps gone, including in the pauses between words?\n",
    "- **Speech.** Does the voice still sound natural? Check consonants and word endings. Breaths and other non-verbal sounds are kept on purpose.\n",
    "- **Removed background.** It should hold the noise and little or no voice. Voice you hear here is voice the model took out."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-10",
   "metadata": {},
   "outputs": [],
   "source": [
    "def play(label, wav):\n",
    "    \"\"\"Shows a player at the waveform's own level, without normalization.\"\"\"\n",
    "    print(label)\n",
    "    display(Audio(wav.clamp(-1, 1).numpy(), rate=sample_rate, normalize=False))\n",
    "\n",
    "\n",
    "play(\"Original\", original)\n",
    "play(\"Cleaned voice\", voice)\n",
    "play(\"Removed background\", background)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-11",
   "metadata": {},
   "source": [
    "## 5. Try your own recording\n",
    "\n",
    "Set `MY_RECORDING` to a file on this machine and run the cell. In Colab, upload the file with the folder icon on the left first.\n",
    "\n",
    "- **Formats:** WAV, FLAC, OGG and MP3 (anything the `soundfile` library reads). Convert other formats first, for example `ffmpeg -i input.m4a input.wav`.\n",
    "- **Sample rate and channels:** any sample rate works. Stereo is mixed down to mono, and the output is mono.\n",
    "- **Length:** long files are processed in 8-second chunks that overlap by 2 seconds and are crossfaded.\n",
    "\n",
    "The cell writes two float32 WAVs beside your file: `<name>_clean.wav` and `<name>_clean_background.wav`. Your audio stays on this machine."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-12",
   "metadata": {},
   "outputs": [],
   "source": [
    "MY_RECORDING = \"\"  # for example \"recordings/call.wav\"\n",
    "\n",
    "if MY_RECORDING:\n",
    "    source = pathlib.Path(MY_RECORDING).expanduser()\n",
    "    original, voice, background, sample_rate = clean(source)\n",
    "\n",
    "    voice_path = source.with_name(f\"{source.stem}_clean.wav\")\n",
    "    background_path = source.with_name(f\"{source.stem}_clean_background.wav\")\n",
    "    voice_isolation.save_audio(str(voice_path), voice, sample_rate,\n",
    "                               subtype=\"FLOAT\")\n",
    "    voice_isolation.save_audio(str(background_path), background, sample_rate,\n",
    "                               subtype=\"FLOAT\")\n",
    "    print(f\"Saved {voice_path} and {background_path}\")\n",
    "\n",
    "    play(\"Original\", original)\n",
    "    play(\"Cleaned voice\", voice)\n",
    "    play(\"Removed background\", background)\n",
    "else:\n",
    "    print(\"Set MY_RECORDING to the path of an audio file, then run this cell.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-13",
   "metadata": {},
   "source": [
    "## Use it in your own code\n",
    "\n",
    "The whole pipeline is a few lines:\n",
    "\n",
    "```python\n",
    "from inworld import voice_isolation\n",
    "\n",
    "isolator = voice_isolation.VoiceIsolator(\"inworld/voice-isolator\")  # load once, reuse\n",
    "wav, sample_rate = voice_isolation.load_audio(\"noisy.wav\")\n",
    "voice = isolator.isolate(wav, sample_rate)\n",
    "voice_isolation.save_audio(\"clean.wav\", voice, sample_rate)\n",
    "```\n",
    "\n",
    "Or from a terminal, for one file or a whole folder:\n",
    "\n",
    "```bash\n",
    "voice-isolate noisy.wav clean.wav\n",
    "voice-isolate recordings/ cleaned/\n",
    "```\n",
    "\n",
    "**Cleaning audio before speech-to-text?** Ask for the rate your STT model expects, and the voice comes back resampled:\n",
    "\n",
    "```python\n",
    "voice_16k = isolator.isolate(wav, sample_rate, output_sample_rate=16000)\n",
    "```\n",
    "\n",
    "Where to go next:\n",
    "\n",
    "- [README](https://github.com/inworld-ai/voice-isolator#quick-start): CLI options and the streaming model for live audio.\n",
    "- [Interactive demo](https://github.com/inworld-ai/voice-isolator/blob/main/demo/README.md): a browser page with file upload and live microphone.\n",
    "- [Model card](https://github.com/inworld-ai/voice-isolator/blob/main/MODEL_CARD.md): what the model does and does not do, benchmark results and training data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "99b362f3-0b23-4e3f-8aee-a13b22f609cc",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}