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: add voice audio preview button in tts-config option 为 TTS 设置选项添加了语音预览按钮 #5651

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

Conversation

Dakai
Copy link
Contributor

@Dakai Dakai commented Oct 13, 2024

💻 变更类型 | Change Type

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

🔀 变更说明 | Description of Change

在 TTS 配置选项中添加了一个语音预览按钮,允许用户在应用设置中试听语音效果。

📝 补充信息 | Additional Information

Summary by CodeRabbit

  • New Features

    • Enhanced TTS configuration with integrated speech synthesis capabilities.
    • Added a play/stop button for speech playback control, improving user interaction.
    • Retained voice selection dropdown for choosing from available voice options.
  • Bug Fixes

    • Improved error handling during speech synthesis requests.

Copy link

vercel bot commented Oct 13, 2024

@Dakai 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 13, 2024

Walkthrough

The changes in this pull request focus on the TTSConfigList component within app/components/tts-config.tsx. Modifications include the introduction of new state management for speech playback, an asynchronous function for handling speech synthesis, and a revised user interface featuring an IconButton for toggling speech playback. The component now tracks loading states and playback status while allowing users to select voices from a dropdown menu.

Changes

File Change Summary
app/components/tts-config.tsx - Added state variables: speechLoading and speechStatus.
- Introduced new method: async openaiSpeech(text: string).
- Modified JSX to include an IconButton for speech playback, replacing the previous voice selection Select element.

Possibly related PRs

  • add tts #5459: This PR adds TTS functionality, which is directly related to the changes in the main PR that enhance the TTSConfigList component for speech synthesis.
  • Feature play audio and video #5519: This PR introduces audio playback capabilities, which aligns with the main PR's focus on enhancing user interaction through speech playback controls in the TTS configuration.

Suggested reviewers

  • Dogtiti

🐇 "In the meadow where voices play,
New buttons hop and sing today.
With speech that flows like a gentle stream,
TTS brings life to every dream.
So choose your voice, let it be heard,
In this joyful world, spread the word!" 🎶


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

🧹 Outside diff range and nitpick comments (4)
app/components/tts-config.tsx (4)

Line range hint 69-69: Avoid assignment within arrow function expressions

Assigning values within an arrow function expression can be confusing and is flagged by static analysis tools. Use a block body instead.

Apply this diff to refactor the code:

-              (config) => (config.enable = e.currentTarget.checked),
+              (config) => {
+                config.enable = e.currentTarget.checked;
+              },

Line range hint 94-97: Avoid assignment within arrow function expressions

For better readability and to adhere to coding standards, avoid using assignments within arrow function expressions.

Apply this diff:

-                (config) =>
-                  (config.engine = TTSConfigValidator.engine(
-                    e.currentTarget.value,
-                  )),
+                (config) => {
+                  config.engine = TTSConfigValidator.engine(
+                    e.currentTarget.value,
+                  );
+                },

Line range hint 115-118: Avoid assignment within arrow function expressions

Using assignments inside arrow function expressions can be misleading. Use a block body to make the assignment explicit.

Apply this diff:

-                      (config) =>
-                        (config.model = TTSConfigValidator.model(
-                          e.currentTarget.value,
-                        )),
+                      (config) => {
+                        config.model = TTSConfigValidator.model(
+                          e.currentTarget.value,
+                        );
+                      },

147-148: Externalize hardcoded preview text for localization

The hardcoded preview text may not be appropriate for all users or locales. Consider moving it to a localized string to support internationalization.

Apply this diff:

-                        "NextChat,Unleash your imagination, experience the future of AI conversation.",
+                        Locale.Settings.TTS.PreviewText,

And add PreviewText to your localization files:

// In Locale.Settings.TTS
PreviewText: "NextChat, unleash your imagination, experience the future of AI conversation.",
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a84383f and bcd50b8.

📒 Files selected for processing (1)
  • app/components/tts-config.tsx (2 hunks)
🧰 Additional context used
🪛 Biome
app/components/tts-config.tsx

[error] 157-159: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

app/components/tts-config.tsx Outdated Show resolved Hide resolved
app/components/tts-config.tsx Outdated Show resolved Hide resolved
app/components/tts-config.tsx Outdated Show resolved Hide resolved
Copy link
Contributor

Your build has completed!

Preview deployment

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

🧹 Outside diff range and nitpick comments (1)
app/components/tts-config.tsx (1)

Line range hint 22-195: Consider performance optimizations

The TTSConfigList component has grown in complexity with the addition of speech playback functionality. While the implementation is sound, consider the following optimizations to improve performance:

  1. Memoize the IconButton and Select components using React.memo to prevent unnecessary re-renders.
  2. Extract the openaiSpeech function to a custom hook or a utility function outside the component to improve readability and potentially reduce re-renders.
  3. Use the useCallback hook for functions passed as props to child components to maintain referential equality across renders.

Here's an example of how you might implement these optimizations:

import React, { useState, useCallback, useMemo } from "react";

// ... other imports ...

const MemoizedIconButton = React.memo(IconButton);
const MemoizedSelect = React.memo(Select);

export function TTSConfigList(props: {
  ttsConfig: TTSConfig;
  updateConfig: (updater: (config: TTSConfig) => void) => void;
}) {
  // ... existing state variables ...

  const openaiSpeech = useCallback(async (text: string) => {
    // ... existing openaiSpeech implementation ...
  }, [props.ttsConfig]);

  const handleVoiceChange = useCallback((e: React.ChangeEvent<HTMLSelectElement>) => {
    props.updateConfig((config) => {
      config.voice = TTSConfigValidator.voice(e.currentTarget.value);
    });
  }, [props.updateConfig]);

  const voiceOptions = useMemo(() => 
    DEFAULT_TTS_VOICES.map((v, i) => (
      <option value={v} key={i}>{v}</option>
    ))
  , []);

  // ... rest of the component ...
}

These optimizations can help improve the component's performance, especially as it grows in complexity.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between bcd50b8 and 67192a7.

📒 Files selected for processing (1)
  • app/components/tts-config.tsx (2 hunks)
🧰 Additional context used
🔇 Additional comments (2)
app/components/tts-config.tsx (2)

2-2: LGTM: New imports and state variables are well-structured

The new imports and state variables are appropriately added to support the new speech playback functionality. The use of useState for managing speechLoading and speechStatus is a good practice for handling component-level state.

Also applies to: 14-19, 26-27


154-169: LGTM: Improved voice selection UI and handler

The voice selection UI has been improved by grouping the IconButton and Select component. The onChange handler for the Select component has been updated to address a previous review comment about assignments in arrow functions. These changes enhance both the user experience and code quality.

app/components/tts-config.tsx Outdated Show resolved Hide resolved
@Leizhenpeng
Copy link
Member

很实用的功能, 交互没问题 @Dogtiti

@Issues-translate-bot
Copy link

Bot detected the issue body's language is not English, translate it automatically.


Very practical function, no problem in interaction @Dogtiti

app/components/tts-config.tsx Outdated Show resolved Hide resolved
@lloydzhou
Copy link
Member

tts以及stt相关功能可能会暂停一下
优先处理openai realtime api

@Issues-translate-bot
Copy link

Bot detected the issue body's language is not English, translate it automatically.


tts and stt related functions may be suspended for a while
Prioritize openai realtime api

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 (2)
app/components/tts-config.tsx (2)

131-165: LGTM: Enhanced UI with speech playback control

The addition of the IconButton for speech playback control and the reorganization of the voice selection dropdown improve the user interface and enhance interaction. The layout changes are well-structured and improve the organization of related controls.

Consider adding an aria-label to the IconButton for better accessibility:

 <IconButton
   aria={Locale.Chat.Actions.Speech}
+  aria-label={speechStatus ? "Stop speech" : "Start speech"}
   icon={speechStatus ? <SpeakStopIcon /> : <SpeakIcon />}
   text={
     speechLoading
       ? "Loading..."
       : speechStatus
       ? Locale.Chat.Actions.Stop
       : Locale.Chat.Actions.Speech
   }
   onClick={() => {
     openaiSpeech(
       "NextChat,Unleash your imagination, experience the future of AI conversation.",
     );
   }}
 />

This change will improve the accessibility of the button for screen reader users.


151-157: Simplify onChange handler for voice selection

The onChange handler for the voice selection dropdown can be simplified for better readability. Consider the following change:

 onChange={(e) => {
-  props.updateConfig((config) => {
-    config.voice = TTSConfigValidator.voice(
-      e.currentTarget.value,
-    );
-  });
+  props.updateConfig((config) => ({
+    ...config,
+    voice: TTSConfigValidator.voice(e.currentTarget.value),
+  }));
 }}

