Claude Code for NVIDIA NeMo: Speech and NLP Models — Claude Skills 360 Blog
Blog / AI / Claude Code for NVIDIA NeMo: Speech and NLP Models
AI

Claude Code for NVIDIA NeMo: Speech and NLP Models

Published: September 29, 2027
Read time: 5 min read
By: Claude Skills 360

NeMo builds speech and NLP models on NVIDIA hardware. pip install nemo_toolkit[all]. ASR inference: from nemo.collections.asr.models import EncDecCTCModelBPE, asr = EncDecCTCModelBPE.from_pretrained("nvidia/stt_en_conformer_ctc_large"), transcripts = asr.transcribe(["audio.wav"]). Streaming ASR: asr.transcribe(["audio.wav"], batch_size=8). Fine-tune ASR: prepare manifest — {"audio_filepath": "path.wav", "duration": 3.2, "text": "hello world"}. Train config via Hydra YAML: trainer.max_epochs=50, model.train_ds.manifest_filepath=train.json. python train.py model=conformer_ctc_bpe model.train_ds.manifest_filepath=train.json. TTS inference: from nemo.collections.tts.models import FastPitchModel, HifiGanModel, spec = FastPitchModel.from_pretrained("nvidia/tts_en_fastpitch"), vocoder = HifiGanModel.from_pretrained("nvidia/tts_hifigan"), parsed = spec.parse("Hello world"), spectrogram, _, _ = spec.generate_spectrogram(tokens=parsed), audio = vocoder.convert_spectrogram_to_audio(spec=spectrogram). NLP: from nemo.collections.nlp.models.language_modeling import MegatronGPTModel, load pretrained or train from scratch with tensor/pipeline parallelism. Custom model: subclass nemo.core.ModelPT (PyTorch Lightning module with NeMo features), implement training_step/validation_step, use self.register_artifact for saving weights with config. exp_manager: from nemo.utils import exp_manager, exp_manager(trainer, cfg.get("exp_manager", None)) — handles checkpointing, W&B, TensorBoard logging. Config: @hydra_runner(config_path="conf", config_name="config"), access via OmegaConf.to_container(cfg). CTC decode: BeamCTCInfer(beam_size=128, return_best_hypothesis=True) with n-gram LM. Claude Code generates NeMo ASR training configs, TTS pipelines, custom model subclasses, manifest creation scripts, and Hydra experiment configs.

CLAUDE.md for NeMo

## NeMo Stack
- Version: nemo_toolkit >= 1.23 + pytorch >= 2.0 + lightning >= 2.0
- ASR: EncDecCTCModelBPE.from_pretrained("nvidia/...") → transcribe(["audio.wav"])
- TTS: FastPitchModel.from_pretrained + HifiGanModel → parse → generate_spectrogram → audio
- Manifest: {"audio_filepath": str, "duration": float, "text": str} — one JSON per line
- Config: Hydra YAML — trainer.max_epochs, model.train_ds.manifest_filepath, etc.
- exp_manager: exp_manager(trainer, cfg.exp_manager) handles checkpoints + logging
- Custom: subclass nemo.core.ModelPT → training_step + validation_step + register_artifact

ASR Fine-Tuning and TTS Pipeline

# nemo_pipeline/asr_finetune.py — NeMo ASR fine-tuning and TTS inference
from __future__ import annotations
import json
import os
import subprocess
from pathlib import Path

import torch


# ── 1. Data manifest creation ─────────────────────────────────────────────────

def create_manifest(
    audio_dir:     str,
    transcripts:   dict[str, str],   # {filename: transcript}
    output_path:   str,
) -> str:
    """
    Create a NeMo data manifest JSONL file.
    NeMo manifest format: one JSON object per line with audio_filepath, duration, text.
    """
    import librosa

    entries: list[dict] = []
    audio_dir_path = Path(audio_dir)

    for filename, text in transcripts.items():
        audio_path = audio_dir_path / filename
        if not audio_path.exists():
            print(f"Warning: {audio_path} not found, skipping")
            continue

        # Get duration without loading full audio
        try:
            duration = librosa.get_duration(path=str(audio_path))
        except Exception:
            duration = 0.0

        entries.append({
            "audio_filepath": str(audio_path.resolve()),
            "duration":       round(duration, 4),
            "text":           text.lower().strip(),
        })

    with open(output_path, "w") as f:
        for entry in entries:
            f.write(json.dumps(entry) + "\n")

    print(f"Manifest written: {output_path} ({len(entries)} entries)")
    return output_path


