File size: 24,608 Bytes
e1fe24a
 
 
 
 
 
 
 
 
 
 
 
92dd616
 
 
6bdc489
8000eeb
 
e1fe24a
 
b3067c5
92dd616
6bdc489
92dd616
 
 
 
e1fe24a
 
 
 
 
 
 
 
 
 
 
 
 
92dd616
 
 
 
 
4e89e7e
92dd616
 
2b6f990
 
 
 
 
 
 
 
 
92dd616
2b6f990
 
 
 
 
 
 
 
 
 
 
 
4792427
92dd616
2b6f990
 
 
 
 
 
 
 
 
92dd616
 
 
 
 
 
 
 
 
 
4e89e7e
e1fe24a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e89e7e
e1fe24a
4e89e7e
2b6f990
e1fe24a
 
 
 
 
 
 
 
 
 
 
 
 
 
2b6f990
e1fe24a
2b6f990
e1fe24a
2b6f990
 
 
 
 
 
e1fe24a
 
 
 
2b6f990
e1fe24a
 
 
 
 
 
 
2b6f990
e1fe24a
 
 
2b6f990
 
 
 
 
e1fe24a
 
 
 
 
 
 
 
 
4e89e7e
 
 
 
 
 
 
 
 
 
 
8000eeb
 
 
 
f1697bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8000eeb
 
 
 
 
 
f1697bd
 
 
8000eeb
 
 
 
 
 
4e89e7e
f1697bd
4e89e7e
f1697bd
 
 
 
 
 
 
 
 
 
2b6f990
 
4e89e7e
 
f1697bd
 
 
4e89e7e
 
 
f1697bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e89e7e
 
 
 
 
 
 
92dd616
8000eeb
4e89e7e
 
8000eeb
 
 
 
 
 
 
2b6f990
 
8000eeb
 
2b6f990
8000eeb
2b6f990
 
8000eeb
 
92dd616
4e89e7e
8000eeb
 
 
 
 
 
f1697bd
2b6f990
 
 
8000eeb
 
 
 
 
 
2b6f990
8000eeb
 
 
 
2b6f990
8000eeb
 
 
 
2b6f990
 
 
4e89e7e
92dd616
 
4e89e7e
 
92dd616
8000eeb
 
4e89e7e
 
8000eeb
 
 
 
 
 
2b6f990
8000eeb
 
 
2b6f990
8000eeb
2b6f990
8000eeb
2b6f990
 
8000eeb
 
4e89e7e
 
 
8000eeb
 
 
 
 
 
 
2b6f990
 
 
8000eeb
 
 
 
 
2b6f990
8000eeb
 
 
2b6f990
8000eeb
2b6f990
8000eeb
 
 
2b6f990
 
 
4e89e7e
 
 
92dd616
 
e1fe24a
 
 
 
 
 
 
 
 
4792427
92dd616
e1fe24a
 
4e89e7e
e1fe24a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92dd616
 
 
4e89e7e
 
 
 
 
 
 
 
92dd616
 
 
4e89e7e
 
f1697bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e89e7e
 
 
 
 
 
f1697bd
2b6f990
4e89e7e
4792427
92dd616
 
4e89e7e
f1697bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e89e7e
 
 
 
 
 
f1697bd
 
4e89e7e
 
 
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
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
# SMARTok Demo - ์‹ค์‹œ๊ฐ„ ๋‹ค๊ตญ์–ด ๋ฒˆ์—ญ ์‹œ์Šคํ…œ
# 
# ํ•„์ˆ˜ ํŒจํ‚ค์ง€:
# pip install gradio openai python-dotenv pdfplumber numpy websockets
# 
# ์„ ํƒ ํŒจํ‚ค์ง€ (๋น„๋””์˜ค ์ฒ˜๋ฆฌ):
# - ffmpeg ์„ค์น˜: sudo apt-get install ffmpeg (Linux) / brew install ffmpeg (Mac)
# - ๋˜๋Š” pip install moviepy
#
# ํ™˜๊ฒฝ ๋ณ€์ˆ˜:
# .env ํŒŒ์ผ์— OPENAI_API_KEY ์„ค์ • ํ•„์š”

import os, asyncio, json, tempfile, websockets, pdfplumber
import gradio as gr
import openai
from dotenv import load_dotenv
import numpy as np
import wave
import subprocess
import mimetypes

# โ”€โ”€โ”€ 0. ์ดˆ๊ธฐํ™” โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
if not openai.api_key:
    raise RuntimeError("OPENAI_API_KEY ๊ฐ€ .env ์— ์—†์Šต๋‹ˆ๋‹ค!")

# ffmpeg ์„ค์น˜ ํ™•์ธ
def check_ffmpeg():
    try:
        subprocess.run(['ffmpeg', '-version'], capture_output=True, check=True)
        return True
    except:
        return False

