{"slug": "how-to-use-nvidia-canary-1b-v2-for-asr-translation-and-automatic-srt-subtitle-in", "title": "How to Use NVIDIA Canary-1B-v2 for ASR, Translation, and Automatic SRT Subtitle Export in Python", "summary": "NVIDIA released Canary-1B-v2, a multilingual speech recognition and translation model, with a Python tutorial demonstrating ASR, translation, and SRT subtitle export. The tutorial shows how to install dependencies, load the model on GPU, process audio at 16 kHz, and generate translated subtitles. This enables developers to build multilingual ASR pipelines for real audio files and large-scale transcription.", "body_md": "In this [tutorial](https://github.com/MARKTECHPOST-AI-MEDIA-INC/AI-Agents-Projects-Tutorials/blob/main/Voice%20AI/nvidia_canary_1b_v2_asr_translation_tutorial_marktechpost.py), we build a speech recognition and translation workflow using[ NVIDIA Canary-1B-v2](https://huggingface.co/nvidia/canary-1b-v2). We begin by setting up the required audio, NeMo, NumPy, and SciPy dependencies, then load the Canary model on a GPU-enabled runtime for efficient inference. From there, we prepare audio into a clean 16 kHz mono format, perform English ASR, translate speech into multiple languages, generate word and segment timestamps, export translated subtitles as an SRT file, test long-form transcription, run batch processing, and benchmark inference speed. At the end, we have a complete multilingual ASR and speech translation pipeline that we can adapt for real audio files, subtitle generation, and large-scale transcription experiments.\n\n**Installing NeMo, Audio Libraries, NumPy, and SciPy Dependencies**\n\n``` python\nimport os, subprocess, sys\nSENTINEL = \"/content/.canary_setup_done\"\nif not os.path.exists(SENTINEL):\n   def sh(c):\n       print(\"$\", c); subprocess.run(c, shell=True, check=False)\n   print(\">>> PHASE 1: installing dependencies (one-time)...\\n\")\n   sh(\"apt-get -qq update\")\n   sh(\"apt-get -qq install -y libsndfile1 ffmpeg > /dev/null\")\n   sh('pip install -q \"nemo_toolkit[asr]\"')\n   sh(\"pip install -q librosa soundfile pydub\")\n   sh('pip install -q --force-reinstall --no-cache-dir \"numpy>=2.2,<2.4\" \"scipy>=1.15\"')\n   open(SENTINEL, \"w\").write(\"done\")\n   print(\"\\n✅ Setup complete. Restarting the runtime now.\")\n   print(\"   When it reconnects, RUN THIS CELL AGAIN to start the tutorial.\")\n   os.kill(os.getpid(), 9)\n```\n\nWe set up the environment for the NVIDIA Canary-1B-v2 tutorial. We install the required system packages, NeMo ASR toolkit, audio libraries, and compatible NumPy and SciPy versions. We then create a setup marker and restart the runtime so that the updated dependencies load cleanly before running the main tutorial.\n\n**Loading NVIDIA Canary-1B-v2 and Checking GPU Availability**\n\n``` python\nimport time, json, gc, math, urllib.request\nimport torch, numpy as np, soundfile as sf, librosa\nprint(\">>> PHASE 2: running tutorial\\n\")\nprint(\"NumPy:\", np.__version__, \"| PyTorch:\", torch.__version__)\nprint(\"CUDA available:\", torch.cuda.is_available())\nif torch.cuda.is_available():\n   print(\"GPU:\", torch.cuda.get_device_name(0),\n         f\"| VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB\")\nelse:\n   print(\"⚠️  No GPU — will run on CPU (very slow). \"\n         \"Set Runtime > Change runtime type > GPU.\")\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nLANGS = {\n   \"bg\":\"Bulgarian\",\"hr\":\"Croatian\",\"cs\":\"Czech\",\"da\":\"Danish\",\"nl\":\"Dutch\",\n   \"en\":\"English\",\"et\":\"Estonian\",\"fi\":\"Finnish\",\"fr\":\"French\",\"de\":\"German\",\n   \"el\":\"Greek\",\"hu\":\"Hungarian\",\"it\":\"Italian\",\"lv\":\"Latvian\",\"lt\":\"Lithuanian\",\n   \"mt\":\"Maltese\",\"pl\":\"Polish\",\"pt\":\"Portuguese\",\"ro\":\"Romanian\",\"sk\":\"Slovak\",\n   \"sl\":\"Slovenian\",\"es\":\"Spanish\",\"sv\":\"Swedish\",\"ru\":\"Russian\",\"uk\":\"Ukrainian\",\n}\nprint(f\"\\nSupported languages ({len(LANGS)}):\", \", \".join(LANGS.keys()))\nfrom nemo.collections.asr.models import ASRModel\nprint(\"\\nLoading nvidia/canary-1b-v2 ...\")\nt0 = time.time()\nasr_model = ASRModel.from_pretrained(model_name=\"nvidia/canary-1b-v2\").to(DEVICE).eval()\nprint(f\"Model loaded in {time.time()-t0:.1f}s\")\n```\n\nWe import the main libraries and check whether CUDA is available for GPU acceleration. We define the supported language dictionary to enable Canary to handle multilingual ASR and translation tasks. We then load the NVIDIA Canary-1B-v2 model from NeMo and move it to the available device for inference.\n\n**Preparing 16 kHz Audio and Running English ASR with Translation**\n\n``` python\nTARGET_SR = 16000\ndef prepare_audio(path_or_url, out_path=None):\n   if str(path_or_url).startswith((\"http://\", \"https://\")):\n       local = \"/content/_dl_\" + os.path.basename(path_or_url.split(\"?\")[0])\n       urllib.request.urlretrieve(path_or_url, local)\n       path_or_url = local\n   audio, _ = librosa.load(path_or_url, sr=TARGET_SR, mono=True)\n   if out_path is None:\n       base = os.path.splitext(os.path.basename(path_or_url))[0]\n       out_path = f\"/content/{base}_16k_mono.wav\"\n   sf.write(out_path, audio, TARGET_SR, subtype=\"PCM_16\")\n   dur = len(audio) / TARGET_SR\n   print(f\"Prepared: {out_path}  ({dur:.1f}s, 16kHz, mono)\")\n   return out_path, dur\nSAMPLE_URL = \"https://dldata-public.s3.us-east-2.amazonaws.com/2086-149220-0033.wav\"\nsample_wav, sample_dur = prepare_audio(SAMPLE_URL)\ndef transcribe(files, source_lang=\"en\", target_lang=\"en\", timestamps=False, batch_size=1):\n   if isinstance(files, str):\n       files = [files]\n   return asr_model.transcribe(files, source_lang=source_lang, target_lang=target_lang,\n                               timestamps=timestamps, batch_size=batch_size)\nprint(\"\\n=== 1) BASIC ASR (English) ===\")\nres = transcribe(sample_wav, source_lang=\"en\", target_lang=\"en\")\nprint(\"Transcript:\", res[0].text)\nprint(\"\\n=== 2) TRANSLATION (EN audio -> X) ===\")\nfor tgt in [\"fr\", \"de\", \"es\", \"it\"]:\n   out = transcribe(sample_wav, source_lang=\"en\", target_lang=tgt)\n   print(f\"  EN -> {LANGS[tgt]:<10} ({tgt}): {out[0].text}\")\n```\n\nWe create a reusable audio preparation function that downloads audio when needed and converts it into 16 kHz mono WAV format. We load the sample audio file and define a helper function for transcription and translation. We then run basic English ASR and translate the same English speech into French, German, Spanish, and Italian.\n\n**Generating Word and Segment Timestamps and Exporting SRT Subtitles**\n\n```\nprint(\"\\n=== 3) TIMESTAMPS (ASR) ===\")\nts_out = transcribe(sample_wav, source_lang=\"en\", target_lang=\"en\", timestamps=True)\nword_ts = ts_out[0].timestamp.get(\"word\", [])\nseg_ts  = ts_out[0].timestamp.get(\"segment\", [])\nprint(\"Segments:\")\nfor s in seg_ts:\n   print(f\"  [{s['start']:6.2f}s - {s['end']:6.2f}s]  {s['segment']}\")\nprint(\"First 10 words:\")\nfor w in word_ts[:10]:\n   print(f\"  [{w['start']:6.2f}s - {w['end']:6.2f}s]  {w['word']}\")\ndef _srt_time(t):\n   h=int(t//3600); m=int((t%3600)//60); s=int(t%60); ms=int(round((t-int(t))*1000))\n   return f\"{h:02d}:{m:02d}:{s:02d},{ms:03d}\"\ndef segments_to_srt(segments, out_path=\"/content/output.srt\"):\n   lines=[]\n   for i, seg in enumerate(segments, 1):\n       lines += [str(i), f\"{_srt_time(seg['start'])} --> {_srt_time(seg['end'])}\",\n                 seg[\"segment\"].strip(), \"\"]\n   open(out_path, \"w\", encoding=\"utf-8\").write(\"\\n\".join(lines))\n   print(f\"Saved SRT: {out_path}\")\n   return out_path\nprint(\"\\n=== 4) SRT EXPORT (translated French subtitles) ===\")\nfr_ts = transcribe(sample_wav, source_lang=\"en\", target_lang=\"fr\", timestamps=True)\nsegments_to_srt(fr_ts[0].timestamp[\"segment\"], \"/content/subtitles_fr.srt\")\nprint(open(\"/content/subtitles_fr.srt\").read())\n```\n\nWe enable timestamped transcription to extract both segment-level and word-level timing information. We print the transcript segments and the first few word timestamps to inspect how the model aligns text with audio. We also convert translated French segments into an SRT subtitle file and display the generated subtitles.\n\n**Running Long-Form Transcription, Batch Processing, and Speed Benchmark**\n\n```\nprint(\"\\n=== 5) LONG-FORM (sample tiled x6) ===\")\nlong_audio, _ = librosa.load(sample_wav, sr=TARGET_SR, mono=True)\nlong_audio = np.tile(long_audio, 6)\nsf.write(\"/content/long.wav\", long_audio, TARGET_SR, subtype=\"PCM_16\")\nprint(f\"Long clip duration: {len(long_audio)/TARGET_SR:.1f}s\")\nlong_out = transcribe(\"/content/long.wav\", source_lang=\"en\", target_lang=\"en\", batch_size=1)\nprint(\"Long transcript (first 300 chars):\", long_out[0].text[:300], \"...\")\nprint(\"\\n=== 6) BATCH ===\")\nfor name in [\"clip_a\", \"clip_b\"]:\n   sf.write(f\"/content/{name}.wav\",\n            librosa.load(sample_wav, sr=TARGET_SR, mono=True)[0], TARGET_SR, subtype=\"PCM_16\")\nbatch = transcribe([\"/content/clip_a.wav\", \"/content/clip_b.wav\"],\n                  source_lang=\"en\", target_lang=\"en\", batch_size=2)\nfor i, b in enumerate(batch):\n   print(f\"  file {i}: {b.text}\")\nprint(\"\\n=== 7) BENCHMARK ===\")\nt0 = time.time(); _ = transcribe(sample_wav, source_lang=\"en\", target_lang=\"en\")\nelapsed = time.time()-t0\nprint(f\"Audio: {sample_dur:.2f}s | Compute: {elapsed:.2f}s | RTFx ≈ {sample_dur/elapsed:.1f}x\")\nprint(\"\\n✅ Done. Change source_lang/target_lang from the LANGS dict to try other languages.\")\n```\n\nWe test long-form transcription by repeating the sample audio several times and passing the longer clip through the model. We also create two duplicate audio clips to demonstrate batch transcription with a batch size of two. Also, we benchmark the model by comparing audio duration with compute time and report the real-time factor speed.\n\n**Conclusion**\n\nIn conclusion, we completed a practical end-to-end workflow for using NVIDIA Canary-1B-v2 as a multilingual ASR and speech translation system. We processed raw audio, generated accurate transcripts, translated speech into different target languages, extracted timestamps, created subtitle files, handled longer audio clips, and compared runtime performance through a simple benchmark. We now have a reusable Colab-ready pipeline that we can extend further with custom uploads, more languages, larger batches, and production-style audio processing.\n\nCheck out the ** Full Codes with Notebook. **Also, feel free to follow us on\n\n**and don’t forget to join our**[Twitter](https://x.com/intent/follow?screen_name=marktechpost)\n\n**and Subscribe to**\n\n[150k+ML SubReddit](https://www.reddit.com/r/machinelearningnews/)**. Wait! are you on telegram?**\n\n[our Newsletter](https://www.aidevsignals.com/)\n\n[now you can join us on telegram as well.](https://t.me/machinelearningresearchnews)Need to partner with us for promoting your GitHub Repo OR Hugging Face Page OR Product Release OR Webinar etc.? [Connect with us](https://forms.gle/wbash1wF6efRj8G58)\n\nSana Hassan, a consulting intern at Marktechpost and dual-degree student at IIT Madras, is passionate about applying technology and AI to address real-world challenges. With a keen interest in solving practical problems, he brings a fresh perspective to the intersection of AI and real-life solutions.\n\n- Sana Hassan\n- Sana Hassan\n- Sana Hassan\n- Sana Hassan", "url": "https://wpnews.pro/news/how-to-use-nvidia-canary-1b-v2-for-asr-translation-and-automatic-srt-subtitle-in", "canonical_source": "https://www.marktechpost.com/2026/06/23/how-to-use-nvidia-canary-1b-v2-for-asr-translation-and-automatic-srt-subtitle-export-in-python/", "published_at": "2026-06-23 18:31:36+00:00", "updated_at": "2026-06-24 00:26:06.898210+00:00", "lang": "en", "topics": ["artificial-intelligence", "machine-learning", "large-language-models", "natural-language-processing", "ai-tools"], "entities": ["NVIDIA", "Canary-1B-v2", "NeMo", "PyTorch", "CUDA", "Hugging Face", "NumPy", "SciPy"], "alternates": {"html": "https://wpnews.pro/news/how-to-use-nvidia-canary-1b-v2-for-asr-translation-and-automatic-srt-subtitle-in", "markdown": "https://wpnews.pro/news/how-to-use-nvidia-canary-1b-v2-for-asr-translation-and-automatic-srt-subtitle-in.md", "text": "https://wpnews.pro/news/how-to-use-nvidia-canary-1b-v2-for-asr-translation-and-automatic-srt-subtitle-in.txt", "jsonld": "https://wpnews.pro/news/how-to-use-nvidia-canary-1b-v2-for-asr-translation-and-automatic-srt-subtitle-in.jsonld"}}