benjamin5607 commited on
Commit
474efb5
Β·
verified Β·
1 Parent(s): 25c52a1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -24
app.py CHANGED
@@ -8,24 +8,34 @@ import asyncio
8
  import numpy as np
9
  from transformers import pipeline
10
 
 
 
 
 
 
 
 
 
 
11
  GENAI_KEY = os.getenv("GEMINI_KEY")
12
 
13
  # μŒμ•… λͺ¨λΈ λ‘œλ“œ
14
  try:
15
  music_synthesiser = pipeline("text-to-audio", "facebook/musicgen-small")
16
- except:
 
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):
@@ -35,22 +45,22 @@ async def band_consulting(user_input, member_name, lang_code):
35
  target_lang = lang_map.get(lang_code, "Korean")
36
 
37
  system_instruction = f"""
38
- {member_data['prompt']}
39
  1. λ°˜λ“œμ‹œ {target_lang}둜만 λ‹΅λ³€ν•˜μ„Έμš”.
40
- 2. μŒμ„± 닡변은 5쀄 이내 μš”μ•½, 상세 μ„€λͺ…은 [TAB]에 λ„£μœΌμ„Έμš”.
41
  3. λ§ˆμ§€λ§‰μ— [MUSIC: μ˜μ–΄ ν”„λ‘¬ν”„νŠΈ]λ₯Ό ν¬ν•¨ν•˜μ„Έμš”.
42
  """
43
 
44
  url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={GENAI_KEY}"
45
  payload = {"contents": [{"parts": [{"text": f"{system_instruction}\n질문: {user_input}"}]}]}
46
 
47
- response = requests.post(url, json=payload, timeout=15)
48
  res_data = response.json()
49
 
50
  if 'candidates' not in res_data:
51
- clean_text = "영감이 μž μ‹œ κΌ¬μ˜€λ„€. λ‹€μ‹œ μ‹œλ„ν•΄μ€˜!"
52
  tab_display = "데이터 였λ₯˜"
53
- music_p = "rock music"
54
  else:
55
  ai_text_raw = res_data['candidates'][0]['content']['parts'][0]['text']
56
  tab_match = re.search(r'\[TAB\](.*?)(\[|$)', ai_text_raw, re.DOTALL)
@@ -58,24 +68,23 @@ async def band_consulting(user_input, member_name, lang_code):
58
  tab_display = tab_match.group(1).strip() if tab_match else "상세 악보 μ—†μŒ"
59
  clean_text = re.sub(r'\[TAB\].*?(\[|$)', '', ai_text_raw, flags=re.DOTALL)
60
  clean_text = re.sub(r'\[MUSIC:.*?\]', '', clean_text).strip()
61
- music_p = music_match.group(1).strip() if music_match else "rock style"
62
 
63
- # μŒμ„± 생성 (5쀄 μš”μ•½ 및 필터링)
64
  tts_final = "\n".join(clean_text.split('\n')[:5])
65
  voice_path = f"/tmp/v_{member_name.split()[0]}.mp3"
 
66
  communicate = edge_tts.Communicate(re.sub(r'[\*\#\-\_\~\|]', '', tts_final), member_data['voice'])
67
  await communicate.save(voice_path)
68
 
69
- # μŒμ•… 생성 (λ¦¬λ”λ‹˜ μš”μ²­λŒ€λ‘œ 512 토큰 - κΈ΄ μ—°μ£Ό)
70
  music_path = None
71
  if music_synthesiser:
72
  try:
73
- # ν•„ν„° 단어 우회
74
  safe_p = music_p.lower()
75
  if any(x in safe_p for x in ['laugh', 'vocal', 'voice', 'human']):
76
- safe_p = "electric guitar riff, rock style"
77
 
78
- # CPU κ³ΌλΆ€ν•˜λ₯Ό 견디기 μœ„ν•΄ max_new_tokens 512 μœ μ§€
79
  music_output = music_synthesiser(safe_p, forward_params={"max_new_tokens": 512})
80
  if music_output and "audio" in music_output:
81
  music_path = f"/tmp/m_{member_name.split()[0]}.wav"
@@ -86,14 +95,13 @@ async def band_consulting(user_input, member_name, lang_code):
86
  return tts_final, voice_path, music_path, tab_display
87
 
88
  except Exception as e:
89
- print(f"Server Catch: {e}")
90
  return f"System Overload: {str(e)}", None, None, "Error"
91
 
92
  with gr.Blocks() as demo:
93
  i1 = gr.Textbox(); i2 = gr.Textbox(); i3 = gr.Textbox()
94
  o1 = gr.Textbox(); o2 = gr.Audio(); o3 = gr.Audio(); o4 = gr.Textbox()
95
- # 큐 μ‹œμŠ€ν…œ ν™œμ„±ν™”λ‘œ λΈŒλΌμš°μ € μ—°κ²° μœ μ§€
96
  btn = gr.Button("GO"); btn.click(band_consulting, [i1, i2, i3], [o1, o2, o3, o4], api_name="predict")
97
 
98
- # β˜… queue()λ₯Ό μΆ”κ°€ν•˜μ—¬ λŒ€κΈ°μ—΄μ„ λ§Œλ“€κ³  νƒ€μž„μ•„μ›ƒ(Invalid FD) μ—λŸ¬λ₯Ό λ°©μ§€
99
  demo.queue().launch()
 
8
  import numpy as np
9
  from transformers import pipeline
10
 
11
+ # [핡심] 비동기 파일 λ””μŠ€ν¬λ¦½ν„° μ—λŸ¬ λ°©μ§€ μ„€μ •
12
+ if os.name != 'nt': # λ¦¬λˆ…μŠ€/λ§₯ ν™˜κ²½ λŒ€μ‘
13
+ import selectors
14
+ selector = selectors.SelectSelector()
15
+ try:
16
+ asyncio.set_event_loop_policy(asyncio.DefaultEventLoopPolicy())
17
+ except:
18
+ pass
19
+
20
  GENAI_KEY = os.getenv("GEMINI_KEY")
21
 
22
  # μŒμ•… λͺ¨λΈ λ‘œλ“œ
23
  try:
24
  music_synthesiser = pipeline("text-to-audio", "facebook/musicgen-small")
25
+ except Exception as e:
26
+ print(f"Music Model Load Error: {e}")
27
  music_synthesiser = None
28
 
29
+ # 8인 멀버 데이터 (μ ˆλŒ€ μΆ•μ†Œ μ—†μŒ)
30
  MEMBERS = {
31
+ "μ„œμœ€ (Korea)": { "voice": "ko-KR-SunHiNeural", "prompt": "보컬 μ„œμœ€. μ‹œλ‹ˆμ»¬ν•˜μ§€λ§Œ μ§„μ‹¬μž„." },
32
+ "Chloe (USA)": { "voice": "en-US-AriaNeural", "prompt": "Guitarist Chloe. Cool rockstar vibe." },
33
+ "Beatrice (Brazil)": { "voice": "pt-BR-FranciscaNeural", "prompt": "Drummer Beatrice. Rhythm focus." },
34
+ "Naomi (Japan)": { "voice": "ja-JP-NanamiNeural", "prompt": "Naomi. Harmony focus." },
35
+ "Elena (Spain)": { "voice": "es-ES-ElviraNeural", "prompt": "Elena. Groove focus." },
36
+ "Amira (Egypt)": { "voice": "ar-EG-SalmaNeural", "prompt": "Amira. Atmosphere focus." },
37
+ "Liwei (China)": { "voice": "zh-CN-XiaoxiaoNeural", "prompt": "Liwei. Sound design focus." },
38
+ "Sophie (France)": { "voice": "fr-FR-DeniseNeural", "prompt": "Sophie. Melody focus." }
39
  }
40
 
41
  async def band_consulting(user_input, member_name, lang_code):
 
45
  target_lang = lang_map.get(lang_code, "Korean")
46
 
