Claude Code for SpeechBrain: Speech Processing Toolkit — Claude Skills 360 Blog
Blog / AI / Claude Code for SpeechBrain: Speech Processing Toolkit
AI

Claude Code for SpeechBrain: Speech Processing Toolkit

Published: October 19, 2027
Read time: 5 min read
By: Claude Skills 360

SpeechBrain is a PyTorch speech processing toolkit. pip install speechbrain. Speaker verification: from speechbrain.pretrained import SpeakerRecognition, model = SpeakerRecognition.from_hparams(source="speechbrain/spkrec-ecapa-voxceleb"), score, prediction = model.verify_files("spk1.wav", "spk2.wav"). Speaker embedding: model = EncoderClassifier.from_hparams(source="speechbrain/spkrec-ecapa-voxceleb"), embeddings = model.encode_batch(wavs) — 192-dim x-vectors. Language ID: model = EncoderClassifier.from_hparams(source="speechbrain/lang-id-voxlingua107-ecapa"), prediction, score = model.classify_file("audio.wav"). Speech separation: from speechbrain.pretrained import SepformerSeparation, model = SepformerSeparation.from_hparams(source="speechbrain/sepformer-wham"), est_sources = model.separate_file("noisy.wav"). ASR: from speechbrain.pretrained import EncoderDecoderASR, asr = EncoderDecoderASR.from_hparams(source="speechbrain/asr-crdnn-rnnlm-librispeech"), transcript = asr.transcribe_file("audio.wav"). TTS: from speechbrain.pretrained import Tacotron2, HIFIGAN, tacotron = Tacotron2.from_hparams(source="speechbrain/tts-tacotron2-ljspeech"), mel_output, _, _ = tacotron.encode_text("Hello world"), hifigan = HIFIGAN.from_hparams(source="speechbrain/tts-hifigan-ljspeech"), waveforms = hifigan.decode_batch(mel_output). Custom training: from speechbrain.core import Brain, subclass with compute_forward, compute_objectives, call brain.fit(epoch_counter, train_set, valid_set). Claude Code generates SpeechBrain speaker verification, speech enhancement, custom training recipes, and audio processing pipelines.

CLAUDE.md for SpeechBrain

## SpeechBrain Stack
- Version: speechbrain >= 1.0
- Pretrained: ModelClass.from_hparams(source="speechbrain/model-name", savedir="./pretrained")
- Speaker: SpeakerRecognition.verify_files(s1, s2) | EncoderClassifier.encode_batch(wavs)
- Lang ID: EncoderClassifier(source="lang-id-*").classify_file(path)
- Separation: SepformerSeparation.separate_file(path) → est_sources tensor
- ASR: EncoderDecoderASR.transcribe_file(path) | transcribe_batch(paths)
- TTS: Tacotron2.encode_text(text) → mel | HIFIGAN.decode_batch(mel) → waveform
- Custom: subclass Brain → compute_forward + compute_objectives → brain.fit(...)
- Audio: torchaudio.load(path) → (waveform, sample_rate)

SpeechBrain Processing Pipeline

# audio/speechbrain_pipeline.py — speech processing with SpeechBrain
from __future__ import annotations
import os
from pathlib import Path
from typing import Optional

import torch
import torchaudio
import numpy as np


# ── 1. Speaker verification and identification ────────────────────────────────

class SpeakerSystem:
    """
    Speaker recognition: verification (same/different person) and
    identification (who is speaking from a set of enrolled speakers).
    """

    def __init__(
        self,
        savedir:    str = "./pretrained/speaker",
        device:     str = "cpu",
    ):
        from speechbrain.pretrained import SpeakerRecognition, EncoderClassifier

        self.device    = device
        self.savedir   = savedir

        # Verification model
        self.verifier  = SpeakerRecognition.from_hparams(
            source="speechbrain/spkrec-ecapa-voxceleb",
            savedir=os.path.join(savedir, "verification"),
            run_opts={"device": device},
        )
        # Embedding encoder (ECAPA-TDNN)
        self.encoder   = EncoderClassifier.from_hparams(
            source="speechbrain/spkrec-ecapa-voxceleb",
            savedir=os.path.join(savedir, "encoder"),
            run_opts={"device": device},
        )
        self._enrolled: dict[str, torch.Tensor] = {}

    def verify(self, file1: str, file2: str, threshold: float = 0.25) -> dict:
        """
        Verify if two audio files are from the same speaker.
        Returns score ∈ [-1, 1]; score > threshold → same speaker.
        """
        score, prediction = self.verifier.verify_files(file1, file2)
        s = float(score.squeeze())
        return {
            "score":       s,
            "same_speaker": s > threshold,
            "confidence":  abs(s),
        }

    def embed(self, audio_path: str) -> torch.Tensor:
        """Extract 192-dim ECAPA speaker embedding from audio file."""
        signal, sr = torchaudio.load(audio_path)
        if sr != 16000:
            signal = torchaudio.functional.resample(signal, sr, 16000)
        with torch.no_grad():
            embedding = self.encoder.encode_batch(signal.unsqueeze(0))
        return embedding.squeeze()   # (192,)

    def enroll(self, speaker_id: str, audio_paths: list[str]):
        """Enroll a speaker by averaging embeddings from multiple recordings."""
        embeddings = [self.embed(p) for p in audio_paths]
        self._enrolled[speaker_id] = torch.stack(embeddings).mean(dim=0)
        # L2 normalize
        self._enrolled[speaker_id] = (
            self._enrolled[speaker_id] /
            self._enrolled[speaker_id].norm()
        )
        print(f"Enrolled speaker '{speaker_id}' from {len(audio_paths)} recordings")

    def identify(self, audio_path: str, threshold: float = 0.3) -> tuple[str, float]:
        """
        Identify the speaker from enrolled speakers.
        Returns (speaker_id, score) or ("unknown", score).
        """
        if not self._enrolled:
            raise RuntimeError("No speakers enrolled. Call enroll() first.")

        query_emb = self.embed(audio_path)
        query_emb = query_emb / query_emb.norm()

        best_id    = "unknown"
        best_score = float("-inf")

        for spk_id, ref_emb in self._enrolled.items():
            score = float(torch.dot(query_emb, ref_emb))
            if score > best_score:
                best_score = score
                best_id    = spk_id

        if best_score < threshold:
            best_id = "unknown"

        return best_id, best_score


