Skip to content

Add Swift API for Google MedASR model - #2947

Merged
csukuangfj merged 1 commit into
k2-fsa:masterfrom
csukuangfj:swift-medasr
Dec 29, 2025
Merged

csukuangfj merged 1 commit into
k2-fsa:masterfrom
csukuangfj:swift-medasr

Conversation

@csukuangfj

@csukuangfj csukuangfj commented Dec 29, 2025 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Added comprehensive MED ASR (MedASR CTC) offline speech recognition support with Swift API
    • Provided working example program demonstrating MED ASR usage with audio decoding and transcription output
    • Included automated setup script for simplified deployment and configuration
  • Tests

    • Added new test script for MED ASR pipeline validation

✏️ Tip: You can customize this high-level summary in your review settings.

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Dec 29, 2025
@csukuangfj
csukuangfj requested a review from Copilot December 29, 2025 02:16
@coderabbitai

coderabbitai Bot commented Dec 29, 2025 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR adds support for a new MED ASR (Multi-Encoder Decoder ASR) CTC model type to Sherpa ONNX's Swift API examples. Changes include configuration helpers, a Swift implementation example, an automated build and execution script, expanded test infrastructure, and gitignore updates.

Changes

Cohort / File(s) Summary
Test & Build Infrastructure
.github/scripts/test-swift.sh, swift-api-examples/run-medasr-ctc-asr.sh
Added new MED ASR test invocation to CI script; created comprehensive build automation script that verifies prerequisites, conditionally downloads model artifacts, compiles Swift executable with Sherpa ONNX linkage, manages runtime library paths, and executes the binary.
Swift API Configuration
swift-api-examples/SherpaOnnx.swift
Added new helper function sherpaOnnxOfflineMedAsrCtcModelConfig() to configure MED ASR models; extended sherpaOnnxOfflineModelConfig() signature to accept and wire medasr parameter into the returned config structure.
Swift Implementation
swift-api-examples/medasr-ctc.swift
New Swift program that configures MED ASR settings, builds an offline recognizer, loads audio, runs decoding, and prints transcription results with optional timestamp information.
Project Configuration
swift-api-examples/.gitignore
Added medasr-ctc build artifact entries to ignore list.

Sequence Diagram

sequenceDiagram
    actor User
    participant BuildScript as run-medasr-ctc-<br/>asr.sh
    participant SwiftCompiler as Swift Compiler
    participant SherpaLib as Sherpa ONNX<br/>Library
    participant App as medasr-ctc<br/>Application
    participant AudioFile as Audio File

    User->>BuildScript: Execute script
    BuildScript->>BuildScript: Check Swift build<br/>directory exists
    BuildScript->>BuildScript: Verify tokens.txt<br/>(download if needed)
    alt Executable missing
        BuildScript->>SwiftCompiler: Invoke swiftc with<br/>Sherpa ONNX linkage
        SwiftCompiler->>SherpaLib: Link against<br/>libsherpa-onnx
        SwiftCompiler-->>BuildScript: Produce binary
        BuildScript->>BuildScript: Strip binary
    end
    BuildScript->>BuildScript: Set DYLD_LIBRARY_PATH
    BuildScript->>App: Execute medasr-ctc
    App->>App: Configure MED ASR model<br/>& feature settings
    App->>SherpaLib: Create offline recognizer
    SherpaLib-->>App: Recognizer ready
    App->>AudioFile: Load WAV samples
    AudioFile-->>App: Audio data
    App->>SherpaLib: Decode audio stream
    SherpaLib-->>App: Transcription + timestamps
    App->>User: Print results
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 Swift whispers float through Sherpa's ears,
Medical words are crystal clear,
MED ASR hops with joyful grace,
Encoding wisdom in its place!
The rabbit's code now heals with care. ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title contains a typo ('Swfit' instead of 'Swift') but accurately describes the main change: adding a Swift API for Google MedASR model, which is supported by all modified files.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 13b8b84 and 29bff16.

📒 Files selected for processing (5)
  • .github/scripts/test-swift.sh
  • swift-api-examples/.gitignore
  • swift-api-examples/SherpaOnnx.swift
  • swift-api-examples/medasr-ctc.swift
  • swift-api-examples/run-medasr-ctc-asr.sh
