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

feat: implement language detection for Microsoft Voice TTS #5582

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

hengstchon
Copy link
Contributor

@hengstchon hengstchon commented Oct 3, 2024

πŸ’» ε˜ζ›΄η±»εž‹ | Change Type

  • feat
  • fix
  • refactor
  • perf
  • style
  • test
  • docs
  • ci
  • chore
  • build

πŸ”€ ε˜ζ›΄θ―΄ζ˜Ž | Description of Change

This update introduces the use of the eld package to detect the language of the input text. Based on the detected language, the corresponding Microsoft TTS voice is selected. If the detected language is not supported, the application falls back to the default voice configuration.

πŸ“ θ‘₯充俑息 | Additional Information

You can find the list of languages supported by the eld package here.

For a comprehensive list of Microsoft TTS voices, please refer to the documentation here.

Summary by CodeRabbit

  • New Features

    • Enhanced text-to-speech functionality with dynamic voice selection based on detected language.
    • Added new voice options for Microsoft Edge TTS, expanding available TTS capabilities.
  • Bug Fixes

    • Improved language detection for more accurate voice selection in speech synthesis.
  • Chores

    • Updated project dependencies to include the new eld package.

Copy link

vercel bot commented Oct 3, 2024

@hengstchon is attempting to deploy a commit to the NextChat Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Oct 3, 2024

Walkthrough

This pull request introduces modifications to enhance the text-to-speech functionality in the app/components/chat.tsx file by integrating a new constant, MS_EDGE_TTS_VOICES, which maps languages to specific voice models. The openaiSpeech function has been updated to utilize this constant for selecting the appropriate voice based on detected language. Additionally, a new enumeration for MS_EDGE_TTS_VOICES has been added in app/constant.ts, and a new dependency, eld, has been included in the package.json file to facilitate language detection.

Changes

File Change Summary
app/components/chat.tsx Integrated MS_EDGE_TTS_VOICES constant; modified openaiSpeech for language-based voice selection.
app/constant.ts Added export enum MS_EDGE_TTS_VOICES for voice options; minor formatting adjustments.
app/global.d.ts Added module declaration for "eld" and exported constant for language detection.
package.json Added new dependency "eld": "^1.0.0" in dependencies.

Possibly related PRs

  • add ttsΒ #5459: The changes in this PR enhance the text-to-speech functionality, which is directly related to the modifications made in the main PR that also focuses on improving speech capabilities through language detection and voice selection.

Suggested reviewers

  • Dogtiti

Poem

In the land of chat, where voices play,
New tones arise, brightening the day.
With languages detected, oh what a treat,
Each word now sings, oh so sweet!
A hop and a skip, we dance with glee,
For voices of many, now sing joyfully! πŸ‡βœ¨


πŸ“œ Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 791ee72 and 554901d.

β›” Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
πŸ“’ Files selected for processing (4)
  • app/components/chat.tsx (3 hunks)
  • app/constant.ts (1 hunks)
  • app/global.d.ts (1 hunks)
  • package.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • app/constant.ts
  • app/global.d.ts
  • package.json
πŸ”‡ Additional comments (2)
app/components/chat.tsx (2)

108-108: LGTM!

The import statement is correctly placed with other constant imports.


1219-1223: ⚠️ Potential issue

Improve language detection accuracy.

The language detection has two potential issues:

  1. It's performed on markdown text which could contain syntax that affects detection accuracy.
  2. The text conversion to plain text is done before language detection, which could strip important context.

Apply this diff to fix the issues:

 const { markdownToTxt } = require("markdown-to-txt");
-const textContent = markdownToTxt(text);
+let detectLang = 'default';
+try {
+  const detectionResult = eld.detect(text);
+  if (detectionResult && detectionResult.language) {
+    detectLang = detectionResult.language;
+  }
+} catch (error) {
+  console.error('Language detection failed:', error);
+}
+const textContent = markdownToTxt(text);
 const edgeVoiceName =
   detectLang in MS_EDGE_TTS_VOICES
     ? MS_EDGE_TTS_VOICES[detectLang as keyof typeof MS_EDGE_TTS_VOICES]
     : accessStore.edgeVoiceName();

Likely invalid or redundant comment.


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 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: 1

🧹 Outside diff range and nitpick comments (4)
app/constant.ts (2)

273-332: Approve the addition of MS_EDGE_TTS_VOICES enumeration with a suggestion.

The new MS_EDGE_TTS_VOICES enumeration is a well-structured addition that supports the implementation of language detection for Microsoft Voice TTS. It provides a comprehensive mapping of language codes to specific TTS voices, which aligns with the PR objectives.

Consider adding a comment above the enumeration to briefly explain its purpose and any special cases (e.g., fallback voices for certain languages). This would enhance code readability and maintainability. For example:

// Mapping of language codes to Microsoft Edge TTS voice names.
// Note: Some languages use fallback voices (e.g., 'be' and 'tl' use 'en-US-AlloyMultilingualNeural').
export enum MS_EDGE_TTS_VOICES {
  // ... (existing enum entries)
}

273-332: Consider updating TTS-related constants for consistency.

The addition of MS_EDGE_TTS_VOICES enhances the TTS capabilities of the application. To fully integrate this new feature:

  1. Consider adding a new constant for the default Edge TTS voice, similar to DEFAULT_TTS_VOICE.
  2. Update DEFAULT_TTS_ENGINES to include "Edge-TTS" if it's not already present.
  3. If applicable, add a constant for Edge TTS models, similar to DEFAULT_TTS_MODELS.

These changes would ensure consistency across all TTS-related constants and make it easier to use the new Edge TTS voices throughout the application.

app/components/chat.tsx (2)

Line range hint 1211-1212: Use 'import' Instead of 'require' for ES6 Modules

Using require inside a function is not recommended in ES6 modules and may cause issues with bundlers. Replace require with import at the top level.

Apply this change:

-const { markdownToTxt } = require("markdown-to-txt");
+import { markdownToTxt } from "markdown-to-txt";

Line range hint 1210-1230: Avoid Re-initializing Constants in 'openaiSpeech' Function

Variables like api and config are re-initialized every time openaiSpeech is called. Consider moving these initializations outside the function if they remain constant to optimize performance.

Refactor the code as follows:

-async function openaiSpeech(text: string) {
-  if (speechStatus) {
-    ttsPlayer.stop();
-    setSpeechStatus(false);
-  } else {
-    var api: ClientApi;
-    api = new ClientApi(ModelProvider.GPT);
-    const config = useAppConfig.getState();
+const api: ClientApi = new ClientApi(ModelProvider.GPT);
+const config = useAppConfig.getState();
+async function openaiSpeech(text: string) {
+  if (speechStatus) {
+    ttsPlayer.stop();
+    setSpeechStatus(false);
+  } else {
     setSpeechLoading(true);
     ttsPlayer.init();
     let audioBuffer: ArrayBuffer;
πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

πŸ“₯ Commits

Files that changed from the base of the PR and between 05e6e4b and 3c32f77.

β›” Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
πŸ“’ Files selected for processing (3)
  • app/components/chat.tsx (3 hunks)
  • app/constant.ts (1 hunks)
  • package.json (1 hunks)
πŸ”‡ Additional comments (3)
package.json (1)

28-28: New dependency added: eld@1.0.0

The addition of the eld package aligns with the PR objective of implementing language detection for Microsoft Voice TTS. This package will enable the application to identify the language of input text, which is crucial for selecting the appropriate Microsoft TTS voice.

A few points to consider:

  1. The version ^1.0.0 allows for compatible updates. This is generally good practice, but ensure that the package maintains backwards compatibility in minor updates.
  2. As this is a new dependency, make sure to update any relevant documentation or setup instructions for other developers.
  3. Verify that this package is actively maintained and compatible with the project's Node.js version.

To ensure the package is being used correctly, let's check its usage in the codebase:

βœ… Verification successful

Dependency eld@^1.0.0 is properly integrated

The eld package is correctly imported in app/components/chat.tsx, aligning with the PR objective of implementing language detection for Microsoft Voice TTS. This confirms that the addition of eld is necessary and appropriately utilized within the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for imports or requires of the 'eld' package
rg --type typescript --type javascript 'import.*from.*eld|require\(.*eld.*\)'

Length of output: 114


Script:

#!/bin/bash
# Search for imports or requires of the 'eld' package using correct file types
rg --type ts --type js 'import.*from.*eld|require\(.*eld.*\)'

Length of output: 114

app/constant.ts (1)

273-332: Summary of changes and impact

The addition of the MS_EDGE_TTS_VOICES enumeration to app/constant.ts is a well-structured and valuable enhancement that supports the implementation of language detection for Microsoft Voice TTS. This change:

  1. Provides a comprehensive mapping of language codes to specific TTS voices.
  2. Aligns with the existing structure and purpose of the file.
  3. Enhances the application's TTS capabilities without disrupting existing functionality.

To fully leverage this addition, consider updating related TTS constants and adding a brief explanatory comment as suggested in previous comments.

app/components/chat.tsx (1)

108-108: Import 'MS_EDGE_TTS_VOICES' Correctly

The import statement for MS_EDGE_TTS_VOICES is correctly added from the '../constant' module, aligning with its usage in the code.

Comment on lines +1216 to +1223
const detectLang = eld.detect(text).language;
const edgeVoiceName =
detectLang in MS_EDGE_TTS_VOICES
? MS_EDGE_TTS_VOICES[detectLang as keyof typeof MS_EDGE_TTS_VOICES]
: accessStore.edgeVoiceName();
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

Add Error Handling for Language Detection

The call to eld.detect(text).language may return undefined or throw an error if the language cannot be detected. To ensure stability, add error handling for cases where language detection fails.

Apply the following changes to handle potential errors:

 const { markdownToTxt } = require("markdown-to-txt");
 const textContent = markdownToTxt(text);
+let detectLang = 'default';
+try {
+  const detectionResult = eld.detect(text);
+  if (detectionResult && detectionResult.language) {
+    detectLang = detectionResult.language;
+  }
+} catch (error) {
+  console.error('Language detection failed:', error);
+}
 const edgeVoiceName =
   detectLang in MS_EDGE_TTS_VOICES
     ? MS_EDGE_TTS_VOICES[detectLang as keyof typeof MS_EDGE_TTS_VOICES]
     : accessStore.edgeVoiceName();

Committable suggestion was skipped due to low confidence.

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)
app/global.d.ts (1)

38-42: LGTM! Consider adding a comment for clarity.

The new module declaration for "eld" is correctly implemented and aligns with the PR objectives. It provides proper type information for the language detection feature.

Consider adding a brief comment above the module declaration to explain its purpose:

+// Declaration for the 'eld' package used for language detection
 declare module "eld" {
   export const eld: {
     detect: (text: string) => { language: string };
   };
 }
πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

πŸ“₯ Commits

Files that changed from the base of the PR and between 3c32f77 and 791ee72.

πŸ“’ Files selected for processing (1)
  • app/global.d.ts (1 hunks)

Copy link
Contributor

github-actions bot commented Oct 3, 2024

Your build has completed!

Preview deployment

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.

2 participants