# ── 2. Language identification ────────────────────────────────────────────────

class LanguageIdentifier:
    """Identify the language spoken in an audio file (107 languages)."""

    def __init__(self, savedir: str = "./pretrained/langid", device: str = "cpu"):
        from speechbrain.pretrained import EncoderClassifier

        self.model = EncoderClassifier.from_hparams(
            source="speechbrain/lang-id-voxlingua107-ecapa",
            savedir=savedir,
            run_opts={"device": device},
        )

    def identify(self, audio_path: str) -> dict:
        """Identify language and return top-5 probabilities."""
        out_prob, score, index, text_lab = self.model.classify_file(audio_path)
        lang_code = text_lab[0]

        # Get top-5 languages
        probs = torch.nn.functional.softmax(out_prob.squeeze(), dim=0)
        top5  = torch.topk(probs, 5)
        top5_langs = {
            self.model.hparams.label_encoder.ind2lab[idx.item()]: float(prob)
            for idx, prob in zip(top5.indices, top5.values)
        }

        return {
            "language": lang_code,
            "score":    float(score.squeeze()),
            "top5":     top5_langs,
        }


# ── 3. Speech separation and enhancement ─────────────────────────────────────

class SpeechEnhancer:
    """
    Speech separation and noise reduction with SepFormer.
    Separates mixed speech or removes background noise.
    """

    def __init__(self, savedir: str = "./pretrained/separation", device: str = "cpu"):
        from speechbrain.pretrained import SepformerSeparation

        # WHAM model: speech + noise separation
        self.separator = SepformerSeparation.from_hparams(
            source="speechbrain/sepformer-wham",
            savedir=savedir,
            run_opts={"device": device},
        )

    def separate(self, audio_path: str, output_dir: str = "./enhanced") -> list[str]:
        """
        Separate audio into clean speech source(s).
        Returns list of output file paths.
        """
        Path(output_dir).mkdir(parents=True, exist_ok=True)
        est_sources = self.separator.separate_file(audio_path)
        # est_sources: (time, n_sources) tensor

        output_paths = []
        stem = Path(audio_path).stem
        for i in range(est_sources.shape[-1]):
            source  = est_sources[:, :, i].T   # (1, time)
            out_path = os.path.join(output_dir, f"{stem}_source{i+1}.wav")
            torchaudio.save(out_path, source.cpu(), 8000)   # WHAM uses 8kHz
            output_paths.append(out_path)
            print(f"Source {i+1} saved: {out_path}")

        return output_paths

    def enhance_batch(
        self,
        audio_paths: list[str],
        output_dir:  str = "./enhanced",
    ) -> list[str]:
        """Batch speech enhancement."""
        all_outputs = []
        for path in audio_paths:
            outputs = self.separate(path, output_dir)
            all_outputs.extend(outputs)
        return all_outputs


# ── 4. Automatic speech recognition ──────────────────────────────────────────

class ASRSystem:
    """Encoder-decoder ASR with language model rescoring."""

    def __init__(self, savedir: str = "./pretrained/asr", device: str = "cpu"):
        from speechbrain.pretrained import EncoderDecoderASR

        self.asr = EncoderDecoderASR.from_hparams(
            source="speechbrain/asr-crdnn-rnnlm-librispeech",
            savedir=savedir,
            run_opts={"device": device},
        )

    def transcribe(self, audio_path: str) -> str:
        """Transcribe a single audio file."""
        return self.asr.transcribe_file(audio_path)

    def transcribe_batch(self, audio_paths: list[str]) -> list[str]:
        """Transcribe multiple files."""
        return [self.asr.transcribe_file(p) for p in audio_paths]


