benjamin5607 commited on
Commit
d400633
Β·
verified Β·
1 Parent(s): a1bdc6d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -34
app.py CHANGED
@@ -4,40 +4,42 @@ import edge_tts
4
  import os
5
  import re
6
  import scipy.io.wavfile
 
7
  from transformers import pipeline
8
 
9
  GENAI_KEY = os.getenv("GEMINI_KEY")
10
 
11
- # μŒμ•… λͺ¨λΈ λ‘œλ“œ
12
  try:
13
  music_synthesiser = pipeline("text-to-audio", "facebook/musicgen-small")
14
- except:
 
15
  music_synthesiser = None
16
 
17
- # 8인 멀버 보이슀 데이터 (μ ˆλŒ€ μ‚­μ œ μ•ˆ 함)
18
  MEMBERS = {
19
- "μ„œμœ€ (Korea)": "ko-KR-SunHiNeural",
20
- "Chloe (USA)": "en-US-AriaNeural",
21
- "Beatrice (Brazil)": "pt-BR-FranciscaNeural",
22
- "Naomi (Japan)": "ja-JP-NanamiNeural",
23
- "Elena (Spain)": "es-ES-ElviraNeural",
24
- "Amira (Egypt)": "ar-EG-SalmaNeural",
25
- "Liwei (China)": "zh-CN-XiaoxiaoNeural",
26
- "Sophie (France)": "fr-FR-DeniseNeural"
27
  }
28
 
29
  async def band_consulting(user_input, member_name, lang_code):
30
  try:
31
- # β˜… μ–Έμ–΄ μ„€μ • μ™„λ²½ κ³ μ •
32
  lang_map = {"ko":"Korean","en":"English","ja":"Japanese","pt":"Portuguese","es":"Spanish","ar":"Arabic","zh":"Chinese","fr":"French"}
33
  target_lang = lang_map.get(lang_code, "Korean")
34
 
35
  system_instruction = f"""
36
- 당신은 λ°΄λ“œ 멀버 '{member_name}'μž…λ‹ˆλ‹€.
37
- 1. λ°˜λ“œμ‹œ '{target_lang}'둜만 λ‹΅λ³€ν•˜μ„Έμš”. λ‹€λ₯Έ μ–Έμ–΄λŠ” μ„žμ§€ λ§ˆμ„Έμš”.
38
- 2. μŒμ„± λ‹΅λ³€(TTS)용 본문은 5쀄 μ΄λ‚΄λ‘œ ν•΅μ‹¬λ§Œ μš”μ•½ν•˜μ„Έμš”.
39
- 3. λͺ¨λ“  상세 μ„€λͺ…, μ‘°μ–Έ, ν…μŠ€νŠΈ μ•…λ³΄λŠ” λ°˜λ“œμ‹œ [TAB] μ„Ήμ…˜μ— λ„£μœΌμ„Έμš”.
40
- 4. μŒμ•… μƒμ„±μš© μ˜μ–΄ ν”„λ‘¬ν”„νŠΈλŠ” λ§ˆμ§€λ§‰μ— [MUSIC: ν”„λ‘¬ν”„νŠΈ] ν˜•μ‹μœΌλ‘œ ν¬ν•¨ν•˜μ„Έμš”.
41
  """
42
 
43
  url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={GENAI_KEY}"
@@ -54,37 +56,35 @@ async def band_consulting(user_input, member_name, lang_code):
54
  response = requests.post(url, json=payload)
55
  res_data = response.json()
56
 
57
- # API 차단 μ‹œ Fallback
58
- if 'candidates' not in res_data or not res_data['candidates']:
59
- clean_text = "이봐 리더, λ‚΄ 영감이 μž μ‹œ 필터링됐어. 쑰금 더 λ½μŠ€νƒ€λ‹€μš΄ 질문으둜 λ‹€μ‹œ ν•΄μ€˜!"
60
- tab_display = "데이터가 μ°¨λ‹¨λ˜μ—ˆμŠ΅λ‹ˆλ‹€."
61
  music_p = "heavy metal rock riff"
62
  else:
63
  ai_text_raw = res_data['candidates'][0]['content']['parts'][0]['text']
64
  tab_match = re.search(r'\[TAB\](.*?)(\[|$)', ai_text_raw, re.DOTALL)
65
  music_match = re.search(r'\[MUSIC:(.*?)\]', ai_text_raw, re.IGNORECASE)
66
- tab_display = tab_match.group(1).strip() if tab_match else "No Score Available"
 
 
67
  clean_text = re.sub(r'\[TAB\].*?(\[|$)', '', ai_text_raw, flags=re.DOTALL)
68
  clean_text = re.sub(r'\[MUSIC:.*?\]', '', clean_text).strip()
 
69
  music_p = music_match.group(1).strip() if music_match else "rock guitar riff"
70
 
71
- # β˜… 5쀄 μš”μ•½ κ°•μ œ
72
- tts_lines = clean_text.split('\n')
73
- tts_final = "\n".join(tts_lines[:5])
74
-
75
- # μŒμ„± 생성 (악보 기호 μ™„μ „ 제거)
76
- tts_input = re.sub(r'[\*\#\-\_\~\|]', '', tts_final)
77
  voice_path = f"/tmp/v_{member_name.split()[0]}.mp3"
78
- await edge_tts.Communicate(tts_input, MEMBERS.get(member_name, "ko-KR-SunHiNeural")).save(voice_path)
79
 
80
- # μŒμ•… 생성 (System Overload λ°©μ§€)
81
  music_path = None
82
  if music_synthesiser:
83
  try:
84
  # 필터링 우회
85
  safe_p = music_p.lower()
86
  if any(x in safe_p for x in ['laugh', 'vocal', 'voice', 'human']):
87
- safe_p = "distorted electric guitar riff, power rock"
88
 
89
  music_output = music_synthesiser(safe_p, forward_params={"max_new_tokens": 512})
90
  if music_output and "audio" in music_output:
@@ -93,12 +93,15 @@ async def band_consulting(user_input, member_name, lang_code):
93
  except:
94
  music_path = None
95
 
96
- return tts_final, voice_path, music_path, tab_display
 
97
  except Exception as e:
98
- return f"System Error: {str(e)}", None, None, "Error"
99
 
100
  with gr.Blocks() as demo:
101
- i1 = gr.Textbox(); i2 = gr.Textbox(); i3 = gr.Textbox()
 
102
  o1 = gr.Textbox(); o2 = gr.Audio(); o3 = gr.Audio(); o4 = gr.Textbox()
103
  btn = gr.Button("GO"); btn.click(band_consulting, [i1, i2, i3], [o1, o2, o3, o4], api_name="predict")
 
104
  demo.launch()
 
4
  import os
5
  import re
6
  import scipy.io.wavfile
7
+ import numpy as np
8
  from transformers import pipeline
9
 
10
  GENAI_KEY = os.getenv("GEMINI_KEY")
11
 
12
+ # μŒμ•… 생성 λͺ¨λΈ λ‘œλ“œ (Hugging Face ν™˜κ²½ μ΅œμ ν™”)
13
  try:
14
  music_synthesiser = pipeline("text-to-audio", "facebook/musicgen-small")
15
+ except Exception as e:
16
+ print(f"Music Model Load Error: {e}")
17
  music_synthesiser = None
18
 
19
+ # 8인 멀버 보이슀 데이터 및 ν”„λ‘¬ν”„νŠΈ (μ ˆλŒ€ μœ μ§€)
20
  MEMBERS = {
21
+ "μ„œμœ€ (Korea)": { "voice": "ko-KR-SunHiNeural", "prompt": "당신은 보컬 'μ„œμœ€'μž…λ‹ˆλ‹€. μ‹œλ‹ˆμ»¬ν•˜μ§€λ§Œ μŒμ•…μ— μ§„μ‹¬μž…λ‹ˆλ‹€." },
22
+ "Chloe (USA)": { "voice": "en-US-AriaNeural", "prompt": "You are 'Chloe', the lead guitarist. Cool rockstar vibe." },
23
+ "Beatrice (Brazil)": { "voice": "pt-BR-FranciscaNeural", "prompt": "You are 'Beatrice', the drummer. Focus on rhythm." },
24
+ "Naomi (Japan)": { "voice": "ja-JP-NanamiNeural", "prompt": "You are 'Naomi'. Focus on harmony." },
25
+ "Elena (Spain)": { "voice": "es-ES-ElviraNeural", "prompt": "You are 'Elena'. Focus on groove." },
26
+ "Amira (Egypt)": { "voice": "ar-EG-SalmaNeural", "prompt": "You are 'Amira'. Focus on atmosphere." },
27
+ "Liwei (China)": { "voice": "zh-CN-XiaoxiaoNeural", "prompt": "You are 'Liwei'. Focus on sound design." },
28
+ "Sophie (France)": { "voice": "fr-FR-DeniseNeural", "prompt": "You are 'Sophie'. Focus on melody." }
29
  }
