Skip to content

TTS系の修正 - #4049

Merged
TinyKitten merged 3 commits into
devfrom
fix/tts
Feb 2, 2025
Merged

TinyKitten merged 3 commits into
devfrom
fix/tts

Conversation

@TinyKitten

@TinyKitten TinyKitten commented Feb 2, 2025 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • 音声合成機能の発音補正処理が改善され、より自然な読み上げが実現されました。
  • Refactor

    • テキスト正規化処理を整理・集約し、内部ロジックの効率化を図りました。
  • Tests

    • 発音処理に関するテストケースを新規追加・改善し、品質保証の信頼性が向上しました。
  • Chores

    • 開発環境の更新(Node.js のバージョン更新や ECMAScript ターゲットの見直しなど)および各種設定の整理を実施しました。

@coderabbitai

coderabbitai Bot commented Feb 2, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

今回の変更では、normalizeRomanText 関数のテストおよび実装の再配置と改良、設定ファイルの更新、Node.js バージョンおよび依存関係のアップデートが行われました。ユニットテストのディレクトリ移動や削除、Jest 用の新しい設定ファイルの追加、さらに音声合成処理内での正規化ロジックの呼び出し変更などが実施されています。

Changes

ファイル / ディレクトリ 変更内容
__tests__/utils/normalize.test.ts
functions/src/utils/normalize.test.ts
旧テストファイルの削除と、normalizeRomanText のテストを含む新規テストスイートの追加。
src/utils/normalize.ts
functions/src/utils/normalize.ts
元の normalizeRomanText 関数を削除し、新しいファイルに改良版の normalizeRomanText 関数を実装。文字の大文字・小文字変換や特定文字列の置換ロジックが更新されています。
functions/biome.json "files.ignore" 配列が更新され、除外対象が ["**/node_modules/**", "jest.config.js"] に変更。
functions/jest.config.js TypeScript 用 ts-jest を適用する Jest 設定ファイルを新規追加。
functions/package.json テスト実行用の "test": "jest" スクリプト追加、Node エンジンバージョンを "20" に更新、新たな devDependencies (@types/jest, jest, ts-jest) を追加。
functions/src/index.ts normalizeRomanText 関数をインポートし、SSML 変換処理の中で使用。特定の文字列処理やログ出力に変更が加えられ、音声合成出力の精度向上を図っています。
src/hooks/useTTSText.ts normalizeRomanText 関数の呼び出しを削除し、対象の文字列プロパティに直接代入。英語・日本語テキストのテンプレートも若干調整。
functions/tsconfig.json コンパイルターゲットを "es2017" から "ES2021" に更新。ファイルのインクルード定義が再フォーマットされ、可読性が向上。

Sequence Diagram(s)

sequenceDiagram
    participant Client as クライアント
    participant TTS as TTS関数(functions/src/index.ts)
    participant Normalizer as normalizeRomanText関数
    participant Logger as コンソールログ

    Client->>TTS: テキストリクエスト送信
    TTS->>Normalizer: normalizeRomanText(req.data.ssmlEn) 呼出
    Normalizer-->>TTS: 正規化済みテキスト返却
    TTS->>Logger: 加工後の ssmlEn をログ出力
    TTS-->>Client: 音声合成結果返却
Loading

Possibly related PRs

  • プレミアム音声廃止 #4046: normalizeRomanText 関数の実装およびテストに関する変更が含まれており、同関数の取り扱いにおいて密接な技術的関連があります。

Poem

ふわふわうさぎが
コードの森を駆け抜ける
テストと設定が光り
文字が踊り出す
小さな変更が大きな夢に
みんなで笑顔、進もう!
🐰✨


📜 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 1a4ef06 and 3c9a960.

📒 Files selected for processing (1)
  • functions/src/index.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • functions/src/index.ts

🪧 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. (Beta)
  • @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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 comments (1)
functions/src/index.ts (1)

Line range hint 146-195: 音声合成処理の保守性を改善できます。

以下の改善点を提案します:

  1. 音素置換ルールを設定ファイルに分離
  2. 文字列置換をMap等を使用してより保守しやすい形に変更
  3. console.logの代わりに適切なロギングを使用

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