def split_manifest(
    manifest_path: str,
    train_ratio:   float = 0.9,
    seed:          int   = 42,
) -> tuple[str, str]:
    """Split manifest into train/val sets."""
    import random
    random.seed(seed)

    with open(manifest_path) as f:
        lines = f.readlines()
    random.shuffle(lines)

    split = int(len(lines) * train_ratio)
    base  = manifest_path.replace(".json", "")

    train_path = f"{base}_train.json"
    val_path   = f"{base}_val.json"

    with open(train_path, "w") as f: f.writelines(lines[:split])
    with open(val_path,   "w") as f: f.writelines(lines[split:])

    print(f"Train: {train_path} ({split} samples)")
    print(f"Val:   {val_path} ({len(lines)-split} samples)")
    return train_path, val_path


# ── 2. ASR inference ──────────────────────────────────────────────────────────

class ASRInferencer:
    """Wrapper for NeMo ASR models with batched transcription."""

    def __init__(
        self,
        model_name: str = "nvidia/stt_en_conformer_ctc_large",
        device:     str = "cuda",
    ):
        from nemo.collections.asr.models import EncDecCTCModelBPE

        self.model = EncDecCTCModelBPE.from_pretrained(model_name)
        self.model = self.model.to(device)
        self.model.eval()
        print(f"Loaded ASR model: {model_name}")

    def transcribe(
        self,
        audio_paths: list[str],
        batch_size:  int = 8,
    ) -> list[str]:
        """Transcribe a list of audio files."""
        with torch.no_grad():
            transcripts = self.model.transcribe(
                audio_paths,
                batch_size=batch_size,
                verbose=False,
            )
        return transcripts

    def transcribe_with_timestamps(
        self,
        audio_path: str,
    ) -> dict:
        """Transcribe a single file with word-level timestamps."""
        output = self.model.transcribe(
            [audio_path],
            return_hypotheses=True,
        )[0]
        return {
            "text":       output.text,
            "timesteps":  output.timestep,
        }

    @classmethod
    def from_checkpoint(cls, checkpoint_path: str, device: str = "cuda") -> "ASRInferencer":
        """Load fine-tuned model from saved checkpoint."""
        from nemo.collections.asr.models import EncDecCTCModelBPE
        obj = cls.__new__(cls)
        obj.model = EncDecCTCModelBPE.restore_from(checkpoint_path).to(device)
        obj.model.eval()
        return obj


# ── 3. TTS pipeline ───────────────────────────────────────────────────────────

class TTSPipeline:
    """FastPitch + HiFiGAN text-to-speech pipeline."""

    def __init__(
        self,
        spec_model:    str = "nvidia/tts_en_fastpitch",
        vocoder_model: str = "nvidia/tts_hifigan",
        device:        str = "cuda",
    ):
        from nemo.collections.tts.models import FastPitchModel, HifiGanModel

        self.spec_model = FastPitchModel.from_pretrained(spec_model).to(device)
        self.vocoder    = HifiGanModel.from_pretrained(vocoder_model).to(device)
        self.spec_model.eval()
        self.vocoder.eval()
        self.sample_rate = 22050
        print("TTS pipeline loaded")

    def synthesize(
        self,
        text:         str,
        pace:         float = 1.0,
        pitch_shift:  float = 0.0,
    ) -> "np.ndarray":
        """Convert text to waveform (float32 numpy array)."""
        import numpy as np

        with torch.no_grad():
            parsed    = self.spec_model.parse(text)
            spectrogram, _, _ = self.spec_model.generate_spectrogram(
                tokens=parsed,
                pace=pace,
                pitch_contour_factor=1.0 + pitch_shift,
            )
            audio = self.vocoder.convert_spectrogram_to_audio(spec=spectrogram)

        return audio.squeeze().cpu().numpy()

    def save_wav(self, text: str, output_path: str) -> None:
        """Synthesize and save to WAV file."""
        import soundfile as sf
        audio = self.synthesize(text)
        sf.write(output_path, audio, self.sample_rate)
        print(f"Audio saved: {output_path} ({len(audio)/self.sample_rate:.2f}s)")


