generated from jphacks/JP_sample
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseConversation.ts
More file actions
278 lines (244 loc) · 6.8 KB
/
useConversation.ts
File metadata and controls
278 lines (244 loc) · 6.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import { useCallback, useEffect, useRef, useState } from "react";
import {
conversationApi,
sessionApi,
speechToText,
textToSpeechUrl,
} from "@/lib/api";
import type { VoiceAnalysisResult } from "@/lib/audio/voiceAnalysis";
import type { ConversationSession, Message } from "@/types/api";
import { useLipSync } from "./useLipSync";
interface UseConversationOptions {
systemPrompt?: string;
onAudioReady?: (audioUrl: string) => void;
onLipSyncUpdate?: (value: number) => void;
ttsVoiceId?: string;
onEmotionUpdate?: (
emotion: "neutral" | "happy" | "sad" | "surprised" | "angry" | "bashful",
) => void;
avatarId?: string; // persona id
}
interface ConversationState {
session: ConversationSession | null;
messages: Message[];
isProcessing: boolean;
error: Error | null;
currentAudioUrl: string | null;
}
export function useConversation(options: UseConversationOptions) {
const {
systemPrompt,
onAudioReady,
onLipSyncUpdate,
ttsVoiceId,
onEmotionUpdate,
avatarId,
} = options;
const [state, setState] = useState<ConversationState>({
session: null,
messages: [],
isProcessing: false,
error: null,
currentAudioUrl: null,
});
const audioRef = useRef<HTMLAudioElement | null>(null);
// リップシンクを統合
const lipSyncValue = useLipSync(audioRef.current);
// セッションを開始
const startSession = useCallback(async () => {
try {
setState((prev) => ({ ...prev, isProcessing: true, error: null }));
// localStorageから既存のuserIdを取得
let existingUserId: string | null = null;
if (typeof window !== "undefined") {
existingUserId = localStorage.getItem("conversationUserId");
console.log("Existing user ID from localStorage:", existingUserId);
}
// 既存のuserIdがあればそれを使用、なければバックエンドで新規作成
const session = await sessionApi.createSession(
existingUserId || undefined,
);
// userIdをlocalStorageに保存して永続化
if (session.userId && typeof window !== "undefined") {
localStorage.setItem("conversationUserId", session.userId);
console.log("User ID saved to localStorage:", session.userId);
}
setState((prev) => ({
...prev,
session,
isProcessing: false,
}));
return session;
} catch (error) {
const err = error instanceof Error ? error : new Error("Unknown error");
setState((prev) => ({
...prev,
error: err,
isProcessing: false,
}));
throw err;
}
}, []);
// セッションを終了
const endSession = useCallback(async () => {
if (!state.session) return;
try {
setState((prev) => ({ ...prev, isProcessing: true }));
await sessionApi.finishSession(state.session.id);
setState((prev) => ({
...prev,
isProcessing: false,
}));
} catch (error) {
const err = error instanceof Error ? error : new Error("Unknown error");
setState((prev) => ({
...prev,
error: err,
isProcessing: false,
}));
}
}, [state.session]);
// リップシンク値を親コンポーネントに通知
useEffect(() => {
if (onLipSyncUpdate) {
onLipSyncUpdate(lipSyncValue);
}
}, [lipSyncValue, onLipSyncUpdate]);
// 音声を送信して応答を取得(STT → AI → TTS)
const sendAudio = useCallback(
async (
audioBlob: Blob,
_voiceAnalysis?: VoiceAnalysisResult | null,
): Promise<Message | null> => {
if (!state.session) {
throw new Error("No active session");
}
try {
setState((prev) => ({ ...prev, isProcessing: true, error: null }));
// 1. STT: 音声をテキストに変換
const audioFile = new File([audioBlob], "recording.webm", {
type: audioBlob.type,
});
const sttResult = await speechToText({
audio: audioFile,
});
console.log("STT Result:", sttResult.text);
// Unsupported language プレースホルダーを検出したらAI呼び出しをスキップ
if (sttResult.text === "[UNSUPPORTED_LANGUAGE]") {
const unsupportedErr = new Error(
"日本語または英語で話してください (Detected unsupported language).",
);
setState((prev) => ({
...prev,
error: unsupportedErr,
isProcessing: false,
}));
return null;
}
// 2. AI: テキストから応答を生成
const relationshipStage =
state.messages.length < 7
? "shy"
: state.messages.length < 15
? "friendly"
: "open";
const aiResponse = await conversationApi.generateResponse({
sessionId: state.session.id,
userMessage: sttResult.text,
systemPrompt,
avatarId,
relationshipStage,
});
console.log(
"AI Response:",
aiResponse.response,
"Emotion:",
aiResponse.emotion,
);
// Emotion update to UI
if (onEmotionUpdate) {
onEmotionUpdate(aiResponse.emotion);
}
// メッセージを状態に追加
setState((prev) => ({
...prev,
messages: [
...prev.messages,
aiResponse.userMessage,
aiResponse.assistantMessage,
],
}));
// 3. TTS: AIの応答を音声に変換
console.log("Starting TTS for text:", aiResponse.response);
const audioUrl = await textToSpeechUrl({
text: aiResponse.response,
voiceId: ttsVoiceId,
});
console.log("TTS Audio URL created:", audioUrl);
// 音声を再生
const audio = new Audio(audioUrl);
audioRef.current = audio;
// 音量を確認(デフォルトは1.0)
audio.volume = 1.0;
console.log("Audio volume set to:", audio.volume);
console.log("Audio element created, waiting for playback...");
try {
await audio.play();
console.log("Audio playback started successfully");
} catch (err) {
console.error("Audio playback failed (autoplay?)", err);
setState((prev) => ({
...prev,
error: new Error(
"Audio playback failed. Please interact with the page (e.g., click somewhere) and try again.",
),
}));
}
setState((prev) => ({
...prev,
currentAudioUrl: audioUrl,
isProcessing: false,
}));
onAudioReady?.(audioUrl);
return aiResponse.assistantMessage;
} catch (error) {
const err = error instanceof Error ? error : new Error("Unknown error");
console.error("Conversation error:", err);
setState((prev) => ({
...prev,
error: err,
isProcessing: false,
}));
return null;
}
},
[
state.session,
systemPrompt,
ttsVoiceId,
onAudioReady,
onEmotionUpdate,
avatarId,
state.messages.length,
],
);
// クリーンアップ
useEffect(() => {
return () => {
if (audioRef.current) {
audioRef.current.pause();
audioRef.current = null;
}
};
}, []);
return {
session: state.session,
messages: state.messages,
isProcessing: state.isProcessing,
error: state.error,
currentAudioUrl: state.currentAudioUrl,
startSession,
endSession,
sendAudio,
};
}