import gradio as gr import requests import edge_tts import os import re import scipy.io.wavfile from transformers import pipeline GENAI_KEY = os.getenv("GEMINI_KEY") try: music_synthesiser = pipeline("text-to-audio", "facebook/musicgen-small") except: music_synthesiser = None MEMBERS = { "서윤 (Korea)": "ko-KR-SunHiNeural", "Chloe (USA)": "en-US-AriaNeural", "Naomi (Japan)": "ja-JP-NanamiNeural", "Beatrice (Brazil)": "pt-BR-FranciscaNeural", "Elena (Spain)": "es-ES-ElviraNeural", "Amira (Egypt)": "ar-EG-SalmaNeural", "Liwei (China)": "zh-CN-XiaoxiaoNeural", "Sophie (France)": "fr-FR-DeniseNeural" } async def band_consulting(user_input, member_name, lang_code): try: lang_map = {"ko":"Korean","en":"English","ja":"Japanese","pt":"Portuguese","es":"Spanish","ar":"Arabic","zh":"Chinese","fr":"French"} target_lang = lang_map.get(lang_code, "Korean") system_instruction = f"당신은 {member_name}입니다. 반드시 {target_lang}로만 답변하세요. 음성은 5줄 이내 요약, 상세 설명은 [TAB]에, 음악 프롬프트는 [MUSIC: 프롬프트]에 넣으세요." url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={GENAI_KEY}" # ★ 차단 방지: 모든 안전 카테고리 BLOCK_NONE 설정 payload = { "contents": [{"parts": [{"text": f"{system_instruction}\n질문: {user_input}"}]}], "safetySettings": [ {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"}, {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}, {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"}, {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"} ], "generationConfig": { "temperature": 0.7, "maxOutputTokens": 1024 } } response = requests.post(url, json=payload) res_data = response.json() # 'candidates'가 없을 경우를 위한 예외 처리 강화 if 'candidates' not in res_data or not res_data['candidates']: # 필터링될 경우를 대비한 기본 답변 세트 fallback_text = f"이봐 리더, 지금 내 영감이 잠시 차단됐어. 다시 물어봐줄래? [TAB] 다시 시도해주세요. [MUSIC: powerful rock riff]" ai_text_raw = fallback_text else: ai_text_raw = res_data['candidates'][0]['content']['parts'][0]['text'] tab_match = re.search(r'\[TAB\](.*?)(\[|$)', ai_text_raw, re.DOTALL) music_match = re.search(r'\[MUSIC:(.*?)\]', ai_text_raw, re.IGNORECASE) tab_display = tab_match.group(1).strip() if tab_match else "상세 악보 없음" clean_text = re.sub(r'\[TAB\].*?(\[|$)', '', ai_text_raw, flags=re.DOTALL) clean_text = re.sub(r'\[MUSIC:.*?\]', '', clean_text).strip() # 5줄 요약 clean_text = "\n".join(clean_text.split("\n")[:5]) voice_path = f"/tmp/v_{member_name.split()[0]}.mp3" await edge_tts.Communicate(clean_text, MEMBERS.get(member_name, "ko-KR-SunHiNeural")).save(voice_path) music_path = None if music_match and music_synthesiser: p = music_match.group(1).strip() music_output = music_synthesiser(p, forward_params={"max_new_tokens": 512}) music_path = f"/tmp/m_{member_name.split()[0]}.wav" scipy.io.wavfile.write(music_path, music_output["sampling_rate"], music_output["audio"][0].T) return clean_text, voice_path, music_path, tab_display except Exception as e: return f"System Reset Needed: {str(e)}", None, None, "Error" with gr.Blocks() as demo: i1 = gr.Textbox(); i2 = gr.Textbox(); i3 = gr.Textbox() o1 = gr.Textbox(); o2 = gr.Audio(); o3 = gr.Audio(); o4 = gr.Textbox() btn = gr.Button("GO"); btn.click(band_consulting, [i1, i2, i3], [o1, o2, o3, o4], api_name="predict") demo.launch()