This change maintains the same functionality while improving code clarity and adhering to immutability principles.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 67192a7 and ab4bf3b.

📒 Files selected for processing (1)
  • app/components/tts-config.tsx (2 hunks)
🧰 Additional context used
🔇 Additional comments (2)
app/components/tts-config.tsx (2)

2-2: LGTM: New imports and ttsPlayer initialization

The new imports and the creation of a single ttsPlayer instance outside the component are appropriate for the added speech synthesis functionality. This approach ensures efficient resource usage by avoiding recreation of the player on each render.

Also applies to: 7-11, 14-19, 21-21


26-27: LGTM: New state variables for speech synthesis

The addition of speechLoading and speechStatus state variables is appropriate for managing the loading and playback status of the speech synthesis feature. The naming is clear and descriptive, enhancing code readability.

app/components/tts-config.tsx 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: 2

🧹 Outside diff range and nitpick comments (1)
app/components/tts-config.tsx (1)

22-22: Consider scoping the ttsPlayer instance to the component.

Creating a global ttsPlayer instance could lead to issues if multiple instances of the component are rendered. Consider moving this into the component or managing it through React Context.

-const ttsPlayer = createTTSPlayer();
+function TTSConfigList(props: {
+  ttsConfig: TTSConfig;
+  updateConfig: (updater: (config: TTSConfig) => void) => void;
+}) {
+  const ttsPlayer = React.useMemo(() => createTTSPlayer(), []);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ab4bf3b and c3b50a9.

📒 Files selected for processing (1)
  • app/components/tts-config.tsx (2 hunks)
🔇 Additional comments (1)
app/components/tts-config.tsx (1)

166-181: LGTM! Voice selection implementation is clean and follows best practices.

The code incorporates previous review suggestions and handles voice selection appropriately.

Comment on lines +148 to +182
<div style={{ display: "flex", gap: "10px" }}>
<IconButton
aria={Locale.Chat.Actions.Speech}
icon={speechStatus ? <SpeakStopIcon /> : <SpeakIcon />}
text={
speechLoading
? "Loading..."
: speechStatus
? Locale.Chat.Actions.Stop
: Locale.Chat.Actions.Speech
}
onClick={() => {
openaiSpeech(
"NextChat,Unleash your imagination, experience the future of AI conversation.",
);
}}
/>

<Select
value={props.ttsConfig.voice}
onChange={(e) => {
props.updateConfig((config) => {
config.voice = TTSConfigValidator.voice(
e.currentTarget.value,
)),
);
}}
>
{DEFAULT_TTS_VOICES.map((v, i) => (
<option value={v} key={i}>
{v}
</option>
))}
</Select>
);
});
}}
>
{DEFAULT_TTS_VOICES.map((v, i) => (
<option value={v} key={i}>
{v}
</option>
))}
</Select>
</div>
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Several UI improvements recommended.

  1. The preview text should be localized
  2. Consider moving inline styles to CSS classes
  3. The loading state could benefit from a loading spinner component
-<div style={{ display: "flex", gap: "10px" }}>
+<div className="tts-voice-controls">

-text={
-  speechLoading
-    ? "Loading..."
-    : speechStatus
-    ? Locale.Chat.Actions.Stop
-    : Locale.Chat.Actions.Speech
-}
+text={
+  speechLoading
+    ? Locale.Chat.Actions.Loading
+    : speechStatus
+    ? Locale.Chat.Actions.Stop
+    : Locale.Chat.Actions.Speech
+}

-"NextChat,Unleash your imagination, experience the future of AI conversation."
+Locale.Settings.TTS.PreviewText

Add this CSS to your stylesheet:

.tts-voice-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

Comment on lines +58 to +60
if (typeof (error as Error).message === "string") {
showToast((error as Error).message);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve error type checking.

The error type assertion could be improved using type guards for better type safety.

-if (typeof (error as Error).message === "string") {
+if (error instanceof Error) {
   showToast(error.message);
+} else {
+  showToast("An unexpected error occurred");
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (typeof (error as Error).message === "string") {
showToast((error as Error).message);
}
if (error instanceof Error) {
showToast(error.message);
} else {
showToast("An unexpected error occurred");
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants