Skip to content

Add Swift API for Cohere Transcribe - #3460

Merged
csukuangfj merged 1 commit into
k2-fsa:masterfrom
csukuangfj:swift-api
Apr 2, 2026
Merged

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

Conversation

@csukuangfj

@csukuangfj csukuangfj commented Apr 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Added Cohere Transcribe model support for offline speech recognition with configurable punctuation and inverse text normalization options.
    • Improved offline recognition stream handling for better resource management.
  • Documentation & Examples

    • Added Swift example code and automated setup script to help developers integrate and test Cohere Transcribe.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 2, 2026
@coderabbitai

coderabbitai Bot commented Apr 2, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3b469afc-5d25-4fed-abe8-386fc9bea425

📥 Commits

Reviewing files that changed from the base of the PR and between 6ee89f0 and e7ea568.

📒 Files selected for processing (4)
  • .github/scripts/test-swift.sh
  • swift-api-examples/SherpaOnnx.swift
  • swift-api-examples/cohere-transcribe.swift
  • swift-api-examples/run-cohere-transcribe.sh

📝 Walkthrough

Walkthrough

This PR adds Cohere Transcribe support to the Swift API bindings and examples for Sherpa-ONNX. It introduces a new offline model configuration factory, refactors stream management in the offline recognizer with persistent stream handling, implements a new Swift example application demonstrating the feature, and provides build automation and CI integration scripts.

Changes

Cohort / File(s) Summary
Swift API Core Changes
swift-api-examples/SherpaOnnx.swift
Added sherpaOnnxOfflineCohereTranscribeModelConfig(...) factory function for Cohere Transcribe configuration. Extended sherpaOnnxOfflineModelConfig(...) with new cohereTranscribe parameter. Refactored SherpaOnnxOfflineRecognizer to replace inline stream lifetime management with persistent stream wrapper pattern; introduced setConfig(...), createStream(), decode(stream:), and getResult(stream:) methods. Added new SherpaOnnxOfflineStreamWrapper class for stream ownership and lifecycle management.
Example Implementation
swift-api-examples/cohere-transcribe.swift
New Swift executable demonstrating Cohere Transcribe offline recognition. Constructs model configs, loads audio via SherpaOnnxWaveWrapper, creates/configures a decoding stream, feeds samples, decodes, and outputs recognized text.
Build and CI Integration
swift-api-examples/run-cohere-transcribe.sh, .github/scripts/test-swift.sh
Added run-cohere-transcribe.sh script to automate model download, Swift compilation, and execution. Updated test-swift.sh to invoke the new runner and clean up generated artifacts.

Sequence Diagram

sequenceDiagram
    participant App as App/Client
    participant Config as Config Factory
    participant Recognizer as SherpaOnnxOfflineRecognizer
    participant Stream as SherpaOnnxOfflineStreamWrapper
    participant Audio as SherpaOnnxWaveWrapper

    App->>Config: Create CohereTranscribeModelConfig
    Config-->>App: Return config
    App->>Recognizer: Initialize with model config
    Recognizer->>Recognizer: setConfig(...)
    App->>Audio: Load WAV file
    Audio-->>App: Return audio samples & rate
    App->>Recognizer: createStream()
    Recognizer->>Stream: Create stream wrapper
    Stream-->>Recognizer: Return wrapper
    Recognizer-->>App: Return wrapper
    App->>Stream: setOption("language", "en")
    App->>Stream: acceptWaveform(samples, rate)
    App->>Recognizer: decode(stream)
    Recognizer->>Recognizer: Decode audio in stream
    App->>Recognizer: getResult(stream)
    Recognizer-->>App: Return recognition result
    App->>App: Print recognized text
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

size:L

Poem

🐰 A transcriber swift and keen,
Cohere's whispers now foreseen,
Streams persist through audio's flow,
Config builds, results aglow! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.69% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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 clearly and concisely summarizes the main change: adding a Swift API for Cohere Transcribe, which is the primary focus of all modifications across multiple files.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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 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 Cohere transcription support to the Swift API examples, adding the necessary model configurations and a new example script. It also refactors the SherpaOnnxOfflineRecognizer to use a SherpaOnnxOfflineStreamWrapper for better management of stream lifecycles. Review feedback highlights a critical memory safety concern regarding the use of toCPointer, which can lead to dangling pointers; it is recommended to use Swift's withCString for passing strings to C functions to ensure memory stability.

Comment on lines +455 to +457
encoder: toCPointer(encoder),
decoder: toCPointer(decoder),
language: toCPointer(language),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

The toCPointer helper function is unsafe because it returns a pointer to a temporary NSString's UTF-8 buffer that is deallocated as soon as the function returns. Storing these pointers in the SherpaOnnxOfflineCohereTranscribeModelConfig struct results in dangling pointers, which can lead to memory corruption or crashes when the struct is used later. While this pattern exists elsewhere in the file, it is a significant correctness issue. Consider a design where the strings are kept alive for the duration of the configuration's use.

}

func setOption(key: String, value: String) {
SherpaOnnxOfflineStreamSetOption(stream, toCPointer(key), toCPointer(value))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

Using toCPointer for immediate function calls is unsafe for the same reason as mentioned above. For passing strings to C functions, it is much safer to use Swift's built-in withCString method, which guarantees the pointer remains valid for the duration of the closure.

Suggested change
SherpaOnnxOfflineStreamSetOption(stream, toCPointer(key), toCPointer(value))
key.withCString { k in
value.withCString { v in
SherpaOnnxOfflineStreamSetOption(stream, k, v)
}
}

@csukuangfj

Copy link
Copy Markdown
Collaborator Author

Closes #3459

@csukuangfj
csukuangfj merged commit 6864344 into k2-fsa:master Apr 2, 2026
3 checks passed
@csukuangfj
csukuangfj deleted the swift-api branch April 2, 2026 12:43
@csukuangfj csukuangfj mentioned this pull request Apr 2, 2026
6 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant