Skip to content

TTS処理の純粋関数化 - #5134

Merged
TinyKitten merged 6 commits into
devfrom
fix/android-bg-tts
Jan 24, 2026
Merged

TinyKitten merged 6 commits into
devfrom
fix/android-bg-tts

Conversation

@TinyKitten

@TinyKitten TinyKitten commented Jan 24, 2026 •

Copy link
Copy Markdown
Member

#5133

Summary by CodeRabbit

  • 新機能

    • Androidで位置更新時に自動で背景TTSを起動するトリガーとリセット機能を追加しました。
    • 単一のTTSプレイヤーとバイリンガル案内文生成ユーティリティを導入しました。
  • 改善

    • 再生安定性、認証対応、背景再生挙動、案内文ロジックを大幅に簡素化・改善しました。
    • 位置更新に連動したTTS呼び出しを実装しました。
  • 削除

    • ローカルTTSキャッシュ機能とその公開エクスポート、および関連テストを削除しました。
  • テスト

    • 案内文生成の単体テストを追加/更新しました。

✏️ Tip: You can customize this high-level summary in your review settings.

@TinyKitten TinyKitten self-assigned this Jan 24, 2026
@github-actions github-actions Bot added the react label Jan 24, 2026
@coderabbitai

coderabbitai Bot commented Jan 24, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Android の位置更新後にバックグラウンドTTSを起動する呼び出しを追加し、Expo依存の音声処理を廃止して TTSPlayer シングルトンおよび新しい TTS テキスト生成 / ヘルパー群へ置き換える大規模リファクタを導入。

Changes

コホート / ファイル(s) 変更の説明
エントリ / 位置更新トリガー
index.js, src/utils/tts/backgroundTTSTrigger.ts
index.js に Android 向け triggerBackgroundTTS() の import と位置更新後呼び出しを追加。backgroundTTSTrigger は状態収集・検証・TTSテキスト生成・TTSPlayer 呼び出し(プラットフォーム/設定ガード含む)を実行する新モジュールを追加。
TTS プレイヤー(新規)
src/utils/tts/TTSPlayer.ts
シングルトン TTSPlayer を新規追加。ID トークン取得設定、音声生成 API 呼び出し(base64→ファイル)、内部キャッシュ(最大10件)、再生シーケンス、stop/reset 等の公開 API を実装。
TTS テキスト生成 & ヘルパー群(新規)
src/utils/tts/generateTTSText.ts, src/utils/tts/helpers.ts
駅/路線/テーマ別のバイリンガル TTS 生成ロジック(TTSTextData, generateTTSText)と多数の純関数ユーティリティ(次駅算出、ループ判定、乗換/接続線、スライス等)を追加。
フックのリファクタ
src/hooks/useTTS.ts, src/hooks/useTTSText.ts, src/hooks/index.ts
useTTS を TTSPlayer 中心に大幅リファクタ(Expo 直結処理・ファイル管理・キャッシュ呼び出し削除)。useTTSText を generateTTSText に委譲するよう書き換え。src/hooks/index.ts から useTTSCache の再エクスポートを削除。
キャッシュ関連の削除(旧実装)
src/hooks/useTTSCache.ts, src/hooks/useTTSCache.test.ts
既存の in-memory TTS キャッシュフックとそのテストを削除(キャッシュロジックは TTSPlayer 内へ移行)。
テスト追加/調整
src/utils/tts/generateTTSText.test.ts, src/hooks/useTTSText.test.ts
generateTTSText の単体テストを新規追加。useTTSText テストの一件(TOKYO_METRO/TY ARRIVING)の英語期待値を更新。
小変更
その他(package.json 等)
入口処理への TTS トリガー接続に伴う軽微な変更(import 追加等、差分小)。

Sequence Diagram(s)

sequenceDiagram
    participant App as アプリ
    participant LocationTask as 位置更新タスク
    participant BGTrigger as backgroundTTSTrigger
    participant State as アプリ状態(station/line/navigation/theme)
    participant TTSPlayer as TTSPlayer
    participant TTSAPI as TTS API
    participant ExpoAudio as ExpoAudio

    App->>LocationTask: setLocation(位置更新)
    LocationTask->>BGTrigger: triggerBackgroundTTS()
    BGTrigger->>State: 状態取得(station/line/navigation/theme)
    BGTrigger->>BGTrigger: データ検証・TTSテキスト生成 (generateTTSText)
    BGTrigger->>TTSPlayer: setAudioMode(backgroundEnabled: true)
    BGTrigger->>TTSPlayer: speak(textJa, textEn)

    alt キャッシュヒット
        TTSPlayer->>TTSPlayer: ローカルキャッシュから読み込み
    else キャッシュミス
        TTSPlayer->>TTSAPI: fetchSpeech(text, idToken)
        TTSAPI-->>TTSPlayer: base64 音声データ
        TTSPlayer->>TTSPlayer: ファイル保存・キャッシュ登録
    end

    TTSPlayer->>ExpoAudio: play(日本語音声)
    ExpoAudio-->>TTSPlayer: 再生完了
    TTSPlayer->>ExpoAudio: play(英語音声)
    ExpoAudio-->>TTSPlayer: 再生完了
    TTSPlayer-->>BGTrigger: 再生完了通知
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 分

Possibly related PRs

  • 位置情報精度修正 #4017: 位置更新バックグラウンド処理(index.js)を変更しており、triggerBackgroundTTS 呼び出し周りで重複・競合する可能性が高い。
  • 脱expo-av #5027: useTTS.ts とアプリ入口(index.js)周りで同領域の実装変更があるため、TTS プレイバックパイプラインの差分が直接衝突する可能性あり。
  • expo-audioに戻し&バグ修正 #5038: useTTS の再設計(expo-av 置換やプレイヤー切替)を含み、TTSPlayer ベース化との実装差分が強く関連する。

Poem

🐰 背景でそっと、声が芽生える
新しい箱(TTSPlayer)で駅名が踊る
位置を受けて二言語で囁くよ
小さな音は記憶にしまわれて
次の停車へ、ふわり知らせる

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed プルリクエストのタイトル「TTS処理の純粋関数化」は、変更セットの主要な内容を正確に反映しています。TTSロジックを純粋関数に重構成し、複数の新しいユーティリティ関数を追加し、既存のキャッシング機構を削除する大規模なリファクタリングが実施されており、タイトルはこの主要な目的を明確に示しています。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Comment @coderabbitai help to get the list of available commands and usage tips.

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

🤖 Fix all issues with AI agents
In `@src/utils/tts/TTSPlayer.ts`:
- Around line 251-272: The code in TTSPlayer is accessing ttsJson.result and
ttsJson.result.id without validating the API response; update the fetch/parse
block to verify ttsJson and ttsJson.result exist and contain an id (and
optionally status/error fields) before creating File instances or writing audio;
if validation fails, throw or return a clear error (including the raw ttsJson)
so callers can handle it, and only call base64ToUint8Array and
fileJa.write/fileEn.write when the corresponding jaAudioContent/enAudioContent
are present; reference symbols: TTSPlayer, ttsJson, ttsJson.result.id, fileJa,
fileEn, Paths.cache, base64ToUint8Array.
🧹 Nitpick comments (5)
src/utils/tts/TTSPlayer.ts (2)

128-139: 空のcatchブロックにコメント追加を検討

クリーンアップ時のエラーは無視して問題ありませんが、意図を明確にするコメントがあると保守性が向上します。

💡 提案
   private cleanup(): void {
     try {
       this.soundJa?.pause();
       this.soundJa?.remove();
-    } catch {}
+    } catch {
+      // クリーンアップ時のエラーは無視
+    }
     try {
       this.soundEn?.pause();
       this.soundEn?.remove();
-    } catch {}
+    } catch {
+      // クリーンアップ時のエラーは無視
+    }
     this.soundJa = null;
     this.soundEn = null;
   }

141-226: 再生完了のタイムアウト処理を検討

オーディオ再生が何らかの理由でイベントを発火しない場合、Promiseが解決されない可能性があります。タイムアウト処理の追加を検討してください。

💡 タイムアウト処理の例
private async speakFromPath(pathJa: string, pathEn: string): Promise<void> {
  // 既存のロジック...
  
  return new Promise((resolve) => {
    const TIMEOUT_MS = 60000; // 60秒
    const timeoutId = setTimeout(() => {
      console.warn('[TTSPlayer] Playback timeout');
      this.cleanup();
      this.isPlaying = false;
      resolve();
    }, TIMEOUT_MS);
    
    // イベントリスナー内でclearTimeout(timeoutId)を呼び出す
    // ...
  });
}
index.js (1)

