Skip to content

Conversation

@tegnike
Copy link
Owner

@tegnike tegnike commented Nov 24, 2024

参考

Summary by CodeRabbit

  • 新機能

    • メッセージ表示ロジックを改善し、感情タグを除去して表示するように変更。
    • 新しい感情タイプ EmotionType を導入し、感情処理を強化。
  • バグ修正

    • メッセージ処理におけるタグの扱いを感情に変更し、関連する関数のロジックを調整。
  • ドキュメント

    • 新しい EMOTIONS 定数を追加し、感情の種類を明確化。
  • リファクタリング

    • speakCharacter 関数のパラメータを Talk に変更し、処理を簡素化。

@vercel
Copy link

vercel bot commented Nov 24, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
aituber-kit ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 24, 2024 9:36pm

@coderabbitai
Copy link

coderabbitai bot commented Nov 24, 2024

Walkthrough

このプルリクエストでは、複数のコンポーネントと機能にわたる変更が行われ、特にメッセージ処理における感情の取り扱いが強化されました。ChatLogコンポーネントでは、メッセージから感情タグを削除するロジックが追加され、useExternalLinkageフックでは感情プロパティの型がより厳密に定義されました。さらに、メッセージの処理ロジックがタグから感情にシフトし、関連する型や関数が更新されました。全体として、感情処理の一貫性が向上し、いくつかの機能が簡素化されました。

Changes

ファイル 変更概要
src/components/chatLog.tsx EMOTIONSのインポート追加、メッセージから感情タグを削除するロジックを追加。
src/components/useExternalLinkage.tsx TmpMessageインターフェースとParamsインターフェースのemotionプロパティをEmotionTypeに変更。
src/features/chat/handlers.ts speakMessageHandlerprocessAIResponse関数でタグ処理を感情処理に変更。
src/features/messages/messages.ts TalkStyle型を削除し、EmotionType型を導入。Screenplay型を削除。
src/features/messages/speakCharacter.ts createSpeakCharacter関数のパラメータをscreenplayからtalkに変更。
src/features/messages/speakQueue.ts SpeakTask型のscreenplayプロパティをtalkに変更。
src/features/messages/synthesizeVoiceGSVI.ts style変数の設定を簡素化。
src/features/messages/synthesizeVoiceKoeiromap.ts synthesizeVoiceKoeiromapApi関数に新しいパラメータkoeiroParamを追加。
src/features/vrmViewer/model.ts speakメソッドのパラメータをScreenplayからTalkに変更。
src/utils/reduceTalkStyle.ts reduceTalkStyle関数と関連型を全てコメントアウト。

Possibly related PRs


🪧 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.

@tegnike tegnike changed the base branch from main to develop November 24, 2024 21:38
Copy link

@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 (8)
src/features/messages/synthesizeVoiceKoeiromap.ts (2)

59-70: 関数のドキュメント化とテストの追加を推奨します

emotionToTalkStyle関数の実装は明確ですが、以下の改善を提案します:

  1. JSDocによる関数の目的と戻り値の説明の追加
  2. エッジケースを含むユニットテストの追加

以下のような形でドキュメントを追加することを推奨します:

