File size: 14,103 Bytes
9b1a8f5
 
 
 
 
bd2cd71
 
 
3c1a098
bd2cd71
 
9b1a8f5
bd2cd71
 
 
 
 
 
 
 
 
 
024290d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c1a098
 
 
 
 
 
 
 
 
 
 
 
 
024290d
3c1a098
 
 
024290d
3c1a098
024290d
 
 
3c1a098
 
024290d
3c1a098
024290d
 
 
3c1a098
 
024290d
3c1a098
024290d
 
 
3c1a098
 
 
024290d
3c1a098
bd2cd71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4594c83
 
bd2cd71
4594c83
 
bd2cd71
 
4594c83
bd2cd71
4594c83
bd2cd71
 
5ebef38
bd2cd71
 
 
 
 
 
 
 
 
9b1a8f5
bd2cd71
 
 
 
 
9b1a8f5
bd2cd71
 
 
 
 
 
9b1a8f5
bd2cd71
 
 
9b1a8f5
c76da8f
bd2cd71
 
 
 
 
 
 
 
9b1a8f5
 
bd2cd71
0e550b3
9b1a8f5
 
bd2cd71
9b1a8f5
 
c76da8f
bd2cd71
c76da8f
bd2cd71
c76da8f
 
bd2cd71
 
c76da8f
 
024290d
 
 
 
c82669c
9b1a8f5
3c1a098
024290d
3c1a098
024290d
 
 
 
 
 
 
3c1a098
bd2cd71
 
 
c94ca07
bd2cd71
 
 
 
3c1a098
bd2cd71
 
3c1a098
bd2cd71
 
 
024290d
3c1a098
bd2cd71
 
024290d
3c1a098
bd2cd71
3c1a098
024290d
 
bd2cd71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b1a8f5
bd2cd71
c76da8f
bd2cd71
 
 
 
9b1a8f5
bd2cd71
 
 
 
 
 
 
9b1a8f5
bd2cd71
9b1a8f5
 
3c1a098
92ed43a
 
 
 
 
 
 
 
 
 
bd2cd71
9b1a8f5
 
bd2cd71
 
 
 
 
3c1a098
024290d
bd2cd71
 
fc4c070
 
bd2cd71
024290d
bd2cd71
 
 
 
024290d
bd2cd71
 
024290d
bd2cd71
3c1a098
bd2cd71
 
024290d
bd2cd71
 
 
fc4c070
024290d
fc4c070
bd2cd71
3c1a098
fc4c070
 
 
aac9182
 
 
 
 
024290d
 
 
 
 
 
 
 
 
 
 
 
aac9182
a5a83e4
 
 
 
fc4c070
 
3c1a098
 
 
 
 
 
 
 
 
 
 
 
 
 
 
024290d
 
 
 
 
fc4c070
 
024290d
 
 
 
fc4c070
 
bd2cd71
 
fc4c070
bd2cd71
 
 
9b1a8f5
bd2cd71
9b1a8f5
bd2cd71
 
 
9b1a8f5
bd2cd71
 
 
 
 
 
 
 
 
024290d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import gradio as gr
import subprocess
import os 
import shutil
import tempfile
import torch
import logging
import numpy as np
import re
from concurrent.futures import ThreadPoolExecutor
from functools import lru_cache

# λ‘œκΉ… μ„€μ •
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('yue_generation.log'),
        logging.StreamHandler()
    ]
)

# 가사 뢄석 ν•¨μˆ˜
def analyze_lyrics(lyrics):
    # 쀄 λ‹¨μœ„λ‘œ 뢄리
    lines = [line.strip() for line in lyrics.split('\n') if line.strip()]
    
    # μ„Ήμ…˜ 카운트
    sections = {
        'verse': 0,
        'chorus': 0,
        'bridge': 0,
        'total_lines': len(lines)
    }
    
    current_section = None
    section_lines = {
        'verse': 0,
        'chorus': 0,
        'bridge': 0
    }
    
    for line in lines:
        lower_line = line.lower()
        if '[verse]' in lower_line:
            current_section = 'verse'
            sections['verse'] += 1
        elif '[chorus]' in lower_line:
            current_section = 'chorus'
            sections['chorus'] += 1
        elif '[bridge]' in lower_line:
            current_section = 'bridge'
            sections['bridge'] += 1
        elif current_section and line.strip():
            section_lines[current_section] += 1
            
    # 총 μ„Ήμ…˜ 수 계산
    total_sections = sections['verse'] + sections['chorus'] + sections['bridge']
    
    return sections, total_sections, len(lines), section_lines

