Spaces:
Running
on
Zero
Running
on
Zero
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) |