HAS_FFMPEG = check_ffmpeg()
if not HAS_FFMPEG:
    print("โš ๏ธ ffmpeg๊ฐ€ ์„ค์น˜๋˜์–ด ์žˆ์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋น„๋””์˜ค ์ฒ˜๋ฆฌ๊ฐ€ ์ œํ•œ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.")
    print("์„ค์น˜ ๋ฐฉ๋ฒ•: sudo apt-get install ffmpeg (Linux) / brew install ffmpeg (Mac)")

LANG = ["Korean","English","Japanese","Chinese",
        "Thai","Russian","Vietnamese","Spanish","French"]
VOICE = {l: ("nova" if l in ["Korean","Japanese","Chinese"] else "alloy")
         for l in LANG}
FOUR = ["English","Chinese","Thai","Russian"]
WS_URL = "wss://api.openai.com/v1/realtime"  # ์˜ฌ๋ฐ”๋ฅธ ์—”๋“œํฌ์ธํŠธ๋กœ ์ˆ˜์ •

# โ”€โ”€โ”€ 1. ๊ณตํ†ต GPT ๋ฒˆ์—ญ / TTS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# ์ „์—ญ ํด๋ผ์ด์–ธํŠธ ๊ด€๋ฆฌ
client = None

def get_client():
    global client
    if client is None:
        client = openai.AsyncClient()
    return client

async def gpt_translate(text, src, tgt):
    try:
        client = get_client()
        rsp = await client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[{"role":"system",
                       "content":f"Translate {src} โ†’ {tgt}. Return only the text."},
                      {"role":"user","content":text}],
            temperature=0.3,max_tokens=2048)
        return rsp.choices[0].message.content.strip()
    except Exception as e:
        print(f"๋ฒˆ์—ญ ์˜ค๋ฅ˜: {e}")
        return ""

async def gpt_tts(text, lang):
    try:
        client = get_client()
        rsp = await client.audio.speech.create(
            model="tts-1", voice=VOICE[lang], input=text[:4096])
        tmp = tempfile.NamedTemporaryFile(delete=False,suffix=".mp3")
        tmp.write(rsp.content); tmp.close(); return tmp.name
    except Exception as e:
        print(f"TTS ์˜ค๋ฅ˜: {e}")
        return None

# โ”€โ”€โ”€ 2. PDF ๋ฒˆ์—ญ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def translate_pdf(file, src, tgt):
    if not file: return "โš ๏ธ PDF ์—…๋กœ๋“œ ํ•„์š”", ""
    with pdfplumber.open(file.name) as pdf:
        text = "\n".join(p.extract_text() or "" for p in pdf.pages[:5]).strip()
    if not text:
        return "โš ๏ธ ํ…์ŠคํŠธ ์ถ”์ถœ ์‹คํŒจ", ""
    return text, asyncio.run(gpt_translate(text, src, tgt))

# โ”€โ”€โ”€ 2-1. ์˜ค๋””์˜ค ๋ฒˆ์—ญ (ํƒญ1์šฉ) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def extract_audio_from_video(video_path):
    """MP4 ๋“ฑ ๋น„๋””์˜ค ํŒŒ์ผ์—์„œ ์˜ค๋””์˜ค ์ถ”์ถœ"""
    audio_output = None
    try:
        # ์ž„์‹œ ์˜ค๋””์˜ค ํŒŒ์ผ ์ƒ์„ฑ
        audio_output = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
        audio_output.close()
        
        # ๋ฐฉ๋ฒ• 1: ffmpeg ์‚ฌ์šฉ ์‹œ๋„
        if HAS_FFMPEG:
            cmd = [
                'ffmpeg',
                '-i', video_path,
                '-vn',  # ๋น„๋””์˜ค ์ŠคํŠธ๋ฆผ ์ œ๊ฑฐ
                '-acodec', 'pcm_s16le',  # WAV ํฌ๋งท
                '-ar', '16000',  # 16kHz ์ƒ˜ํ”Œ๋ง
                '-ac', '1',  # ๋ชจ๋…ธ
                '-y',  # ๋ฎ์–ด์“ฐ๊ธฐ
                audio_output.name
            ]
            
            result = subprocess.run(cmd, capture_output=True, text=True)
            
            if result.returncode == 0:
                return audio_output.name
            else:
                print(f"ffmpeg ์˜ค๋ฅ˜: {result.stderr}")
        
        # ๋ฐฉ๋ฒ• 2: moviepy ์‚ฌ์šฉ ์‹œ๋„
        try:
            from moviepy.editor import VideoFileClip
            print("moviepy๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์˜ค๋””์˜ค ์ถ”์ถœ ์ค‘...")
            video = VideoFileClip(video_path)
            video.audio.write_audiofile(
                audio_output.name, 
                fps=16000, 
                nbytes=2,
                codec='pcm_s16le',
                verbose=False, 
                logger=None
            )
            video.close()
            return audio_output.name
        except ImportError:
            raise Exception(
                "๋น„๋””์˜ค ์ฒ˜๋ฆฌ๋ฅผ ์œ„ํ•ด ffmpeg ๋˜๋Š” moviepy๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.\n"
                "์„ค์น˜: pip install moviepy ๋˜๋Š” ffmpeg ์„ค์น˜"
            )
        except Exception as e:
            raise Exception(f"moviepy ์˜ค๋ฅ˜: {str(e)}")
            
    except Exception as e:
        # ์˜ค๋ฅ˜ ์‹œ ์ž„์‹œ ํŒŒ์ผ ์ •๋ฆฌ
        if audio_output and os.path.exists(audio_output.name):
            os.unlink(audio_output.name)
        raise e

