import spaces # 추가 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 import requests import logging from datetime import datetime, timedelta from dataclasses import dataclass from typing import List, Tuple, Dict, Optional from pathlib import Path from threading import Thread from dotenv import load_dotenv # PDF processing imports from langchain_community.document_loaders import PyPDFLoader # Edge TTS imports import edge_tts from pydub import AudioSegment # OpenAI imports from openai import OpenAI # Transformers imports (for legacy local mode) from transformers import ( AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, BitsAndBytesConfig, ) # Llama CPP imports (for new local mode) try: from llama_cpp import Llama from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType from llama_cpp_agent.providers import LlamaCppPythonProvider from llama_cpp_agent.chat_history import BasicChatHistory from llama_cpp_agent.chat_history.messages import Roles from huggingface_hub import hf_hub_download LLAMA_CPP_AVAILABLE = True except ImportError: LLAMA_CPP_AVAILABLE = False # Spark TTS imports try: from huggingface_hub import snapshot_download SPARK_AVAILABLE = True except: SPARK_AVAILABLE = False # MeloTTS imports (for local mode) try: # unidic 다운로드를 조건부로 처리 if not os.path.exists("/usr/local/lib/python3.10/site-packages/unidic"): try: os.system("python -m unidic download") except: pass from melo.api import TTS as MeloTTS MELO_AVAILABLE = True except: MELO_AVAILABLE = False load_dotenv() # Brave Search API 설정 BRAVE_KEY = os.getenv("BSEARCH_API") BRAVE_ENDPOINT = "https://api.search.brave.com/res/v1/web/search" @dataclass class ConversationConfig: max_words: int = 8000 # 4000에서 6000으로 증가 (1.5배) prefix_url: str = "https://r.jina.ai/" api_model_name: str = "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo" legacy_local_model_name: str = "NousResearch/Hermes-2-Pro-Llama-3-8B" # 새로운 로컬 모델 설정 local_model_name: str = "Private-BitSix-Mistral-Small-3.1-24B-Instruct-2503.gguf" local_model_repo: str = "ginigen/Private-BitSix-Mistral-Small-3.1-24B-Instruct-2503" # 토큰 수 증가 max_tokens: int = 6000 # 3000에서 4500으로 증가 (1.5배) max_new_tokens: int = 12000 # 6000에서 9000으로 증가 (1.5배) min_conversation_turns: int = 18 # 최소 대화 턴 수 max_conversation_turns: int = 20 # 최대 대화 턴 수 def brave_search(query: str, count: int = 8, freshness_days: int | None = None): """Brave Search API를 사용하여 최신 정보 검색""" if not BRAVE_KEY: return [] params = {"q": query, "count": str(count)} if freshness_days: dt_from = (datetime.utcnow() - timedelta(days=freshness_days)).strftime("%Y-%m-%d") params["freshness"] = dt_from try: r = requests.get( BRAVE_ENDPOINT, headers={"Accept": "application/json", "X-Subscription-Token": BRAVE_KEY}, params=params, timeout=15 ) raw = r.json().get("web", {}).get("results") or [] return [{ "title": r.get("title", ""), "url": r.get("url", r.get("link", "")), "snippet": r.get("description", r.get("text", "")), "host": re.sub(r"https?://(www\.)?", "", r.get("url", "")).split("/")[0] } for r in raw[:count]] except Exception as e: logging.error(f"Brave search error: {e}") return [] def format_search_results(query: str, for_keyword: bool = False) -> str: """검색 결과를 포맷팅하여 반환""" # 키워드 검색의 경우 더 많은 결과 사용 count = 5 if for_keyword else 3 rows = brave_search(query, count, freshness_days=7 if not for_keyword else None) if not rows: return "" results = [] # 키워드 검색의 경우 더 상세한 정보 포함 max_results = 4 if for_keyword else 2 for r in rows[:max_results]: if for_keyword: # 키워드 검색은 더 긴 스니펫 사용 snippet = r['snippet'][:200] + "..." if len(r['snippet']) > 200 else r['snippet'] results.append(f"**{r['title']}**\n{snippet}\nSource: {r['host']}") else: # 일반 검색은 짧은 스니펫 snippet = r['snippet'][:100] + "..." if len(r['snippet']) > 100 else r['snippet'] results.append(f"- {r['title']}: {snippet}") return "\n\n".join(results) + "\n" def extract_keywords_for_search(text: str, language: str = "English") -> List[str]: """텍스트에서 검색할 키워드 추출 (개선)""" # 텍스트 앞부분만 사용 (너무 많은 텍스트 처리 방지) text_sample = text[:500] if language == "Korean": import re # 한국어 명사 추출 (2글자 이상) keywords = re.findall(r'[가-힣]{2,}', text_sample) # 중복 제거하고 가장 긴 단어 1개만 선택 unique_keywords = list(dict.fromkeys(keywords)) # 길이 순으로 정렬하고 가장 의미있을 것 같은 단어 선택 unique_keywords.sort(key=len, reverse=True) return unique_keywords[:1] # 1개만 반환 else: # 영어는 대문자로 시작하는 단어 중 가장 긴 것 1개 words = text_sample.split() keywords = [word.strip('.,!?;:') for word in words if len(word) > 4 and word[0].isupper()] if keywords: return [max(keywords, key=len)] # 가장 긴 단어 1개 return [] def search_and_compile_content(keyword: str, language: str = "English") -> str: """키워드로 검색하여 충분한 콘텐츠 컴파일""" if not BRAVE_KEY: # API 없을 때도 기본 콘텐츠 생성 if language == "Korean": return f""" '{keyword}'에 대한 종합적인 정보: {keyword}는 현대 사회에서 매우 중요한 주제입니다. 이 주제는 다양한 측면에서 우리의 삶에 영향을 미치고 있으며, 최근 들어 더욱 주목받고 있습니다. 주요 특징: 1. 기술적 발전과 혁신 2. 사회적 영향과 변화 3. 미래 전망과 가능성 4. 실용적 활용 방안 5. 글로벌 트렌드와 동향 전문가들은 {keyword}가 앞으로 더욱 중요해질 것으로 예상하고 있으며, 이에 대한 깊이 있는 이해가 필요한 시점입니다. """ else: return f""" Comprehensive information about '{keyword}': {keyword} is a significant topic in modern society. This subject impacts our lives in various ways and has been gaining increasing attention recently. Key aspects: 1. Technological advancement and innovation 2. Social impact and changes 3. Future prospects and possibilities 4. Practical applications 5. Global trends and developments Experts predict that {keyword} will become even more important, and it's crucial to develop a deep understanding of this topic. """ # 언어에 따른 다양한 검색 쿼리 if language == "Korean": queries = [ f"{keyword} 최신 뉴스 2024", f"{keyword} 정보 설명", f"{keyword} 트렌드 전망", f"{keyword} 장점 단점", f"{keyword} 활용 방법", f"{keyword} 전문가 의견" ] else: queries = [ f"{keyword} latest news 2024", f"{keyword} explained comprehensive", f"{keyword} trends forecast", f"{keyword} advantages disadvantages", f"{keyword} how to use", f"{keyword} expert opinions" ] all_content = [] total_content_length = 0 for query in queries: results = brave_search(query, count=5) # 더 많은 결과 가져오기 for r in results[:3]: # 각 쿼리당 상위 3개 content = f"**{r['title']}**\n{r['snippet']}\nSource: {r['host']}\n" all_content.append(content) total_content_length += len(r['snippet']) # 콘텐츠가 부족하면 추가 생성 if total_content_length < 1000: # 최소 1000자 확보 if language == "Korean": additional_content = f""" 추가 정보: {keyword}와 관련된 최근 동향을 살펴보면, 이 분야는 빠르게 발전하고 있습니다. 많은 전문가들이 이 주제에 대해 활발히 연구하고 있으며, 실생활에서의 응용 가능성도 계속 확대되고 있습니다. 특히 주목할 점은: - 기술 혁신의 가속화 - 사용자 경험의 개선 - 접근성의 향상 - 비용 효율성 증대 - 글로벌 시장의 성장 이러한 요소들이 {keyword}의 미래를 더욱 밝게 만들고 있습니다. """ else: additional_content = f""" Additional insights: Recent developments in {keyword} show rapid advancement in this field. Many experts are actively researching this topic, and its practical applications continue to expand. Key points to note: - Accelerating technological innovation - Improving user experience - Enhanced accessibility - Increased cost efficiency - Growing global market These factors are making the future of {keyword} increasingly promising. """ all_content.append(additional_content) # 컴파일된 콘텐츠 반환 compiled = "\n\n".join(all_content) # 키워드 기반 소개 if language == "Korean": intro = f"### '{keyword}'에 대한 종합적인 정보와 최신 동향:\n\n" else: intro = f"### Comprehensive information and latest trends about '{keyword}':\n\n" return intro + compiled def _build_prompt(self, text: str, language: str = "English", search_context: str = "") -> str: """Build prompt for conversation generation with enhanced radio talk show style""" # 텍스트 길이 제한 max_text_length = 4500 if search_context else 6000 if len(text) > max_text_length: text = text[:max_text_length] + "..." if language == "Korean": # 대화 템플릿을 더 많은 턴으로 확장 (15-20회) template = """ { "conversation": [ {"speaker": "준수", "text": ""}, {"speaker": "민호", "text": ""}, {"speaker": "준수", "text": ""}, {"speaker": "민호", "text": ""}, {"speaker": "준수", "text": ""}, {"speaker": "민호", "text": ""}, {"speaker": "준수", "text": ""}, {"speaker": "민호", "text": ""}, {"speaker": "준수", "text": ""}, {"speaker": "민호", "text": ""}, {"speaker": "준수", "text": ""}, {"speaker": "민호", "text": ""}, {"speaker": "준수", "text": ""}, {"speaker": "민호", "text": ""}, {"speaker": "준수", "text": ""}, {"speaker": "민호", "text": ""}, {"speaker": "준수", "text": ""}, {"speaker": "민호", "text": ""} ] } """ context_part = "" if search_context: context_part = f"# 최신 관련 정보:\n{search_context}\n" base_prompt = ( f"# 원본 콘텐츠:\n{text}\n\n" f"{context_part}" f"위 내용으로 30줄 이상의 라디오 대담 프로그램 대본을 작성해주세요.\n\n" f"## 필수 요구사항:\n" f"1. **최소 18회 이상의 대화 교환** (준수 9회, 민호 9회 이상)\n" f"2. **대화 스타일**: 실제 라디오 대담처럼 아주 자연스럽고 편안한 구어체\n" f"3. **화자 역할**:\n" f" - 준수: 진행자 (짧은 질문, 리액션, 화제 전환)\n" f" - 민호: 전문가 (간결한 설명, 예시 제공)\n" f"4. **대화 패턴**:\n" f" - 준수: \"그렇군요\", \"흥미롭네요\", \"더 자세히 설명해주시겠어요?\"\n" f" - 민호: 1-2문장으로 핵심 설명\n" f" - 자연스러운 추임새 사용\n" f"5. **내용 구성**:\n" f" - 도입부 (2-3회): 주제 소개\n" f" - 전개부 (10-12회): 핵심 내용 설명\n" f" - 마무리 (3-4회): 요약 및 정리\n" f"6. **필수**: 서로 존댓말 사용\n\n" f"반드시 위 JSON 형식으로 18회 이상의 대화를 작성하세요:\n{template}" ) return base_prompt else: # 영어 템플릿도 확장 template = """ { "conversation": [ {"speaker": "Alex", "text": ""}, {"speaker": "Jordan", "text": ""}, {"speaker": "Alex", "text": ""}, {"speaker": "Jordan", "text": ""}, {"speaker": "Alex", "text": ""}, {"speaker": "Jordan", "text": ""}, {"speaker": "Alex", "text": ""}, {"speaker": "Jordan", "text": ""}, {"speaker": "Alex", "text": ""}, {"speaker": "Jordan", "text": ""}, {"speaker": "Alex", "text": ""}, {"speaker": "Jordan", "text": ""}, {"speaker": "Alex", "text": ""}, {"speaker": "Jordan", "text": ""}, {"speaker": "Alex", "text": ""}, {"speaker": "Jordan", "text": ""}, {"speaker": "Alex", "text": ""}, {"speaker": "Jordan", "text": ""} ] } """ context_part = "" if search_context: context_part = f"# Latest Information:\n{search_context}\n" base_prompt = ( f"# Content:\n{text}\n\n" f"{context_part}" f"Create a radio talk show conversation with at least 30 lines.\n\n" f"## Requirements:\n" f"1. **Minimum 18 conversation exchanges** (Alex 9+, Jordan 9+)\n" f"2. **Style**: Natural radio talk show conversation\n" f"3. **Roles**:\n" f" - Alex: Host (short questions, reactions, transitions)\n" f" - Jordan: Expert (concise explanations, examples)\n" f"4. **Pattern**:\n" f" - Alex: \"I see\", \"Fascinating\", \"Could you elaborate?\"\n" f" - Jordan: 1-2 sentence explanations\n" f" - Natural speech fillers\n" f"5. **Structure**:\n" f" - Introduction (2-3 exchanges): Topic intro\n" f" - Main content (10-12 exchanges): Core discussion\n" f" - Conclusion (3-4 exchanges): Summary\n\n" f"Create exactly 18+ exchanges in this JSON format:\n{template}" ) return base_prompt class UnifiedAudioConverter: def __init__(self, config: ConversationConfig): self.config = config self.llm_client = None self.legacy_local_model = None self.legacy_tokenizer = None # 새로운 로컬 LLM 관련 self.local_llm = None self.local_llm_model = 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 (now fallback)""" self.llm_client = OpenAI(api_key=api_key, base_url="https://api.together.xyz/v1") @spaces.GPU(duration=120) def initialize_local_mode(self): """Initialize new local mode with Llama CPP""" if not LLAMA_CPP_AVAILABLE: raise RuntimeError("Llama CPP dependencies not available. Please install llama-cpp-python and llama-cpp-agent.") if self.local_llm is None or self.local_llm_model != self.config.local_model_name: try: # 모델 다운로드 model_path = hf_hub_download( repo_id=self.config.local_model_repo, filename=self.config.local_model_name, local_dir="./models" ) model_path_local = os.path.join("./models", self.config.local_model_name) if not os.path.exists(model_path_local): raise RuntimeError(f"Model file not found at {model_path_local}") # Llama 모델 초기화 self.local_llm = Llama( model_path=model_path_local, flash_attn=True, n_gpu_layers=81 if torch.cuda.is_available() else 0, n_batch=1024, n_ctx=16384, ) self.local_llm_model = self.config.local_model_name print(f"Local LLM initialized: {model_path_local}") except Exception as e: print(f"Failed to initialize local LLM: {e}") raise RuntimeError(f"Failed to initialize local LLM: {e}") @spaces.GPU(duration=60) def initialize_legacy_local_mode(self): """Initialize legacy local mode with Hugging Face model (fallback)""" if self.legacy_local_model is None: quantization_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_compute_dtype=torch.float16 ) self.legacy_local_model = AutoModelForCausalLM.from_pretrained( self.config.legacy_local_model_name, quantization_config=quantization_config ) self.legacy_tokenizer = AutoTokenizer.from_pretrained( self.config.legacy_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.") @spaces.GPU(duration=60) 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 extract_text_from_pdf(self, pdf_file) -> str: """Extract text content from PDF file""" try: # Gradio returns file path, not file object if isinstance(pdf_file, str): pdf_path = pdf_file else: # If it's a file object (shouldn't happen with Gradio) with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file: tmp_file.write(pdf_file.read()) pdf_path = tmp_file.name # PDF 로드 및 텍스트 추출 loader = PyPDFLoader(pdf_path) pages = loader.load() # 모든 페이지의 텍스트를 결합 text = "\n".join([page.page_content for page in pages]) # 임시 파일인 경우 삭제 if not isinstance(pdf_file, str) and os.path.exists(pdf_path): os.unlink(pdf_path) return text except Exception as e: raise RuntimeError(f"Failed to extract text from PDF: {e}") def _get_messages_formatter_type(self, model_name): """Get appropriate message formatter for the model""" if "Mistral" in model_name or "BitSix" in model_name: return MessagesFormatterType.CHATML else: return MessagesFormatterType.LLAMA_3 def _build_prompt(self, text: str, language: str = "English", search_context: str = "") -> str: """Build prompt for conversation generation with enhanced radio talk show style""" # 텍스트 길이 제한 max_text_length = 4500 if search_context else 6000 if len(text) > max_text_length: text = text[:max_text_length] + "..." if language == "Korean": # 대화 템플릿을 더 많은 턴으로 확장 template = """ { "conversation": [ {"speaker": "준수", "text": ""}, {"speaker": "민호", "text": ""}, {"speaker": "준수", "text": ""}, {"speaker": "민호", "text": ""}, {"speaker": "준수", "text": ""}, {"speaker": "민호", "text": ""}, {"speaker": "준수", "text": ""}, {"speaker": "민호", "text": ""}, {"speaker": "준수", "text": ""}, {"speaker": "민호", "text": ""}, {"speaker": "준수", "text": ""}, {"speaker": "민호", "text": ""} ] } """ context_part = "" if search_context: context_part = f"# 최신 관련 정보:\n{search_context}\n" base_prompt = ( f"# 원본 콘텐츠:\n{text}\n\n" f"{context_part}" f"위 내용으로 라디오 대담 프로그램 대본을 작성해주세요.\n\n" f"## 핵심 지침:\n" f"1. **대화 스타일**: 실제 라디오 대담처럼 아주 자연스럽고 편안한 구어체 사용\n" f"2. **화자 역할**:\n" f" - 준수: 진행자/호스트 (주로 질문하고 대화를 이끌어감)\n" f" - 민호: 전문가 (질문에 답하고 설명함)\n" f"3. **대화 패턴**:\n" f" - 준수는 주로 짧은 질문이나 리액션 (\"아, 그렇군요\", \"흥미롭네요\", \"그럼 ~는 어떤가요?\")\n" f" - 민호는 1-2문장으로 간결하게 답변\n" f" - 절대 한 사람이 3문장 이상 연속으로 말하지 않음\n" f"4. **자연스러움**:\n" f" - \"음...\", \"아...\", \"네,\" 같은 추임새 사용\n" f" - 때로는 상대방 말에 짧게 반응 (\"맞아요\", \"그렇죠\")\n" f"5. **필수 규칙**: 서로 존댓말 사용, 12-15회 대화 교환\n\n" f"JSON 형식으로만 반환:\n{template}" ) return base_prompt else: # 영어 템플릿도 확장 template = """ { "conversation": [ {"speaker": "Alex", "text": ""}, {"speaker": "Jordan", "text": ""}, {"speaker": "Alex", "text": ""}, {"speaker": "Jordan", "text": ""}, {"speaker": "Alex", "text": ""}, {"speaker": "Jordan", "text": ""}, {"speaker": "Alex", "text": ""}, {"speaker": "Jordan", "text": ""}, {"speaker": "Alex", "text": ""}, {"speaker": "Jordan", "text": ""}, {"speaker": "Alex", "text": ""}, {"speaker": "Jordan", "text": ""} ] } """ context_part = "" if search_context: context_part = f"# Latest Information:\n{search_context}\n" base_prompt = ( f"# Content:\n{text}\n\n" f"{context_part}" f"Create a natural radio talk show conversation.\n\n" f"## Key Guidelines:\n" f"1. **Style**: Natural, conversational English like a real radio show\n" f"2. **Roles**:\n" f" - Alex: Host (asks questions, guides conversation)\n" f" - Jordan: Expert (answers, explains)\n" f"3. **Pattern**:\n" f" - Alex mostly asks short questions or reacts (\"I see\", \"Interesting\", \"What about...?\")\n" f" - Jordan gives brief 1-2 sentence answers\n" f" - Never more than 2-3 sentences per turn\n" f"4. **Natural flow**:\n" f" - Use fillers like \"Well,\" \"You know,\" \"Actually,\"\n" f" - Short reactions (\"Right\", \"Exactly\")\n" f"5. **Length**: 12-15 exchanges total\n\n" f"Return JSON only:\n{template}" ) return base_prompt def _build_messages_for_local(self, text: str, language: str = "English", search_context: str = "") -> List[Dict]: """Build messages for local LLM with enhanced radio talk show style""" if language == "Korean": system_message = ( "당신은 한국 최고의 라디오 대담 프로그램 작가입니다. " "실제 라디오 방송처럼 자연스럽고 생동감 있는 대화를 만들어냅니다.\n\n" "핵심 원칙:\n" "1. 라디오 진행자(준수)는 주로 짧은 질문과 리액션으로 대화를 이끌어갑니다\n" "2. 전문가(민호)는 질문에 간결하고 이해하기 쉽게 답합니다\n" "3. 한 번에 너무 많은 정보를 전달하지 않고, 대화를 통해 점진적으로 풀어갑니다\n" "4. \"음...\", \"아...\", \"네,\" 등 자연스러운 구어체 표현을 사용합니다\n" "5. 청취자가 라디오를 듣는 것처럼 몰입할 수 있도록 생생하게 작성합니다\n" "6. 반드시 서로 존댓말을 사용하며, 정중하면서도 친근한 톤을 유지합니다" ) else: system_message = ( "You are an expert radio talk show scriptwriter who creates engaging, " "natural conversations that sound like real radio broadcasts.\n\n" "Key principles:\n" "1. The host (Alex) mainly asks short questions and gives reactions to guide the conversation\n" "2. The expert (Jordan) answers concisely and clearly\n" "3. Information is revealed gradually through dialogue, not in long monologues\n" "4. Use natural speech patterns with fillers like 'Well,' 'You know,' etc.\n" "5. Make it sound like an actual radio show that listeners would enjoy\n" "6. Keep each turn brief - no more than 2-3 sentences" ) return [ {"role": "system", "content": system_message}, {"role": "user", "content": self._build_prompt(text, language, search_context)} ] @spaces.GPU(duration=120) def extract_conversation_local(self, text: str, language: str = "English", progress=None) -> Dict: """Extract conversation using new local LLM with enhanced search and style""" try: # 검색 컨텍스트 생성 (키워드 기반이 아닌 경우) search_context = "" if BRAVE_KEY and not text.startswith("Keyword-based content:"): try: keywords = extract_keywords_for_search(text, language) if keywords: search_query = keywords[0] if language == "Korean" else f"{keywords[0]} latest news" search_context = format_search_results(search_query) print(f"Search context added for: {search_query}") except Exception as e: print(f"Search failed, continuing without context: {e}") # 먼저 새로운 로컬 LLM 시도 self.initialize_local_mode() chat_template = self._get_messages_formatter_type(self.config.local_model_name) provider = LlamaCppPythonProvider(self.local_llm) # 강화된 라디오 스타일 시스템 메시지 if language == "Korean": system_message = ( "당신은 한국의 인기 라디오 대담 프로그램 전문 작가입니다. " "청취자들이 실제 라디오를 듣는 것처럼 몰입할 수 있는 자연스러운 대화를 만듭니다.\n\n" "작성 규칙:\n" "1. 진행자(준수)는 주로 짧은 질문으로 대화를 이끌어가세요 (\"그렇군요\", \"어떤 점이 특별한가요?\", \"청취자분들이 궁금해하실 것 같은데요\")\n" "2. 전문가(민호)는 1-2문장으로 간결하게 답변하세요\n" "3. 절대 한 사람이 3문장 이상 연속으로 말하지 마세요\n" "4. 구어체와 추임새를 자연스럽게 사용하세요\n" "5. 반드시 서로 존댓말을 사용하세요\n" "6. 12-15회의 대화 교환으로 구성하세요\n" "7. JSON 형식으로만 응답하세요" ) else: system_message = ( "You are a professional radio talk show scriptwriter creating engaging, " "natural conversations that sound like real radio broadcasts.\n\n" "Writing rules:\n" "1. Host (Alex) mainly asks short questions to guide the conversation (\"I see\", \"What makes it special?\", \"Our listeners might wonder...\")\n" "2. Expert (Jordan) answers in 1-2 concise sentences\n" "3. Never have one person speak more than 2-3 sentences at once\n" "4. Use natural speech patterns and fillers\n" "5. Create 12-15 conversation exchanges\n" "6. Respond only in JSON format" ) agent = LlamaCppAgent( provider, system_prompt=system_message, predefined_messages_formatter_type=chat_template, debug_output=False ) settings = provider.get_provider_default_settings() settings.temperature = 0.85 # 약간 높여서 더 자연스러운 대화 생성 settings.top_k = 40 settings.top_p = 0.95 settings.max_tokens = self.config.max_tokens # 증가된 토큰 수 사용 settings.repeat_penalty = 1.1 settings.stream = False messages = BasicChatHistory() prompt = self._build_prompt(text, language, search_context) response = agent.get_chat_response( prompt, llm_sampling_settings=settings, chat_history=messages, returns_streaming_generator=False, print_output=False ) # JSON 파싱 pattern = r"\{(?:[^{}]|(?:\{[^{}]*\}))*\}" json_match = re.search(pattern, response) if json_match: conversation_data = json.loads(json_match.group()) # 대화 길이 확인 및 조정 if len(conversation_data["conversation"]) < self.config.min_conversation_turns: print(f"Conversation too short ({len(conversation_data['conversation'])} turns), regenerating...") # 재시도 로직 추가 가능 return conversation_data else: raise ValueError("No valid JSON found in local LLM response") except Exception as e: print(f"Local LLM failed: {e}, falling back to legacy local method") return self.extract_conversation_legacy_local(text, language, progress, search_context) @spaces.GPU(duration=120) def extract_conversation_legacy_local(self, text: str, language: str = "English", progress=None, search_context: str = "") -> Dict: """Extract conversation using legacy local model with enhanced style""" try: self.initialize_legacy_local_mode() # 강화된 라디오 스타일 시스템 메시지 if language == "Korean": system_message = ( "당신은 라디오 대담 프로그램 작가입니다. " "진행자(준수)는 짧은 질문으로, 전문가(민호)는 간결한 답변으로 " "자연스러운 대화를 만드세요. 서로 존댓말을 사용하고, " "한 번에 2-3문장 이내로 말하세요. 12-15회 대화 교환으로 구성하세요." ) else: system_message = ( "You are a radio talk show scriptwriter. " "Create natural dialogue where the host (Alex) asks short questions " "and the expert (Jordan) gives brief answers. " "Keep each turn to 2-3 sentences max. Create 12-15 exchanges." ) chat = [ {"role": "system", "content": system_message}, {"role": "user", "content": self._build_prompt(text, language, search_context)} ] terminators = [ self.legacy_tokenizer.eos_token_id, self.legacy_tokenizer.convert_tokens_to_ids("<|eot_id|>") ] messages = self.legacy_tokenizer.apply_chat_template( chat, tokenize=False, add_generation_prompt=True ) model_inputs = self.legacy_tokenizer([messages], return_tensors="pt").to(self.device) streamer = TextIteratorStreamer( self.legacy_tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True ) generate_kwargs = dict( model_inputs, streamer=streamer, max_new_tokens=self.config.max_new_tokens, # 증가된 토큰 수 사용 do_sample=True, temperature=0.85, eos_token_id=terminators, ) t = Thread(target=self.legacy_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: raise ValueError("No valid JSON found in legacy local response") except Exception as e: print(f"Legacy local model also failed: {e}") # Return enhanced default template if language == "Korean": return self._get_default_korean_conversation() else: return self._get_default_english_conversation() def _get_default_korean_conversation(self) -> Dict: """더 긴 기본 한국어 대화 템플릿""" return { "conversation": [ {"speaker": "준수", "text": "안녕하세요, 여러분! 오늘도 저희 팟캐스트를 찾아주셔서 정말 감사합니다."}, {"speaker": "민호", "text": "네, 안녕하세요! 오늘 정말 흥미로운 주제를 준비했습니다."}, {"speaker": "준수", "text": "아, 그래요? 어떤 내용인지 정말 궁금한데요?"}, {"speaker": "민호", "text": "오늘은 최근 많은 분들이 관심을 가지고 계신 주제에 대해 이야기해볼까 해요."}, {"speaker": "준수", "text": "음, 요즘 정말 화제가 되고 있죠. 구체적으로 어떤 측면을 다룰 예정이신가요?"}, {"speaker": "민호", "text": "네, 먼저 기본적인 개념부터 차근차근 설명드리고, 실생활에 어떻게 적용할 수 있는지 알아볼게요."}, {"speaker": "준수", "text": "좋아요! 청취자분들도 이해하기 쉽게 설명해주실 거죠?"}, {"speaker": "민호", "text": "물론이죠. 최대한 쉽고 재미있게 풀어서 설명드릴게요."}, {"speaker": "준수", "text": "그럼 본격적으로 시작해볼까요?"}, {"speaker": "민호", "text": "네, 좋습니다. 우선 이 주제가 왜 중요한지부터 말씀드릴게요."}, {"speaker": "준수", "text": "아, 맞아요. 그 부분이 정말 중요하죠."}, {"speaker": "민호", "text": "최근 연구 결과를 보면 정말 놀라운 발견들이 많았어요."} ] } def _get_default_english_conversation(self) -> Dict: """Enhanced default English conversation template""" return { "conversation": [ {"speaker": "Alex", "text": "Welcome everyone to our podcast! We have a fascinating topic today."}, {"speaker": "Jordan", "text": "Thanks, Alex. I'm excited to dive into this subject with our listeners."}, {"speaker": "Alex", "text": "So, what makes this topic particularly relevant right now?"}, {"speaker": "Jordan", "text": "Well, there have been some significant developments recently that everyone should know about."}, {"speaker": "Alex", "text": "Interesting! Can you break it down for us?"}, {"speaker": "Jordan", "text": "Absolutely. Let me start with the basics and build from there."}, {"speaker": "Alex", "text": "That sounds perfect. Our listeners will appreciate that approach."}, {"speaker": "Jordan", "text": "So, first, let's understand what we're really talking about here."}, {"speaker": "Alex", "text": "Right, the fundamentals are crucial."}, {"speaker": "Jordan", "text": "Exactly. And once we grasp that, the rest becomes much clearer."}, {"speaker": "Alex", "text": "I'm already learning something new! What's next?"}, {"speaker": "Jordan", "text": "Now, here's where it gets really interesting..."} ] } def extract_conversation_api(self, text: str, language: str = "English") -> Dict: """Extract conversation using API with enhanced radio style""" if not self.llm_client: raise RuntimeError("API mode not initialized") try: # 검색 컨텍스트 생성 search_context = "" if BRAVE_KEY and not text.startswith("Keyword-based content:"): try: keywords = extract_keywords_for_search(text, language) if keywords: search_query = keywords[0] if language == "Korean" else f"{keywords[0]} latest news" search_context = format_search_results(search_query) print(f"Search context added for: {search_query}") except Exception as e: print(f"Search failed, continuing without context: {e}") # 강화된 라디오 스타일 프롬프트 if language == "Korean": system_message = ( "당신은 한국의 인기 라디오 대담 프로그램 작가입니다. " "실제 라디오 방송처럼 자연스럽고 편안한 대화를 만드세요.\n" "준수(진행자)는 주로 짧은 질문과 리액션으로 대화를 이끌고, " "민호(전문가)는 1-2문장으로 간결하게 답변합니다. " "구어체와 추임새를 사용하고, 반드시 서로 존댓말을 사용하세요. " "12-15회의 대화 교환으로 구성하세요." ) else: system_message = ( "You are a professional radio talk show scriptwriter. " "Create natural, engaging dialogue like a real radio broadcast. " "Alex (host) mainly asks short questions and gives reactions, " "while Jordan (expert) answers in 1-2 concise sentences. " "Use conversational language with natural fillers. " "Create 12-15 conversation exchanges." ) chat_completion = self.llm_client.chat.completions.create( messages=[ {"role": "system", "content": system_message}, {"role": "user", "content": self._build_prompt(text, language, search_context)} ], model=self.config.api_model_name, temperature=0.85, ) 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 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-HyunsuNeural", # 남성 음성 1 (차분하고 신뢰감 있는) "ko-KR-InJoonNeural" # 남성 음성 2 (활기차고 친근한) ] else: voices = [ "en-US-AndrewMultilingualNeural", # 남성 음성 1 "en-US-BrianMultilingualNeural" # 남성 음성 2 ] 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 @spaces.GPU(duration=60) 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": "male"}, {"prompt_text": "안녕하세요, 저는 오늘 이 주제에 대해 설명드릴 민호입니다. 쉽고 재미있게 설명드릴게요.", "gender": "male"} ] else: voice_configs = [ {"prompt_text": "Hello everyone, I'm Alex, your host for today's podcast. Let's explore this fascinating topic together.", "gender": "male"}, {"prompt_text": "Hi, I'm Jordan. I'm excited to share my insights on this subject with you all today.", "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}") @spaces.GPU(duration=60) 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_input, input_type: str = "URL", mode: str = "Local", tts_engine: str = "Edge-TTS", language: str = "English"): """Main synthesis function - handles URL, PDF, and Keyword inputs""" try: # Extract text based on input type if input_type == "URL": if not article_input or not isinstance(article_input, str): return "Please provide a valid URL.", None text = converter.fetch_text(article_input) elif input_type == "PDF": if not article_input: return "Please upload a PDF file.", None text = converter.extract_text_from_pdf(article_input) else: # Keyword if not article_input or not isinstance(article_input, str): return "Please provide a keyword or topic.", None # 키워드로 검색하여 콘텐츠 생성 text = search_and_compile_content(article_input, language) text = f"Keyword-based content:\n{text}" # 마커 추가 # 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 == "Local": # 로컬 모드가 기본 (새로운 Local LLM 사용) try: conversation_json = converter.extract_conversation_local(text, language) except Exception as e: print(f"Local mode failed: {e}, trying API fallback") # API 폴백 api_key = os.environ.get("TOGETHER_API_KEY") if api_key: converter.initialize_api_mode(api_key) conversation_json = converter.extract_conversation_api(text, language) else: raise RuntimeError("Local mode failed and no API key available for fallback") else: # API mode (now secondary) api_key = os.environ.get("TOGETHER_API_KEY") if not api_key: print("API key not found, falling back to local mode") conversation_json = converter.extract_conversation_local(text, language) else: try: converter.initialize_api_mode(api_key) conversation_json = converter.extract_conversation_api(text, language) except Exception as e: print(f"API mode failed: {e}, falling back to 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": tts_engine = "Edge-TTS" # 자동으로 Edge-TTS로 변경 # 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_input, input_type: str = "URL", mode: str = "Local", tts_engine: str = "Edge-TTS", language: str = "English"): """Synchronous wrapper for async synthesis""" return asyncio.run(synthesize(article_input, input_type, 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 ) def toggle_input_visibility(input_type): """Toggle visibility of URL input, file upload, and keyword input based on input type""" if input_type == "URL": return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False) elif input_type == "PDF": return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False) else: # Keyword return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True) # 모델 초기화 (앱 시작 시) if LLAMA_CPP_AVAILABLE: try: model_path = hf_hub_download( repo_id=converter.config.local_model_repo, filename=converter.config.local_model_name, local_dir="./models" ) print(f"Model downloaded to: {model_path}") except Exception as e: print(f"Failed to download model at startup: {e}") # Gradio Interface with gr.Blocks(theme='soft', title="AI Podcast Generator") as demo: gr.Markdown("# 🎙️ AI Podcast Generator") gr.Markdown("Convert any article, blog, PDF document, or topic into an engaging podcast conversation!") # 상단에 로컬 LLM 상태 표시 with gr.Row(): gr.Markdown(f""" ### 🤖 Enhanced Configuration: - **Primary**: Local LLM ({converter.config.local_model_name}) - Runs on your device - **Fallback**: API LLM ({converter.config.api_model_name}) - Used when local fails - **Status**: {"✅ Llama CPP Available" if LLAMA_CPP_AVAILABLE else "❌ Llama CPP Not Available - Install llama-cpp-python"} - **Conversation Length**: {converter.config.min_conversation_turns}-{converter.config.max_conversation_turns} exchanges (1.5x longer) - **Search**: {"✅ Brave Search Enabled" if BRAVE_KEY else "❌ Brave Search Not Available - Set BSEARCH_API"} - **New**: 🎯 Keyword input for topic-based podcast generation """) with gr.Row(): with gr.Column(scale=3): # Input type selector - 키워드 옵션 추가 input_type_selector = gr.Radio( choices=["URL", "PDF", "Keyword"], value="URL", label="Input Type", info="Choose between URL, PDF file upload, or keyword/topic" ) # URL input url_input = gr.Textbox( label="Article URL", placeholder="Enter the article URL here...", value="", visible=True ) # PDF upload pdf_input = gr.File( label="Upload PDF", file_types=[".pdf"], visible=False ) # Keyword input (새로 추가) keyword_input = gr.Textbox( label="Topic/Keyword", placeholder="Enter a topic or keyword (e.g., 'AI trends', '인공지능 최신 동향')", value="", visible=False, info="The system will search for latest information about this topic" ) 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=["Local", "API"], value="Local", label="Processing Mode", info="Local: Runs on device (Primary) | API: Cloud-based (Fallback)" ) # 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(""" **📻 Radio Talk Show Style:** - Natural, conversational dialogue - Host asks short questions - Expert gives brief, clear answers - 12-15 conversation exchanges **🔍 Keyword Feature:** - Enter any topic to generate a podcast - Automatically searches latest information - Creates engaging discussion from search results **🇰🇷 한국어 지원:** - 자연스러운 라디오 대담 스타일 - 진행자(준수)가 짧은 질문으로 대화 유도 - 전문가(민호)가 간결하게 답변 - 최신 정보 자동 검색 및 반영 """) 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=30, # 더 긴 대화를 위해 증가 max_lines=60, interactive=True, placeholder="Generated conversation will appear here. You can edit it before generating audio.\n생성된 대화가 여기에 표시됩니다. 오디오 생성 전에 편집할 수 있습니다.\n\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 ) gr.Examples( examples=[ ["https://huggingface.co/blog/openfree/cycle-navigator", "URL", "Local", "Edge-TTS", "English"], ["", "Keyword", "Local", "Edge-TTS", "English"], # Keyword example ["https://huggingface.co/papers/2505.14810", "URL", "Local", "Edge-TTS", "Korean"], ["", "Keyword", "Local", "Edge-TTS", "Korean"], # Korean keyword example ], inputs=[url_input, input_type_selector, mode_selector, tts_selector, language_selector], outputs=[conversation_output, status_output], fn=synthesize_sync, cache_examples=False, ) # Input type change handler - 수정됨 input_type_selector.change( fn=toggle_input_visibility, inputs=[input_type_selector], outputs=[url_input, pdf_input, keyword_input] ) # 언어 변경 시 TTS 엔진 옵션 업데이트 language_selector.change( fn=update_tts_engine_for_korean, inputs=[language_selector], outputs=[tts_selector] ) # 이벤트 연결 - 수정된 부분 def get_article_input(input_type, url_input, pdf_input, keyword_input): """Get the appropriate input based on input type""" if input_type == "URL": return url_input elif input_type == "PDF": return pdf_input else: # Keyword return keyword_input convert_btn.click( fn=lambda input_type, url_input, pdf_input, keyword_input, mode, tts, lang: synthesize_sync( get_article_input(input_type, url_input, pdf_input, keyword_input), input_type, mode, tts, lang ), inputs=[input_type_selector, url_input, pdf_input, keyword_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 )