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
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
import React, { useState, useRef, useEffect } from 'react';
import { Mic, MicOff, Volume2, Globe, Loader2 } from 'lucide-react';

const RealtimeVoiceTranslator = () => {
  const [isConnected, setIsConnected] = useState(false);
  const [isRecording, setIsRecording] = useState(false);
  const [transcript, setTranscript] = useState('');
  const [translation, setTranslation] = useState('');
  const [sourceLanguage, setSourceLanguage] = useState('ko');
  const [targetLanguage, setTargetLanguage] = useState('en');
  const [ephemeralKey, setEphemeralKey] = useState('');
  const [logs, setLogs] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  const pcRef = useRef(null);
  const dcRef = useRef(null);
  const audioElRef = useRef(null);

  // ๋กœ๊ทธ ์ถ”๊ฐ€ ํ•จ์ˆ˜
  const addLog = (message, type = 'info') => {
    const timestamp = new Date().toLocaleTimeString();
    setLogs(prev => [...prev, { message, type, timestamp }]);
  };

  // Ephemeral key ๊ฐ€์ ธ์˜ค๊ธฐ (์‹œ๋ฎฌ๋ ˆ์ด์…˜)
  const getEphemeralKey = async () => {
    // ์‹ค์ œ ๊ตฌํ˜„์—์„œ๋Š” ์„œ๋ฒ„์—์„œ ephemeral key๋ฅผ ๊ฐ€์ ธ์™€์•ผ ํ•ฉ๋‹ˆ๋‹ค
    addLog('Ephemeral key๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ์„œ๋ฒ„ ์—”๋“œํฌ์ธํŠธ๋ฅผ ๊ตฌํ˜„ํ•ด์ฃผ์„ธ์š”.', 'warning');
    return 'YOUR_EPHEMERAL_KEY';
  };

  // WebRTC ์—ฐ๊ฒฐ ์ดˆ๊ธฐํ™”
  const initializeConnection = async () => {
    try {
      setIsLoading(true);
      addLog('์—ฐ๊ฒฐ ์ดˆ๊ธฐํ™” ์ค‘...', 'info');

      // Ephemeral key ๊ฐ€์ ธ์˜ค๊ธฐ
      const key = await getEphemeralKey();
      setEphemeralKey(key);

      // Peer connection ์ƒ์„ฑ
      const pc = new RTCPeerConnection({
        iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
      });
      pcRef.current = pc;

      // ์›๊ฒฉ ์˜ค๋””์˜ค ์ŠคํŠธ๋ฆผ ์„ค์ •
      const audioEl = audioElRef.current;
      pc.ontrack = (e) => {
        audioEl.srcObject = e.streams[0];
        addLog('์˜ค๋””์˜ค ์ŠคํŠธ๋ฆผ ์—ฐ๊ฒฐ๋จ', 'success');
      };

      // ๋กœ์ปฌ ์˜ค๋””์˜ค ํŠธ๋ž™ ์ถ”๊ฐ€
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      stream.getTracks().forEach(track => {
        pc.addTrack(track, stream);
      });

      // ๋ฐ์ดํ„ฐ ์ฑ„๋„ ์„ค์ •
      const dc = pc.createDataChannel('oai-events');
      dcRef.current = dc;

      dc.addEventListener('open', () => {
        addLog('๋ฐ์ดํ„ฐ ์ฑ„๋„ ์—ด๋ฆผ', 'success');
        setIsConnected(true);
        
        // ์„ธ์…˜ ์„ค์ •
        const sessionConfig = {
          type: 'session.update',
          session: {
            modalities: ['text', 'audio'],
            instructions: `You are a helpful translator. Translate between ${sourceLanguage === 'ko' ? 'Korean' : 'English'} and ${targetLanguage === 'ko' ? 'Korean' : 'English'}.`,
            voice: 'alloy',
            input_audio_format: 'pcm16',
            output_audio_format: 'pcm16',
            input_audio_transcription: {
              model: 'whisper-1'
            },
            turn_detection: {
              type: 'server_vad',
              threshold: 0.5,
              prefix_padding_ms: 300,
              silence_duration_ms: 500
            }
          }
        };
        dc.send(JSON.stringify(sessionConfig));
      });

      dc.addEventListener('message', (e) => {
        const event = JSON.parse(e.data);
        handleRealtimeEvent(event);
      });

      dc.addEventListener('error', (error) => {
        addLog(`๋ฐ์ดํ„ฐ ์ฑ„๋„ ์˜ค๋ฅ˜: ${error}`, 'error');
      });

      // SDP ์˜คํผ ์ƒ์„ฑ ๋ฐ ์—ฐ๊ฒฐ
      const offer = await pc.createOffer();
      await pc.setLocalDescription(offer);

      // API ์—ฐ๊ฒฐ (์‹ค์ œ ๊ตฌํ˜„ ์‹œ ์‚ฌ์šฉ)
      /*
      const baseUrl = 'https://api.openai.com/v1/realtime';
      const model = 'gpt-4o-realtime-preview-2025-06-03';
      const response = await fetch(`${baseUrl}?model=${model}`, {
        method: 'POST',
        body: offer.sdp,
        headers: {
          'Authorization': `Bearer ${key}`,
          'Content-Type': 'application/sdp'
        }
      });

      const answerSdp = await response.text();
      const answer = {
        type: 'answer',
        sdp: answerSdp
      };
      await pc.setRemoteDescription(answer);
      */

      addLog('WebRTC ์—ฐ๊ฒฐ ์‹œ๋ฎฌ๋ ˆ์ด์…˜ ์™„๋ฃŒ', 'warning');
      setIsConnected(true);
      setIsLoading(false);

    } catch (error) {
      addLog(`์—ฐ๊ฒฐ ์˜ค๋ฅ˜: ${error.message}`, 'error');
      setIsLoading(false);
    }
  };

  // Realtime ์ด๋ฒคํŠธ ์ฒ˜๋ฆฌ
  const handleRealtimeEvent = (event) => {
    switch (event.type) {
      case 'conversation.item.created':
        if (event.item.role === 'user') {
          setTranscript(event.item.content?.[0]?.transcript || '');
          addLog(`์‚ฌ์šฉ์ž: ${event.item.content?.[0]?.transcript}`, 'info');
        }
        break;
      
      case 'conversation.item.input_audio_transcription.completed':
        setTranscript(event.transcript);
        addLog(`์ „์‚ฌ ์™„๋ฃŒ: ${event.transcript}`, 'info');
        // ๋ฒˆ์—ญ ์š”์ฒญ
        requestTranslation(event.transcript);
        break;
      
      case 'response.audio_transcript.delta':
        setTranslation(prev => prev + event.delta);
        break;
      
      case 'response.audio_transcript.done':
        addLog(`๋ฒˆ์—ญ ์™„๋ฃŒ: ${translation}`, 'success');
        break;
      
      case 'error':
        addLog(`์˜ค๋ฅ˜: ${event.error.message}`, 'error');
        break;
      
      default:
        console.log('Unhandled event:', event);
    }
  };

  // ๋ฒˆ์—ญ ์š”์ฒญ
  const requestTranslation = (text) => {
    if (!dcRef.current || dcRef.current.readyState !== 'open') return;

    const message = {
      type: 'conversation.item.create',
      item: {
        type: 'message',
        role: 'user',
        content: [{
          type: 'input_text',
          text: `Translate this to ${targetLanguage === 'ko' ? 'Korean' : 'English'}: "${text}"`
        }]
      }
    };

    dcRef.current.send(JSON.stringify(message));
    
    // ์‘๋‹ต ์ƒ์„ฑ ์š”์ฒญ
    dcRef.current.send(JSON.stringify({ type: 'response.create' }));
  };

  // ๋…น์Œ ์‹œ์ž‘/์ค‘์ง€
  const toggleRecording = () => {
    if (!isConnected) {
      addLog('๋จผ์ € ์—ฐ๊ฒฐ์„ ์‹œ์ž‘ํ•ด์ฃผ์„ธ์š”', 'warning');
      return;
    }

    setIsRecording(!isRecording);
    
    if (!isRecording) {
      addLog('๋…น์Œ ์‹œ์ž‘', 'info');
      // ์Œ์„ฑ ์ž…๋ ฅ ์‹œ์ž‘์„ ์œ„ํ•œ ์ด๋ฒคํŠธ ์ „์†ก
      if (dcRef.current && dcRef.current.readyState === 'open') {
        dcRef.current.send(JSON.stringify({
          type: 'input_audio_buffer.commit'
        }));
      }
    } else {
      addLog('๋…น์Œ ์ค‘์ง€', 'info');
    }
  };

  // ์–ธ์–ด ์ „ํ™˜
  const swapLanguages = () => {
    setSourceLanguage(targetLanguage);
    setTargetLanguage(sourceLanguage);
    addLog(`์–ธ์–ด ์ „ํ™˜: ${targetLanguage} โ†’ ${sourceLanguage}`, 'info');
  };

  // ์—ฐ๊ฒฐ ์ข…๋ฃŒ
  const disconnect = () => {
    if (pcRef.current) {
      pcRef.current.close();
      pcRef.current = null;
    }
    setIsConnected(false);
    setIsRecording(false);
    addLog('์—ฐ๊ฒฐ ์ข…๋ฃŒ๋จ', 'info');
  };

  // ์ปดํฌ๋„ŒํŠธ ์–ธ๋งˆ์šดํŠธ ์‹œ ์ •๋ฆฌ
  useEffect(() => {
    return () => {
      if (pcRef.current) {
        pcRef.current.close();
      }
    };
  }, []);

  return (
    <div className="min-h-screen bg-gray-50 p-4">
      <div className="max-w-4xl mx-auto">
        <h1 className="text-3xl font-bold text-center mb-8 text-gray-800">
          ์‹ค์‹œ๊ฐ„ ์Œ์„ฑ ๋ฒˆ์—ญ๊ธฐ
        </h1>

        {/* ์—ฐ๊ฒฐ ์ƒํƒœ */}
        <div className="bg-white rounded-lg shadow-md p-6 mb-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-xl font-semibold">์—ฐ๊ฒฐ ์ƒํƒœ</h2>
            <div className="flex items-center gap-2">
              <div className={`w-3 h-3 rounded-full ${isConnected ? 'bg-green-500' : 'bg-red-500'}`} />
              <span className="text-sm">{isConnected ? '์—ฐ๊ฒฐ๋จ' : '์—ฐ๊ฒฐ ์•ˆ๋จ'}</span>
            </div>
          </div>
          
          <div className="flex gap-4">
            {!isConnected ? (
              <button
                onClick={initializeConnection}
                disabled={isLoading}
                className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:bg-gray-400"
              >
                {isLoading ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    ์—ฐ๊ฒฐ ์ค‘...
                  </>
                ) : (
                  '์—ฐ๊ฒฐ ์‹œ์ž‘'
                )}
              </button>
            ) : (
              <button
                onClick={disconnect}
                className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600"
              >
                ์—ฐ๊ฒฐ ์ข…๋ฃŒ
              </button>
            )}
          </div>
        </div>

        {/* ์–ธ์–ด ์„ ํƒ */}
        <div className="bg-white rounded-lg shadow-md p-6 mb-6">
          <div className="flex items-center justify-between gap-4">
            <div className="flex-1">
              <label className="block text-sm font-medium mb-2">์ž…๋ ฅ ์–ธ์–ด</label>
              <select
                value={sourceLanguage}
                onChange={(e) => setSourceLanguage(e.target.value)}
                className="w-full p-2 border rounded-lg"
              >
                <option value="ko">ํ•œ๊ตญ์–ด</option>
                <option value="en">์˜์–ด</option>
              </select>
            </div>
            
            <button
              onClick={swapLanguages}
              className="mt-6 p-2 hover:bg-gray-100 rounded-lg"
            >
              <Globe className="w-6 h-6" />
            </button>
            
            <div className="flex-1">
              <label className="block text-sm font-medium mb-2">์ถœ๋ ฅ ์–ธ์–ด</label>
              <select
                value={targetLanguage}
                onChange={(e) => setTargetLanguage(e.target.value)}
                className="w-full p-2 border rounded-lg"
              >
                <option value="en">์˜์–ด</option>
                <option value="ko">ํ•œ๊ตญ์–ด</option>
              </select>
            </div>
          </div>
        </div>

        {/* ๋…น์Œ ์ปจํŠธ๋กค */}
        <div className="bg-white rounded-lg shadow-md p-6 mb-6">
          <div className="flex flex-col items-center">
            <button
              onClick={toggleRecording}
              disabled={!isConnected}
              className={`p-6 rounded-full transition-colors ${
                isRecording 
                  ? 'bg-red-500 hover:bg-red-600' 
                  : 'bg-blue-500 hover:bg-blue-600 disabled:bg-gray-400'
              } text-white`}
            >
              {isRecording ? (
                <MicOff className="w-8 h-8" />
              ) : (
                <Mic className="w-8 h-8" />
              )}
            </button>
            <p className="mt-4 text-sm text-gray-600">
              {isRecording ? '๋…น์Œ ์ค‘... ํด๋ฆญํ•˜์—ฌ ์ค‘์ง€' : 'ํด๋ฆญํ•˜์—ฌ ๋…น์Œ ์‹œ์ž‘'}
            </p>
          </div>
        </div>

        {/* ๊ฒฐ๊ณผ ํ‘œ์‹œ */}
        <div className="bg-white rounded-lg shadow-md p-6 mb-6">
          <h3 className="text-lg font-semibold mb-4">๋ฒˆ์—ญ ๊ฒฐ๊ณผ</h3>
          
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium mb-2">์›๋ณธ ํ…์ŠคํŠธ</label>
              <div className="p-4 bg-gray-50 rounded-lg min-h-[80px]">
                {transcript || <span className="text-gray-400">์Œ์„ฑ ์ž…๋ ฅ์„ ๊ธฐ๋‹ค๋ฆฌ๋Š” ์ค‘...</span>}
              </div>
            </div>
            
            <div>
              <label className="block text-sm font-medium mb-2">๋ฒˆ์—ญ๋œ ํ…์ŠคํŠธ</label>
              <div className="p-4 bg-blue-50 rounded-lg min-h-[80px]">
                {translation || <span className="text-gray-400">๋ฒˆ์—ญ ๊ฒฐ๊ณผ๊ฐ€ ์—ฌ๊ธฐ์— ํ‘œ์‹œ๋ฉ๋‹ˆ๋‹ค...</span>}
              </div>
            </div>
          </div>
        </div>

        {/* ๋กœ๊ทธ */}
        <div className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-lg font-semibold mb-4">ํ™œ๋™ ๋กœ๊ทธ</h3>
          <div className="h-48 overflow-y-auto bg-gray-50 rounded-lg p-4 text-sm">
            {logs.length === 0 ? (
              <p className="text-gray-400">๋กœ๊ทธ๊ฐ€ ์—ฌ๊ธฐ์— ํ‘œ์‹œ๋ฉ๋‹ˆ๋‹ค...</p>
            ) : (
              logs.map((log, index) => (
                <div
                  key={index}
                  className={`mb-2 ${
                    log.type === 'error' ? 'text-red-600' :
                    log.type === 'success' ? 'text-green-600' :
                    log.type === 'warning' ? 'text-yellow-600' :
                    'text-gray-700'
                  }`}
                >
                  <span className="text-gray-500">[{log.timestamp}]</span> {log.message}
                </div>
              ))
            )}
          </div>
        </div>

        {/* ์˜ค๋””์˜ค ์—˜๋ฆฌ๋จผํŠธ (์ˆจ๊น€) */}
        <audio ref={audioElRef} autoPlay style={{ display: 'none' }} />

        {/* ์‚ฌ์šฉ ์•ˆ๋‚ด */}
        <div className="mt-6 p-4 bg-yellow-50 rounded-lg">
          <h4 className="font-semibold text-yellow-800 mb-2">โš ๏ธ ์ค‘์š” ์•ˆ๋‚ด</h4>
          <ul className="text-sm text-yellow-700 space-y-1">
            <li>โ€ข ์ด ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์„ ์‚ฌ์šฉํ•˜๋ ค๋ฉด ์„œ๋ฒ„์—์„œ ephemeral key๋ฅผ ์ƒ์„ฑํ•˜๋Š” ์—”๋“œํฌ์ธํŠธ๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.</li>
            <li>โ€ข OpenAI API ํ‚ค๊ฐ€ ํ•„์š”ํ•˜๋ฉฐ, ํด๋ผ์ด์–ธํŠธ ์ธก์—์„œ ์ง์ ‘ ์‚ฌ์šฉํ•˜๋ฉด ์•ˆ ๋ฉ๋‹ˆ๋‹ค.</li>
            <li>โ€ข ์‹ค์ œ ๊ตฌํ˜„ ์‹œ ์ฃผ์„ ์ฒ˜๋ฆฌ๋œ API ์—ฐ๊ฒฐ ์ฝ”๋“œ๋ฅผ ํ™œ์„ฑํ™”ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.</li>
            <li>โ€ข ๋งˆ์ดํฌ ๊ถŒํ•œ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.</li>
          </ul>
        </div>
      </div>
    </div>
  );
};

export default RealtimeVoiceTranslator;