File size: 30,286 Bytes
49e7687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd4641e
 
49e7687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
import gradio as gr
import os
import asyncio
import torch
import io
import json
import re
import httpx
import tempfile
import wave
import base64
import numpy as np
import soundfile as sf
import subprocess
import shutil
from dataclasses import dataclass
from typing import List, Tuple, Dict, Optional
from pathlib import Path
from threading import Thread
from dotenv import load_dotenv

# Edge TTS imports
import edge_tts
from pydub import AudioSegment

# OpenAI imports
from openai import OpenAI

# Transformers imports (for local mode)
from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
    TextIteratorStreamer,
    BitsAndBytesConfig,
)

# Spark TTS imports
try:
    from huggingface_hub import snapshot_download
    SPARK_AVAILABLE = True
except:
    SPARK_AVAILABLE = False

# MeloTTS imports (for local mode)
try:
    os.system("python -m unidic download")
    from melo.api import TTS as MeloTTS
    MELO_AVAILABLE = True
except:
    MELO_AVAILABLE = False

load_dotenv()


@dataclass
class ConversationConfig:
    max_words: int = 6000
    prefix_url: str = "https://r.jina.ai/"
    model_name: str = "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo"
    local_model_name: str = "NousResearch/Hermes-2-Pro-Llama-3-8B"