# ── 5. Text-to-speech ─────────────────────────────────────────────────────────

class TTSSystem:
    """Tacotron2 + HiFi-GAN TTS pipeline."""

    def __init__(
        self,
        tts_savedir:    str = "./pretrained/tts-tacotron2",
        vocoder_savedir: str = "./pretrained/tts-hifigan",
        device:          str = "cpu",
    ):
        from speechbrain.pretrained import Tacotron2, HIFIGAN

        self.tacotron = Tacotron2.from_hparams(
            source="speechbrain/tts-tacotron2-ljspeech",
            savedir=tts_savedir,
            run_opts={"device": device},
        )
        self.hifigan = HIFIGAN.from_hparams(
            source="speechbrain/tts-hifigan-ljspeech",
            savedir=vocoder_savedir,
            run_opts={"device": device},
        )
        self.sample_rate = 22050

    def synthesize(self, text: str) -> torch.Tensor:
        """Synthesize speech from text. Returns waveform tensor."""
        with torch.no_grad():
            mel_output, mel_length, alignment = self.tacotron.encode_text(text)
            waveforms = self.hifigan.decode_batch(mel_output)
        return waveforms.squeeze(1)   # (1, time)

    def save_audio(self, text: str, output_path: str = "output.wav") -> str:
        """Synthesize and save to WAV file."""
        waveforms = self.synthesize(text)
        torchaudio.save(output_path, waveforms.cpu(), self.sample_rate)
        print(f"Saved: {output_path} ({waveforms.shape[-1]/self.sample_rate:.1f}s)")
        return output_path

    def batch_synthesize(
        self,
        texts:      list[str],
        output_dir: str = "./tts_output",
    ) -> list[str]:
        """Synthesize multiple texts."""
        Path(output_dir).mkdir(parents=True, exist_ok=True)
        paths = []
        for i, text in enumerate(texts):
            out_path = os.path.join(output_dir, f"utterance_{i:04d}.wav")
            self.save_audio(text, out_path)
            paths.append(out_path)
        return paths


# ── 6. Audio utilities ────────────────────────────────────────────────────────

def load_audio_16k(audio_path: str) -> tuple[torch.Tensor, int]:
    """Load audio and resample to 16kHz mono."""
    signal, sr = torchaudio.load(audio_path)
    if signal.shape[0] > 1:
        signal = signal.mean(dim=0, keepdim=True)   # Stereo → mono
    if sr != 16000:
        signal = torchaudio.functional.resample(signal, sr, 16000)
    return signal, 16000


def compute_snr(clean: torch.Tensor, noisy: torch.Tensor) -> float:
    """Compute Signal-to-Noise Ratio in dB."""
    noise   = noisy - clean
    signal_power = (clean ** 2).mean()
    noise_power  = (noise  ** 2).mean()
    if noise_power == 0:
        return float("inf")
    return float(10 * torch.log10(signal_power / noise_power))


# ── Demo ──────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    # TTS demo — no audio input needed
    tts = TTSSystem(device="cpu")
    tts.save_audio(
        "SpeechBrain provides a clean interface for speech processing tasks.",
        "speechbrain_demo.wav",
    )
    print("TTS demo complete: speechbrain_demo.wav")

    # ASR demo
    asr = ASRSystem(device="cpu")
    transcript = asr.transcribe("speechbrain_demo.wav")
    print(f"Transcript: {transcript}")

    # Language ID demo
    lang_id = LanguageIdentifier(device="cpu")
    result  = lang_id.identify("speechbrain_demo.wav")
    print(f"Language: {result['language']} (score={result['score']:.3f})")
    print(f"Top 5: {result['top5']}")

For the Whisper alternative when needing multilingual transcription with the highest accuracy on challenging real-world audio across all languages — Whisper excels at transcription while SpeechBrain’s speaker recognition (ECAPA-TDNN embeddings, cosine similarity enrollment), speech separation (SepFormer), and 107-language identification provide capabilities that Whisper doesn’t cover, making SpeechBrain the right toolkit for multi-speaker, speaker-aware, or speech enhancement applications. For the TorchAudio alternative when adding audio augmentations, spectral features, and codec transforms via a thin PyTorch-native library — TorchAudio provides low-level audio operations while SpeechBrain adds complete pretrained pipelines (ECAPA speaker embeddings, SepFormer separation, Tacotron2+HiFi-GAN TTS) with a uniform from_hparams(source=...) loader and a full training framework for fine-tuning on custom datasets. The Claude Skills 360 bundle includes SpeechBrain skill sets covering speaker verification and enrollment, language identification, speech separation, ASR transcription, TTS synthesis, custom Brain training loops, and audio utility functions. Start with the free tier to try speech processing pipeline generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free