41-43: 非同期処理のエラーハンドリングを確認

triggerBackgroundTTS()は非同期関数ですが、awaitされていないため、エラーが発生した場合にキャッチされません。catchを追加するか、内部でエラーハンドリングが完結していることを確認してください。

💡 修正案
       setLocation(latestLocation);
       // Androidバックグラウンド時にTTSをトリガー
-      triggerBackgroundTTS();
+      triggerBackgroundTTS().catch((err) => {
+        console.error('[Location Task] triggerBackgroundTTS error:', err);
+      });

内部で既にtry-catchがあるため、このパターンは冗長かもしれませんが、将来的な変更に対する防御になります。

src/utils/tts/generateTTSText.ts (1)

206-366: 長いテンプレート文字列の可読性

テーマ別のテンプレートは適切に構成されていますが、一部の文字列連結が非常に長くなっています。必要に応じて変数に分割することで可読性が向上する可能性があります。

src/utils/tts/helpers.ts (1)

133-146: 重複したロジック

isOedoLineとisPartiallyLoopLineは同じ条件を持っています。isOedoLineを再利用できます。

💡 修正案
   const isOedoLine = line
     ? line.id === TOEI_OEDO_LINE_ID
     : stations.every((s) => s.line?.id === TOEI_OEDO_LINE_ID);
 
   const isLoopLine = (() => {
     if (trainType && !getIsLocal(trainType)) {
       return false;
     }
     return isYamanoteLine || isOsakaLoopLine || isMeijoLine;
   })();
 
-  const isPartiallyLoopLine = line
-    ? line.id === TOEI_OEDO_LINE_ID
-    : stations.every((s) => s.line?.id === TOEI_OEDO_LINE_ID);
+  const isPartiallyLoopLine = isOedoLine;

Comment thread src/utils/tts/TTSPlayer.ts Resolved

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

🤖 Fix all issues with AI agents
In `@src/utils/tts/generateTTSText.ts`:
- Around line 85-94: Guard against findIndex returning -1 before calling slice:
check nextStationIndex and afterNextStationIndex (from the
slicedStations.findIndex calls) and if either is -1 (or afterNextStationIndex <=
nextStationIndex) set betweenNextStation to an empty array instead of slicing;
otherwise perform slicedStations.slice(nextStationIndex + 1,
afterNextStationIndex). This ensures betweenNextStation cannot become an
unintended range when findIndex fails.
- Around line 420-425: In the APP_THEME.TY case inside generateTTSText.ts (the
ARRIVING branch), guard the space+period so that when nextStationNumberText is
empty you don't emit "Name .": only prepend a space before nextStationNumberText
and conditionally append the period/terminus text when nextStationNumberText is
non-empty (or compute the trailing punctuation separately based on
isNextStopTerminus and whether nextStationNumberText exists); update the
expression around nextStation?.nameRoman + nextStationNumberText +
isNextStopTerminus to handle the empty string case, and apply the same
conditional whitespace/punctuation fix to other themes/branches that concatenate
nextStationNumberText.

Comment thread src/utils/tts/generateTTSText.ts Resolved
Comment thread src/utils/tts/generateTTSText.ts Resolved

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

🤖 Fix all issues with AI agents
In `@src/utils/tts/generateTTSText.test.ts`:
- Around line 6-35: Add an afterEach hook to the generateTTSText test file that
calls jest.clearAllMocks() so mocks are reset between tests; place it in the
same scope as createBaseData within the describe('generateTTSText', ...) block
(i.e., add afterEach(() => jest.clearAllMocks());) to ensure all mocks/spies are
cleared after each test.

In `@src/utils/tts/generateTTSText.ts`:
- Around line 130-132: The current single-station branch in generateTTSText
produces e.g. "02" (or "Station Number 02") without a trailing period which
breaks Tokyo Metro English phrasing; update getStationNumberText to always
return the station-number string with a trailing period (e.g., "02." or "Station
Number 02.") for the single-number case and have generateTTSText call
getStationNumberText (using nextStationNumber.stationNumber and honoring
APP_THEME.JR_WEST) instead of inline formatting so the period is consistently
present; adjust logic that uses split to rely on getStationNumberText’s output.

Comment thread src/utils/tts/generateTTSText.test.ts Resolved
Comment thread src/utils/tts/generateTTSText.ts Resolved
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.

1 participant