def calculate_generation_params(lyrics):
    sections, total_sections, total_lines, section_lines = analyze_lyrics(lyrics)
    
    # κΈ°λ³Έ 토큰 수 계산
    base_tokens_per_line = 200
    verse_tokens = section_lines['verse'] * base_tokens_per_line
    chorus_tokens = section_lines['chorus'] * (base_tokens_per_line * 1.5)  # μ½”λŸ¬μŠ€λŠ” 50% 더 λ§Žμ€ 토큰
    bridge_tokens = section_lines['bridge'] * base_tokens_per_line
    
    # 총 토큰 수 계산
    total_tokens = int(verse_tokens + chorus_tokens + bridge_tokens)
    
    # μ„Ήμ…˜ 기반 μ„Έκ·Έλ¨ΌνŠΈ 수 계산
    num_segments = max(2, min(4, total_sections))
    
    # 토큰 수 μ œν•œ
    max_tokens = min(32000, max(3000, total_tokens))
    
    return {
        'max_tokens': max_tokens,
        'num_segments': num_segments,
        'sections': sections,
        'section_lines': section_lines
    }

# μ–Έμ–΄ 감지 및 λͺ¨λΈ 선택 ν•¨μˆ˜
def detect_and_select_model(text):
    if re.search(r'[\u3131-\u318E\uAC00-\uD7A3]', text):  # ν•œκΈ€
        return "m-a-p/YuE-s1-7B-anneal-jp-kr-cot"
    elif re.search(r'[\u4e00-\u9fff]', text):  # 쀑ꡭ어
        return "m-a-p/YuE-s1-7B-anneal-zh-cot"
    elif re.search(r'[\u3040-\u309F\u30A0-\u30FF]', text):  # 일본어
        return "m-a-p/YuE-s1-7B-anneal-jp-kr-cot"
    else:  # μ˜μ–΄/기타
        return "m-a-p/YuE-s1-7B-anneal-en-cot"

def optimize_model_selection(lyrics, genre):
    model_path = detect_and_select_model(lyrics)
    params = calculate_generation_params(lyrics)
    
    model_config = {
        "m-a-p/YuE-s1-7B-anneal-en-cot": {
            "max_tokens": params['max_tokens'],
            "temperature": 0.8,
            "batch_size": 8,
            "num_segments": params['num_segments'],
            "chorus_strength": 1.2 if params['sections']['chorus'] > 0 else 1.0
        },
        "m-a-p/YuE-s1-7B-anneal-jp-kr-cot": {
            "max_tokens": params['max_tokens'],
            "temperature": 0.7,
            "batch_size": 8,
            "num_segments": params['num_segments'],
            "chorus_strength": 1.2 if params['sections']['chorus'] > 0 else 1.0
        },
        "m-a-p/YuE-s1-7B-anneal-zh-cot": {
            "max_tokens": params['max_tokens'],
            "temperature": 0.7,
            "batch_size": 8,
            "num_segments": params['num_segments'],
            "chorus_strength": 1.2 if params['sections']['chorus'] > 0 else 1.0
        }
    }
    
    return model_path, model_config[model_path], params

# GPU μ„€μ • μ΅œμ ν™”
def optimize_gpu_settings():
    if torch.cuda.is_available():
        torch.backends.cuda.matmul.allow_tf32 = True
        torch.backends.cudnn.benchmark = True
        torch.backends.cudnn.deterministic = False
        torch.backends.cudnn.enabled = True
        
        torch.cuda.empty_cache()
        torch.cuda.set_device(0)
        
        logging.info(f"Using GPU: {torch.cuda.get_device_name(0)}")
        logging.info(f"Available GPU memory: {torch.cuda.get_device_properties(0).total_memory / 1024**3:.2f} GB")
    else:
        logging.warning("GPU not available!")

def install_flash_attn():
    try:
        logging.info("Installing flash-attn...")
        subprocess.run(
            ["pip", "install", "flash-attn", "--no-build-isolation"], 
            check=True,
            capture_output=True
        )
        logging.info("flash-attn installed successfully!")
    except subprocess.CalledProcessError as e:
        logging.error(f"Failed to install flash-attn: {e}")
        raise

def initialize_system():
    optimize_gpu_settings()
    install_flash_attn()
    
    from huggingface_hub import snapshot_download
    
    folder_path = './inference/xcodec_mini_infer'
    os.makedirs(folder_path, exist_ok=True)
    logging.info(f"Created folder at: {folder_path}")

    snapshot_download(
        repo_id="m-a-p/xcodec_mini_infer",
        local_dir="./inference/xcodec_mini_infer",
        resume_download=True
    )

    try:
        os.chdir("./inference")
        logging.info(f"Working directory changed to: {os.getcwd()}")
    except FileNotFoundError as e:
        logging.error(f"Directory error: {e}")
        raise

@lru_cache(maxsize=100)
def get_cached_file_path(content_hash, prefix):
    return create_temp_file(content_hash, prefix)

def empty_output_folder(output_dir):
    try:
        shutil.rmtree(output_dir)
        os.makedirs(output_dir)
        logging.info(f"Output folder cleaned: {output_dir}")
    except Exception as e:
        logging.error(f"Error cleaning output folder: {e}")
        raise

def create_temp_file(content, prefix, suffix=".txt"):
    temp_file = tempfile.NamedTemporaryFile(delete=False, mode="w", prefix=prefix, suffix=suffix)
    content = content.strip() + "\n\n"
    content = content.replace("\r\n", "\n").replace("\r", "\n")
    temp_file.write(content)
    temp_file.close()
    logging.debug(f"Temporary file created: {temp_file.name}")
    return temp_file.name

def get_last_mp3_file(output_dir):
    mp3_files = [f for f in os.listdir(output_dir) if f.endswith('.mp3')]
    if not mp3_files:
        logging.warning("No MP3 files found")
        return None
    
    mp3_files_with_path = [os.path.join(output_dir, f) for f in mp3_files]
    mp3_files_with_path.sort(key=os.path.getmtime, reverse=True)
    return mp3_files_with_path[0]





def infer(genre_txt_content, lyrics_txt_content, num_segments, max_new_tokens):
    try:
        # λͺ¨λΈ 선택 및 μ„€μ •
        model_path, config, params = optimize_model_selection(lyrics_txt_content, genre_txt_content)
        logging.info(f"Selected model: {model_path}")
        logging.info(f"Lyrics analysis: {params}")
        
        # μ‹€μ œ μ‚¬μš©ν•  νŒŒλΌλ―Έν„°
        actual_num_segments = config['num_segments']
        actual_max_tokens = config['max_tokens']
        
        logging.info(f"Using segments: {actual_num_segments}, tokens: {actual_max_tokens}")
        
        # μž„μ‹œ 파일 생성
        genre_txt_path = create_temp_file(genre_txt_content, prefix="genre_")
        lyrics_txt_path = create_temp_file(lyrics_txt_content, prefix="lyrics_")
        
        output_dir = "./output"
        os.makedirs(output_dir, exist_ok=True)
        empty_output_folder(output_dir)

        # λͺ…λ Ήμ–΄ ꡬ성
        command = [
            "python", "infer.py",
            "--stage1_model", model_path,
            "--stage2_model", "m-a-p/YuE-s2-1B-general",
            "--genre_txt", genre_txt_path,
            "--lyrics_txt", lyrics_txt_path,
            "--run_n_segments", str(actual_num_segments),
            "--stage2_batch_size", str(config['batch_size']),
            "--output_dir", output_dir,
            "--cuda_idx", "0",
            "--max_new_tokens", str(actual_max_tokens),
            "--temperature", str(config['temperature']),
            "--disable_offload_model",
            "--use_flash_attention_2",
            "--bf16",
            "--chorus_strength", str(config['chorus_strength'])
        ]

        # CUDA ν™˜κ²½ λ³€μˆ˜ μ„€μ •
        env = os.environ.copy()
        env.update({
            "CUDA_VISIBLE_DEVICES": "0",
            "CUDA_HOME": "/usr/local/cuda",
            "PATH": f"/usr/local/cuda/bin:{env.get('PATH', '')}",
            "LD_LIBRARY_PATH": f"/usr/local/cuda/lib64:{env.get('LD_LIBRARY_PATH', '')}",
            "PYTORCH_CUDA_ALLOC_CONF": "max_split_size_mb:512"
        })

        # λͺ…λ Ή μ‹€ν–‰
        process = subprocess.run(command, env=env, check=True, capture_output=True)
        logging.info("Inference completed successfully")

        # 결과 처리
        last_mp3 = get_last_mp3_file(output_dir)
        if last_mp3:
            logging.info(f"Generated audio file: {last_mp3}")
            return last_mp3
        else:
            logging.warning("No output audio file generated")
            return None

    except Exception as e:
        logging.error(f"Inference error: {e}")
        raise
    finally:
        # μž„μ‹œ 파일 정리
        for file in [genre_txt_path, lyrics_txt_path]:
            try:
                os.remove(file)
                logging.debug(f"Removed temporary file: {file}")
            except Exception as e:
                logging.warning(f"Failed to remove temporary file {file}: {e}")

# Gradio μΈν„°νŽ˜μ΄μŠ€
with gr.Blocks() as demo:
    with gr.Column():
        gr.Markdown("# YuE: Open Music Foundation Models for Full-Song Generation (Multi-Language Support)")
        gr.HTML("""
        <div style="display:flex;column-gap:4px;">
            <a href="https://github.com/multimodal-art-projection/YuE">
                <img src='https://img.shields.io/badge/GitHub-Repo-blue'>
            </a> 
            <a href="https://map-yue.github.io">
                <img src='https://img.shields.io/badge/Project-Page-green'>
            </a>
        </div>
        """)
        
        with gr.Row():
            with gr.Column():
                genre_txt = gr.Textbox(
                    label="Genre",
                    placeholder="Enter music genre and style descriptions..."
                )
                lyrics_txt = gr.Textbox(
                    label="Lyrics (Supports English, Korean, Japanese, Chinese)",
                    placeholder="Enter song lyrics with [verse], [chorus], [bridge] tags...",
                    lines=10
                )
                
            with gr.Column():
                num_segments = gr.Number(
                    label="Number of Song Segments (Auto-adjusted based on lyrics)",
                    value=2,
                    minimum=1,
                    maximum=4,
                    step=1,
                    interactive=False
                )
                max_new_tokens = gr.Slider(
                    label="Max New Tokens (Auto-adjusted based on lyrics)",
                    minimum=500,
                    maximum=32000,
                    step=500,
                    value=4000,
                    interactive=False
                )
                submit_btn = gr.Button("Generate Music", variant="primary")
                music_out = gr.Audio(label="Generated Audio")

        # λ‹€κ΅­μ–΄ 예제
        gr.Examples(
            examples=[
                # μ˜μ–΄ 예제
                [
                    "female blues airy vocal bright vocal piano sad romantic guitar jazz",
                    """[verse]
In the quiet of the evening, shadows start to fall
Whispers of the night wind echo through the hall
Lost within the silence, I hear your gentle voice
Guiding me back homeward, making my heart rejoice

[chorus]
Don't let this moment fade, hold me close tonight
With you here beside me, everything's alright
Can't imagine life alone, don't want to let you go
Stay with me forever, let our love just flow

[verse]
Morning light is breaking, through the window pane
Memories of yesterday, like soft summer rain
In your arms I'm finding, all I'm dreaming of
Every day beside you, fills my heart with love

[chorus]
Don't let this moment fade, hold me close tonight
With you here beside me, everything's alright
Can't imagine life alone, don't want to let you go
Stay with me forever, let our love just flow
                    """
                ],
                # ν•œκ΅­μ–΄ 예제
                [
                    "K-pop bright energetic synth dance electronic",
                    """[verse]
λΉ›λ‚˜λŠ” λ³„λ“€μ²˜λŸΌ 우리의 꿈이
μ € ν•˜λŠ˜μ„ μˆ˜λ†“μ•„ λ°˜μ§μ΄λ„€
ν•¨κ»˜λΌλ©΄ μ–΄λ””λ“  갈 수 μžˆμ–΄
우리의 이야기가 μ‹œμž‘λ˜λ„€

[chorus]
λ‹¬λ €κ°€μž 더 높이 더 멀리
두렀움은 μ—†μ–΄ λ„ˆμ™€ ν•¨κ»˜λΌλ©΄
μ˜μ›νžˆ 계속될 우리의 λ…Έλž˜
이 μˆœκ°„μ„ κΈ°μ–΅ν•΄ forever

[verse]
μƒˆλ‘œμš΄ 내일을 ν–₯ν•΄ λ‚˜μ•„κ°€
우리만의 길을 λ§Œλ“€μ–΄κ°€
믿음으둜 κ°€λ“ν•œ 우리의 맘
μ ˆλŒ€ λ©ˆμΆ”μ§€ μ•Šμ•„ κ³„μ†ν•΄μ„œ

[chorus]
λ‹¬λ €κ°€μž 더 높이 더 멀리
두렀움은 μ—†μ–΄ λ„ˆμ™€ ν•¨κ»˜λΌλ©΄
μ˜μ›νžˆ 계속될 우리의 λ…Έλž˜
이 μˆœκ°„μ„ κΈ°μ–΅ν•΄ forever
                    """
                ]
            ],
            inputs=[genre_txt, lyrics_txt]
        )

    # μ‹œμŠ€ν…œ μ΄ˆκΈ°ν™”
    initialize_system()
    
    # 이벀트 ν•Έλ“€λŸ¬
    submit_btn.click(
        fn=infer,
        inputs=[genre_txt, lyrics_txt, num_segments, max_new_tokens],
        outputs=[music_out]
    )

# μ„œλ²„ μ„€μ •μœΌλ‘œ μ‹€ν–‰
demo.queue(concurrency_count=2).launch(
    server_name="0.0.0.0",
    server_port=7860,
    share=True,
    enable_queue=True,
    show_api=True,
    show_error=True
)