async def translate_audio_async(file, src, tgt):
    if not file: return "โš ๏ธ ์˜ค๋””์˜ค/๋น„๋””์˜ค ์—…๋กœ๋“œ ํ•„์š”", "", None
    
    try:
        # ํŒŒ์ผ ํƒ€์ž… ํ™•์ธ
        mime_type, _ = mimetypes.guess_type(file)
        audio_file_path = file
        temp_audio_path = None
        
        # ๋น„๋””์˜ค ํŒŒ์ผ์ธ ๊ฒฝ์šฐ ์˜ค๋””์˜ค ์ถ”์ถœ
        if mime_type and mime_type.startswith('video/'):
            print(f"๋น„๋””์˜ค ํŒŒ์ผ ๊ฐ์ง€: {mime_type}")
            print(f"ํŒŒ์ผ ํฌ๊ธฐ: {os.path.getsize(file) / 1024 / 1024:.1f} MB")
            print("๋น„๋””์˜ค์—์„œ ์˜ค๋””์˜ค ์ถ”์ถœ ์ค‘... (์‹œ๊ฐ„์ด ๊ฑธ๋ฆด ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค)")
            temp_audio_path = extract_audio_from_video(file)
            audio_file_path = temp_audio_path
            print("์˜ค๋””์˜ค ์ถ”์ถœ ์™„๋ฃŒ!")
        
        # STT: Whisper API ์‚ฌ์šฉ
        print("์Œ์„ฑ ์ธ์‹ ์ค‘...")
        client = get_client()
        with open(audio_file_path, 'rb') as audio_file:
            transcript = await client.audio.transcriptions.create(
                model="whisper-1",
                file=audio_file,
                language=src[:2].lower()  # ์–ธ์–ด ์ฝ”๋“œ ๊ฐ„์†Œํ™”
            )
        
        # ์ž„์‹œ ํŒŒ์ผ ์ •๋ฆฌ
        if temp_audio_path and os.path.exists(temp_audio_path):
            os.unlink(temp_audio_path)
        
        orig_text = transcript.text
        if not orig_text.strip():
            return "โš ๏ธ ์Œ์„ฑ์ด ๊ฐ์ง€๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค", "", None
        
        print(f"์ธ์‹๋œ ํ…์ŠคํŠธ: {orig_text[:50]}...")
        
        # ๋ฒˆ์—ญ
        print(f"{src} โ†’ {tgt} ๋ฒˆ์—ญ ์ค‘...")
        trans_text = await gpt_translate(orig_text, src, tgt)
        
        # TTS
        print("์Œ์„ฑ ํ•ฉ์„ฑ ์ค‘...")
        audio_path = await gpt_tts(trans_text, tgt)
        
        return orig_text, trans_text, audio_path
    except Exception as e:
        print(f"์˜ค๋””์˜ค ๋ฒˆ์—ญ ์˜ค๋ฅ˜: {e}")
        # ์ž„์‹œ ํŒŒ์ผ ์ •๋ฆฌ
        if 'temp_audio_path' in locals() and temp_audio_path and os.path.exists(temp_audio_path):
            os.unlink(temp_audio_path)
        
        error_msg = str(e)
        if "ffmpeg" in error_msg.lower():
            error_msg += "\n\n๐Ÿ’ก ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•:\n1. ffmpeg ์„ค์น˜: sudo apt-get install ffmpeg\n2. ๋˜๋Š” pip install moviepy"
        
        return "โš ๏ธ ๋ฒˆ์—ญ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ", error_msg, None

def translate_audio(file, src, tgt):
    return asyncio.run(translate_audio_async(file, src, tgt))

# โ”€โ”€โ”€ 3. ์‹ค์‹œ๊ฐ„ STT (Whisper API ์‚ฌ์šฉ) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
async def process_audio_chunk(audio_data, src_lang):
    """์˜ค๋””์˜ค ์ฒญํฌ๋ฅผ ์ฒ˜๋ฆฌํ•˜์—ฌ ํ…์ŠคํŠธ๋กœ ๋ณ€ํ™˜"""
    if audio_data is None:
        return ""
    
    try:
        # Gradio๋Š” (sample_rate, audio_array) ํŠœํ”Œ์„ ๋ฐ˜ํ™˜
        if isinstance(audio_data, tuple):
            sample_rate, audio_array = audio_data
            
            # ์˜ค๋””์˜ค๊ฐ€ ๋„ˆ๋ฌด ์งง์œผ๋ฉด ๋ฌด์‹œ (0.5์ดˆ ๋ฏธ๋งŒ)
            if len(audio_array) < sample_rate * 0.5:
                return ""
            
            # ์˜ค๋””์˜ค ์ •๊ทœํ™” ๋ฐ ๋…ธ์ด์ฆˆ ํ•„ํ„ฐ๋ง
            audio_array = audio_array.astype(np.float32)
            
            # ๋ฌด์Œ ๊ฐ์ง€ - RMS๊ฐ€ ๋„ˆ๋ฌด ๋‚ฎ์œผ๋ฉด ๋ฌด์‹œ
            rms = np.sqrt(np.mean(audio_array**2))
            if rms < 0.01:  # ๋ฌด์Œ ์ž„๊ณ„๊ฐ’
                return ""
            
            # ์ •๊ทœํ™”
            max_val = np.max(np.abs(audio_array))
            if max_val > 0:
                audio_array = audio_array / max_val * 0.95
            
            # numpy array๋ฅผ WAV ํŒŒ์ผ๋กœ ๋ณ€ํ™˜
            with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
                with wave.open(tmp.name, 'wb') as wav_file:
                    wav_file.setnchannels(1)  # mono
                    wav_file.setsampwidth(2)  # 16-bit
                    wav_file.setframerate(sample_rate)
                    
                    # float32๋ฅผ 16-bit PCM์œผ๋กœ ๋ณ€ํ™˜
                    audio_int16 = (audio_array * 32767).astype(np.int16)
                    wav_file.writeframes(audio_int16.tobytes())
                tmp_path = tmp.name
        else:
            # bytes ๋ฐ์ดํ„ฐ์ธ ๊ฒฝ์šฐ
            with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
                tmp.write(audio_data)
                tmp_path = tmp.name
        
        # Whisper API๋กœ ๋ณ€ํ™˜ - ์–ธ์–ด ํžŒํŠธ์™€ ํ”„๋กฌํ”„ํŠธ ์ถ”๊ฐ€
        with open(tmp_path, 'rb') as audio_file:
            # ์–ธ์–ด๋ณ„ ํ”„๋กฌํ”„ํŠธ ์„ค์ •์œผ๋กœ hallucination ๋ฐฉ์ง€
            language_prompts = {
                "Korean": "์ด๊ฒƒ์€ ํ•œ๊ตญ์–ด ๋Œ€ํ™”์ž…๋‹ˆ๋‹ค.",
                "English": "This is an English conversation.",
                "Japanese": "ใ“ใ‚Œใฏๆ—ฅๆœฌ่ชžใฎไผš่ฉฑใงใ™ใ€‚",
                "Chinese": "่ฟ™ๆ˜ฏไธญๆ–‡ๅฏน่ฏใ€‚",
            }
            
            prompt = language_prompts.get(src_lang, "")
            
            client = get_client()
            transcript = await client.audio.transcriptions.create(
                model="whisper-1",
                file=audio_file,
                language=src_lang[:2].lower(),
                prompt=prompt,
                temperature=0.0  # ๋” ๋ณด์ˆ˜์ ์ธ ์ถ”๋ก 
            )
        
        os.unlink(tmp_path)  # ์ž„์‹œ ํŒŒ์ผ ์‚ญ์ œ
        
        # ๊ฒฐ๊ณผ ํ›„์ฒ˜๋ฆฌ - ๋ฐ˜๋ณต๋˜๋Š” ํŒจํ„ด ์ œ๊ฑฐ
        text = transcript.text.strip()
        
        # ๊ฐ™์€ ๋ฌธ์žฅ์ด ๋ฐ˜๋ณต๋˜๋Š” ๊ฒฝ์šฐ ์ฒ˜๋ฆฌ
        sentences = text.split('.')
        if len(sentences) > 1:
            unique_sentences = []
            for sent in sentences:
                sent = sent.strip()
                if sent and (not unique_sentences or sent != unique_sentences[-1]):
                    unique_sentences.append(sent)
            text = '. '.join(unique_sentences)
            if text and not text.endswith('.'):
                text += '.'
        
        # ๋‰ด์Šค ๊ด€๋ จ hallucination ํŒจํ„ด ๊ฐ์ง€ ๋ฐ ์ œ๊ฑฐ
        hallucination_patterns = [
            "MBC ๋‰ด์Šค", "KBS ๋‰ด์Šค", "SBS ๋‰ด์Šค", "JTBC ๋‰ด์Šค", 
            "๋‰ด์Šค๋ฃธ", "๋‰ด์Šค๋ฐ์Šคํฌ", "์•ต์ปค", "๊ธฐ์ž์ž…๋‹ˆ๋‹ค"
        ]
        
        # ์งง์€ ํ…์ŠคํŠธ์—์„œ ๋‰ด์Šค ํŒจํ„ด์ด ๊ฐ์ง€๋˜๋ฉด ๋ฌด์‹œ
        if len(text) < 50 and any(pattern in text for pattern in hallucination_patterns):
            return ""
        
        return text
        
    except Exception as e:
        print(f"STT ์˜ค๋ฅ˜: {e}")
        return ""

# โ”€โ”€โ”€ 4. Gradio ์ŠคํŠธ๋ฆผ ํ•ธ๋“ค๋Ÿฌ (๋™๊ธฐ ๋ฒ„์ „) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def realtime_single_sync(audio, src, tgt, state):
    """๋™๊ธฐ ๋ฒ„์ „์˜ ์‹ค์‹œ๊ฐ„ ๋‹จ์ผ ์–ธ์–ด ๋ฒˆ์—ญ"""
    if state is None:
        state = {"orig": "", "trans": "", "audio_buffer": [], "sample_rate": None}
    
    if audio is None:
        # ์ŠคํŠธ๋ฆผ ์ข…๋ฃŒ ์‹œ ๋‚จ์€ ๋ฒ„ํผ ์ฒ˜๋ฆฌ
        if state["audio_buffer"] and state["sample_rate"]:
            try:
                # ๋ฒ„ํผ์˜ ์˜ค๋””์˜ค ํ•ฉ์น˜๊ธฐ
                combined_audio = np.concatenate(state["audio_buffer"])
                audio_data = (state["sample_rate"], combined_audio)
                
                # ๋น„๋™๊ธฐ ์ž‘์—… ์‹คํ–‰
                text = asyncio.run(process_audio_chunk(audio_data, src))
                if text:
                    state["orig"] = state["orig"] + " " + text if state["orig"] else text
                    trans = asyncio.run(gpt_translate(text, src, tgt))
                    state["trans"] = state["trans"] + " " + trans if state["trans"] else trans
            except Exception as e:
                print(f"์ฒ˜๋ฆฌ ์˜ค๋ฅ˜: {e}")
            state["audio_buffer"] = []
        
        return state["orig"], state["trans"], state
    
    # ์˜ค๋””์˜ค ๋ฐ์ดํ„ฐ ๋ฒ„ํผ๋ง
    if isinstance(audio, tuple):
        sample_rate, audio_array = audio
        state["sample_rate"] = sample_rate
        state["audio_buffer"].append(audio_array)
        
        # ๋ฒ„ํผ๊ฐ€ ์ถฉ๋ถ„ํžˆ ์Œ“์˜€์„ ๋•Œ๋งŒ ์ฒ˜๋ฆฌ (์•ฝ 2-3์ดˆ ๋ถ„๋Ÿ‰)
        if state["audio_buffer"]:  # ๋ฒ„ํผ๊ฐ€ ๋น„์–ด์žˆ์ง€ ์•Š์€์ง€ ํ™•์ธ
            buffer_duration = len(np.concatenate(state["audio_buffer"])) / sample_rate
            if buffer_duration >= 2.0:  # 2์ดˆ๋งˆ๋‹ค ์ฒ˜๋ฆฌ
            try:
                # ๋ฒ„ํผ์˜ ์˜ค๋””์˜ค ํ•ฉ์น˜๊ธฐ
                combined_audio = np.concatenate(state["audio_buffer"])
                audio_data = (sample_rate, combined_audio)
                
                # STT
                text = asyncio.run(process_audio_chunk(audio_data, src))
                if text:
                    state["orig"] = state["orig"] + " " + text if state["orig"] else text
                    
                    # ๋ฒˆ์—ญ
                    trans = asyncio.run(gpt_translate(text, src, tgt))
                    state["trans"] = state["trans"] + " " + trans if state["trans"] else trans
                
                # ๋ฒ„ํผ ์ดˆ๊ธฐํ™”
                state["audio_buffer"] = []
            except Exception as e:
                print(f"์ฒ˜๋ฆฌ ์˜ค๋ฅ˜: {e}")
                state["audio_buffer"] = []  # ์˜ค๋ฅ˜ ์‹œ์—๋„ ๋ฒ„ํผ ์ดˆ๊ธฐํ™”
    
    return state["orig"], state["trans"], state