47
  system_instruction = f"""
48
+ 당신은 '{member_name}'μž…λ‹ˆλ‹€.
49
  1. λ°˜λ“œμ‹œ {target_lang}둜만 λ‹΅λ³€ν•˜μ„Έμš”.
50
+ 2. μŒμ„± 닡변은 5쀄 이내 μš”μ•½, 상세 μ„€λͺ…/μ•…λ³΄λŠ” [TAB]에 λ„£μœΌμ„Έμš”.
51
  3. λ§ˆμ§€λ§‰μ— [MUSIC: μ˜μ–΄ ν”„λ‘¬ν”„νŠΈ]λ₯Ό ν¬ν•¨ν•˜μ„Έμš”.
52
  """
53
 
54
  url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={GENAI_KEY}"
55
  payload = {"contents": [{"parts": [{"text": f"{system_instruction}\n질문: {user_input}"}]}]}
56
 
57
+ response = requests.post(url, json=payload, timeout=20)
58
  res_data = response.json()
59
 
60
  if 'candidates' not in res_data:
61
+ clean_text = "영감이 κΌ¬μ˜€μ–΄. λ‹€μ‹œ μ‹œλ„ν•΄μ€˜!"
62
  tab_display = "데이터 였λ₯˜"
63
+ music_p = "rock music riff"
64
  else:
65
  ai_text_raw = res_data['candidates'][0]['content']['parts'][0]['text']
66
  tab_match = re.search(r'\[TAB\](.*?)(\[|$)', ai_text_raw, re.DOTALL)
 
68
  tab_display = tab_match.group(1).strip() if tab_match else "상세 악보 μ—†μŒ"
69
  clean_text = re.sub(r'\[TAB\].*?(\[|$)', '', ai_text_raw, flags=re.DOTALL)
70
  clean_text = re.sub(r'\[MUSIC:.*?\]', '', clean_text).strip()
71
+ music_p = music_match.group(1).strip() if music_match else "rock guitar riff"
72
 
73
+ # μŒμ„± 생성 (비동기 루프 직접 μ œμ–΄)
74
  tts_final = "\n".join(clean_text.split('\n')[:5])
75
  voice_path = f"/tmp/v_{member_name.split()[0]}.mp3"
76
+ # 파일이 μ—΄λ €μžˆλŠ”μ§€ 확인 ν›„ 생성
77
  communicate = edge_tts.Communicate(re.sub(r'[\*\#\-\_\~\|]', '', tts_final), member_data['voice'])
78
  await communicate.save(voice_path)
79
 
80
+ # μŒμ•… 생성 (512 토큰 ν’€ νŒŒμ›Œ)
81
  music_path = None
82
  if music_synthesiser:
83
  try:
 
84
  safe_p = music_p.lower()
85
  if any(x in safe_p for x in ['laugh', 'vocal', 'voice', 'human']):
86
+ safe_p = "heavy rock electric guitar riff"
87
 
 
88
  music_output = music_synthesiser(safe_p, forward_params={"max_new_tokens": 512})
89
  if music_output and "audio" in music_output:
90
  music_path = f"/tmp/m_{member_name.split()[0]}.wav"
 
95
  return tts_final, voice_path, music_path, tab_display
96
 
97
  except Exception as e:
98
+ print(f"Error caught: {e}")
99
  return f"System Overload: {str(e)}", None, None, "Error"
100
 
101
  with gr.Blocks() as demo:
102
  i1 = gr.Textbox(); i2 = gr.Textbox(); i3 = gr.Textbox()
103
  o1 = gr.Textbox(); o2 = gr.Audio(); o3 = gr.Audio(); o4 = gr.Textbox()
 
104
  btn = gr.Button("GO"); btn.click(band_consulting, [i1, i2, i3], [o1, o2, o3, o4], api_name="predict")
105
 
106
+ # 큐 μ‹œμŠ€ν…œμœΌλ‘œ νƒ€μž„μ•„μ›ƒ λ°©μ§€
107
  demo.queue().launch()