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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -41
app.py CHANGED
@@ -4,77 +4,96 @@ import edge_tts
4
  import os
5
  import re
6
  import scipy.io.wavfile
 
 
7
  from transformers import pipeline
8
- # β˜… GPU 지원을 μœ„ν•œ 라이브러리 (Hugging Face ν™˜κ²½μΈ 경우)
9
- try:
10
- import spaces
11
- has_spaces = True
12
- except:
13
- has_spaces = False
14
 
15
  GENAI_KEY = os.getenv("GEMINI_KEY")
16
 
17
- # λͺ¨λΈ λ‘œλ“œ (Hugging Face μ΅œμ ν™”)
18
  try:
19
- music_synthesiser = pipeline("text-to-audio", "facebook/musicgen-small", device=0 if has_spaces else -1)
20
  except:
21
  music_synthesiser = None
22
 
23
- # 8인 멀버 및 데이터 (μ‚­μ œ/μΆ•μ†Œ μ—†μŒ)
24
- 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" }
25
-
26
- # β˜… GPU 가속 λ°μ½”λ ˆμ΄ν„° (Hugging Face 무료 GPU ν™œμ„±ν™”)
27
- def generate_music_safe(prompt):
28
- if not music_synthesiser: return None, None
29
- try:
30
- # λ¦¬λ”λ‹˜ μš”μ²­λŒ€λ‘œ 512(μ•½ 12초) ν’€ νŒŒμ›Œ!
31
- output = music_synthesiser(prompt, forward_params={"max_new_tokens": 512, "do_sample": True})
32
- return output["sampling_rate"], output["audio"][0].T
33
- except:
34
- return None, None
35
 
36
  async def band_consulting(user_input, member_name, lang_code):
37
  try:
 
38
  lang_map = {"ko":"Korean","en":"English","ja":"Japanese","pt":"Portuguese","es":"Spanish","ar":"Arabic","zh":"Chinese","fr":"French"}
39
  target_lang = lang_map.get(lang_code, "Korean")
40
 
41
- system_instruction = f"당신은 {member_name}μž…λ‹ˆλ‹€. λ°˜λ“œμ‹œ {target_lang}둜만 λ‹΅λ³€ν•˜μ„Έμš”. μŒμ„±μ€ 5쀄 이내, 상세 μ„€λͺ…은 [TAB]에, μŒμ•… ν”„λ‘¬ν”„νŠΈλŠ” [MUSIC: ν”„λ‘¬ν”„νŠΈ]에 λ„£μœΌμ„Έμš”."
 
 
 
 
 
42
 
43
  url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={GENAI_KEY}"
44
  payload = {"contents": [{"parts": [{"text": f"{system_instruction}\n질문: {user_input}"}]}]}
45
 
46
- res = requests.post(url, json=payload).json()
47
- ai_text_raw = res['candidates'][0]['content']['parts'][0]['text']
48
 
49
- tab_match = re.search(r'\[TAB\](.*?)(\[|$)', ai_text_raw, re.DOTALL)
50
- music_match = re.search(r'\[MUSIC:(.*?)\]', ai_text_raw, re.IGNORECASE)
51
- tab_display = tab_match.group(1).strip() if tab_match else "상세 악보 μ—†μŒ"
52
-
53
- clean_text = re.sub(r'\[TAB\].*?(\[|$)', '', ai_text_raw, flags=re.DOTALL)
54
- clean_text = re.sub(r'\[MUSIC:.*?\]', '', clean_text).strip()
55
- tts_final = "\n".join(clean_text.split('\n')[:5])
 
 
 
 
 
56
 
57
- # μŒμ„± 생성
 
58
  voice_path = f"/tmp/v_{member_name.split()[0]}.mp3"
59
- await edge_tts.Communicate(re.sub(r'[\*\#\-\_\~\|]', '', tts_final), MEMBERS.get(member_name, "ko-KR-SunHiNeural")).save(voice_path)
 
60
 
61
- # μŒμ•… 생성 (νƒ€μž„μ•„μ›ƒ λ°©μ§€ 둜직 포함)
62
  music_path = None
63
- if music_match:
64
- sr, audio = generate_music_safe(music_match.group(1).strip())
65
- if sr is not None:
66
- music_path = f"/tmp/m_{member_name.split()[0]}.wav"
67
- scipy.io.wavfile.write(music_path, sr, audio)
 
 
 
 
 
 
 
 
 
68
 
69
  return tts_final, voice_path, music_path, tab_display
 
70
  except Exception as e:
71
- return f"System Error: {str(e)}", None, None, "Error"
 
72
 
73
  with gr.Blocks() as demo:
74
  i1 = gr.Textbox(); i2 = gr.Textbox(); i3 = gr.Textbox()
75
  o1 = gr.Textbox(); o2 = gr.Audio(); o3 = gr.Audio(); o4 = gr.Textbox()
76
- # β˜… 큐(Queue)λ₯Ό ν™œμ„±ν™”ν•˜μ—¬ μ„œλ²„κ°€ λŠκΈ°μ§€ μ•Šκ²Œ 함
77
  btn = gr.Button("GO"); btn.click(band_consulting, [i1, i2, i3], [o1, o2, o3, o4], api_name="predict")
78
 
79
- # β˜… queue()λ₯Ό λ°˜λ“œμ‹œ λΆ™μ—¬μ•Ό κΈ΄ μž‘μ—…μ„ λΈŒλΌμš°μ €κ°€ κΈ°λ‹€λ €μ€λ‹ˆλ‹€.
80
  demo.queue().launch()
 
4
  import os
5
  import re
6
  import scipy.io.wavfile
7
+ 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):
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
+ 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)
57
+ music_match = re.search(r'\[MUSIC:(.*?)\]', ai_text_raw, re.IGNORECASE)
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"
82
+ scipy.io.wavfile.write(music_path, music_output["sampling_rate"], music_output["audio"][0].T)
83
+ except:
84
+ music_path = None
85
 
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()