def realtime_four_sync(audio, src, state):
    """๋™๊ธฐ ๋ฒ„์ „์˜ ์‹ค์‹œ๊ฐ„ 4์–ธ์–ด ๋ฒˆ์—ญ"""
    if state is None:
        state = {"orig": "", "English": "", "Chinese": "", "Thai": "", "Russian": "", 
                 "audio_buffer": [], "sample_rate": None}
    
    if audio is None:
        # ์ŠคํŠธ๋ฆผ ์ข…๋ฃŒ ์‹œ ๋‚จ์€ ๋ฒ„ํผ ์ฒ˜๋ฆฌ
        if state["audio_buffer"] and state["sample_rate"]:
            try:
                combined_audio = np.concatenate(state["audio_buffer"])
                audio_data = (state["sample_rate"], combined_audio)
                
                text = asyncio.run(process_audio_chunk(audio_data, src))
                if text:
                    state["orig"] = state["orig"] + " " + text if state["orig"] else text
                    
                    # ์ˆœ์ฐจ์ ์œผ๋กœ ๋ฒˆ์—ญ (๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ ์‹œ ๋ฌธ์ œ ๋ฐœ์ƒ ๊ฐ€๋Šฅ)
                    for lang in FOUR:
                        trans = asyncio.run(gpt_translate(text, src, lang))
                        state[lang] = state[lang] + " " + trans if state[lang] else trans
            except Exception as e:
                print(f"์ฒ˜๋ฆฌ ์˜ค๋ฅ˜: {e}")
            state["audio_buffer"] = []
        
        return (state["orig"], state["English"], state["Chinese"], 
                state["Thai"], state["Russian"], state)
    
    # ์˜ค๋””์˜ค ๋ฐ์ดํ„ฐ ๋ฒ„ํผ๋ง
    if isinstance(audio, tuple):
        sample_rate, audio_array = audio
        state["sample_rate"] = sample_rate
        state["audio_buffer"].append(audio_array)
        
        # ๋ฒ„ํผ๊ฐ€ ์ถฉ๋ถ„ํžˆ ์Œ“์˜€์„ ๋•Œ๋งŒ ์ฒ˜๋ฆฌ
        if state["audio_buffer"]:  # ๋ฒ„ํผ๊ฐ€ ๋น„์–ด์žˆ์ง€ ์•Š์€์ง€ ํ™•์ธ
            buffer_duration = len(np.concatenate(state["audio_buffer"])) / sample_rate
            if buffer_duration >= 2.0:  # 2์ดˆ๋งˆ๋‹ค ์ฒ˜๋ฆฌ
            try:
                combined_audio = np.concatenate(state["audio_buffer"])
                audio_data = (sample_rate, combined_audio)
                
                # STT
                text = asyncio.run(process_audio_chunk(audio_data, src))
                if text:
                    state["orig"] = state["orig"] + " " + text if state["orig"] else text
                    
                    # 4๊ฐœ ์–ธ์–ด๋กœ ์ˆœ์ฐจ ๋ฒˆ์—ญ
                    for lang in FOUR:
                        trans = asyncio.run(gpt_translate(text, src, lang))
                        state[lang] = state[lang] + " " + trans if state[lang] else trans
                
                state["audio_buffer"] = []
            except Exception as e:
                print(f"์ฒ˜๋ฆฌ ์˜ค๋ฅ˜: {e}")
                state["audio_buffer"] = []
    
    return (state["orig"], state["English"], state["Chinese"], 
            state["Thai"], state["Russian"], state)

# โ”€โ”€โ”€ 5. UI โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
with gr.Blocks(title="SMARTok Demo", theme=gr.themes.Soft()) as demo:
    gr.Markdown(
        """
        # ๐ŸŒ SMARTok ์‹ค์‹œ๊ฐ„ ๋ฒˆ์—ญ ์‹œ์Šคํ…œ
        
        ๋‹ค๊ตญ์–ด ์‹ค์‹œ๊ฐ„ ๋ฒˆ์—ญ์„ ์ง€์›ํ•˜๋Š” ํ†ตํ•ฉ ๋ฒˆ์—ญ ํ”Œ๋žซํผ
        """
    )
    
    with gr.Tabs():
        # ํƒญ 1 โ€“ ์˜ค๋””์˜ค ๋ฒˆ์—ญ
        with gr.TabItem("๐ŸŽ™๏ธ ์˜ค๋””์˜ค/๋น„๋””์˜ค"):
            gr.Markdown("### ๐ŸŒ ์˜ค๋””์˜ค/๋น„๋””์˜ค ํŒŒ์ผ ๋ฒˆ์—ญ")
            
            with gr.Row():
                src1 = gr.Dropdown(LANG, value="Korean", label="์ž…๋ ฅ ์–ธ์–ด")
                tgt1 = gr.Dropdown(LANG, value="English", label="์ถœ๋ ฅ ์–ธ์–ด")
            
            with gr.Tabs():
                with gr.TabItem("๐Ÿ“ ํŒŒ์ผ ์—…๋กœ๋“œ"):
                    # ํŒŒ์ผ ์—…๋กœ๋“œ - ์˜ค๋””์˜ค์™€ ๋น„๋””์˜ค ๋ชจ๋‘ ์ง€์›
                    aud1_file = gr.File(
                        label="์˜ค๋””์˜ค/๋น„๋””์˜ค ํŒŒ์ผ ์—…๋กœ๋“œ",
                        file_types=[".mp3", ".wav", ".m4a", ".flac", ".ogg", ".opus", 
                                   ".mp4", ".avi", ".mov", ".mkv", ".webm", ".flv"],
                        type="filepath"
                    )
                    gr.Markdown(
                        "๐Ÿ“Œ **์ง€์› ํ˜•์‹**\n"
                        "- ์˜ค๋””์˜ค: MP3, WAV, M4A, FLAC, OGG, OPUS\n"
                        "- ๋น„๋””์˜ค: MP4, AVI, MOV, MKV, WebM, FLV\n\n"
                        "โš ๏ธ **์ฃผ์˜์‚ฌํ•ญ**\n"
                        "- ๋น„๋””์˜ค ํŒŒ์ผ์€ ์˜ค๋””์˜ค ์ถ”์ถœ ์‹œ๊ฐ„์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค\n"
                        "- ๋Œ€์šฉ๋Ÿ‰ ํŒŒ์ผ์€ ์ฒ˜๋ฆฌ ์‹œ๊ฐ„์ด ์˜ค๋ž˜ ๊ฑธ๋ฆด ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค"
                    )
                
                with gr.TabItem("๐ŸŽค ๋งˆ์ดํฌ ๋…น์Œ"):
                    aud1_mic = gr.Audio(
                        sources=["microphone"],
                        type="filepath",
                        label="๋งˆ์ดํฌ ๋…น์Œ"
                    )
                    gr.Markdown("๐Ÿ’ก **ํŒ**: ๋…น์Œ ํ›„ '์ •์ง€' ๋ฒ„ํŠผ์„ ๋ˆŒ๋Ÿฌ์ฃผ์„ธ์š”")
            
            btn1 = gr.Button("๐Ÿ”„ ๋ฒˆ์—ญ ์‹œ์ž‘", variant="primary", size="lg")
            
            # ์ง„ํ–‰ ์ƒํƒœ ํ‘œ์‹œ
            status1 = gr.Textbox(label="์ง„ํ–‰ ์ƒํƒœ", value="๋Œ€๊ธฐ ์ค‘...", interactive=False)
            
            with gr.Row():
                with gr.Column():
                    o1 = gr.Textbox(label="๐Ÿ“ ์›๋ฌธ", lines=6)
                with gr.Column():
                    t1 = gr.Textbox(label="๐Ÿ“ ๋ฒˆ์—ญ", lines=6)
            
            a1 = gr.Audio(label="๐Ÿ”Š ๋ฒˆ์—ญ๋œ ์Œ์„ฑ (TTS)", type="filepath", autoplay=True)
            
            # ํŒŒ์ผ์ด๋‚˜ ๋งˆ์ดํฌ ์ค‘ ํ™œ์„ฑํ™”๋œ ์ž…๋ ฅ ์‚ฌ์šฉ
            def translate_with_status(file_input, mic_input, src, tgt):
                active_input = file_input if file_input else mic_input
                if not active_input:
                    return "โš ๏ธ ํŒŒ์ผ์„ ์—…๋กœ๋“œํ•˜๊ฑฐ๋‚˜ ๋…น์Œ์„ ํ•ด์ฃผ์„ธ์š”", "", None
                
                # ์ƒํƒœ ์—…๋ฐ์ดํŠธ๋Š” ๋™๊ธฐ ํ•จ์ˆ˜์—์„œ ์ฒ˜๋ฆฌ
                return translate_audio(active_input, src, tgt)
            
            btn1.click(
                lambda: "์ฒ˜๋ฆฌ ์ค‘... ์ž ์‹œ๋งŒ ๊ธฐ๋‹ค๋ ค์ฃผ์„ธ์š” โณ",
                outputs=status1
            ).then(
                translate_with_status,
                [aud1_file, aud1_mic, src1, tgt1],
                [o1, t1, a1]
            ).then(
                lambda: "โœ… ์™„๋ฃŒ!",
                outputs=status1
            )

        # ํƒญ 2 โ€“ PDF ๋ฒˆ์—ญ
        with gr.TabItem("๐Ÿ“„ PDF"):
            src2 = gr.Dropdown(LANG, value="Korean", label="์ž…๋ ฅ ์–ธ์–ด")
            tgt2 = gr.Dropdown(LANG, value="English", label="์ถœ๋ ฅ ์–ธ์–ด")
            pdf = gr.File(file_types=[".pdf"])
            btn2 = gr.Button("๋ฒˆ์—ญ")
            o2 = gr.Textbox(label="์ถ”์ถœ ์›๋ฌธ", lines=15)
            t2 = gr.Textbox(label="๋ฒˆ์—ญ ๊ฒฐ๊ณผ", lines=15)
            
            btn2.click(translate_pdf, [pdf, src2, tgt2], [o2, t2])

        # ํƒญ 3 โ€“ ์‹ค์‹œ๊ฐ„ 1์–ธ์–ด
        with gr.TabItem("โฑ๏ธ ์‹ค์‹œ๊ฐ„ 1"):
            src3 = gr.Dropdown(LANG, value="Korean", label="์ž…๋ ฅ ์–ธ์–ด")
            tgt3 = gr.Dropdown(LANG, value="English", label="์ถœ๋ ฅ ์–ธ์–ด")
            
            with gr.Row():
                with gr.Column():
                    gr.Markdown("๐ŸŽค **๋งˆ์ดํฌ ์ž…๋ ฅ**")
                    mic3 = gr.Audio(
                        sources=["microphone"], 
                        streaming=True,
                        type="numpy",  # numpy ํ˜•์‹ ๋ช…์‹œ
                        label="๋งˆ์ดํฌ"
                    )
                    gr.Markdown("๐Ÿ’ก **์‚ฌ์šฉ ๋ฐฉ๋ฒ•**\n- 2-3์ดˆ ์ •๋„ ๋ฌธ์žฅ์„ ๋ง์”€ํ•ด์ฃผ์„ธ์š”\n- ๋„ˆ๋ฌด ์งง๊ฑฐ๋‚˜ ๊ธด ๋ฌธ์žฅ์€ ์ธ์‹์ด ์–ด๋ ค์šธ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค")
                
                with gr.Column():
                    o3 = gr.Textbox(label="์›๋ฌธ(์‹ค์‹œ๊ฐ„)", lines=8, interactive=False)
                    t3 = gr.Textbox(label="๋ฒˆ์—ญ(์‹ค์‹œ๊ฐ„)", lines=8, interactive=False)
            
            st3 = gr.State()
            
            # stream ๋ฉ”์„œ๋“œ ์ˆ˜์ •
            mic3.stream(
                realtime_single_sync,
                inputs=[mic3, src3, tgt3, st3],
                outputs=[o3, t3, st3],
                stream_every=0.5  # 0.5์ดˆ๋งˆ๋‹ค ์ŠคํŠธ๋ฆผ (time_limit ์ œ๊ฑฐ)
            )

        # ํƒญ 4 โ€“ ์‹ค์‹œ๊ฐ„ 4์–ธ์–ด
        with gr.TabItem("๐ŸŒ ์‹ค์‹œ๊ฐ„ 4"):
            src4 = gr.Dropdown(LANG, value="Korean", label="์ž…๋ ฅ ์–ธ์–ด")
            
            with gr.Row():
                with gr.Column(scale=1):
                    gr.Markdown("๐ŸŽค **๋งˆ์ดํฌ ์ž…๋ ฅ**")
                    mic4 = gr.Audio(
                        sources=["microphone"], 
                        streaming=True,
                        type="numpy",
                        label="๋งˆ์ดํฌ"
                    )
                    o4 = gr.Textbox(label="์›๋ฌธ", lines=8, interactive=False)
                
                with gr.Column(scale=2):
                    with gr.Row():
                        e4 = gr.Textbox(label="English", lines=8, interactive=False)
                        c4 = gr.Textbox(label="Chinese(็ฎ€ไฝ“)", lines=8, interactive=False)
                    with gr.Row():
                        th4 = gr.Textbox(label="Thai", lines=8, interactive=False)
                        r4 = gr.Textbox(label="Russian", lines=8, interactive=False)
            
            st4 = gr.State()
            
            # stream ๋ฉ”์„œ๋“œ ์ˆ˜์ •
            mic4.stream(
                realtime_four_sync,
                inputs=[mic4, src4, st4],
                outputs=[o4, e4, c4, th4, r4, st4],
                stream_every=0.5
            )

demo.launch(server_name="0.0.0.0", server_port=7860, debug=True)