class UnifiedAudioConverter:
    def __init__(self, config: ConversationConfig):
        self.config = config
        self.llm_client = None
        self.local_model = None
        self.tokenizer = None
        self.melo_models = None
        self.spark_model_dir = None
        self.device = "cuda" if torch.cuda.is_available() else "cpu"
        
    def initialize_api_mode(self, api_key: str):
        """Initialize API mode with Together API"""
        self.llm_client = OpenAI(api_key=api_key, base_url="https://api.together.xyz/v1")
        
    def initialize_local_mode(self):
        """Initialize local mode with Hugging Face model"""
        if self.local_model is None:
            quantization_config = BitsAndBytesConfig(
                load_in_4bit=True, 
                bnb_4bit_compute_dtype=torch.float16
            )
            self.local_model = AutoModelForCausalLM.from_pretrained(
                self.config.local_model_name, 
                quantization_config=quantization_config
            )
            self.tokenizer = AutoTokenizer.from_pretrained(
                self.config.local_model_name,
                revision='8ab73a6800796d84448bc936db9bac5ad9f984ae'
            )

    def initialize_spark_tts(self):
        """Initialize Spark TTS model by downloading if needed"""
        if not SPARK_AVAILABLE:
            raise RuntimeError("Spark TTS dependencies not available")
        
        model_dir = "pretrained_models/Spark-TTS-0.5B"
        
        # Check if model exists, if not download it
        if not os.path.exists(model_dir):
            print("Downloading Spark-TTS model...")
            try:
                os.makedirs("pretrained_models", exist_ok=True)
                snapshot_download(
                    "SparkAudio/Spark-TTS-0.5B", 
                    local_dir=model_dir
                )
                print("Spark-TTS model downloaded successfully")
            except Exception as e:
                raise RuntimeError(f"Failed to download Spark-TTS model: {e}")
        
        self.spark_model_dir = model_dir
        
        # Check if we have the CLI inference script
        if not os.path.exists("cli/inference.py"):
            print("Warning: Spark-TTS CLI not found. Please clone the Spark-TTS repository.")

    def initialize_melo_tts(self):
        """Initialize MeloTTS models"""        
        if MELO_AVAILABLE and self.melo_models is None:
            self.melo_models = {"EN": MeloTTS(language="EN", device=self.device)}

    def fetch_text(self, url: str) -> str:
        """Fetch text content from URL"""
        if not url:
            raise ValueError("URL cannot be empty")
            
        if not url.startswith("http://") and not url.startswith("https://"):
            raise ValueError("URL must start with 'http://' or 'https://'")

        full_url = f"{self.config.prefix_url}{url}"
        try:
            response = httpx.get(full_url, timeout=60.0)
            response.raise_for_status()
            return response.text
        except httpx.HTTPError as e:
            raise RuntimeError(f"Failed to fetch URL: {e}")

    def _build_prompt(self, text: str, language: str = "English") -> str:
        """Build prompt for conversation generation"""
        if language == "Korean":
            template = """
            {
                "conversation": [
                    {"speaker": "", "text": ""},
                    {"speaker": "", "text": ""}
                ]
            }
            """
            return (
                f"{text}\n\n์ œ๊ณต๋œ ํ…์ŠคํŠธ๋ฅผ ๋‘ ๋ช…์˜ ์ „๋ฌธ๊ฐ€ ๊ฐ„์˜ ์งง๊ณ  ์œ ์ตํ•˜๋ฉฐ ๋ช…ํ™•ํ•œ "
                f"ํŒŸ์บ์ŠคํŠธ ๋Œ€ํ™”๋กœ ๋ณ€ํ™˜ํ•ด์ฃผ์„ธ์š”. ํ†ค์€ ์ „๋ฌธ์ ์ด๊ณ  ๋งค๋ ฅ์ ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. "
                f"๋‹ค์Œ ํ˜•์‹์„ ์ค€์ˆ˜ํ•˜๊ณ  JSON๋งŒ ๋ฐ˜ํ™˜ํ•ด์ฃผ์„ธ์š”:\n{template}"
            )
        else:
            template = """
            {
                "conversation": [
                    {"speaker": "", "text": ""},
                    {"speaker": "", "text": ""}
                ]
            }
            """
            return (
                f"{text}\n\nConvert the provided text into a short, informative and crisp "
                f"podcast conversation between two experts. The tone should be "
                f"professional and engaging. Please adhere to the following "
                f"format and return ONLY the JSON:\n{template}"
            )

    def extract_conversation_api(self, text: str, language: str = "English") -> Dict:
        """Extract conversation using API"""
        if not self.llm_client:
            raise RuntimeError("API mode not initialized")

        try:
            # ์–ธ์–ด๋ณ„ ํ”„๋กฌํ”„ํŠธ ๊ตฌ์„ฑ
            if language == "Korean":
                system_message = "๋‹น์‹ ์€ ํ•œ๊ตญ์–ด๋กœ ํŒŸ์บ์ŠคํŠธ ๋Œ€ํ™”๋ฅผ ์ƒ์„ฑํ•˜๋Š” ์ „๋ฌธ๊ฐ€์ž…๋‹ˆ๋‹ค. ์ž์—ฐ์Šค๋Ÿฝ๊ณ  ์œ ์ตํ•œ ํ•œ๊ตญ์–ด ๋Œ€ํ™”๋ฅผ ๋งŒ๋“ค์–ด์ฃผ์„ธ์š”."
            else:
                system_message = "You are an expert at creating podcast conversations in English. Create natural and informative English conversations."

            chat_completion = self.llm_client.chat.completions.create(
                messages=[
                    {"role": "system", "content": system_message},
                    {"role": "user", "content": self._build_prompt(text, language)}
                ],
                model=self.config.model_name,
            )

            pattern = r"\{(?:[^{}]|(?:\{[^{}]*\}))*\}"
            json_match = re.search(pattern, chat_completion.choices[0].message.content)

            if not json_match:
                raise ValueError("No valid JSON found in response")

            return json.loads(json_match.group())
        except Exception as e:
            raise RuntimeError(f"Failed to extract conversation: {e}")

    def extract_conversation_local(self, text: str, language: str = "English", progress=None) -> Dict:
        """Extract conversation using local model"""
        if not self.local_model or not self.tokenizer:
            raise RuntimeError("Local mode not initialized")

        # ์–ธ์–ด๋ณ„ ์‹œ์Šคํ…œ ๋ฉ”์‹œ์ง€
        if language == "Korean":
            system_message = "๋‹น์‹ ์€ ํ•œ๊ตญ์–ด๋กœ ํŒŸ์บ์ŠคํŠธ ๋Œ€ํ™”๋ฅผ ์ƒ์„ฑํ•˜๋Š” ์ „๋ฌธ๊ฐ€์ž…๋‹ˆ๋‹ค. ์ž์—ฐ์Šค๋Ÿฝ๊ณ  ์œ ์ตํ•œ ํ•œ๊ตญ์–ด ๋Œ€ํ™”๋ฅผ ๋งŒ๋“ค์–ด์ฃผ์„ธ์š”."
        else:
            system_message = "You are an expert at creating podcast conversations in English. Create natural and informative English conversations."

        chat = [
            {"role": "system", "content": system_message},
            {"role": "user", "content": self._build_prompt(text, language)}
        ]

        terminators = [
            self.tokenizer.eos_token_id,
            self.tokenizer.convert_tokens_to_ids("<|eot_id|>")
        ]

        messages = self.tokenizer.apply_chat_template(
            chat, tokenize=False, add_generation_prompt=True
        )
        model_inputs = self.tokenizer([messages], return_tensors="pt").to(self.device)
        
        streamer = TextIteratorStreamer(
            self.tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True
        )
        
        generate_kwargs = dict(
            model_inputs,
            streamer=streamer,
            max_new_tokens=4000,
            do_sample=True,
            temperature=0.9,
            eos_token_id=terminators,
        )

        t = Thread(target=self.local_model.generate, kwargs=generate_kwargs)
        t.start()

        partial_text = ""
        for new_text in streamer:
            partial_text += new_text

        pattern = r"\{(?:[^{}]|(?:\{[^{}]*\}))*\}"
        json_match = re.search(pattern, partial_text)
        
        if json_match:
            return json.loads(json_match.group())
        else:
            # Return a default template based on language
            if language == "Korean":
                return {
                    "conversation": [
                        {"speaker": "์ง„ํ–‰์ž", "text": "์•ˆ๋…•ํ•˜์„ธ์š”, ํŒŸ์บ์ŠคํŠธ์— ์˜ค์‹  ๊ฒƒ์„ ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค."},
                        {"speaker": "๊ฒŒ์ŠคํŠธ", "text": "์•ˆ๋…•ํ•˜์„ธ์š”, ์ดˆ๋Œ€ํ•ด ์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค."}
                    ]
                }
            else:
                return {
                    "conversation": [
                        {"speaker": "Host", "text": "Welcome to our podcast."},
                        {"speaker": "Guest", "text": "Thank you for having me."}
                    ]
                }

    def parse_conversation_text(self, conversation_text: str) -> Dict:
        """Parse conversation text back to JSON format"""
        lines = conversation_text.strip().split('\n')
        conversation_data = {"conversation": []}
        
        for line in lines:
            if ':' in line:
                speaker, text = line.split(':', 1)
                conversation_data["conversation"].append({
                    "speaker": speaker.strip(),
                    "text": text.strip()
                })
        
        return conversation_data

    async def text_to_speech_edge(self, conversation_json: Dict, language: str = "English") -> Tuple[str, str]:
        """Convert text to speech using Edge TTS"""
        output_dir = Path(self._create_output_directory())
        filenames = []

        try:
            # ์–ธ์–ด๋ณ„ ์Œ์„ฑ ์„ค์ •
            if language == "Korean":
                voices = [
                    "ko-KR-SunHiMultilingualNeural",  # ์—ฌ์„ฑ ์Œ์„ฑ (์ž์—ฐ์Šค๋Ÿฌ์šด ํ•œ๊ตญ์–ด)
                    "ko-KR-HyunsuMultilingualNeural"  # ๋‚จ์„ฑ ์Œ์„ฑ (์ž์—ฐ์Šค๋Ÿฌ์šด ํ•œ๊ตญ์–ด)
                ]
            else:
                voices = [
                    "en-US-AvaMultilingualNeural",    # ์—ฌ์„ฑ ์Œ์„ฑ
                    "en-US-AndrewMultilingualNeural"  # ๋‚จ์„ฑ ์Œ์„ฑ
                ]

            for i, turn in enumerate(conversation_json["conversation"]):
                filename = output_dir / f"output_{i}.wav"
                voice = voices[i % len(voices)]

                tmp_path = await self._generate_audio_edge(turn["text"], voice)
                os.rename(tmp_path, filename)
                filenames.append(str(filename))

            # Combine audio files
            final_output = os.path.join(output_dir, "combined_output.wav")
            self._combine_audio_files(filenames, final_output)
            
            # Generate conversation text
            conversation_text = "\n".join(
                f"{turn.get('speaker', f'Speaker {i+1}')}: {turn['text']}" 
                for i, turn in enumerate(conversation_json["conversation"])
            )
            
            return final_output, conversation_text
        except Exception as e:
            raise RuntimeError(f"Failed to convert text to speech: {e}")

    async def _generate_audio_edge(self, text: str, voice: str) -> str:
        """Generate audio using Edge TTS"""
        if not text.strip():
            raise ValueError("Text cannot be empty")
            
        voice_short_name = voice.split(" - ")[0] if " - " in voice else voice
        communicate = edge_tts.Communicate(text, voice_short_name)

        with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
            tmp_path = tmp_file.name
            await communicate.save(tmp_path)

        return tmp_path

    def text_to_speech_spark(self, conversation_json: Dict, language: str = "English", progress=None) -> Tuple[str, str]:
        """Convert text to speech using Spark TTS CLI"""
        if not SPARK_AVAILABLE or not self.spark_model_dir:
            raise RuntimeError("Spark TTS not available")

        try:
            output_dir = self._create_output_directory()
            audio_files = []
            
            # Create different voice characteristics for different speakers
            if language == "Korean":
                voice_configs = [
                    {"prompt_text": "์•ˆ๋…•ํ•˜์„ธ์š”, ์˜ค๋Š˜ ํŒŸ์บ์ŠคํŠธ ์ง„ํ–‰์„ ๋งก์€ ์ง„ํ–‰์ž์ž…๋‹ˆ๋‹ค.", "gender": "female"},
                    {"prompt_text": "์•ˆ๋…•ํ•˜์„ธ์š”, ์˜ค๋Š˜ ๊ฒŒ์ŠคํŠธ๋กœ ์ฐธ์—ฌํ•˜๊ฒŒ ๋˜์–ด ๊ธฐ์ฉ๋‹ˆ๋‹ค.", "gender": "male"}
                ]
            else:
                voice_configs = [
                    {"prompt_text": "Hello, welcome to our podcast. I'm your host today.", "gender": "female"},
                    {"prompt_text": "Thank you for having me. I'm excited to be here.", "gender": "male"}
                ]

            for i, turn in enumerate(conversation_json["conversation"]):
                text = turn["text"]
                if not text.strip():
                    continue
                
                # Use different voice config for each speaker
                voice_config = voice_configs[i % len(voice_configs)]
                
                output_file = os.path.join(output_dir, f"spark_output_{i}.wav")
                
                # Run Spark TTS CLI inference
                cmd = [
                    "python", "-m", "cli.inference",
                    "--text", text,
                    "--device", "0" if torch.cuda.is_available() else "cpu",
                    "--save_dir", output_dir,
                    "--model_dir", self.spark_model_dir,
                    "--prompt_text", voice_config["prompt_text"],
                    "--output_name", f"spark_output_{i}.wav"
                ]
                
                try:
                    # Run the command
                    result = subprocess.run(
                        cmd, 
                        capture_output=True, 
                        text=True, 
                        timeout=60,
                        cwd="."  # Make sure we're in the right directory
                    )
                    
                    if result.returncode == 0:
                        audio_files.append(output_file)
                    else:
                        print(f"Spark TTS error for turn {i}: {result.stderr}")
                        # Create a short silence as fallback
                        silence = np.zeros(int(22050 * 1.0))  # 1 second of silence
                        sf.write(output_file, silence, 22050)
                        audio_files.append(output_file)
                        
                except subprocess.TimeoutExpired:
                    print(f"Spark TTS timeout for turn {i}")
                    # Create silence as fallback
                    silence = np.zeros(int(22050 * 1.0))
                    sf.write(output_file, silence, 22050)
                    audio_files.append(output_file)
                except Exception as e:
                    print(f"Error running Spark TTS for turn {i}: {e}")
                    # Create silence as fallback
                    silence = np.zeros(int(22050 * 1.0))
                    sf.write(output_file, silence, 22050)
                    audio_files.append(output_file)

            # Combine all audio files
            if audio_files:
                final_output = os.path.join(output_dir, "spark_combined.wav")
                self._combine_audio_files(audio_files, final_output)
            else:
                raise RuntimeError("No audio files generated")

            # Generate conversation text
            conversation_text = "\n".join(
                f"{turn.get('speaker', f'Speaker {i+1}')}: {turn['text']}" 
                for i, turn in enumerate(conversation_json["conversation"])
            )
            
            return final_output, conversation_text
            
        except Exception as e:
            raise RuntimeError(f"Failed to convert text to speech with Spark TTS: {e}")

    def text_to_speech_melo(self, conversation_json: Dict, progress=None) -> Tuple[str, str]:
        """Convert text to speech using MeloTTS"""
        if not MELO_AVAILABLE or not self.melo_models:
            raise RuntimeError("MeloTTS not available")

        speakers = ["EN-Default", "EN-US"]
        combined_audio = AudioSegment.empty()

        for i, turn in enumerate(conversation_json["conversation"]):
            bio = io.BytesIO()
            text = turn["text"]
            speaker = speakers[i % 2]
            speaker_id = self.melo_models["EN"].hps.data.spk2id[speaker]
            
            # Generate audio
            self.melo_models["EN"].tts_to_file(
                text, speaker_id, bio, speed=1.0, 
                pbar=progress.tqdm if progress else None, 
                format="wav"
            )
            
            bio.seek(0)
            audio_segment = AudioSegment.from_file(bio, format="wav")
            combined_audio += audio_segment

        # Save final audio
        final_audio_path = "melo_podcast.mp3"
        combined_audio.export(final_audio_path, format="mp3")
        
        # Generate conversation text
        conversation_text = "\n".join(
            f"{turn.get('speaker', f'Speaker {i+1}')}: {turn['text']}" 
            for i, turn in enumerate(conversation_json["conversation"])
        )
        
        return final_audio_path, conversation_text

    def _create_output_directory(self) -> str:
        """Create a unique output directory"""
        random_bytes = os.urandom(8)
        folder_name = base64.urlsafe_b64encode(random_bytes).decode("utf-8")
        os.makedirs(folder_name, exist_ok=True)
        return folder_name

    def _combine_audio_files(self, filenames: List[str], output_file: str) -> None:
        """Combine multiple audio files into one"""
        if not filenames:
            raise ValueError("No input files provided")

        try:
            audio_segments = []
            for filename in filenames:
                if os.path.exists(filename):
                    audio_segment = AudioSegment.from_file(filename)
                    audio_segments.append(audio_segment)

            if audio_segments:
                combined = sum(audio_segments)
                combined.export(output_file, format="wav")

            # Clean up temporary files
            for filename in filenames:
                if os.path.exists(filename):
                    os.remove(filename)

        except Exception as e:
            raise RuntimeError(f"Failed to combine audio files: {e}")


# Global converter instance
converter = UnifiedAudioConverter(ConversationConfig())


async def synthesize(article_url: str, mode: str = "API", tts_engine: str = "Edge-TTS", language: str = "English"):
    """Main synthesis function"""
    if not article_url:
        return "Please provide a valid URL.", None

    try:
        # Fetch text from URL
        text = converter.fetch_text(article_url)
        
        # Limit text to max words
        words = text.split()
        if len(words) > converter.config.max_words:
            text = " ".join(words[:converter.config.max_words])

        # Extract conversation based on mode
        if mode == "API":
            api_key = os.environ.get("TOGETHER_API_KEY")
            if not api_key:
                return "API key not found. Please set TOGETHER_API_KEY environment variable.", None
            converter.initialize_api_mode(api_key)
            conversation_json = converter.extract_conversation_api(text, language)
        else:  # Local mode
            converter.initialize_local_mode()
            conversation_json = converter.extract_conversation_local(text, language)

        # Generate conversation text
        conversation_text = "\n".join(
            f"{turn.get('speaker', f'Speaker {i+1}')}: {turn['text']}" 
            for i, turn in enumerate(conversation_json["conversation"])
        )

        return conversation_text, None
        
    except Exception as e:
        return f"Error: {str(e)}", None


async def regenerate_audio(conversation_text: str, tts_engine: str = "Edge-TTS", language: str = "English"):
    """Regenerate audio from edited conversation text"""
    if not conversation_text.strip():
        return "Please provide conversation text.", None

    try:
        # Parse the conversation text back to JSON format
        conversation_json = converter.parse_conversation_text(conversation_text)
        
        if not conversation_json["conversation"]:
            return "No valid conversation found in the text.", None

        # ํ•œ๊ตญ์–ด์ธ ๊ฒฝ์šฐ Edge-TTS๋งŒ ์‚ฌ์šฉ (๋‹ค๋ฅธ TTS๋Š” ํ•œ๊ตญ์–ด ์ง€์›์ด ์ œํ•œ์ )
        if language == "Korean" and tts_engine != "Edge-TTS":
            return "ํ•œ๊ตญ์–ด๋Š” Edge-TTS๋งŒ ์ง€์›๋ฉ๋‹ˆ๋‹ค. TTS ์—”์ง„์ด ์ž๋™์œผ๋กœ Edge-TTS๋กœ ๋ณ€๊ฒฝ๋ฉ๋‹ˆ๋‹ค.", None

        # Generate audio based on TTS engine
        if tts_engine == "Edge-TTS":
            output_file, _ = await converter.text_to_speech_edge(conversation_json, language)
        elif tts_engine == "Spark-TTS":
            if not SPARK_AVAILABLE:
                return "Spark TTS not available. Please install required dependencies and clone the Spark-TTS repository.", None
            converter.initialize_spark_tts()
            output_file, _ = converter.text_to_speech_spark(conversation_json, language)
        else:  # MeloTTS
            if not MELO_AVAILABLE:
                return "MeloTTS not available. Please install required dependencies.", None
            if language == "Korean":
                return "MeloTTS does not support Korean. Please use Edge-TTS for Korean.", None
            converter.initialize_melo_tts()
            output_file, _ = converter.text_to_speech_melo(conversation_json)

        return "Audio generated successfully!", output_file
        
    except Exception as e:
        return f"Error generating audio: {str(e)}", None


def synthesize_sync(article_url: str, mode: str = "API", tts_engine: str = "Edge-TTS", language: str = "English"):
    """Synchronous wrapper for async synthesis"""
    return asyncio.run(synthesize(article_url, mode, tts_engine, language))


def regenerate_audio_sync(conversation_text: str, tts_engine: str = "Edge-TTS", language: str = "English"):
    """Synchronous wrapper for async audio regeneration"""
    return asyncio.run(regenerate_audio(conversation_text, tts_engine, language))


def update_tts_engine_for_korean(language):
    """ํ•œ๊ตญ์–ด ์„ ํƒ ์‹œ TTS ์—”์ง„ ์˜ต์…˜ ์—…๋ฐ์ดํŠธ"""
    if language == "Korean":
        return gr.Radio(
            choices=["Edge-TTS"],
            value="Edge-TTS",
            label="TTS Engine",
            info="ํ•œ๊ตญ์–ด๋Š” Edge-TTS๋งŒ ์ง€์›๋ฉ๋‹ˆ๋‹ค",
            interactive=False
        )
    else:
        return gr.Radio(
            choices=["Edge-TTS", "Spark-TTS", "MeloTTS"],
            value="Edge-TTS",
            label="TTS Engine",
            info="Edge-TTS: Cloud-based, natural voices | Spark-TTS: Local AI model | MeloTTS: Local, requires GPU",
            interactive=True
        )


# Gradio Interface
with gr.Blocks(theme='soft', title="URL to Podcast Converter") as demo:
    gr.Markdown("# ๐ŸŽ™๏ธ URL to Podcast Converter")
    gr.Markdown("Convert any article, blog, or news into an engaging podcast conversation!")
    
    with gr.Row():
        with gr.Column(scale=3):
            url_input = gr.Textbox(
                label="Article URL", 
                placeholder="Enter the article URL here...",
                value=""
            )
        with gr.Column(scale=1):
            # ์–ธ์–ด ์„ ํƒ ์ถ”๊ฐ€
            language_selector = gr.Radio(
                choices=["English", "Korean"],
                value="English",
                label="Language / ์–ธ์–ด",
                info="Select output language / ์ถœ๋ ฅ ์–ธ์–ด๋ฅผ ์„ ํƒํ•˜์„ธ์š”"
            )
            
            mode_selector = gr.Radio(
                choices=["API", "Local"],
                value="API",
                label="Processing Mode",
                info="API: Faster, requires API key | Local: Slower, runs on device"
            )
            
            # TTS ์—”์ง„ ์„ ํƒ
            with gr.Group():
                gr.Markdown("### TTS Engine Selection")
                tts_selector = gr.Radio(
                    choices=["Edge-TTS", "Spark-TTS", "MeloTTS"],
                    value="Edge-TTS",
                    label="TTS Engine",
                    info="Edge-TTS: Cloud-based, natural voices | Spark-TTS: Local AI model | MeloTTS: Local, requires GPU"
                )
                
                gr.Markdown("""
                **Recommended:**
                - ๐ŸŒŸ **Edge-TTS**: Best quality, cloud-based, instant setup
                - ๐Ÿค– **Spark-TTS**: Local AI model (0.5B), zero-shot voice cloning
                
                **Additional Option:**
                - โšก **MeloTTS**: Local processing, GPU recommended
                
                **ํ•œ๊ตญ์–ด ์ง€์›:**
                - ๐Ÿ‡ฐ๐Ÿ‡ท ํ•œ๊ตญ์–ด ์„ ํƒ ์‹œ Edge-TTS๋งŒ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค
                """)
    
    convert_btn = gr.Button("๐ŸŽฏ Generate Conversation / ๋Œ€ํ™” ์ƒ์„ฑ", variant="primary", size="lg")
    
    with gr.Row():
        with gr.Column():
            conversation_output = gr.Textbox(
                label="Generated Conversation (Editable) / ์ƒ์„ฑ๋œ ๋Œ€ํ™” (ํŽธ์ง‘ ๊ฐ€๋Šฅ)",
                lines=15,
                max_lines=30,
                interactive=True,
                placeholder="Generated conversation will appear here. You can edit it before generating audio.\n์ƒ์„ฑ๋œ ๋Œ€ํ™”๊ฐ€ ์—ฌ๊ธฐ์— ํ‘œ์‹œ๋ฉ๋‹ˆ๋‹ค. ์˜ค๋””์˜ค ์ƒ์„ฑ ์ „์— ํŽธ์ง‘ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.",
                info="Edit the conversation as needed. Format: 'Speaker Name: Text' / ํ•„์š”์— ๋”ฐ๋ผ ๋Œ€ํ™”๋ฅผ ํŽธ์ง‘ํ•˜์„ธ์š”. ํ˜•์‹: 'ํ™”์ž ์ด๋ฆ„: ํ…์ŠคํŠธ'"
            )
            
            # ์˜ค๋””์˜ค ์ƒ์„ฑ ๋ฒ„ํŠผ ์ถ”๊ฐ€
            with gr.Row():
                generate_audio_btn = gr.Button("๐ŸŽ™๏ธ Generate Audio from Text / ํ…์ŠคํŠธ์—์„œ ์˜ค๋””์˜ค ์ƒ์„ฑ", variant="secondary", size="lg")
                gr.Markdown("*Edit the conversation above, then click to generate audio / ์œ„์˜ ๋Œ€ํ™”๋ฅผ ํŽธ์ง‘ํ•œ ํ›„ ํด๋ฆญํ•˜์—ฌ ์˜ค๋””์˜ค๋ฅผ ์ƒ์„ฑํ•˜์„ธ์š”*")
            
        with gr.Column():
            audio_output = gr.Audio(
                label="Podcast Audio / ํŒŸ์บ์ŠคํŠธ ์˜ค๋””์˜ค",
                type="filepath",
                interactive=False
            )
            
            # ์ƒํƒœ ๋ฉ”์‹œ์ง€ ์ถ”๊ฐ€
            status_output = gr.Textbox(
                label="Status / ์ƒํƒœ",
                interactive=False,
                visible=True
            )
    
    # TTS ์—”์ง„๋ณ„ ์„ค๋ช… ๋ฐ ์„ค์น˜ ์•ˆ๋‚ด ์ถ”๊ฐ€
    with gr.Row():
        gr.Markdown("""
        ### TTS Engine Details / TTS ์—”์ง„ ์ƒ์„ธ์ •๋ณด:
        
        - **Edge-TTS**: Microsoft's cloud TTS service with high-quality natural voices. Requires internet connection.
          - ๐Ÿ‡ฐ๐Ÿ‡ท **ํ•œ๊ตญ์–ด ์ง€์›**: ์ž์—ฐ์Šค๋Ÿฌ์šด ํ•œ๊ตญ์–ด ์Œ์„ฑ (์—ฌ์„ฑ: SunHi, ๋‚จ์„ฑ: InJoon)
        - **Spark-TTS**: SparkAudio's local AI model (0.5B parameters) with zero-shot voice cloning capability. 
          - **Setup required**: Clone [Spark-TTS repository](https://github.com/SparkAudio/Spark-TTS) in current directory
          - Features: Bilingual support (Chinese/English), controllable speech generation
          - License: CC BY-NC-SA (Non-commercial use only)
          - โš ๏ธ **ํ•œ๊ตญ์–ด ๋ฏธ์ง€์›**
        - **MeloTTS**: Local TTS with multiple voice options. GPU recommended for better performance.
          - โš ๏ธ **ํ•œ๊ตญ์–ด ๋ฏธ์ง€์›**
        
        ### Spark-TTS Setup Instructions:
        ```bash
        git clone https://github.com/SparkAudio/Spark-TTS.git
        cd Spark-TTS
        pip install -r requirements.txt
        ```
        """)
    
    gr.Examples(
        examples=[
            ["https://huggingface.co/blog/openfree/cycle-navigator", "API", "Edge-TTS", "English"],
            ["https://www.bbc.com/news/technology-67988517", "API", "Spark-TTS", "English"],
            ["https://arxiv.org/abs/2301.00810", "API", "Edge-TTS", "Korean"],
        ],
        inputs=[url_input, mode_selector, tts_selector, language_selector],
        outputs=[conversation_output, status_output],
        fn=synthesize_sync,
        cache_examples=False,
    )
    
    # ์–ธ์–ด ๋ณ€๊ฒฝ ์‹œ TTS ์—”์ง„ ์˜ต์…˜ ์—…๋ฐ์ดํŠธ
    language_selector.change(
        fn=update_tts_engine_for_korean,
        inputs=[language_selector],
        outputs=[tts_selector]
    )
    
    # ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ
    convert_btn.click(
        fn=synthesize_sync,
        inputs=[url_input, mode_selector, tts_selector, language_selector],
        outputs=[conversation_output, status_output]
    )
    
    generate_audio_btn.click(
        fn=regenerate_audio_sync,
        inputs=[conversation_output, tts_selector, language_selector],
        outputs=[status_output, audio_output]
    )


# Launch the app
if __name__ == "__main__":
    demo.queue(api_open=True, default_concurrency_limit=10).launch(
        show_api=True,
        share=False,
        server_name="0.0.0.0",
        server_port=7860
    )