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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -72
app.py CHANGED
@@ -4,104 +4,77 @@ import edge_tts
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}"
46
- payload = {
47
- "contents": [{"parts": [{"text": f"{system_instruction}\n질문: {user_input}"}]}],
48
- "safetySettings": [
49
- {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
50
- {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
51
- {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
52
- {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"}
53
- ]
54
- }
55
 
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:
91
- music_path = f"/tmp/m_{member_name.split()[0]}.wav"
92
- scipy.io.wavfile.write(music_path, music_output["sampling_rate"], music_output["audio"][0].T)
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()
 
 
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()