🧰 Additional context used
🧬 Code graph analysis (1)
swift-api-examples/medasr-ctc.swift (1)
swift-api-examples/SherpaOnnx.swift (10)
  • run (1683-1688)
  • sherpaOnnxOfflineMedAsrCtcModelConfig (379-385)
  • sherpaOnnxOfflineModelConfig (489-541)
  • sherpaOnnxFeatureConfig (133-140)
  • sherpaOnnxOfflineRecognizerConfig (543-569)
  • readWave (1008-1011)
  • decode (286-288)
  • decode (661-677)
  • decode (1186-1199)
  • decode (1297-1299)
🔇 Additional comments (6)
swift-api-examples/.gitignore (1)

28-28: LGTM!

The gitignore entry correctly excludes the MedASR CTC executable, consistent with other model-specific artifacts in this file.

.github/scripts/test-swift.sh (1)

12-13: LGTM!

The test invocation and cleanup follow the established pattern used for other models in this script.

swift-api-examples/medasr-ctc.swift (1)

1-42: LGTM!

The implementation follows the established pattern for offline ASR examples in this repository. The code correctly configures the MedASR CTC model, loads audio, and performs recognition with appropriate debug output.

swift-api-examples/run-medasr-ctc-asr.sh (1)

1-34: LGTM!

The script follows the established pattern for Swift example runners, with appropriate build checks, model downloading, and library path configuration.

swift-api-examples/SherpaOnnx.swift (2)

513-515: LGTM!

The integration of the medasr parameter into sherpaOnnxOfflineModelConfig is consistent with how other model types (e.g., wenetCtc, omnilingual, dolphin) are handled. The trailing comma addition on line 513 and the field inclusion in the struct initialization maintain proper Swift syntax.

Also applies to: 538-539


379-385: C API type verification successful.

The underlying C API properly defines SherpaOnnxOfflineMedAsrCtcModelConfig in sherpa-onnx/c-api/c-api.h as a struct with a single const char *model field, and it is correctly integrated as the medasr field in SherpaOnnxOfflineModelConfig. The Swift helper function appropriately mirrors this C API structure.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello @csukuangfj, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the Swift API by introducing support for the Google MedASR model. It provides the necessary Swift bindings and a comprehensive example, allowing developers to seamlessly integrate and leverage the MedASR model for offline automatic speech recognition within their Swift projects. This expansion broadens the capabilities of the Sherpa Onnx Swift API, offering more options for ASR tasks.

Highlights

  • MedASR Swift API Support: Added Swift API support for the Google MedASR model, enabling its integration into Swift applications for offline speech recognition.
  • New Swift Example: Introduced a new Swift example (medasr-ctc.swift) demonstrating how to use the MedASR model with the Sherpa Onnx Swift API.
  • Automated Example Execution: Included a shell script (run-medasr-ctc-asr.sh) to automate the download of the MedASR model, build the Swift example, and execute it.
  • CI Integration: Updated the CI test script (.github/scripts/test-swift.sh) to incorporate testing for the newly added MedASR Swift example, ensuring its functionality.
  • API Configuration Update: Modified swift-api-examples/SherpaOnnx.swift to expose the necessary configuration functions for the MedASR model and integrate it into the main model configuration.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces Swift API support for the Google MedASR model. It includes a new example (medasr-ctc.swift), a script to run it (run-medasr-ctc-asr.sh), updates to the Swift wrapper (SherpaOnnx.swift), and integration into the CI test script. The changes are well-structured and follow the existing patterns in the repository. My review focuses on improving the maintainability and code style of the newly added example and its corresponding run script by refactoring repeated strings into variables and using more idiomatic Swift constructs.

