Spaces:
Sleeping
Sleeping
Download app.py from benjamin5607/error404-api: direct link, hf CLI and curl.
- Browser
- Download file 5.76 kB
-
https://huggingface.co/spaces/benjamin5607/error404-api/resolve/b22fa4ed0e802b12d5aed9a14aa76b7c12425b41/app.py
- Command line
-
hf download hf://spaces/benjamin5607/error404-api@b22fa4ed0e802b12d5aed9a14aa76b7c12425b41/app.py
-
curl -L -o app.py https://huggingface.co/spaces/benjamin5607/error404-api/resolve/b22fa4ed0e802b12d5aed9a14aa76b7c12425b41/app.py
5.76 kB
| import gradio as gr | |
| import httpx | |
| import edge_tts | |
| import os | |
| import re | |
| import uuid | |
| import torch | |
| import numpy as np | |
| import scipy.io.wavfile | |
| import asyncio | |
| from transformers import pipeline | |
| # νκ²½ λ³μ λ‘λ λ° κ²μ¦ | |
| GENAI_KEY = os.getenv("GEMINI_KEY") | |
| # μμ μμ± λͺ¨λΈ λ‘λ | |
| 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": "Guitarist Chloe. Cool rockstar vibe." }, | |
| "Beatrice (Brazil)": { "voice": "pt-BR-FranciscaNeural", "prompt": "Drummer Beatrice. Rhythm focus." }, | |
| "Naomi (Japan)": { "voice": "ja-JP-NanamiNeural", "prompt": "Naomi. Harmony focus." }, | |
| "Elena (Spain)": { "voice": "es-ES-ElviraNeural", "prompt": "Elena. Groove focus." }, | |
| "Amira (Egypt)": { "voice": "ar-EG-SalmaNeural", "prompt": "Amira. Atmosphere focus." }, | |
| "Liwei (China)": { "voice": "zh-CN-XiaoxiaoNeural", "prompt": "Liwei. Sound design focus." }, | |
| "Sophie (France)": { "voice": "fr-FR-DeniseNeural", "prompt": "Sophie. Melody focus." } | |
| } | |
| async def band_consulting(user_input, member_name, lang_code): | |
| # 리νμ€νΈλ³ κ³ μ ID μμ± (νμΌ μΆ©λ λ°©μ§) | |
| req_id = str(uuid.uuid4())[:8] | |
| voice_path = f"/tmp/v_{req_id}.mp3" | |
| music_path = f"/tmp/m_{req_id}.wav" | |
| try: | |
| if not GENAI_KEY: | |
| raise ValueError("API Key is missing in Environment Variables") | |
| 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_name}'μ λλ€. | |
| 1. λ°λμ {target_lang}λ‘λ§ λ΅λ³νμΈμ. | |
| 2. μμ± λ΅λ³μ 5μ€ μ΄λ΄ μμ½, μμΈ μ€λͺ /μ 보λ [TAB]μ λ£μΌμΈμ. | |
| 3. λ§μ§λ§μ [MUSIC: μμ΄ ν둬ννΈ]λ₯Ό ν¬ν¨νμΈμ. | |
| """ | |
| # λΉλκΈ° HTTP ν΄λΌμ΄μΈνΈ μ¬μ© (Blocking λ°©μ§) | |
| 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}"}]}]} | |
| async with httpx.AsyncClient() as client: | |
| response = await client.post(url, json=payload, timeout=25.0) | |
| res_data = response.json() | |
| if 'candidates' not in res_data: | |
| ai_text_raw = "μκ°μ΄ μ μ μ°¨λ¨λμ΄. λ€μ λ¬Όμ΄λ΄μ€λ? [TAB] API μλ΅ μ€λ₯ [MUSIC: rock guitar riff]" | |
| else: | |
| ai_text_raw = res_data['candidates'][0]['content']['parts'][0]['text'] | |
| # μ κ·ννμ νμ± (λμλ¬Έμ 무μ λ° μ μ°ν λ§€μΉ) | |
| tab_match = re.search(r'\[TAB\](.*?)(\[|$)', ai_text_raw, re.DOTALL | re.IGNORECASE) | |
| 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 | re.IGNORECASE) | |
| clean_text = re.sub(r'\[MUSIC:.*?\]', '', clean_text, flags=re.IGNORECASE).strip() | |
| # TTS μμ± μμ± | |
| tts_text = "\n".join(clean_text.split('\n')[:5]) | |
| communicate = edge_tts.Communicate(re.sub(r'[\*\#\-\_\~\|]', '', tts_text), member_data['voice']) | |
| await communicate.save(voice_path) | |
| # μμ μμ± (Blocking λ°©μ§ μν΄ λ³λ μ€λ λ κ³ λ € κ°λ₯νλ Gradio Queueκ° μμΌλ―λ‘ μ§μ μ€ν) | |
| if music_synthesiser: | |
| music_p = music_match.group(1).strip() if music_match else "rock music" | |
| # κ°μ΄λλΌμΈ μλ° λ¨μ΄ μ°ν | |
| if any(x in music_p.lower() for x in ['laugh', 'vocal', 'voice', 'human']): | |
| music_p = "energetic rock electric guitar solo" | |
| # [MUSICGEN μ€ν] - 512 ν ν° (μ½ 12μ΄) | |
| music_output = music_synthesiser(music_p, forward_params={"max_new_tokens": 512}) | |
| # μ€λμ€ λ°μ΄ν° μ²λ¦¬ (Float32 -> Int16) | |
| audio_tensor = music_output["audio"] | |
| if torch.is_tensor(audio_tensor): | |
| audio_data = audio_tensor.cpu().numpy() | |
| else: | |
| audio_data = np.array(audio_tensor) | |
| audio_data = np.squeeze(audio_data) # μ°¨μ μμΆ | |
| audio_int16 = (audio_data * 32767).astype(np.int16) # μ κ·ν | |
| scipy.io.wavfile.write(music_path, music_output["sampling_rate"], audio_int16) | |
| else: | |
| music_path = None | |
| return tts_text, voice_path, music_path, tab_display | |
| except Exception as e: | |
| print(f"Critical Error: {e}") | |
| return f"System Overload: λ€μ μλν΄μ£ΌμΈμ. ({str(e)})", None, None, "Error" | |
| # Gradio Interface | |
| with gr.Blocks() as demo: | |
| # λΉλκΈ° μ²λ¦¬λ₯Ό μν λ΄λΆ ν΅λ‘ | |
| i1 = gr.Textbox(visible=False); i2 = gr.Textbox(visible=False); i3 = gr.Textbox(visible=False) | |
| o1 = gr.Textbox(visible=False); o2 = gr.Audio(visible=False); o3 = gr.Audio(visible=False); o4 = gr.Textbox(visible=False) | |
| btn = gr.Button("GO", visible=False) # JSμμ νΈμΆμ© | |
| btn.click(band_consulting, [i1, i2, i3], [o1, o2, o3, o4], api_name="predict") | |
| # ν νμ±ν λ° μ€ν | |
| demo.queue().launch(ssr_mode=False) |