Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

packaging:drop dependency on neon package #8

Merged
merged 5 commits into from
Dec 13, 2024
Merged

Conversation

JarbasAl
Copy link
Member

@JarbasAl JarbasAl commented Dec 13, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new Model class for enhanced speech-to-text functionality.
    • Added support for multiple languages with specific models.
    • Updated installation instructions in the README for optimal PyTorch installation.
  • Bug Fixes

    • Improved error handling for unsupported languages.
  • Chores

    • Updated dependencies in requirements.txt to include necessary libraries for STT functionality and audio processing.
    • Removed outdated dependency for streaming-stt-nemo.

Copy link
Contributor

coderabbitai bot commented Dec 13, 2024

Warning

Rate limit exceeded

@JarbasAl has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 18 minutes and 30 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 66fe636 and 4ac43e1.

📒 Files selected for processing (2)
  • .github/workflows/unit_tests.yml (0 hunks)
  • requirements.txt (1 hunks)

Walkthrough

The changes in this pull request primarily involve the introduction of a new engine.py file containing a Model class for speech-to-text functionality. The import statements in __init__.py have been updated to source Model and available_languages from the new engine module. Additionally, the requirements.txt file has been modified to remove the streaming-stt-nemo dependency and add several new dependencies relevant to the STT functionality, organized into categorized sections. The README.md has been updated to provide installation instructions for a CPU-only version of PyTorch.

Changes

File Change Summary
ovos_stt_plugin_citrinet/init.py Updated import source for Model and available_languages; removed a commented-out line in the constructor.
ovos_stt_plugin_citrinet/engine.py Added a new Model class with methods for STT functionality, including model initialization and audio processing.
requirements.txt Removed streaming-stt-nemo; added dependencies for torch, onnxruntime, sentencepiece, soxr, pydub, and huggingface-hub, organized into sections.
README.md Added installation instructions for a CPU-only version of PyTorch to avoid unnecessary dependencies.

Possibly related PRs

  • feat/initial_implementation #1: The changes in ovos_stt_plugin_citrinet/__init__.py in the main PR directly relate to the initial implementation of the STT plugin introduced in PR feat/initial_implementation #1, as both involve modifications to the same file and are part of the same project.
  • documentation:add WER #4: The modifications in the README.md file for the OVOS Citrinet STT plugin provide context and documentation that support the changes made in the main PR, particularly regarding the functionality of the Model class and its integration into the plugin.

Suggested labels

enhancement, documentation

Poem

🐰 In the land of code where rabbits play,
New models hop in to save the day.
With dependencies fresh and imports anew,
Speech-to-text magic is waiting for you!
So let’s cheer for the changes, both big and small,
For every little tweak makes our project stand tall! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Experiment)
  • @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
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (3)
ovos_stt_plugin_citrinet/engine.py (1)

127-135: Use torch.no_grad() context during inference for efficiency.

Wrapping inference code with torch.no_grad() prevents unnecessary gradient calculations, improving performance and reducing memory usage.

Modify the _run_preprocessor method:

def _run_preprocessor(self, audio_16k: np.array):
    with torch.no_grad():
        input_signal = torch.tensor(audio_16k).unsqueeze(0)
        length = torch.tensor(len(audio_16k)).unsqueeze(0)
        processed_signal, processed_signal_len = self.preprocessor.forward(
            input_signal=input_signal, length=length
        )
    processed_signal = processed_signal.numpy()
    processed_signal_len = processed_signal_len.numpy()
    return processed_signal, processed_signal_len

Consider applying torch.no_grad() in other methods where inference is performed.

ovos_stt_plugin_citrinet/__init__.py (2)

Line range hint 29-29: Correct the typo in the docstring of the execute method.

The word "speach" should be corrected to "speech" in the docstring.

Apply this correction:

'''
- Executes speach recognition
+ Executes speech recognition

Line range hint 54-68: Move example code to a separate script or test file.

Including executable code under __main__ in __init__.py is not recommended, as it can cause unintended side effects when the module is imported. Move this example code to a dedicated example script or test module.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8eaef9e and 5d11fa4.

📒 Files selected for processing (3)
  • ovos_stt_plugin_citrinet/__init__.py (1 hunks)
  • ovos_stt_plugin_citrinet/engine.py (1 hunks)
  • requirements.txt (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • requirements.txt
🔇 Additional comments (2)
ovos_stt_plugin_citrinet/__init__.py (2)

8-8: Ensure import statement reflects new module structure.

The import statement now sources Model and available_languages from ovos_stt_plugin_citrinet.engine. This aligns with the introduction of the new engine.py file.


11-12: Verify the default language setting in __init__.

The default language is set to "ca". Confirm that this is intentional and matches user expectations. If a different default language is preferred, consider updating it.

Comment on lines +187 to +194
def _trim_memory():
"""
If possible, gives memory allocated by PyTorch back to the system
"""
libc = ctypes.CDLL("libc.so.6")
libc.malloc_trim(0)
gc.collect()

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure cross-platform compatibility in _trim_memory method.

The _trim_memory method uses libc.so.6, which is specific to Linux systems. This will raise an exception on other platforms like Windows or macOS. Consider adding a platform check or using a cross-platform approach for memory trimming.

Modify the method to check the operating system:

import platform

@staticmethod
def _trim_memory():
    """
    If possible, gives memory allocated by PyTorch back to the system.
    """
    if platform.system() == 'Linux':
        libc = ctypes.CDLL("libc.so.6")
        libc.malloc_trim(0)
    gc.collect()

Comment on lines +199 to +201
def _to_float32(self, audio_buffer: np.array):
audio_fp32 = np.divide(audio_buffer, np.iinfo(audio_buffer.dtype).max, dtype=np.float32)
return audio_fp32
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle floating-point data types in _to_float32 method.

The _to_float32 method assumes that audio_buffer has an integer data type. If audio_buffer is already a floating-point array, np.iinfo will raise an error. Add a check to handle floating-point inputs appropriately.

Update the method to accommodate different data types:

def _to_float32(self, audio_buffer: np.array):
    if np.issubdtype(audio_buffer.dtype, np.integer):
        max_val = np.iinfo(audio_buffer.dtype).max
        audio_fp32 = np.divide(audio_buffer, max_val, dtype=np.float32)
    elif np.issubdtype(audio_buffer.dtype, np.floating):
        audio_fp32 = audio_buffer.astype(np.float32)
    else:
        raise ValueError(f"Unsupported audio buffer data type: {audio_buffer.dtype}")
    return audio_fp32

ovos_stt_plugin_citrinet/engine.py Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
README.md (1)

12-17: Improve formatting and punctuation of installation instructions.

The installation instructions could be clearer with better formatting and punctuation:

-by default this plugin will install the full pytorch, to avoid dragging all the dependencies it is recommended you install the cpu only version of pytorch **before** installing the plugin
+By default, this plugin will install the full PyTorch. To avoid dragging all the dependencies, it is recommended you install the CPU-only version of PyTorch **before** installing the plugin.

-`pip install torch==2.1.0+cpu  -f https://download.pytorch.org/whl/torch_stable.html`
+```bash
+pip install torch==2.1.0+cpu -f https://download.pytorch.org/whl/torch_stable.html
+```

-If you skip the step above then the full pytorch will be installed together with the plugin
+If you skip the step above, then the full PyTorch will be installed together with the plugin.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~12-~12: A comma might be missing here.
Context: ...e used with this plugin ## Install by default this plugin will install the full pytor...

(AI_EN_LECTOR_MISSING_PUNCTUATION_COMMA)


[uncategorized] ~12-~12: A period might be missing here.
Context: ...on of pytorch before installing the plugin `pip install torch==2.1.0+cpu -f http...

(AI_EN_LECTOR_MISSING_PUNCTUATION_PERIOD)


[typographical] ~16-~16: Consider adding a comma.
Context: ...stable.html` If you skip the step above then the full pytorch will be installed toge...

(IF_THEN_COMMA)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5d11fa4 and 2bdca95.

📒 Files selected for processing (2)
  • README.md (1 hunks)
  • requirements.txt (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • requirements.txt
🧰 Additional context used
🪛 LanguageTool
README.md

[uncategorized] ~12-~12: A comma might be missing here.
Context: ...e used with this plugin ## Install by default this plugin will install the full pytor...

(AI_EN_LECTOR_MISSING_PUNCTUATION_COMMA)


[uncategorized] ~12-~12: A period might be missing here.
Context: ...on of pytorch before installing the plugin `pip install torch==2.1.0+cpu -f http...

(AI_EN_LECTOR_MISSING_PUNCTUATION_PERIOD)


[typographical] ~16-~16: Consider adding a comma.
Context: ...stable.html` If you skip the step above then the full pytorch will be installed toge...

(IF_THEN_COMMA)

🔇 Additional comments (1)
README.md (1)

14-14: Verify PyTorch version compatibility.

Let's verify if the specified PyTorch version (2.1.0) matches the version constraints in requirements.txt.

✅ Verification successful

PyTorch version in README.md is compatible with requirements.txt

The PyTorch version (2.1.0) specified in the installation command matches the version constraint in requirements.txt (torch>=2.1.0), ensuring compatibility.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check PyTorch version specification in requirements.txt
rg "torch[>=<]" requirements.txt

Length of output: 47

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (4)
ovos_stt_plugin_citrinet/engine.py (4)

97-106: Enhance error messages in _init_model_from_path method.

The method raises a ValueError if the provided path is not valid, but additional checks on the existence of required files could improve error reporting.

Consider updating the method to check for the required files:

def _init_model_from_path(self, path: str):
    if not os.path.isdir(path):
        raise ValueError(f"'{path}' is not a valid model directory.")
    preprocessor_path = os.path.join(path, "preprocessor.ts")
    encoder_path = os.path.join(path, "model.onnx")
    tokenizer_path = os.path.join(path, "tokenizer.spm")
    if not all(os.path.isfile(p) for p in [preprocessor_path, encoder_path, tokenizer_path]):
        raise ValueError(f"Model files are missing in '{path}'. Expected 'preprocessor.ts', 'model.onnx', and 'tokenizer.spm'.")
    self._init_preprocessor(preprocessor_path)
    self._init_encoder(encoder_path)
    self._init_tokenizer(tokenizer_path)
    self._trim_memory()

172-173: Optimize memory trimming in stt method.

Calling _trim_memory after each STT operation might introduce performance overhead. Assess whether it's necessary to trim memory every time or if it can be called less frequently.


175-179: Add error handling to stt_file method.

The stt_file method does not handle exceptions that may occur during file reading or processing. Consider adding try-except blocks to provide meaningful error messages to the users.

def stt_file(self, file_path: str):
    try:
        audio_buffer, sr = self.read_file(file_path)
        current_hypotheses = self.stt(audio_buffer, sr)
        return current_hypotheses
    except Exception as e:
        raise RuntimeError(f"An error occurred while processing the file '{file_path}': {e}")

197-199: Handle exceptions in _resample method.

The soxr.resample function may raise exceptions if the input parameters are invalid. Adding error handling can improve the robustness of the method.

Consider wrapping the resampling in a try-except block:

def _resample(self, audio_fp32: np.array, sr: int):
    try:
        audio_16k = soxr.resample(audio_fp32, sr, self.sample_rate)
        return audio_16k
    except Exception as e:
        raise RuntimeError(f"Resampling failed: {e}")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2bdca95 and 66fe636.

📒 Files selected for processing (1)
  • ovos_stt_plugin_citrinet/engine.py (1 hunks)
🔇 Additional comments (5)
ovos_stt_plugin_citrinet/engine.py (5)

1-30: Review licensing and attribution in the header comments.

The file contains licensing and contributor information from the NeonGecko project. Ensure that the licensing terms are compatible with this project, and update the attribution if necessary to reflect the contributors and license applicable to your codebase.


88-90: Good job adding error handling for unsupported languages in _init_model.

The inclusion of a check for unsupported languages improves the robustness of the model initialization process.


130-137: Verify the input shapes and types in _run_preprocessor method.

Ensure that the input tensors are correctly shaped and of the expected data type to prevent runtime errors during the preprocessing step.


189-196: ⚠️ Potential issue

Ensure cross-platform compatibility in _trim_memory method.

The _trim_memory method uses libc.so.6, which is specific to Linux systems. This will raise an exception on other platforms like Windows or macOS. Consider adding a platform check or using a cross-platform approach for memory trimming.

Apply this change to handle cross-platform compatibility:

import platform

@staticmethod
def _trim_memory():
    """
    If possible, gives memory allocated by PyTorch back to the system.
    """
    if platform.system() == 'Linux':
        libc = ctypes.CDLL("libc.so.6")
        libc.malloc_trim(0)
    gc.collect()

201-203: ⚠️ Potential issue

Handle floating-point data types in _to_float32 method.

The _to_float32 method assumes that audio_buffer has an integer data type. If audio_buffer is already a floating-point array, np.iinfo will raise an error. Add a check to handle floating-point inputs appropriately.

Update the method to accommodate different data types:

def _to_float32(self, audio_buffer: np.array):
    if np.issubdtype(audio_buffer.dtype, np.integer):
        max_val = np.iinfo(audio_buffer.dtype).max
        audio_fp32 = np.divide(audio_buffer, max_val, dtype=np.float32)
    elif np.issubdtype(audio_buffer.dtype, np.floating):
        audio_fp32 = audio_buffer.astype(np.float32)
    else:
        raise ValueError(f"Unsupported audio buffer data type: {audio_buffer.dtype}")
    return audio_fp32

@JarbasAl JarbasAl merged commit 4bfcbeb into dev Dec 13, 2024
1 of 2 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Dec 13, 2024
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.

1 participant