Spaces:
Building
on
L40S
Building
on
L40S
File size: 32,704 Bytes
9b1a8f5 bd2cd71 3c1a098 bd2cd71 9b1a8f5 a6582cc bd2cd71 6d09855 edfc27d 024290d edfc27d 024290d a7b49e3 edfc27d a7b49e3 024290d a7b49e3 024290d a7b49e3 024290d a7b49e3 6d09855 024290d a7b49e3 024290d a7b49e3 6d09855 024290d a7b49e3 024290d a7b49e3 6d09855 edfc27d a7b49e3 edfc27d a7b49e3 edfc27d a7b49e3 edfc27d 024290d a7b49e3 dbad390 a7b49e3 dbad390 024290d a7b49e3 13bfd1b a7b49e3 3469b26 a7b49e3 13bfd1b a7b49e3 dbad390 a7b49e3 6d09855 a7b49e3 024290d a7b49e3 024290d a7b49e3 3469b26 a7b49e3 3469b26 a7b49e3 dbad390 a7b49e3 024290d 4fb8e24 024290d c8a3a02 dbad390 3469b26 024290d 3c1a098 6d09855 3c1a098 6d09855 3c1a098 6d09855 3c1a098 bd2cd71 6d09855 bd2cd71 4594c83 5d47f79 58da738 5d47f79 6d09855 cb17632 5d47f79 5ebef38 299f10b 7621f85 6d09855 7621f85 a406e84 7621f85 a406e84 7621f85 299f10b 98e03fd 7621f85 a406e84 7621f85 a406e84 7621f85 a406e84 7621f85 a406e84 7621f85 a406e84 7621f85 a406e84 98e03fd 299f10b 3693724 299f10b f08699a 3693724 299f10b a406e84 f08699a a406e84 299f10b f08699a a406e84 299f10b 7621f85 299f10b f08699a 7621f85 299f10b bd2cd71 299f10b 9320919 299f10b 01ee1f1 299f10b 01ee1f1 f08699a 01ee1f1 299f10b 9320919 299f10b 01ee1f1 9320919 01ee1f1 9320919 01ee1f1 9320919 299f10b 9320919 bd2cd71 9b1a8f5 6d09855 fe0dd07 6d09855 1d7d926 299f10b c82669c 299f10b 1d7d926 9b1a8f5 299f10b 024290d 3c1a098 024290d 1d7d926 3469b26 a7b49e3 6d09855 dbad390 a7b49e3 6d09855 a7b49e3 86bd09d c8a3a02 024290d 3c1a098 bd2cd71 c94ca07 bd2cd71 6d09855 bd2cd71 9320919 024290d 6d09855 9320919 bd2cd71 6d09855 9320919 bd2cd71 f08699a bd2cd71 5d47f79 6d09855 3693724 5d47f79 bd2cd71 3693724 0c540a1 2792e64 bd2cd71 bddc80f dbad390 3469b26 dbad390 bddc80f bd2cd71 9b1a8f5 bd2cd71 c76da8f bd2cd71 9b1a8f5 6d09855 9b1a8f5 2ae7725 fe0dd07 22f0ac1 7e28ce1 22f0ac1 ec47ce6 22f0ac1 c8a3a02 22f0ac1 7e28ce1 9f11480 7e28ce1 9f11480 7e28ce1 22f0ac1 2792e64 fe0dd07 edfc27d 22f0ac1 7e28ce1 edfc27d 6d09855 22f0ac1 9f11480 22f0ac1 fe0dd07 dbad390 c8a3a02 dbad390 c8a3a02 22f0ac1 c8a3a02 dbad390 a6582cc 7e28ce1 a6582cc 7e28ce1 a6582cc 7e28ce1 a6582cc 7e28ce1 22f0ac1 9f11480 22f0ac1 8c01fb9 9f11480 a6582cc 22f0ac1 8c01fb9 7e28ce1 8c01fb9 22f0ac1 8c01fb9 22f0ac1 8c01fb9 1a2d5b4 a6582cc fc4c070 1a2d5b4 a6582cc 6df0adf 1a2d5b4 6df0adf |
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 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 |
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
from datetime import datetime
# ๋ก๊น
์ค์
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('yue_generation.log'),
logging.StreamHandler()
]
)
def optimize_gpu_settings():
if torch.cuda.is_available():
# GPU ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ ์ต์ ํ
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.enabled = True
torch.backends.cudnn.deterministic = False
# L40S์ ์ต์ ํ๋ ๋ฉ๋ชจ๋ฆฌ ์ค์
torch.cuda.empty_cache()
torch.cuda.set_device(0)
# CUDA ์คํธ๋ฆผ ์ต์ ํ
torch.cuda.Stream(0)
# ๋ฉ๋ชจ๋ฆฌ ํ ๋น ์ต์ ํ
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:512'
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")
# L40S ํนํ ์ค์
if 'L40S' in torch.cuda.get_device_name(0):
torch.cuda.set_per_process_memory_fraction(0.95)
def analyze_lyrics(lyrics, repeat_chorus=2):
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': [],
'chorus': [],
'bridge': []
}
last_section = None
# ๋ง์ง๋ง ์น์
ํ๊ทธ ์ฐพ๊ธฐ
for i, line in enumerate(lines):
if '[verse]' in line.lower() or '[chorus]' in line.lower() or '[bridge]' in line.lower():
last_section = i
for i, line in enumerate(lines):
lower_line = line.lower()
# ์น์
ํ๊ทธ ์ฒ๋ฆฌ
if '[verse]' in lower_line:
if current_section: # ์ด์ ์น์
์ ๋ผ์ธ๋ค ์ ์ฅ
section_lines[current_section].extend(lines[last_section_start:i])
current_section = 'verse'
sections['verse'] += 1
last_section_start = i + 1
continue
elif '[chorus]' in lower_line:
if current_section:
section_lines[current_section].extend(lines[last_section_start:i])
current_section = 'chorus'
sections['chorus'] += 1
last_section_start = i + 1
continue
elif '[bridge]' in lower_line:
if current_section:
section_lines[current_section].extend(lines[last_section_start:i])
current_section = 'bridge'
sections['bridge'] += 1
last_section_start = i + 1
continue
# ๋ง์ง๋ง ์น์
์ ๋ผ์ธ๋ค ์ถ๊ฐ
if current_section and last_section_start < len(lines):
section_lines[current_section].extend(lines[last_section_start:])
# ์ฝ๋ฌ์ค ๋ฐ๋ณต ์ฒ๋ฆฌ
if sections['chorus'] > 0 and repeat_chorus > 1:
original_chorus = section_lines['chorus'][:]
for _ in range(repeat_chorus - 1):
section_lines['chorus'].extend(original_chorus)
# ์น์
๋ณ ๋ผ์ธ ์ ํ์ธ ๋ก๊น
logging.info(f"Section line counts - Verse: {len(section_lines['verse'])}, "
f"Chorus: {len(section_lines['chorus'])}, "
f"Bridge: {len(section_lines['bridge'])}")
return sections, (sections['verse'] + sections['chorus'] + sections['bridge']), len(lines), section_lines
def calculate_generation_params(lyrics):
sections, total_sections, total_lines, section_lines = analyze_lyrics(lyrics)
# ๊ธฐ๋ณธ ์๊ฐ ๊ณ์ฐ (์ด ๋จ์)
time_per_line = {
'verse': 4, # verse๋ ํ ์ค๋น 4์ด
'chorus': 6, # chorus๋ ํ ์ค๋น 6์ด
'bridge': 5 # bridge๋ ํ ์ค๋น 5์ด
}
# ๊ฐ ์น์
๋ณ ์์ ์๊ฐ ๊ณ์ฐ (๋ง์ง๋ง ์น์
ํฌํจ)
section_durations = {}
for section_type in ['verse', 'chorus', 'bridge']:
lines_count = len(section_lines[section_type])
section_durations[section_type] = lines_count * time_per_line[section_type]
# ์ ์ฒด ์๊ฐ ๊ณ์ฐ (์ฌ์ ์๊ฐ ์ถ๊ฐ)
total_duration = sum(duration for duration in section_durations.values())
total_duration = max(60, int(total_duration * 1.2)) # 20% ์ฌ์ ์๊ฐ ์ถ๊ฐ
# ํ ํฐ ๊ณ์ฐ (๋ง์ง๋ง ์น์
์ ์ํ ์ถ๊ฐ ํ ํฐ)
base_tokens = 3000
tokens_per_line = 200
extra_tokens = 1000 # ๋ง์ง๋ง ์น์
์ ์ํ ์ถ๊ฐ ํ ํฐ
total_tokens = base_tokens + (total_lines * tokens_per_line) + extra_tokens
# ์ธ๊ทธ๋จผํธ ์ ๊ณ์ฐ (๋ง์ง๋ง ์น์
์ ์ํ ์ถ๊ฐ ์ธ๊ทธ๋จผํธ)
if sections['chorus'] > 0:
num_segments = 4 # ์ฝ๋ฌ์ค๊ฐ ์๋ ๊ฒฝ์ฐ 4๊ฐ ์ธ๊ทธ๋จผํธ
else:
num_segments = 3 # ์ฝ๋ฌ์ค๊ฐ ์๋ ๊ฒฝ์ฐ 3๊ฐ ์ธ๊ทธ๋จผํธ
# ํ ํฐ ์ ์ ํ (๋ ํฐ ์ ํ)
max_tokens = min(12000, total_tokens) # ์ต๋ ํ ํฐ ์ ์ฆ๊ฐ
return {
'max_tokens': max_tokens,
'num_segments': num_segments,
'sections': sections,
'section_lines': section_lines,
'estimated_duration': total_duration,
'section_durations': section_durations,
'has_chorus': sections['chorus'] > 0
}
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 install_flash_attn():
try:
if not torch.cuda.is_available():
logging.warning("GPU not available, skipping flash-attn installation")
return False
cuda_version = torch.version.cuda
if cuda_version is None:
logging.warning("CUDA not available, skipping flash-attn installation")
return False
logging.info(f"Detected CUDA version: {cuda_version}")
try:
import flash_attn
logging.info("flash-attn already installed")
return True
except ImportError:
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!")
return True
except Exception as e:
logging.warning(f"Failed to install flash-attn: {e}")
return False
def download_missing_files():
try:
from huggingface_hub import hf_hub_download, snapshot_download
# xcodec_mini_infer ํ์ผ๋ค ์ง์ ๋ค์ด๋ก๋
repo_id = "hf-internal-testing/xcodec_mini_infer" # ์ ์ฅ์ ๊ฒฝ๋ก ์์
files_to_download = {
"config.json": "config/config.json",
"vocal_decoder.pth": "checkpoints/vocal_decoder.pth",
"inst_decoder.pth": "checkpoints/inst_decoder.pth"
}
xcodec_dir = "./xcodec_mini_infer"
os.makedirs(xcodec_dir, exist_ok=True)
os.makedirs(os.path.join(xcodec_dir, "checkpoints"), exist_ok=True)
for target_name, source_path in files_to_download.items():
try:
downloaded_path = hf_hub_download(
repo_id=repo_id,
filename=source_path,
cache_dir="./models/cache",
force_download=True,
local_files_only=False
)
logging.info(f"Downloaded {source_path} to: {downloaded_path}")
# ํ์ผ์ ์ฌ๋ฐ๋ฅธ ์์น๋ก ๋ณต์ฌ
target_path = os.path.join(xcodec_dir, target_name)
shutil.copy2(downloaded_path, target_path)
logging.info(f"Copied to: {target_path}")
except Exception as e:
logging.error(f"Error downloading {source_path}: {e}")
# ๋์ฒด ์ ์ฅ์ ์๋
try:
alt_repo_id = "facebook/musicgen-small"
downloaded_path = hf_hub_download(
repo_id=alt_repo_id,
filename=source_path,
cache_dir="./models/cache",
force_download=True
)
target_path = os.path.join(xcodec_dir, target_name)
shutil.copy2(downloaded_path, target_path)
logging.info(f"Downloaded from alternate source to: {target_path}")
except Exception as alt_e:
logging.error(f"Error with alternate download: {alt_e}")
raise
# YuE ๋ชจ๋ธ๋ค ๋ค์ด๋ก๋
models = [
"m-a-p/YuE-s1-7B-anneal-jp-kr-cot",
"m-a-p/YuE-s1-7B-anneal-en-cot",
"m-a-p/YuE-s1-7B-anneal-zh-cot",
"m-a-p/YuE-s2-1B-general"
]
for model in models:
model_name = model.split('/')[-1]
model_path = snapshot_download(
repo_id=model,
local_dir=f"./models/{model_name}",
cache_dir="./models/cache",
resume_download=True,
force_download=True
)
logging.info(f"Downloaded {model_name} to: {model_path}")
# ํ์ผ ์กด์ฌ ๋ฐ ํฌ๊ธฐ ํ์ธ
for target_name in files_to_download.keys():
file_path = os.path.join(xcodec_dir, target_name)
if not os.path.exists(file_path):
raise FileNotFoundError(f"Failed to download {target_name}")
file_size = os.path.getsize(file_path)
if file_size == 0:
raise FileNotFoundError(f"Downloaded file is empty: {target_name}")
logging.info(f"Verified {target_name}: {file_size} bytes")
logging.info("All required models downloaded successfully")
except Exception as e:
logging.error(f"Error downloading models: {e}")
raise
def check_model_files():
base_dir = os.getcwd()
xcodec_dir = os.path.join(base_dir, "xcodec_mini_infer")
# ํ์ํ ํ์ผ ๋ชฉ๋ก
required_files = {
"config.json": "config.json",
"vocal_decoder.pth": "vocal_decoder.pth",
"inst_decoder.pth": "inst_decoder.pth"
}
# ํ์ผ ์กด์ฌ ์ฌ๋ถ ํ์ธ
missing = False
for file_name in required_files.keys():
file_path = os.path.join(xcodec_dir, file_name)
if not os.path.exists(file_path):
missing = True
logging.warning(f"Missing file: {file_path}")
if missing:
logging.info("Downloading missing files...")
download_missing_files()
# ๋ค์ด๋ก๋ ํ ํ์ผ ์ฌํ์ธ
for file_name in required_files.keys():
file_path = os.path.join(xcodec_dir, file_name)
if not os.path.exists(file_path):
raise FileNotFoundError(f"Failed to download or locate required file: {file_name}")
else:
file_size = os.path.getsize(file_path)
if file_size == 0:
raise FileNotFoundError(f"Downloaded file is empty: {file_name}")
logging.info(f"Verified {file_name}: {file_size} bytes")
def initialize_system():
optimize_gpu_settings()
try:
# ๊ธฐ๋ณธ ๋๋ ํ ๋ฆฌ ๊ตฌ์กฐ ์์ฑ
base_dir = os.path.abspath("./inference")
os.makedirs(base_dir, exist_ok=True)
os.makedirs(os.path.join(base_dir, "models"), exist_ok=True)
# ์์
๋๋ ํ ๋ฆฌ ๋ณ๊ฒฝ
os.chdir(base_dir)
logging.info(f"Working directory changed to: {os.getcwd()}")
from huggingface_hub import snapshot_download, hf_hub_download
# xcodec_mini_infer ํ์ผ๋ค ์ง์ ๋ค์ด๋ก๋
xcodec_dir = os.path.join(base_dir, "xcodec_mini_infer")
os.makedirs(xcodec_dir, exist_ok=True)
# ํ์ ํ์ผ ์ง์ ๋ค์ด๋ก๋
required_files = {
"config.json": "config.json",
"vocal_decoder.pth": "vocal_decoder.pth",
"inst_decoder.pth": "inst_decoder.pth"
}
for file_name in required_files.keys():
try:
file_path = os.path.join(xcodec_dir, file_name)
if not os.path.exists(file_path):
downloaded_path = hf_hub_download(
repo_id="m-a-p/xcodec_mini_infer",
filename=file_name,
local_dir=xcodec_dir,
force_download=True
)
if downloaded_path != file_path:
shutil.copy2(downloaded_path, file_path)
logging.info(f"Downloaded {file_name} to {file_path}")
except Exception as e:
logging.error(f"Error downloading {file_name}: {e}")
raise
# YuE ๋ชจ๋ธ๋ค ๋ค์ด๋ก๋
models = [
"m-a-p/YuE-s1-7B-anneal-jp-kr-cot",
"m-a-p/YuE-s1-7B-anneal-en-cot",
"m-a-p/YuE-s1-7B-anneal-zh-cot",
"m-a-p/YuE-s2-1B-general"
]
with ThreadPoolExecutor(max_workers=4) as executor:
futures = []
# Flash Attention ์ค์น
futures.append(executor.submit(install_flash_attn))
# ๋ชจ๋ธ ๋ค์ด๋ก๋
for model in models:
model_name = model.split('/')[-1]
model_path = os.path.join(base_dir, "models", model_name)
futures.append(executor.submit(
snapshot_download,
repo_id=model,
local_dir=model_path,
force_download=True
))
# ๋ชจ๋ ์์
์๋ฃ ๋๊ธฐ
for future in futures:
future.result()
# ํ์ผ ์กด์ฌ ํ์ธ
for file_name, _ in required_files.items():
file_path = os.path.join(xcodec_dir, file_name)
if not os.path.exists(file_path):
raise FileNotFoundError(f"Required file still missing after download: {file_path}")
else:
file_size = os.path.getsize(file_path)
logging.info(f"Verified {file_name}: {file_size} bytes")
logging.info("System initialization completed successfully")
except Exception 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 get_audio_duration(file_path):
try:
import librosa
duration = librosa.get_duration(path=file_path)
return duration
except Exception as e:
logging.error(f"Failed to get audio duration: {e}")
return None
def infer(genre_txt_content, lyrics_txt_content, num_segments, max_new_tokens):
check_model_files() # ํ์ํ ํ์ผ ์ฒดํฌ ๋ฐ ๋ค์ด๋ก๋
genre_txt_path = None
lyrics_txt_path = None
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}")
has_chorus = params['sections']['chorus'] > 0
estimated_duration = params.get('estimated_duration', 90)
# ์ธ๊ทธ๋จผํธ ๋ฐ ํ ํฐ ์ ์ค์
if has_chorus:
actual_max_tokens = min(12000, int(config['max_tokens'] * 1.3)) # 30% ๋ ๋ง์ ํ ํฐ
actual_num_segments = min(5, params['num_segments'] + 2) # ์ถ๊ฐ ์ธ๊ทธ๋จผํธ
else:
actual_max_tokens = min(10000, int(config['max_tokens'] * 1.2))
actual_num_segments = min(4, params['num_segments'] + 1)
logging.info(f"Estimated duration: {estimated_duration} seconds")
logging.info(f"Has chorus sections: {has_chorus}")
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", "16",
"--output_dir", output_dir,
"--cuda_idx", "0",
"--max_new_tokens", str(actual_max_tokens),
"--disable_offload_model"
]
env = os.environ.copy()
if torch.cuda.is_available():
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",
"CUDA_LAUNCH_BLOCKING": "0",
"TRANSFORMERS_CACHE": "./models/cache",
"HF_HOME": "./models/cache"
})
# transformers ์บ์ ๋ง์ด๊ทธ๋ ์ด์
์ฒ๋ฆฌ
try:
from transformers.utils import move_cache
move_cache()
except Exception as e:
logging.warning(f"Cache migration warning (non-critical): {e}")
process = subprocess.run(
command,
env=env,
check=False,
capture_output=True,
text=True
)
logging.info(f"Command output: {process.stdout}")
if process.stderr:
logging.error(f"Command error: {process.stderr}")
if process.returncode != 0:
logging.error(f"Command failed with return code: {process.returncode}")
logging.error(f"Command: {' '.join(command)}")
raise RuntimeError(f"Inference failed: {process.stderr}")
last_mp3 = get_last_mp3_file(output_dir)
if last_mp3:
try:
duration = get_audio_duration(last_mp3)
logging.info(f"Generated audio file: {last_mp3}")
if duration:
logging.info(f"Audio duration: {duration:.2f} seconds")
logging.info(f"Expected duration: {estimated_duration} seconds")
if duration < estimated_duration * 0.8:
logging.warning(f"Generated audio is shorter than expected: {duration:.2f}s < {estimated_duration:.2f}s")
except Exception as e:
logging.warning(f"Failed to get audio duration: {e}")
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 path in [genre_txt_path, lyrics_txt_path]:
if path and os.path.exists(path):
try:
os.remove(path)
logging.debug(f"Removed temporary file: {path}")
except Exception as e:
logging.warning(f"Failed to remove temporary file {path}: {e}")
def optimize_model_selection(lyrics, genre):
model_path = detect_and_select_model(lyrics)
params = calculate_generation_params(lyrics)
has_chorus = params['sections']['chorus'] > 0
tokens_per_segment = params['max_tokens'] // params['num_segments']
model_config = {
"m-a-p/YuE-s1-7B-anneal-en-cot": {
"max_tokens": params['max_tokens'],
"temperature": 0.8,
"batch_size": 16,
"num_segments": params['num_segments'],
"estimated_duration": params['estimated_duration']
},
"m-a-p/YuE-s1-7B-anneal-jp-kr-cot": {
"max_tokens": params['max_tokens'],
"temperature": 0.7,
"batch_size": 16,
"num_segments": params['num_segments'],
"estimated_duration": params['estimated_duration']
},
"m-a-p/YuE-s1-7B-anneal-zh-cot": {
"max_tokens": params['max_tokens'],
"temperature": 0.7,
"batch_size": 16,
"num_segments": params['num_segments'],
"estimated_duration": params['estimated_duration']
}
}
if has_chorus:
for config in model_config.values():
config['max_tokens'] = int(config['max_tokens'] * 1.5)
return model_path, model_config[model_path], params
css = """
#main-container {
max-width: 1200px;
margin: auto;
padding: 20px;
}
#header {
text-align: center;
margin-bottom: 30px;
}
#genre-input, #lyrics-input {
border-radius: 8px;
}
#generate-btn {
margin-top: 20px;
min-height: 45px;
}
.label {
font-weight: bold;
}
.example-container {
background: #f8f9fa;
padding: 15px;
border-radius: 8px;
margin: 10px 0;
}
"""
def main():
with gr.Blocks(theme=gr.themes.Soft(
primary_hue="indigo",
secondary_hue="purple",
neutral_hue="slate",
font=["Arial", "sans-serif"]
), css=css) as demo:
with gr.Column(elem_id="main-container"):
# ํค๋ ์น์
with gr.Row(elem_id="header"):
gr.Markdown(
"""
# ๐ต Open SUNO: Transform Your Lyrics into Complete Songs
### Create complete songs from your lyrics in multiple languages
""",
elem_id="title"
)
# ๋ฉ์ธ ์ปจํ
์ธ ๋ฅผ ํญ์ผ๋ก ๊ตฌ์ฑ
with gr.Tabs() as tabs:
# ์์ฑ ํญ
with gr.TabItem("โจ Create Music", id="create"):
with gr.Row():
# ์
๋ ฅ ์น์
with gr.Column(scale=1):
genre_txt = gr.Textbox(
label="๐ธ Music Genre & Style",
placeholder="e.g., K-pop bright energetic synth dance electronic...",
elem_id="genre-input"
)
lyrics_txt = gr.Textbox(
label="๐ Lyrics",
placeholder="Enter lyrics with section tags: [verse], [chorus], [bridge]...",
lines=10,
elem_id="lyrics-input"
)
# ์ ๋ณด ํ์ ์น์
with gr.Row():
with gr.Column(scale=1):
duration_info = gr.Label(
label="โฑ๏ธ Estimated Duration",
elem_id="duration-info"
)
with gr.Column(scale=1):
sections_info = gr.Label(
label="๐ Section Analysis",
elem_id="sections-info"
)
# ์์ฑ ๋ฒํผ
submit_btn = gr.Button(
"๐ผ Generate Music",
variant="primary",
elem_id="generate-btn"
)
# ์ถ๋ ฅ ์น์
with gr.Column(scale=1):
music_out = gr.Audio(
label="๐ต Generated Music",
elem_id="music-output"
)
# ์งํ ์ํ ํ์
progress = gr.Textbox(
label="Generation Status",
interactive=False,
elem_id="progress-status"
)
# ํ์คํ ๋ฆฌ ํญ
with gr.TabItem("๐ History", id="history"):
with gr.Row():
history_container = gr.HTML("""
<div id="history-container" style="width: 100%; padding: 10px;">
<h3>๐ต Generation History</h3>
<div id="history-list"></div>
</div>
""")
# ํ์คํ ๋ฆฌ ์ํ ์ ์ฅ
history_state = gr.State([])
# ์์ ์น์
with gr.Accordion("๐ Examples", open=False):
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
"""
],
[
"K-pop bright energetic synth dance electronic",
"""[verse]
์ธ์ ๊ฐ ๋ง์ฃผํ ๋๋น ์์์
์ด๋์ด ๋ฐค์ ์ง๋ ๋๋ง๋ค
[chorus]
๋ค์ ํ ๋ฒ ๋ด๊ฒ ๋งํด์ค
"""
]
],
inputs=[genre_txt, lyrics_txt]
)
# ๋์๋ง ๋ฐ ์ค๋ช
์น์
with gr.Accordion("โน๏ธ Help & Information", open=False):
gr.Markdown(
"""
### ๐ต How to Use
1. **Enter Genre & Style**: Describe the musical style you want (e.g., "K-pop", "Jazz", "Rock")
2. **Input Lyrics**: Write your lyrics using section tags:
- Use `[verse]` for verses
- Use `[chorus]` for choruses
- Use `[bridge]` for bridges
3. **Generate**: Click the Generate button and wait for your music!
### ๐ Supported Languages
- English
- Korean (ํ๊ตญ์ด)
- Japanese (ๆฅๆฌ่ช)
- Chinese (ไธญๆ)
### โก Tips
- Be specific with your genre descriptions
- Include emotion and instrument preferences
- Make sure to properly tag your lyrics sections
- For best results, include both verse and chorus sections
"""
)
# ์จ๊ฒจ์ง ์ํ ๋ณ์๋ค
num_segments = gr.State(value=2) # ๊ธฐ๋ณธ๊ฐ 2
max_new_tokens = gr.State(value=4000) # ๊ธฐ๋ณธ๊ฐ 4000
# ์์คํ
์ด๊ธฐํ
initialize_system()
def update_info(lyrics):
if not lyrics:
return "No lyrics entered", "No sections detected"
params = calculate_generation_params(lyrics)
duration = params['estimated_duration']
sections = params['sections']
return (
f"โฑ๏ธ Estimated: {duration:.1f} seconds",
f"๐ Verses: {sections['verse']}, Chorus: {sections['chorus']}"
)
def update_history(audio_path, genre, lyrics, history):
if audio_path:
new_entry = {
"audio": audio_path,
"genre": genre,
"lyrics": lyrics,
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S") # datetime ์ง์ ์ฌ์ฉ
}
history = [new_entry] + (history or [])
history_html = "<div class='history-entries'>"
for entry in history:
history_html += f"""
<div class='history-entry' style='margin: 10px 0; padding: 10px; border: 1px solid #ddd; border-radius: 8px;'>
<audio controls src='{entry["audio"]}'></audio>
<div style='margin-top: 5px;'><strong>Genre:</strong> {entry["genre"]}</div>
<div style='margin-top: 5px;'><strong>Lyrics:</strong><pre>{entry["lyrics"]}</pre></div>
<div style='color: #666; font-size: 0.9em;'>{entry["timestamp"]}</div>
</div>
"""
history_html += "</div>"
return history, history_html
return history, ""
def generate_with_progress(genre, lyrics, segments, tokens, history):
try:
status_text = "๐ต Starting generation..."
result = infer(genre, lyrics, segments, tokens)
if result:
status_text = "โ
Generation complete!"
new_history, history_html = update_history(result, genre, lyrics, history)
return result, new_history, history_html, status_text
else:
status_text = "โ Generation failed"
return None, history, "", status_text
except Exception as e:
status_text = f"โ Error: {str(e)}"
return None, history, "", status_text
# ์ด๋ฒคํธ ํธ๋ค๋ฌ
lyrics_txt.change(
fn=update_info,
inputs=[lyrics_txt],
outputs=[duration_info, sections_info]
)
# submit ๋ฒํผ ํด๋ฆญ ์ด๋ฒคํธ ์ถ๊ฐ
submit_btn.click(
fn=generate_with_progress,
inputs=[genre_txt, lyrics_txt, num_segments, max_new_tokens, history_state],
outputs=[music_out, history_state, history_container, progress]
)
return demo
if __name__ == "__main__":
demo = main()
demo.queue(max_size=20).launch(
server_name="0.0.0.0",
server_port=7860,
share=True,
show_api=True,
show_error=True,
max_threads=8
) |