// phoneme-rules.ts
export const PHONEME_RULES = new Map([
  ['-itchome', '<phoneme alphabet="ipa" ph="itt͡ɕoːme">いっちょうめ</phoneme>'],
  ['-sanchome', '<phoneme alphabet="ipa" ph="sant͡ɕoːme">さんちょうめ</phoneme>'],
  ['Ube', '<phoneme alphabet="ipa" ph="ɯbe">うべ</phoneme>'],
  // ... 他のルール
]);

// index.ts
import { PHONEME_RULES } from './phoneme-rules';

const ssmlEn = normalizeRomanText(req.data.ssmlEn);
let normalizedText = ssmlEn
  .replaceAll('・', ' ')
  .replaceAll('・', ' ')
  .replaceAll(/[!-/:-@[-`{-~、-〜"'・]+/g, ' ')
  .replaceAll('`', '');

for (const [pattern, replacement] of PHONEME_RULES) {
  normalizedText = normalizedText.replaceAll(pattern, replacement);
}

// ロギングの改善
const logger = functions.logger;
logger.info('Text normalization', { original: req.data.ssmlEn, normalized: normalizedText });
🧹 Nitpick comments (5)
functions/src/utils/normalize.ts (1)

1-15: パフォーマンスと保守性の改善を提案します。

以下の改善点を提案します:

  1. 大文字小文字の変換をより効率的に行うことができます。
  2. 'Jr' から 'J-R' への変換ロジックにコメントを追加することで、意図が明確になります。

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

 export const normalizeRomanText = (str: string | undefined): string => {
   if (!str) return '';
 
+  // 単語の先頭を大文字に、残りを小文字に変換
   const replaced = str
     .split(' ')
-    .map((seg) =>
-      /[A-Z]/.test(seg)
-        ? seg.charAt(0).toUpperCase() + seg.slice(1).toLowerCase()
-        : seg
-    )
+    .map((seg) => seg.charAt(0).toUpperCase() + seg.slice(1).toLowerCase())
     .join(' ');
 
+  // JR(Japan Railways)の表記を標準化
   return replaced.replace('Jr', 'J-R');
 };
functions/src/utils/normalize.test.ts (1)

3-16: テストケースの追加を推奨します。

以下のエッジケースのテストを追加することを推奨します:

 describe('utils/normalize.ts', () => {
+  it('Should handle edge cases', () => {
+    expect(normalizeRomanText(undefined)).toBe('');
+    expect(normalizeRomanText('')).toBe('');
+  });
+
   it('Should be normalized', () => {
     expect(normalizeRomanText('TOKYO')).toBe('Tokyo');
     // ... existing tests ...
   });
functions/src/index.ts (1)

197-197: console.logの使用を避けてください。

開発用のconsole.logが本番コードに残っています。Firebase Functionsのロガーを使用することを推奨します。

-console.log(req.data.ssmlEn, '->', ssmlEn);
+functions.logger.info('Text normalization', { original: req.data.ssmlEn, normalized: ssmlEn });
src/hooks/useTTSText.ts (2)

782-802: 英語アナウンステンプレートの改善提案

現在のテンプレート構造は複雑で、メンテナンスが困難になる可能性があります。以下の改善を提案します:

  1. テンプレート文字列をより小さな関数に分割
  2. 共通のフレーズを定数として抽出
+ const COMMON_PHRASES = {
+   THANK_YOU: 'Thank you for using',
+   BOUND_FOR: 'bound for',
+   TERMINAL: 'terminal',
+ } as const;

- ? `Thank you for using ${currentLine?.company?.nameEnglishShort}. This is the ${currentTrainType?.nameRoman ?? 'Local'} Service bound for ${boundForEn}`
+ ? `${COMMON_PHRASES.THANK_YOU} ${currentLine?.company?.nameEnglishShort}. This is the ${currentTrainType?.nameRoman ?? 'Local'} Service ${COMMON_PHRASES.BOUND_FOR} ${boundForEn}`

847-847: テンプレートリテラルの最適化

長いテンプレートリテラルは可読性とメンテナンス性に影響を与える可能性があります。

テンプレート文字列を複数の小さな関数に分割することを推奨します:

const getTrainTypeAnnouncement = (type: string) => 
  `This is the ${type ?? 'Local'} train`;

const getDestinationAnnouncement = (destination: string) =>
  `bound for ${destination}`;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4891946 and 525da84.

⛔ Files ignored due to path filters (1)
  • functions/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (10)
  • __tests__/utils/normalize.test.ts (0 hunks)
  • functions/biome.json (1 hunks)
  • functions/jest.config.js (1 hunks)
  • functions/package.json (3 hunks)
  • functions/src/index.ts (3 hunks)
  • functions/src/utils/normalize.test.ts (1 hunks)
  • functions/src/utils/normalize.ts (1 hunks)
  • functions/tsconfig.json (1 hunks)
  • src/hooks/useTTSText.ts (12 hunks)
  • src/utils/normalize.ts (0 hunks)
💤 Files with no reviewable changes (2)
  • tests/utils/normalize.test.ts
  • src/utils/normalize.ts
✅ Files skipped from review due to trivial changes (1)
  • functions/tsconfig.json
🔇 Additional comments (5)
functions/jest.config.js (1)

1-7: 設定は適切です!

TypeScriptプロジェクト用の標準的なJest設定が実装されています。

src/hooks/useTTSText.ts (1)

72-72: nameRomanプロパティの直接アクセスへの変更を確認

normalizeRomanText関数の削除に伴い、nameRomanプロパティへの直接アクセスに変更されています。この変更は適切ですが、以下の点に注意が必要です。

  • nameRomanプロパティがundefinedの場合の処理
  • 特殊文字を含む駅名の正規化

Also applies to: 81-81, 90-90, 99-101, 173-173, 182-182, 200-200, 203-203

✅ Verification successful

以下のスクリプトを実行して、src/hooks/useTTSText.ts 内での nameRoman プロパティへの直接アクセスが意図どおりに変更されているか、該当箇所(例:l.nameRoman の使用部分)を確認してください。

この結果をもとに、値が undefined になった場合の処理や、特殊文字を含む場合の対応が必要かどうかも合わせて検証してください。


nameRomanプロパティの直接アクセス変更を確認しました

  • src/hooks/useTTSText.ts 内で、かつて使用されていた正規化関数を呼び出す処理がなくなり、全ての箇所で l.nameRoman への直接アクセスに置き換えられているのが確認できました。(例: 行 72、173、203 など)
  • テンプレート文字列内でも同様の直接アクセスが行われており、仕様通りの変更になっています。
  • なお、現状では nameRoman が undefined の可能性や、特殊文字を含むケースに対する明示的な対処は実装されていないため、必要に応じてその対応を検討することが望ましいです。
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# nameRomanプロパティの使用箇所を確認
rg "nameRoman" -A 2 -B 2

Length of output: 116945


Script:

#!/bin/bash
# src/hooks/useTTSText.ts 内で "l.nameRoman" の使用箇所とその前後の数行を抽出
rg "l\.nameRoman" -n --context 3 src/hooks/useTTSText.ts

Length of output: 4372

functions/biome.json (1)

2-5: Biomeの設定が適切に更新されています

スキーマバージョンの更新と、ignoreパターンの簡素化が行われています。テスト関連ファイルの除外が適切に設定されています。

functions/package.json (2)

28-31: テスト環境の設定を確認

Jestとts-jestの追加は適切ですが、以下の点を確認してください:

  • テストカバレッジの設定
  • TypeScriptの設定との整合性

テストカバレッジの設定やサンプルテストケースの作成をお手伝いしましょうか?


16-16: Node.jsバージョンの更新を確認

Node.js 20への更新は適切ですが、以下の確認が必要です:

  • 依存パッケージの互換性
  • デプロイ環境のNode.jsバージョン
✅ Verification successful

依存パッケージとの互換性確認済み

  • firebase-functions は Node.js >=14.10.0 が必要なため、Node.js 20 で問題なし
  • firebase-admin は Node.js >=18 が必要なため、Node.js 20 で問題なし

デプロイ環境でも Node.js 20 が利用可能であることを合わせて確認してください。

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 依存パッケージのNode.js互換性を確認
npm info firebase-functions engines
npm info firebase-admin engines

Length of output: 110

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant