svjack commited on
Commit
d710de9
·
verified ·
1 Parent(s): 31adf56

Create env_app.py

Browse files
Files changed (1) hide show
  1. env_app.py +269 -0
env_app.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import subprocess
3
+ import os
4
+ import shutil
5
+ import tempfile
6
+
7
+ # 运行 'which python' 命令并获取输出
8
+ which_python = subprocess.check_output(['which', 'python']).decode('utf-8').strip()
9
+
10
+ # 输出结果
11
+ print(which_python)
12
+
13
+ #is_shared_ui = True if "fffiloni/YuE" in os.environ['SPACE_ID'] else False
14
+
15
+ # Install required package
16
+ def install_flash_attn():
17
+ try:
18
+ print("Installing flash-attn...")
19
+ subprocess.run(
20
+ ["pip", "install", "flash-attn", "--no-build-isolation"],
21
+ check=True
22
+ )
23
+ print("flash-attn installed successfully!")
24
+ except subprocess.CalledProcessError as e:
25
+ print(f"Failed to install flash-attn: {e}")
26
+ exit(1)
27
+
28
+ # Install flash-attn
29
+ #install_flash_attn()
30
+
31
+ from huggingface_hub import snapshot_download
32
+
33
+ # Create xcodec_mini_infer folder
34
+ folder_path = './inference/xcodec_mini_infer'
35
+
36
+ # Create the folder if it doesn't exist
37
+ if not os.path.exists(folder_path):
38
+ os.mkdir(folder_path)
39
+ print(f"Folder created at: {folder_path}")
40
+ else:
41
+ print(f"Folder already exists at: {folder_path}")
42
+
43
+ snapshot_download(
44
+ repo_id = "m-a-p/xcodec_mini_infer",
45
+ local_dir = "./inference/xcodec_mini_infer"
46
+ )
47
+
48
+ # Change to the "inference" directory
49
+ inference_dir = "./inference"
50
+ try:
51
+ os.chdir(inference_dir)
52
+ print(f"Changed working directory to: {os.getcwd()}")
53
+ except FileNotFoundError:
54
+ print(f"Directory not found: {inference_dir}")
55
+ exit(1)
56
+
57
+ def empty_output_folder(output_dir):
58
+ # List all files in the output directory
59
+ files = os.listdir(output_dir)
60
+
61
+ # Iterate over the files and remove them
62
+ for file in files:
63
+ file_path = os.path.join(output_dir, file)
64
+ try:
65
+ if os.path.isdir(file_path):
66
+ # If it's a directory, remove it recursively
67
+ shutil.rmtree(file_path)
68
+ else:
69
+ # If it's a file, delete it
70
+ os.remove(file_path)
71
+ except Exception as e:
72
+ print(f"Error deleting file {file_path}: {e}")
73
+
74
+ # Function to create a temporary file with string content
75
+ def create_temp_file(content, suffix=".txt"):
76
+ fd, path = tempfile.mkstemp(suffix=suffix)
77
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
78
+ f.write(content)
79
+ return path
80
+
81
+ def get_last_mp3_file(output_dir):
82
+ # List all files in the output directory
83
+ files = os.listdir(output_dir)
84
+
85
+ # Filter only .mp3 files
86
+ mp3_files = [file for file in files if file.endswith('.mp3')]
87
+
88
+ if not mp3_files:
89
+ print("No .mp3 files found in the output folder.")
90
+ return None
91
+
92
+ # Get the full path for the mp3 files
93
+ mp3_files_with_path = [os.path.join(output_dir, file) for file in mp3_files]
94
+
95
+ # Sort the files based on the modification time (most recent first)
96
+ mp3_files_with_path.sort(key=lambda x: os.path.getmtime(x), reverse=True)
97
+
98
+ # Return the most recent .mp3 file
99
+ return mp3_files_with_path[0]
100
+
101
+ def infer(genre_txt_content, lyrics_txt_content, num_segments, max_new_tokens):
102
+ # Create temporary files
103
+ genre_txt_path = create_temp_file(genre_txt_content, ".txt")
104
+ lyrics_txt_path = create_temp_file(lyrics_txt_content, ".txt")
105
+
106
+ print(f"Genre TXT path: {genre_txt_path}")
107
+ print(f"Lyrics TXT path: {lyrics_txt_path}")
108
+
109
+ # Ensure the output folder exists
110
+ output_dir = "./output"
111
+ os.makedirs(output_dir, exist_ok=True)
112
+ print(f"Output folder ensured at: {output_dir}")
113
+
114
+ empty_output_folder(output_dir)
115
+
116
+ # Command and arguments with optimized settings
117
+ command = [
118
+ which_python, "infer.py",
119
+ "--stage1_model", "m-a-p/YuE-s1-7B-anneal-en-cot",
120
+ "--stage2_model", "m-a-p/YuE-s2-1B-general",
121
+ "--genre_txt", f"{genre_txt_path}",
122
+ "--lyrics_txt", f"{lyrics_txt_path}",
123
+ "--run_n_segments", str(num_segments),
124
+ "--stage2_batch_size", "4",
125
+ "--output_dir", f"{output_dir}",
126
+ "--cuda_idx", "0",
127
+ "--max_new_tokens", str(max_new_tokens),
128
+ "--disable_offload_model"
129
+ ]
130
+
131
+ # Set up environment variables for CUDA with optimized settings
132
+ env = os.environ.copy()
133
+ env.update({
134
+ "CUDA_VISIBLE_DEVICES": "0",
135
+ "CUDA_HOME": "/usr/local/cuda",
136
+ "PATH": f"/usr/local/cuda/bin:{env.get('PATH', '')}",
137
+ "LD_LIBRARY_PATH": f"/usr/local/cuda/lib64:{env.get('LD_LIBRARY_PATH', '')}"
138
+ })
139
+
140
+ # Execute the command
141
+ try:
142
+ subprocess.run(command, check=True, env=env)
143
+ print("Command executed successfully!")
144
+
145
+ # Check and print the contents of the output folder
146
+ output_files = os.listdir(output_dir)
147
+ if output_files:
148
+ print("Output folder contents:")
149
+ for file in output_files:
150
+ print(f"- {file}")
151
+
152
+ last_mp3 = get_last_mp3_file(output_dir)
153
+
154
+ if last_mp3:
155
+ print("Last .mp3 file:", last_mp3)
156
+ return last_mp3
157
+ else:
158
+ return None
159
+ else:
160
+ print("Output folder is empty.")
161
+ return None
162
+ except subprocess.CalledProcessError as e:
163
+ print(f"Error occurred: {e}")
164
+ return None
165
+ finally:
166
+ # Clean up temporary files
167
+ os.remove(genre_txt_path)
168
+ os.remove(lyrics_txt_path)
169
+ print("Temporary files deleted.")
170
+
171
+ # Gradio
172
+
173
+ with gr.Blocks() as demo:
174
+ with gr.Column():
175
+ gr.Markdown("# YuE: Open Music Foundation Models for Full-Song Generation")
176
+ gr.HTML("""
177
+ <div style="display:flex;column-gap:4px;">
178
+ <a href="https://github.com/multimodal-art-projection/YuE">
179
+ <img src='https://img.shields.io/badge/GitHub-Repo-blue'>
180
+ </a>
181
+ <a href="https://map-yue.github.io">
182
+ <img src='https://img.shields.io/badge/Project-Page-green'>
183
+ </a>
184
+ <a href="https://huggingface.co/spaces/fffiloni/YuE?duplicate=true">
185
+ <img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/duplicate-this-space-sm.svg" alt="Duplicate this Space">
186
+ </a>
187
+ </div>
188
+ """)
189
+ with gr.Row():
190
+ with gr.Column():
191
+ with gr.Accordion("Pro Tips", open=False):
192
+ gr.Markdown(f"""
193
+ **Tips:**
194
+ 1. `genres` should include details like instruments, genre, mood, vocal timbre, and vocal gender.
195
+ 2. The length of `lyrics` segments and the `--max_new_tokens` value should be matched. For example, if `--max_new_tokens` is set to 3000, the maximum duration for a segment is around 30 seconds. Ensure your lyrics fit this time frame.
196
+
197
+
198
+ **Notice:**
199
+ 1. A suitable [Genre] tag consists of five components: genre, instrument, mood, gender, and timbre. All five should be included if possible, separated by spaces. The values of timbre should include "vocal" (e.g., "bright vocal").
200
+
201
+ 2. Although our tags have an open vocabulary, we have provided the 200 most commonly used <a href="https://github.com/multimodal-art-projection/YuE/blob/main/top_200_tags.json" id="tags_link" target="_blank">tags</a>. It is recommended to select tags from this list for more stable results.
202
+
203
+ 3. The order of the tags is flexible. For example, a stable genre control string might look like: "inspiring female uplifting pop airy vocal electronic bright vocal vocal."
204
+
205
+ 4. Additionally, we have introduced the "Mandarin" and "Cantonese" tags to distinguish between Mandarin and Cantonese, as their lyrics often share similarities.
206
+ """)
207
+ genre_txt = gr.Textbox(
208
+ label="Genre",
209
+ placeholder="Example: inspiring female uplifting pop airy vocal...",
210
+ info="Text containing genre tags that describe the musical style or characteristics (e.g., instrumental, genre, mood, vocal timbre, vocal gender). This is used as part of the generation prompt."
211
+ )
212
+ lyrics_txt = gr.Textbox(
213
+ label="Lyrics", lines=12,
214
+ placeholder="Type the lyrics here...",
215
+ info="Text containing the lyrics for the music generation. These lyrics will be processed and split into structured segments to guide the generation process."
216
+ )
217
+
218
+ with gr.Column():
219
+
220
+ num_segments = gr.Number(label="Number of Segments", value=2, interactive=True)
221
+ max_new_tokens = gr.Slider(label="Max New Tokens", minimum=500, maximum="3000", step=500, value=1500, interactive=True)
222
+
223
+ submit_btn = gr.Button("Submit")
224
+ music_out = gr.Audio(label="Audio Result")
225
+
226
+ gr.Examples(
227
+ examples = [
228
+ [
229
+ "female blues airy vocal bright vocal piano sad romantic guitar jazz",
230
+ """[verse]
231
+ In the quiet of the evening, shadows start to fall
232
+ Whispers of the night wind echo through the hall
233
+ Lost within the silence, I hear your gentle voice
234
+ Guiding me back homeward, making my heart rejoice
235
+
236
+ [chorus]
237
+ Don't let this moment fade, hold me close tonight
238
+ With you here beside me, everything's alright
239
+ Can't imagine life alone, don't want to let you go
240
+ Stay with me forever, let our love just flow"""
241
+ ],
242
+ [
243
+ "rap piano street tough piercing vocal hip-hop synthesizer clear vocal male",
244
+ """[verse]
245
+ Woke up in the morning, sun is shining bright
246
+ Chasing all my dreams, gotta get my mind right
247
+ City lights are fading, but my vision's clear
248
+ Got my team beside me, no room for fear
249
+ Walking through the streets, beats inside my head
250
+ Every step I take, closer to the bread
251
+ People passing by, they don't understand
252
+ Building up my future with my own two hands
253
+
254
+ [chorus]
255
+ This is my life, and I'm aiming for the top
256
+ Never gonna quit, no, I'm never gonna stop
257
+ Through the highs and lows, I'mma keep it real
258
+ Living out my dreams with this mic and a deal"""
259
+ ]
260
+ ],
261
+ inputs = [genre_txt, lyrics_txt]
262
+ )
263
+
264
+ submit_btn.click(
265
+ fn = infer,
266
+ inputs = [genre_txt, lyrics_txt, num_segments, max_new_tokens],
267
+ outputs = [music_out]
268
+ )
269
+ demo.queue().launch(share = True ,show_api=True, show_error=True)