# ── 4. Custom NeMo model subclass ────────────────────────────────────────────

def example_custom_model():
    """
    Minimal NeMo custom model skeleton.
    ModelPT = ModelPT inherits from LightningModule + NeMo model utilities.
    """
    from nemo.core import ModelPT
    from omegaconf import DictConfig

    class CustomClassifier(ModelPT):
        def __init__(self, cfg: DictConfig, trainer=None):
            super().__init__(cfg, trainer)
            import torch.nn as nn
            self.encoder = nn.Linear(cfg.input_dim, cfg.hidden_dim)
            self.head    = nn.Linear(cfg.hidden_dim, cfg.num_classes)
            self.loss    = nn.CrossEntropyLoss()

        def forward(self, x):
            return self.head(torch.relu(self.encoder(x)))

        def training_step(self, batch, batch_idx):
            x, y  = batch
            logits = self(x)
            loss   = self.loss(logits, y)
            self.log("train_loss", loss, prog_bar=True)
            return loss

        def validation_step(self, batch, batch_idx):
            x, y  = batch
            logits = self(x)
            loss   = self.loss(logits, y)
            self.log("val_loss", loss, prog_bar=True)

        def setup_training_data(self, train_data_config):
            pass  # Return a dataloader

        def setup_validation_data(self, val_data_config):
            pass  # Return a dataloader

        @classmethod
        def list_available_models(cls):
            return []

    return CustomClassifier


# ── 5. Generate NeMo ASR training config ─────────────────────────────────────

def generate_asr_config(
    train_manifest: str,
    val_manifest:   str,
    output_dir:     str = "experiments/asr",
    max_epochs:     int = 50,
) -> str:
    """Generate a Hydra-compatible ASR fine-tuning YAML config."""
    config = f"""
name: conformer_ctc_finetune

model:
  pretrained_model: nvidia/stt_en_conformer_ctc_large

  train_ds:
    manifest_filepath: {train_manifest}
    sample_rate: 16000
    batch_size: 16
    shuffle: true
    num_workers: 4
    trim_silence: true
    max_duration: 20.0

  validation_ds:
    manifest_filepath: {val_manifest}
    sample_rate: 16000
    batch_size: 16
    shuffle: false
    num_workers: 4

  optim:
    name: adamw
    lr: 5e-5
    weight_decay: 1e-3
    sched:
      name: CosineAnnealing
      warmup_steps: 500
      min_lr: 1e-6

trainer:
  devices: 1
  accelerator: gpu
  strategy: auto
  max_epochs: {max_epochs}
  gradient_clip_val: 1.0
  log_every_n_steps: 10
  val_check_interval: 0.25
  precision: 16-mixed

exp_manager:
  exp_dir: {output_dir}
  name: asr_finetune
  create_tensorboard_logger: true
  create_wandb_logger: false
  checkpoint_callback_params:
    monitor: val_wer
    mode: min
    save_top_k: 3
"""
    config_path = "conf/asr_finetune.yaml"
    Path("conf").mkdir(exist_ok=True)
    with open(config_path, "w") as f:
        f.write(config)
    print(f"Config saved: {config_path}")
    print(f"Train with: python -m nemo.collections.asr.train_asr.py --config-path conf --config-name asr_finetune")
    return config_path

For the OpenAI Whisper alternative when needing a simple, battle-tested ASR model that runs anywhere without NVIDIA-specific tooling — Whisper’s simplicity and broad language support make it the default choice for most transcription tasks while NeMo’s Conformer CTC/RNNT models achieve lower word error rates on English and domain-specific speech, offer streaming ASR for real-time applications, and integrate tightly with NVIDIA’s Riva production serving stack. For the Coqui TTS alternative when needing an open-source voices with fine-tuning for custom voices without NVIDIA hardware — Coqui handles CPU inference while NeMo’s FastPitch + HiFiGAN pipeline is specifically optimized for NVIDIA GPU throughput and integrates with the NeMo training framework for custom voice cloning on GPU clusters. The Claude Skills 360 bundle includes NeMo skill sets covering ASR inference and fine-tuning, TTS synthesis, manifest creation, Hydra configs, custom ModelPT subclasses, and exp_manager experiment tracking. Start with the free tier to try speech model code 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