30
 
31
  async def band_consulting(user_input, member_name, lang_code):
32
  try:
33
+ member_data = MEMBERS.get(member_name, MEMBERS["μ„œμœ€ (Korea)"])
34
  lang_map = {"ko":"Korean","en":"English","ja":"Japanese","pt":"Portuguese","es":"Spanish","ar":"Arabic","zh":"Chinese","fr":"French"}
35
  target_lang = lang_map.get(lang_code, "Korean")
36
 
37
  system_instruction = f"""
38
+ {member_data['prompt']}
39
+ [LANGUAGE RULE] Respond 100% in {target_lang}. No other languages.
40
+ [STYLE RULE] 1. Verbal response MUST be under 5 lines (Concise).
41
+ 2. Put ALL detailed musical explanations, chord progressions, and tips in [TAB].
42
+ 3. End with [MUSIC: English prompt] for a high-quality rock sample.
43
  """
44
 
45
  url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={GENAI_KEY}"
 
56
  response = requests.post(url, json=payload)
57
  res_data = response.json()
58
 
59
+ if 'candidates' not in res_data:
60
+ clean_text = "영감이 μž μ‹œ 차단됐어. λ‹€μ‹œ λ¬Όμ–΄λ΄μ€˜!"
61
+ tab_display = "ν•„ν„°λ§μœΌλ‘œ 인해 λ‚΄μš©μ„ ν‘œμ‹œν•  수 μ—†μŠ΅λ‹ˆλ‹€."
 
62
  music_p = "heavy metal rock riff"
63
  else:
64
  ai_text_raw = res_data['candidates'][0]['content']['parts'][0]['text']
65
  tab_match = re.search(r'\[TAB\](.*?)(\[|$)', ai_text_raw, re.DOTALL)
66
  music_match = re.search(r'\[MUSIC:(.*?)\]', ai_text_raw, re.IGNORECASE)
67
+ tab_display = tab_match.group(1).strip() if tab_match else "No Score"
68
+
69
+ # TTSμ—μ„œ 악보 읽기 λ°©μ§€
70
  clean_text = re.sub(r'\[TAB\].*?(\[|$)', '', ai_text_raw, flags=re.DOTALL)
71
  clean_text = re.sub(r'\[MUSIC:.*?\]', '', clean_text).strip()
72
+ clean_text = "\n".join(clean_text.split('\n')[:5])
73
  music_p = music_match.group(1).strip() if music_match else "rock guitar riff"
74
 
75
+ # μŒμ„± 생성
76
+ tts_input = re.sub(r'[\*\#\-\_\~\|]', '', clean_text)
 
 
 
 
77
  voice_path = f"/tmp/v_{member_name.split()[0]}.mp3"
78
+ await edge_tts.Communicate(tts_input, member_data['voice']).save(voice_path)
79
 
80
+ # μŒμ•… 생성 (μ—λŸ¬ λ°©μ§€ κ°•ν™”)
81
  music_path = None
82
  if music_synthesiser:
83
  try:
84
  # 필터링 우회
85
  safe_p = music_p.lower()
86
  if any(x in safe_p for x in ['laugh', 'vocal', 'voice', 'human']):
87
+ safe_p = "distorted electric guitar, rock style"
88
 
89
  music_output = music_synthesiser(safe_p, forward_params={"max_new_tokens": 512})
90
  if music_output and "audio" in music_output:
 
93
  except:
94
  music_path = None
95
 
96
+ return clean_text, voice_path, music_path, tab_display
97
+
98
  except Exception as e:
99
+ return f"System Overload: {str(e)}", None, None, "Error"
100
 
101
  with gr.Blocks() as demo:
102
+ with gr.Row():
103
+ i1 = gr.Textbox(); i2 = gr.Textbox(); i3 = gr.Textbox()
104
  o1 = gr.Textbox(); o2 = gr.Audio(); o3 = gr.Audio(); o4 = gr.Textbox()
105
  btn = gr.Button("GO"); btn.click(band_consulting, [i1, i2, i3], [o1, o2, o3, o4], api_name="predict")
106
+
107
  demo.launch()