+/**
+ * 感情タイプをトークスタイルに変換します
+ * @param emotion - 変換する感情タイプ
+ * @returns トークスタイルを表す文字列
+ */
const emotionToTalkStyle = (emotion: EmotionType): string => {

ユニットテストのコードを生成しましょうか?


エラーメッセージの言語に一貫性がありません

アプリケーション全体のエラーメッセージを確認したところ、以下の点で一貫性に問題があります:

  • 音声合成関連のモジュール(Koeiromap、VOICEVOX、Google TTS、ElevenLabs等)は日本語でエラーメッセージを表示
  • VRMアニメーション、リップシンク、チャット機能などのコアモジュールは英語でエラーメッセージを表示
  • APIエンドポイントでは両方の言語が混在

推奨される修正箇所:

  • src/features/messages/synthesizeVoiceKoeiromap.tsのエラーメッセージを英語に統一
    throw new Error(`Invalid response from Koeiromap API. Status code: ${res.status}`)
    throw new Error('No audio URL returned from Koeiromap API')
    throw new Error(`Failed to fetch audio file from Koeiromap. Status code: ${resAudio.status}`)
    throw new Error(`Error occurred in Koeiromap: ${error.message}`)
    throw new Error('Unknown error occurred in Koeiromap')
🔗 Analysis chain

Line range hint 10-57: エラーメッセージの一貫性を確認してください

エラーメッセージが日本語で記述されていますが、アプリケーション全体での一貫性を確認する必要があります。

エラーメッセージの一貫性を確認するために以下のスクリプトを実行してください:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# アプリケーション全体でのエラーメッセージのパターンを確認
rg "throw new Error\(" -A 1

Length of output: 9060

src/components/useExternalLinkage.tsx (1)

Line range hint 1-108: アーキテクチャに関する提案

WebSocket接続のエラーハンドリングについて、以下の改善を検討してください:

  1. エラーイベントでのユーザーへのフィードバック
  2. 再接続の最大試行回数の設定
  3. エラー状態の集中管理

これらの改善により、より堅牢なエラーハンドリングが実現できます。

エラーハンドリングの実装例を提供しましょうか?

src/components/chatLog.tsx (2)

74-75: 正規表現パターンのパフォーマンス最適化の提案

正規表現パターンがレンダリングの度に生成されています。これをコンポーネントの外部で定義することで、パフォーマンスを改善できます。

以下のような実装を提案します:

+const emotionPattern = new RegExp(`\\[(${EMOTIONS.join('|')})\\]\\s*`, 'g')
+
 const Chat = ({
   role,
   message,
   characterName,
 }: {
   role: string
   message: string
   characterName: string
 }) => {
-  const emotionPattern = new RegExp(`\\[(${EMOTIONS.join('|')})\\]\\s*`, 'g')
   const processedMessage = message.replace(emotionPattern, '')

74-76: 感情処理の設計に関する提案

感情タグの処理方法が変更されていますが、この変更に関する設計の意図やガイドラインをドキュメント化することを推奨します。また、将来的な拡張性を考慮して、感情処理のロジックを別のユーティリティ関数として切り出すことも検討してください。

Also applies to: 97-97

src/features/messages/speakCharacter.ts (1)

Line range hint 189-222: テスト関数の改善が推奨されます

テスト関数がemotion: 'neutral'のみをテストしていますが、より包括的なテストのために以下の改善を提案します:

export const testVoiceVox = async () => {
  const ss = settingsStore.getState()
-  const talk: Talk = {
+  const emotions: Talk[] = [{
    message: 'ボイスボックスを使用します',
    emotion: 'neutral',
+  }, {
+    message: 'ボイスボックスを使用します(喜び)',
+    emotion: 'happy',
+  }, {
+    message: 'ボイスボックスを使用します(悲しみ)',
+    emotion: 'sad',
+  }]
+
+  for (const talk of emotions) {
    const buffer = await synthesizeVoiceVoicevoxApi(
      talk,
      ss.voicevoxSpeaker,
      ss.voicevoxSpeed,
      ss.voicevoxPitch,
      ss.voicevoxIntonation
    ).catch(() => null)
    if (buffer) {
      const hs = homeStore.getState()
      await hs.viewer.model?.speak(buffer, talk)
    }
+  }
}

同様の改善をtestAivisSpeech関数にも適用することを推奨します。

src/features/chat/handlers.ts (2)

578-580: リアルタイムAPIでの感情処理を改善できます

現在、感情が'neutral'にハードコードされていますが、より柔軟な実装が可能です。

以下のような改善を提案します:

- emotion: 'neutral',
+ emotion: type?.includes('emotion.') 
+   ? type.split('.')[1] as EmotionType 
+   : DEFAULT_EMOTION,

これにより:

  • 音声応答時の感情表現が可能になります
  • 将来の機能拡張に対応しやすくなります

Line range hint 1-590: アーキテクチャ面での改善提案

全体的なコード品質を向上させるため、以下の改善を提案します:

  1. 感情関連の定数の一元管理
  2. エラーハンドリングの強化
  3. ログ出力の統一

以下のような改善を検討してください:

  1. 感情関連の定数を別ファイルに分離
// emotions.ts
export const EMOTION_CONSTANTS = {
  DEFAULT: 'neutral' as EmotionType,
  PATTERN: /^\[(.*?)\]/,
  FORMAT: (emotion: EmotionType) => `[${emotion}]`
} as const;
  1. エラーハンドリングの追加
class EmotionParsingError extends Error {
  constructor(message: string) {
    super(`感情解析エラー: ${message}`);
    this.name = 'EmotionParsingError';
  }
}
  1. ログ出力の統一
const logEmotionProcessing = (
  emotion: EmotionType,
  context: string
) => {
  console.debug(`感情処理: ${emotion}, コンテキスト: ${context}`);
};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1d4fffd and 314afb5.

📒 Files selected for processing (10)
  • src/components/chatLog.tsx (3 hunks)
  • src/components/useExternalLinkage.tsx (1 hunks)
  • src/features/chat/handlers.ts (10 hunks)
  • src/features/messages/messages.ts (1 hunks)
  • src/features/messages/speakCharacter.ts (8 hunks)
  • src/features/messages/speakQueue.ts (2 hunks)
  • src/features/messages/synthesizeVoiceGSVI.ts (1 hunks)
  • src/features/messages/synthesizeVoiceKoeiromap.ts (2 hunks)
  • src/features/vrmViewer/model.ts (2 hunks)
  • src/utils/reduceTalkStyle.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/utils/reduceTalkStyle.ts
🔇 Additional comments (18)
src/features/messages/messages.ts (2)

9-10: LGTM: EMOTIONS定数とEmotionType型の追加

EMOTIONS定数とEmotionType型が適切に定義されています。


13-13: Talk型へのemotionプロパティ追加に伴うコード全体の更新を確認してください

Talk型にemotionプロパティが追加されました。これにより、Talk型を使用する全ての箇所でこのプロパティを正しく扱う必要があります。

以下のスクリプトを実行して、Talk型の使用箇所を特定し、emotionプロパティが適切に使用されているか確認してください。

✅ Verification successful

Let me analyze the results. The search shows that Talk type is used across multiple files, and in all instances where it's used, the emotion property is properly handled:

  1. In model.ts, the emotion is used for playing emotions: this.emoteController?.playEmotion(talk.emotion)
  2. In synthesizeVoiceKoeiromap.ts, emotion is converted to talk style: const reducedStyle = emotionToTalkStyle(talk.emotion)
  3. In test/example cases (speakCharacter.ts), emotion is properly initialized: emotion: 'neutral'
  4. All other files that import and use Talk type are voice synthesis related files that pass through the emotion property without modification.

I can now generate the final response:

emotionプロパティは全ての使用箇所で適切に処理されています

Talk型のemotionプロパティは、以下の主要な箇所で正しく使用されています:

  • VRMモデルの感情表現制御
  • 音声合成時の話者スタイル変換
  • テストケースでの初期化
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 説明: `Talk`型の使用箇所を検索し、`emotion`プロパティが適切に使用されているか確認します。

# コマンド: `Talk`型を使用している箇所を検索し、周辺のコードも5行表示
rg -A 5 'Talk'

# 期待結果: `Talk`型を使用している箇所が一覧表示されます。それぞれの場所で`emotion`プロパティが正しく追加・使用されているか確認してください。

Length of output: 14361

src/features/messages/synthesizeVoiceGSVI.ts (1)

Line range hint 24-39: エラーハンドリングの実装について

エラー処理が適切に実装されており、以下の点が評価できます:

  • HTTPレスポンスステータスの確認
  • エラーの型チェック
  • 日本語での明確なエラーメッセージ
src/features/messages/synthesizeVoiceKoeiromap.ts (1)

1-8: 型の安全性が向上しています!

EmotionTypeの導入とKoeiroParamの追加により、型の安全性が向上し、関数の意図がより明確になっています。

src/features/messages/speakQueue.ts (2)

1-1: 型の更新が適切に行われています

ScreenplayからTalkへの移行が一貫して行われており、型の定義が正しく更新されています。

Also applies to: 6-6


30-31: 実装の整合性を確認してください

speakメソッドの引数の変更に伴い、以下の点を確認することを推奨します:

  1. このクラスを使用している他のコンポーネントが新しいTalk型に対応していること
  2. エラーハンドリングがTalk型に対して適切であること

以下のスクリプトで関連する箇所を確認できます:

✅ Verification successful

Let me gather more information about the usage context.


Based on the gathered information, I can now provide the final response:

実装の整合性は問題ありません

speakCharacter.tsの実装を確認した結果:

  • Talk型は適切に定義・使用されており、全ての呼び出し箇所で正しく型が適用されています
  • エラーハンドリングはhandleTTSError関数で適切に実装されています
  • SpeakQueueの使用方法は一貫しており、talkパラメータは正しく渡されています
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# SpeakQueueクラスの使用箇所を確認
rg -l "new SpeakQueue" 

# speakメソッドの呼び出しパターンを確認
ast-grep --pattern 'speak($$$)'

Length of output: 98


Script:

#!/bin/bash
# Check the content of speakCharacter.ts to understand how SpeakQueue is used
cat src/features/messages/speakCharacter.ts

# Search for Talk type definition and usage
rg "type Talk" -A 5

# Search for any error handling related to speak method
rg "catch.*speak" -A 3

Length of output: 7048

src/features/vrmViewer/model.ts (2)

13-13: インポートの変更が適切に行われています

ScreenplayからTalkへの移行が正しく実装されており、PRの目的に沿っています。


79-82: メソッドの更新を確認してください

speakメソッドの変更は適切に実装されていますが、このメソッドを使用している他の箇所も更新されていることを確認する必要があります。

以下のスクリプトで、このメソッドの使用箇所を確認してください:

✅ Verification successful

Let me verify the usage of the speak method by checking the implementation of the callers to ensure they are using the updated signature correctly.


speakメソッドの使用箇所は正しく更新されています

コードベースの確認の結果、speakメソッドを呼び出しているすべての箇所(speakCharacter.tsspeakQueue.ts)で、新しいシグネチャ(buffertalkisNeedDecode)に従って正しく実装されていることが確認できました。以下の点が確認できました:

  • SpeakQueueクラスではspeak(audioBuffer, talk, isNeedDecode)の形で正しく呼び出されています
  • テスト関数(testVoiceVoxtestAivisSpeech)でもspeak(buffer, talk)の形で適切に実装されています
  • すべての呼び出し箇所でTalk型のパラメータが正しく渡されています
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: speak メソッドの使用箇所を確認

# speak メソッドの呼び出しを検索
rg -A 5 "speak\(" --type ts

Length of output: 1393


Script:

#!/bin/bash
# Check the implementation of files that call speak method
cat src/features/messages/speakCharacter.ts src/features/messages/speakQueue.ts

Length of output: 8519

src/components/useExternalLinkage.tsx (4)

7-7: 型の安全性が向上しました!

EmotionTypeのインポートにより、感情の型チェックが強化され、予期しない感情値の使用を防ぐことができます。


13-13: TmpMessageインターフェースの型安全性が向上しました!

emotionプロパティの型をstringからEmotionTypeに変更することで、より厳密な型チェックが可能になりました。


Line range hint 33-37: processMessage関数の実装は適切です

handleReceiveTextFromWsの呼び出しが、新しい型システムに正しく対応しています。


21-21: Paramsインターフェースの型安全性が向上しました!

handleReceiveTextFromWsemotionパラメータの型をEmotionTypeに変更することで、関数呼び出し時の型チェックが強化されました。

この変更による影響を確認するため、以下のスクリプトを実行します:

✅ Verification successful

型の整合性が確認できました!

EmotionType'neutral' | 'happy' | 'angry' | 'sad' | 'relaxed'のユニオン型として適切に定義されており、Talkインターフェースでも同じ型が使用されています。この型定義の変更により、感情パラメータの値が制限され、より安全なコード実装が実現されています。

  • src/features/messages/messages.tsEMOTIONS定数とEmotionTypeが明確に定義されています
  • handleReceiveTextFromWsの呼び出し時に正しく型チェックが行われることが確認できました
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: handleReceiveTextFromWsの使用箇所を確認し、新しい型との互換性を検証します

# handleReceiveTextFromWsの呼び出しパターンを検索
rg -A 3 "handleReceiveTextFromWs.*emotion" 

# EmotionTypeの使用箇所を確認
ast-grep --pattern 'EmotionType'

Length of output: 375


Script:

#!/bin/bash
# EmotionTypeの定義を確認
rg -A 5 "type EmotionType" 

# handleReceiveTextFromWsの実装と使用箇所をより詳しく確認
ast-grep --pattern 'handleReceiveTextFromWs($$$)'

# emotionパラメータを含むメッセージ関連の型定義を確認
rg -A 5 "interface.*Message.*emotion"

Length of output: 843


Script:

#!/bin/bash
# EMOTIONSの定義を確認
rg -A 5 "EMOTIONS.*=" 

# messageの型定義を確認
rg -A 10 "type.*message.*=.*{" --ignore-case

# handleReceiveTextFromWsの完全な実装を確認
ast-grep --pattern 'const handleReceiveTextFromWs = $$$'

Length of output: 732

src/components/chatLog.tsx (2)

3-3: 感情関連の定数のインポートが適切に追加されています

メッセージの感情処理に必要なEMOTIONS定数が正しくインポートされています。


97-97: 感情タグの除去処理の検証が必要です

メッセージから感情タグを除去する処理が追加されましたが、すべての感情タグが適切に処理されることを確認する必要があります。

✅ Verification successful

感情タグの処理が適切に実装されていることを確認しました

コードベースの分析から以下が確認できました:

  • 感情タグは [neutral][happy][angry][sad][relaxed] の5種類が定義されています
  • emotionPattern は正規表現を使用して、これらの感情タグを適切に検出・除去しています
  • メッセージ表示時に message.replace(emotionPattern, '') で感情タグが正しく除去されます
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 感情タグの使用箇所を確認
rg "\[\w+\]" --type=typescript --type=tsx

# EMOTIONSの定義を確認
rg "EMOTIONS.*=.*\[" --type=typescript --type=tsx

Length of output: 165


Script:

#!/bin/bash
# Search for emotion tags and EMOTIONS definition
rg "\[\w+\]" --type ts --type tsx
rg "EMOTIONS.*=.*\[" --type ts --type tsx

# Check the message processing implementation
ast-grep --pattern 'const processedMessage = $_'

Length of output: 279


Script:

#!/bin/bash
# Search for emotion tags and EMOTIONS definition without file type specification
rg "\[\w+\]"
rg "EMOTIONS.*=.*\["

# Check the emotion pattern definition
rg "emotionPattern.*=" -A 2

Length of output: 14118

src/features/messages/speakCharacter.ts (3)

5-5: importの変更が適切に行われています

Screenplayの代わりにTalk型をインポートする変更は、PRの目的に沿った適切な修正です。


31-36: パラメータの型変更が適切に実装されています

screenplay: Screenplayからtalk: Talkへの変更により、コードがよりシンプルになっています。メッセージの英語から日本語への変換処理も適切に更新されています。


Line range hint 49-124: TTSサービスの呼び出し更新の確認が必要です

各TTSサービスの実装がTalk型のemotionプロパティを適切に処理できることを確認する必要があります。

src/features/chat/handlers.ts (1)

468-468: 型の安全性が適切に確保されています

WebSocket経由の感情処理において、以下の点が適切に実装されています:

  • EmotionTypeの使用による型安全性の確保
  • デフォルト値の適切な設定
  • speakCharacter関数との整合性

Also applies to: 511-514

): Promise<ArrayBuffer> {
try {
const style = talk.style !== 'talk' ? talk.style : 'default'
const style = 'default'
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

感情パラメータの扱いに関する問題

APIリクエストでは emotion パラメータを使用していますが、固定値の 'default' を送信しています。Talk 型に含まれる感情情報を活用していない可能性があります。

以下の修正を提案します:

-const style = 'default'
+const emotion = talk.emotion ?? 'default'

そして、JSONリクエストボディも更新する必要があります:

{
  character: character,
-  emotion: style,
+  emotion: emotion,
  text: talk.message,
  // ...
}

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +61 to +66
// 返答内容の感情部分と返答部分を分離
let emotion: string = ''
const emotionMatch = remainingMessage.match(/^\[(.*?)\]/)
if (emotionMatch?.[0]) {
emotion = emotionMatch[0]
remainingMessage = remainingMessage.slice(emotion.length)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

感情抽出ロジックの改善が必要です

感情の抽出方法について、以下の改善点があります:

  1. 正規表現による抽出は脆弱である可能性があります
  2. デフォルトの感情設定がコード内の複数箇所で繰り返されています

以下のような改善を提案します:

+ const DEFAULT_EMOTION: EmotionType = 'neutral';
+ 
+ const extractEmotion = (text: string): { emotion: EmotionType, remainingText: string } => {
+   const emotionMatch = text.match(/^\[(.*?)\]/);
+   if (!emotionMatch?.[0]) {
+     return { emotion: DEFAULT_EMOTION, remainingText: text };
+   }
+   const emotionText = emotionMatch[1];
+   return {
+     emotion: emotionText as EmotionType,
+     remainingText: text.slice(emotionMatch[0].length)
+   };
+ };

この変更により:

  • 感情抽出ロジックが一元化されます
  • デフォルト値の管理が容易になります
  • 型安全性が向上します

Also applies to: 96-106

let receivedMessage = ''
let aiTextLog: Message[] = [] // 会話ログ欄で使用
let tag = ''
let emotion = ''
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

コードの重複を解消する必要があります

processAIResponse関数内の感情処理ロジックがspeakMessageHandlerと重複しています。

先ほど提案したextractEmotion関数を使用して、以下のようにリファクタリングすることを提案します:

- let emotion = ''
+ let emotion: EmotionType = DEFAULT_EMOTION
  
  // 感情抽出部分
- const emotionMatch = receivedMessage.match(/^\[(.*?)\]/)
- if (emotionMatch && emotionMatch[0]) {
-   emotion = emotionMatch[0]
-   receivedMessage = receivedMessage.slice(emotion.length)
- }
+ const { emotion: extractedEmotion, remainingText } = extractEmotion(receivedMessage);
+ emotion = extractedEmotion;
+ receivedMessage = remainingText;

これにより:

  • ロジックの一貫性が保たれます
  • コードの保守性が向上します
  • バグの可能性が減少します

Also applies to: 208-212, 236-249

@tegnike tegnike merged commit fbdfd61 into develop Nov 24, 2024
3 checks passed
@tegnike tegnike deleted the feature/fix-screenplay branch November 24, 2024 22:09
terisuke pushed a commit to terisuke/aituber-kit that referenced this pull request Dec 5, 2025
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