import gradio as gr import requests import edge_tts import os import re import scipy.io.wavfile import numpy as np from transformers import pipeline GENAI_KEY = os.getenv("GEMINI_KEY") # 음악 생성 모델 로드 (Hugging Face 환경 최적화) try: music_synthesiser = pipeline("text-to-audio", "facebook/musicgen-small") except Exception as e: print(f"Music Model Load Error: {e}") music_synthesiser = None # 8인 멤버 보이스 데이터 및 프롬프트 (절대 유지) MEMBERS = { "서윤 (Korea)": { "voice": "ko-KR-SunHiNeural", "prompt": "당신은 보컬 '서윤'입니다. 시니컬하지만 음악에 진심입니다." }, "Chloe (USA)": { "voice": "en-US-AriaNeural", "prompt": "You are 'Chloe', the lead guitarist. Cool rockstar vibe." }, "Beatrice (Brazil)": { "voice": "pt-BR-FranciscaNeural", "prompt": "You are 'Beatrice', the drummer. Focus on rhythm." }, "Naomi (Japan)": { "voice": "ja-JP-NanamiNeural", "prompt": "You are 'Naomi'. Focus on harmony." }, "Elena (Spain)": { "voice": "es-ES-ElviraNeural", "prompt": "You are 'Elena'. Focus on groove." }, "Amira (Egypt)": { "voice": "ar-EG-SalmaNeural", "prompt": "You are 'Amira'. Focus on atmosphere." }, "Liwei (China)": { "voice": "zh-CN-XiaoxiaoNeural", "prompt": "You are 'Liwei'. Focus on sound design." }, "Sophie (France)": { "voice": "fr-FR-DeniseNeural", "prompt": "You are 'Sophie'. Focus on melody." } } async def band_consulting(user_input, member_name, lang_code): try: member_data = MEMBERS.get(member_name, MEMBERS["서윤 (Korea)"]) 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_data['prompt']} [LANGUAGE RULE] Respond 100% in {target_lang}. No other languages. [STYLE RULE] 1. Verbal response MUST be under 5 lines (Concise). 2. Put ALL detailed musical explanations, chord progressions, and tips in [TAB]. 3. End with [MUSIC: English prompt] for a high-quality rock sample. """ url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={GENAI_KEY}" 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"} ] } response = requests.post(url, json=payload) res_data = response.json() if 'candidates' not in res_data: clean_text = "영감이 잠시 차단됐어. 다시 물어봐줘!" tab_display = "필터링으로 인해 내용을 표시할 수 없습니다." music_p = "heavy metal rock riff" 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 "No Score" # TTS에서 악보 읽기 방지 clean_text = re.sub(r'\[TAB\].*?(\[|$)', '', ai_text_raw, flags=re.DOTALL) clean_text = re.sub(r'\[MUSIC:.*?\]', '', clean_text).strip() clean_text = "\n".join(clean_text.split('\n')[:5]) music_p = music_match.group(1).strip() if music_match else "rock guitar riff" # 음성 생성 tts_input = re.sub(r'[\*\#\-\_\~\|]', '', clean_text) voice_path = f"/tmp/v_{member_name.split()[0]}.mp3" await edge_tts.Communicate(tts_input, member_data['voice']).save(voice_path) # 음악 생성 (에러 방지 강화) music_path = None if music_synthesiser: try: # 필터링 우회 safe_p = music_p.lower() if any(x in safe_p for x in ['laugh', 'vocal', 'voice', 'human']): safe_p = "distorted electric guitar, rock style" music_output = music_synthesiser(safe_p, forward_params={"max_new_tokens": 512}) if music_output and "audio" in music_output: 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) except: music_path = None return clean_text, voice_path, music_path, tab_display except Exception as e: return f"System Overload: {str(e)}", None, None, "Error" with gr.Blocks() as demo: with gr.Row(): 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()