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