Comment on lines +1 to +35
func run() {
let model =
"./sherpa-onnx-medasr-ctc-en-int8-2025-12-25/model.int8.onnx"
let tokens =
"./sherpa-onnx-medasr-ctc-en-int8-2025-12-25/tokens.txt"

let medasr = sherpaOnnxOfflineMedAsrCtcModelConfig(
model: model
)

let modelConfig = sherpaOnnxOfflineModelConfig(
tokens: tokens,
debug: 1,
medasr: medasr
)

let featConfig = sherpaOnnxFeatureConfig()
var config = sherpaOnnxOfflineRecognizerConfig(
featConfig: featConfig,
modelConfig: modelConfig
)

let recognizer = SherpaOnnxOfflineRecognizer(config: &config)

let filePath = "./sherpa-onnx-medasr-ctc-en-int8-2025-12-25/test_wavs/0.wav"
let audio = SherpaOnnxWaveWrapper.readWave(filename: filePath)

let result = recognizer.decode(samples: audio.samples, sampleRate: audio.sampleRate)
print("decode done")

print("\nresult is:\n\(result.text)")
if result.timestamps.count != 0 {
print("\ntimestamps is:\n\(result.timestamps)")
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This function can be improved in a few ways for better maintainability and adherence to Swift idioms:

  1. Reduce Redundancy: The model directory path is repeated multiple times. It's better to define it as a constant and reuse it.
  2. Debug Flag: For consistency with other examples, debug should be set to 0 instead of 1.
  3. Idiomatic Check: Use !result.timestamps.isEmpty instead of result.timestamps.count != 0 to check for an empty collection, which is more idiomatic in Swift.

Here is a suggested refactoring that applies these improvements.

func run() {
  let modelDir = "./sherpa-onnx-medasr-ctc-en-int8-2025-12-25"
  let model = "\(modelDir)/model.int8.onnx"
  let tokens = "\(modelDir)/tokens.txt"

  let medasr = sherpaOnnxOfflineMedAsrCtcModelConfig(
    model: model
  )

  let modelConfig = sherpaOnnxOfflineModelConfig(
    tokens: tokens,
    debug: 0,
    medasr: medasr
  )

  let featConfig = sherpaOnnxFeatureConfig()
  var config = sherpaOnnxOfflineRecognizerConfig(
    featConfig: featConfig,
    modelConfig: modelConfig
  )

  let recognizer = SherpaOnnxOfflineRecognizer(config: &config)

  let filePath = "\(modelDir)/test_wavs/0.wav"
  let audio = SherpaOnnxWaveWrapper.readWave(filename: filePath)

  let result = recognizer.decode(samples: audio.samples, sampleRate: audio.sampleRate)
  print("decode done")

  print("\nresult is:\n\(result.text)")
  if !result.timestamps.isEmpty {
    print("\ntimestamps is:\n\(result.timestamps)")
  }
}

Comment on lines +10 to +14
if [ ! -f ./sherpa-onnx-medasr-ctc-en-int8-2025-12-25/tokens.txt ]; then
curl -SL -O https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-medasr-ctc-en-int8-2025-12-25.tar.bz2
tar xvf sherpa-onnx-medasr-ctc-en-int8-2025-12-25.tar.bz2
rm sherpa-onnx-medasr-ctc-en-int8-2025-12-25.tar.bz2
fi

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To improve readability and maintainability, you should define the model directory/archive name as a variable and reuse it. This avoids repeating the long string and makes it easier to update in the future.

Suggested change
if [ ! -f ./sherpa-onnx-medasr-ctc-en-int8-2025-12-25/tokens.txt ]; then
curl -SL -O https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-medasr-ctc-en-int8-2025-12-25.tar.bz2
tar xvf sherpa-onnx-medasr-ctc-en-int8-2025-12-25.tar.bz2
rm sherpa-onnx-medasr-ctc-en-int8-2025-12-25.tar.bz2
fi
model_name="sherpa-onnx-medasr-ctc-en-int8-2025-12-25"
if [ ! -f ./${model_name}/tokens.txt ]; then
curl -SL -O https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/${model_name}.tar.bz2
tar xvf ${model_name}.tar.bz2
rm ${model_name}.tar.bz2
fi

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds Swift API support for the Google MedASR (Medical Automatic Speech Recognition) CTC model. The implementation follows the established pattern used for similar ASR models in the repository.

  • Adds Swift wrapper functions for MedASR CTC model configuration
  • Includes example implementation demonstrating model usage with test audio
  • Integrates MedASR testing into the CI/CD pipeline

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated no comments.

Show a summary per file
File Description
swift-api-examples/run-medasr-ctc-asr.sh Shell script to download model files, compile, and run the MedASR CTC example
swift-api-examples/medasr-ctc.swift Swift implementation demonstrating MedASR model usage for audio transcription
swift-api-examples/SherpaOnnx.swift Adds MedASR model configuration wrapper functions to the Swift API
swift-api-examples/.gitignore Adds medasr-ctc executable to the ignore list
.github/scripts/test-swift.sh Integrates MedASR example into the CI test suite

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@csukuangfj
csukuangfj merged commit 234bfe3 into k2-fsa:master Dec 29, 2025
9 checks passed
@csukuangfj
csukuangfj deleted the swift-medasr branch December 29, 2025 04:40
@csukuangfj csukuangfj changed the title Add Swfit API for Google MedASR model Add Swift API for Google MedASR model Dec 29, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Jul 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants