Skip to content

Conversation

csukuangfj
Copy link
Collaborator

@csukuangfj csukuangfj commented Jul 15, 2025

Fixes #2396

With this PR, you don't need to wait until the speaker stops speaking to get the current speech segment.

CC @livefantasia

Summary by CodeRabbit

  • New Features

    • Added a method and property to access the current speech segment in the voice activity detector for both C++ and Python interfaces.
  • Documentation

    • Enhanced documentation and usage notes for voice activity detector methods and properties in both C++ and Python bindings.

@csukuangfj csukuangfj requested a review from Copilot July 15, 2025 03:57
Copy link

coderabbitai bot commented Jul 15, 2025

Walkthrough

A new method and property were introduced in the VoiceActivityDetector C++ and Python APIs to provide access to the current speech segment as soon as speech is detected, rather than only after the segment completes. Documentation was updated, and an example script was modified to demonstrate the new capability, though the demonstration code is currently disabled.

Changes

File(s) Change Summary
sherpa-onnx/csrc/voice-activity-detector.cc, .h Added current speech segment tracking, new CurrentSpeechSegment() method, and updated documentation.
sherpa-onnx/python/csrc/voice-activity-detector.cc Added Python property current_segment, detailed docstring for usage, no logic changes.
python-api-examples/generate-subtitles.py Added (currently disabled) example usage of new current speech segment API in the processing loop.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant VAD (VoiceActivityDetector)
    participant AudioBuffer

    User->>VAD: AcceptWaveform(audio_chunk)
    VAD->>VAD: Process audio, update cur_segment_
    User->>VAD: IsSpeechDetected()
    alt Speech detected
        User->>VAD: CurrentSpeechSegment()
        VAD-->>User: Return current speech segment (start, samples)
    end
    User->>VAD: Front() (when segment completes)
    VAD-->>User: Return finalized speech segment
Loading

Assessment against linked issues

Objective Addressed Explanation
Provide method to return the latest start point of speech as soon as speech is detected (#2396)
Expose current speech segment in both C++ and Python APIs (#2396)
Update documentation to clarify new and existing method behaviors (#2396)

Poem

A rabbit hops through code so bright,
Now VAD reveals speech at first light.
No need to wait for utterance end,
The start is known, just round the bend!
With segments shown as soon as they start,
Streaming’s now smarter—hippity heart!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8693b1e and 06f26b5.

📒 Files selected for processing (4)
  • python-api-examples/generate-subtitles.py (1 hunks)
  • sherpa-onnx/csrc/voice-activity-detector.cc (5 hunks)
  • sherpa-onnx/csrc/voice-activity-detector.h (1 hunks)
  • sherpa-onnx/python/csrc/voice-activity-detector.cc (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
sherpa-onnx/python/csrc/voice-activity-detector.cc (1)
sherpa-onnx/csrc/voice-activity-detector.cc (4)
  • Front (239-241)
  • Front (239-239)
  • CurrentSpeechSegment (251-253)
  • CurrentSpeechSegment (251-251)
🔇 Additional comments (10)
python-api-examples/generate-subtitles.py (1)

612-621: Good demonstration of the new current_segment functionality.

The disabled code block effectively demonstrates how to use the new current_segment property to access ongoing speech detection results. The intentional if False: guard is appropriate for example code that users can enable for debugging or real-time monitoring purposes.

sherpa-onnx/csrc/voice-activity-detector.h (2)

34-39: Excellent documentation improvements.

The added documentation clearly explains the error conditions and reference validity constraints for the Front() method, which will help prevent misuse.


43-44: Well-documented new method declaration.

The CurrentSpeechSegment() method declaration is clear and the documentation appropriately explains when the segment is considered empty.

sherpa-onnx/python/csrc/voice-activity-detector.cc (2)

25-35: Comprehensive and helpful class documentation.

The detailed docstring clearly explains the usage patterns, error conditions, and the relationship between speech detection state and the various properties. This will significantly help Python users understand the correct usage of the class.


52-53: Correctly implemented property binding.

The new current_segment property follows the established pattern of exposing C++ methods as read-only properties and correctly binds to the CurrentSpeechSegment() method.

sherpa-onnx/csrc/voice-activity-detector.cc (5)

94-97: Correct implementation of current segment tracking during speech detection.

The logic properly updates the current segment with the start index and samples when speech is detected, maintaining consistency with the existing speech detection logic.


101-102: Proper cleanup of current segment during non-speech detection.

Correctly clears the current segment when transitioning from speech to non-speech, ensuring the segment is empty when no speech is being detected.


149-150: Consistent state management in Reset() and Flush() methods.

The current segment is properly reset in both Reset() and Flush() methods, maintaining consistent state management across all operations.

Also applies to: 175-176


181-182: Well-implemented CurrentSpeechSegment() method.

The method correctly returns the current segment by value, which provides a safe copy of the segment data and follows good C++ practices for data access.

Also applies to: 251-253


202-203: Appropriate member variable declaration.

The cur_segment_ member variable is properly declared with clear documentation explaining its purpose and state semantics.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@Copilot Copilot AI left a comment

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 exposes a new current_segment property in VoiceActivityDetector to allow retrieving the ongoing speech segment before speech ends.

  • Declare and implement CurrentSpeechSegment in the C++ core
  • Bind current_segment in the Python extension with documentation
  • Add a commented example in the Python script demonstrating real-time usage

Reviewed Changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
sherpa-onnx/python/csrc/voice-activity-detector.cc Added Python binding and docstring for current_segment
sherpa-onnx/csrc/voice-activity-detector.h Declared CurrentSpeechSegment and added comments
sherpa-onnx/csrc/voice-activity-detector.cc Implemented cur_segment_ updates and CurrentSpeechSegment
python-api-examples/generate-subtitles.py Provided example usage guarded by if False
Comments suppressed due to low confidence (3)

sherpa-onnx/python/csrc/voice-activity-detector.cc:26

  • [nitpick] The long raw-string doc comment is hard to read and has inconsistent numbering and grammar. Consider reformatting into a concise, bulleted docstring (or use Doxygen tags) with clear sentences and consistent punctuation.
                      R"(

sherpa-onnx/csrc/voice-activity-detector.h:44

  • [nitpick] The comment for CurrentSpeechSegment is vague. Document that it returns an empty segment (e.g. start = -1, empty samples) when no speech is detected, and specify the return semantics clearly in Doxygen style.
  SpeechSegment CurrentSpeechSegment() const;

sherpa-onnx/csrc/voice-activity-detector.h:44

  • There's no existing unit test for the new CurrentSpeechSegment API. Please add tests covering both when speech is ongoing and when no speech is detected to validate the returned segment.
  SpeechSegment CurrentSpeechSegment() const;

Comment on lines +149 to +150
cur_segment_.start = -1;
cur_segment_.samples.clear();
Copy link

Copilot AI Jul 15, 2025

Choose a reason for hiding this comment

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

Clearing cur_segment_ is duplicated in multiple methods (Reset, Flush, and non-speech branch). Consider extracting a private helper like ClearCurrentSegment() to reduce duplication.

Suggested change
cur_segment_.start = -1;
cur_segment_.samples.clear();
ClearCurrentSegment();

Copilot uses AI. Check for mistakes.

Comment on lines +612 to +620
if False:
# If you want to process the speech segment as soon as
# speech is detected, you can use
current_segment = vad.current_segment
if len(current_segment.samples) > 0:
print(
f"speech starts at {current_segment.start/16000} seconds: ",
f"duration {len(current_segment.samples)/16000} seconds",
)
Copy link

Copilot AI Jul 15, 2025

Choose a reason for hiding this comment

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

[nitpick] The example code is guarded by if False, so it never runs. If this is meant for documentation, convert it to a commented block or set the condition to if True for a runnable demonstration.

Suggested change
if False:
# If you want to process the speech segment as soon as
# speech is detected, you can use
current_segment = vad.current_segment
if len(current_segment.samples) > 0:
print(
f"speech starts at {current_segment.start/16000} seconds: ",
f"duration {len(current_segment.samples)/16000} seconds",
)
# Example: If you want to process the speech segment as soon as
# speech is detected, you can use the following code:
# current_segment = vad.current_segment
# if len(current_segment.samples) > 0:
# print(
# f"speech starts at {current_segment.start/16000} seconds: ",
# f"duration {len(current_segment.samples)/16000} seconds",
# )

Copilot uses AI. Check for mistakes.

@csukuangfj csukuangfj merged commit a77ba48 into k2-fsa:master Jul 15, 2025
206 of 228 checks passed
@csukuangfj csukuangfj deleted the vad-current-speech-segment branch July 15, 2025 04:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Can we get the start position of the VAD before full utterrence is finished

1 participant