error404-api / app.py
benjamin5607's picture
Update app.py
d400633 verified
Raw History Blame
5.38 kB
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()