Spaces:
Paused
Paused
ACE-Step v1.5 Worker (schlanke API-Variante)
Browse files- .env.example +4 -0
- .gitattributes +3 -0
- .gitignore +228 -0
- Dockerfile +57 -0
- LICENSE +21 -0
- README.md +17 -7
- acestep/__init__.py +1 -0
- acestep/acestep_v15_pipeline.py +303 -0
- acestep/api_server.py +1700 -0
- acestep/audio_utils.py +378 -0
- acestep/constants.py +109 -0
- acestep/constrained_logits_processor.py +0 -0
- acestep/dataset_handler.py +37 -0
- acestep/dit_alignment_score.py +870 -0
- acestep/genres_vocab.txt +0 -0
- acestep/gradio_ui/__init__.py +1 -0
- acestep/gradio_ui/events/__init__.py +1355 -0
- acestep/gradio_ui/events/generation_handlers.py +1071 -0
- acestep/gradio_ui/events/results_handlers.py +0 -0
- acestep/gradio_ui/events/training_handlers.py +644 -0
.env.example
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ACESTEP_CONFIG_PATH=acestep-v15-turbo
|
| 2 |
+
ACESTEP_LM_MODEL_PATH=acestep-5Hz-lm-1.7B
|
| 3 |
+
ACESTEP_DEVICE=auto
|
| 4 |
+
ACESTEP_LM_BACKEND=vllm
|
.gitattributes
CHANGED
|
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
data/
|
| 2 |
+
*.mp3
|
| 3 |
+
*.wav
|
| 4 |
+
|
| 5 |
+
# Byte-compiled / optimized / DLL files
|
| 6 |
+
__pycache__/
|
| 7 |
+
*.py[codz]
|
| 8 |
+
*$py.class
|
| 9 |
+
|
| 10 |
+
# C extensions
|
| 11 |
+
*.so
|
| 12 |
+
|
| 13 |
+
# Distribution / packaging
|
| 14 |
+
.Python
|
| 15 |
+
build/
|
| 16 |
+
develop-eggs/
|
| 17 |
+
dist/
|
| 18 |
+
downloads/
|
| 19 |
+
eggs/
|
| 20 |
+
.eggs/
|
| 21 |
+
lib/
|
| 22 |
+
lib64/
|
| 23 |
+
parts/
|
| 24 |
+
sdist/
|
| 25 |
+
var/
|
| 26 |
+
wheels/
|
| 27 |
+
share/python-wheels/
|
| 28 |
+
*.egg-info/
|
| 29 |
+
.installed.cfg
|
| 30 |
+
*.egg
|
| 31 |
+
MANIFEST
|
| 32 |
+
|
| 33 |
+
# PyInstaller
|
| 34 |
+
# Usually these files are written by a python script from a template
|
| 35 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
| 36 |
+
*.manifest
|
| 37 |
+
*.spec
|
| 38 |
+
|
| 39 |
+
# Installer logs
|
| 40 |
+
pip-log.txt
|
| 41 |
+
pip-delete-this-directory.txt
|
| 42 |
+
|
| 43 |
+
# Unit test / coverage reports
|
| 44 |
+
htmlcov/
|
| 45 |
+
.tox/
|
| 46 |
+
.nox/
|
| 47 |
+
.coverage
|
| 48 |
+
.coverage.*
|
| 49 |
+
.cache
|
| 50 |
+
nosetests.xml
|
| 51 |
+
coverage.xml
|
| 52 |
+
*.cover
|
| 53 |
+
*.py.cover
|
| 54 |
+
.hypothesis/
|
| 55 |
+
.pytest_cache/
|
| 56 |
+
cover/
|
| 57 |
+
|
| 58 |
+
# Translations
|
| 59 |
+
*.mo
|
| 60 |
+
*.pot
|
| 61 |
+
|
| 62 |
+
# Django stuff:
|
| 63 |
+
*.log
|
| 64 |
+
local_settings.py
|
| 65 |
+
db.sqlite3
|
| 66 |
+
db.sqlite3-journal
|
| 67 |
+
|
| 68 |
+
# Flask stuff:
|
| 69 |
+
instance/
|
| 70 |
+
.webassets-cache
|
| 71 |
+
|
| 72 |
+
# Scrapy stuff:
|
| 73 |
+
.scrapy
|
| 74 |
+
|
| 75 |
+
# Sphinx documentation
|
| 76 |
+
docs/_build/
|
| 77 |
+
|
| 78 |
+
# PyBuilder
|
| 79 |
+
.pybuilder/
|
| 80 |
+
target/
|
| 81 |
+
|
| 82 |
+
# Jupyter Notebook
|
| 83 |
+
.ipynb_checkpoints
|
| 84 |
+
|
| 85 |
+
# IPython
|
| 86 |
+
profile_default/
|
| 87 |
+
ipython_config.py
|
| 88 |
+
|
| 89 |
+
# pyenv
|
| 90 |
+
# For a library or package, you might want to ignore these files since the code is
|
| 91 |
+
# intended to run in multiple environments; otherwise, check them in:
|
| 92 |
+
# .python-version
|
| 93 |
+
|
| 94 |
+
# pipenv
|
| 95 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
| 96 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
| 97 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
| 98 |
+
# install all needed dependencies.
|
| 99 |
+
#Pipfile.lock
|
| 100 |
+
|
| 101 |
+
# UV
|
| 102 |
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
| 103 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
| 104 |
+
# commonly ignored for libraries.
|
| 105 |
+
uv.lock
|
| 106 |
+
|
| 107 |
+
# poetry
|
| 108 |
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
| 109 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
| 110 |
+
# commonly ignored for libraries.
|
| 111 |
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
| 112 |
+
#poetry.lock
|
| 113 |
+
#poetry.toml
|
| 114 |
+
|
| 115 |
+
# pdm
|
| 116 |
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
| 117 |
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
| 118 |
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
| 119 |
+
#pdm.lock
|
| 120 |
+
#pdm.toml
|
| 121 |
+
.pdm-python
|
| 122 |
+
.pdm-build/
|
| 123 |
+
|
| 124 |
+
# pixi
|
| 125 |
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
| 126 |
+
#pixi.lock
|
| 127 |
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
| 128 |
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
| 129 |
+
.pixi
|
| 130 |
+
|
| 131 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
| 132 |
+
__pypackages__/
|
| 133 |
+
|
| 134 |
+
# Celery stuff
|
| 135 |
+
celerybeat-schedule
|
| 136 |
+
celerybeat.pid
|
| 137 |
+
|
| 138 |
+
# SageMath parsed files
|
| 139 |
+
*.sage.py
|
| 140 |
+
|
| 141 |
+
# Environments
|
| 142 |
+
.env
|
| 143 |
+
.envrc
|
| 144 |
+
.venv
|
| 145 |
+
env/
|
| 146 |
+
venv/
|
| 147 |
+
ENV/
|
| 148 |
+
env.bak/
|
| 149 |
+
venv.bak/
|
| 150 |
+
|
| 151 |
+
# Spyder project settings
|
| 152 |
+
.spyderproject
|
| 153 |
+
.spyproject
|
| 154 |
+
|
| 155 |
+
# Rope project settings
|
| 156 |
+
.ropeproject
|
| 157 |
+
|
| 158 |
+
# mkdocs documentation
|
| 159 |
+
/site
|
| 160 |
+
|
| 161 |
+
# mypy
|
| 162 |
+
.mypy_cache/
|
| 163 |
+
.dmypy.json
|
| 164 |
+
dmypy.json
|
| 165 |
+
|
| 166 |
+
# Pyre type checker
|
| 167 |
+
.pyre/
|
| 168 |
+
|
| 169 |
+
# pytype static type analyzer
|
| 170 |
+
.pytype/
|
| 171 |
+
|
| 172 |
+
# Cython debug symbols
|
| 173 |
+
cython_debug/
|
| 174 |
+
|
| 175 |
+
# PyCharm
|
| 176 |
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
| 177 |
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
| 178 |
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
| 179 |
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
| 180 |
+
#.idea/
|
| 181 |
+
|
| 182 |
+
# Abstra
|
| 183 |
+
# Abstra is an AI-powered process automation framework.
|
| 184 |
+
# Ignore directories containing user credentials, local state, and settings.
|
| 185 |
+
# Learn more at https://abstra.io/docs
|
| 186 |
+
.abstra/
|
| 187 |
+
|
| 188 |
+
# Visual Studio Code
|
| 189 |
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
| 190 |
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
| 191 |
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
| 192 |
+
# you could uncomment the following to ignore the entire vscode folder
|
| 193 |
+
# .vscode/
|
| 194 |
+
|
| 195 |
+
# Ruff stuff:
|
| 196 |
+
.ruff_cache/
|
| 197 |
+
|
| 198 |
+
# PyPI configuration file
|
| 199 |
+
.pypirc
|
| 200 |
+
|
| 201 |
+
# Cursor
|
| 202 |
+
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
|
| 203 |
+
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
| 204 |
+
# refer to https://docs.cursor.com/context/ignore-files
|
| 205 |
+
.cursorignore
|
| 206 |
+
.cursorindexingignore
|
| 207 |
+
|
| 208 |
+
# Marimo
|
| 209 |
+
marimo/_static/
|
| 210 |
+
marimo/_lsp/
|
| 211 |
+
__marimo__/
|
| 212 |
+
tests/
|
| 213 |
+
checkpoints/
|
| 214 |
+
playground.ipynb
|
| 215 |
+
.history/
|
| 216 |
+
upload_checkpoints.sh
|
| 217 |
+
checkpoints.7z
|
| 218 |
+
README_old.md
|
| 219 |
+
discord_bot/
|
| 220 |
+
feishu_bot/
|
| 221 |
+
tmp*
|
| 222 |
+
torchinductor_root/
|
| 223 |
+
scripts/
|
| 224 |
+
checkpoints_legacy/
|
| 225 |
+
lora_output/
|
| 226 |
+
datasets/
|
| 227 |
+
python_embeded/
|
| 228 |
+
checkpoints_pack/
|
Dockerfile
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# HuggingFace Space Docker SDK
|
| 2 |
+
# Use slim Python image - HuggingFace GPU Spaces provide CUDA runtime
|
| 3 |
+
FROM python:3.11-slim
|
| 4 |
+
|
| 5 |
+
# Set environment variables
|
| 6 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 7 |
+
PYTHONUNBUFFERED=1 \
|
| 8 |
+
DEBIAN_FRONTEND=noninteractive \
|
| 9 |
+
TORCHAUDIO_USE_TORCHCODEC=0
|
| 10 |
+
|
| 11 |
+
# Install system dependencies
|
| 12 |
+
# build-essential is required for triton to compile CUDA kernels
|
| 13 |
+
# ffmpeg and libav* dev packages are required for torchaudio's ffmpeg backend
|
| 14 |
+
# Note: torchaudio's ffmpeg backend needs shared libraries, not just the ffmpeg binary
|
| 15 |
+
RUN apt-get update && \
|
| 16 |
+
apt-get install -y --no-install-recommends git libsndfile1 build-essential && \
|
| 17 |
+
apt-get install -y ffmpeg libavcodec-dev libavformat-dev libavutil-dev libswresample-dev && \
|
| 18 |
+
rm -rf /var/lib/apt/lists/*
|
| 19 |
+
|
| 20 |
+
# Set up a new user named "user" with user ID 1000 (HuggingFace Space requirement)
|
| 21 |
+
RUN useradd -m -u 1000 user
|
| 22 |
+
|
| 23 |
+
# Create /data directory with proper permissions for persistent storage
|
| 24 |
+
RUN mkdir -p /data && chown user:user /data && chmod 755 /data
|
| 25 |
+
|
| 26 |
+
# Set environment variables for user
|
| 27 |
+
ENV HOME=/home/user \
|
| 28 |
+
PATH=/home/user/.local/bin:$PATH \
|
| 29 |
+
GRADIO_SERVER_NAME=0.0.0.0 \
|
| 30 |
+
GRADIO_SERVER_PORT=7860
|
| 31 |
+
|
| 32 |
+
# Set the working directory
|
| 33 |
+
WORKDIR $HOME/app
|
| 34 |
+
|
| 35 |
+
# Copy requirements first for better Docker layer caching
|
| 36 |
+
COPY --chown=user:user requirements.txt .
|
| 37 |
+
|
| 38 |
+
# Copy the local nano-vllm package
|
| 39 |
+
COPY --chown=user:user acestep/third_parts/nano-vllm ./acestep/third_parts/nano-vllm
|
| 40 |
+
|
| 41 |
+
# Switch to user before installing packages
|
| 42 |
+
USER user
|
| 43 |
+
|
| 44 |
+
# Install dependencies from requirements.txt (includes PyTorch with CUDA from --extra-index-url)
|
| 45 |
+
RUN pip install --no-cache-dir --user -r requirements.txt
|
| 46 |
+
|
| 47 |
+
# Install nano-vllm with --no-deps since all dependencies are already installed
|
| 48 |
+
RUN pip install --no-deps ./acestep/third_parts/nano-vllm
|
| 49 |
+
|
| 50 |
+
# Copy the rest of the application
|
| 51 |
+
COPY --chown=user:user . .
|
| 52 |
+
|
| 53 |
+
# Expose port
|
| 54 |
+
EXPOSE 7860
|
| 55 |
+
|
| 56 |
+
# Run the application
|
| 57 |
+
CMD ["python", "app.py"]
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 ACEStep
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
README.md
CHANGED
|
@@ -1,13 +1,23 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version: 6.
|
| 8 |
-
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: ACE-Step Worker
|
| 3 |
+
emoji: 🎵
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 6.2.0
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
---
|
| 11 |
|
| 12 |
+
# ACE-Step v1.5 Worker
|
| 13 |
+
|
| 14 |
+
2B-Studio Free-Modell-Worker auf Basis von [ACE-Step/Ace-Step-v1.5](https://huggingface.co/spaces/ACE-Step/Ace-Step-v1.5).
|
| 15 |
+
|
| 16 |
+
- DiT: `acestep-v15-xl-turbo`
|
| 17 |
+
- 5Hz-LM: `acestep-5Hz-lm-1.7B` (Chain-of-Thought, PyTorch-Backend)
|
| 18 |
+
- Endpoint: `POST /generate` (Gradio-API) mit `(prompt, seconds, seed, steps, instrumental)`
|
| 19 |
+
- ZeroGPU: `@spaces.GPU` auf dem Top-Level-Handler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|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ACE-Step V1.5 Pipeline
|
| 3 |
+
Handler wrapper connecting model and UI
|
| 4 |
+
"""
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
|
| 8 |
+
# Load environment variables from .env file in project root
|
| 9 |
+
# This allows configuration without hardcoding values
|
| 10 |
+
# Falls back to .env.example if .env is not found
|
| 11 |
+
try:
|
| 12 |
+
from dotenv import load_dotenv
|
| 13 |
+
# Get project root directory
|
| 14 |
+
_current_file = os.path.abspath(__file__)
|
| 15 |
+
_project_root = os.path.dirname(os.path.dirname(_current_file))
|
| 16 |
+
_env_path = os.path.join(_project_root, '.env')
|
| 17 |
+
_env_example_path = os.path.join(_project_root, '.env.example')
|
| 18 |
+
|
| 19 |
+
if os.path.exists(_env_path):
|
| 20 |
+
load_dotenv(_env_path)
|
| 21 |
+
print(f"Loaded configuration from {_env_path}")
|
| 22 |
+
elif os.path.exists(_env_example_path):
|
| 23 |
+
load_dotenv(_env_example_path)
|
| 24 |
+
print(f"Loaded configuration from {_env_example_path} (fallback)")
|
| 25 |
+
except ImportError:
|
| 26 |
+
# python-dotenv not installed, skip loading .env
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
# Clear proxy settings that may affect Gradio
|
| 30 |
+
for proxy_var in ['http_proxy', 'https_proxy', 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY']:
|
| 31 |
+
os.environ.pop(proxy_var, None)
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
# When executed as a module: `python -m acestep.acestep_v15_pipeline`
|
| 35 |
+
from .handler import AceStepHandler
|
| 36 |
+
from .llm_inference import LLMHandler
|
| 37 |
+
from .dataset_handler import DatasetHandler
|
| 38 |
+
from .gradio_ui import create_gradio_interface
|
| 39 |
+
except ImportError:
|
| 40 |
+
# When executed as a script: `python acestep/acestep_v15_pipeline.py`
|
| 41 |
+
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 42 |
+
if project_root not in sys.path:
|
| 43 |
+
sys.path.insert(0, project_root)
|
| 44 |
+
from acestep.handler import AceStepHandler
|
| 45 |
+
from acestep.llm_inference import LLMHandler
|
| 46 |
+
from acestep.dataset_handler import DatasetHandler
|
| 47 |
+
from acestep.gradio_ui import create_gradio_interface
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def create_demo(init_params=None, language='en'):
|
| 51 |
+
"""
|
| 52 |
+
Create Gradio demo interface
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
init_params: Dictionary containing initialization parameters and state.
|
| 56 |
+
If None, service will not be pre-initialized.
|
| 57 |
+
Keys: 'pre_initialized' (bool), 'checkpoint', 'config_path', 'device',
|
| 58 |
+
'init_llm', 'lm_model_path', 'backend', 'use_flash_attention',
|
| 59 |
+
'offload_to_cpu', 'offload_dit_to_cpu', 'init_status',
|
| 60 |
+
'dit_handler', 'llm_handler' (initialized handlers if pre-initialized),
|
| 61 |
+
'language' (UI language code)
|
| 62 |
+
language: UI language code ('en', 'zh', 'ja', default: 'en')
|
| 63 |
+
|
| 64 |
+
Returns:
|
| 65 |
+
Gradio Blocks instance
|
| 66 |
+
"""
|
| 67 |
+
# Get persistent storage path from init_params (for HuggingFace Space)
|
| 68 |
+
persistent_storage_path = None
|
| 69 |
+
if init_params:
|
| 70 |
+
persistent_storage_path = init_params.get('persistent_storage_path')
|
| 71 |
+
|
| 72 |
+
# Use pre-initialized handlers if available, otherwise create new ones
|
| 73 |
+
if init_params and init_params.get('pre_initialized') and 'dit_handler' in init_params:
|
| 74 |
+
dit_handler = init_params['dit_handler']
|
| 75 |
+
llm_handler = init_params['llm_handler']
|
| 76 |
+
else:
|
| 77 |
+
dit_handler = AceStepHandler(persistent_storage_path=persistent_storage_path)
|
| 78 |
+
llm_handler = LLMHandler(persistent_storage_path=persistent_storage_path)
|
| 79 |
+
|
| 80 |
+
dataset_handler = DatasetHandler() # Dataset handler
|
| 81 |
+
|
| 82 |
+
# Create Gradio interface with all handlers and initialization parameters
|
| 83 |
+
demo = create_gradio_interface(dit_handler, llm_handler, dataset_handler, init_params=init_params, language=language)
|
| 84 |
+
|
| 85 |
+
return demo
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def get_gpu_memory_gb():
|
| 89 |
+
"""
|
| 90 |
+
Get GPU memory in GB. Returns 0 if no GPU is available.
|
| 91 |
+
"""
|
| 92 |
+
try:
|
| 93 |
+
import torch
|
| 94 |
+
if torch.cuda.is_available():
|
| 95 |
+
# Get total memory of the first GPU in GB
|
| 96 |
+
total_memory = torch.cuda.get_device_properties(0).total_memory
|
| 97 |
+
memory_gb = total_memory / (1024**3) # Convert bytes to GB
|
| 98 |
+
return memory_gb
|
| 99 |
+
else:
|
| 100 |
+
return 0
|
| 101 |
+
except Exception as e:
|
| 102 |
+
print(f"Warning: Failed to detect GPU memory: {e}", file=sys.stderr)
|
| 103 |
+
return 0
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def main():
|
| 107 |
+
"""Main entry function"""
|
| 108 |
+
import argparse
|
| 109 |
+
|
| 110 |
+
# Detect GPU memory to auto-configure offload settings
|
| 111 |
+
gpu_memory_gb = get_gpu_memory_gb()
|
| 112 |
+
auto_offload = gpu_memory_gb > 0 and gpu_memory_gb < 16
|
| 113 |
+
|
| 114 |
+
if auto_offload:
|
| 115 |
+
print(f"Detected GPU memory: {gpu_memory_gb:.2f} GB (< 16GB)")
|
| 116 |
+
print("Auto-enabling CPU offload to reduce GPU memory usage")
|
| 117 |
+
elif gpu_memory_gb > 0:
|
| 118 |
+
print(f"Detected GPU memory: {gpu_memory_gb:.2f} GB (>= 16GB)")
|
| 119 |
+
print("CPU offload disabled by default")
|
| 120 |
+
else:
|
| 121 |
+
print("No GPU detected, running on CPU")
|
| 122 |
+
|
| 123 |
+
parser = argparse.ArgumentParser(description="Gradio Demo for ACE-Step V1.5")
|
| 124 |
+
parser.add_argument("--port", type=int, default=7860, help="Port to run the gradio server on")
|
| 125 |
+
parser.add_argument("--share", action="store_true", help="Create a public link")
|
| 126 |
+
parser.add_argument("--debug", action="store_true", help="Enable debug mode")
|
| 127 |
+
parser.add_argument("--server-name", type=str, default="127.0.0.1", help="Server name (default: 127.0.0.1, use 0.0.0.0 for all interfaces)")
|
| 128 |
+
parser.add_argument("--language", type=str, default="en", choices=["en", "zh", "ja"], help="UI language: en (English), zh (中文), ja (日本語)")
|
| 129 |
+
|
| 130 |
+
# Service mode argument
|
| 131 |
+
parser.add_argument("--service_mode", type=lambda x: x.lower() in ['true', '1', 'yes'], default=False,
|
| 132 |
+
help="Enable service mode (default: False). When enabled, uses preset models and restricts UI options.")
|
| 133 |
+
|
| 134 |
+
# Service initialization arguments
|
| 135 |
+
parser.add_argument("--init_service", type=lambda x: x.lower() in ['true', '1', 'yes'], default=False, help="Initialize service on startup (default: False)")
|
| 136 |
+
parser.add_argument("--checkpoint", type=str, default=None, help="Checkpoint file path (optional, for display purposes)")
|
| 137 |
+
parser.add_argument("--config_path", type=str, default=None, help="Main model path (e.g., 'acestep-v15-turbo')")
|
| 138 |
+
parser.add_argument("--device", type=str, default="auto", choices=["auto", "cuda", "cpu"], help="Processing device (default: auto)")
|
| 139 |
+
parser.add_argument("--init_llm", type=lambda x: x.lower() in ['true', '1', 'yes'], default=True, help="Initialize 5Hz LM (default: True)")
|
| 140 |
+
parser.add_argument("--lm_model_path", type=str, default=None, help="5Hz LM model path (e.g., 'acestep-5Hz-lm-0.6B')")
|
| 141 |
+
parser.add_argument("--backend", type=str, default="vllm", choices=["vllm", "pt"], help="5Hz LM backend (default: vllm)")
|
| 142 |
+
parser.add_argument("--use_flash_attention", type=lambda x: x.lower() in ['true', '1', 'yes'], default=None, help="Use flash attention (default: auto-detect)")
|
| 143 |
+
parser.add_argument("--offload_to_cpu", type=lambda x: x.lower() in ['true', '1', 'yes'], default=auto_offload, help=f"Offload models to CPU (default: {'True' if auto_offload else 'False'}, auto-detected based on GPU VRAM)")
|
| 144 |
+
parser.add_argument("--offload_dit_to_cpu", type=lambda x: x.lower() in ['true', '1', 'yes'], default=False, help="Offload DiT to CPU (default: False)")
|
| 145 |
+
|
| 146 |
+
args = parser.parse_args()
|
| 147 |
+
|
| 148 |
+
# Service mode defaults (can be configured via .env file)
|
| 149 |
+
if args.service_mode:
|
| 150 |
+
print("Service mode enabled - applying preset configurations...")
|
| 151 |
+
# Force init_service in service mode
|
| 152 |
+
args.init_service = True
|
| 153 |
+
# Default DiT model for service mode (from env or fallback)
|
| 154 |
+
if args.config_path is None:
|
| 155 |
+
args.config_path = os.environ.get(
|
| 156 |
+
"SERVICE_MODE_DIT_MODEL",
|
| 157 |
+
"acestep-v15-turbo-fix-inst-shift-dynamic"
|
| 158 |
+
)
|
| 159 |
+
# Default LM model for service mode (from env or fallback)
|
| 160 |
+
if args.lm_model_path is None:
|
| 161 |
+
args.lm_model_path = os.environ.get(
|
| 162 |
+
"SERVICE_MODE_LM_MODEL",
|
| 163 |
+
"acestep-5Hz-lm-1.7B-v4-fix"
|
| 164 |
+
)
|
| 165 |
+
# Backend for service mode (from env or fallback to vllm)
|
| 166 |
+
args.backend = os.environ.get("SERVICE_MODE_BACKEND", "vllm")
|
| 167 |
+
print(f" DiT model: {args.config_path}")
|
| 168 |
+
print(f" LM model: {args.lm_model_path}")
|
| 169 |
+
print(f" Backend: {args.backend}")
|
| 170 |
+
|
| 171 |
+
try:
|
| 172 |
+
init_params = None
|
| 173 |
+
|
| 174 |
+
# If init_service is True, perform initialization before creating UI
|
| 175 |
+
if args.init_service:
|
| 176 |
+
print("Initializing service from command line...")
|
| 177 |
+
|
| 178 |
+
# Create handler instances for initialization
|
| 179 |
+
dit_handler = AceStepHandler()
|
| 180 |
+
llm_handler = LLMHandler()
|
| 181 |
+
|
| 182 |
+
# Auto-select config_path if not provided
|
| 183 |
+
if args.config_path is None:
|
| 184 |
+
available_models = dit_handler.get_available_acestep_v15_models()
|
| 185 |
+
if available_models:
|
| 186 |
+
args.config_path = "acestep-v15-turbo" if "acestep-v15-turbo" in available_models else available_models[0]
|
| 187 |
+
print(f"Auto-selected config_path: {args.config_path}")
|
| 188 |
+
else:
|
| 189 |
+
print("Error: No available models found. Please specify --config_path", file=sys.stderr)
|
| 190 |
+
sys.exit(1)
|
| 191 |
+
|
| 192 |
+
# Get project root (same logic as in handler)
|
| 193 |
+
current_file = os.path.abspath(__file__)
|
| 194 |
+
project_root = os.path.dirname(os.path.dirname(current_file))
|
| 195 |
+
|
| 196 |
+
# Determine flash attention setting
|
| 197 |
+
use_flash_attention = args.use_flash_attention
|
| 198 |
+
if use_flash_attention is None:
|
| 199 |
+
use_flash_attention = dit_handler.is_flash_attention_available()
|
| 200 |
+
|
| 201 |
+
# Initialize DiT handler
|
| 202 |
+
print(f"Initializing DiT model: {args.config_path} on {args.device}...")
|
| 203 |
+
init_status, enable_generate = dit_handler.initialize_service(
|
| 204 |
+
project_root=project_root,
|
| 205 |
+
config_path=args.config_path,
|
| 206 |
+
device=args.device,
|
| 207 |
+
use_flash_attention=use_flash_attention,
|
| 208 |
+
compile_model=False,
|
| 209 |
+
offload_to_cpu=args.offload_to_cpu,
|
| 210 |
+
offload_dit_to_cpu=args.offload_dit_to_cpu
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
if not enable_generate:
|
| 214 |
+
print(f"Error initializing DiT model: {init_status}", file=sys.stderr)
|
| 215 |
+
sys.exit(1)
|
| 216 |
+
|
| 217 |
+
print(f"DiT model initialized successfully")
|
| 218 |
+
|
| 219 |
+
# Initialize LM handler if requested
|
| 220 |
+
lm_status = ""
|
| 221 |
+
if args.init_llm:
|
| 222 |
+
if args.lm_model_path is None:
|
| 223 |
+
# Try to get default LM model
|
| 224 |
+
available_lm_models = llm_handler.get_available_5hz_lm_models()
|
| 225 |
+
if available_lm_models:
|
| 226 |
+
args.lm_model_path = available_lm_models[0]
|
| 227 |
+
print(f"Using default LM model: {args.lm_model_path}")
|
| 228 |
+
else:
|
| 229 |
+
print("Warning: No LM models available, skipping LM initialization", file=sys.stderr)
|
| 230 |
+
args.init_llm = False
|
| 231 |
+
|
| 232 |
+
if args.init_llm and args.lm_model_path:
|
| 233 |
+
checkpoint_dir = os.path.join(project_root, "checkpoints")
|
| 234 |
+
print(f"Initializing 5Hz LM: {args.lm_model_path} on {args.device}...")
|
| 235 |
+
lm_status, lm_success = llm_handler.initialize(
|
| 236 |
+
checkpoint_dir=checkpoint_dir,
|
| 237 |
+
lm_model_path=args.lm_model_path,
|
| 238 |
+
backend=args.backend,
|
| 239 |
+
device=args.device,
|
| 240 |
+
offload_to_cpu=args.offload_to_cpu,
|
| 241 |
+
dtype=dit_handler.dtype
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
if lm_success:
|
| 245 |
+
print(f"5Hz LM initialized successfully")
|
| 246 |
+
init_status += f"\n{lm_status}"
|
| 247 |
+
else:
|
| 248 |
+
print(f"Warning: 5Hz LM initialization failed: {lm_status}", file=sys.stderr)
|
| 249 |
+
init_status += f"\n{lm_status}"
|
| 250 |
+
|
| 251 |
+
# Prepare initialization parameters for UI
|
| 252 |
+
init_params = {
|
| 253 |
+
'pre_initialized': True,
|
| 254 |
+
'service_mode': args.service_mode,
|
| 255 |
+
'checkpoint': args.checkpoint,
|
| 256 |
+
'config_path': args.config_path,
|
| 257 |
+
'device': args.device,
|
| 258 |
+
'init_llm': args.init_llm,
|
| 259 |
+
'lm_model_path': args.lm_model_path,
|
| 260 |
+
'backend': args.backend,
|
| 261 |
+
'use_flash_attention': use_flash_attention,
|
| 262 |
+
'offload_to_cpu': args.offload_to_cpu,
|
| 263 |
+
'offload_dit_to_cpu': args.offload_dit_to_cpu,
|
| 264 |
+
'init_status': init_status,
|
| 265 |
+
'enable_generate': enable_generate,
|
| 266 |
+
'dit_handler': dit_handler,
|
| 267 |
+
'llm_handler': llm_handler,
|
| 268 |
+
'language': args.language
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
print("Service initialization completed successfully!")
|
| 272 |
+
|
| 273 |
+
# Create and launch demo
|
| 274 |
+
print(f"Creating Gradio interface with language: {args.language}...")
|
| 275 |
+
demo = create_demo(init_params=init_params, language=args.language)
|
| 276 |
+
|
| 277 |
+
# Enable queue for multi-user support
|
| 278 |
+
# This ensures proper request queuing and prevents concurrent generation conflicts
|
| 279 |
+
print("Enabling queue for multi-user support...")
|
| 280 |
+
demo.queue(
|
| 281 |
+
max_size=20, # Maximum queue size (adjust based on your needs)
|
| 282 |
+
status_update_rate="auto", # Update rate for queue status
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
print(f"Launching server on {args.server_name}:{args.port}...")
|
| 286 |
+
demo.launch(
|
| 287 |
+
server_name=args.server_name,
|
| 288 |
+
server_port=args.port,
|
| 289 |
+
share=args.share,
|
| 290 |
+
debug=args.debug,
|
| 291 |
+
show_error=True,
|
| 292 |
+
prevent_thread_lock=False, # Keep thread locked to maintain server running
|
| 293 |
+
inbrowser=False, # Don't auto-open browser
|
| 294 |
+
)
|
| 295 |
+
except Exception as e:
|
| 296 |
+
print(f"Error launching Gradio: {e}", file=sys.stderr)
|
| 297 |
+
import traceback
|
| 298 |
+
traceback.print_exc()
|
| 299 |
+
sys.exit(1)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
if __name__ == "__main__":
|
| 303 |
+
main()
|
acestep/api_server.py
ADDED
|
@@ -0,0 +1,1700 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FastAPI server for ACE-Step V1.5.
|
| 2 |
+
|
| 3 |
+
Endpoints:
|
| 4 |
+
- POST /release_task Create music generation task
|
| 5 |
+
- POST /query_result Batch query task results
|
| 6 |
+
- POST /v1/music/random Create random sample task
|
| 7 |
+
- GET /v1/models List available models
|
| 8 |
+
- GET /v1/audio Download audio file
|
| 9 |
+
- GET /health Health check
|
| 10 |
+
|
| 11 |
+
NOTE:
|
| 12 |
+
- In-memory queue and job store -> run uvicorn with workers=1.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import asyncio
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import sys
|
| 21 |
+
import time
|
| 22 |
+
import traceback
|
| 23 |
+
import tempfile
|
| 24 |
+
import urllib.parse
|
| 25 |
+
from collections import deque
|
| 26 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 27 |
+
from contextlib import asynccontextmanager
|
| 28 |
+
from dataclasses import dataclass
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
from threading import Lock
|
| 31 |
+
from typing import Any, Dict, List, Literal, Optional
|
| 32 |
+
from uuid import uuid4
|
| 33 |
+
|
| 34 |
+
try:
|
| 35 |
+
from dotenv import load_dotenv
|
| 36 |
+
except ImportError: # Optional dependency
|
| 37 |
+
load_dotenv = None # type: ignore
|
| 38 |
+
|
| 39 |
+
from fastapi import FastAPI, HTTPException, Request
|
| 40 |
+
from pydantic import BaseModel, Field
|
| 41 |
+
from starlette.datastructures import UploadFile as StarletteUploadFile
|
| 42 |
+
|
| 43 |
+
from acestep.handler import AceStepHandler
|
| 44 |
+
from acestep.llm_inference import LLMHandler
|
| 45 |
+
from acestep.constants import (
|
| 46 |
+
DEFAULT_DIT_INSTRUCTION,
|
| 47 |
+
DEFAULT_LM_INSTRUCTION,
|
| 48 |
+
TASK_INSTRUCTIONS,
|
| 49 |
+
)
|
| 50 |
+
from acestep.inference import (
|
| 51 |
+
GenerationParams,
|
| 52 |
+
GenerationConfig,
|
| 53 |
+
generate_music,
|
| 54 |
+
create_sample,
|
| 55 |
+
format_sample,
|
| 56 |
+
)
|
| 57 |
+
from acestep.gradio_ui.events.results_handlers import _build_generation_info
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# =============================================================================
|
| 61 |
+
# Constants
|
| 62 |
+
# =============================================================================
|
| 63 |
+
|
| 64 |
+
RESULT_KEY_PREFIX = "ace_step_v1.5_"
|
| 65 |
+
RESULT_EXPIRE_SECONDS = 7 * 24 * 60 * 60 # 7 days
|
| 66 |
+
TASK_TIMEOUT_SECONDS = 3600 # 1 hour
|
| 67 |
+
STATUS_MAP = {"queued": 0, "running": 0, "succeeded": 1, "failed": 2}
|
| 68 |
+
|
| 69 |
+
LM_DEFAULT_TEMPERATURE = 0.85
|
| 70 |
+
LM_DEFAULT_CFG_SCALE = 2.5
|
| 71 |
+
LM_DEFAULT_TOP_P = 0.9
|
| 72 |
+
|
| 73 |
+
# Parameter aliases for request parsing
|
| 74 |
+
PARAM_ALIASES = {
|
| 75 |
+
"prompt": ["prompt"],
|
| 76 |
+
"sample_mode": ["sample_mode", "sampleMode"],
|
| 77 |
+
"sample_query": ["sample_query", "sampleQuery", "description", "desc"],
|
| 78 |
+
"use_format": ["use_format", "useFormat", "format"],
|
| 79 |
+
"model": ["model", "dit_model", "ditModel"],
|
| 80 |
+
"key_scale": ["key_scale", "keyscale", "keyScale"],
|
| 81 |
+
"time_signature": ["time_signature", "timesignature", "timeSignature"],
|
| 82 |
+
"audio_duration": ["audio_duration", "duration", "audioDuration", "target_duration", "targetDuration"],
|
| 83 |
+
"vocal_language": ["vocal_language", "vocalLanguage"],
|
| 84 |
+
"inference_steps": ["inference_steps", "inferenceSteps"],
|
| 85 |
+
"guidance_scale": ["guidance_scale", "guidanceScale"],
|
| 86 |
+
"use_random_seed": ["use_random_seed", "useRandomSeed"],
|
| 87 |
+
"audio_code_string": ["audio_code_string", "audioCodeString"],
|
| 88 |
+
"audio_cover_strength": ["audio_cover_strength", "audioCoverStrength"],
|
| 89 |
+
"task_type": ["task_type", "taskType"],
|
| 90 |
+
"infer_method": ["infer_method", "inferMethod"],
|
| 91 |
+
"use_tiled_decode": ["use_tiled_decode", "useTiledDecode"],
|
| 92 |
+
"constrained_decoding": ["constrained_decoding", "constrainedDecoding", "constrained"],
|
| 93 |
+
"constrained_decoding_debug": ["constrained_decoding_debug", "constrainedDecodingDebug"],
|
| 94 |
+
"use_cot_caption": ["use_cot_caption", "cot_caption", "cot-caption"],
|
| 95 |
+
"use_cot_language": ["use_cot_language", "cot_language", "cot-language"],
|
| 96 |
+
"is_format_caption": ["is_format_caption", "isFormatCaption"],
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _parse_description_hints(description: str) -> tuple[Optional[str], bool]:
|
| 101 |
+
"""
|
| 102 |
+
Parse a description string to extract language code and instrumental flag.
|
| 103 |
+
|
| 104 |
+
This function analyzes user descriptions like "Pop rock. English" or "piano solo"
|
| 105 |
+
to detect:
|
| 106 |
+
- Language: Maps language names to ISO codes (e.g., "English" -> "en")
|
| 107 |
+
- Instrumental: Detects patterns indicating instrumental/no-vocal music
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
description: User's natural language music description
|
| 111 |
+
|
| 112 |
+
Returns:
|
| 113 |
+
(language_code, is_instrumental) tuple:
|
| 114 |
+
- language_code: ISO language code (e.g., "en", "zh") or None if not detected
|
| 115 |
+
- is_instrumental: True if description indicates instrumental music
|
| 116 |
+
"""
|
| 117 |
+
import re
|
| 118 |
+
|
| 119 |
+
if not description:
|
| 120 |
+
return None, False
|
| 121 |
+
|
| 122 |
+
description_lower = description.lower().strip()
|
| 123 |
+
|
| 124 |
+
# Language mapping: input patterns -> ISO code
|
| 125 |
+
language_mapping = {
|
| 126 |
+
'english': 'en', 'en': 'en',
|
| 127 |
+
'chinese': 'zh', '中文': 'zh', 'zh': 'zh', 'mandarin': 'zh',
|
| 128 |
+
'japanese': 'ja', '日本語': 'ja', 'ja': 'ja',
|
| 129 |
+
'korean': 'ko', '한국어': 'ko', 'ko': 'ko',
|
| 130 |
+
'spanish': 'es', 'español': 'es', 'es': 'es',
|
| 131 |
+
'french': 'fr', 'français': 'fr', 'fr': 'fr',
|
| 132 |
+
'german': 'de', 'deutsch': 'de', 'de': 'de',
|
| 133 |
+
'italian': 'it', 'italiano': 'it', 'it': 'it',
|
| 134 |
+
'portuguese': 'pt', 'português': 'pt', 'pt': 'pt',
|
| 135 |
+
'russian': 'ru', 'русский': 'ru', 'ru': 'ru',
|
| 136 |
+
'bengali': 'bn', 'bn': 'bn',
|
| 137 |
+
'hindi': 'hi', 'hi': 'hi',
|
| 138 |
+
'arabic': 'ar', 'ar': 'ar',
|
| 139 |
+
'thai': 'th', 'th': 'th',
|
| 140 |
+
'vietnamese': 'vi', 'vi': 'vi',
|
| 141 |
+
'indonesian': 'id', 'id': 'id',
|
| 142 |
+
'turkish': 'tr', 'tr': 'tr',
|
| 143 |
+
'dutch': 'nl', 'nl': 'nl',
|
| 144 |
+
'polish': 'pl', 'pl': 'pl',
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
# Detect language
|
| 148 |
+
detected_language = None
|
| 149 |
+
for lang_name, lang_code in language_mapping.items():
|
| 150 |
+
if len(lang_name) <= 2:
|
| 151 |
+
pattern = r'(?:^|\s|[.,;:!?])' + re.escape(lang_name) + r'(?:$|\s|[.,;:!?])'
|
| 152 |
+
else:
|
| 153 |
+
pattern = r'\b' + re.escape(lang_name) + r'\b'
|
| 154 |
+
|
| 155 |
+
if re.search(pattern, description_lower):
|
| 156 |
+
detected_language = lang_code
|
| 157 |
+
break
|
| 158 |
+
|
| 159 |
+
# Detect instrumental
|
| 160 |
+
is_instrumental = False
|
| 161 |
+
if 'instrumental' in description_lower:
|
| 162 |
+
is_instrumental = True
|
| 163 |
+
elif 'pure music' in description_lower or 'pure instrument' in description_lower:
|
| 164 |
+
is_instrumental = True
|
| 165 |
+
elif description_lower.endswith(' solo') or description_lower == 'solo':
|
| 166 |
+
is_instrumental = True
|
| 167 |
+
|
| 168 |
+
return detected_language, is_instrumental
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
JobStatus = Literal["queued", "running", "succeeded", "failed"]
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class GenerateMusicRequest(BaseModel):
|
| 175 |
+
prompt: str = Field(default="", description="Text prompt describing the music")
|
| 176 |
+
lyrics: str = Field(default="", description="Lyric text")
|
| 177 |
+
|
| 178 |
+
# New API semantics:
|
| 179 |
+
# - thinking=True: use 5Hz LM to generate audio codes (lm-dit behavior)
|
| 180 |
+
# - thinking=False: do not use LM to generate codes (dit behavior)
|
| 181 |
+
# Regardless of thinking, if some metas are missing, server may use LM to fill them.
|
| 182 |
+
thinking: bool = False
|
| 183 |
+
# Sample-mode requests auto-generate caption/lyrics/metas via LM (no user prompt).
|
| 184 |
+
sample_mode: bool = False
|
| 185 |
+
# Description for sample mode: auto-generate caption/lyrics from description query
|
| 186 |
+
sample_query: str = Field(default="", description="Query/description for sample mode (use create_sample)")
|
| 187 |
+
# Whether to use format_sample() to enhance input caption/lyrics
|
| 188 |
+
use_format: bool = Field(default=False, description="Use format_sample() to enhance input (default: False)")
|
| 189 |
+
# Model name for multi-model support (select which DiT model to use)
|
| 190 |
+
model: Optional[str] = Field(default=None, description="Model name to use (e.g., 'acestep-v15-turbo')")
|
| 191 |
+
|
| 192 |
+
bpm: Optional[int] = None
|
| 193 |
+
# Accept common client keys via manual parsing (see RequestParser).
|
| 194 |
+
key_scale: str = ""
|
| 195 |
+
time_signature: str = ""
|
| 196 |
+
vocal_language: str = "en"
|
| 197 |
+
inference_steps: int = 8
|
| 198 |
+
guidance_scale: float = 7.0
|
| 199 |
+
use_random_seed: bool = True
|
| 200 |
+
seed: int = -1
|
| 201 |
+
|
| 202 |
+
reference_audio_path: Optional[str] = None
|
| 203 |
+
src_audio_path: Optional[str] = None
|
| 204 |
+
audio_duration: Optional[float] = None
|
| 205 |
+
batch_size: Optional[int] = None
|
| 206 |
+
|
| 207 |
+
audio_code_string: str = ""
|
| 208 |
+
|
| 209 |
+
repainting_start: float = 0.0
|
| 210 |
+
repainting_end: Optional[float] = None
|
| 211 |
+
|
| 212 |
+
instruction: str = DEFAULT_DIT_INSTRUCTION
|
| 213 |
+
audio_cover_strength: float = 1.0
|
| 214 |
+
task_type: str = "text2music"
|
| 215 |
+
|
| 216 |
+
use_adg: bool = False
|
| 217 |
+
cfg_interval_start: float = 0.0
|
| 218 |
+
cfg_interval_end: float = 1.0
|
| 219 |
+
infer_method: str = "ode" # "ode" or "sde" - diffusion inference method
|
| 220 |
+
shift: float = Field(
|
| 221 |
+
default=3.0,
|
| 222 |
+
description="Timestep shift factor (range 1.0~5.0, default 3.0). Only effective for base models, not turbo models."
|
| 223 |
+
)
|
| 224 |
+
timesteps: Optional[str] = Field(
|
| 225 |
+
default=None,
|
| 226 |
+
description="Custom timesteps (comma-separated, e.g., '0.97,0.76,0.615,0.5,0.395,0.28,0.18,0.085,0'). Overrides inference_steps and shift."
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
audio_format: str = "mp3"
|
| 230 |
+
use_tiled_decode: bool = True
|
| 231 |
+
|
| 232 |
+
# 5Hz LM (server-side): used for metadata completion and (when thinking=True) codes generation.
|
| 233 |
+
lm_model_path: Optional[str] = None # e.g. "acestep-5Hz-lm-0.6B"
|
| 234 |
+
lm_backend: Literal["vllm", "pt"] = "vllm"
|
| 235 |
+
|
| 236 |
+
constrained_decoding: bool = True
|
| 237 |
+
constrained_decoding_debug: bool = False
|
| 238 |
+
use_cot_caption: bool = True
|
| 239 |
+
use_cot_language: bool = True
|
| 240 |
+
is_format_caption: bool = False
|
| 241 |
+
|
| 242 |
+
lm_temperature: float = 0.85
|
| 243 |
+
lm_cfg_scale: float = 2.5
|
| 244 |
+
lm_top_k: Optional[int] = None
|
| 245 |
+
lm_top_p: Optional[float] = 0.9
|
| 246 |
+
lm_repetition_penalty: float = 1.0
|
| 247 |
+
lm_negative_prompt: str = "NO USER INPUT"
|
| 248 |
+
|
| 249 |
+
class Config:
|
| 250 |
+
allow_population_by_field_name = True
|
| 251 |
+
allow_population_by_alias = True
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class CreateJobResponse(BaseModel):
|
| 255 |
+
task_id: str
|
| 256 |
+
status: JobStatus
|
| 257 |
+
queue_position: int = 0 # 1-based best-effort position when queued
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class JobResult(BaseModel):
|
| 261 |
+
first_audio_path: Optional[str] = None
|
| 262 |
+
second_audio_path: Optional[str] = None
|
| 263 |
+
audio_paths: list[str] = Field(default_factory=list)
|
| 264 |
+
|
| 265 |
+
generation_info: str = ""
|
| 266 |
+
status_message: str = ""
|
| 267 |
+
seed_value: str = ""
|
| 268 |
+
|
| 269 |
+
metas: Dict[str, Any] = Field(default_factory=dict)
|
| 270 |
+
bpm: Optional[int] = None
|
| 271 |
+
duration: Optional[float] = None
|
| 272 |
+
genres: Optional[str] = None
|
| 273 |
+
keyscale: Optional[str] = None
|
| 274 |
+
timesignature: Optional[str] = None
|
| 275 |
+
|
| 276 |
+
# Model information
|
| 277 |
+
lm_model: Optional[str] = None
|
| 278 |
+
dit_model: Optional[str] = None
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
class JobResponse(BaseModel):
|
| 282 |
+
job_id: str
|
| 283 |
+
status: JobStatus
|
| 284 |
+
created_at: float
|
| 285 |
+
started_at: Optional[float] = None
|
| 286 |
+
finished_at: Optional[float] = None
|
| 287 |
+
|
| 288 |
+
# queue observability
|
| 289 |
+
queue_position: int = 0
|
| 290 |
+
eta_seconds: Optional[float] = None
|
| 291 |
+
avg_job_seconds: Optional[float] = None
|
| 292 |
+
|
| 293 |
+
result: Optional[JobResult] = None
|
| 294 |
+
error: Optional[str] = None
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
@dataclass
|
| 298 |
+
class _JobRecord:
|
| 299 |
+
job_id: str
|
| 300 |
+
status: JobStatus
|
| 301 |
+
created_at: float
|
| 302 |
+
started_at: Optional[float] = None
|
| 303 |
+
finished_at: Optional[float] = None
|
| 304 |
+
result: Optional[Dict[str, Any]] = None
|
| 305 |
+
error: Optional[str] = None
|
| 306 |
+
env: str = "development"
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
class _JobStore:
|
| 310 |
+
def __init__(self) -> None:
|
| 311 |
+
self._lock = Lock()
|
| 312 |
+
self._jobs: Dict[str, _JobRecord] = {}
|
| 313 |
+
|
| 314 |
+
def create(self) -> _JobRecord:
|
| 315 |
+
job_id = str(uuid4())
|
| 316 |
+
rec = _JobRecord(job_id=job_id, status="queued", created_at=time.time())
|
| 317 |
+
with self._lock:
|
| 318 |
+
self._jobs[job_id] = rec
|
| 319 |
+
return rec
|
| 320 |
+
|
| 321 |
+
def create_with_id(self, job_id: str, env: str = "development") -> _JobRecord:
|
| 322 |
+
"""Create job record with specified ID"""
|
| 323 |
+
rec = _JobRecord(
|
| 324 |
+
job_id=job_id,
|
| 325 |
+
status="queued",
|
| 326 |
+
created_at=time.time(),
|
| 327 |
+
env=env
|
| 328 |
+
)
|
| 329 |
+
with self._lock:
|
| 330 |
+
self._jobs[job_id] = rec
|
| 331 |
+
return rec
|
| 332 |
+
|
| 333 |
+
def get(self, job_id: str) -> Optional[_JobRecord]:
|
| 334 |
+
with self._lock:
|
| 335 |
+
return self._jobs.get(job_id)
|
| 336 |
+
|
| 337 |
+
def mark_running(self, job_id: str) -> None:
|
| 338 |
+
with self._lock:
|
| 339 |
+
rec = self._jobs[job_id]
|
| 340 |
+
rec.status = "running"
|
| 341 |
+
rec.started_at = time.time()
|
| 342 |
+
|
| 343 |
+
def mark_succeeded(self, job_id: str, result: Dict[str, Any]) -> None:
|
| 344 |
+
with self._lock:
|
| 345 |
+
rec = self._jobs[job_id]
|
| 346 |
+
rec.status = "succeeded"
|
| 347 |
+
rec.finished_at = time.time()
|
| 348 |
+
rec.result = result
|
| 349 |
+
rec.error = None
|
| 350 |
+
|
| 351 |
+
def mark_failed(self, job_id: str, error: str) -> None:
|
| 352 |
+
with self._lock:
|
| 353 |
+
rec = self._jobs[job_id]
|
| 354 |
+
rec.status = "failed"
|
| 355 |
+
rec.finished_at = time.time()
|
| 356 |
+
rec.result = None
|
| 357 |
+
rec.error = error
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def _env_bool(name: str, default: bool) -> bool:
|
| 361 |
+
v = os.getenv(name)
|
| 362 |
+
if v is None:
|
| 363 |
+
return default
|
| 364 |
+
return v.strip().lower() in {"1", "true", "yes", "y", "on"}
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def _get_project_root() -> str:
|
| 368 |
+
current_file = os.path.abspath(__file__)
|
| 369 |
+
return os.path.dirname(os.path.dirname(current_file))
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def _get_model_name(config_path: str) -> str:
|
| 373 |
+
"""
|
| 374 |
+
Extract model name from config_path.
|
| 375 |
+
|
| 376 |
+
Args:
|
| 377 |
+
config_path: Path like "acestep-v15-turbo" or "/path/to/acestep-v15-turbo"
|
| 378 |
+
|
| 379 |
+
Returns:
|
| 380 |
+
Model name (last directory name from config_path)
|
| 381 |
+
"""
|
| 382 |
+
if not config_path:
|
| 383 |
+
return ""
|
| 384 |
+
normalized = config_path.rstrip("/\\")
|
| 385 |
+
return os.path.basename(normalized)
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def _load_project_env() -> None:
|
| 389 |
+
if load_dotenv is None:
|
| 390 |
+
return
|
| 391 |
+
try:
|
| 392 |
+
project_root = _get_project_root()
|
| 393 |
+
env_path = os.path.join(project_root, ".env")
|
| 394 |
+
if os.path.exists(env_path):
|
| 395 |
+
load_dotenv(env_path, override=False)
|
| 396 |
+
except Exception:
|
| 397 |
+
# Optional best-effort: continue even if .env loading fails.
|
| 398 |
+
pass
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
_load_project_env()
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def _to_int(v: Any, default: Optional[int] = None) -> Optional[int]:
|
| 405 |
+
if v is None:
|
| 406 |
+
return default
|
| 407 |
+
if isinstance(v, int):
|
| 408 |
+
return v
|
| 409 |
+
s = str(v).strip()
|
| 410 |
+
if s == "":
|
| 411 |
+
return default
|
| 412 |
+
try:
|
| 413 |
+
return int(s)
|
| 414 |
+
except Exception:
|
| 415 |
+
return default
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def _to_float(v: Any, default: Optional[float] = None) -> Optional[float]:
|
| 419 |
+
if v is None:
|
| 420 |
+
return default
|
| 421 |
+
if isinstance(v, float):
|
| 422 |
+
return v
|
| 423 |
+
s = str(v).strip()
|
| 424 |
+
if s == "":
|
| 425 |
+
return default
|
| 426 |
+
try:
|
| 427 |
+
return float(s)
|
| 428 |
+
except Exception:
|
| 429 |
+
return default
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def _to_bool(v: Any, default: bool = False) -> bool:
|
| 433 |
+
if v is None:
|
| 434 |
+
return default
|
| 435 |
+
if isinstance(v, bool):
|
| 436 |
+
return v
|
| 437 |
+
s = str(v).strip().lower()
|
| 438 |
+
if s == "":
|
| 439 |
+
return default
|
| 440 |
+
return s in {"1", "true", "yes", "y", "on"}
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def _map_status(status: str) -> int:
|
| 444 |
+
"""Map job status string to integer code."""
|
| 445 |
+
return STATUS_MAP.get(status, 2)
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
def _parse_timesteps(s: Optional[str]) -> Optional[List[float]]:
|
| 449 |
+
"""Parse comma-separated timesteps string to list of floats."""
|
| 450 |
+
if not s or not s.strip():
|
| 451 |
+
return None
|
| 452 |
+
try:
|
| 453 |
+
return [float(t.strip()) for t in s.split(",") if t.strip()]
|
| 454 |
+
except (ValueError, Exception):
|
| 455 |
+
return None
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
class RequestParser:
|
| 459 |
+
"""Parse request parameters from multiple sources with alias support."""
|
| 460 |
+
|
| 461 |
+
def __init__(self, raw: dict):
|
| 462 |
+
self._raw = dict(raw) if raw else {}
|
| 463 |
+
self._param_obj = self._parse_json(self._raw.get("param_obj"))
|
| 464 |
+
self._metas = self._find_metas()
|
| 465 |
+
|
| 466 |
+
def _parse_json(self, v) -> dict:
|
| 467 |
+
if isinstance(v, dict):
|
| 468 |
+
return v
|
| 469 |
+
if isinstance(v, str) and v.strip():
|
| 470 |
+
try:
|
| 471 |
+
return json.loads(v)
|
| 472 |
+
except Exception:
|
| 473 |
+
pass
|
| 474 |
+
return {}
|
| 475 |
+
|
| 476 |
+
def _find_metas(self) -> dict:
|
| 477 |
+
for key in ("metas", "meta", "metadata", "user_metadata", "userMetadata"):
|
| 478 |
+
v = self._raw.get(key)
|
| 479 |
+
if v:
|
| 480 |
+
return self._parse_json(v)
|
| 481 |
+
return {}
|
| 482 |
+
|
| 483 |
+
def get(self, name: str, default=None):
|
| 484 |
+
"""Get parameter by canonical name from all sources."""
|
| 485 |
+
aliases = PARAM_ALIASES.get(name, [name])
|
| 486 |
+
for source in (self._raw, self._param_obj, self._metas):
|
| 487 |
+
for alias in aliases:
|
| 488 |
+
v = source.get(alias)
|
| 489 |
+
if v is not None:
|
| 490 |
+
return v
|
| 491 |
+
return default
|
| 492 |
+
|
| 493 |
+
def str(self, name: str, default: str = "") -> str:
|
| 494 |
+
v = self.get(name)
|
| 495 |
+
return str(v) if v is not None else default
|
| 496 |
+
|
| 497 |
+
def int(self, name: str, default: Optional[int] = None) -> Optional[int]:
|
| 498 |
+
return _to_int(self.get(name), default)
|
| 499 |
+
|
| 500 |
+
def float(self, name: str, default: Optional[float] = None) -> Optional[float]:
|
| 501 |
+
return _to_float(self.get(name), default)
|
| 502 |
+
|
| 503 |
+
def bool(self, name: str, default: bool = False) -> bool:
|
| 504 |
+
return _to_bool(self.get(name), default)
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
async def _save_upload_to_temp(upload: StarletteUploadFile, *, prefix: str) -> str:
|
| 508 |
+
suffix = Path(upload.filename or "").suffix
|
| 509 |
+
fd, path = tempfile.mkstemp(prefix=f"{prefix}_", suffix=suffix)
|
| 510 |
+
os.close(fd)
|
| 511 |
+
try:
|
| 512 |
+
with open(path, "wb") as f:
|
| 513 |
+
while True:
|
| 514 |
+
chunk = await upload.read(1024 * 1024)
|
| 515 |
+
if not chunk:
|
| 516 |
+
break
|
| 517 |
+
f.write(chunk)
|
| 518 |
+
except Exception:
|
| 519 |
+
try:
|
| 520 |
+
os.remove(path)
|
| 521 |
+
except Exception:
|
| 522 |
+
pass
|
| 523 |
+
raise
|
| 524 |
+
finally:
|
| 525 |
+
try:
|
| 526 |
+
await upload.close()
|
| 527 |
+
except Exception:
|
| 528 |
+
pass
|
| 529 |
+
return path
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
def create_app() -> FastAPI:
|
| 533 |
+
store = _JobStore()
|
| 534 |
+
|
| 535 |
+
QUEUE_MAXSIZE = int(os.getenv("ACESTEP_QUEUE_MAXSIZE", "200"))
|
| 536 |
+
WORKER_COUNT = int(os.getenv("ACESTEP_QUEUE_WORKERS", "1")) # Single GPU recommended
|
| 537 |
+
|
| 538 |
+
INITIAL_AVG_JOB_SECONDS = float(os.getenv("ACESTEP_AVG_JOB_SECONDS", "5.0"))
|
| 539 |
+
AVG_WINDOW = int(os.getenv("ACESTEP_AVG_WINDOW", "50"))
|
| 540 |
+
|
| 541 |
+
def _path_to_audio_url(path: str) -> str:
|
| 542 |
+
"""Convert local file path to downloadable relative URL"""
|
| 543 |
+
if not path:
|
| 544 |
+
return path
|
| 545 |
+
if path.startswith("http://") or path.startswith("https://"):
|
| 546 |
+
return path
|
| 547 |
+
encoded_path = urllib.parse.quote(path, safe="")
|
| 548 |
+
return f"/v1/audio?path={encoded_path}"
|
| 549 |
+
|
| 550 |
+
@asynccontextmanager
|
| 551 |
+
async def lifespan(app: FastAPI):
|
| 552 |
+
# Clear proxy env that may affect downstream libs
|
| 553 |
+
for proxy_var in ["http_proxy", "https_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"]:
|
| 554 |
+
os.environ.pop(proxy_var, None)
|
| 555 |
+
|
| 556 |
+
# Ensure compilation/temp caches do not fill up small default /tmp.
|
| 557 |
+
# Triton/Inductor (and the system compiler) can create large temporary files.
|
| 558 |
+
project_root = _get_project_root()
|
| 559 |
+
cache_root = os.path.join(project_root, ".cache", "acestep")
|
| 560 |
+
tmp_root = (os.getenv("ACESTEP_TMPDIR") or os.path.join(cache_root, "tmp")).strip()
|
| 561 |
+
triton_cache_root = (os.getenv("TRITON_CACHE_DIR") or os.path.join(cache_root, "triton")).strip()
|
| 562 |
+
inductor_cache_root = (os.getenv("TORCHINDUCTOR_CACHE_DIR") or os.path.join(cache_root, "torchinductor")).strip()
|
| 563 |
+
|
| 564 |
+
for p in [cache_root, tmp_root, triton_cache_root, inductor_cache_root]:
|
| 565 |
+
try:
|
| 566 |
+
os.makedirs(p, exist_ok=True)
|
| 567 |
+
except Exception:
|
| 568 |
+
# Best-effort: do not block startup if directory creation fails.
|
| 569 |
+
pass
|
| 570 |
+
|
| 571 |
+
# Respect explicit user overrides; if ACESTEP_TMPDIR is set, it should win.
|
| 572 |
+
if os.getenv("ACESTEP_TMPDIR"):
|
| 573 |
+
os.environ["TMPDIR"] = tmp_root
|
| 574 |
+
os.environ["TEMP"] = tmp_root
|
| 575 |
+
os.environ["TMP"] = tmp_root
|
| 576 |
+
else:
|
| 577 |
+
os.environ.setdefault("TMPDIR", tmp_root)
|
| 578 |
+
os.environ.setdefault("TEMP", tmp_root)
|
| 579 |
+
os.environ.setdefault("TMP", tmp_root)
|
| 580 |
+
|
| 581 |
+
os.environ.setdefault("TRITON_CACHE_DIR", triton_cache_root)
|
| 582 |
+
os.environ.setdefault("TORCHINDUCTOR_CACHE_DIR", inductor_cache_root)
|
| 583 |
+
|
| 584 |
+
handler = AceStepHandler()
|
| 585 |
+
llm_handler = LLMHandler()
|
| 586 |
+
init_lock = asyncio.Lock()
|
| 587 |
+
app.state._initialized = False
|
| 588 |
+
app.state._init_error = None
|
| 589 |
+
app.state._init_lock = init_lock
|
| 590 |
+
|
| 591 |
+
app.state.llm_handler = llm_handler
|
| 592 |
+
app.state._llm_initialized = False
|
| 593 |
+
app.state._llm_init_error = None
|
| 594 |
+
app.state._llm_init_lock = Lock()
|
| 595 |
+
|
| 596 |
+
# Multi-model support: secondary DiT handlers
|
| 597 |
+
handler2 = None
|
| 598 |
+
handler3 = None
|
| 599 |
+
config_path2 = os.getenv("ACESTEP_CONFIG_PATH2", "").strip()
|
| 600 |
+
config_path3 = os.getenv("ACESTEP_CONFIG_PATH3", "").strip()
|
| 601 |
+
|
| 602 |
+
if config_path2:
|
| 603 |
+
handler2 = AceStepHandler()
|
| 604 |
+
if config_path3:
|
| 605 |
+
handler3 = AceStepHandler()
|
| 606 |
+
|
| 607 |
+
app.state.handler2 = handler2
|
| 608 |
+
app.state.handler3 = handler3
|
| 609 |
+
app.state._initialized2 = False
|
| 610 |
+
app.state._initialized3 = False
|
| 611 |
+
app.state._config_path = os.getenv("ACESTEP_CONFIG_PATH", "acestep-v15-turbo")
|
| 612 |
+
app.state._config_path2 = config_path2
|
| 613 |
+
app.state._config_path3 = config_path3
|
| 614 |
+
|
| 615 |
+
max_workers = int(os.getenv("ACESTEP_API_WORKERS", "1"))
|
| 616 |
+
executor = ThreadPoolExecutor(max_workers=max_workers)
|
| 617 |
+
|
| 618 |
+
# Queue & observability
|
| 619 |
+
app.state.job_queue = asyncio.Queue(maxsize=QUEUE_MAXSIZE) # (job_id, req)
|
| 620 |
+
app.state.pending_ids = deque() # queued job_ids
|
| 621 |
+
app.state.pending_lock = asyncio.Lock()
|
| 622 |
+
|
| 623 |
+
# temp files per job (from multipart uploads)
|
| 624 |
+
app.state.job_temp_files = {} # job_id -> list[path]
|
| 625 |
+
app.state.job_temp_files_lock = asyncio.Lock()
|
| 626 |
+
|
| 627 |
+
# stats
|
| 628 |
+
app.state.stats_lock = asyncio.Lock()
|
| 629 |
+
app.state.recent_durations = deque(maxlen=AVG_WINDOW)
|
| 630 |
+
app.state.avg_job_seconds = INITIAL_AVG_JOB_SECONDS
|
| 631 |
+
|
| 632 |
+
app.state.handler = handler
|
| 633 |
+
app.state.executor = executor
|
| 634 |
+
app.state.job_store = store
|
| 635 |
+
app.state._python_executable = sys.executable
|
| 636 |
+
|
| 637 |
+
# Temporary directory for saving generated audio files
|
| 638 |
+
app.state.temp_audio_dir = os.path.join(tmp_root, "api_audio")
|
| 639 |
+
os.makedirs(app.state.temp_audio_dir, exist_ok=True)
|
| 640 |
+
|
| 641 |
+
# Initialize local cache
|
| 642 |
+
try:
|
| 643 |
+
from acestep.local_cache import get_local_cache
|
| 644 |
+
local_cache_dir = os.path.join(cache_root, "local_redis")
|
| 645 |
+
app.state.local_cache = get_local_cache(local_cache_dir)
|
| 646 |
+
except ImportError:
|
| 647 |
+
app.state.local_cache = None
|
| 648 |
+
|
| 649 |
+
async def _ensure_initialized() -> None:
|
| 650 |
+
h: AceStepHandler = app.state.handler
|
| 651 |
+
|
| 652 |
+
if getattr(app.state, "_initialized", False):
|
| 653 |
+
return
|
| 654 |
+
if getattr(app.state, "_init_error", None):
|
| 655 |
+
raise RuntimeError(app.state._init_error)
|
| 656 |
+
|
| 657 |
+
async with app.state._init_lock:
|
| 658 |
+
if getattr(app.state, "_initialized", False):
|
| 659 |
+
return
|
| 660 |
+
if getattr(app.state, "_init_error", None):
|
| 661 |
+
raise RuntimeError(app.state._init_error)
|
| 662 |
+
|
| 663 |
+
project_root = _get_project_root()
|
| 664 |
+
config_path = os.getenv("ACESTEP_CONFIG_PATH", "acestep-v15-turbo")
|
| 665 |
+
device = os.getenv("ACESTEP_DEVICE", "auto")
|
| 666 |
+
|
| 667 |
+
use_flash_attention = _env_bool("ACESTEP_USE_FLASH_ATTENTION", True)
|
| 668 |
+
offload_to_cpu = _env_bool("ACESTEP_OFFLOAD_TO_CPU", False)
|
| 669 |
+
offload_dit_to_cpu = _env_bool("ACESTEP_OFFLOAD_DIT_TO_CPU", False)
|
| 670 |
+
|
| 671 |
+
# Initialize primary model
|
| 672 |
+
status_msg, ok = h.initialize_service(
|
| 673 |
+
project_root=project_root,
|
| 674 |
+
config_path=config_path,
|
| 675 |
+
device=device,
|
| 676 |
+
use_flash_attention=use_flash_attention,
|
| 677 |
+
compile_model=False,
|
| 678 |
+
offload_to_cpu=offload_to_cpu,
|
| 679 |
+
offload_dit_to_cpu=offload_dit_to_cpu,
|
| 680 |
+
)
|
| 681 |
+
if not ok:
|
| 682 |
+
app.state._init_error = status_msg
|
| 683 |
+
raise RuntimeError(status_msg)
|
| 684 |
+
app.state._initialized = True
|
| 685 |
+
|
| 686 |
+
# Initialize secondary model if configured
|
| 687 |
+
if app.state.handler2 and app.state._config_path2:
|
| 688 |
+
try:
|
| 689 |
+
status_msg2, ok2 = app.state.handler2.initialize_service(
|
| 690 |
+
project_root=project_root,
|
| 691 |
+
config_path=app.state._config_path2,
|
| 692 |
+
device=device,
|
| 693 |
+
use_flash_attention=use_flash_attention,
|
| 694 |
+
compile_model=False,
|
| 695 |
+
offload_to_cpu=offload_to_cpu,
|
| 696 |
+
offload_dit_to_cpu=offload_dit_to_cpu,
|
| 697 |
+
)
|
| 698 |
+
app.state._initialized2 = ok2
|
| 699 |
+
if ok2:
|
| 700 |
+
print(f"[API Server] Secondary model loaded: {_get_model_name(app.state._config_path2)}")
|
| 701 |
+
else:
|
| 702 |
+
print(f"[API Server] Warning: Secondary model failed to load: {status_msg2}")
|
| 703 |
+
except Exception as e:
|
| 704 |
+
print(f"[API Server] Warning: Failed to initialize secondary model: {e}")
|
| 705 |
+
app.state._initialized2 = False
|
| 706 |
+
|
| 707 |
+
# Initialize third model if configured
|
| 708 |
+
if app.state.handler3 and app.state._config_path3:
|
| 709 |
+
try:
|
| 710 |
+
status_msg3, ok3 = app.state.handler3.initialize_service(
|
| 711 |
+
project_root=project_root,
|
| 712 |
+
config_path=app.state._config_path3,
|
| 713 |
+
device=device,
|
| 714 |
+
use_flash_attention=use_flash_attention,
|
| 715 |
+
compile_model=False,
|
| 716 |
+
offload_to_cpu=offload_to_cpu,
|
| 717 |
+
offload_dit_to_cpu=offload_dit_to_cpu,
|
| 718 |
+
)
|
| 719 |
+
app.state._initialized3 = ok3
|
| 720 |
+
if ok3:
|
| 721 |
+
print(f"[API Server] Third model loaded: {_get_model_name(app.state._config_path3)}")
|
| 722 |
+
else:
|
| 723 |
+
print(f"[API Server] Warning: Third model failed to load: {status_msg3}")
|
| 724 |
+
except Exception as e:
|
| 725 |
+
print(f"[API Server] Warning: Failed to initialize third model: {e}")
|
| 726 |
+
app.state._initialized3 = False
|
| 727 |
+
|
| 728 |
+
async def _cleanup_job_temp_files(job_id: str) -> None:
|
| 729 |
+
async with app.state.job_temp_files_lock:
|
| 730 |
+
paths = app.state.job_temp_files.pop(job_id, [])
|
| 731 |
+
for p in paths:
|
| 732 |
+
try:
|
| 733 |
+
os.remove(p)
|
| 734 |
+
except Exception:
|
| 735 |
+
pass
|
| 736 |
+
|
| 737 |
+
def _update_local_cache(job_id: str, result: Optional[Dict], status: str) -> None:
|
| 738 |
+
"""Update local cache with job result"""
|
| 739 |
+
local_cache = getattr(app.state, 'local_cache', None)
|
| 740 |
+
if not local_cache:
|
| 741 |
+
return
|
| 742 |
+
|
| 743 |
+
rec = store.get(job_id)
|
| 744 |
+
env = getattr(rec, 'env', 'development') if rec else 'development'
|
| 745 |
+
create_time = rec.created_at if rec else time.time()
|
| 746 |
+
|
| 747 |
+
status_int = _map_status(status)
|
| 748 |
+
|
| 749 |
+
if status == "succeeded" and result:
|
| 750 |
+
audio_paths = result.get("audio_paths", [])
|
| 751 |
+
# Final prompt/lyrics (may be modified by thinking/format)
|
| 752 |
+
final_prompt = result.get("prompt", "")
|
| 753 |
+
final_lyrics = result.get("lyrics", "")
|
| 754 |
+
# Original user input from metas
|
| 755 |
+
metas_raw = result.get("metas", {}) or {}
|
| 756 |
+
original_prompt = metas_raw.get("prompt", "")
|
| 757 |
+
original_lyrics = metas_raw.get("lyrics", "")
|
| 758 |
+
# metas contains original input + other metadata
|
| 759 |
+
metas = {
|
| 760 |
+
"bpm": metas_raw.get("bpm"),
|
| 761 |
+
"duration": metas_raw.get("duration"),
|
| 762 |
+
"genres": metas_raw.get("genres", ""),
|
| 763 |
+
"keyscale": metas_raw.get("keyscale", ""),
|
| 764 |
+
"timesignature": metas_raw.get("timesignature", ""),
|
| 765 |
+
"prompt": original_prompt,
|
| 766 |
+
"lyrics": original_lyrics,
|
| 767 |
+
}
|
| 768 |
+
# Extra fields for Discord bot
|
| 769 |
+
generation_info = result.get("generation_info", "")
|
| 770 |
+
seed_value = result.get("seed_value", "")
|
| 771 |
+
lm_model = result.get("lm_model", "")
|
| 772 |
+
dit_model = result.get("dit_model", "")
|
| 773 |
+
|
| 774 |
+
if audio_paths:
|
| 775 |
+
result_data = [
|
| 776 |
+
{
|
| 777 |
+
"file": p,
|
| 778 |
+
"wave": "",
|
| 779 |
+
"status": status_int,
|
| 780 |
+
"create_time": int(create_time),
|
| 781 |
+
"env": env,
|
| 782 |
+
"prompt": final_prompt,
|
| 783 |
+
"lyrics": final_lyrics,
|
| 784 |
+
"metas": metas,
|
| 785 |
+
"generation_info": generation_info,
|
| 786 |
+
"seed_value": seed_value,
|
| 787 |
+
"lm_model": lm_model,
|
| 788 |
+
"dit_model": dit_model,
|
| 789 |
+
}
|
| 790 |
+
for p in audio_paths
|
| 791 |
+
]
|
| 792 |
+
else:
|
| 793 |
+
result_data = [{
|
| 794 |
+
"file": "",
|
| 795 |
+
"wave": "",
|
| 796 |
+
"status": status_int,
|
| 797 |
+
"create_time": int(create_time),
|
| 798 |
+
"env": env,
|
| 799 |
+
"prompt": final_prompt,
|
| 800 |
+
"lyrics": final_lyrics,
|
| 801 |
+
"metas": metas,
|
| 802 |
+
"generation_info": generation_info,
|
| 803 |
+
"seed_value": seed_value,
|
| 804 |
+
"lm_model": lm_model,
|
| 805 |
+
"dit_model": dit_model,
|
| 806 |
+
}]
|
| 807 |
+
else:
|
| 808 |
+
result_data = [{"file": "", "wave": "", "status": status_int, "create_time": int(create_time), "env": env}]
|
| 809 |
+
|
| 810 |
+
result_key = f"{RESULT_KEY_PREFIX}{job_id}"
|
| 811 |
+
local_cache.set(result_key, result_data, ex=RESULT_EXPIRE_SECONDS)
|
| 812 |
+
|
| 813 |
+
async def _run_one_job(job_id: str, req: GenerateMusicRequest) -> None:
|
| 814 |
+
job_store: _JobStore = app.state.job_store
|
| 815 |
+
llm: LLMHandler = app.state.llm_handler
|
| 816 |
+
executor: ThreadPoolExecutor = app.state.executor
|
| 817 |
+
|
| 818 |
+
await _ensure_initialized()
|
| 819 |
+
job_store.mark_running(job_id)
|
| 820 |
+
|
| 821 |
+
# Select DiT handler based on user's model choice
|
| 822 |
+
# Default: use primary handler
|
| 823 |
+
selected_handler: AceStepHandler = app.state.handler
|
| 824 |
+
selected_model_name = _get_model_name(app.state._config_path)
|
| 825 |
+
|
| 826 |
+
if req.model:
|
| 827 |
+
model_matched = False
|
| 828 |
+
|
| 829 |
+
# Check if it matches the second model
|
| 830 |
+
if app.state.handler2 and getattr(app.state, "_initialized2", False):
|
| 831 |
+
model2_name = _get_model_name(app.state._config_path2)
|
| 832 |
+
if req.model == model2_name:
|
| 833 |
+
selected_handler = app.state.handler2
|
| 834 |
+
selected_model_name = model2_name
|
| 835 |
+
model_matched = True
|
| 836 |
+
print(f"[API Server] Job {job_id}: Using second model: {model2_name}")
|
| 837 |
+
|
| 838 |
+
# Check if it matches the third model
|
| 839 |
+
if not model_matched and app.state.handler3 and getattr(app.state, "_initialized3", False):
|
| 840 |
+
model3_name = _get_model_name(app.state._config_path3)
|
| 841 |
+
if req.model == model3_name:
|
| 842 |
+
selected_handler = app.state.handler3
|
| 843 |
+
selected_model_name = model3_name
|
| 844 |
+
model_matched = True
|
| 845 |
+
print(f"[API Server] Job {job_id}: Using third model: {model3_name}")
|
| 846 |
+
|
| 847 |
+
if not model_matched:
|
| 848 |
+
available_models = [_get_model_name(app.state._config_path)]
|
| 849 |
+
if app.state.handler2 and getattr(app.state, "_initialized2", False):
|
| 850 |
+
available_models.append(_get_model_name(app.state._config_path2))
|
| 851 |
+
if app.state.handler3 and getattr(app.state, "_initialized3", False):
|
| 852 |
+
available_models.append(_get_model_name(app.state._config_path3))
|
| 853 |
+
print(f"[API Server] Job {job_id}: Model '{req.model}' not found in {available_models}, using primary: {selected_model_name}")
|
| 854 |
+
|
| 855 |
+
# Use selected handler for generation
|
| 856 |
+
h: AceStepHandler = selected_handler
|
| 857 |
+
|
| 858 |
+
def _blocking_generate() -> Dict[str, Any]:
|
| 859 |
+
"""Generate music using unified inference logic from acestep.inference"""
|
| 860 |
+
|
| 861 |
+
def _ensure_llm_ready() -> None:
|
| 862 |
+
"""Ensure LLM handler is initialized when needed"""
|
| 863 |
+
with app.state._llm_init_lock:
|
| 864 |
+
initialized = getattr(app.state, "_llm_initialized", False)
|
| 865 |
+
had_error = getattr(app.state, "_llm_init_error", None)
|
| 866 |
+
if initialized or had_error is not None:
|
| 867 |
+
return
|
| 868 |
+
|
| 869 |
+
project_root = _get_project_root()
|
| 870 |
+
checkpoint_dir = os.path.join(project_root, "checkpoints")
|
| 871 |
+
lm_model_path = (req.lm_model_path or os.getenv("ACESTEP_LM_MODEL_PATH") or "acestep-5Hz-lm-0.6B").strip()
|
| 872 |
+
backend = (req.lm_backend or os.getenv("ACESTEP_LM_BACKEND") or "vllm").strip().lower()
|
| 873 |
+
if backend not in {"vllm", "pt"}:
|
| 874 |
+
backend = "vllm"
|
| 875 |
+
|
| 876 |
+
lm_device = os.getenv("ACESTEP_LM_DEVICE", os.getenv("ACESTEP_DEVICE", "auto"))
|
| 877 |
+
lm_offload = _env_bool("ACESTEP_LM_OFFLOAD_TO_CPU", False)
|
| 878 |
+
|
| 879 |
+
status, ok = llm.initialize(
|
| 880 |
+
checkpoint_dir=checkpoint_dir,
|
| 881 |
+
lm_model_path=lm_model_path,
|
| 882 |
+
backend=backend,
|
| 883 |
+
device=lm_device,
|
| 884 |
+
offload_to_cpu=lm_offload,
|
| 885 |
+
dtype=h.dtype,
|
| 886 |
+
)
|
| 887 |
+
if not ok:
|
| 888 |
+
app.state._llm_init_error = status
|
| 889 |
+
else:
|
| 890 |
+
app.state._llm_initialized = True
|
| 891 |
+
|
| 892 |
+
def _normalize_metas(meta: Dict[str, Any]) -> Dict[str, Any]:
|
| 893 |
+
"""Ensure a stable `metas` dict (keys always present)."""
|
| 894 |
+
meta = meta or {}
|
| 895 |
+
out: Dict[str, Any] = dict(meta)
|
| 896 |
+
|
| 897 |
+
# Normalize key aliases
|
| 898 |
+
if "keyscale" not in out and "key_scale" in out:
|
| 899 |
+
out["keyscale"] = out.get("key_scale")
|
| 900 |
+
if "timesignature" not in out and "time_signature" in out:
|
| 901 |
+
out["timesignature"] = out.get("time_signature")
|
| 902 |
+
|
| 903 |
+
# Ensure required keys exist
|
| 904 |
+
for k in ["bpm", "duration", "genres", "keyscale", "timesignature"]:
|
| 905 |
+
if out.get(k) in (None, ""):
|
| 906 |
+
out[k] = "N/A"
|
| 907 |
+
return out
|
| 908 |
+
|
| 909 |
+
# Normalize LM sampling parameters
|
| 910 |
+
lm_top_k = req.lm_top_k if req.lm_top_k and req.lm_top_k > 0 else 0
|
| 911 |
+
lm_top_p = req.lm_top_p if req.lm_top_p and req.lm_top_p < 1.0 else 0.9
|
| 912 |
+
|
| 913 |
+
# Determine if LLM is needed
|
| 914 |
+
thinking = bool(req.thinking)
|
| 915 |
+
sample_mode = bool(req.sample_mode)
|
| 916 |
+
has_sample_query = bool(req.sample_query and req.sample_query.strip())
|
| 917 |
+
use_format = bool(req.use_format)
|
| 918 |
+
use_cot_caption = bool(req.use_cot_caption)
|
| 919 |
+
use_cot_language = bool(req.use_cot_language)
|
| 920 |
+
|
| 921 |
+
# LLM is needed for:
|
| 922 |
+
# - thinking mode (LM generates audio codes)
|
| 923 |
+
# - sample_mode (LM generates random caption/lyrics/metas)
|
| 924 |
+
# - sample_query/description (LM generates from description)
|
| 925 |
+
# - use_format (LM enhances caption/lyrics)
|
| 926 |
+
# - use_cot_caption or use_cot_language (LM enhances metadata)
|
| 927 |
+
need_llm = thinking or sample_mode or has_sample_query or use_format or use_cot_caption or use_cot_language
|
| 928 |
+
|
| 929 |
+
# Ensure LLM is ready if needed
|
| 930 |
+
if need_llm:
|
| 931 |
+
_ensure_llm_ready()
|
| 932 |
+
if getattr(app.state, "_llm_init_error", None):
|
| 933 |
+
raise RuntimeError(f"5Hz LM init failed: {app.state._llm_init_error}")
|
| 934 |
+
|
| 935 |
+
# Handle sample mode or description: generate caption/lyrics/metas via LM
|
| 936 |
+
caption = req.prompt
|
| 937 |
+
lyrics = req.lyrics
|
| 938 |
+
bpm = req.bpm
|
| 939 |
+
key_scale = req.key_scale
|
| 940 |
+
time_signature = req.time_signature
|
| 941 |
+
audio_duration = req.audio_duration
|
| 942 |
+
|
| 943 |
+
# Save original user input for metas
|
| 944 |
+
original_prompt = req.prompt or ""
|
| 945 |
+
original_lyrics = req.lyrics or ""
|
| 946 |
+
|
| 947 |
+
if sample_mode or has_sample_query:
|
| 948 |
+
if has_sample_query:
|
| 949 |
+
# Use create_sample() with description query
|
| 950 |
+
parsed_language, parsed_instrumental = _parse_description_hints(req.sample_query)
|
| 951 |
+
|
| 952 |
+
# Determine vocal_language with priority:
|
| 953 |
+
# 1. User-specified vocal_language (if not default "en")
|
| 954 |
+
# 2. Language parsed from description
|
| 955 |
+
# 3. None (no constraint)
|
| 956 |
+
if req.vocal_language and req.vocal_language not in ("en", "unknown", ""):
|
| 957 |
+
sample_language = req.vocal_language
|
| 958 |
+
else:
|
| 959 |
+
sample_language = parsed_language
|
| 960 |
+
|
| 961 |
+
sample_result = create_sample(
|
| 962 |
+
llm_handler=llm,
|
| 963 |
+
query=req.sample_query,
|
| 964 |
+
instrumental=parsed_instrumental,
|
| 965 |
+
vocal_language=sample_language,
|
| 966 |
+
temperature=req.lm_temperature,
|
| 967 |
+
top_k=lm_top_k if lm_top_k > 0 else None,
|
| 968 |
+
top_p=lm_top_p if lm_top_p < 1.0 else None,
|
| 969 |
+
use_constrained_decoding=req.constrained_decoding,
|
| 970 |
+
)
|
| 971 |
+
|
| 972 |
+
if not sample_result.success:
|
| 973 |
+
raise RuntimeError(f"create_sample failed: {sample_result.error or sample_result.status_message}")
|
| 974 |
+
|
| 975 |
+
# Use generated sample data
|
| 976 |
+
caption = sample_result.caption
|
| 977 |
+
lyrics = sample_result.lyrics
|
| 978 |
+
bpm = sample_result.bpm
|
| 979 |
+
key_scale = sample_result.keyscale
|
| 980 |
+
time_signature = sample_result.timesignature
|
| 981 |
+
audio_duration = sample_result.duration
|
| 982 |
+
else:
|
| 983 |
+
# Original sample_mode behavior: random generation
|
| 984 |
+
sample_metadata, sample_status = llm.understand_audio_from_codes(
|
| 985 |
+
audio_codes="NO USER INPUT",
|
| 986 |
+
temperature=req.lm_temperature,
|
| 987 |
+
top_k=lm_top_k if lm_top_k > 0 else None,
|
| 988 |
+
top_p=lm_top_p if lm_top_p < 1.0 else None,
|
| 989 |
+
repetition_penalty=req.lm_repetition_penalty,
|
| 990 |
+
use_constrained_decoding=req.constrained_decoding,
|
| 991 |
+
constrained_decoding_debug=req.constrained_decoding_debug,
|
| 992 |
+
)
|
| 993 |
+
|
| 994 |
+
if not sample_metadata or str(sample_status).startswith("❌"):
|
| 995 |
+
raise RuntimeError(f"Sample generation failed: {sample_status}")
|
| 996 |
+
|
| 997 |
+
# Use generated values with fallback defaults
|
| 998 |
+
caption = sample_metadata.get("caption", "")
|
| 999 |
+
lyrics = sample_metadata.get("lyrics", "")
|
| 1000 |
+
bpm = _to_int(sample_metadata.get("bpm"), None) or _to_int(os.getenv("ACESTEP_SAMPLE_DEFAULT_BPM", "120"), 120)
|
| 1001 |
+
key_scale = sample_metadata.get("keyscale", "") or os.getenv("ACESTEP_SAMPLE_DEFAULT_KEY", "C Major")
|
| 1002 |
+
time_signature = sample_metadata.get("timesignature", "") or os.getenv("ACESTEP_SAMPLE_DEFAULT_TIMESIGNATURE", "4/4")
|
| 1003 |
+
audio_duration = _to_float(sample_metadata.get("duration"), None) or _to_float(os.getenv("ACESTEP_SAMPLE_DEFAULT_DURATION_SECONDS", "120"), 120.0)
|
| 1004 |
+
|
| 1005 |
+
# Apply format_sample() if use_format is True and caption/lyrics are provided
|
| 1006 |
+
format_has_duration = False
|
| 1007 |
+
|
| 1008 |
+
if req.use_format and (caption or lyrics):
|
| 1009 |
+
_ensure_llm_ready()
|
| 1010 |
+
if getattr(app.state, "_llm_init_error", None):
|
| 1011 |
+
raise RuntimeError(f"5Hz LM init failed (needed for format): {app.state._llm_init_error}")
|
| 1012 |
+
|
| 1013 |
+
# Build user_metadata from request params (matching bot.py behavior)
|
| 1014 |
+
user_metadata_for_format = {}
|
| 1015 |
+
if bpm is not None:
|
| 1016 |
+
user_metadata_for_format['bpm'] = bpm
|
| 1017 |
+
if audio_duration is not None and audio_duration > 0:
|
| 1018 |
+
user_metadata_for_format['duration'] = int(audio_duration)
|
| 1019 |
+
if key_scale:
|
| 1020 |
+
user_metadata_for_format['keyscale'] = key_scale
|
| 1021 |
+
if time_signature:
|
| 1022 |
+
user_metadata_for_format['timesignature'] = time_signature
|
| 1023 |
+
if req.vocal_language and req.vocal_language != "unknown":
|
| 1024 |
+
user_metadata_for_format['language'] = req.vocal_language
|
| 1025 |
+
|
| 1026 |
+
format_result = format_sample(
|
| 1027 |
+
llm_handler=llm,
|
| 1028 |
+
caption=caption,
|
| 1029 |
+
lyrics=lyrics,
|
| 1030 |
+
user_metadata=user_metadata_for_format if user_metadata_for_format else None,
|
| 1031 |
+
temperature=req.lm_temperature,
|
| 1032 |
+
top_k=lm_top_k if lm_top_k > 0 else None,
|
| 1033 |
+
top_p=lm_top_p if lm_top_p < 1.0 else None,
|
| 1034 |
+
use_constrained_decoding=req.constrained_decoding,
|
| 1035 |
+
)
|
| 1036 |
+
|
| 1037 |
+
if format_result.success:
|
| 1038 |
+
# Extract all formatted data (matching bot.py behavior)
|
| 1039 |
+
caption = format_result.caption or caption
|
| 1040 |
+
lyrics = format_result.lyrics or lyrics
|
| 1041 |
+
if format_result.duration:
|
| 1042 |
+
audio_duration = format_result.duration
|
| 1043 |
+
format_has_duration = True
|
| 1044 |
+
if format_result.bpm:
|
| 1045 |
+
bpm = format_result.bpm
|
| 1046 |
+
if format_result.keyscale:
|
| 1047 |
+
key_scale = format_result.keyscale
|
| 1048 |
+
if format_result.timesignature:
|
| 1049 |
+
time_signature = format_result.timesignature
|
| 1050 |
+
|
| 1051 |
+
# Parse timesteps string to list of floats if provided
|
| 1052 |
+
parsed_timesteps = _parse_timesteps(req.timesteps)
|
| 1053 |
+
|
| 1054 |
+
# Determine actual inference steps (timesteps override inference_steps)
|
| 1055 |
+
actual_inference_steps = len(parsed_timesteps) if parsed_timesteps else req.inference_steps
|
| 1056 |
+
|
| 1057 |
+
# Auto-select instruction based on task_type if user didn't provide custom instruction
|
| 1058 |
+
# This matches gradio behavior which uses TASK_INSTRUCTIONS for each task type
|
| 1059 |
+
instruction_to_use = req.instruction
|
| 1060 |
+
if instruction_to_use == DEFAULT_DIT_INSTRUCTION and req.task_type in TASK_INSTRUCTIONS:
|
| 1061 |
+
instruction_to_use = TASK_INSTRUCTIONS[req.task_type]
|
| 1062 |
+
|
| 1063 |
+
# Build GenerationParams using unified interface
|
| 1064 |
+
# Note: thinking controls LM code generation, sample_mode only affects CoT metas
|
| 1065 |
+
params = GenerationParams(
|
| 1066 |
+
task_type=req.task_type,
|
| 1067 |
+
instruction=instruction_to_use,
|
| 1068 |
+
reference_audio=req.reference_audio_path,
|
| 1069 |
+
src_audio=req.src_audio_path,
|
| 1070 |
+
audio_codes=req.audio_code_string,
|
| 1071 |
+
caption=caption,
|
| 1072 |
+
lyrics=lyrics,
|
| 1073 |
+
instrumental=False,
|
| 1074 |
+
vocal_language=req.vocal_language,
|
| 1075 |
+
bpm=bpm,
|
| 1076 |
+
keyscale=key_scale,
|
| 1077 |
+
timesignature=time_signature,
|
| 1078 |
+
duration=audio_duration if audio_duration else -1.0,
|
| 1079 |
+
inference_steps=req.inference_steps,
|
| 1080 |
+
seed=req.seed,
|
| 1081 |
+
guidance_scale=req.guidance_scale,
|
| 1082 |
+
use_adg=req.use_adg,
|
| 1083 |
+
cfg_interval_start=req.cfg_interval_start,
|
| 1084 |
+
cfg_interval_end=req.cfg_interval_end,
|
| 1085 |
+
shift=req.shift,
|
| 1086 |
+
infer_method=req.infer_method,
|
| 1087 |
+
timesteps=parsed_timesteps,
|
| 1088 |
+
repainting_start=req.repainting_start,
|
| 1089 |
+
repainting_end=req.repainting_end if req.repainting_end else -1,
|
| 1090 |
+
audio_cover_strength=req.audio_cover_strength,
|
| 1091 |
+
# LM parameters
|
| 1092 |
+
thinking=thinking, # Use LM for code generation when thinking=True
|
| 1093 |
+
lm_temperature=req.lm_temperature,
|
| 1094 |
+
lm_cfg_scale=req.lm_cfg_scale,
|
| 1095 |
+
lm_top_k=lm_top_k,
|
| 1096 |
+
lm_top_p=lm_top_p,
|
| 1097 |
+
lm_negative_prompt=req.lm_negative_prompt,
|
| 1098 |
+
# use_cot_metas logic:
|
| 1099 |
+
# - sample_mode: metas already generated, skip Phase 1
|
| 1100 |
+
# - format with duration: metas already generated, skip Phase 1
|
| 1101 |
+
# - format without duration: need Phase 1 to generate duration
|
| 1102 |
+
# - no format: need Phase 1 to generate all metas
|
| 1103 |
+
use_cot_metas=not sample_mode and not format_has_duration,
|
| 1104 |
+
use_cot_caption=req.use_cot_caption,
|
| 1105 |
+
use_cot_language=req.use_cot_language,
|
| 1106 |
+
use_constrained_decoding=req.constrained_decoding,
|
| 1107 |
+
)
|
| 1108 |
+
|
| 1109 |
+
# Build GenerationConfig - default to 2 audios like gradio_ui
|
| 1110 |
+
batch_size = req.batch_size if req.batch_size is not None else 2
|
| 1111 |
+
config = GenerationConfig(
|
| 1112 |
+
batch_size=batch_size,
|
| 1113 |
+
use_random_seed=req.use_random_seed,
|
| 1114 |
+
seeds=None, # Let unified logic handle seed generation
|
| 1115 |
+
audio_format=req.audio_format,
|
| 1116 |
+
constrained_decoding_debug=req.constrained_decoding_debug,
|
| 1117 |
+
)
|
| 1118 |
+
|
| 1119 |
+
# Check LLM initialization status
|
| 1120 |
+
llm_is_initialized = getattr(app.state, "_llm_initialized", False)
|
| 1121 |
+
llm_to_pass = llm if llm_is_initialized else None
|
| 1122 |
+
|
| 1123 |
+
# Generate music using unified interface
|
| 1124 |
+
result = generate_music(
|
| 1125 |
+
dit_handler=h,
|
| 1126 |
+
llm_handler=llm_to_pass,
|
| 1127 |
+
params=params,
|
| 1128 |
+
config=config,
|
| 1129 |
+
save_dir=app.state.temp_audio_dir,
|
| 1130 |
+
progress=None,
|
| 1131 |
+
)
|
| 1132 |
+
|
| 1133 |
+
if not result.success:
|
| 1134 |
+
raise RuntimeError(f"Music generation failed: {result.error or result.status_message}")
|
| 1135 |
+
|
| 1136 |
+
# Extract results
|
| 1137 |
+
audio_paths = [audio["path"] for audio in result.audios if audio.get("path")]
|
| 1138 |
+
first_audio = audio_paths[0] if len(audio_paths) > 0 else None
|
| 1139 |
+
second_audio = audio_paths[1] if len(audio_paths) > 1 else None
|
| 1140 |
+
|
| 1141 |
+
# Get metadata from LM or CoT results
|
| 1142 |
+
lm_metadata = result.extra_outputs.get("lm_metadata", {})
|
| 1143 |
+
metas_out = _normalize_metas(lm_metadata)
|
| 1144 |
+
|
| 1145 |
+
# Update metas with actual values used
|
| 1146 |
+
if params.cot_bpm:
|
| 1147 |
+
metas_out["bpm"] = params.cot_bpm
|
| 1148 |
+
elif bpm:
|
| 1149 |
+
metas_out["bpm"] = bpm
|
| 1150 |
+
|
| 1151 |
+
if params.cot_duration:
|
| 1152 |
+
metas_out["duration"] = params.cot_duration
|
| 1153 |
+
elif audio_duration:
|
| 1154 |
+
metas_out["duration"] = audio_duration
|
| 1155 |
+
|
| 1156 |
+
if params.cot_keyscale:
|
| 1157 |
+
metas_out["keyscale"] = params.cot_keyscale
|
| 1158 |
+
elif key_scale:
|
| 1159 |
+
metas_out["keyscale"] = key_scale
|
| 1160 |
+
|
| 1161 |
+
if params.cot_timesignature:
|
| 1162 |
+
metas_out["timesignature"] = params.cot_timesignature
|
| 1163 |
+
elif time_signature:
|
| 1164 |
+
metas_out["timesignature"] = time_signature
|
| 1165 |
+
|
| 1166 |
+
# Store original user input in metas (not the final/modified values)
|
| 1167 |
+
metas_out["prompt"] = original_prompt
|
| 1168 |
+
metas_out["lyrics"] = original_lyrics
|
| 1169 |
+
|
| 1170 |
+
# Extract seed values for response (comma-separated for multiple audios)
|
| 1171 |
+
seed_values = []
|
| 1172 |
+
for audio in result.audios:
|
| 1173 |
+
audio_params = audio.get("params", {})
|
| 1174 |
+
seed = audio_params.get("seed")
|
| 1175 |
+
if seed is not None:
|
| 1176 |
+
seed_values.append(str(seed))
|
| 1177 |
+
seed_value = ",".join(seed_values) if seed_values else ""
|
| 1178 |
+
|
| 1179 |
+
# Build generation_info using the helper function (like gradio_ui)
|
| 1180 |
+
time_costs = result.extra_outputs.get("time_costs", {})
|
| 1181 |
+
generation_info = _build_generation_info(
|
| 1182 |
+
lm_metadata=lm_metadata,
|
| 1183 |
+
time_costs=time_costs,
|
| 1184 |
+
seed_value=seed_value,
|
| 1185 |
+
inference_steps=req.inference_steps,
|
| 1186 |
+
num_audios=len(result.audios),
|
| 1187 |
+
)
|
| 1188 |
+
|
| 1189 |
+
def _none_if_na_str(v: Any) -> Optional[str]:
|
| 1190 |
+
if v is None:
|
| 1191 |
+
return None
|
| 1192 |
+
s = str(v).strip()
|
| 1193 |
+
if s in {"", "N/A"}:
|
| 1194 |
+
return None
|
| 1195 |
+
return s
|
| 1196 |
+
|
| 1197 |
+
# Get model information
|
| 1198 |
+
lm_model_name = os.getenv("ACESTEP_LM_MODEL_PATH", "acestep-5Hz-lm-0.6B")
|
| 1199 |
+
# Use selected_model_name (set at the beginning of _run_one_job)
|
| 1200 |
+
dit_model_name = selected_model_name
|
| 1201 |
+
|
| 1202 |
+
return {
|
| 1203 |
+
"first_audio_path": _path_to_audio_url(first_audio) if first_audio else None,
|
| 1204 |
+
"second_audio_path": _path_to_audio_url(second_audio) if second_audio else None,
|
| 1205 |
+
"audio_paths": [_path_to_audio_url(p) for p in audio_paths],
|
| 1206 |
+
"generation_info": generation_info,
|
| 1207 |
+
"status_message": result.status_message,
|
| 1208 |
+
"seed_value": seed_value,
|
| 1209 |
+
# Final prompt/lyrics (may be modified by thinking/format)
|
| 1210 |
+
"prompt": caption or "",
|
| 1211 |
+
"lyrics": lyrics or "",
|
| 1212 |
+
# metas contains original user input + other metadata
|
| 1213 |
+
"metas": metas_out,
|
| 1214 |
+
"bpm": metas_out.get("bpm") if isinstance(metas_out.get("bpm"), int) else None,
|
| 1215 |
+
"duration": metas_out.get("duration") if isinstance(metas_out.get("duration"), (int, float)) else None,
|
| 1216 |
+
"genres": _none_if_na_str(metas_out.get("genres")),
|
| 1217 |
+
"keyscale": _none_if_na_str(metas_out.get("keyscale")),
|
| 1218 |
+
"timesignature": _none_if_na_str(metas_out.get("timesignature")),
|
| 1219 |
+
"lm_model": lm_model_name,
|
| 1220 |
+
"dit_model": dit_model_name,
|
| 1221 |
+
}
|
| 1222 |
+
|
| 1223 |
+
t0 = time.time()
|
| 1224 |
+
try:
|
| 1225 |
+
loop = asyncio.get_running_loop()
|
| 1226 |
+
result = await loop.run_in_executor(executor, _blocking_generate)
|
| 1227 |
+
job_store.mark_succeeded(job_id, result)
|
| 1228 |
+
|
| 1229 |
+
# Update local cache
|
| 1230 |
+
_update_local_cache(job_id, result, "succeeded")
|
| 1231 |
+
except Exception:
|
| 1232 |
+
job_store.mark_failed(job_id, traceback.format_exc())
|
| 1233 |
+
|
| 1234 |
+
# Update local cache
|
| 1235 |
+
_update_local_cache(job_id, None, "failed")
|
| 1236 |
+
finally:
|
| 1237 |
+
dt = max(0.0, time.time() - t0)
|
| 1238 |
+
async with app.state.stats_lock:
|
| 1239 |
+
app.state.recent_durations.append(dt)
|
| 1240 |
+
if app.state.recent_durations:
|
| 1241 |
+
app.state.avg_job_seconds = sum(app.state.recent_durations) / len(app.state.recent_durations)
|
| 1242 |
+
|
| 1243 |
+
async def _queue_worker(worker_idx: int) -> None:
|
| 1244 |
+
while True:
|
| 1245 |
+
job_id, req = await app.state.job_queue.get()
|
| 1246 |
+
try:
|
| 1247 |
+
async with app.state.pending_lock:
|
| 1248 |
+
try:
|
| 1249 |
+
app.state.pending_ids.remove(job_id)
|
| 1250 |
+
except ValueError:
|
| 1251 |
+
pass
|
| 1252 |
+
|
| 1253 |
+
await _run_one_job(job_id, req)
|
| 1254 |
+
finally:
|
| 1255 |
+
await _cleanup_job_temp_files(job_id)
|
| 1256 |
+
app.state.job_queue.task_done()
|
| 1257 |
+
|
| 1258 |
+
worker_count = max(1, WORKER_COUNT)
|
| 1259 |
+
workers = [asyncio.create_task(_queue_worker(i)) for i in range(worker_count)]
|
| 1260 |
+
app.state.worker_tasks = workers
|
| 1261 |
+
|
| 1262 |
+
try:
|
| 1263 |
+
yield
|
| 1264 |
+
finally:
|
| 1265 |
+
for t in workers:
|
| 1266 |
+
t.cancel()
|
| 1267 |
+
executor.shutdown(wait=False, cancel_futures=True)
|
| 1268 |
+
|
| 1269 |
+
app = FastAPI(title="ACE-Step API", version="1.0", lifespan=lifespan)
|
| 1270 |
+
|
| 1271 |
+
async def _queue_position(job_id: str) -> int:
|
| 1272 |
+
async with app.state.pending_lock:
|
| 1273 |
+
try:
|
| 1274 |
+
return list(app.state.pending_ids).index(job_id) + 1
|
| 1275 |
+
except ValueError:
|
| 1276 |
+
return 0
|
| 1277 |
+
|
| 1278 |
+
async def _eta_seconds_for_position(pos: int) -> Optional[float]:
|
| 1279 |
+
if pos <= 0:
|
| 1280 |
+
return None
|
| 1281 |
+
async with app.state.stats_lock:
|
| 1282 |
+
avg = float(getattr(app.state, "avg_job_seconds", INITIAL_AVG_JOB_SECONDS))
|
| 1283 |
+
return pos * avg
|
| 1284 |
+
|
| 1285 |
+
@app.post("/release_task", response_model=CreateJobResponse)
|
| 1286 |
+
async def create_music_generate_job(request: Request) -> CreateJobResponse:
|
| 1287 |
+
content_type = (request.headers.get("content-type") or "").lower()
|
| 1288 |
+
temp_files: list[str] = []
|
| 1289 |
+
|
| 1290 |
+
def _build_request(p: RequestParser, **kwargs) -> GenerateMusicRequest:
|
| 1291 |
+
"""Build GenerateMusicRequest from parsed parameters."""
|
| 1292 |
+
return GenerateMusicRequest(
|
| 1293 |
+
prompt=p.str("prompt"),
|
| 1294 |
+
lyrics=p.str("lyrics"),
|
| 1295 |
+
thinking=p.bool("thinking"),
|
| 1296 |
+
sample_mode=p.bool("sample_mode"),
|
| 1297 |
+
sample_query=p.str("sample_query"),
|
| 1298 |
+
use_format=p.bool("use_format"),
|
| 1299 |
+
model=p.str("model") or None,
|
| 1300 |
+
bpm=p.int("bpm"),
|
| 1301 |
+
key_scale=p.str("key_scale"),
|
| 1302 |
+
time_signature=p.str("time_signature"),
|
| 1303 |
+
audio_duration=p.float("audio_duration"),
|
| 1304 |
+
vocal_language=p.str("vocal_language", "en"),
|
| 1305 |
+
inference_steps=p.int("inference_steps", 8),
|
| 1306 |
+
guidance_scale=p.float("guidance_scale", 7.0),
|
| 1307 |
+
use_random_seed=p.bool("use_random_seed", True),
|
| 1308 |
+
seed=p.int("seed", -1),
|
| 1309 |
+
batch_size=p.int("batch_size"),
|
| 1310 |
+
audio_code_string=p.str("audio_code_string"),
|
| 1311 |
+
repainting_start=p.float("repainting_start", 0.0),
|
| 1312 |
+
repainting_end=p.float("repainting_end"),
|
| 1313 |
+
instruction=p.str("instruction", DEFAULT_DIT_INSTRUCTION),
|
| 1314 |
+
audio_cover_strength=p.float("audio_cover_strength", 1.0),
|
| 1315 |
+
task_type=p.str("task_type", "text2music"),
|
| 1316 |
+
use_adg=p.bool("use_adg"),
|
| 1317 |
+
cfg_interval_start=p.float("cfg_interval_start", 0.0),
|
| 1318 |
+
cfg_interval_end=p.float("cfg_interval_end", 1.0),
|
| 1319 |
+
infer_method=p.str("infer_method", "ode"),
|
| 1320 |
+
shift=p.float("shift", 3.0),
|
| 1321 |
+
audio_format=p.str("audio_format", "mp3"),
|
| 1322 |
+
use_tiled_decode=p.bool("use_tiled_decode", True),
|
| 1323 |
+
lm_model_path=p.str("lm_model_path") or None,
|
| 1324 |
+
lm_backend=p.str("lm_backend", "vllm"),
|
| 1325 |
+
lm_temperature=p.float("lm_temperature", LM_DEFAULT_TEMPERATURE),
|
| 1326 |
+
lm_cfg_scale=p.float("lm_cfg_scale", LM_DEFAULT_CFG_SCALE),
|
| 1327 |
+
lm_top_k=p.int("lm_top_k"),
|
| 1328 |
+
lm_top_p=p.float("lm_top_p", LM_DEFAULT_TOP_P),
|
| 1329 |
+
lm_repetition_penalty=p.float("lm_repetition_penalty", 1.0),
|
| 1330 |
+
lm_negative_prompt=p.str("lm_negative_prompt", "NO USER INPUT"),
|
| 1331 |
+
constrained_decoding=p.bool("constrained_decoding", True),
|
| 1332 |
+
constrained_decoding_debug=p.bool("constrained_decoding_debug"),
|
| 1333 |
+
use_cot_caption=p.bool("use_cot_caption", True),
|
| 1334 |
+
use_cot_language=p.bool("use_cot_language", True),
|
| 1335 |
+
is_format_caption=p.bool("is_format_caption"),
|
| 1336 |
+
**kwargs,
|
| 1337 |
+
)
|
| 1338 |
+
|
| 1339 |
+
if content_type.startswith("application/json"):
|
| 1340 |
+
body = await request.json()
|
| 1341 |
+
if not isinstance(body, dict):
|
| 1342 |
+
raise HTTPException(status_code=400, detail="JSON payload must be an object")
|
| 1343 |
+
req = _build_request(RequestParser(body))
|
| 1344 |
+
|
| 1345 |
+
elif content_type.endswith("+json"):
|
| 1346 |
+
body = await request.json()
|
| 1347 |
+
if not isinstance(body, dict):
|
| 1348 |
+
raise HTTPException(status_code=400, detail="JSON payload must be an object")
|
| 1349 |
+
req = _build_request(RequestParser(body))
|
| 1350 |
+
|
| 1351 |
+
elif content_type.startswith("multipart/form-data"):
|
| 1352 |
+
form = await request.form()
|
| 1353 |
+
|
| 1354 |
+
ref_up = form.get("reference_audio")
|
| 1355 |
+
src_up = form.get("src_audio")
|
| 1356 |
+
|
| 1357 |
+
reference_audio_path = None
|
| 1358 |
+
src_audio_path = None
|
| 1359 |
+
|
| 1360 |
+
if isinstance(ref_up, StarletteUploadFile):
|
| 1361 |
+
reference_audio_path = await _save_upload_to_temp(ref_up, prefix="reference_audio")
|
| 1362 |
+
temp_files.append(reference_audio_path)
|
| 1363 |
+
else:
|
| 1364 |
+
reference_audio_path = str(form.get("reference_audio_path") or "").strip() or None
|
| 1365 |
+
|
| 1366 |
+
if isinstance(src_up, StarletteUploadFile):
|
| 1367 |
+
src_audio_path = await _save_upload_to_temp(src_up, prefix="src_audio")
|
| 1368 |
+
temp_files.append(src_audio_path)
|
| 1369 |
+
else:
|
| 1370 |
+
src_audio_path = str(form.get("src_audio_path") or "").strip() or None
|
| 1371 |
+
|
| 1372 |
+
req = _build_request(
|
| 1373 |
+
RequestParser(dict(form)),
|
| 1374 |
+
reference_audio_path=reference_audio_path,
|
| 1375 |
+
src_audio_path=src_audio_path,
|
| 1376 |
+
)
|
| 1377 |
+
|
| 1378 |
+
elif content_type.startswith("application/x-www-form-urlencoded"):
|
| 1379 |
+
form = await request.form()
|
| 1380 |
+
reference_audio_path = str(form.get("reference_audio_path") or "").strip() or None
|
| 1381 |
+
src_audio_path = str(form.get("src_audio_path") or "").strip() or None
|
| 1382 |
+
req = _build_request(
|
| 1383 |
+
RequestParser(dict(form)),
|
| 1384 |
+
reference_audio_path=reference_audio_path,
|
| 1385 |
+
src_audio_path=src_audio_path,
|
| 1386 |
+
)
|
| 1387 |
+
|
| 1388 |
+
else:
|
| 1389 |
+
raw = await request.body()
|
| 1390 |
+
raw_stripped = raw.lstrip()
|
| 1391 |
+
# Best-effort: accept missing/incorrect Content-Type if payload is valid JSON.
|
| 1392 |
+
if raw_stripped.startswith(b"{") or raw_stripped.startswith(b"["):
|
| 1393 |
+
try:
|
| 1394 |
+
body = json.loads(raw.decode("utf-8"))
|
| 1395 |
+
if isinstance(body, dict):
|
| 1396 |
+
req = _build_request(RequestParser(body))
|
| 1397 |
+
else:
|
| 1398 |
+
raise HTTPException(status_code=400, detail="JSON payload must be an object")
|
| 1399 |
+
except HTTPException:
|
| 1400 |
+
raise
|
| 1401 |
+
except Exception:
|
| 1402 |
+
raise HTTPException(
|
| 1403 |
+
status_code=400,
|
| 1404 |
+
detail="Invalid JSON body (hint: set 'Content-Type: application/json')",
|
| 1405 |
+
)
|
| 1406 |
+
# Best-effort: parse key=value bodies even if Content-Type is missing.
|
| 1407 |
+
elif raw_stripped and b"=" in raw:
|
| 1408 |
+
parsed = urllib.parse.parse_qs(raw.decode("utf-8"), keep_blank_values=True)
|
| 1409 |
+
flat = {k: (v[0] if isinstance(v, list) and v else v) for k, v in parsed.items()}
|
| 1410 |
+
reference_audio_path = str(flat.get("reference_audio_path") or "").strip() or None
|
| 1411 |
+
src_audio_path = str(flat.get("src_audio_path") or "").strip() or None
|
| 1412 |
+
req = _build_request(
|
| 1413 |
+
RequestParser(flat),
|
| 1414 |
+
reference_audio_path=reference_audio_path,
|
| 1415 |
+
src_audio_path=src_audio_path,
|
| 1416 |
+
)
|
| 1417 |
+
else:
|
| 1418 |
+
raise HTTPException(
|
| 1419 |
+
status_code=415,
|
| 1420 |
+
detail=(
|
| 1421 |
+
f"Unsupported Content-Type: {content_type or '(missing)'}; "
|
| 1422 |
+
"use application/json, application/x-www-form-urlencoded, or multipart/form-data"
|
| 1423 |
+
),
|
| 1424 |
+
)
|
| 1425 |
+
|
| 1426 |
+
rec = store.create()
|
| 1427 |
+
|
| 1428 |
+
q: asyncio.Queue = app.state.job_queue
|
| 1429 |
+
if q.full():
|
| 1430 |
+
for p in temp_files:
|
| 1431 |
+
try:
|
| 1432 |
+
os.remove(p)
|
| 1433 |
+
except Exception:
|
| 1434 |
+
pass
|
| 1435 |
+
raise HTTPException(status_code=429, detail="Server busy: queue is full")
|
| 1436 |
+
|
| 1437 |
+
if temp_files:
|
| 1438 |
+
async with app.state.job_temp_files_lock:
|
| 1439 |
+
app.state.job_temp_files[rec.job_id] = temp_files
|
| 1440 |
+
|
| 1441 |
+
async with app.state.pending_lock:
|
| 1442 |
+
app.state.pending_ids.append(rec.job_id)
|
| 1443 |
+
position = len(app.state.pending_ids)
|
| 1444 |
+
|
| 1445 |
+
await q.put((rec.job_id, req))
|
| 1446 |
+
return CreateJobResponse(task_id=rec.job_id, status="queued", queue_position=position)
|
| 1447 |
+
|
| 1448 |
+
@app.post("/v1/music/random", response_model=CreateJobResponse)
|
| 1449 |
+
async def create_random_sample_job(request: Request) -> CreateJobResponse:
|
| 1450 |
+
"""Create a sample-mode job that auto-generates caption/lyrics via LM."""
|
| 1451 |
+
|
| 1452 |
+
thinking_value: Any = None
|
| 1453 |
+
content_type = (request.headers.get("content-type") or "").lower()
|
| 1454 |
+
body_dict: Dict[str, Any] = {}
|
| 1455 |
+
|
| 1456 |
+
if "json" in content_type:
|
| 1457 |
+
try:
|
| 1458 |
+
payload = await request.json()
|
| 1459 |
+
if isinstance(payload, dict):
|
| 1460 |
+
body_dict = payload
|
| 1461 |
+
except Exception:
|
| 1462 |
+
body_dict = {}
|
| 1463 |
+
|
| 1464 |
+
if not body_dict and request.query_params:
|
| 1465 |
+
body_dict = dict(request.query_params)
|
| 1466 |
+
|
| 1467 |
+
thinking_value = body_dict.get("thinking")
|
| 1468 |
+
if thinking_value is None:
|
| 1469 |
+
thinking_value = body_dict.get("Thinking")
|
| 1470 |
+
|
| 1471 |
+
thinking_flag = _to_bool(thinking_value, True)
|
| 1472 |
+
|
| 1473 |
+
req = GenerateMusicRequest(
|
| 1474 |
+
caption="",
|
| 1475 |
+
lyrics="",
|
| 1476 |
+
thinking=thinking_flag,
|
| 1477 |
+
sample_mode=True,
|
| 1478 |
+
)
|
| 1479 |
+
|
| 1480 |
+
rec = store.create()
|
| 1481 |
+
q: asyncio.Queue = app.state.job_queue
|
| 1482 |
+
if q.full():
|
| 1483 |
+
raise HTTPException(status_code=429, detail="Server busy: queue is full")
|
| 1484 |
+
|
| 1485 |
+
async with app.state.pending_lock:
|
| 1486 |
+
app.state.pending_ids.append(rec.job_id)
|
| 1487 |
+
position = len(app.state.pending_ids)
|
| 1488 |
+
|
| 1489 |
+
await q.put((rec.job_id, req))
|
| 1490 |
+
return CreateJobResponse(task_id=rec.job_id, status="queued", queue_position=position)
|
| 1491 |
+
|
| 1492 |
+
@app.post("/query_result")
|
| 1493 |
+
async def query_result(request: Request) -> List[Dict[str, Any]]:
|
| 1494 |
+
"""Batch query job results"""
|
| 1495 |
+
content_type = (request.headers.get("content-type") or "").lower()
|
| 1496 |
+
|
| 1497 |
+
if "json" in content_type:
|
| 1498 |
+
body = await request.json()
|
| 1499 |
+
else:
|
| 1500 |
+
form = await request.form()
|
| 1501 |
+
body = {k: v for k, v in form.items()}
|
| 1502 |
+
|
| 1503 |
+
task_id_list_str = body.get("task_id_list", "[]")
|
| 1504 |
+
|
| 1505 |
+
# Parse task ID list
|
| 1506 |
+
if isinstance(task_id_list_str, list):
|
| 1507 |
+
task_id_list = task_id_list_str
|
| 1508 |
+
else:
|
| 1509 |
+
try:
|
| 1510 |
+
task_id_list = json.loads(task_id_list_str)
|
| 1511 |
+
except Exception:
|
| 1512 |
+
task_id_list = []
|
| 1513 |
+
|
| 1514 |
+
local_cache = getattr(app.state, 'local_cache', None)
|
| 1515 |
+
data_list = []
|
| 1516 |
+
current_time = time.time()
|
| 1517 |
+
|
| 1518 |
+
for task_id in task_id_list:
|
| 1519 |
+
result_key = f"{RESULT_KEY_PREFIX}{task_id}"
|
| 1520 |
+
|
| 1521 |
+
# Read from local cache first
|
| 1522 |
+
if local_cache:
|
| 1523 |
+
data = local_cache.get(result_key)
|
| 1524 |
+
if data:
|
| 1525 |
+
try:
|
| 1526 |
+
data_json = json.loads(data)
|
| 1527 |
+
except Exception:
|
| 1528 |
+
data_json = []
|
| 1529 |
+
|
| 1530 |
+
if len(data_json) <= 0:
|
| 1531 |
+
data_list.append({"task_id": task_id, "result": data, "status": 2})
|
| 1532 |
+
else:
|
| 1533 |
+
status = data_json[0].get("status")
|
| 1534 |
+
create_time = data_json[0].get("create_time", 0)
|
| 1535 |
+
if status == 0 and (current_time - create_time) > TASK_TIMEOUT_SECONDS:
|
| 1536 |
+
data_list.append({"task_id": task_id, "result": data, "status": 2})
|
| 1537 |
+
else:
|
| 1538 |
+
data_list.append({
|
| 1539 |
+
"task_id": task_id,
|
| 1540 |
+
"result": data,
|
| 1541 |
+
"status": int(status) if status is not None else 1,
|
| 1542 |
+
})
|
| 1543 |
+
continue
|
| 1544 |
+
|
| 1545 |
+
# Fallback to job_store query
|
| 1546 |
+
rec = store.get(task_id)
|
| 1547 |
+
if rec:
|
| 1548 |
+
env = getattr(rec, 'env', 'development')
|
| 1549 |
+
create_time = rec.created_at
|
| 1550 |
+
status_int = _map_status(rec.status)
|
| 1551 |
+
|
| 1552 |
+
if rec.result and rec.status == "succeeded":
|
| 1553 |
+
audio_paths = rec.result.get("audio_paths", [])
|
| 1554 |
+
metas = rec.result.get("metas", {}) or {}
|
| 1555 |
+
result_data = [
|
| 1556 |
+
{
|
| 1557 |
+
"file": p, "wave": "", "status": status_int,
|
| 1558 |
+
"create_time": int(create_time), "env": env,
|
| 1559 |
+
"prompt": metas.get("caption", ""),
|
| 1560 |
+
"lyrics": metas.get("lyrics", ""),
|
| 1561 |
+
"metas": {
|
| 1562 |
+
"bpm": metas.get("bpm"),
|
| 1563 |
+
"duration": metas.get("duration"),
|
| 1564 |
+
"genres": metas.get("genres", ""),
|
| 1565 |
+
"keyscale": metas.get("keyscale", ""),
|
| 1566 |
+
"timesignature": metas.get("timesignature", ""),
|
| 1567 |
+
}
|
| 1568 |
+
}
|
| 1569 |
+
for p in audio_paths
|
| 1570 |
+
] if audio_paths else [{
|
| 1571 |
+
"file": "", "wave": "", "status": status_int,
|
| 1572 |
+
"create_time": int(create_time), "env": env,
|
| 1573 |
+
"prompt": metas.get("caption", ""),
|
| 1574 |
+
"lyrics": metas.get("lyrics", ""),
|
| 1575 |
+
"metas": {
|
| 1576 |
+
"bpm": metas.get("bpm"),
|
| 1577 |
+
"duration": metas.get("duration"),
|
| 1578 |
+
"genres": metas.get("genres", ""),
|
| 1579 |
+
"keyscale": metas.get("keyscale", ""),
|
| 1580 |
+
"timesignature": metas.get("timesignature", ""),
|
| 1581 |
+
}
|
| 1582 |
+
}]
|
| 1583 |
+
else:
|
| 1584 |
+
result_data = [{
|
| 1585 |
+
"file": "", "wave": "", "status": status_int,
|
| 1586 |
+
"create_time": int(create_time), "env": env,
|
| 1587 |
+
"prompt": "", "lyrics": "",
|
| 1588 |
+
"metas": {}
|
| 1589 |
+
}]
|
| 1590 |
+
|
| 1591 |
+
data_list.append({
|
| 1592 |
+
"task_id": task_id,
|
| 1593 |
+
"result": json.dumps(result_data, ensure_ascii=False),
|
| 1594 |
+
"status": status_int,
|
| 1595 |
+
})
|
| 1596 |
+
else:
|
| 1597 |
+
data_list.append({"task_id": task_id, "result": "[]", "status": 0})
|
| 1598 |
+
|
| 1599 |
+
return data_list
|
| 1600 |
+
|
| 1601 |
+
@app.get("/health")
|
| 1602 |
+
async def health_check():
|
| 1603 |
+
"""Health check endpoint for service status."""
|
| 1604 |
+
return {
|
| 1605 |
+
"status": "ok",
|
| 1606 |
+
"service": "ACE-Step API",
|
| 1607 |
+
"version": "1.0",
|
| 1608 |
+
}
|
| 1609 |
+
|
| 1610 |
+
@app.get("/v1/models")
|
| 1611 |
+
async def list_models():
|
| 1612 |
+
"""List available DiT models."""
|
| 1613 |
+
models = []
|
| 1614 |
+
|
| 1615 |
+
# Primary model (always available if initialized)
|
| 1616 |
+
if getattr(app.state, "_initialized", False):
|
| 1617 |
+
primary_model = _get_model_name(app.state._config_path)
|
| 1618 |
+
if primary_model:
|
| 1619 |
+
models.append({
|
| 1620 |
+
"name": primary_model,
|
| 1621 |
+
"is_default": True,
|
| 1622 |
+
})
|
| 1623 |
+
|
| 1624 |
+
# Secondary model
|
| 1625 |
+
if getattr(app.state, "_initialized2", False) and app.state._config_path2:
|
| 1626 |
+
secondary_model = _get_model_name(app.state._config_path2)
|
| 1627 |
+
if secondary_model:
|
| 1628 |
+
models.append({
|
| 1629 |
+
"name": secondary_model,
|
| 1630 |
+
"is_default": False,
|
| 1631 |
+
})
|
| 1632 |
+
|
| 1633 |
+
# Third model
|
| 1634 |
+
if getattr(app.state, "_initialized3", False) and app.state._config_path3:
|
| 1635 |
+
third_model = _get_model_name(app.state._config_path3)
|
| 1636 |
+
if third_model:
|
| 1637 |
+
models.append({
|
| 1638 |
+
"name": third_model,
|
| 1639 |
+
"is_default": False,
|
| 1640 |
+
})
|
| 1641 |
+
|
| 1642 |
+
return {
|
| 1643 |
+
"models": models,
|
| 1644 |
+
"default_model": models[0]["name"] if models else None,
|
| 1645 |
+
}
|
| 1646 |
+
|
| 1647 |
+
@app.get("/v1/audio")
|
| 1648 |
+
async def get_audio(path: str):
|
| 1649 |
+
"""Serve audio file by path."""
|
| 1650 |
+
from fastapi.responses import FileResponse
|
| 1651 |
+
|
| 1652 |
+
if not os.path.exists(path):
|
| 1653 |
+
raise HTTPException(status_code=404, detail=f"Audio file not found: {path}")
|
| 1654 |
+
|
| 1655 |
+
ext = os.path.splitext(path)[1].lower()
|
| 1656 |
+
media_types = {
|
| 1657 |
+
".mp3": "audio/mpeg",
|
| 1658 |
+
".wav": "audio/wav",
|
| 1659 |
+
".flac": "audio/flac",
|
| 1660 |
+
".ogg": "audio/ogg",
|
| 1661 |
+
}
|
| 1662 |
+
media_type = media_types.get(ext, "audio/mpeg")
|
| 1663 |
+
|
| 1664 |
+
return FileResponse(path, media_type=media_type)
|
| 1665 |
+
|
| 1666 |
+
return app
|
| 1667 |
+
|
| 1668 |
+
|
| 1669 |
+
app = create_app()
|
| 1670 |
+
|
| 1671 |
+
|
| 1672 |
+
def main() -> None:
|
| 1673 |
+
import argparse
|
| 1674 |
+
import uvicorn
|
| 1675 |
+
|
| 1676 |
+
parser = argparse.ArgumentParser(description="ACE-Step API server")
|
| 1677 |
+
parser.add_argument(
|
| 1678 |
+
"--host",
|
| 1679 |
+
default=os.getenv("ACESTEP_API_HOST", "127.0.0.1"),
|
| 1680 |
+
help="Bind host (default from ACESTEP_API_HOST or 127.0.0.1)",
|
| 1681 |
+
)
|
| 1682 |
+
parser.add_argument(
|
| 1683 |
+
"--port",
|
| 1684 |
+
type=int,
|
| 1685 |
+
default=int(os.getenv("ACESTEP_API_PORT", "8001")),
|
| 1686 |
+
help="Bind port (default from ACESTEP_API_PORT or 8001)",
|
| 1687 |
+
)
|
| 1688 |
+
args = parser.parse_args()
|
| 1689 |
+
|
| 1690 |
+
# IMPORTANT: in-memory queue/store -> workers MUST be 1
|
| 1691 |
+
uvicorn.run(
|
| 1692 |
+
"acestep.api_server:app",
|
| 1693 |
+
host=str(args.host),
|
| 1694 |
+
port=int(args.port),
|
| 1695 |
+
reload=False,
|
| 1696 |
+
workers=1,
|
| 1697 |
+
)
|
| 1698 |
+
|
| 1699 |
+
if __name__ == "__main__":
|
| 1700 |
+
main()
|
acestep/audio_utils.py
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Audio saving and transcoding utility module
|
| 3 |
+
|
| 4 |
+
Independent audio file operations outside of handler, supporting:
|
| 5 |
+
- Save audio tensor/numpy to files (default FLAC format, fast)
|
| 6 |
+
- Format conversion (FLAC/WAV/MP3)
|
| 7 |
+
- Batch processing
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
# Disable torchcodec backend to avoid CUDA dependency issues on HuggingFace Space
|
| 13 |
+
# This forces torchaudio to use ffmpeg/sox/soundfile backends instead
|
| 14 |
+
os.environ["TORCHAUDIO_USE_TORCHCODEC"] = "0"
|
| 15 |
+
|
| 16 |
+
import hashlib
|
| 17 |
+
import json
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Union, Optional, List, Tuple
|
| 20 |
+
import torch
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torchaudio
|
| 23 |
+
from loguru import logger
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class AudioSaver:
|
| 27 |
+
"""Audio saving and transcoding utility class"""
|
| 28 |
+
|
| 29 |
+
def __init__(self, default_format: str = "flac"):
|
| 30 |
+
"""
|
| 31 |
+
Initialize audio saver
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
default_format: Default save format ('flac', 'wav', 'mp3')
|
| 35 |
+
"""
|
| 36 |
+
self.default_format = default_format.lower()
|
| 37 |
+
if self.default_format not in ["flac", "wav", "mp3"]:
|
| 38 |
+
logger.warning(f"Unsupported format {default_format}, using 'flac'")
|
| 39 |
+
self.default_format = "flac"
|
| 40 |
+
|
| 41 |
+
def save_audio(
|
| 42 |
+
self,
|
| 43 |
+
audio_data: Union[torch.Tensor, np.ndarray],
|
| 44 |
+
output_path: Union[str, Path],
|
| 45 |
+
sample_rate: int = 48000,
|
| 46 |
+
format: Optional[str] = None,
|
| 47 |
+
channels_first: bool = True,
|
| 48 |
+
) -> str:
|
| 49 |
+
"""
|
| 50 |
+
Save audio data to file
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
audio_data: Audio data, torch.Tensor [channels, samples] or numpy.ndarray
|
| 54 |
+
output_path: Output file path (extension can be omitted)
|
| 55 |
+
sample_rate: Sample rate
|
| 56 |
+
format: Audio format ('flac', 'wav', 'mp3'), defaults to default_format
|
| 57 |
+
channels_first: If True, tensor format is [channels, samples], else [samples, channels]
|
| 58 |
+
|
| 59 |
+
Returns:
|
| 60 |
+
Actual saved file path
|
| 61 |
+
"""
|
| 62 |
+
format = (format or self.default_format).lower()
|
| 63 |
+
if format not in ["flac", "wav", "mp3"]:
|
| 64 |
+
logger.warning(f"Unsupported format {format}, using {self.default_format}")
|
| 65 |
+
format = self.default_format
|
| 66 |
+
|
| 67 |
+
# Ensure output path has correct extension
|
| 68 |
+
output_path = Path(output_path)
|
| 69 |
+
if output_path.suffix.lower() not in ['.flac', '.wav', '.mp3']:
|
| 70 |
+
output_path = output_path.with_suffix(f'.{format}')
|
| 71 |
+
|
| 72 |
+
# Convert to torch tensor
|
| 73 |
+
if isinstance(audio_data, np.ndarray):
|
| 74 |
+
if channels_first:
|
| 75 |
+
# numpy [samples, channels] -> tensor [channels, samples]
|
| 76 |
+
audio_tensor = torch.from_numpy(audio_data.T).float()
|
| 77 |
+
else:
|
| 78 |
+
# numpy [samples, channels] -> tensor [samples, channels] -> [channels, samples]
|
| 79 |
+
audio_tensor = torch.from_numpy(audio_data).float()
|
| 80 |
+
if audio_tensor.dim() == 2 and audio_tensor.shape[0] < audio_tensor.shape[1]:
|
| 81 |
+
audio_tensor = audio_tensor.T
|
| 82 |
+
else:
|
| 83 |
+
# torch tensor
|
| 84 |
+
audio_tensor = audio_data.cpu().float()
|
| 85 |
+
if not channels_first and audio_tensor.dim() == 2:
|
| 86 |
+
# [samples, channels] -> [channels, samples]
|
| 87 |
+
if audio_tensor.shape[0] > audio_tensor.shape[1]:
|
| 88 |
+
audio_tensor = audio_tensor.T
|
| 89 |
+
|
| 90 |
+
# Ensure memory is contiguous
|
| 91 |
+
audio_tensor = audio_tensor.contiguous()
|
| 92 |
+
|
| 93 |
+
# Select backend and save
|
| 94 |
+
try:
|
| 95 |
+
if format == "mp3":
|
| 96 |
+
# MP3 uses ffmpeg backend
|
| 97 |
+
torchaudio.save(
|
| 98 |
+
str(output_path),
|
| 99 |
+
audio_tensor,
|
| 100 |
+
sample_rate,
|
| 101 |
+
channels_first=True,
|
| 102 |
+
backend='ffmpeg',
|
| 103 |
+
)
|
| 104 |
+
elif format in ["flac", "wav"]:
|
| 105 |
+
# FLAC and WAV use soundfile backend (fastest)
|
| 106 |
+
torchaudio.save(
|
| 107 |
+
str(output_path),
|
| 108 |
+
audio_tensor,
|
| 109 |
+
sample_rate,
|
| 110 |
+
channels_first=True,
|
| 111 |
+
backend='soundfile',
|
| 112 |
+
)
|
| 113 |
+
else:
|
| 114 |
+
# Other formats use default backend
|
| 115 |
+
torchaudio.save(
|
| 116 |
+
str(output_path),
|
| 117 |
+
audio_tensor,
|
| 118 |
+
sample_rate,
|
| 119 |
+
channels_first=True,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
logger.debug(f"[AudioSaver] Saved audio to {output_path} ({format}, {sample_rate}Hz)")
|
| 123 |
+
return str(output_path)
|
| 124 |
+
|
| 125 |
+
except Exception as e:
|
| 126 |
+
try:
|
| 127 |
+
import soundfile as sf
|
| 128 |
+
audio_np = audio_tensor.transpose(0, 1).numpy() # -> [samples, channels]
|
| 129 |
+
sf.write(str(output_path), audio_np, sample_rate, format=format.upper())
|
| 130 |
+
logger.debug(f"[AudioSaver] Fallback soundfile Saved audio to {output_path} ({format}, {sample_rate}Hz)")
|
| 131 |
+
return str(output_path)
|
| 132 |
+
except Exception as e:
|
| 133 |
+
logger.error(f"[AudioSaver] Failed to save audio: {e}")
|
| 134 |
+
raise
|
| 135 |
+
|
| 136 |
+
def _load_audio_file(self, audio_file: Union[str, Path]) -> Tuple[torch.Tensor, int]:
|
| 137 |
+
"""
|
| 138 |
+
Load audio file with ffmpeg backend, fallback to soundfile if failed.
|
| 139 |
+
|
| 140 |
+
This handles CUDA dependency issues with torchcodec on HuggingFace Space.
|
| 141 |
+
|
| 142 |
+
Args:
|
| 143 |
+
audio_file: Path to the audio file
|
| 144 |
+
|
| 145 |
+
Returns:
|
| 146 |
+
Tuple of (audio_tensor, sample_rate)
|
| 147 |
+
|
| 148 |
+
Raises:
|
| 149 |
+
FileNotFoundError: If the audio file doesn't exist
|
| 150 |
+
Exception: If all methods fail to load the audio
|
| 151 |
+
"""
|
| 152 |
+
audio_file = str(audio_file)
|
| 153 |
+
|
| 154 |
+
# Check if file exists first
|
| 155 |
+
if not Path(audio_file).exists():
|
| 156 |
+
raise FileNotFoundError(f"Audio file not found: {audio_file}")
|
| 157 |
+
|
| 158 |
+
# Try torchaudio with explicit ffmpeg backend first
|
| 159 |
+
try:
|
| 160 |
+
audio, sr = torchaudio.load(audio_file, backend="ffmpeg")
|
| 161 |
+
return audio, sr
|
| 162 |
+
except Exception as e:
|
| 163 |
+
logger.debug(f"[AudioSaver._load_audio_file] ffmpeg backend failed: {e}, trying soundfile fallback")
|
| 164 |
+
|
| 165 |
+
# Fallback: use soundfile directly (most compatible)
|
| 166 |
+
try:
|
| 167 |
+
import soundfile as sf
|
| 168 |
+
audio_np, sr = sf.read(audio_file)
|
| 169 |
+
# soundfile returns [samples, channels] or [samples], convert to [channels, samples]
|
| 170 |
+
audio = torch.from_numpy(audio_np).float()
|
| 171 |
+
if audio.dim() == 1:
|
| 172 |
+
# Mono: [samples] -> [1, samples]
|
| 173 |
+
audio = audio.unsqueeze(0)
|
| 174 |
+
else:
|
| 175 |
+
# Stereo: [samples, channels] -> [channels, samples]
|
| 176 |
+
audio = audio.T
|
| 177 |
+
return audio, sr
|
| 178 |
+
except Exception as e:
|
| 179 |
+
logger.error(f"[AudioSaver._load_audio_file] All methods failed to load audio: {audio_file}, error: {e}")
|
| 180 |
+
raise
|
| 181 |
+
|
| 182 |
+
def convert_audio(
|
| 183 |
+
self,
|
| 184 |
+
input_path: Union[str, Path],
|
| 185 |
+
output_path: Union[str, Path],
|
| 186 |
+
output_format: str,
|
| 187 |
+
remove_input: bool = False,
|
| 188 |
+
) -> str:
|
| 189 |
+
"""
|
| 190 |
+
Convert audio format
|
| 191 |
+
|
| 192 |
+
Args:
|
| 193 |
+
input_path: Input audio file path
|
| 194 |
+
output_path: Output audio file path
|
| 195 |
+
output_format: Target format ('flac', 'wav', 'mp3')
|
| 196 |
+
remove_input: Whether to delete input file
|
| 197 |
+
|
| 198 |
+
Returns:
|
| 199 |
+
Output file path
|
| 200 |
+
"""
|
| 201 |
+
input_path = Path(input_path)
|
| 202 |
+
output_path = Path(output_path)
|
| 203 |
+
|
| 204 |
+
if not input_path.exists():
|
| 205 |
+
raise FileNotFoundError(f"Input file not found: {input_path}")
|
| 206 |
+
|
| 207 |
+
# Load audio with fallback backends
|
| 208 |
+
audio_tensor, sample_rate = self._load_audio_file(input_path)
|
| 209 |
+
|
| 210 |
+
# Save as new format
|
| 211 |
+
output_path = self.save_audio(
|
| 212 |
+
audio_tensor,
|
| 213 |
+
output_path,
|
| 214 |
+
sample_rate=sample_rate,
|
| 215 |
+
format=output_format,
|
| 216 |
+
channels_first=True
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
# Delete input file if needed
|
| 220 |
+
if remove_input:
|
| 221 |
+
input_path.unlink()
|
| 222 |
+
logger.debug(f"[AudioSaver] Removed input file: {input_path}")
|
| 223 |
+
|
| 224 |
+
return output_path
|
| 225 |
+
|
| 226 |
+
def save_batch(
|
| 227 |
+
self,
|
| 228 |
+
audio_batch: Union[List[torch.Tensor], torch.Tensor],
|
| 229 |
+
output_dir: Union[str, Path],
|
| 230 |
+
file_prefix: str = "audio",
|
| 231 |
+
sample_rate: int = 48000,
|
| 232 |
+
format: Optional[str] = None,
|
| 233 |
+
channels_first: bool = True,
|
| 234 |
+
) -> List[str]:
|
| 235 |
+
"""
|
| 236 |
+
Save audio batch
|
| 237 |
+
|
| 238 |
+
Args:
|
| 239 |
+
audio_batch: Audio batch, List[tensor] or tensor [batch, channels, samples]
|
| 240 |
+
output_dir: Output directory
|
| 241 |
+
file_prefix: File prefix
|
| 242 |
+
sample_rate: Sample rate
|
| 243 |
+
format: Audio format
|
| 244 |
+
channels_first: Tensor format flag
|
| 245 |
+
|
| 246 |
+
Returns:
|
| 247 |
+
List of saved file paths
|
| 248 |
+
"""
|
| 249 |
+
output_dir = Path(output_dir)
|
| 250 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 251 |
+
|
| 252 |
+
# Process batch
|
| 253 |
+
if isinstance(audio_batch, torch.Tensor) and audio_batch.dim() == 3:
|
| 254 |
+
# [batch, channels, samples]
|
| 255 |
+
audio_list = [audio_batch[i] for i in range(audio_batch.shape[0])]
|
| 256 |
+
elif isinstance(audio_batch, list):
|
| 257 |
+
audio_list = audio_batch
|
| 258 |
+
else:
|
| 259 |
+
audio_list = [audio_batch]
|
| 260 |
+
|
| 261 |
+
saved_paths = []
|
| 262 |
+
for i, audio in enumerate(audio_list):
|
| 263 |
+
output_path = output_dir / f"{file_prefix}_{i:04d}"
|
| 264 |
+
saved_path = self.save_audio(
|
| 265 |
+
audio,
|
| 266 |
+
output_path,
|
| 267 |
+
sample_rate=sample_rate,
|
| 268 |
+
format=format,
|
| 269 |
+
channels_first=channels_first
|
| 270 |
+
)
|
| 271 |
+
saved_paths.append(saved_path)
|
| 272 |
+
|
| 273 |
+
return saved_paths
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def get_audio_file_hash(audio_file) -> str:
|
| 277 |
+
"""
|
| 278 |
+
Get hash identifier for an audio file.
|
| 279 |
+
|
| 280 |
+
Args:
|
| 281 |
+
audio_file: Path to audio file (str) or file-like object
|
| 282 |
+
|
| 283 |
+
Returns:
|
| 284 |
+
Hash string or empty string
|
| 285 |
+
"""
|
| 286 |
+
if audio_file is None:
|
| 287 |
+
return ""
|
| 288 |
+
|
| 289 |
+
try:
|
| 290 |
+
if isinstance(audio_file, str):
|
| 291 |
+
if os.path.exists(audio_file):
|
| 292 |
+
with open(audio_file, 'rb') as f:
|
| 293 |
+
return hashlib.md5(f.read()).hexdigest()
|
| 294 |
+
return hashlib.md5(audio_file.encode('utf-8')).hexdigest()
|
| 295 |
+
elif hasattr(audio_file, 'name'):
|
| 296 |
+
return hashlib.md5(str(audio_file.name).encode('utf-8')).hexdigest()
|
| 297 |
+
return hashlib.md5(str(audio_file).encode('utf-8')).hexdigest()
|
| 298 |
+
except Exception:
|
| 299 |
+
return hashlib.md5(str(audio_file).encode('utf-8')).hexdigest()
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def generate_uuid_from_params(params_dict) -> str:
|
| 303 |
+
"""
|
| 304 |
+
Generate deterministic UUID from generation parameters.
|
| 305 |
+
Same parameters will always generate the same UUID.
|
| 306 |
+
|
| 307 |
+
Args:
|
| 308 |
+
params_dict: Dictionary of parameters
|
| 309 |
+
|
| 310 |
+
Returns:
|
| 311 |
+
UUID string
|
| 312 |
+
"""
|
| 313 |
+
|
| 314 |
+
params_json = json.dumps(params_dict, sort_keys=True, ensure_ascii=False)
|
| 315 |
+
hash_obj = hashlib.sha256(params_json.encode('utf-8'))
|
| 316 |
+
hash_hex = hash_obj.hexdigest()
|
| 317 |
+
uuid_str = f"{hash_hex[0:8]}-{hash_hex[8:12]}-{hash_hex[12:16]}-{hash_hex[16:20]}-{hash_hex[20:32]}"
|
| 318 |
+
return uuid_str
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def generate_uuid_from_audio_data(
|
| 322 |
+
audio_data: Union[torch.Tensor, np.ndarray],
|
| 323 |
+
seed: Optional[int] = None
|
| 324 |
+
) -> str:
|
| 325 |
+
"""
|
| 326 |
+
Generate UUID from audio data (for caching/deduplication)
|
| 327 |
+
|
| 328 |
+
Args:
|
| 329 |
+
audio_data: Audio data
|
| 330 |
+
seed: Optional seed value
|
| 331 |
+
|
| 332 |
+
Returns:
|
| 333 |
+
UUID string
|
| 334 |
+
"""
|
| 335 |
+
if isinstance(audio_data, torch.Tensor):
|
| 336 |
+
# Convert to numpy and calculate hash
|
| 337 |
+
audio_np = audio_data.cpu().numpy()
|
| 338 |
+
else:
|
| 339 |
+
audio_np = audio_data
|
| 340 |
+
|
| 341 |
+
# Calculate data hash
|
| 342 |
+
data_hash = hashlib.md5(audio_np.tobytes()).hexdigest()
|
| 343 |
+
|
| 344 |
+
if seed is not None:
|
| 345 |
+
combined = f"{data_hash}_{seed}"
|
| 346 |
+
return hashlib.md5(combined.encode()).hexdigest()
|
| 347 |
+
|
| 348 |
+
return data_hash
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
# Global default instance
|
| 352 |
+
_default_saver = AudioSaver(default_format="flac")
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def save_audio(
|
| 356 |
+
audio_data: Union[torch.Tensor, np.ndarray],
|
| 357 |
+
output_path: Union[str, Path],
|
| 358 |
+
sample_rate: int = 48000,
|
| 359 |
+
format: Optional[str] = None,
|
| 360 |
+
channels_first: bool = True,
|
| 361 |
+
) -> str:
|
| 362 |
+
"""
|
| 363 |
+
Convenience function: save audio (using default configuration)
|
| 364 |
+
|
| 365 |
+
Args:
|
| 366 |
+
audio_data: Audio data
|
| 367 |
+
output_path: Output path
|
| 368 |
+
sample_rate: Sample rate
|
| 369 |
+
format: Format (default flac)
|
| 370 |
+
channels_first: Tensor format flag
|
| 371 |
+
|
| 372 |
+
Returns:
|
| 373 |
+
Saved file path
|
| 374 |
+
"""
|
| 375 |
+
return _default_saver.save_audio(
|
| 376 |
+
audio_data, output_path, sample_rate, format, channels_first
|
| 377 |
+
)
|
| 378 |
+
|
acestep/constants.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Constants for ACE-Step
|
| 3 |
+
Centralized constants used across the codebase
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
# ==============================================================================
|
| 7 |
+
# Language Constants
|
| 8 |
+
# ==============================================================================
|
| 9 |
+
|
| 10 |
+
VALID_LANGUAGES = [
|
| 11 |
+
'ar', 'az', 'bg', 'bn', 'ca', 'cs', 'da', 'de', 'el', 'en',
|
| 12 |
+
'es', 'fa', 'fi', 'fr', 'he', 'hi', 'hr', 'ht', 'hu', 'id',
|
| 13 |
+
'is', 'it', 'ja', 'ko', 'la', 'lt', 'ms', 'ne', 'nl', 'no',
|
| 14 |
+
'pa', 'pl', 'pt', 'ro', 'ru', 'sa', 'sk', 'sr', 'sv', 'sw',
|
| 15 |
+
'ta', 'te', 'th', 'tl', 'tr', 'uk', 'ur', 'vi', 'yue', 'zh',
|
| 16 |
+
'unknown'
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# ==============================================================================
|
| 21 |
+
# Keyscale Constants
|
| 22 |
+
# ==============================================================================
|
| 23 |
+
|
| 24 |
+
KEYSCALE_NOTES = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
|
| 25 |
+
KEYSCALE_ACCIDENTALS = ['', '#', 'b', '♯', '♭'] # empty + ASCII sharp/flat + Unicode sharp/flat
|
| 26 |
+
KEYSCALE_MODES = ['major', 'minor']
|
| 27 |
+
|
| 28 |
+
# Generate all valid keyscales: 7 notes × 5 accidentals × 2 modes = 70 combinations
|
| 29 |
+
VALID_KEYSCALES = set()
|
| 30 |
+
for note in KEYSCALE_NOTES:
|
| 31 |
+
for acc in KEYSCALE_ACCIDENTALS:
|
| 32 |
+
for mode in KEYSCALE_MODES:
|
| 33 |
+
VALID_KEYSCALES.add(f"{note}{acc} {mode}")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# ==============================================================================
|
| 37 |
+
# Metadata Range Constants
|
| 38 |
+
# ==============================================================================
|
| 39 |
+
|
| 40 |
+
# BPM (Beats Per Minute) range
|
| 41 |
+
BPM_MIN = 30
|
| 42 |
+
BPM_MAX = 300
|
| 43 |
+
|
| 44 |
+
# Duration range (in seconds)
|
| 45 |
+
DURATION_MIN = 10
|
| 46 |
+
DURATION_MAX = 600
|
| 47 |
+
|
| 48 |
+
# Valid time signatures
|
| 49 |
+
VALID_TIME_SIGNATURES = [2, 3, 4, 6]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# ==============================================================================
|
| 53 |
+
# Task Type Constants
|
| 54 |
+
# ==============================================================================
|
| 55 |
+
|
| 56 |
+
TASK_TYPES = ["text2music", "repaint", "cover", "extract", "lego", "complete"]
|
| 57 |
+
|
| 58 |
+
# Task types available for turbo models (subset)
|
| 59 |
+
TASK_TYPES_TURBO = ["text2music", "repaint", "cover"]
|
| 60 |
+
|
| 61 |
+
# Task types available for base models (full set)
|
| 62 |
+
TASK_TYPES_BASE = ["text2music", "repaint", "cover", "extract", "lego", "complete"]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# ==============================================================================
|
| 66 |
+
# Instruction Constants
|
| 67 |
+
# ==============================================================================
|
| 68 |
+
|
| 69 |
+
# Default instructions
|
| 70 |
+
DEFAULT_DIT_INSTRUCTION = "Fill the audio semantic mask based on the given conditions:"
|
| 71 |
+
DEFAULT_LM_INSTRUCTION = "Generate audio semantic tokens based on the given conditions:"
|
| 72 |
+
DEFAULT_LM_UNDERSTAND_INSTRUCTION = "Understand the given musical conditions and describe the audio semantics accordingly:"
|
| 73 |
+
DEFAULT_LM_INSPIRED_INSTRUCTION = "Expand the user's input into a more detailed and specific musical description:"
|
| 74 |
+
DEFAULT_LM_REWRITE_INSTRUCTION = "Format the user's input into a more detailed and specific musical description:"
|
| 75 |
+
|
| 76 |
+
# Instruction templates for each task type
|
| 77 |
+
# Note: Some instructions use placeholders like {TRACK_NAME} or {TRACK_CLASSES}
|
| 78 |
+
# These should be formatted using .format() or f-strings when used
|
| 79 |
+
TASK_INSTRUCTIONS = {
|
| 80 |
+
"text2music": "Fill the audio semantic mask based on the given conditions:",
|
| 81 |
+
"repaint": "Repaint the mask area based on the given conditions:",
|
| 82 |
+
"cover": "Generate audio semantic tokens based on the given conditions:",
|
| 83 |
+
"extract": "Extract the {TRACK_NAME} track from the audio:",
|
| 84 |
+
"extract_default": "Extract the track from the audio:",
|
| 85 |
+
"lego": "Generate the {TRACK_NAME} track based on the audio context:",
|
| 86 |
+
"lego_default": "Generate the track based on the audio context:",
|
| 87 |
+
"complete": "Complete the input track with {TRACK_CLASSES}:",
|
| 88 |
+
"complete_default": "Complete the input track:",
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# ==============================================================================
|
| 93 |
+
# Track/Instrument Constants
|
| 94 |
+
# ==============================================================================
|
| 95 |
+
|
| 96 |
+
TRACK_NAMES = [
|
| 97 |
+
"woodwinds", "brass", "fx", "synth", "strings", "percussion",
|
| 98 |
+
"keyboard", "guitar", "bass", "drums", "backing_vocals", "vocals"
|
| 99 |
+
]
|
| 100 |
+
|
| 101 |
+
SFT_GEN_PROMPT = """# Instruction
|
| 102 |
+
{}
|
| 103 |
+
|
| 104 |
+
# Caption
|
| 105 |
+
{}
|
| 106 |
+
|
| 107 |
+
# Metas
|
| 108 |
+
{}<|endoftext|>
|
| 109 |
+
"""
|
acestep/constrained_logits_processor.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
acestep/dataset_handler.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dataset Handler
|
| 3 |
+
Handles dataset import and exploration functionality
|
| 4 |
+
"""
|
| 5 |
+
from typing import Optional, Tuple, Any, Dict
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class DatasetHandler:
|
| 9 |
+
"""Dataset Handler for Dataset Explorer functionality"""
|
| 10 |
+
|
| 11 |
+
def __init__(self):
|
| 12 |
+
"""Initialize dataset handler"""
|
| 13 |
+
self.dataset = None
|
| 14 |
+
self.dataset_imported = False
|
| 15 |
+
|
| 16 |
+
def import_dataset(self, dataset_type: str) -> str:
|
| 17 |
+
"""
|
| 18 |
+
Import dataset (temporarily disabled)
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
dataset_type: Type of dataset to import (e.g., "train", "test")
|
| 22 |
+
|
| 23 |
+
Returns:
|
| 24 |
+
Status message string
|
| 25 |
+
"""
|
| 26 |
+
self.dataset_imported = False
|
| 27 |
+
return f"⚠️ Dataset import is currently disabled. Text2MusicDataset dependency not available."
|
| 28 |
+
|
| 29 |
+
def get_item_data(self, *args, **kwargs) -> Tuple:
|
| 30 |
+
"""
|
| 31 |
+
Get dataset item (temporarily disabled)
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
Tuple of placeholder values matching the expected return format
|
| 35 |
+
"""
|
| 36 |
+
return "", "", "", "", "", None, None, None, "❌ Dataset not available", "", 0, "", None, None, None, {}, "text2music"
|
| 37 |
+
|
acestep/dit_alignment_score.py
ADDED
|
@@ -0,0 +1,870 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
DiT Alignment Score Module
|
| 3 |
+
|
| 4 |
+
This module provides lyrics-to-audio alignment using cross-attention matrices
|
| 5 |
+
from DiT model for generating LRC timestamps.
|
| 6 |
+
|
| 7 |
+
Refactored from lyrics_alignment_infos.py for integration with ACE-Step.
|
| 8 |
+
"""
|
| 9 |
+
import numba
|
| 10 |
+
import torch
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
from dataclasses import dataclass, asdict
|
| 14 |
+
from typing import List, Dict, Any, Optional, Tuple, Union
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# ================= Data Classes =================
|
| 18 |
+
@dataclass
|
| 19 |
+
class TokenTimestamp:
|
| 20 |
+
"""Stores per-token timing information."""
|
| 21 |
+
token_id: int
|
| 22 |
+
text: str
|
| 23 |
+
start: float
|
| 24 |
+
end: float
|
| 25 |
+
probability: float
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass
|
| 29 |
+
class SentenceTimestamp:
|
| 30 |
+
"""Stores per-sentence timing information with token list."""
|
| 31 |
+
text: str
|
| 32 |
+
start: float
|
| 33 |
+
end: float
|
| 34 |
+
tokens: List[TokenTimestamp]
|
| 35 |
+
confidence: float
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# ================= DTW Algorithm (Numba Optimized) =================
|
| 39 |
+
@numba.jit(nopython=True)
|
| 40 |
+
def dtw_cpu(x: np.ndarray):
|
| 41 |
+
"""
|
| 42 |
+
Dynamic Time Warping algorithm optimized with Numba.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
x: Cost matrix of shape [N, M]
|
| 46 |
+
|
| 47 |
+
Returns:
|
| 48 |
+
Tuple of (text_indices, time_indices) arrays
|
| 49 |
+
"""
|
| 50 |
+
N, M = x.shape
|
| 51 |
+
# Use float32 for memory efficiency
|
| 52 |
+
cost = np.ones((N + 1, M + 1), dtype=np.float32) * np.inf
|
| 53 |
+
trace = -np.ones((N + 1, M + 1), dtype=np.float32)
|
| 54 |
+
cost[0, 0] = 0
|
| 55 |
+
|
| 56 |
+
for j in range(1, M + 1):
|
| 57 |
+
for i in range(1, N + 1):
|
| 58 |
+
c0 = cost[i - 1, j - 1]
|
| 59 |
+
c1 = cost[i - 1, j]
|
| 60 |
+
c2 = cost[i, j - 1]
|
| 61 |
+
|
| 62 |
+
if c0 < c1 and c0 < c2:
|
| 63 |
+
c, t = c0, 0
|
| 64 |
+
elif c1 < c0 and c1 < c2:
|
| 65 |
+
c, t = c1, 1
|
| 66 |
+
else:
|
| 67 |
+
c, t = c2, 2
|
| 68 |
+
|
| 69 |
+
cost[i, j] = x[i - 1, j - 1] + c
|
| 70 |
+
trace[i, j] = t
|
| 71 |
+
|
| 72 |
+
return _backtrace(trace, N, M)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@numba.jit(nopython=True)
|
| 76 |
+
def _backtrace(trace: np.ndarray, N: int, M: int):
|
| 77 |
+
"""
|
| 78 |
+
Optimized backtrace function for DTW.
|
| 79 |
+
|
| 80 |
+
Args:
|
| 81 |
+
trace: Trace matrix of shape (N+1, M+1)
|
| 82 |
+
N, M: Original matrix dimensions
|
| 83 |
+
|
| 84 |
+
Returns:
|
| 85 |
+
Path array of shape (2, path_len) - first row is text indices, second is time indices
|
| 86 |
+
"""
|
| 87 |
+
# Boundary handling
|
| 88 |
+
trace[0, :] = 2
|
| 89 |
+
trace[:, 0] = 1
|
| 90 |
+
|
| 91 |
+
# Pre-allocate array, max path length is N+M
|
| 92 |
+
max_path_len = N + M
|
| 93 |
+
path = np.zeros((2, max_path_len), dtype=np.int32)
|
| 94 |
+
|
| 95 |
+
i, j = N, M
|
| 96 |
+
path_idx = max_path_len - 1
|
| 97 |
+
|
| 98 |
+
while i > 0 or j > 0:
|
| 99 |
+
path[0, path_idx] = i - 1 # text index
|
| 100 |
+
path[1, path_idx] = j - 1 # time index
|
| 101 |
+
path_idx -= 1
|
| 102 |
+
|
| 103 |
+
t = trace[i, j]
|
| 104 |
+
if t == 0:
|
| 105 |
+
i -= 1
|
| 106 |
+
j -= 1
|
| 107 |
+
elif t == 1:
|
| 108 |
+
i -= 1
|
| 109 |
+
elif t == 2:
|
| 110 |
+
j -= 1
|
| 111 |
+
else:
|
| 112 |
+
break
|
| 113 |
+
|
| 114 |
+
actual_len = max_path_len - path_idx - 1
|
| 115 |
+
return path[:, path_idx + 1:max_path_len]
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# ================= Utility Functions =================
|
| 119 |
+
def median_filter(x: torch.Tensor, filter_width: int) -> torch.Tensor:
|
| 120 |
+
"""
|
| 121 |
+
Apply median filter to tensor.
|
| 122 |
+
|
| 123 |
+
Args:
|
| 124 |
+
x: Input tensor
|
| 125 |
+
filter_width: Width of median filter
|
| 126 |
+
|
| 127 |
+
Returns:
|
| 128 |
+
Filtered tensor
|
| 129 |
+
"""
|
| 130 |
+
pad_width = filter_width // 2
|
| 131 |
+
if x.shape[-1] <= pad_width:
|
| 132 |
+
return x
|
| 133 |
+
if x.ndim == 2:
|
| 134 |
+
x = x[None, :]
|
| 135 |
+
x = F.pad(x, (filter_width // 2, filter_width // 2, 0, 0), mode="reflect")
|
| 136 |
+
result = x.unfold(-1, filter_width, 1).sort()[0][..., filter_width // 2]
|
| 137 |
+
if result.ndim > 2:
|
| 138 |
+
result = result.squeeze(0)
|
| 139 |
+
return result
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ================= Main Aligner Class =================
|
| 143 |
+
class MusicStampsAligner:
|
| 144 |
+
"""
|
| 145 |
+
Aligner class for generating lyrics timestamps from cross-attention matrices.
|
| 146 |
+
|
| 147 |
+
Uses bidirectional consensus denoising and DTW for alignment.
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
def __init__(self, tokenizer):
|
| 151 |
+
"""
|
| 152 |
+
Initialize the aligner.
|
| 153 |
+
|
| 154 |
+
Args:
|
| 155 |
+
tokenizer: Text tokenizer for decoding tokens
|
| 156 |
+
"""
|
| 157 |
+
self.tokenizer = tokenizer
|
| 158 |
+
|
| 159 |
+
def _apply_bidirectional_consensus(
|
| 160 |
+
self,
|
| 161 |
+
weights_stack: torch.Tensor,
|
| 162 |
+
violence_level: float,
|
| 163 |
+
medfilt_width: int
|
| 164 |
+
) -> tuple:
|
| 165 |
+
"""
|
| 166 |
+
Core denoising logic using bidirectional consensus.
|
| 167 |
+
|
| 168 |
+
Args:
|
| 169 |
+
weights_stack: Attention weights [Heads, Tokens, Frames]
|
| 170 |
+
violence_level: Denoising strength coefficient
|
| 171 |
+
medfilt_width: Median filter width
|
| 172 |
+
|
| 173 |
+
Returns:
|
| 174 |
+
Tuple of (calc_matrix, energy_matrix) as numpy arrays
|
| 175 |
+
"""
|
| 176 |
+
# A. Bidirectional Consensus
|
| 177 |
+
row_prob = F.softmax(weights_stack, dim=-1) # Token -> Frame
|
| 178 |
+
col_prob = F.softmax(weights_stack, dim=-2) # Frame -> Token
|
| 179 |
+
processed = row_prob * col_prob
|
| 180 |
+
|
| 181 |
+
# 1. Row suppression (kill horizontal crossing lines)
|
| 182 |
+
row_medians = torch.quantile(processed, 0.5, dim=-1, keepdim=True)
|
| 183 |
+
processed = processed - (violence_level * row_medians)
|
| 184 |
+
processed = torch.relu(processed)
|
| 185 |
+
|
| 186 |
+
# 2. Column suppression (kill vertical crossing lines)
|
| 187 |
+
col_medians = torch.quantile(processed, 0.5, dim=-2, keepdim=True)
|
| 188 |
+
processed = processed - (violence_level * col_medians)
|
| 189 |
+
processed = torch.relu(processed)
|
| 190 |
+
|
| 191 |
+
# C. Power sharpening
|
| 192 |
+
processed = processed ** 2
|
| 193 |
+
|
| 194 |
+
# Energy matrix for confidence
|
| 195 |
+
energy_matrix = processed.mean(dim=0).cpu().numpy()
|
| 196 |
+
|
| 197 |
+
# D. Z-Score normalization
|
| 198 |
+
std, mean = torch.std_mean(processed, unbiased=False)
|
| 199 |
+
weights_processed = (processed - mean) / (std + 1e-9)
|
| 200 |
+
|
| 201 |
+
# E. Median filtering
|
| 202 |
+
weights_processed = median_filter(weights_processed, filter_width=medfilt_width)
|
| 203 |
+
calc_matrix = weights_processed.mean(dim=0).numpy()
|
| 204 |
+
|
| 205 |
+
return calc_matrix, energy_matrix
|
| 206 |
+
|
| 207 |
+
def _preprocess_attention(
|
| 208 |
+
self,
|
| 209 |
+
attention_matrix: torch.Tensor,
|
| 210 |
+
custom_config: Dict[int, List[int]],
|
| 211 |
+
violence_level: float,
|
| 212 |
+
medfilt_width: int = 7
|
| 213 |
+
) -> tuple:
|
| 214 |
+
"""
|
| 215 |
+
Preprocess attention matrix for alignment.
|
| 216 |
+
|
| 217 |
+
Args:
|
| 218 |
+
attention_matrix: Attention tensor [Layers, Heads, Tokens, Frames]
|
| 219 |
+
custom_config: Dict mapping layer indices to head indices
|
| 220 |
+
violence_level: Denoising strength
|
| 221 |
+
medfilt_width: Median filter width
|
| 222 |
+
|
| 223 |
+
Returns:
|
| 224 |
+
Tuple of (calc_matrix, energy_matrix, visual_matrix)
|
| 225 |
+
"""
|
| 226 |
+
if not isinstance(attention_matrix, torch.Tensor):
|
| 227 |
+
weights = torch.tensor(attention_matrix)
|
| 228 |
+
else:
|
| 229 |
+
weights = attention_matrix.clone()
|
| 230 |
+
|
| 231 |
+
weights = weights.cpu().float()
|
| 232 |
+
|
| 233 |
+
selected_tensors = []
|
| 234 |
+
for layer_idx, head_indices in custom_config.items():
|
| 235 |
+
for head_idx in head_indices:
|
| 236 |
+
if layer_idx < weights.shape[0] and head_idx < weights.shape[1]:
|
| 237 |
+
head_matrix = weights[layer_idx, head_idx]
|
| 238 |
+
selected_tensors.append(head_matrix)
|
| 239 |
+
|
| 240 |
+
if not selected_tensors:
|
| 241 |
+
return None, None, None
|
| 242 |
+
|
| 243 |
+
# Stack selected heads: [Heads, Tokens, Frames]
|
| 244 |
+
weights_stack = torch.stack(selected_tensors, dim=0)
|
| 245 |
+
visual_matrix = weights_stack.mean(dim=0).numpy()
|
| 246 |
+
|
| 247 |
+
calc_matrix, energy_matrix = self._apply_bidirectional_consensus(
|
| 248 |
+
weights_stack, violence_level, medfilt_width
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
return calc_matrix, energy_matrix, visual_matrix
|
| 252 |
+
|
| 253 |
+
def stamps_align_info(
|
| 254 |
+
self,
|
| 255 |
+
attention_matrix: torch.Tensor,
|
| 256 |
+
lyrics_tokens: List[int],
|
| 257 |
+
total_duration_seconds: float,
|
| 258 |
+
custom_config: Dict[int, List[int]],
|
| 259 |
+
return_matrices: bool = False,
|
| 260 |
+
violence_level: float = 2.0,
|
| 261 |
+
medfilt_width: int = 1
|
| 262 |
+
) -> Dict[str, Any]:
|
| 263 |
+
"""
|
| 264 |
+
Get alignment information from attention matrix.
|
| 265 |
+
|
| 266 |
+
Args:
|
| 267 |
+
attention_matrix: Cross-attention tensor [Layers, Heads, Tokens, Frames]
|
| 268 |
+
lyrics_tokens: List of lyrics token IDs
|
| 269 |
+
total_duration_seconds: Total audio duration in seconds
|
| 270 |
+
custom_config: Dict mapping layer indices to head indices
|
| 271 |
+
return_matrices: Whether to return intermediate matrices
|
| 272 |
+
violence_level: Denoising strength
|
| 273 |
+
medfilt_width: Median filter width
|
| 274 |
+
|
| 275 |
+
Returns:
|
| 276 |
+
Dict containing calc_matrix, lyrics_tokens, total_duration_seconds,
|
| 277 |
+
and optionally energy_matrix and vis_matrix
|
| 278 |
+
"""
|
| 279 |
+
calc_matrix, energy_matrix, visual_matrix = self._preprocess_attention(
|
| 280 |
+
attention_matrix, custom_config, violence_level, medfilt_width
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
if calc_matrix is None:
|
| 284 |
+
return {
|
| 285 |
+
"calc_matrix": None,
|
| 286 |
+
"lyrics_tokens": lyrics_tokens,
|
| 287 |
+
"total_duration_seconds": total_duration_seconds,
|
| 288 |
+
"error": "No valid attention heads found"
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
return_dict = {
|
| 292 |
+
"calc_matrix": calc_matrix,
|
| 293 |
+
"lyrics_tokens": lyrics_tokens,
|
| 294 |
+
"total_duration_seconds": total_duration_seconds
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
if return_matrices:
|
| 298 |
+
return_dict['energy_matrix'] = energy_matrix
|
| 299 |
+
return_dict['vis_matrix'] = visual_matrix
|
| 300 |
+
|
| 301 |
+
return return_dict
|
| 302 |
+
|
| 303 |
+
def _decode_tokens_incrementally(self, token_ids: List[int]) -> List[str]:
|
| 304 |
+
"""
|
| 305 |
+
Decode tokens incrementally to properly handle multi-byte UTF-8 characters.
|
| 306 |
+
|
| 307 |
+
For Chinese and other multi-byte characters, the tokenizer may split them
|
| 308 |
+
into multiple byte-level tokens. Decoding each token individually produces
|
| 309 |
+
invalid UTF-8 sequences (showing as �). This method uses byte-level comparison
|
| 310 |
+
to correctly track which characters each token contributes.
|
| 311 |
+
|
| 312 |
+
Args:
|
| 313 |
+
token_ids: List of token IDs
|
| 314 |
+
|
| 315 |
+
Returns:
|
| 316 |
+
List of decoded text for each token position
|
| 317 |
+
"""
|
| 318 |
+
decoded_tokens = []
|
| 319 |
+
prev_bytes = b""
|
| 320 |
+
|
| 321 |
+
for i in range(len(token_ids)):
|
| 322 |
+
# Decode tokens from start to current position
|
| 323 |
+
current_text = self.tokenizer.decode(token_ids[:i+1], skip_special_tokens=False)
|
| 324 |
+
current_bytes = current_text.encode('utf-8', errors='surrogatepass')
|
| 325 |
+
|
| 326 |
+
# The contribution of current token is the new bytes added
|
| 327 |
+
if len(current_bytes) >= len(prev_bytes):
|
| 328 |
+
new_bytes = current_bytes[len(prev_bytes):]
|
| 329 |
+
# Try to decode the new bytes; if incomplete, use empty string
|
| 330 |
+
try:
|
| 331 |
+
token_text = new_bytes.decode('utf-8')
|
| 332 |
+
except UnicodeDecodeError:
|
| 333 |
+
# Incomplete UTF-8 sequence, this token doesn't complete a character
|
| 334 |
+
token_text = ""
|
| 335 |
+
else:
|
| 336 |
+
# Edge case: current decode is shorter (shouldn't happen normally)
|
| 337 |
+
token_text = ""
|
| 338 |
+
|
| 339 |
+
decoded_tokens.append(token_text)
|
| 340 |
+
prev_bytes = current_bytes
|
| 341 |
+
|
| 342 |
+
return decoded_tokens
|
| 343 |
+
|
| 344 |
+
def token_timestamps(
|
| 345 |
+
self,
|
| 346 |
+
calc_matrix: np.ndarray,
|
| 347 |
+
lyrics_tokens: List[int],
|
| 348 |
+
total_duration_seconds: float
|
| 349 |
+
) -> List[TokenTimestamp]:
|
| 350 |
+
"""
|
| 351 |
+
Generate per-token timestamps using DTW.
|
| 352 |
+
|
| 353 |
+
Args:
|
| 354 |
+
calc_matrix: Processed attention matrix [Tokens, Frames]
|
| 355 |
+
lyrics_tokens: List of token IDs
|
| 356 |
+
total_duration_seconds: Total audio duration
|
| 357 |
+
|
| 358 |
+
Returns:
|
| 359 |
+
List of TokenTimestamp objects
|
| 360 |
+
"""
|
| 361 |
+
n_frames = calc_matrix.shape[-1]
|
| 362 |
+
text_indices, time_indices = dtw_cpu(-calc_matrix.astype(np.float64))
|
| 363 |
+
|
| 364 |
+
seconds_per_frame = total_duration_seconds / n_frames
|
| 365 |
+
alignment_results = []
|
| 366 |
+
|
| 367 |
+
# Use incremental decoding to properly handle multi-byte UTF-8 characters
|
| 368 |
+
decoded_tokens = self._decode_tokens_incrementally(lyrics_tokens)
|
| 369 |
+
|
| 370 |
+
for i in range(len(lyrics_tokens)):
|
| 371 |
+
mask = (text_indices == i)
|
| 372 |
+
|
| 373 |
+
if not np.any(mask):
|
| 374 |
+
start = alignment_results[-1].end if alignment_results else 0.0
|
| 375 |
+
end = start
|
| 376 |
+
token_conf = 0.0
|
| 377 |
+
else:
|
| 378 |
+
times = time_indices[mask] * seconds_per_frame
|
| 379 |
+
start = times[0]
|
| 380 |
+
end = times[-1]
|
| 381 |
+
token_conf = 0.0
|
| 382 |
+
|
| 383 |
+
if end < start:
|
| 384 |
+
end = start
|
| 385 |
+
|
| 386 |
+
alignment_results.append(TokenTimestamp(
|
| 387 |
+
token_id=lyrics_tokens[i],
|
| 388 |
+
text=decoded_tokens[i],
|
| 389 |
+
start=float(start),
|
| 390 |
+
end=float(end),
|
| 391 |
+
probability=token_conf
|
| 392 |
+
))
|
| 393 |
+
|
| 394 |
+
return alignment_results
|
| 395 |
+
|
| 396 |
+
def _decode_sentence_from_tokens(self, tokens: List[TokenTimestamp]) -> str:
|
| 397 |
+
"""
|
| 398 |
+
Decode a sentence by decoding all token IDs together.
|
| 399 |
+
This avoids UTF-8 encoding issues from joining individual token texts.
|
| 400 |
+
|
| 401 |
+
Args:
|
| 402 |
+
tokens: List of TokenTimestamp objects
|
| 403 |
+
|
| 404 |
+
Returns:
|
| 405 |
+
Properly decoded sentence text
|
| 406 |
+
"""
|
| 407 |
+
token_ids = [t.token_id for t in tokens]
|
| 408 |
+
return self.tokenizer.decode(token_ids, skip_special_tokens=False)
|
| 409 |
+
|
| 410 |
+
def sentence_timestamps(
|
| 411 |
+
self,
|
| 412 |
+
token_alignment: List[TokenTimestamp]
|
| 413 |
+
) -> List[SentenceTimestamp]:
|
| 414 |
+
"""
|
| 415 |
+
Group token timestamps into sentence timestamps.
|
| 416 |
+
|
| 417 |
+
Args:
|
| 418 |
+
token_alignment: List of TokenTimestamp objects
|
| 419 |
+
|
| 420 |
+
Returns:
|
| 421 |
+
List of SentenceTimestamp objects
|
| 422 |
+
"""
|
| 423 |
+
results = []
|
| 424 |
+
current_tokens = []
|
| 425 |
+
|
| 426 |
+
for token in token_alignment:
|
| 427 |
+
current_tokens.append(token)
|
| 428 |
+
|
| 429 |
+
if '\n' in token.text:
|
| 430 |
+
# Decode all token IDs together to avoid UTF-8 issues
|
| 431 |
+
full_text = self._decode_sentence_from_tokens(current_tokens)
|
| 432 |
+
|
| 433 |
+
if full_text.strip():
|
| 434 |
+
valid_scores = [t.probability for t in current_tokens if t.probability > 0]
|
| 435 |
+
sent_conf = sum(valid_scores) / len(valid_scores) if valid_scores else 0.0
|
| 436 |
+
|
| 437 |
+
results.append(SentenceTimestamp(
|
| 438 |
+
text=full_text.strip(),
|
| 439 |
+
start=round(current_tokens[0].start, 3),
|
| 440 |
+
end=round(current_tokens[-1].end, 3),
|
| 441 |
+
tokens=list(current_tokens),
|
| 442 |
+
confidence=sent_conf
|
| 443 |
+
))
|
| 444 |
+
|
| 445 |
+
current_tokens = []
|
| 446 |
+
|
| 447 |
+
# Handle last sentence
|
| 448 |
+
if current_tokens:
|
| 449 |
+
# Decode all token IDs together to avoid UTF-8 issues
|
| 450 |
+
full_text = self._decode_sentence_from_tokens(current_tokens)
|
| 451 |
+
if full_text.strip():
|
| 452 |
+
valid_scores = [t.probability for t in current_tokens if t.probability > 0]
|
| 453 |
+
sent_conf = sum(valid_scores) / len(valid_scores) if valid_scores else 0.0
|
| 454 |
+
|
| 455 |
+
results.append(SentenceTimestamp(
|
| 456 |
+
text=full_text.strip(),
|
| 457 |
+
start=round(current_tokens[0].start, 3),
|
| 458 |
+
end=round(current_tokens[-1].end, 3),
|
| 459 |
+
tokens=list(current_tokens),
|
| 460 |
+
confidence=sent_conf
|
| 461 |
+
))
|
| 462 |
+
|
| 463 |
+
# Normalize confidence scores
|
| 464 |
+
if results:
|
| 465 |
+
all_scores = [s.confidence for s in results]
|
| 466 |
+
min_score = min(all_scores)
|
| 467 |
+
max_score = max(all_scores)
|
| 468 |
+
score_range = max_score - min_score
|
| 469 |
+
|
| 470 |
+
if score_range > 1e-9:
|
| 471 |
+
for s in results:
|
| 472 |
+
normalized_score = (s.confidence - min_score) / score_range
|
| 473 |
+
s.confidence = round(normalized_score, 2)
|
| 474 |
+
else:
|
| 475 |
+
for s in results:
|
| 476 |
+
s.confidence = round(s.confidence, 2)
|
| 477 |
+
|
| 478 |
+
return results
|
| 479 |
+
|
| 480 |
+
def format_lrc(
|
| 481 |
+
self,
|
| 482 |
+
sentence_timestamps: List[SentenceTimestamp],
|
| 483 |
+
include_end_time: bool = False
|
| 484 |
+
) -> str:
|
| 485 |
+
"""
|
| 486 |
+
Format sentence timestamps as LRC lyrics format.
|
| 487 |
+
|
| 488 |
+
Args:
|
| 489 |
+
sentence_timestamps: List of SentenceTimestamp objects
|
| 490 |
+
include_end_time: Whether to include end time (enhanced LRC format)
|
| 491 |
+
|
| 492 |
+
Returns:
|
| 493 |
+
LRC formatted string
|
| 494 |
+
"""
|
| 495 |
+
lines = []
|
| 496 |
+
|
| 497 |
+
for sentence in sentence_timestamps:
|
| 498 |
+
# Convert seconds to mm:ss.xx format
|
| 499 |
+
start_minutes = int(sentence.start // 60)
|
| 500 |
+
start_seconds = sentence.start % 60
|
| 501 |
+
|
| 502 |
+
if include_end_time:
|
| 503 |
+
end_minutes = int(sentence.end // 60)
|
| 504 |
+
end_seconds = sentence.end % 60
|
| 505 |
+
timestamp = f"[{start_minutes:02d}:{start_seconds:05.2f}][{end_minutes:02d}:{end_seconds:05.2f}]"
|
| 506 |
+
else:
|
| 507 |
+
timestamp = f"[{start_minutes:02d}:{start_seconds:05.2f}]"
|
| 508 |
+
|
| 509 |
+
# Clean the text (remove structural tags like [verse], [chorus])
|
| 510 |
+
text = sentence.text
|
| 511 |
+
|
| 512 |
+
lines.append(f"{timestamp}{text}")
|
| 513 |
+
|
| 514 |
+
return "\n".join(lines)
|
| 515 |
+
|
| 516 |
+
def get_timestamps_and_lrc(
|
| 517 |
+
self,
|
| 518 |
+
calc_matrix: np.ndarray,
|
| 519 |
+
lyrics_tokens: List[int],
|
| 520 |
+
total_duration_seconds: float
|
| 521 |
+
) -> Dict[str, Any]:
|
| 522 |
+
"""
|
| 523 |
+
Convenience method to get both timestamps and LRC in one call.
|
| 524 |
+
|
| 525 |
+
Args:
|
| 526 |
+
calc_matrix: Processed attention matrix
|
| 527 |
+
lyrics_tokens: List of token IDs
|
| 528 |
+
total_duration_seconds: Total audio duration
|
| 529 |
+
|
| 530 |
+
Returns:
|
| 531 |
+
Dict containing token_timestamps, sentence_timestamps, and lrc_text
|
| 532 |
+
"""
|
| 533 |
+
token_stamps = self.token_timestamps(
|
| 534 |
+
calc_matrix=calc_matrix,
|
| 535 |
+
lyrics_tokens=lyrics_tokens,
|
| 536 |
+
total_duration_seconds=total_duration_seconds
|
| 537 |
+
)
|
| 538 |
+
|
| 539 |
+
sentence_stamps = self.sentence_timestamps(token_stamps)
|
| 540 |
+
lrc_text = self.format_lrc(sentence_stamps)
|
| 541 |
+
|
| 542 |
+
return {
|
| 543 |
+
"token_timestamps": token_stamps,
|
| 544 |
+
"sentence_timestamps": sentence_stamps,
|
| 545 |
+
"lrc_text": lrc_text
|
| 546 |
+
}
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
class MusicLyricScorer:
|
| 550 |
+
"""
|
| 551 |
+
Scorer class for evaluating lyrics-to-audio alignment quality.
|
| 552 |
+
|
| 553 |
+
Focuses on calculating alignment quality metrics (Coverage, Monotonicity, Confidence)
|
| 554 |
+
using tensor operations for potential differentiability or GPU acceleration.
|
| 555 |
+
"""
|
| 556 |
+
|
| 557 |
+
def __init__(self, tokenizer: Any):
|
| 558 |
+
"""
|
| 559 |
+
Initialize the aligner.
|
| 560 |
+
|
| 561 |
+
Args:
|
| 562 |
+
tokenizer: Tokenizer instance (must implement .decode()).
|
| 563 |
+
"""
|
| 564 |
+
self.tokenizer = tokenizer
|
| 565 |
+
|
| 566 |
+
def _generate_token_type_mask(self, token_ids: List[int]) -> np.ndarray:
|
| 567 |
+
"""
|
| 568 |
+
Generate a mask distinguishing lyrics (1) from structural tags (0).
|
| 569 |
+
Uses self.tokenizer to decode tokens.
|
| 570 |
+
|
| 571 |
+
Args:
|
| 572 |
+
token_ids: List of token IDs.
|
| 573 |
+
|
| 574 |
+
Returns:
|
| 575 |
+
Numpy array of shape [len(token_ids)] with 1 or 0.
|
| 576 |
+
"""
|
| 577 |
+
decoded_tokens = [self.tokenizer.decode([tid]) for tid in token_ids]
|
| 578 |
+
mask = np.ones(len(token_ids), dtype=np.int32)
|
| 579 |
+
in_bracket = False
|
| 580 |
+
|
| 581 |
+
for i, token_str in enumerate(decoded_tokens):
|
| 582 |
+
if '[' in token_str:
|
| 583 |
+
in_bracket = True
|
| 584 |
+
if in_bracket:
|
| 585 |
+
mask[i] = 0
|
| 586 |
+
if ']' in token_str:
|
| 587 |
+
in_bracket = False
|
| 588 |
+
mask[i] = 0
|
| 589 |
+
return mask
|
| 590 |
+
|
| 591 |
+
def _preprocess_attention(
|
| 592 |
+
self,
|
| 593 |
+
attention_matrix: Union[torch.Tensor, np.ndarray],
|
| 594 |
+
custom_config: Dict[int, List[int]],
|
| 595 |
+
medfilt_width: int = 1
|
| 596 |
+
) -> Tuple[Optional[np.ndarray], Optional[np.ndarray], Optional[torch.Tensor]]:
|
| 597 |
+
"""
|
| 598 |
+
Extracts and normalizes the attention matrix.
|
| 599 |
+
|
| 600 |
+
Logic V4: Uses Min-Max normalization to highlight energy differences.
|
| 601 |
+
|
| 602 |
+
Args:
|
| 603 |
+
attention_matrix: Raw attention tensor [Layers, Heads, Tokens, Frames].
|
| 604 |
+
custom_config: Config mapping layers to heads.
|
| 605 |
+
medfilt_width: Width for median filtering.
|
| 606 |
+
|
| 607 |
+
Returns:
|
| 608 |
+
Tuple of (calc_matrix, energy_matrix, avg_weights_tensor).
|
| 609 |
+
"""
|
| 610 |
+
# 1. Prepare Tensor
|
| 611 |
+
if not isinstance(attention_matrix, torch.Tensor):
|
| 612 |
+
weights = torch.tensor(attention_matrix)
|
| 613 |
+
else:
|
| 614 |
+
weights = attention_matrix.clone()
|
| 615 |
+
weights = weights.cpu().float()
|
| 616 |
+
|
| 617 |
+
# 2. Select Heads based on config
|
| 618 |
+
selected_tensors = []
|
| 619 |
+
for layer_idx, head_indices in custom_config.items():
|
| 620 |
+
for head_idx in head_indices:
|
| 621 |
+
if layer_idx < weights.shape[0] and head_idx < weights.shape[1]:
|
| 622 |
+
selected_tensors.append(weights[layer_idx, head_idx])
|
| 623 |
+
|
| 624 |
+
if not selected_tensors:
|
| 625 |
+
return None, None, None
|
| 626 |
+
|
| 627 |
+
weights_stack = torch.stack(selected_tensors, dim=0)
|
| 628 |
+
|
| 629 |
+
# 3. Average Heads
|
| 630 |
+
avg_weights = weights_stack.mean(dim=0) # [Tokens, Frames]
|
| 631 |
+
|
| 632 |
+
# 4. Preprocessing Logic
|
| 633 |
+
# Min-Max normalization preserving energy distribution
|
| 634 |
+
# Median filter is applied to the energy matrix
|
| 635 |
+
energy_tensor = median_filter(avg_weights, filter_width=medfilt_width)
|
| 636 |
+
energy_matrix = energy_tensor.numpy()
|
| 637 |
+
|
| 638 |
+
e_min, e_max = energy_matrix.min(), energy_matrix.max()
|
| 639 |
+
|
| 640 |
+
if e_max - e_min > 1e-9:
|
| 641 |
+
energy_matrix = (energy_matrix - e_min) / (e_max - e_min)
|
| 642 |
+
else:
|
| 643 |
+
energy_matrix = np.zeros_like(energy_matrix)
|
| 644 |
+
|
| 645 |
+
# Contrast enhancement for DTW pathfinding
|
| 646 |
+
# calc_matrix is used for pathfinding, energy_matrix for scoring
|
| 647 |
+
calc_matrix = energy_matrix ** 2
|
| 648 |
+
|
| 649 |
+
return calc_matrix, energy_matrix, avg_weights
|
| 650 |
+
|
| 651 |
+
def _compute_alignment_metrics(
|
| 652 |
+
self,
|
| 653 |
+
energy_matrix: torch.Tensor,
|
| 654 |
+
path_coords: torch.Tensor,
|
| 655 |
+
type_mask: torch.Tensor,
|
| 656 |
+
time_weight: float = 0.01,
|
| 657 |
+
overlap_frames: float = 9.0,
|
| 658 |
+
instrumental_weight: float = 1.0
|
| 659 |
+
) -> Tuple[float, float, float]:
|
| 660 |
+
"""
|
| 661 |
+
Core metric calculation logic using high-precision Tensor operations.
|
| 662 |
+
|
| 663 |
+
Args:
|
| 664 |
+
energy_matrix: Normalized energy [Rows, Cols].
|
| 665 |
+
path_coords: DTW path coordinates [Steps, 2].
|
| 666 |
+
type_mask: Token type mask [Rows] (1=Lyrics, 0=Tags).
|
| 667 |
+
time_weight: Minimum energy threshold for monotonicity.
|
| 668 |
+
overlap_frames: Allowed overlap for monotonicity check.
|
| 669 |
+
instrumental_weight: Weight for non-lyric tokens in confidence calc.
|
| 670 |
+
|
| 671 |
+
Returns:
|
| 672 |
+
Tuple of (coverage, monotonicity, confidence).
|
| 673 |
+
"""
|
| 674 |
+
# Ensure high precision for internal calculation
|
| 675 |
+
energy_matrix = energy_matrix.to(dtype=torch.float64)
|
| 676 |
+
path_coords = path_coords.long()
|
| 677 |
+
type_mask = type_mask.long()
|
| 678 |
+
|
| 679 |
+
device = energy_matrix.device
|
| 680 |
+
rows, cols = energy_matrix.shape
|
| 681 |
+
|
| 682 |
+
is_lyrics_row = (type_mask == 1)
|
| 683 |
+
|
| 684 |
+
# ================= A. Coverage Score =================
|
| 685 |
+
# Ratio of lyric lines that have significant energy peak
|
| 686 |
+
row_max_energies = energy_matrix.max(dim=1).values
|
| 687 |
+
total_sung_rows = is_lyrics_row.sum().double()
|
| 688 |
+
|
| 689 |
+
coverage_threshold = 0.1
|
| 690 |
+
valid_sung_mask = is_lyrics_row & (row_max_energies > coverage_threshold)
|
| 691 |
+
valid_sung_rows = valid_sung_mask.sum().double()
|
| 692 |
+
|
| 693 |
+
if total_sung_rows > 0:
|
| 694 |
+
coverage_score = valid_sung_rows / total_sung_rows
|
| 695 |
+
else:
|
| 696 |
+
coverage_score = torch.tensor(1.0, device=device, dtype=torch.float64)
|
| 697 |
+
|
| 698 |
+
# ================= B. Monotonicity Score =================
|
| 699 |
+
# Check if the "center of mass" of lyric lines moves forward in time
|
| 700 |
+
col_indices = torch.arange(cols, device=device, dtype=torch.float64)
|
| 701 |
+
|
| 702 |
+
# Zero out low energy noise
|
| 703 |
+
weights = torch.where(
|
| 704 |
+
energy_matrix > time_weight,
|
| 705 |
+
energy_matrix,
|
| 706 |
+
torch.zeros_like(energy_matrix)
|
| 707 |
+
)
|
| 708 |
+
|
| 709 |
+
sum_w = weights.sum(dim=1)
|
| 710 |
+
sum_t = (weights * col_indices).sum(dim=1)
|
| 711 |
+
|
| 712 |
+
# Calculate centroids
|
| 713 |
+
centroids = torch.full((rows,), -1.0, device=device, dtype=torch.float64)
|
| 714 |
+
valid_w_mask = sum_w > 1e-9
|
| 715 |
+
centroids[valid_w_mask] = sum_t[valid_w_mask] / sum_w[valid_w_mask]
|
| 716 |
+
|
| 717 |
+
# Extract sequence of valid lyrics centroids
|
| 718 |
+
valid_sequence_mask = is_lyrics_row & (centroids >= 0)
|
| 719 |
+
sung_centroids = centroids[valid_sequence_mask]
|
| 720 |
+
|
| 721 |
+
cnt = sung_centroids.shape[0]
|
| 722 |
+
if cnt > 1:
|
| 723 |
+
curr_c = sung_centroids[:-1]
|
| 724 |
+
next_c = sung_centroids[1:]
|
| 725 |
+
|
| 726 |
+
# Check non-decreasing order with overlap tolerance
|
| 727 |
+
non_decreasing = (next_c >= (curr_c - overlap_frames)).double().sum()
|
| 728 |
+
pairs = torch.tensor(cnt - 1, device=device, dtype=torch.float64)
|
| 729 |
+
monotonicity_score = non_decreasing / pairs
|
| 730 |
+
else:
|
| 731 |
+
monotonicity_score = torch.tensor(1.0, device=device, dtype=torch.float64)
|
| 732 |
+
|
| 733 |
+
# ================= C. Path Confidence =================
|
| 734 |
+
# Average energy along the optimal path
|
| 735 |
+
if path_coords.shape[0] > 0:
|
| 736 |
+
p_rows = path_coords[:, 0]
|
| 737 |
+
p_cols = path_coords[:, 1]
|
| 738 |
+
|
| 739 |
+
path_energies = energy_matrix[p_rows, p_cols]
|
| 740 |
+
step_weights = torch.ones_like(path_energies)
|
| 741 |
+
|
| 742 |
+
# Lower weight for instrumental/tag steps
|
| 743 |
+
is_inst_step = (type_mask[p_rows] == 0)
|
| 744 |
+
step_weights[is_inst_step] = instrumental_weight
|
| 745 |
+
|
| 746 |
+
total_energy = (path_energies * step_weights).sum()
|
| 747 |
+
total_steps = step_weights.sum()
|
| 748 |
+
|
| 749 |
+
if total_steps > 0:
|
| 750 |
+
path_confidence = total_energy / total_steps
|
| 751 |
+
else:
|
| 752 |
+
path_confidence = torch.tensor(0.0, device=device, dtype=torch.float64)
|
| 753 |
+
else:
|
| 754 |
+
path_confidence = torch.tensor(0.0, device=device, dtype=torch.float64)
|
| 755 |
+
|
| 756 |
+
return coverage_score.item(), monotonicity_score.item(), path_confidence.item()
|
| 757 |
+
|
| 758 |
+
def lyrics_alignment_info(
|
| 759 |
+
self,
|
| 760 |
+
attention_matrix: Union[torch.Tensor, np.ndarray],
|
| 761 |
+
token_ids: List[int],
|
| 762 |
+
custom_config: Dict[int, List[int]],
|
| 763 |
+
return_matrices: bool = False,
|
| 764 |
+
medfilt_width: int = 1
|
| 765 |
+
) -> Dict[str, Any]:
|
| 766 |
+
"""
|
| 767 |
+
Generates alignment path and processed matrices.
|
| 768 |
+
|
| 769 |
+
Args:
|
| 770 |
+
attention_matrix: Input attention tensor.
|
| 771 |
+
token_ids: Corresponding token IDs.
|
| 772 |
+
custom_config: Layer/Head configuration.
|
| 773 |
+
return_matrices: If True, returns matrices in the output.
|
| 774 |
+
medfilt_width: Median filter width.
|
| 775 |
+
|
| 776 |
+
Returns:
|
| 777 |
+
Dict or AlignmentInfo object containing path and masks.
|
| 778 |
+
"""
|
| 779 |
+
calc_matrix, energy_matrix, vis_matrix = self._preprocess_attention(
|
| 780 |
+
attention_matrix, custom_config, medfilt_width
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
if calc_matrix is None:
|
| 784 |
+
return {
|
| 785 |
+
"calc_matrix": None,
|
| 786 |
+
"error": "No valid attention heads found"
|
| 787 |
+
}
|
| 788 |
+
|
| 789 |
+
# 1. Generate Semantic Mask (1=Lyrics, 0=Tags)
|
| 790 |
+
# Uses self.tokenizer internally
|
| 791 |
+
type_mask = self._generate_token_type_mask(token_ids)
|
| 792 |
+
|
| 793 |
+
# Safety check for shape mismatch
|
| 794 |
+
if len(type_mask) != energy_matrix.shape[0]:
|
| 795 |
+
# Fallback to all lyrics if shapes don't align
|
| 796 |
+
type_mask = np.ones(energy_matrix.shape[0], dtype=np.int32)
|
| 797 |
+
|
| 798 |
+
# 2. DTW Pathfinding
|
| 799 |
+
# Using negative calc_matrix because DTW minimizes cost
|
| 800 |
+
text_indices, time_indices = dtw_cpu(-calc_matrix.astype(np.float32))
|
| 801 |
+
path_coords = np.stack([text_indices, time_indices], axis=1)
|
| 802 |
+
|
| 803 |
+
return_dict = {
|
| 804 |
+
"path_coords": path_coords,
|
| 805 |
+
"type_mask": type_mask,
|
| 806 |
+
"energy_matrix": energy_matrix
|
| 807 |
+
}
|
| 808 |
+
if return_matrices:
|
| 809 |
+
return_dict['calc_matrix'] = calc_matrix
|
| 810 |
+
return_dict['vis_matrix'] = vis_matrix
|
| 811 |
+
|
| 812 |
+
return return_dict
|
| 813 |
+
|
| 814 |
+
def calculate_score(
|
| 815 |
+
self,
|
| 816 |
+
energy_matrix: Union[torch.Tensor, np.ndarray],
|
| 817 |
+
type_mask: Union[torch.Tensor, np.ndarray],
|
| 818 |
+
path_coords: Union[torch.Tensor, np.ndarray],
|
| 819 |
+
time_weight: float = 0.01,
|
| 820 |
+
overlap_frames: float = 9.0,
|
| 821 |
+
instrumental_weight: float = 1.0
|
| 822 |
+
) -> Dict[str, Any]:
|
| 823 |
+
"""
|
| 824 |
+
Calculates the final alignment score based on pre-computed components.
|
| 825 |
+
|
| 826 |
+
Args:
|
| 827 |
+
energy_matrix: Processed energy matrix.
|
| 828 |
+
type_mask: Token type mask.
|
| 829 |
+
path_coords: DTW path coordinates.
|
| 830 |
+
time_weight: Minimum energy threshold for monotonicity.
|
| 831 |
+
overlap_frames: Allowed backward movement frames.
|
| 832 |
+
instrumental_weight: Weight for non-lyric path steps.
|
| 833 |
+
|
| 834 |
+
Returns:
|
| 835 |
+
AlignmentScore object containing individual metrics and final score.
|
| 836 |
+
"""
|
| 837 |
+
# Ensure Inputs are Tensors on the correct device
|
| 838 |
+
if not isinstance(energy_matrix, torch.Tensor):
|
| 839 |
+
energy_matrix = torch.tensor(energy_matrix, device='cuda', dtype=torch.float32)
|
| 840 |
+
|
| 841 |
+
device = energy_matrix.device
|
| 842 |
+
|
| 843 |
+
if not isinstance(type_mask, torch.Tensor):
|
| 844 |
+
type_mask = torch.tensor(type_mask, device=device, dtype=torch.long)
|
| 845 |
+
else:
|
| 846 |
+
type_mask = type_mask.to(device=device, dtype=torch.long)
|
| 847 |
+
|
| 848 |
+
if not isinstance(path_coords, torch.Tensor):
|
| 849 |
+
path_coords = torch.tensor(path_coords, device=device, dtype=torch.long)
|
| 850 |
+
else:
|
| 851 |
+
path_coords = path_coords.to(device=device, dtype=torch.long)
|
| 852 |
+
|
| 853 |
+
# Compute Metrics
|
| 854 |
+
coverage, monotonicity, confidence = self._compute_alignment_metrics(
|
| 855 |
+
energy_matrix=energy_matrix,
|
| 856 |
+
path_coords=path_coords,
|
| 857 |
+
type_mask=type_mask,
|
| 858 |
+
time_weight=time_weight,
|
| 859 |
+
overlap_frames=overlap_frames,
|
| 860 |
+
instrumental_weight=instrumental_weight
|
| 861 |
+
)
|
| 862 |
+
|
| 863 |
+
# Final Score Calculation
|
| 864 |
+
# (Cov^2 * Mono^2 * Conf)
|
| 865 |
+
final_score = (coverage ** 2) * (monotonicity ** 2) * confidence
|
| 866 |
+
final_score = float(np.clip(final_score, 0.0, 1.0))
|
| 867 |
+
|
| 868 |
+
return {
|
| 869 |
+
"lyrics_score": round(final_score, 4)
|
| 870 |
+
}
|
acestep/genres_vocab.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
acestep/gradio_ui/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from acestep.gradio_ui.interfaces import create_gradio_interface
|
acestep/gradio_ui/events/__init__.py
ADDED
|
@@ -0,0 +1,1355 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Gradio UI Event Handlers Module
|
| 3 |
+
Main entry point for setting up all event handlers
|
| 4 |
+
"""
|
| 5 |
+
import os
|
| 6 |
+
import gradio as gr
|
| 7 |
+
from typing import Optional
|
| 8 |
+
from loguru import logger
|
| 9 |
+
|
| 10 |
+
# Import handler modules
|
| 11 |
+
from . import generation_handlers as gen_h
|
| 12 |
+
from . import results_handlers as res_h
|
| 13 |
+
from . import training_handlers as train_h
|
| 14 |
+
from acestep.gradio_ui.i18n import t
|
| 15 |
+
|
| 16 |
+
# HuggingFace Space environment detection for ZeroGPU support
|
| 17 |
+
IS_HUGGINGFACE_SPACE = os.environ.get("SPACE_ID") is not None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _get_spaces_gpu_decorator(duration=120):
|
| 21 |
+
"""
|
| 22 |
+
Get the @spaces.GPU decorator if running in HuggingFace Space environment.
|
| 23 |
+
Returns identity decorator if not in Space environment.
|
| 24 |
+
"""
|
| 25 |
+
if IS_HUGGINGFACE_SPACE:
|
| 26 |
+
try:
|
| 27 |
+
import spaces
|
| 28 |
+
return spaces.GPU(duration=duration)
|
| 29 |
+
except ImportError:
|
| 30 |
+
logger.warning("spaces package not found, GPU decorator disabled")
|
| 31 |
+
return lambda func: func
|
| 32 |
+
return lambda func: func
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def setup_event_handlers(demo, dit_handler, llm_handler, dataset_handler, dataset_section, generation_section, results_section, init_params=None):
|
| 36 |
+
"""Setup event handlers connecting UI components and business logic
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
init_params: Dictionary containing initialization parameters including:
|
| 40 |
+
- dit_handler_2: Optional second DiT handler for multi-model setup
|
| 41 |
+
- available_dit_models: List of available DiT model names
|
| 42 |
+
- config_path: Primary model config path
|
| 43 |
+
- config_path_2: Secondary model config path (if available)
|
| 44 |
+
"""
|
| 45 |
+
# Get secondary DiT handler from init_params (for multi-model support)
|
| 46 |
+
dit_handler_2 = init_params.get('dit_handler_2') if init_params else None
|
| 47 |
+
config_path_1 = init_params.get('config_path', '') if init_params else ''
|
| 48 |
+
config_path_2 = init_params.get('config_path_2', '') if init_params else ''
|
| 49 |
+
|
| 50 |
+
# ========== Dataset Handlers ==========
|
| 51 |
+
dataset_section["import_dataset_btn"].click(
|
| 52 |
+
fn=dataset_handler.import_dataset,
|
| 53 |
+
inputs=[dataset_section["dataset_type"]],
|
| 54 |
+
outputs=[dataset_section["data_status"]]
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
# ========== Service Initialization ==========
|
| 58 |
+
generation_section["refresh_btn"].click(
|
| 59 |
+
fn=lambda: gen_h.refresh_checkpoints(dit_handler),
|
| 60 |
+
outputs=[generation_section["checkpoint_dropdown"]]
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
generation_section["config_path"].change(
|
| 64 |
+
fn=gen_h.update_model_type_settings,
|
| 65 |
+
inputs=[generation_section["config_path"]],
|
| 66 |
+
outputs=[
|
| 67 |
+
generation_section["inference_steps"],
|
| 68 |
+
generation_section["guidance_scale"],
|
| 69 |
+
generation_section["use_adg"],
|
| 70 |
+
generation_section["shift"],
|
| 71 |
+
generation_section["cfg_interval_start"],
|
| 72 |
+
generation_section["cfg_interval_end"],
|
| 73 |
+
generation_section["task_type"],
|
| 74 |
+
]
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
generation_section["init_btn"].click(
|
| 78 |
+
fn=lambda *args: gen_h.init_service_wrapper(dit_handler, llm_handler, *args),
|
| 79 |
+
inputs=[
|
| 80 |
+
generation_section["checkpoint_dropdown"],
|
| 81 |
+
generation_section["config_path"],
|
| 82 |
+
generation_section["device"],
|
| 83 |
+
generation_section["init_llm_checkbox"],
|
| 84 |
+
generation_section["lm_model_path"],
|
| 85 |
+
generation_section["backend_dropdown"],
|
| 86 |
+
generation_section["use_flash_attention_checkbox"],
|
| 87 |
+
generation_section["offload_to_cpu_checkbox"],
|
| 88 |
+
generation_section["offload_dit_to_cpu_checkbox"],
|
| 89 |
+
],
|
| 90 |
+
outputs=[
|
| 91 |
+
generation_section["init_status"],
|
| 92 |
+
generation_section["generate_btn"],
|
| 93 |
+
generation_section["service_config_accordion"],
|
| 94 |
+
# Model type settings (updated based on actual loaded model)
|
| 95 |
+
generation_section["inference_steps"],
|
| 96 |
+
generation_section["guidance_scale"],
|
| 97 |
+
generation_section["use_adg"],
|
| 98 |
+
generation_section["shift"],
|
| 99 |
+
generation_section["cfg_interval_start"],
|
| 100 |
+
generation_section["cfg_interval_end"],
|
| 101 |
+
generation_section["task_type"],
|
| 102 |
+
]
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
# ========== LoRA Handlers ==========
|
| 106 |
+
generation_section["load_lora_btn"].click(
|
| 107 |
+
fn=dit_handler.load_lora,
|
| 108 |
+
inputs=[generation_section["lora_path"]],
|
| 109 |
+
outputs=[generation_section["lora_status"]]
|
| 110 |
+
).then(
|
| 111 |
+
# Update checkbox to enabled state after loading
|
| 112 |
+
fn=lambda: gr.update(value=True),
|
| 113 |
+
outputs=[generation_section["use_lora_checkbox"]]
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
generation_section["unload_lora_btn"].click(
|
| 117 |
+
fn=dit_handler.unload_lora,
|
| 118 |
+
outputs=[generation_section["lora_status"]]
|
| 119 |
+
).then(
|
| 120 |
+
# Update checkbox to disabled state after unloading
|
| 121 |
+
fn=lambda: gr.update(value=False),
|
| 122 |
+
outputs=[generation_section["use_lora_checkbox"]]
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
generation_section["use_lora_checkbox"].change(
|
| 126 |
+
fn=dit_handler.set_use_lora,
|
| 127 |
+
inputs=[generation_section["use_lora_checkbox"]],
|
| 128 |
+
outputs=[generation_section["lora_status"]]
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# ========== UI Visibility Updates ==========
|
| 132 |
+
generation_section["init_llm_checkbox"].change(
|
| 133 |
+
fn=gen_h.update_negative_prompt_visibility,
|
| 134 |
+
inputs=[generation_section["init_llm_checkbox"]],
|
| 135 |
+
outputs=[generation_section["lm_negative_prompt"]]
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
generation_section["init_llm_checkbox"].change(
|
| 139 |
+
fn=gen_h.update_audio_cover_strength_visibility,
|
| 140 |
+
inputs=[generation_section["task_type"], generation_section["init_llm_checkbox"]],
|
| 141 |
+
outputs=[generation_section["audio_cover_strength"]]
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
generation_section["task_type"].change(
|
| 145 |
+
fn=gen_h.update_audio_cover_strength_visibility,
|
| 146 |
+
inputs=[generation_section["task_type"], generation_section["init_llm_checkbox"]],
|
| 147 |
+
outputs=[generation_section["audio_cover_strength"]]
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
generation_section["batch_size_input"].change(
|
| 151 |
+
fn=gen_h.update_audio_components_visibility,
|
| 152 |
+
inputs=[generation_section["batch_size_input"]],
|
| 153 |
+
outputs=[
|
| 154 |
+
results_section["audio_col_1"],
|
| 155 |
+
results_section["audio_col_2"],
|
| 156 |
+
results_section["audio_col_3"],
|
| 157 |
+
results_section["audio_col_4"],
|
| 158 |
+
results_section["audio_row_5_8"],
|
| 159 |
+
results_section["audio_col_5"],
|
| 160 |
+
results_section["audio_col_6"],
|
| 161 |
+
results_section["audio_col_7"],
|
| 162 |
+
results_section["audio_col_8"],
|
| 163 |
+
]
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
# ========== Audio Conversion ==========
|
| 167 |
+
generation_section["convert_src_to_codes_btn"].click(
|
| 168 |
+
fn=lambda src: gen_h.convert_src_audio_to_codes_wrapper(dit_handler, src),
|
| 169 |
+
inputs=[generation_section["src_audio"]],
|
| 170 |
+
outputs=[generation_section["text2music_audio_code_string"]]
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
# ========== Instruction UI Updates ==========
|
| 174 |
+
for trigger in [generation_section["task_type"], generation_section["track_name"], generation_section["complete_track_classes"]]:
|
| 175 |
+
trigger.change(
|
| 176 |
+
fn=lambda *args: gen_h.update_instruction_ui(dit_handler, *args),
|
| 177 |
+
inputs=[
|
| 178 |
+
generation_section["task_type"],
|
| 179 |
+
generation_section["track_name"],
|
| 180 |
+
generation_section["complete_track_classes"],
|
| 181 |
+
generation_section["text2music_audio_code_string"],
|
| 182 |
+
generation_section["init_llm_checkbox"]
|
| 183 |
+
],
|
| 184 |
+
outputs=[
|
| 185 |
+
generation_section["instruction_display_gen"],
|
| 186 |
+
generation_section["track_name"],
|
| 187 |
+
generation_section["complete_track_classes"],
|
| 188 |
+
generation_section["audio_cover_strength"],
|
| 189 |
+
generation_section["repainting_group"],
|
| 190 |
+
generation_section["text2music_audio_codes_group"],
|
| 191 |
+
]
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
# ========== Sample/Transcribe Handlers ==========
|
| 195 |
+
# Load random example from ./examples/text2music directory
|
| 196 |
+
generation_section["sample_btn"].click(
|
| 197 |
+
fn=lambda task: gen_h.load_random_example(task) + (True,),
|
| 198 |
+
inputs=[
|
| 199 |
+
generation_section["task_type"],
|
| 200 |
+
],
|
| 201 |
+
outputs=[
|
| 202 |
+
generation_section["captions"],
|
| 203 |
+
generation_section["lyrics"],
|
| 204 |
+
generation_section["think_checkbox"],
|
| 205 |
+
generation_section["bpm"],
|
| 206 |
+
generation_section["audio_duration"],
|
| 207 |
+
generation_section["key_scale"],
|
| 208 |
+
generation_section["vocal_language"],
|
| 209 |
+
generation_section["time_signature"],
|
| 210 |
+
results_section["is_format_caption_state"]
|
| 211 |
+
]
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
generation_section["text2music_audio_code_string"].change(
|
| 215 |
+
fn=gen_h.update_transcribe_button_text,
|
| 216 |
+
inputs=[generation_section["text2music_audio_code_string"]],
|
| 217 |
+
outputs=[generation_section["transcribe_btn"]]
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
generation_section["transcribe_btn"].click(
|
| 221 |
+
fn=lambda codes, debug: gen_h.transcribe_audio_codes(llm_handler, codes, debug),
|
| 222 |
+
inputs=[
|
| 223 |
+
generation_section["text2music_audio_code_string"],
|
| 224 |
+
generation_section["constrained_decoding_debug"]
|
| 225 |
+
],
|
| 226 |
+
outputs=[
|
| 227 |
+
results_section["status_output"],
|
| 228 |
+
generation_section["captions"],
|
| 229 |
+
generation_section["lyrics"],
|
| 230 |
+
generation_section["bpm"],
|
| 231 |
+
generation_section["audio_duration"],
|
| 232 |
+
generation_section["key_scale"],
|
| 233 |
+
generation_section["vocal_language"],
|
| 234 |
+
generation_section["time_signature"],
|
| 235 |
+
results_section["is_format_caption_state"]
|
| 236 |
+
]
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
# ========== Reset Format Caption Flag ==========
|
| 240 |
+
for trigger in [generation_section["captions"], generation_section["lyrics"], generation_section["bpm"],
|
| 241 |
+
generation_section["key_scale"], generation_section["time_signature"],
|
| 242 |
+
generation_section["vocal_language"], generation_section["audio_duration"]]:
|
| 243 |
+
trigger.change(
|
| 244 |
+
fn=gen_h.reset_format_caption_flag,
|
| 245 |
+
inputs=[],
|
| 246 |
+
outputs=[results_section["is_format_caption_state"]]
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
# ========== Audio Uploads Accordion ==========
|
| 250 |
+
for trigger in [generation_section["reference_audio"], generation_section["src_audio"]]:
|
| 251 |
+
trigger.change(
|
| 252 |
+
fn=gen_h.update_audio_uploads_accordion,
|
| 253 |
+
inputs=[generation_section["reference_audio"], generation_section["src_audio"]],
|
| 254 |
+
outputs=[generation_section["audio_uploads_accordion"]]
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
# ========== Instrumental Checkbox ==========
|
| 258 |
+
generation_section["instrumental_checkbox"].change(
|
| 259 |
+
fn=gen_h.handle_instrumental_checkbox,
|
| 260 |
+
inputs=[generation_section["instrumental_checkbox"], generation_section["lyrics"]],
|
| 261 |
+
outputs=[generation_section["lyrics"]]
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
# ========== Format Button ==========
|
| 265 |
+
# Note: cfg_scale and negative_prompt are not supported in format mode
|
| 266 |
+
@_get_spaces_gpu_decorator(duration=120)
|
| 267 |
+
def handle_format_sample_wrapper(caption, lyrics, bpm, duration, key_scale, time_sig, temp, top_k, top_p, debug):
|
| 268 |
+
return gen_h.handle_format_sample(
|
| 269 |
+
llm_handler, caption, lyrics, bpm, duration, key_scale, time_sig, temp, top_k, top_p, debug
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
generation_section["format_btn"].click(
|
| 273 |
+
fn=handle_format_sample_wrapper,
|
| 274 |
+
inputs=[
|
| 275 |
+
generation_section["captions"],
|
| 276 |
+
generation_section["lyrics"],
|
| 277 |
+
generation_section["bpm"],
|
| 278 |
+
generation_section["audio_duration"],
|
| 279 |
+
generation_section["key_scale"],
|
| 280 |
+
generation_section["time_signature"],
|
| 281 |
+
generation_section["lm_temperature"],
|
| 282 |
+
generation_section["lm_top_k"],
|
| 283 |
+
generation_section["lm_top_p"],
|
| 284 |
+
generation_section["constrained_decoding_debug"],
|
| 285 |
+
],
|
| 286 |
+
outputs=[
|
| 287 |
+
generation_section["captions"],
|
| 288 |
+
generation_section["lyrics"],
|
| 289 |
+
generation_section["bpm"],
|
| 290 |
+
generation_section["audio_duration"],
|
| 291 |
+
generation_section["key_scale"],
|
| 292 |
+
generation_section["vocal_language"],
|
| 293 |
+
generation_section["time_signature"],
|
| 294 |
+
results_section["is_format_caption_state"],
|
| 295 |
+
results_section["status_output"],
|
| 296 |
+
]
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
# ========== Generation Mode Toggle (Simple/Custom/Cover/Repaint) ==========
|
| 300 |
+
generation_section["generation_mode"].change(
|
| 301 |
+
fn=gen_h.handle_generation_mode_change,
|
| 302 |
+
inputs=[generation_section["generation_mode"]],
|
| 303 |
+
outputs=[
|
| 304 |
+
generation_section["simple_mode_group"],
|
| 305 |
+
generation_section["custom_mode_content"],
|
| 306 |
+
generation_section["cover_mode_group"],
|
| 307 |
+
generation_section["repainting_group"],
|
| 308 |
+
generation_section["task_type"],
|
| 309 |
+
generation_section["generate_btn"],
|
| 310 |
+
generation_section["simple_sample_created"],
|
| 311 |
+
generation_section["src_audio_group"],
|
| 312 |
+
generation_section["audio_cover_strength"],
|
| 313 |
+
generation_section["think_checkbox"], # Disable thinking for cover/repaint modes
|
| 314 |
+
]
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
# ========== Process Source Audio Button ==========
|
| 318 |
+
# Combines Convert to Codes + Transcribe in one step
|
| 319 |
+
# Note: @spaces.GPU decorator must be on the function passed directly to fn=,
|
| 320 |
+
# not on a module-level function wrapped in a lambda. Lambdas capturing handler
|
| 321 |
+
# objects cause pickling errors on ZeroGPU because the model contains unpicklable
|
| 322 |
+
# local objects (e.g. AceStepDiTModel.__init__ lambdas).
|
| 323 |
+
@_get_spaces_gpu_decorator(duration=120)
|
| 324 |
+
def process_source_audio_wrapper(src, debug):
|
| 325 |
+
return gen_h.process_source_audio(dit_handler, llm_handler, src, debug)
|
| 326 |
+
|
| 327 |
+
generation_section["process_src_btn"].click(
|
| 328 |
+
fn=process_source_audio_wrapper,
|
| 329 |
+
inputs=[
|
| 330 |
+
generation_section["src_audio"],
|
| 331 |
+
generation_section["constrained_decoding_debug"]
|
| 332 |
+
],
|
| 333 |
+
outputs=[
|
| 334 |
+
generation_section["text2music_audio_code_string"],
|
| 335 |
+
results_section["status_output"],
|
| 336 |
+
generation_section["captions"],
|
| 337 |
+
generation_section["lyrics"],
|
| 338 |
+
generation_section["bpm"],
|
| 339 |
+
generation_section["audio_duration"],
|
| 340 |
+
generation_section["key_scale"],
|
| 341 |
+
generation_section["vocal_language"],
|
| 342 |
+
generation_section["time_signature"],
|
| 343 |
+
results_section["is_format_caption_state"],
|
| 344 |
+
]
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
# ========== Simple Mode Instrumental Checkbox ==========
|
| 348 |
+
# When instrumental is checked, disable vocal language and set to ["unknown"]
|
| 349 |
+
generation_section["simple_instrumental_checkbox"].change(
|
| 350 |
+
fn=gen_h.handle_simple_instrumental_change,
|
| 351 |
+
inputs=[generation_section["simple_instrumental_checkbox"]],
|
| 352 |
+
outputs=[generation_section["simple_vocal_language"]]
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
# ========== Random Description Button ==========
|
| 356 |
+
generation_section["random_desc_btn"].click(
|
| 357 |
+
fn=gen_h.load_random_simple_description,
|
| 358 |
+
inputs=[],
|
| 359 |
+
outputs=[
|
| 360 |
+
generation_section["simple_query_input"],
|
| 361 |
+
generation_section["simple_instrumental_checkbox"],
|
| 362 |
+
generation_section["simple_vocal_language"],
|
| 363 |
+
]
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
# ========== Create Sample Button (Simple Mode) ==========
|
| 367 |
+
# Note: cfg_scale and negative_prompt are not supported in create_sample mode
|
| 368 |
+
@_get_spaces_gpu_decorator(duration=120)
|
| 369 |
+
def handle_create_sample_wrapper(query, instrumental, vocal_lang, temp, top_k, top_p, debug):
|
| 370 |
+
return gen_h.handle_create_sample(
|
| 371 |
+
llm_handler, query, instrumental, vocal_lang, temp, top_k, top_p, debug
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
generation_section["create_sample_btn"].click(
|
| 375 |
+
fn=handle_create_sample_wrapper,
|
| 376 |
+
inputs=[
|
| 377 |
+
generation_section["simple_query_input"],
|
| 378 |
+
generation_section["simple_instrumental_checkbox"],
|
| 379 |
+
generation_section["simple_vocal_language"],
|
| 380 |
+
generation_section["lm_temperature"],
|
| 381 |
+
generation_section["lm_top_k"],
|
| 382 |
+
generation_section["lm_top_p"],
|
| 383 |
+
generation_section["constrained_decoding_debug"],
|
| 384 |
+
],
|
| 385 |
+
outputs=[
|
| 386 |
+
generation_section["captions"],
|
| 387 |
+
generation_section["lyrics"],
|
| 388 |
+
generation_section["bpm"],
|
| 389 |
+
generation_section["audio_duration"],
|
| 390 |
+
generation_section["key_scale"],
|
| 391 |
+
generation_section["vocal_language"],
|
| 392 |
+
generation_section["simple_vocal_language"],
|
| 393 |
+
generation_section["time_signature"],
|
| 394 |
+
generation_section["instrumental_checkbox"],
|
| 395 |
+
generation_section["caption_accordion"],
|
| 396 |
+
generation_section["lyrics_accordion"],
|
| 397 |
+
generation_section["generate_btn"],
|
| 398 |
+
generation_section["simple_sample_created"],
|
| 399 |
+
generation_section["think_checkbox"],
|
| 400 |
+
results_section["is_format_caption_state"],
|
| 401 |
+
results_section["status_output"],
|
| 402 |
+
]
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
# ========== Load/Save Metadata ==========
|
| 406 |
+
generation_section["load_file"].upload(
|
| 407 |
+
fn=gen_h.load_metadata,
|
| 408 |
+
inputs=[generation_section["load_file"]],
|
| 409 |
+
outputs=[
|
| 410 |
+
generation_section["task_type"],
|
| 411 |
+
generation_section["captions"],
|
| 412 |
+
generation_section["lyrics"],
|
| 413 |
+
generation_section["vocal_language"],
|
| 414 |
+
generation_section["bpm"],
|
| 415 |
+
generation_section["key_scale"],
|
| 416 |
+
generation_section["time_signature"],
|
| 417 |
+
generation_section["audio_duration"],
|
| 418 |
+
generation_section["batch_size_input"],
|
| 419 |
+
generation_section["inference_steps"],
|
| 420 |
+
generation_section["guidance_scale"],
|
| 421 |
+
generation_section["seed"],
|
| 422 |
+
generation_section["random_seed_checkbox"],
|
| 423 |
+
generation_section["use_adg"],
|
| 424 |
+
generation_section["cfg_interval_start"],
|
| 425 |
+
generation_section["cfg_interval_end"],
|
| 426 |
+
generation_section["shift"],
|
| 427 |
+
generation_section["infer_method"],
|
| 428 |
+
generation_section["custom_timesteps"],
|
| 429 |
+
generation_section["audio_format"],
|
| 430 |
+
generation_section["lm_temperature"],
|
| 431 |
+
generation_section["lm_cfg_scale"],
|
| 432 |
+
generation_section["lm_top_k"],
|
| 433 |
+
generation_section["lm_top_p"],
|
| 434 |
+
generation_section["lm_negative_prompt"],
|
| 435 |
+
generation_section["use_cot_metas"], # Added: use_cot_metas
|
| 436 |
+
generation_section["use_cot_caption"],
|
| 437 |
+
generation_section["use_cot_language"],
|
| 438 |
+
generation_section["audio_cover_strength"],
|
| 439 |
+
generation_section["think_checkbox"],
|
| 440 |
+
generation_section["text2music_audio_code_string"],
|
| 441 |
+
generation_section["repainting_start"],
|
| 442 |
+
generation_section["repainting_end"],
|
| 443 |
+
generation_section["track_name"],
|
| 444 |
+
generation_section["complete_track_classes"],
|
| 445 |
+
generation_section["instrumental_checkbox"], # Added: instrumental_checkbox
|
| 446 |
+
results_section["is_format_caption_state"]
|
| 447 |
+
]
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
# Save buttons for all 8 audio outputs
|
| 451 |
+
download_existing_js = """(current_audio, batch_files) => {
|
| 452 |
+
// Debug: print what the input actually is
|
| 453 |
+
console.log("👉 [Debug] Current Audio Input:", current_audio);
|
| 454 |
+
|
| 455 |
+
// 1. Safety check
|
| 456 |
+
if (!current_audio) {
|
| 457 |
+
console.warn("⚠️ No audio selected or audio is empty.");
|
| 458 |
+
return;
|
| 459 |
+
}
|
| 460 |
+
if (!batch_files || !Array.isArray(batch_files)) {
|
| 461 |
+
console.warn("⚠️ Batch file list is empty/not ready.");
|
| 462 |
+
return;
|
| 463 |
+
}
|
| 464 |
+
|
| 465 |
+
// 2. Smartly extract path string
|
| 466 |
+
let pathString = "";
|
| 467 |
+
|
| 468 |
+
if (typeof current_audio === "string") {
|
| 469 |
+
// Case A: direct path string received
|
| 470 |
+
pathString = current_audio;
|
| 471 |
+
} else if (typeof current_audio === "object") {
|
| 472 |
+
// Case B: an object is received, try common properties
|
| 473 |
+
// Gradio file objects usually have path, url, or name
|
| 474 |
+
pathString = current_audio.path || current_audio.name || current_audio.url || "";
|
| 475 |
+
}
|
| 476 |
+
|
| 477 |
+
if (!pathString) {
|
| 478 |
+
console.error("❌ Error: Could not extract a valid path string from input.", current_audio);
|
| 479 |
+
return;
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
// 3. Extract Key (UUID)
|
| 483 |
+
// Path could be /tmp/.../uuid.mp3 or url like /file=.../uuid.mp3
|
| 484 |
+
let filename = pathString.split(/[\\\\/]/).pop(); // get the filename
|
| 485 |
+
let key = filename.split('.')[0]; // get UUID without extension
|
| 486 |
+
|
| 487 |
+
console.log(`🔑 Key extracted: ${key}`);
|
| 488 |
+
|
| 489 |
+
// 4. Find matching file(s) in the list
|
| 490 |
+
let targets = batch_files.filter(f => {
|
| 491 |
+
// Also extract names from batch_files objects
|
| 492 |
+
// f usually contains name (backend path) and orig_name (download name)
|
| 493 |
+
const fPath = f.name || f.path || "";
|
| 494 |
+
return fPath.includes(key);
|
| 495 |
+
});
|
| 496 |
+
|
| 497 |
+
if (targets.length === 0) {
|
| 498 |
+
console.warn("❌ No matching files found in batch list for key:", key);
|
| 499 |
+
alert("Batch list does not contain this file yet. Please wait for generation to finish.");
|
| 500 |
+
return;
|
| 501 |
+
}
|
| 502 |
+
|
| 503 |
+
// 5. Trigger download(s)
|
| 504 |
+
console.log(`🎯 Found ${targets.length} files to download.`);
|
| 505 |
+
targets.forEach((f, index) => {
|
| 506 |
+
setTimeout(() => {
|
| 507 |
+
const a = document.createElement('a');
|
| 508 |
+
// Prefer url (frontend-accessible link), otherwise try data
|
| 509 |
+
a.href = f.url || f.data;
|
| 510 |
+
a.download = f.orig_name || "download";
|
| 511 |
+
a.style.display = 'none';
|
| 512 |
+
document.body.appendChild(a);
|
| 513 |
+
a.click();
|
| 514 |
+
document.body.removeChild(a);
|
| 515 |
+
}, index * 1000); // 300ms interval to avoid browser blocking
|
| 516 |
+
});
|
| 517 |
+
}
|
| 518 |
+
"""
|
| 519 |
+
for btn_idx in range(1, 9):
|
| 520 |
+
results_section[f"save_btn_{btn_idx}"].click(
|
| 521 |
+
fn=None,
|
| 522 |
+
inputs=[
|
| 523 |
+
results_section[f"generated_audio_{btn_idx}"],
|
| 524 |
+
results_section["generated_audio_batch"],
|
| 525 |
+
],
|
| 526 |
+
js=download_existing_js # Run the above JS
|
| 527 |
+
)
|
| 528 |
+
# ========== Send to Cover Handlers ==========
|
| 529 |
+
def send_to_cover_handler(audio_file, lm_metadata):
|
| 530 |
+
"""Send audio to cover mode and switch to cover"""
|
| 531 |
+
if audio_file is None:
|
| 532 |
+
return (gr.skip(),) * 11
|
| 533 |
+
return (
|
| 534 |
+
audio_file, # src_audio
|
| 535 |
+
gr.skip(), # bpm
|
| 536 |
+
gr.skip(), # captions
|
| 537 |
+
gr.skip(), # lyrics
|
| 538 |
+
gr.skip(), # audio_duration
|
| 539 |
+
gr.skip(), # key_scale
|
| 540 |
+
gr.skip(), # vocal_language
|
| 541 |
+
gr.skip(), # time_signature
|
| 542 |
+
gr.skip(), # is_format_caption_state
|
| 543 |
+
"cover", # generation_mode - switch to cover
|
| 544 |
+
"cover", # task_type - set to cover
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
for btn_idx in range(1, 9):
|
| 548 |
+
results_section[f"send_to_cover_btn_{btn_idx}"].click(
|
| 549 |
+
fn=send_to_cover_handler,
|
| 550 |
+
inputs=[
|
| 551 |
+
results_section[f"generated_audio_{btn_idx}"],
|
| 552 |
+
results_section["lm_metadata_state"]
|
| 553 |
+
],
|
| 554 |
+
outputs=[
|
| 555 |
+
generation_section["src_audio"],
|
| 556 |
+
generation_section["bpm"],
|
| 557 |
+
generation_section["captions"],
|
| 558 |
+
generation_section["lyrics"],
|
| 559 |
+
generation_section["audio_duration"],
|
| 560 |
+
generation_section["key_scale"],
|
| 561 |
+
generation_section["vocal_language"],
|
| 562 |
+
generation_section["time_signature"],
|
| 563 |
+
results_section["is_format_caption_state"],
|
| 564 |
+
generation_section["generation_mode"],
|
| 565 |
+
generation_section["task_type"],
|
| 566 |
+
]
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
# ========== Send to Repaint Handlers ==========
|
| 570 |
+
def send_to_repaint_handler(audio_file, lm_metadata):
|
| 571 |
+
"""Send audio to repaint mode and switch to repaint"""
|
| 572 |
+
if audio_file is None:
|
| 573 |
+
return (gr.skip(),) * 11
|
| 574 |
+
return (
|
| 575 |
+
audio_file, # src_audio
|
| 576 |
+
gr.skip(), # bpm
|
| 577 |
+
gr.skip(), # captions
|
| 578 |
+
gr.skip(), # lyrics
|
| 579 |
+
gr.skip(), # audio_duration
|
| 580 |
+
gr.skip(), # key_scale
|
| 581 |
+
gr.skip(), # vocal_language
|
| 582 |
+
gr.skip(), # time_signature
|
| 583 |
+
gr.skip(), # is_format_caption_state
|
| 584 |
+
"repaint", # generation_mode - switch to repaint
|
| 585 |
+
"repaint", # task_type - set to repaint
|
| 586 |
+
)
|
| 587 |
+
|
| 588 |
+
for btn_idx in range(1, 9):
|
| 589 |
+
results_section[f"send_to_repaint_btn_{btn_idx}"].click(
|
| 590 |
+
fn=send_to_repaint_handler,
|
| 591 |
+
inputs=[
|
| 592 |
+
results_section[f"generated_audio_{btn_idx}"],
|
| 593 |
+
results_section["lm_metadata_state"]
|
| 594 |
+
],
|
| 595 |
+
outputs=[
|
| 596 |
+
generation_section["src_audio"],
|
| 597 |
+
generation_section["bpm"],
|
| 598 |
+
generation_section["captions"],
|
| 599 |
+
generation_section["lyrics"],
|
| 600 |
+
generation_section["audio_duration"],
|
| 601 |
+
generation_section["key_scale"],
|
| 602 |
+
generation_section["vocal_language"],
|
| 603 |
+
generation_section["time_signature"],
|
| 604 |
+
results_section["is_format_caption_state"],
|
| 605 |
+
generation_section["generation_mode"],
|
| 606 |
+
generation_section["task_type"],
|
| 607 |
+
]
|
| 608 |
+
)
|
| 609 |
+
|
| 610 |
+
# ========== Score Calculation Handlers ==========
|
| 611 |
+
# Use default argument to capture btn_idx value at definition time (Python closure fix)
|
| 612 |
+
# Note: @spaces.GPU decorator applied here (not on module-level function) to avoid
|
| 613 |
+
# pickling issues on ZeroGPU when handler objects are captured in closures.
|
| 614 |
+
def make_score_handler(idx):
|
| 615 |
+
@_get_spaces_gpu_decorator(duration=120)
|
| 616 |
+
def score_handler(scale, batch_idx, queue):
|
| 617 |
+
return res_h.calculate_score_handler_with_selection(
|
| 618 |
+
dit_handler, llm_handler, idx, scale, batch_idx, queue
|
| 619 |
+
)
|
| 620 |
+
return score_handler
|
| 621 |
+
|
| 622 |
+
for btn_idx in range(1, 9):
|
| 623 |
+
results_section[f"score_btn_{btn_idx}"].click(
|
| 624 |
+
fn=make_score_handler(btn_idx),
|
| 625 |
+
inputs=[
|
| 626 |
+
generation_section["score_scale"],
|
| 627 |
+
results_section["current_batch_index"],
|
| 628 |
+
results_section["batch_queue"],
|
| 629 |
+
],
|
| 630 |
+
outputs=[
|
| 631 |
+
results_section[f"score_display_{btn_idx}"],
|
| 632 |
+
results_section[f"details_accordion_{btn_idx}"],
|
| 633 |
+
results_section["batch_queue"]
|
| 634 |
+
]
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
# ========== LRC Timestamp Handlers ==========
|
| 638 |
+
# Use default argument to capture btn_idx value at definition time (Python closure fix)
|
| 639 |
+
def make_lrc_handler(idx):
|
| 640 |
+
@_get_spaces_gpu_decorator(duration=120)
|
| 641 |
+
def lrc_handler(batch_idx, queue, vocal_lang, infer_steps):
|
| 642 |
+
return res_h.generate_lrc_handler(
|
| 643 |
+
dit_handler, idx, batch_idx, queue, vocal_lang, infer_steps
|
| 644 |
+
)
|
| 645 |
+
return lrc_handler
|
| 646 |
+
|
| 647 |
+
for btn_idx in range(1, 9):
|
| 648 |
+
results_section[f"lrc_btn_{btn_idx}"].click(
|
| 649 |
+
fn=make_lrc_handler(btn_idx),
|
| 650 |
+
inputs=[
|
| 651 |
+
results_section["current_batch_index"],
|
| 652 |
+
results_section["batch_queue"],
|
| 653 |
+
generation_section["vocal_language"],
|
| 654 |
+
generation_section["inference_steps"],
|
| 655 |
+
],
|
| 656 |
+
outputs=[
|
| 657 |
+
results_section[f"lrc_display_{btn_idx}"],
|
| 658 |
+
results_section[f"details_accordion_{btn_idx}"],
|
| 659 |
+
# NOTE: Removed generated_audio output!
|
| 660 |
+
# Audio subtitles are now updated via lrc_display.change() event.
|
| 661 |
+
results_section["batch_queue"]
|
| 662 |
+
]
|
| 663 |
+
)
|
| 664 |
+
|
| 665 |
+
@_get_spaces_gpu_decorator(duration=120)
|
| 666 |
+
def generation_wrapper(selected_model, generation_mode, simple_query_input, simple_vocal_language, *args):
|
| 667 |
+
"""Wrapper that selects the appropriate DiT handler based on model selection"""
|
| 668 |
+
# Convert args to list for modification
|
| 669 |
+
args_list = list(args)
|
| 670 |
+
|
| 671 |
+
# args order (after simple mode params):
|
| 672 |
+
# captions (0), lyrics (1), bpm (2), key_scale (3), time_signature (4), vocal_language (5),
|
| 673 |
+
# inference_steps (6), guidance_scale (7), random_seed_checkbox (8), seed (9),
|
| 674 |
+
# reference_audio (10), audio_duration (11), batch_size_input (12), src_audio (13),
|
| 675 |
+
# text2music_audio_code_string (14), repainting_start (15), repainting_end (16),
|
| 676 |
+
# instruction_display_gen (17), audio_cover_strength (18), task_type (19), ...
|
| 677 |
+
# ... lm_temperature (27), think_checkbox (28), ...
|
| 678 |
+
# ... instrumental_checkbox (at position after all regular params)
|
| 679 |
+
|
| 680 |
+
src_audio = args_list[13] if len(args_list) > 13 else None
|
| 681 |
+
task_type = args_list[19] if len(args_list) > 19 else "text2music"
|
| 682 |
+
|
| 683 |
+
# Validate: Cover and Repaint modes require source audio
|
| 684 |
+
if task_type in ["cover", "repaint"] and src_audio is None:
|
| 685 |
+
raise gr.Error(f"Source Audio is required for {task_type.capitalize()} mode. Please upload an audio file.")
|
| 686 |
+
|
| 687 |
+
# Handle Simple mode: first create sample, then generate
|
| 688 |
+
if generation_mode == "simple":
|
| 689 |
+
# Get instrumental from the main checkbox (args[-6] based on input order)
|
| 690 |
+
# The instrumental_checkbox is passed after all the regular generation params
|
| 691 |
+
instrumental = args_list[-6] if len(args_list) > 6 else False # instrumental_checkbox position
|
| 692 |
+
lm_temperature = args_list[27] if len(args_list) > 27 else 0.85
|
| 693 |
+
lm_top_k = args_list[30] if len(args_list) > 30 else 0
|
| 694 |
+
lm_top_p = args_list[31] if len(args_list) > 31 else 0.9
|
| 695 |
+
constrained_decoding_debug = args_list[38] if len(args_list) > 38 else False
|
| 696 |
+
|
| 697 |
+
# Call create_sample to generate caption/lyrics/metadata
|
| 698 |
+
from acestep.inference import create_sample
|
| 699 |
+
|
| 700 |
+
top_k_value = None if not lm_top_k or lm_top_k == 0 else int(lm_top_k)
|
| 701 |
+
top_p_value = None if not lm_top_p or lm_top_p >= 1.0 else lm_top_p
|
| 702 |
+
|
| 703 |
+
result = create_sample(
|
| 704 |
+
llm_handler=llm_handler,
|
| 705 |
+
query=simple_query_input,
|
| 706 |
+
instrumental=instrumental,
|
| 707 |
+
vocal_language=simple_vocal_language,
|
| 708 |
+
temperature=lm_temperature,
|
| 709 |
+
top_k=top_k_value,
|
| 710 |
+
top_p=top_p_value,
|
| 711 |
+
use_constrained_decoding=True,
|
| 712 |
+
constrained_decoding_debug=constrained_decoding_debug,
|
| 713 |
+
)
|
| 714 |
+
|
| 715 |
+
if not result.success:
|
| 716 |
+
raise gr.Error(f"Failed to create sample: {result.status_message}")
|
| 717 |
+
|
| 718 |
+
# Update args with generated data
|
| 719 |
+
args_list[0] = result.caption # captions
|
| 720 |
+
args_list[1] = result.lyrics # lyrics
|
| 721 |
+
args_list[2] = result.bpm # bpm
|
| 722 |
+
args_list[3] = result.keyscale # key_scale
|
| 723 |
+
args_list[4] = result.timesignature # time_signature
|
| 724 |
+
args_list[5] = result.language # vocal_language
|
| 725 |
+
if result.duration and result.duration > 0:
|
| 726 |
+
args_list[11] = result.duration # audio_duration
|
| 727 |
+
# Enable thinking for Simple mode
|
| 728 |
+
args_list[28] = True # think_checkbox
|
| 729 |
+
# Mark as formatted caption (LM-generated sample)
|
| 730 |
+
args_list[36] = True # is_format_caption_state
|
| 731 |
+
|
| 732 |
+
# Determine which handler to use based on model selection
|
| 733 |
+
active_handler = dit_handler # Default to primary handler
|
| 734 |
+
if dit_handler_2 is not None and selected_model == config_path_2:
|
| 735 |
+
active_handler = dit_handler_2
|
| 736 |
+
yield from res_h.generate_with_batch_management(active_handler, llm_handler, *args_list)
|
| 737 |
+
|
| 738 |
+
# ========== Generation Handler ==========
|
| 739 |
+
generation_section["generate_btn"].click(
|
| 740 |
+
fn=generation_wrapper,
|
| 741 |
+
inputs=[
|
| 742 |
+
generation_section["dit_model_selector"], # Model selection input
|
| 743 |
+
generation_section["generation_mode"], # For Simple mode detection
|
| 744 |
+
generation_section["simple_query_input"], # Simple mode query
|
| 745 |
+
generation_section["simple_vocal_language"], # Simple mode vocal language
|
| 746 |
+
generation_section["captions"],
|
| 747 |
+
generation_section["lyrics"],
|
| 748 |
+
generation_section["bpm"],
|
| 749 |
+
generation_section["key_scale"],
|
| 750 |
+
generation_section["time_signature"],
|
| 751 |
+
generation_section["vocal_language"],
|
| 752 |
+
generation_section["inference_steps"],
|
| 753 |
+
generation_section["guidance_scale"],
|
| 754 |
+
generation_section["random_seed_checkbox"],
|
| 755 |
+
generation_section["seed"],
|
| 756 |
+
generation_section["reference_audio"],
|
| 757 |
+
generation_section["audio_duration"],
|
| 758 |
+
generation_section["batch_size_input"],
|
| 759 |
+
generation_section["src_audio"],
|
| 760 |
+
generation_section["text2music_audio_code_string"],
|
| 761 |
+
generation_section["repainting_start"],
|
| 762 |
+
generation_section["repainting_end"],
|
| 763 |
+
generation_section["instruction_display_gen"],
|
| 764 |
+
generation_section["audio_cover_strength"],
|
| 765 |
+
generation_section["task_type"],
|
| 766 |
+
generation_section["use_adg"],
|
| 767 |
+
generation_section["cfg_interval_start"],
|
| 768 |
+
generation_section["cfg_interval_end"],
|
| 769 |
+
generation_section["shift"],
|
| 770 |
+
generation_section["infer_method"],
|
| 771 |
+
generation_section["custom_timesteps"],
|
| 772 |
+
generation_section["audio_format"],
|
| 773 |
+
generation_section["lm_temperature"],
|
| 774 |
+
generation_section["think_checkbox"],
|
| 775 |
+
generation_section["lm_cfg_scale"],
|
| 776 |
+
generation_section["lm_top_k"],
|
| 777 |
+
generation_section["lm_top_p"],
|
| 778 |
+
generation_section["lm_negative_prompt"],
|
| 779 |
+
generation_section["use_cot_metas"],
|
| 780 |
+
generation_section["use_cot_caption"],
|
| 781 |
+
generation_section["use_cot_language"],
|
| 782 |
+
results_section["is_format_caption_state"],
|
| 783 |
+
generation_section["constrained_decoding_debug"],
|
| 784 |
+
generation_section["allow_lm_batch"],
|
| 785 |
+
generation_section["auto_score"],
|
| 786 |
+
generation_section["auto_lrc"],
|
| 787 |
+
generation_section["score_scale"],
|
| 788 |
+
generation_section["lm_batch_chunk_size"],
|
| 789 |
+
generation_section["track_name"],
|
| 790 |
+
generation_section["complete_track_classes"],
|
| 791 |
+
generation_section["autogen_checkbox"],
|
| 792 |
+
results_section["current_batch_index"],
|
| 793 |
+
results_section["total_batches"],
|
| 794 |
+
results_section["batch_queue"],
|
| 795 |
+
results_section["generation_params_state"],
|
| 796 |
+
],
|
| 797 |
+
outputs=[
|
| 798 |
+
results_section["generated_audio_1"],
|
| 799 |
+
results_section["generated_audio_2"],
|
| 800 |
+
results_section["generated_audio_3"],
|
| 801 |
+
results_section["generated_audio_4"],
|
| 802 |
+
results_section["generated_audio_5"],
|
| 803 |
+
results_section["generated_audio_6"],
|
| 804 |
+
results_section["generated_audio_7"],
|
| 805 |
+
results_section["generated_audio_8"],
|
| 806 |
+
results_section["generated_audio_batch"],
|
| 807 |
+
results_section["generation_info"],
|
| 808 |
+
results_section["status_output"],
|
| 809 |
+
generation_section["seed"],
|
| 810 |
+
results_section["score_display_1"],
|
| 811 |
+
results_section["score_display_2"],
|
| 812 |
+
results_section["score_display_3"],
|
| 813 |
+
results_section["score_display_4"],
|
| 814 |
+
results_section["score_display_5"],
|
| 815 |
+
results_section["score_display_6"],
|
| 816 |
+
results_section["score_display_7"],
|
| 817 |
+
results_section["score_display_8"],
|
| 818 |
+
results_section["codes_display_1"],
|
| 819 |
+
results_section["codes_display_2"],
|
| 820 |
+
results_section["codes_display_3"],
|
| 821 |
+
results_section["codes_display_4"],
|
| 822 |
+
results_section["codes_display_5"],
|
| 823 |
+
results_section["codes_display_6"],
|
| 824 |
+
results_section["codes_display_7"],
|
| 825 |
+
results_section["codes_display_8"],
|
| 826 |
+
results_section["details_accordion_1"],
|
| 827 |
+
results_section["details_accordion_2"],
|
| 828 |
+
results_section["details_accordion_3"],
|
| 829 |
+
results_section["details_accordion_4"],
|
| 830 |
+
results_section["details_accordion_5"],
|
| 831 |
+
results_section["details_accordion_6"],
|
| 832 |
+
results_section["details_accordion_7"],
|
| 833 |
+
results_section["details_accordion_8"],
|
| 834 |
+
results_section["lrc_display_1"],
|
| 835 |
+
results_section["lrc_display_2"],
|
| 836 |
+
results_section["lrc_display_3"],
|
| 837 |
+
results_section["lrc_display_4"],
|
| 838 |
+
results_section["lrc_display_5"],
|
| 839 |
+
results_section["lrc_display_6"],
|
| 840 |
+
results_section["lrc_display_7"],
|
| 841 |
+
results_section["lrc_display_8"],
|
| 842 |
+
results_section["lm_metadata_state"],
|
| 843 |
+
results_section["is_format_caption_state"],
|
| 844 |
+
results_section["current_batch_index"],
|
| 845 |
+
results_section["total_batches"],
|
| 846 |
+
results_section["batch_queue"],
|
| 847 |
+
results_section["generation_params_state"],
|
| 848 |
+
results_section["batch_indicator"],
|
| 849 |
+
results_section["prev_batch_btn"],
|
| 850 |
+
results_section["next_batch_btn"],
|
| 851 |
+
results_section["next_batch_status"],
|
| 852 |
+
results_section["restore_params_btn"],
|
| 853 |
+
]
|
| 854 |
+
).then(
|
| 855 |
+
fn=lambda selected_model, *args: res_h.generate_next_batch_background(
|
| 856 |
+
dit_handler_2 if (dit_handler_2 is not None and selected_model == config_path_2) else dit_handler,
|
| 857 |
+
llm_handler, *args
|
| 858 |
+
),
|
| 859 |
+
inputs=[
|
| 860 |
+
generation_section["dit_model_selector"], # Model selection input
|
| 861 |
+
generation_section["autogen_checkbox"],
|
| 862 |
+
results_section["generation_params_state"],
|
| 863 |
+
results_section["current_batch_index"],
|
| 864 |
+
results_section["total_batches"],
|
| 865 |
+
results_section["batch_queue"],
|
| 866 |
+
results_section["is_format_caption_state"],
|
| 867 |
+
],
|
| 868 |
+
outputs=[
|
| 869 |
+
results_section["batch_queue"],
|
| 870 |
+
results_section["total_batches"],
|
| 871 |
+
results_section["next_batch_status"],
|
| 872 |
+
results_section["next_batch_btn"],
|
| 873 |
+
]
|
| 874 |
+
)
|
| 875 |
+
|
| 876 |
+
# ========== Batch Navigation Handlers ==========
|
| 877 |
+
results_section["prev_batch_btn"].click(
|
| 878 |
+
fn=res_h.navigate_to_previous_batch,
|
| 879 |
+
inputs=[
|
| 880 |
+
results_section["current_batch_index"],
|
| 881 |
+
results_section["batch_queue"],
|
| 882 |
+
],
|
| 883 |
+
outputs=[
|
| 884 |
+
results_section["generated_audio_1"],
|
| 885 |
+
results_section["generated_audio_2"],
|
| 886 |
+
results_section["generated_audio_3"],
|
| 887 |
+
results_section["generated_audio_4"],
|
| 888 |
+
results_section["generated_audio_5"],
|
| 889 |
+
results_section["generated_audio_6"],
|
| 890 |
+
results_section["generated_audio_7"],
|
| 891 |
+
results_section["generated_audio_8"],
|
| 892 |
+
results_section["generated_audio_batch"],
|
| 893 |
+
results_section["generation_info"],
|
| 894 |
+
results_section["current_batch_index"],
|
| 895 |
+
results_section["batch_indicator"],
|
| 896 |
+
results_section["prev_batch_btn"],
|
| 897 |
+
results_section["next_batch_btn"],
|
| 898 |
+
results_section["status_output"],
|
| 899 |
+
results_section["score_display_1"],
|
| 900 |
+
results_section["score_display_2"],
|
| 901 |
+
results_section["score_display_3"],
|
| 902 |
+
results_section["score_display_4"],
|
| 903 |
+
results_section["score_display_5"],
|
| 904 |
+
results_section["score_display_6"],
|
| 905 |
+
results_section["score_display_7"],
|
| 906 |
+
results_section["score_display_8"],
|
| 907 |
+
results_section["codes_display_1"],
|
| 908 |
+
results_section["codes_display_2"],
|
| 909 |
+
results_section["codes_display_3"],
|
| 910 |
+
results_section["codes_display_4"],
|
| 911 |
+
results_section["codes_display_5"],
|
| 912 |
+
results_section["codes_display_6"],
|
| 913 |
+
results_section["codes_display_7"],
|
| 914 |
+
results_section["codes_display_8"],
|
| 915 |
+
results_section["lrc_display_1"],
|
| 916 |
+
results_section["lrc_display_2"],
|
| 917 |
+
results_section["lrc_display_3"],
|
| 918 |
+
results_section["lrc_display_4"],
|
| 919 |
+
results_section["lrc_display_5"],
|
| 920 |
+
results_section["lrc_display_6"],
|
| 921 |
+
results_section["lrc_display_7"],
|
| 922 |
+
results_section["lrc_display_8"],
|
| 923 |
+
results_section["details_accordion_1"],
|
| 924 |
+
results_section["details_accordion_2"],
|
| 925 |
+
results_section["details_accordion_3"],
|
| 926 |
+
results_section["details_accordion_4"],
|
| 927 |
+
results_section["details_accordion_5"],
|
| 928 |
+
results_section["details_accordion_6"],
|
| 929 |
+
results_section["details_accordion_7"],
|
| 930 |
+
results_section["details_accordion_8"],
|
| 931 |
+
results_section["restore_params_btn"],
|
| 932 |
+
]
|
| 933 |
+
)
|
| 934 |
+
|
| 935 |
+
results_section["next_batch_btn"].click(
|
| 936 |
+
fn=res_h.capture_current_params,
|
| 937 |
+
inputs=[
|
| 938 |
+
generation_section["captions"],
|
| 939 |
+
generation_section["lyrics"],
|
| 940 |
+
generation_section["bpm"],
|
| 941 |
+
generation_section["key_scale"],
|
| 942 |
+
generation_section["time_signature"],
|
| 943 |
+
generation_section["vocal_language"],
|
| 944 |
+
generation_section["inference_steps"],
|
| 945 |
+
generation_section["guidance_scale"],
|
| 946 |
+
generation_section["random_seed_checkbox"],
|
| 947 |
+
generation_section["seed"],
|
| 948 |
+
generation_section["reference_audio"],
|
| 949 |
+
generation_section["audio_duration"],
|
| 950 |
+
generation_section["batch_size_input"],
|
| 951 |
+
generation_section["src_audio"],
|
| 952 |
+
generation_section["text2music_audio_code_string"],
|
| 953 |
+
generation_section["repainting_start"],
|
| 954 |
+
generation_section["repainting_end"],
|
| 955 |
+
generation_section["instruction_display_gen"],
|
| 956 |
+
generation_section["audio_cover_strength"],
|
| 957 |
+
generation_section["task_type"],
|
| 958 |
+
generation_section["use_adg"],
|
| 959 |
+
generation_section["cfg_interval_start"],
|
| 960 |
+
generation_section["cfg_interval_end"],
|
| 961 |
+
generation_section["shift"],
|
| 962 |
+
generation_section["infer_method"],
|
| 963 |
+
generation_section["custom_timesteps"],
|
| 964 |
+
generation_section["audio_format"],
|
| 965 |
+
generation_section["lm_temperature"],
|
| 966 |
+
generation_section["think_checkbox"],
|
| 967 |
+
generation_section["lm_cfg_scale"],
|
| 968 |
+
generation_section["lm_top_k"],
|
| 969 |
+
generation_section["lm_top_p"],
|
| 970 |
+
generation_section["lm_negative_prompt"],
|
| 971 |
+
generation_section["use_cot_metas"],
|
| 972 |
+
generation_section["use_cot_caption"],
|
| 973 |
+
generation_section["use_cot_language"],
|
| 974 |
+
generation_section["constrained_decoding_debug"],
|
| 975 |
+
generation_section["allow_lm_batch"],
|
| 976 |
+
generation_section["auto_score"],
|
| 977 |
+
generation_section["auto_lrc"],
|
| 978 |
+
generation_section["score_scale"],
|
| 979 |
+
generation_section["lm_batch_chunk_size"],
|
| 980 |
+
generation_section["track_name"],
|
| 981 |
+
generation_section["complete_track_classes"],
|
| 982 |
+
],
|
| 983 |
+
outputs=[results_section["generation_params_state"]]
|
| 984 |
+
).then(
|
| 985 |
+
fn=res_h.navigate_to_next_batch,
|
| 986 |
+
inputs=[
|
| 987 |
+
generation_section["autogen_checkbox"],
|
| 988 |
+
results_section["current_batch_index"],
|
| 989 |
+
results_section["total_batches"],
|
| 990 |
+
results_section["batch_queue"],
|
| 991 |
+
],
|
| 992 |
+
outputs=[
|
| 993 |
+
results_section["generated_audio_1"],
|
| 994 |
+
results_section["generated_audio_2"],
|
| 995 |
+
results_section["generated_audio_3"],
|
| 996 |
+
results_section["generated_audio_4"],
|
| 997 |
+
results_section["generated_audio_5"],
|
| 998 |
+
results_section["generated_audio_6"],
|
| 999 |
+
results_section["generated_audio_7"],
|
| 1000 |
+
results_section["generated_audio_8"],
|
| 1001 |
+
results_section["generated_audio_batch"],
|
| 1002 |
+
results_section["generation_info"],
|
| 1003 |
+
results_section["current_batch_index"],
|
| 1004 |
+
results_section["batch_indicator"],
|
| 1005 |
+
results_section["prev_batch_btn"],
|
| 1006 |
+
results_section["next_batch_btn"],
|
| 1007 |
+
results_section["status_output"],
|
| 1008 |
+
results_section["next_batch_status"],
|
| 1009 |
+
results_section["score_display_1"],
|
| 1010 |
+
results_section["score_display_2"],
|
| 1011 |
+
results_section["score_display_3"],
|
| 1012 |
+
results_section["score_display_4"],
|
| 1013 |
+
results_section["score_display_5"],
|
| 1014 |
+
results_section["score_display_6"],
|
| 1015 |
+
results_section["score_display_7"],
|
| 1016 |
+
results_section["score_display_8"],
|
| 1017 |
+
results_section["codes_display_1"],
|
| 1018 |
+
results_section["codes_display_2"],
|
| 1019 |
+
results_section["codes_display_3"],
|
| 1020 |
+
results_section["codes_display_4"],
|
| 1021 |
+
results_section["codes_display_5"],
|
| 1022 |
+
results_section["codes_display_6"],
|
| 1023 |
+
results_section["codes_display_7"],
|
| 1024 |
+
results_section["codes_display_8"],
|
| 1025 |
+
results_section["lrc_display_1"],
|
| 1026 |
+
results_section["lrc_display_2"],
|
| 1027 |
+
results_section["lrc_display_3"],
|
| 1028 |
+
results_section["lrc_display_4"],
|
| 1029 |
+
results_section["lrc_display_5"],
|
| 1030 |
+
results_section["lrc_display_6"],
|
| 1031 |
+
results_section["lrc_display_7"],
|
| 1032 |
+
results_section["lrc_display_8"],
|
| 1033 |
+
results_section["details_accordion_1"],
|
| 1034 |
+
results_section["details_accordion_2"],
|
| 1035 |
+
results_section["details_accordion_3"],
|
| 1036 |
+
results_section["details_accordion_4"],
|
| 1037 |
+
results_section["details_accordion_5"],
|
| 1038 |
+
results_section["details_accordion_6"],
|
| 1039 |
+
results_section["details_accordion_7"],
|
| 1040 |
+
results_section["details_accordion_8"],
|
| 1041 |
+
results_section["restore_params_btn"],
|
| 1042 |
+
]
|
| 1043 |
+
).then(
|
| 1044 |
+
fn=lambda selected_model, *args: res_h.generate_next_batch_background(
|
| 1045 |
+
dit_handler_2 if (dit_handler_2 is not None and selected_model == config_path_2) else dit_handler,
|
| 1046 |
+
llm_handler, *args
|
| 1047 |
+
),
|
| 1048 |
+
inputs=[
|
| 1049 |
+
generation_section["dit_model_selector"], # Model selection input
|
| 1050 |
+
generation_section["autogen_checkbox"],
|
| 1051 |
+
results_section["generation_params_state"],
|
| 1052 |
+
results_section["current_batch_index"],
|
| 1053 |
+
results_section["total_batches"],
|
| 1054 |
+
results_section["batch_queue"],
|
| 1055 |
+
results_section["is_format_caption_state"],
|
| 1056 |
+
],
|
| 1057 |
+
outputs=[
|
| 1058 |
+
results_section["batch_queue"],
|
| 1059 |
+
results_section["total_batches"],
|
| 1060 |
+
results_section["next_batch_status"],
|
| 1061 |
+
results_section["next_batch_btn"],
|
| 1062 |
+
]
|
| 1063 |
+
)
|
| 1064 |
+
|
| 1065 |
+
# ========== Restore Parameters Handler ==========
|
| 1066 |
+
results_section["restore_params_btn"].click(
|
| 1067 |
+
fn=res_h.restore_batch_parameters,
|
| 1068 |
+
inputs=[
|
| 1069 |
+
results_section["current_batch_index"],
|
| 1070 |
+
results_section["batch_queue"]
|
| 1071 |
+
],
|
| 1072 |
+
outputs=[
|
| 1073 |
+
generation_section["text2music_audio_code_string"],
|
| 1074 |
+
generation_section["captions"],
|
| 1075 |
+
generation_section["lyrics"],
|
| 1076 |
+
generation_section["bpm"],
|
| 1077 |
+
generation_section["key_scale"],
|
| 1078 |
+
generation_section["time_signature"],
|
| 1079 |
+
generation_section["vocal_language"],
|
| 1080 |
+
generation_section["audio_duration"],
|
| 1081 |
+
generation_section["batch_size_input"],
|
| 1082 |
+
generation_section["inference_steps"],
|
| 1083 |
+
generation_section["lm_temperature"],
|
| 1084 |
+
generation_section["lm_cfg_scale"],
|
| 1085 |
+
generation_section["lm_top_k"],
|
| 1086 |
+
generation_section["lm_top_p"],
|
| 1087 |
+
generation_section["think_checkbox"],
|
| 1088 |
+
generation_section["use_cot_caption"],
|
| 1089 |
+
generation_section["use_cot_language"],
|
| 1090 |
+
generation_section["allow_lm_batch"],
|
| 1091 |
+
generation_section["track_name"],
|
| 1092 |
+
generation_section["complete_track_classes"],
|
| 1093 |
+
]
|
| 1094 |
+
)
|
| 1095 |
+
|
| 1096 |
+
# ========== LRC Display Change Handlers ==========
|
| 1097 |
+
# NEW APPROACH: Use lrc_display.change() to update audio subtitles
|
| 1098 |
+
# This decouples audio value updates from subtitle updates, avoiding flickering.
|
| 1099 |
+
#
|
| 1100 |
+
# When lrc_display text changes (from generate, LRC button, or manual edit):
|
| 1101 |
+
# 1. lrc_display.change() is triggered
|
| 1102 |
+
# 2. update_audio_subtitles_from_lrc() parses LRC and updates audio subtitles
|
| 1103 |
+
# 3. Audio value is NEVER updated here - only subtitles
|
| 1104 |
+
for lrc_idx in range(1, 9):
|
| 1105 |
+
results_section[f"lrc_display_{lrc_idx}"].change(
|
| 1106 |
+
fn=res_h.update_audio_subtitles_from_lrc,
|
| 1107 |
+
inputs=[
|
| 1108 |
+
results_section[f"lrc_display_{lrc_idx}"],
|
| 1109 |
+
# audio_duration not needed - parse_lrc_to_subtitles calculates end time from timestamps
|
| 1110 |
+
],
|
| 1111 |
+
outputs=[
|
| 1112 |
+
results_section[f"generated_audio_{lrc_idx}"], # Only updates subtitles, not value
|
| 1113 |
+
]
|
| 1114 |
+
)
|
| 1115 |
+
|
| 1116 |
+
|
| 1117 |
+
def setup_training_event_handlers(demo, dit_handler, llm_handler, training_section):
|
| 1118 |
+
"""Setup event handlers for the training tab (dataset builder and LoRA training)"""
|
| 1119 |
+
|
| 1120 |
+
# ========== Load Existing Dataset (Top Section) ==========
|
| 1121 |
+
|
| 1122 |
+
# Load existing dataset JSON at the top of Dataset Builder
|
| 1123 |
+
training_section["load_json_btn"].click(
|
| 1124 |
+
fn=train_h.load_existing_dataset_for_preprocess,
|
| 1125 |
+
inputs=[
|
| 1126 |
+
training_section["load_json_path"],
|
| 1127 |
+
training_section["dataset_builder_state"],
|
| 1128 |
+
],
|
| 1129 |
+
outputs=[
|
| 1130 |
+
training_section["load_json_status"],
|
| 1131 |
+
training_section["audio_files_table"],
|
| 1132 |
+
training_section["sample_selector"],
|
| 1133 |
+
training_section["dataset_builder_state"],
|
| 1134 |
+
# Also update preview fields with first sample
|
| 1135 |
+
training_section["preview_audio"],
|
| 1136 |
+
training_section["preview_filename"],
|
| 1137 |
+
training_section["edit_caption"],
|
| 1138 |
+
training_section["edit_lyrics"],
|
| 1139 |
+
training_section["edit_bpm"],
|
| 1140 |
+
training_section["edit_keyscale"],
|
| 1141 |
+
training_section["edit_timesig"],
|
| 1142 |
+
training_section["edit_duration"],
|
| 1143 |
+
training_section["edit_language"],
|
| 1144 |
+
training_section["edit_instrumental"],
|
| 1145 |
+
]
|
| 1146 |
+
)
|
| 1147 |
+
|
| 1148 |
+
# ========== Dataset Builder Handlers ==========
|
| 1149 |
+
|
| 1150 |
+
# Scan directory for audio files
|
| 1151 |
+
training_section["scan_btn"].click(
|
| 1152 |
+
fn=lambda dir, name, tag, pos, instr, state: train_h.scan_directory(
|
| 1153 |
+
dir, name, tag, pos, instr, state
|
| 1154 |
+
),
|
| 1155 |
+
inputs=[
|
| 1156 |
+
training_section["audio_directory"],
|
| 1157 |
+
training_section["dataset_name"],
|
| 1158 |
+
training_section["custom_tag"],
|
| 1159 |
+
training_section["tag_position"],
|
| 1160 |
+
training_section["all_instrumental"],
|
| 1161 |
+
training_section["dataset_builder_state"],
|
| 1162 |
+
],
|
| 1163 |
+
outputs=[
|
| 1164 |
+
training_section["audio_files_table"],
|
| 1165 |
+
training_section["scan_status"],
|
| 1166 |
+
training_section["sample_selector"],
|
| 1167 |
+
training_section["dataset_builder_state"],
|
| 1168 |
+
]
|
| 1169 |
+
)
|
| 1170 |
+
|
| 1171 |
+
# Auto-label all samples
|
| 1172 |
+
training_section["auto_label_btn"].click(
|
| 1173 |
+
fn=lambda state, skip: train_h.auto_label_all(dit_handler, llm_handler, state, skip),
|
| 1174 |
+
inputs=[
|
| 1175 |
+
training_section["dataset_builder_state"],
|
| 1176 |
+
training_section["skip_metas"],
|
| 1177 |
+
],
|
| 1178 |
+
outputs=[
|
| 1179 |
+
training_section["audio_files_table"],
|
| 1180 |
+
training_section["label_progress"],
|
| 1181 |
+
training_section["dataset_builder_state"],
|
| 1182 |
+
]
|
| 1183 |
+
)
|
| 1184 |
+
|
| 1185 |
+
# Sample selector change - update preview
|
| 1186 |
+
training_section["sample_selector"].change(
|
| 1187 |
+
fn=train_h.get_sample_preview,
|
| 1188 |
+
inputs=[
|
| 1189 |
+
training_section["sample_selector"],
|
| 1190 |
+
training_section["dataset_builder_state"],
|
| 1191 |
+
],
|
| 1192 |
+
outputs=[
|
| 1193 |
+
training_section["preview_audio"],
|
| 1194 |
+
training_section["preview_filename"],
|
| 1195 |
+
training_section["edit_caption"],
|
| 1196 |
+
training_section["edit_lyrics"],
|
| 1197 |
+
training_section["edit_bpm"],
|
| 1198 |
+
training_section["edit_keyscale"],
|
| 1199 |
+
training_section["edit_timesig"],
|
| 1200 |
+
training_section["edit_duration"],
|
| 1201 |
+
training_section["edit_language"],
|
| 1202 |
+
training_section["edit_instrumental"],
|
| 1203 |
+
]
|
| 1204 |
+
)
|
| 1205 |
+
|
| 1206 |
+
# Save sample edit
|
| 1207 |
+
training_section["save_edit_btn"].click(
|
| 1208 |
+
fn=train_h.save_sample_edit,
|
| 1209 |
+
inputs=[
|
| 1210 |
+
training_section["sample_selector"],
|
| 1211 |
+
training_section["edit_caption"],
|
| 1212 |
+
training_section["edit_lyrics"],
|
| 1213 |
+
training_section["edit_bpm"],
|
| 1214 |
+
training_section["edit_keyscale"],
|
| 1215 |
+
training_section["edit_timesig"],
|
| 1216 |
+
training_section["edit_language"],
|
| 1217 |
+
training_section["edit_instrumental"],
|
| 1218 |
+
training_section["dataset_builder_state"],
|
| 1219 |
+
],
|
| 1220 |
+
outputs=[
|
| 1221 |
+
training_section["audio_files_table"],
|
| 1222 |
+
training_section["edit_status"],
|
| 1223 |
+
training_section["dataset_builder_state"],
|
| 1224 |
+
]
|
| 1225 |
+
)
|
| 1226 |
+
|
| 1227 |
+
# Update settings when changed
|
| 1228 |
+
for trigger in [training_section["custom_tag"], training_section["tag_position"], training_section["all_instrumental"]]:
|
| 1229 |
+
trigger.change(
|
| 1230 |
+
fn=train_h.update_settings,
|
| 1231 |
+
inputs=[
|
| 1232 |
+
training_section["custom_tag"],
|
| 1233 |
+
training_section["tag_position"],
|
| 1234 |
+
training_section["all_instrumental"],
|
| 1235 |
+
training_section["dataset_builder_state"],
|
| 1236 |
+
],
|
| 1237 |
+
outputs=[training_section["dataset_builder_state"]]
|
| 1238 |
+
)
|
| 1239 |
+
|
| 1240 |
+
# Save dataset
|
| 1241 |
+
training_section["save_dataset_btn"].click(
|
| 1242 |
+
fn=train_h.save_dataset,
|
| 1243 |
+
inputs=[
|
| 1244 |
+
training_section["save_path"],
|
| 1245 |
+
training_section["dataset_name"],
|
| 1246 |
+
training_section["dataset_builder_state"],
|
| 1247 |
+
],
|
| 1248 |
+
outputs=[training_section["save_status"]]
|
| 1249 |
+
)
|
| 1250 |
+
|
| 1251 |
+
# ========== Preprocess Handlers ==========
|
| 1252 |
+
|
| 1253 |
+
# Load existing dataset JSON for preprocessing
|
| 1254 |
+
# This also updates the preview section so users can view/edit samples
|
| 1255 |
+
training_section["load_existing_dataset_btn"].click(
|
| 1256 |
+
fn=train_h.load_existing_dataset_for_preprocess,
|
| 1257 |
+
inputs=[
|
| 1258 |
+
training_section["load_existing_dataset_path"],
|
| 1259 |
+
training_section["dataset_builder_state"],
|
| 1260 |
+
],
|
| 1261 |
+
outputs=[
|
| 1262 |
+
training_section["load_existing_status"],
|
| 1263 |
+
training_section["audio_files_table"],
|
| 1264 |
+
training_section["sample_selector"],
|
| 1265 |
+
training_section["dataset_builder_state"],
|
| 1266 |
+
# Also update preview fields with first sample
|
| 1267 |
+
training_section["preview_audio"],
|
| 1268 |
+
training_section["preview_filename"],
|
| 1269 |
+
training_section["edit_caption"],
|
| 1270 |
+
training_section["edit_lyrics"],
|
| 1271 |
+
training_section["edit_bpm"],
|
| 1272 |
+
training_section["edit_keyscale"],
|
| 1273 |
+
training_section["edit_timesig"],
|
| 1274 |
+
training_section["edit_duration"],
|
| 1275 |
+
training_section["edit_language"],
|
| 1276 |
+
training_section["edit_instrumental"],
|
| 1277 |
+
]
|
| 1278 |
+
)
|
| 1279 |
+
|
| 1280 |
+
# Preprocess dataset to tensor files
|
| 1281 |
+
training_section["preprocess_btn"].click(
|
| 1282 |
+
fn=lambda output_dir, state: train_h.preprocess_dataset(
|
| 1283 |
+
output_dir, dit_handler, state
|
| 1284 |
+
),
|
| 1285 |
+
inputs=[
|
| 1286 |
+
training_section["preprocess_output_dir"],
|
| 1287 |
+
training_section["dataset_builder_state"],
|
| 1288 |
+
],
|
| 1289 |
+
outputs=[training_section["preprocess_progress"]]
|
| 1290 |
+
)
|
| 1291 |
+
|
| 1292 |
+
# ========== Training Tab Handlers ==========
|
| 1293 |
+
|
| 1294 |
+
# Load preprocessed tensor dataset
|
| 1295 |
+
training_section["load_dataset_btn"].click(
|
| 1296 |
+
fn=train_h.load_training_dataset,
|
| 1297 |
+
inputs=[training_section["training_tensor_dir"]],
|
| 1298 |
+
outputs=[training_section["training_dataset_info"]]
|
| 1299 |
+
)
|
| 1300 |
+
|
| 1301 |
+
# Start training from preprocessed tensors
|
| 1302 |
+
def training_wrapper(tensor_dir, r, a, d, lr, ep, bs, ga, se, sh, sd, od, ts):
|
| 1303 |
+
try:
|
| 1304 |
+
for progress, log, plot, state in train_h.start_training(
|
| 1305 |
+
tensor_dir, dit_handler, r, a, d, lr, ep, bs, ga, se, sh, sd, od, ts
|
| 1306 |
+
):
|
| 1307 |
+
yield progress, log, plot, state
|
| 1308 |
+
except Exception as e:
|
| 1309 |
+
logger.exception("Training wrapper error")
|
| 1310 |
+
yield f"❌ Error: {str(e)}", str(e), None, ts
|
| 1311 |
+
|
| 1312 |
+
training_section["start_training_btn"].click(
|
| 1313 |
+
fn=training_wrapper,
|
| 1314 |
+
inputs=[
|
| 1315 |
+
training_section["training_tensor_dir"],
|
| 1316 |
+
training_section["lora_rank"],
|
| 1317 |
+
training_section["lora_alpha"],
|
| 1318 |
+
training_section["lora_dropout"],
|
| 1319 |
+
training_section["learning_rate"],
|
| 1320 |
+
training_section["train_epochs"],
|
| 1321 |
+
training_section["train_batch_size"],
|
| 1322 |
+
training_section["gradient_accumulation"],
|
| 1323 |
+
training_section["save_every_n_epochs"],
|
| 1324 |
+
training_section["training_shift"],
|
| 1325 |
+
training_section["training_seed"],
|
| 1326 |
+
training_section["lora_output_dir"],
|
| 1327 |
+
training_section["training_state"],
|
| 1328 |
+
],
|
| 1329 |
+
outputs=[
|
| 1330 |
+
training_section["training_progress"],
|
| 1331 |
+
training_section["training_log"],
|
| 1332 |
+
training_section["training_loss_plot"],
|
| 1333 |
+
training_section["training_state"],
|
| 1334 |
+
]
|
| 1335 |
+
)
|
| 1336 |
+
|
| 1337 |
+
# Stop training
|
| 1338 |
+
training_section["stop_training_btn"].click(
|
| 1339 |
+
fn=train_h.stop_training,
|
| 1340 |
+
inputs=[training_section["training_state"]],
|
| 1341 |
+
outputs=[
|
| 1342 |
+
training_section["training_progress"],
|
| 1343 |
+
training_section["training_state"],
|
| 1344 |
+
]
|
| 1345 |
+
)
|
| 1346 |
+
|
| 1347 |
+
# Export LoRA
|
| 1348 |
+
training_section["export_lora_btn"].click(
|
| 1349 |
+
fn=train_h.export_lora,
|
| 1350 |
+
inputs=[
|
| 1351 |
+
training_section["export_path"],
|
| 1352 |
+
training_section["lora_output_dir"],
|
| 1353 |
+
],
|
| 1354 |
+
outputs=[training_section["export_status"]]
|
| 1355 |
+
)
|
acestep/gradio_ui/events/generation_handlers.py
ADDED
|
@@ -0,0 +1,1071 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Generation Input Handlers Module
|
| 3 |
+
Contains event handlers and helper functions related to generation inputs
|
| 4 |
+
"""
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
import random
|
| 8 |
+
import glob
|
| 9 |
+
import gradio as gr
|
| 10 |
+
from typing import Optional, List, Tuple
|
| 11 |
+
from loguru import logger
|
| 12 |
+
from acestep.constants import (
|
| 13 |
+
TASK_TYPES_TURBO,
|
| 14 |
+
TASK_TYPES_BASE,
|
| 15 |
+
)
|
| 16 |
+
from acestep.gradio_ui.i18n import t
|
| 17 |
+
from acestep.inference import understand_music, create_sample, format_sample
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# HuggingFace Space environment detection for ZeroGPU support
|
| 21 |
+
IS_HUGGINGFACE_SPACE = os.environ.get("SPACE_ID") is not None
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _get_spaces_gpu_decorator(duration=120):
|
| 25 |
+
"""
|
| 26 |
+
Get the @spaces.GPU decorator if running in HuggingFace Space environment.
|
| 27 |
+
Returns identity decorator if not in Space environment.
|
| 28 |
+
"""
|
| 29 |
+
if IS_HUGGINGFACE_SPACE:
|
| 30 |
+
try:
|
| 31 |
+
import spaces
|
| 32 |
+
return spaces.GPU(duration=duration)
|
| 33 |
+
except ImportError:
|
| 34 |
+
logger.warning("spaces package not found, GPU decorator disabled")
|
| 35 |
+
return lambda func: func
|
| 36 |
+
return lambda func: func
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def parse_and_validate_timesteps(
|
| 40 |
+
timesteps_str: str,
|
| 41 |
+
inference_steps: int
|
| 42 |
+
) -> Tuple[Optional[List[float]], bool, str]:
|
| 43 |
+
"""
|
| 44 |
+
Parse timesteps string and validate.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
timesteps_str: Comma-separated timesteps string (e.g., "0.97,0.76,0.615,0.5,0.395,0.28,0.18,0.085,0")
|
| 48 |
+
inference_steps: Expected number of inference steps
|
| 49 |
+
|
| 50 |
+
Returns:
|
| 51 |
+
Tuple of (parsed_timesteps, has_warning, warning_message)
|
| 52 |
+
- parsed_timesteps: List of float timesteps, or None if invalid/empty
|
| 53 |
+
- has_warning: Whether a warning was shown
|
| 54 |
+
- warning_message: Description of the warning
|
| 55 |
+
"""
|
| 56 |
+
if not timesteps_str or not timesteps_str.strip():
|
| 57 |
+
return None, False, ""
|
| 58 |
+
|
| 59 |
+
# Parse comma-separated values
|
| 60 |
+
values = [v.strip() for v in timesteps_str.split(",") if v.strip()]
|
| 61 |
+
|
| 62 |
+
if not values:
|
| 63 |
+
return None, False, ""
|
| 64 |
+
|
| 65 |
+
# Handle optional trailing 0
|
| 66 |
+
if values[-1] != "0":
|
| 67 |
+
values.append("0")
|
| 68 |
+
|
| 69 |
+
try:
|
| 70 |
+
timesteps = [float(v) for v in values]
|
| 71 |
+
except ValueError:
|
| 72 |
+
gr.Warning(t("messages.invalid_timesteps_format"))
|
| 73 |
+
return None, True, "Invalid format"
|
| 74 |
+
|
| 75 |
+
# Validate range [0, 1]
|
| 76 |
+
if any(ts < 0 or ts > 1 for ts in timesteps):
|
| 77 |
+
gr.Warning(t("messages.timesteps_out_of_range"))
|
| 78 |
+
return None, True, "Out of range"
|
| 79 |
+
|
| 80 |
+
# Check if count matches inference_steps
|
| 81 |
+
actual_steps = len(timesteps) - 1
|
| 82 |
+
if actual_steps != inference_steps:
|
| 83 |
+
gr.Warning(t("messages.timesteps_count_mismatch", actual=actual_steps, expected=inference_steps))
|
| 84 |
+
return timesteps, True, f"Using {actual_steps} steps from timesteps"
|
| 85 |
+
|
| 86 |
+
return timesteps, False, ""
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def load_metadata(file_obj):
|
| 90 |
+
"""Load generation parameters from a JSON file"""
|
| 91 |
+
if file_obj is None:
|
| 92 |
+
gr.Warning(t("messages.no_file_selected"))
|
| 93 |
+
return [None] * 36 + [False] # Return None for all fields, False for is_format_caption
|
| 94 |
+
|
| 95 |
+
try:
|
| 96 |
+
# Read the uploaded file
|
| 97 |
+
if hasattr(file_obj, 'name'):
|
| 98 |
+
filepath = file_obj.name
|
| 99 |
+
else:
|
| 100 |
+
filepath = file_obj
|
| 101 |
+
|
| 102 |
+
with open(filepath, 'r', encoding='utf-8') as f:
|
| 103 |
+
metadata = json.load(f)
|
| 104 |
+
|
| 105 |
+
# Extract all fields
|
| 106 |
+
task_type = metadata.get('task_type', 'text2music')
|
| 107 |
+
captions = metadata.get('caption', '')
|
| 108 |
+
lyrics = metadata.get('lyrics', '')
|
| 109 |
+
vocal_language = metadata.get('vocal_language', 'unknown')
|
| 110 |
+
|
| 111 |
+
# Convert bpm
|
| 112 |
+
bpm_value = metadata.get('bpm')
|
| 113 |
+
if bpm_value is not None and bpm_value != "N/A":
|
| 114 |
+
try:
|
| 115 |
+
bpm = int(bpm_value) if bpm_value else None
|
| 116 |
+
except:
|
| 117 |
+
bpm = None
|
| 118 |
+
else:
|
| 119 |
+
bpm = None
|
| 120 |
+
|
| 121 |
+
key_scale = metadata.get('keyscale', '')
|
| 122 |
+
time_signature = metadata.get('timesignature', '')
|
| 123 |
+
|
| 124 |
+
# Convert duration
|
| 125 |
+
duration_value = metadata.get('duration', -1)
|
| 126 |
+
if duration_value is not None and duration_value != "N/A":
|
| 127 |
+
try:
|
| 128 |
+
audio_duration = float(duration_value)
|
| 129 |
+
except:
|
| 130 |
+
audio_duration = -1
|
| 131 |
+
else:
|
| 132 |
+
audio_duration = -1
|
| 133 |
+
|
| 134 |
+
batch_size = metadata.get('batch_size', 2)
|
| 135 |
+
inference_steps = metadata.get('inference_steps', 8)
|
| 136 |
+
guidance_scale = metadata.get('guidance_scale', 7.0)
|
| 137 |
+
seed = metadata.get('seed', '-1')
|
| 138 |
+
random_seed = False # Always set to False when loading to enable reproducibility with saved seed
|
| 139 |
+
use_adg = metadata.get('use_adg', False)
|
| 140 |
+
cfg_interval_start = metadata.get('cfg_interval_start', 0.0)
|
| 141 |
+
cfg_interval_end = metadata.get('cfg_interval_end', 1.0)
|
| 142 |
+
audio_format = metadata.get('audio_format', 'mp3')
|
| 143 |
+
lm_temperature = metadata.get('lm_temperature', 0.85)
|
| 144 |
+
lm_cfg_scale = metadata.get('lm_cfg_scale', 2.0)
|
| 145 |
+
lm_top_k = metadata.get('lm_top_k', 0)
|
| 146 |
+
lm_top_p = metadata.get('lm_top_p', 0.9)
|
| 147 |
+
lm_negative_prompt = metadata.get('lm_negative_prompt', 'NO USER INPUT')
|
| 148 |
+
use_cot_metas = metadata.get('use_cot_metas', True) # Added: read use_cot_metas
|
| 149 |
+
use_cot_caption = metadata.get('use_cot_caption', True)
|
| 150 |
+
use_cot_language = metadata.get('use_cot_language', True)
|
| 151 |
+
audio_cover_strength = metadata.get('audio_cover_strength', 1.0)
|
| 152 |
+
think = metadata.get('thinking', True) # Fixed: read 'thinking' not 'think'
|
| 153 |
+
audio_codes = metadata.get('audio_codes', '')
|
| 154 |
+
repainting_start = metadata.get('repainting_start', 0.0)
|
| 155 |
+
repainting_end = metadata.get('repainting_end', -1)
|
| 156 |
+
track_name = metadata.get('track_name')
|
| 157 |
+
complete_track_classes = metadata.get('complete_track_classes', [])
|
| 158 |
+
shift = metadata.get('shift', 3.0) # Default 3.0 for base models
|
| 159 |
+
infer_method = metadata.get('infer_method', 'ode') # Default 'ode' for diffusion inference
|
| 160 |
+
custom_timesteps = metadata.get('timesteps', '') # Custom timesteps (stored as 'timesteps' in JSON)
|
| 161 |
+
if custom_timesteps is None:
|
| 162 |
+
custom_timesteps = ''
|
| 163 |
+
instrumental = metadata.get('instrumental', False) # Added: read instrumental
|
| 164 |
+
|
| 165 |
+
gr.Info(t("messages.params_loaded", filename=os.path.basename(filepath)))
|
| 166 |
+
|
| 167 |
+
return (
|
| 168 |
+
task_type, captions, lyrics, vocal_language, bpm, key_scale, time_signature,
|
| 169 |
+
audio_duration, batch_size, inference_steps, guidance_scale, seed, random_seed,
|
| 170 |
+
use_adg, cfg_interval_start, cfg_interval_end, shift, infer_method,
|
| 171 |
+
custom_timesteps, # Added: custom_timesteps (between infer_method and audio_format)
|
| 172 |
+
audio_format, lm_temperature, lm_cfg_scale, lm_top_k, lm_top_p, lm_negative_prompt,
|
| 173 |
+
use_cot_metas, use_cot_caption, use_cot_language, audio_cover_strength,
|
| 174 |
+
think, audio_codes, repainting_start, repainting_end,
|
| 175 |
+
track_name, complete_track_classes, instrumental,
|
| 176 |
+
True # Set is_format_caption to True when loading from file
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
except json.JSONDecodeError as e:
|
| 180 |
+
gr.Warning(t("messages.invalid_json", error=str(e)))
|
| 181 |
+
return [None] * 36 + [False]
|
| 182 |
+
except Exception as e:
|
| 183 |
+
gr.Warning(t("messages.load_error", error=str(e)))
|
| 184 |
+
return [None] * 36 + [False]
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def load_random_example(task_type: str):
|
| 188 |
+
"""Load a random example from the task-specific examples directory
|
| 189 |
+
|
| 190 |
+
Args:
|
| 191 |
+
task_type: The task type (e.g., "text2music")
|
| 192 |
+
|
| 193 |
+
Returns:
|
| 194 |
+
Tuple of (caption, lyrics, think, bpm, duration, keyscale, language, timesignature) for updating UI components
|
| 195 |
+
"""
|
| 196 |
+
try:
|
| 197 |
+
# Get the project root directory
|
| 198 |
+
current_file = os.path.abspath(__file__)
|
| 199 |
+
# This file is in acestep/gradio_ui/events/, need 4 levels up to reach project root
|
| 200 |
+
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(current_file))))
|
| 201 |
+
|
| 202 |
+
# Construct the examples directory path
|
| 203 |
+
examples_dir = os.path.join(project_root, "examples", task_type)
|
| 204 |
+
|
| 205 |
+
# Check if directory exists
|
| 206 |
+
if not os.path.exists(examples_dir):
|
| 207 |
+
gr.Warning(f"Examples directory not found: examples/{task_type}/")
|
| 208 |
+
return "", "", True, None, None, "", "", ""
|
| 209 |
+
|
| 210 |
+
# Find all JSON files in the directory
|
| 211 |
+
json_files = glob.glob(os.path.join(examples_dir, "*.json"))
|
| 212 |
+
|
| 213 |
+
if not json_files:
|
| 214 |
+
gr.Warning(f"No JSON files found in examples/{task_type}/")
|
| 215 |
+
return "", "", True, None, None, "", "", ""
|
| 216 |
+
|
| 217 |
+
# Randomly select one file
|
| 218 |
+
selected_file = random.choice(json_files)
|
| 219 |
+
|
| 220 |
+
# Read and parse JSON
|
| 221 |
+
try:
|
| 222 |
+
with open(selected_file, 'r', encoding='utf-8') as f:
|
| 223 |
+
data = json.load(f)
|
| 224 |
+
|
| 225 |
+
# Extract caption (prefer 'caption', fallback to 'prompt')
|
| 226 |
+
caption_value = data.get('caption', data.get('prompt', ''))
|
| 227 |
+
if not isinstance(caption_value, str):
|
| 228 |
+
caption_value = str(caption_value) if caption_value else ''
|
| 229 |
+
|
| 230 |
+
# Extract lyrics
|
| 231 |
+
lyrics_value = data.get('lyrics', '')
|
| 232 |
+
if not isinstance(lyrics_value, str):
|
| 233 |
+
lyrics_value = str(lyrics_value) if lyrics_value else ''
|
| 234 |
+
|
| 235 |
+
# Extract think (default to True if not present)
|
| 236 |
+
think_value = data.get('think', True)
|
| 237 |
+
if not isinstance(think_value, bool):
|
| 238 |
+
think_value = True
|
| 239 |
+
|
| 240 |
+
# Extract optional metadata fields
|
| 241 |
+
bpm_value = None
|
| 242 |
+
if 'bpm' in data and data['bpm'] not in [None, "N/A", ""]:
|
| 243 |
+
try:
|
| 244 |
+
bpm_value = int(data['bpm'])
|
| 245 |
+
except (ValueError, TypeError):
|
| 246 |
+
pass
|
| 247 |
+
|
| 248 |
+
duration_value = None
|
| 249 |
+
if 'duration' in data and data['duration'] not in [None, "N/A", ""]:
|
| 250 |
+
try:
|
| 251 |
+
duration_value = float(data['duration'])
|
| 252 |
+
except (ValueError, TypeError):
|
| 253 |
+
pass
|
| 254 |
+
|
| 255 |
+
keyscale_value = data.get('keyscale', '')
|
| 256 |
+
if keyscale_value in [None, "N/A"]:
|
| 257 |
+
keyscale_value = ''
|
| 258 |
+
|
| 259 |
+
language_value = data.get('language', '')
|
| 260 |
+
if language_value in [None, "N/A"]:
|
| 261 |
+
language_value = ''
|
| 262 |
+
|
| 263 |
+
timesignature_value = data.get('timesignature', '')
|
| 264 |
+
if timesignature_value in [None, "N/A"]:
|
| 265 |
+
timesignature_value = ''
|
| 266 |
+
|
| 267 |
+
gr.Info(t("messages.example_loaded", filename=os.path.basename(selected_file)))
|
| 268 |
+
return caption_value, lyrics_value, think_value, bpm_value, duration_value, keyscale_value, language_value, timesignature_value
|
| 269 |
+
|
| 270 |
+
except json.JSONDecodeError as e:
|
| 271 |
+
gr.Warning(t("messages.example_failed", filename=os.path.basename(selected_file), error=str(e)))
|
| 272 |
+
return "", "", True, None, None, "", "", ""
|
| 273 |
+
except Exception as e:
|
| 274 |
+
gr.Warning(t("messages.example_error", error=str(e)))
|
| 275 |
+
return "", "", True, None, None, "", "", ""
|
| 276 |
+
|
| 277 |
+
except Exception as e:
|
| 278 |
+
gr.Warning(t("messages.example_error", error=str(e)))
|
| 279 |
+
return "", "", True, None, None, "", "", ""
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def sample_example_smart(llm_handler, task_type: str, constrained_decoding_debug: bool = False):
|
| 283 |
+
"""Smart sample function that uses LM if initialized, otherwise falls back to examples
|
| 284 |
+
|
| 285 |
+
This is a Gradio wrapper that uses the understand_music API from acestep.inference
|
| 286 |
+
to generate examples when LM is available.
|
| 287 |
+
|
| 288 |
+
Args:
|
| 289 |
+
llm_handler: LLM handler instance
|
| 290 |
+
task_type: The task type (e.g., "text2music")
|
| 291 |
+
constrained_decoding_debug: Whether to enable debug logging for constrained decoding
|
| 292 |
+
|
| 293 |
+
Returns:
|
| 294 |
+
Tuple of (caption, lyrics, think, bpm, duration, keyscale, language, timesignature) for updating UI components
|
| 295 |
+
"""
|
| 296 |
+
# Check if LM is initialized
|
| 297 |
+
if llm_handler.llm_initialized:
|
| 298 |
+
# Use LM to generate example via understand_music API
|
| 299 |
+
try:
|
| 300 |
+
result = understand_music(
|
| 301 |
+
llm_handler=llm_handler,
|
| 302 |
+
audio_codes="NO USER INPUT", # Empty input triggers example generation
|
| 303 |
+
temperature=0.85,
|
| 304 |
+
use_constrained_decoding=True,
|
| 305 |
+
constrained_decoding_debug=constrained_decoding_debug,
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
if result.success:
|
| 309 |
+
gr.Info(t("messages.lm_generated"))
|
| 310 |
+
return (
|
| 311 |
+
result.caption,
|
| 312 |
+
result.lyrics,
|
| 313 |
+
True, # Always enable think when using LM-generated examples
|
| 314 |
+
result.bpm,
|
| 315 |
+
result.duration,
|
| 316 |
+
result.keyscale,
|
| 317 |
+
result.language,
|
| 318 |
+
result.timesignature,
|
| 319 |
+
)
|
| 320 |
+
else:
|
| 321 |
+
gr.Warning(t("messages.lm_fallback"))
|
| 322 |
+
return load_random_example(task_type)
|
| 323 |
+
|
| 324 |
+
except Exception as e:
|
| 325 |
+
gr.Warning(t("messages.lm_fallback"))
|
| 326 |
+
return load_random_example(task_type)
|
| 327 |
+
else:
|
| 328 |
+
# LM not initialized, use examples directory
|
| 329 |
+
return load_random_example(task_type)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def load_random_simple_description():
|
| 333 |
+
"""Load a random description from the simple_mode examples directory.
|
| 334 |
+
|
| 335 |
+
Returns:
|
| 336 |
+
Tuple of (description, instrumental, vocal_language) for updating UI components
|
| 337 |
+
"""
|
| 338 |
+
try:
|
| 339 |
+
# Get the project root directory
|
| 340 |
+
current_file = os.path.abspath(__file__)
|
| 341 |
+
# This file is in acestep/gradio_ui/events/, need 4 levels up to reach project root
|
| 342 |
+
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(current_file))))
|
| 343 |
+
|
| 344 |
+
# Construct the examples directory path
|
| 345 |
+
examples_dir = os.path.join(project_root, "examples", "simple_mode")
|
| 346 |
+
|
| 347 |
+
# Check if directory exists
|
| 348 |
+
if not os.path.exists(examples_dir):
|
| 349 |
+
gr.Warning(t("messages.simple_examples_not_found"))
|
| 350 |
+
return gr.update(), gr.update(), gr.update()
|
| 351 |
+
|
| 352 |
+
# Find all JSON files in the directory
|
| 353 |
+
json_files = glob.glob(os.path.join(examples_dir, "*.json"))
|
| 354 |
+
|
| 355 |
+
if not json_files:
|
| 356 |
+
gr.Warning(t("messages.simple_examples_empty"))
|
| 357 |
+
return gr.update(), gr.update(), gr.update()
|
| 358 |
+
|
| 359 |
+
# Randomly select one file
|
| 360 |
+
selected_file = random.choice(json_files)
|
| 361 |
+
|
| 362 |
+
# Read and parse JSON
|
| 363 |
+
try:
|
| 364 |
+
with open(selected_file, 'r', encoding='utf-8') as f:
|
| 365 |
+
data = json.load(f)
|
| 366 |
+
|
| 367 |
+
# Extract fields
|
| 368 |
+
description = data.get('description', '')
|
| 369 |
+
instrumental = data.get('instrumental', False)
|
| 370 |
+
vocal_language = data.get('vocal_language', 'unknown')
|
| 371 |
+
|
| 372 |
+
# Ensure vocal_language is a string
|
| 373 |
+
if isinstance(vocal_language, list):
|
| 374 |
+
vocal_language = vocal_language[0] if vocal_language else 'unknown'
|
| 375 |
+
|
| 376 |
+
gr.Info(t("messages.simple_example_loaded", filename=os.path.basename(selected_file)))
|
| 377 |
+
return description, instrumental, vocal_language
|
| 378 |
+
|
| 379 |
+
except json.JSONDecodeError as e:
|
| 380 |
+
gr.Warning(t("messages.example_failed", filename=os.path.basename(selected_file), error=str(e)))
|
| 381 |
+
return gr.update(), gr.update(), gr.update()
|
| 382 |
+
except Exception as e:
|
| 383 |
+
gr.Warning(t("messages.example_error", error=str(e)))
|
| 384 |
+
return gr.update(), gr.update(), gr.update()
|
| 385 |
+
|
| 386 |
+
except Exception as e:
|
| 387 |
+
gr.Warning(t("messages.example_error", error=str(e)))
|
| 388 |
+
return gr.update(), gr.update(), gr.update()
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def refresh_checkpoints(dit_handler):
|
| 392 |
+
"""Refresh available checkpoints"""
|
| 393 |
+
choices = dit_handler.get_available_checkpoints()
|
| 394 |
+
return gr.update(choices=choices)
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def update_model_type_settings(config_path):
|
| 398 |
+
"""Update UI settings based on model type (fallback when handler not initialized yet)
|
| 399 |
+
|
| 400 |
+
Note: This is used as a fallback when the user changes config_path dropdown
|
| 401 |
+
before initializing the model. The actual settings are determined by the
|
| 402 |
+
handler's is_turbo_model() method after initialization.
|
| 403 |
+
"""
|
| 404 |
+
if config_path is None:
|
| 405 |
+
config_path = ""
|
| 406 |
+
config_path_lower = config_path.lower()
|
| 407 |
+
|
| 408 |
+
# Determine is_turbo based on config_path string
|
| 409 |
+
# This is a heuristic fallback - actual model type is determined after loading
|
| 410 |
+
if "turbo" in config_path_lower:
|
| 411 |
+
is_turbo = True
|
| 412 |
+
elif "base" in config_path_lower:
|
| 413 |
+
is_turbo = False
|
| 414 |
+
else:
|
| 415 |
+
# Default to turbo settings for unknown model types
|
| 416 |
+
is_turbo = True
|
| 417 |
+
|
| 418 |
+
return get_model_type_ui_settings(is_turbo)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def init_service_wrapper(dit_handler, llm_handler, checkpoint, config_path, device, init_llm, lm_model_path, backend, use_flash_attention, offload_to_cpu, offload_dit_to_cpu):
|
| 422 |
+
"""Wrapper for service initialization, returns status, button state, accordion state, and model type settings"""
|
| 423 |
+
# Initialize DiT handler
|
| 424 |
+
status, enable = dit_handler.initialize_service(
|
| 425 |
+
checkpoint, config_path, device,
|
| 426 |
+
use_flash_attention=use_flash_attention, compile_model=False,
|
| 427 |
+
offload_to_cpu=offload_to_cpu, offload_dit_to_cpu=offload_dit_to_cpu
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
# Initialize LM handler if requested
|
| 431 |
+
if init_llm:
|
| 432 |
+
# Get checkpoint directory
|
| 433 |
+
current_file = os.path.abspath(__file__)
|
| 434 |
+
# This file is in acestep/gradio_ui/events/, need 4 levels up to reach project root
|
| 435 |
+
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(current_file))))
|
| 436 |
+
checkpoint_dir = os.path.join(project_root, "checkpoints")
|
| 437 |
+
|
| 438 |
+
lm_status, lm_success = llm_handler.initialize(
|
| 439 |
+
checkpoint_dir=checkpoint_dir,
|
| 440 |
+
lm_model_path=lm_model_path,
|
| 441 |
+
backend=backend,
|
| 442 |
+
device=device,
|
| 443 |
+
offload_to_cpu=offload_to_cpu,
|
| 444 |
+
dtype=dit_handler.dtype
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
if lm_success:
|
| 448 |
+
status += f"\n{lm_status}"
|
| 449 |
+
else:
|
| 450 |
+
status += f"\n{lm_status}"
|
| 451 |
+
# Don't fail the entire initialization if LM fails, but log it
|
| 452 |
+
# Keep enable as is (DiT initialization result) even if LM fails
|
| 453 |
+
|
| 454 |
+
# Check if model is initialized - if so, collapse the accordion
|
| 455 |
+
is_model_initialized = dit_handler.model is not None
|
| 456 |
+
accordion_state = gr.Accordion(open=not is_model_initialized)
|
| 457 |
+
|
| 458 |
+
# Get model type settings based on actual loaded model
|
| 459 |
+
is_turbo = dit_handler.is_turbo_model()
|
| 460 |
+
model_type_settings = get_model_type_ui_settings(is_turbo)
|
| 461 |
+
|
| 462 |
+
return (
|
| 463 |
+
status,
|
| 464 |
+
gr.update(interactive=enable),
|
| 465 |
+
accordion_state,
|
| 466 |
+
*model_type_settings
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def get_model_type_ui_settings(is_turbo: bool):
|
| 471 |
+
"""Get UI settings based on whether the model is turbo or base"""
|
| 472 |
+
if is_turbo:
|
| 473 |
+
# Turbo model: max 20 steps, default 8, show shift with default 3.0, only show text2music/repaint/cover
|
| 474 |
+
return (
|
| 475 |
+
gr.update(value=8, maximum=20, minimum=1), # inference_steps
|
| 476 |
+
gr.update(visible=False), # guidance_scale
|
| 477 |
+
gr.update(visible=False), # use_adg
|
| 478 |
+
gr.update(value=3.0, visible=True), # shift (show with default 3.0)
|
| 479 |
+
gr.update(visible=False), # cfg_interval_start
|
| 480 |
+
gr.update(visible=False), # cfg_interval_end
|
| 481 |
+
gr.update(choices=TASK_TYPES_TURBO), # task_type
|
| 482 |
+
)
|
| 483 |
+
else:
|
| 484 |
+
# Base model: max 200 steps, default 32, show CFG/ADG/shift, show all task types
|
| 485 |
+
return (
|
| 486 |
+
gr.update(value=32, maximum=200, minimum=1), # inference_steps
|
| 487 |
+
gr.update(visible=True), # guidance_scale
|
| 488 |
+
gr.update(visible=True), # use_adg
|
| 489 |
+
gr.update(value=3.0, visible=True), # shift (effective for base, default 3.0)
|
| 490 |
+
gr.update(visible=True), # cfg_interval_start
|
| 491 |
+
gr.update(visible=True), # cfg_interval_end
|
| 492 |
+
gr.update(choices=TASK_TYPES_BASE), # task_type
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
def update_negative_prompt_visibility(init_llm_checked):
|
| 497 |
+
"""Update negative prompt visibility: show if Initialize 5Hz LM checkbox is checked"""
|
| 498 |
+
return gr.update(visible=init_llm_checked)
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def update_audio_cover_strength_visibility(task_type_value, init_llm_checked):
|
| 502 |
+
"""Update audio_cover_strength visibility and label"""
|
| 503 |
+
# Show if task is cover OR if LM is initialized (but NOT for repaint mode)
|
| 504 |
+
# Repaint mode never shows this control
|
| 505 |
+
is_repaint = task_type_value == "repaint"
|
| 506 |
+
is_cover = task_type_value == "cover"
|
| 507 |
+
is_visible = is_cover or (init_llm_checked and not is_repaint)
|
| 508 |
+
|
| 509 |
+
# Change label based on context
|
| 510 |
+
if init_llm_checked and not is_cover:
|
| 511 |
+
label = "LM codes strength"
|
| 512 |
+
info = "Control how many denoising steps use LM-generated codes"
|
| 513 |
+
else:
|
| 514 |
+
label = "Audio Cover Strength"
|
| 515 |
+
info = "Control how many denoising steps use cover mode"
|
| 516 |
+
|
| 517 |
+
return gr.update(visible=is_visible, label=label, info=info)
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
def convert_src_audio_to_codes_wrapper(dit_handler, src_audio):
|
| 521 |
+
"""Wrapper for converting src audio to codes"""
|
| 522 |
+
codes_string = dit_handler.convert_src_audio_to_codes(src_audio)
|
| 523 |
+
return codes_string
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def update_instruction_ui(
|
| 527 |
+
dit_handler,
|
| 528 |
+
task_type_value: str,
|
| 529 |
+
track_name_value: Optional[str],
|
| 530 |
+
complete_track_classes_value: list,
|
| 531 |
+
audio_codes_content: str = "",
|
| 532 |
+
init_llm_checked: bool = False
|
| 533 |
+
) -> tuple:
|
| 534 |
+
"""Update instruction and UI visibility based on task type."""
|
| 535 |
+
instruction = dit_handler.generate_instruction(
|
| 536 |
+
task_type=task_type_value,
|
| 537 |
+
track_name=track_name_value,
|
| 538 |
+
complete_track_classes=complete_track_classes_value
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
# Show track_name for lego and extract
|
| 542 |
+
track_name_visible = task_type_value in ["lego", "extract"]
|
| 543 |
+
# Show complete_track_classes for complete
|
| 544 |
+
complete_visible = task_type_value == "complete"
|
| 545 |
+
# Show audio_cover_strength for cover OR when LM is initialized (but NOT for repaint)
|
| 546 |
+
is_repaint = task_type_value == "repaint"
|
| 547 |
+
is_cover = task_type_value == "cover"
|
| 548 |
+
audio_cover_strength_visible = is_cover or (init_llm_checked and not is_repaint)
|
| 549 |
+
# Determine label and info based on context
|
| 550 |
+
if init_llm_checked and not is_cover:
|
| 551 |
+
audio_cover_strength_label = "LM codes strength"
|
| 552 |
+
audio_cover_strength_info = "Control how many denoising steps use LM-generated codes"
|
| 553 |
+
else:
|
| 554 |
+
audio_cover_strength_label = "Audio Cover Strength"
|
| 555 |
+
audio_cover_strength_info = "Control how many denoising steps use cover mode"
|
| 556 |
+
# Show repainting controls for repaint and lego
|
| 557 |
+
repainting_visible = task_type_value in ["repaint", "lego"]
|
| 558 |
+
# Show text2music_audio_codes if task is text2music OR if it has content
|
| 559 |
+
# This allows it to stay visible even if user switches task type but has codes
|
| 560 |
+
has_audio_codes = audio_codes_content and str(audio_codes_content).strip()
|
| 561 |
+
text2music_audio_codes_visible = task_type_value == "text2music" or has_audio_codes
|
| 562 |
+
|
| 563 |
+
return (
|
| 564 |
+
instruction, # instruction_display_gen
|
| 565 |
+
gr.update(visible=track_name_visible), # track_name
|
| 566 |
+
gr.update(visible=complete_visible), # complete_track_classes
|
| 567 |
+
gr.update(visible=audio_cover_strength_visible, label=audio_cover_strength_label, info=audio_cover_strength_info), # audio_cover_strength
|
| 568 |
+
gr.update(visible=repainting_visible), # repainting_group
|
| 569 |
+
gr.update(visible=text2music_audio_codes_visible), # text2music_audio_codes_group
|
| 570 |
+
)
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def transcribe_audio_codes(llm_handler, audio_code_string, constrained_decoding_debug):
|
| 574 |
+
"""
|
| 575 |
+
Transcribe audio codes to metadata using LLM understanding.
|
| 576 |
+
If audio_code_string is empty, generate a sample example instead.
|
| 577 |
+
|
| 578 |
+
This is a Gradio wrapper around the understand_music API in acestep.inference.
|
| 579 |
+
|
| 580 |
+
Args:
|
| 581 |
+
llm_handler: LLM handler instance
|
| 582 |
+
audio_code_string: String containing audio codes (or empty for example generation)
|
| 583 |
+
constrained_decoding_debug: Whether to enable debug logging for constrained decoding
|
| 584 |
+
|
| 585 |
+
Returns:
|
| 586 |
+
Tuple of (status_message, caption, lyrics, bpm, duration, keyscale, language, timesignature, is_format_caption)
|
| 587 |
+
"""
|
| 588 |
+
# Call the inference API
|
| 589 |
+
result = understand_music(
|
| 590 |
+
llm_handler=llm_handler,
|
| 591 |
+
audio_codes=audio_code_string,
|
| 592 |
+
use_constrained_decoding=True,
|
| 593 |
+
constrained_decoding_debug=constrained_decoding_debug,
|
| 594 |
+
)
|
| 595 |
+
|
| 596 |
+
# Handle error case with localized message
|
| 597 |
+
if not result.success:
|
| 598 |
+
# Use localized error message for LLM not initialized
|
| 599 |
+
if result.error == "LLM not initialized":
|
| 600 |
+
return t("messages.lm_not_initialized"), "", "", None, None, "", "", "", False
|
| 601 |
+
return result.status_message, "", "", None, None, "", "", "", False
|
| 602 |
+
|
| 603 |
+
return (
|
| 604 |
+
result.status_message,
|
| 605 |
+
result.caption,
|
| 606 |
+
result.lyrics,
|
| 607 |
+
result.bpm,
|
| 608 |
+
result.duration,
|
| 609 |
+
result.keyscale,
|
| 610 |
+
result.language,
|
| 611 |
+
result.timesignature,
|
| 612 |
+
True # Set is_format_caption to True (from Transcribe/LM understanding)
|
| 613 |
+
)
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def update_transcribe_button_text(audio_code_string):
|
| 617 |
+
"""
|
| 618 |
+
Update the transcribe button text based on input content.
|
| 619 |
+
If empty: "Generate Example"
|
| 620 |
+
If has content: "Transcribe"
|
| 621 |
+
"""
|
| 622 |
+
if not audio_code_string or not audio_code_string.strip():
|
| 623 |
+
return gr.update(value="Generate Example")
|
| 624 |
+
else:
|
| 625 |
+
return gr.update(value="Transcribe")
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
def reset_format_caption_flag():
|
| 629 |
+
"""Reset is_format_caption to False when user manually edits caption/metadata"""
|
| 630 |
+
return False
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
def update_audio_uploads_accordion(reference_audio, src_audio):
|
| 634 |
+
"""Update Audio Uploads visibility based on whether audio files are present"""
|
| 635 |
+
has_audio = (reference_audio is not None) or (src_audio is not None)
|
| 636 |
+
return gr.update(visible=has_audio)
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
def handle_instrumental_checkbox(instrumental_checked, current_lyrics):
|
| 640 |
+
"""
|
| 641 |
+
Handle instrumental checkbox changes.
|
| 642 |
+
When checked: if no lyrics, fill with [Instrumental]
|
| 643 |
+
When unchecked: if lyrics is [Instrumental], clear it
|
| 644 |
+
"""
|
| 645 |
+
if instrumental_checked:
|
| 646 |
+
# If checked and no lyrics, fill with [Instrumental]
|
| 647 |
+
if not current_lyrics or not current_lyrics.strip():
|
| 648 |
+
return "[Instrumental]"
|
| 649 |
+
else:
|
| 650 |
+
# Has lyrics, don't change
|
| 651 |
+
return current_lyrics
|
| 652 |
+
else:
|
| 653 |
+
# If unchecked and lyrics is exactly [Instrumental], clear it
|
| 654 |
+
if current_lyrics and current_lyrics.strip() == "[Instrumental]":
|
| 655 |
+
return ""
|
| 656 |
+
else:
|
| 657 |
+
# Has other lyrics, don't change
|
| 658 |
+
return current_lyrics
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
def handle_simple_instrumental_change(is_instrumental: bool):
|
| 662 |
+
"""
|
| 663 |
+
Handle simple mode instrumental checkbox changes.
|
| 664 |
+
When checked: set vocal_language to "unknown" and disable editing.
|
| 665 |
+
When unchecked: enable vocal_language editing.
|
| 666 |
+
|
| 667 |
+
Args:
|
| 668 |
+
is_instrumental: Whether instrumental checkbox is checked
|
| 669 |
+
|
| 670 |
+
Returns:
|
| 671 |
+
gr.update for simple_vocal_language dropdown
|
| 672 |
+
"""
|
| 673 |
+
if is_instrumental:
|
| 674 |
+
return gr.update(value="unknown", interactive=False)
|
| 675 |
+
else:
|
| 676 |
+
return gr.update(interactive=True)
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
def update_audio_components_visibility(batch_size):
|
| 680 |
+
"""Show/hide individual audio components based on batch size (1-8)
|
| 681 |
+
|
| 682 |
+
Row 1: Components 1-4 (batch_size 1-4)
|
| 683 |
+
Row 2: Components 5-8 (batch_size 5-8)
|
| 684 |
+
"""
|
| 685 |
+
# Clamp batch size to 1-8 range for UI
|
| 686 |
+
batch_size = min(max(int(batch_size), 1), 8)
|
| 687 |
+
|
| 688 |
+
# Row 1 columns (1-4)
|
| 689 |
+
updates_row1 = (
|
| 690 |
+
gr.update(visible=True), # audio_col_1: always visible
|
| 691 |
+
gr.update(visible=batch_size >= 2), # audio_col_2
|
| 692 |
+
gr.update(visible=batch_size >= 3), # audio_col_3
|
| 693 |
+
gr.update(visible=batch_size >= 4), # audio_col_4
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
# Row 2 container and columns (5-8)
|
| 697 |
+
show_row_5_8 = batch_size >= 5
|
| 698 |
+
updates_row2 = (
|
| 699 |
+
gr.update(visible=show_row_5_8), # audio_row_5_8 (container)
|
| 700 |
+
gr.update(visible=batch_size >= 5), # audio_col_5
|
| 701 |
+
gr.update(visible=batch_size >= 6), # audio_col_6
|
| 702 |
+
gr.update(visible=batch_size >= 7), # audio_col_7
|
| 703 |
+
gr.update(visible=batch_size >= 8), # audio_col_8
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
return updates_row1 + updates_row2
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
def handle_generation_mode_change(mode: str):
|
| 710 |
+
"""
|
| 711 |
+
Handle generation mode change between Simple, Custom, Cover, and Repaint modes.
|
| 712 |
+
|
| 713 |
+
Modes:
|
| 714 |
+
- Simple: Show simple mode group, hide others
|
| 715 |
+
- Custom: Show custom content (prompt), hide others
|
| 716 |
+
- Cover: Show src_audio_group + custom content + LM codes strength
|
| 717 |
+
- Repaint: Show src_audio_group + custom content + repaint time controls (hide LM codes strength)
|
| 718 |
+
|
| 719 |
+
Args:
|
| 720 |
+
mode: "simple", "custom", "cover", or "repaint"
|
| 721 |
+
|
| 722 |
+
Returns:
|
| 723 |
+
Tuple of updates for:
|
| 724 |
+
- simple_mode_group (visibility)
|
| 725 |
+
- custom_mode_content (visibility)
|
| 726 |
+
- cover_mode_group (visibility) - legacy, always hidden
|
| 727 |
+
- repainting_group (visibility)
|
| 728 |
+
- task_type (value)
|
| 729 |
+
- generate_btn (interactive state)
|
| 730 |
+
- simple_sample_created (reset state)
|
| 731 |
+
- src_audio_group (visibility) - shown for cover and repaint
|
| 732 |
+
- audio_cover_strength (visibility) - shown only for cover mode
|
| 733 |
+
- think_checkbox (value and interactive) - disabled for cover/repaint modes
|
| 734 |
+
"""
|
| 735 |
+
is_simple = mode == "simple"
|
| 736 |
+
is_custom = mode == "custom"
|
| 737 |
+
is_cover = mode == "cover"
|
| 738 |
+
is_repaint = mode == "repaint"
|
| 739 |
+
|
| 740 |
+
# Map mode to task_type
|
| 741 |
+
task_type_map = {
|
| 742 |
+
"simple": "text2music",
|
| 743 |
+
"custom": "text2music",
|
| 744 |
+
"cover": "cover",
|
| 745 |
+
"repaint": "repaint",
|
| 746 |
+
}
|
| 747 |
+
task_type_value = task_type_map.get(mode, "text2music")
|
| 748 |
+
|
| 749 |
+
# think_checkbox: disabled and set to False for cover/repaint modes
|
| 750 |
+
# (these modes don't use LM thinking, they use source audio codes)
|
| 751 |
+
if is_cover or is_repaint:
|
| 752 |
+
think_checkbox_update = gr.update(value=False, interactive=False)
|
| 753 |
+
else:
|
| 754 |
+
think_checkbox_update = gr.update(value=True, interactive=True)
|
| 755 |
+
|
| 756 |
+
return (
|
| 757 |
+
gr.update(visible=is_simple), # simple_mode_group
|
| 758 |
+
gr.update(visible=not is_simple), # custom_mode_content - visible for custom/cover/repaint
|
| 759 |
+
gr.update(visible=False), # cover_mode_group - legacy, always hidden
|
| 760 |
+
gr.update(visible=is_repaint), # repainting_group - time range controls
|
| 761 |
+
gr.update(value=task_type_value), # task_type
|
| 762 |
+
gr.update(interactive=True), # generate_btn - always enabled (Simple mode does create+generate in one step)
|
| 763 |
+
False, # simple_sample_created - reset to False on mode change
|
| 764 |
+
gr.update(visible=is_cover or is_repaint), # src_audio_group - shown for cover and repaint
|
| 765 |
+
gr.update(visible=is_cover), # audio_cover_strength - only shown for cover mode
|
| 766 |
+
think_checkbox_update, # think_checkbox - disabled for cover/repaint modes
|
| 767 |
+
)
|
| 768 |
+
|
| 769 |
+
def process_source_audio(dit_handler, llm_handler, src_audio, constrained_decoding_debug):
|
| 770 |
+
"""
|
| 771 |
+
Process source audio: convert to codes and then transcribe.
|
| 772 |
+
This combines convert_src_audio_to_codes_wrapper + transcribe_audio_codes.
|
| 773 |
+
|
| 774 |
+
Args:
|
| 775 |
+
dit_handler: DiT handler instance
|
| 776 |
+
llm_handler: LLM handler instance
|
| 777 |
+
src_audio: Path to source audio file
|
| 778 |
+
constrained_decoding_debug: Whether to enable debug logging
|
| 779 |
+
|
| 780 |
+
Returns:
|
| 781 |
+
Tuple of (audio_codes, status_message, caption, lyrics, bpm, duration, keyscale, language, timesignature, is_format_caption)
|
| 782 |
+
"""
|
| 783 |
+
if src_audio is None:
|
| 784 |
+
return ("", "No audio file provided", "", "", None, None, "", "", "", False)
|
| 785 |
+
|
| 786 |
+
# Step 1: Convert audio to codes
|
| 787 |
+
try:
|
| 788 |
+
codes_string = dit_handler.convert_src_audio_to_codes(src_audio)
|
| 789 |
+
if not codes_string:
|
| 790 |
+
return ("", "Failed to convert audio to codes", "", "", None, None, "", "", "", False)
|
| 791 |
+
except Exception as e:
|
| 792 |
+
return ("", f"Error converting audio: {str(e)}", "", "", None, None, "", "", "", False)
|
| 793 |
+
|
| 794 |
+
# Step 2: Transcribe the codes
|
| 795 |
+
result = understand_music(
|
| 796 |
+
llm_handler=llm_handler,
|
| 797 |
+
audio_codes=codes_string,
|
| 798 |
+
use_constrained_decoding=True,
|
| 799 |
+
constrained_decoding_debug=constrained_decoding_debug,
|
| 800 |
+
)
|
| 801 |
+
|
| 802 |
+
# Handle error case
|
| 803 |
+
if not result.success:
|
| 804 |
+
if result.error == "LLM not initialized":
|
| 805 |
+
return (codes_string, t("messages.lm_not_initialized"), "", "", None, None, "", "", "", False)
|
| 806 |
+
return (codes_string, result.status_message, "", "", None, None, "", "", "", False)
|
| 807 |
+
|
| 808 |
+
return (
|
| 809 |
+
codes_string,
|
| 810 |
+
result.status_message,
|
| 811 |
+
result.caption,
|
| 812 |
+
result.lyrics,
|
| 813 |
+
result.bpm,
|
| 814 |
+
result.duration,
|
| 815 |
+
result.keyscale,
|
| 816 |
+
result.language,
|
| 817 |
+
result.timesignature,
|
| 818 |
+
True # Set is_format_caption to True
|
| 819 |
+
)
|
| 820 |
+
|
| 821 |
+
def handle_create_sample(
|
| 822 |
+
llm_handler,
|
| 823 |
+
query: str,
|
| 824 |
+
instrumental: bool,
|
| 825 |
+
vocal_language: str,
|
| 826 |
+
lm_temperature: float,
|
| 827 |
+
lm_top_k: int,
|
| 828 |
+
lm_top_p: float,
|
| 829 |
+
constrained_decoding_debug: bool = False,
|
| 830 |
+
):
|
| 831 |
+
"""
|
| 832 |
+
Handle the Create Sample button click in Simple mode.
|
| 833 |
+
|
| 834 |
+
Creates a sample from the user's query using the LLM, then populates
|
| 835 |
+
the caption, lyrics, and metadata fields.
|
| 836 |
+
|
| 837 |
+
Note: cfg_scale and negative_prompt are not supported in create_sample mode.
|
| 838 |
+
|
| 839 |
+
Args:
|
| 840 |
+
llm_handler: LLM handler instance (unused, fetched from registry)
|
| 841 |
+
query: User's natural language music description
|
| 842 |
+
instrumental: Whether to generate instrumental music
|
| 843 |
+
vocal_language: Preferred vocal language for constrained decoding
|
| 844 |
+
lm_temperature: LLM temperature for generation
|
| 845 |
+
lm_top_k: LLM top-k sampling
|
| 846 |
+
lm_top_p: LLM top-p sampling
|
| 847 |
+
constrained_decoding_debug: Whether to enable debug logging
|
| 848 |
+
|
| 849 |
+
Returns:
|
| 850 |
+
Tuple of updates for:
|
| 851 |
+
- captions
|
| 852 |
+
- lyrics
|
| 853 |
+
- bpm
|
| 854 |
+
- audio_duration
|
| 855 |
+
- key_scale
|
| 856 |
+
- vocal_language
|
| 857 |
+
- time_signature
|
| 858 |
+
- instrumental_checkbox
|
| 859 |
+
- caption_accordion (open)
|
| 860 |
+
- lyrics_accordion (open)
|
| 861 |
+
- generate_btn (interactive)
|
| 862 |
+
- simple_sample_created (True)
|
| 863 |
+
- think_checkbox (True)
|
| 864 |
+
- is_format_caption_state (True)
|
| 865 |
+
- status_output
|
| 866 |
+
"""
|
| 867 |
+
# Check if LLM is initialized
|
| 868 |
+
if not llm_handler.llm_initialized:
|
| 869 |
+
gr.Warning(t("messages.lm_not_initialized"))
|
| 870 |
+
return (
|
| 871 |
+
gr.update(), # captions - no change
|
| 872 |
+
gr.update(), # lyrics - no change
|
| 873 |
+
gr.update(), # bpm - no change
|
| 874 |
+
gr.update(), # audio_duration - no change
|
| 875 |
+
gr.update(), # key_scale - no change
|
| 876 |
+
gr.update(), # vocal_language - no change
|
| 877 |
+
gr.update(), # time_signature - no change
|
| 878 |
+
gr.update(), # instrumental_checkbox - no change
|
| 879 |
+
gr.update(), # caption_accordion - no change
|
| 880 |
+
gr.update(), # lyrics_accordion - no change
|
| 881 |
+
gr.update(interactive=False), # generate_btn - keep disabled
|
| 882 |
+
False, # simple_sample_created - still False
|
| 883 |
+
gr.update(), # think_checkbox - no change
|
| 884 |
+
gr.update(), # is_format_caption_state - no change
|
| 885 |
+
t("messages.lm_not_initialized"), # status_output
|
| 886 |
+
)
|
| 887 |
+
|
| 888 |
+
# Convert LM parameters
|
| 889 |
+
top_k_value = None if not lm_top_k or lm_top_k == 0 else int(lm_top_k)
|
| 890 |
+
top_p_value = None if not lm_top_p or lm_top_p >= 1.0 else lm_top_p
|
| 891 |
+
|
| 892 |
+
# Call create_sample API
|
| 893 |
+
# Note: cfg_scale and negative_prompt are not supported in create_sample mode
|
| 894 |
+
result = create_sample(
|
| 895 |
+
llm_handler=llm_handler,
|
| 896 |
+
query=query,
|
| 897 |
+
instrumental=instrumental,
|
| 898 |
+
vocal_language=vocal_language,
|
| 899 |
+
temperature=lm_temperature,
|
| 900 |
+
top_k=top_k_value,
|
| 901 |
+
top_p=top_p_value,
|
| 902 |
+
use_constrained_decoding=True,
|
| 903 |
+
constrained_decoding_debug=constrained_decoding_debug,
|
| 904 |
+
)
|
| 905 |
+
|
| 906 |
+
# Handle error
|
| 907 |
+
if not result.success:
|
| 908 |
+
gr.Warning(result.status_message or t("messages.sample_creation_failed"))
|
| 909 |
+
return (
|
| 910 |
+
gr.update(), # captions - no change
|
| 911 |
+
gr.update(), # lyrics - no change
|
| 912 |
+
gr.update(), # bpm - no change
|
| 913 |
+
gr.update(), # audio_duration - no change
|
| 914 |
+
gr.update(), # key_scale - no change
|
| 915 |
+
gr.update(), # vocal_language - no change
|
| 916 |
+
gr.update(), # simple vocal_language - no change
|
| 917 |
+
gr.update(), # time_signature - no change
|
| 918 |
+
gr.update(), # instrumental_checkbox - no change
|
| 919 |
+
gr.update(), # caption_accordion - no change
|
| 920 |
+
gr.update(), # lyrics_accordion - no change
|
| 921 |
+
gr.update(interactive=False), # generate_btn - keep disabled
|
| 922 |
+
False, # simple_sample_created - still False
|
| 923 |
+
gr.update(), # think_checkbox - no change
|
| 924 |
+
gr.update(), # is_format_caption_state - no change
|
| 925 |
+
result.status_message or t("messages.sample_creation_failed"), # status_output
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
# Success - populate fields
|
| 929 |
+
gr.Info(t("messages.sample_created"))
|
| 930 |
+
|
| 931 |
+
return (
|
| 932 |
+
result.caption, # captions
|
| 933 |
+
result.lyrics, # lyrics
|
| 934 |
+
result.bpm, # bpm
|
| 935 |
+
result.duration if result.duration and result.duration > 0 else -1, # audio_duration
|
| 936 |
+
result.keyscale, # key_scale
|
| 937 |
+
result.language, # vocal_language
|
| 938 |
+
result.language, # simple vocal_language
|
| 939 |
+
result.timesignature, # time_signature
|
| 940 |
+
result.instrumental, # instrumental_checkbox
|
| 941 |
+
gr.Accordion(open=True), # caption_accordion - expand
|
| 942 |
+
gr.Accordion(open=True), # lyrics_accordion - expand
|
| 943 |
+
gr.update(interactive=True), # generate_btn - enable
|
| 944 |
+
True, # simple_sample_created - True
|
| 945 |
+
True, # think_checkbox - enable thinking
|
| 946 |
+
True, # is_format_caption_state - True (LM-generated)
|
| 947 |
+
result.status_message, # status_output
|
| 948 |
+
)
|
| 949 |
+
|
| 950 |
+
def handle_format_sample(
|
| 951 |
+
llm_handler,
|
| 952 |
+
caption: str,
|
| 953 |
+
lyrics: str,
|
| 954 |
+
bpm,
|
| 955 |
+
audio_duration,
|
| 956 |
+
key_scale: str,
|
| 957 |
+
time_signature: str,
|
| 958 |
+
lm_temperature: float,
|
| 959 |
+
lm_top_k: int,
|
| 960 |
+
lm_top_p: float,
|
| 961 |
+
constrained_decoding_debug: bool = False,
|
| 962 |
+
):
|
| 963 |
+
"""
|
| 964 |
+
Handle the Format button click to format caption and lyrics.
|
| 965 |
+
|
| 966 |
+
Takes user-provided caption and lyrics, and uses the LLM to generate
|
| 967 |
+
structured music metadata and an enhanced description.
|
| 968 |
+
|
| 969 |
+
Note: cfg_scale and negative_prompt are not supported in format mode.
|
| 970 |
+
|
| 971 |
+
Args:
|
| 972 |
+
llm_handler: LLM handler instance (unused, fetched from registry)
|
| 973 |
+
caption: User's caption/description
|
| 974 |
+
lyrics: User's lyrics
|
| 975 |
+
bpm: User-provided BPM (optional, for constrained decoding)
|
| 976 |
+
audio_duration: User-provided duration (optional, for constrained decoding)
|
| 977 |
+
key_scale: User-provided key scale (optional, for constrained decoding)
|
| 978 |
+
time_signature: User-provided time signature (optional, for constrained decoding)
|
| 979 |
+
lm_temperature: LLM temperature for generation
|
| 980 |
+
lm_top_k: LLM top-k sampling
|
| 981 |
+
lm_top_p: LLM top-p sampling
|
| 982 |
+
constrained_decoding_debug: Whether to enable debug logging
|
| 983 |
+
|
| 984 |
+
Returns:
|
| 985 |
+
Tuple of updates for:
|
| 986 |
+
- captions
|
| 987 |
+
- lyrics
|
| 988 |
+
- bpm
|
| 989 |
+
- audio_duration
|
| 990 |
+
- key_scale
|
| 991 |
+
- vocal_language
|
| 992 |
+
- time_signature
|
| 993 |
+
- is_format_caption_state
|
| 994 |
+
- status_output
|
| 995 |
+
"""
|
| 996 |
+
# Check if LLM is initialized
|
| 997 |
+
if not llm_handler.llm_initialized:
|
| 998 |
+
gr.Warning(t("messages.lm_not_initialized"))
|
| 999 |
+
return (
|
| 1000 |
+
gr.update(), # captions - no change
|
| 1001 |
+
gr.update(), # lyrics - no change
|
| 1002 |
+
gr.update(), # bpm - no change
|
| 1003 |
+
gr.update(), # audio_duration - no change
|
| 1004 |
+
gr.update(), # key_scale - no change
|
| 1005 |
+
gr.update(), # vocal_language - no change
|
| 1006 |
+
gr.update(), # time_signature - no change
|
| 1007 |
+
gr.update(), # is_format_caption_state - no change
|
| 1008 |
+
t("messages.lm_not_initialized"), # status_output
|
| 1009 |
+
)
|
| 1010 |
+
|
| 1011 |
+
# Build user_metadata from provided values for constrained decoding
|
| 1012 |
+
user_metadata = {}
|
| 1013 |
+
if bpm is not None and bpm > 0:
|
| 1014 |
+
user_metadata['bpm'] = int(bpm)
|
| 1015 |
+
if audio_duration is not None and audio_duration > 0:
|
| 1016 |
+
user_metadata['duration'] = int(audio_duration)
|
| 1017 |
+
if key_scale and key_scale.strip():
|
| 1018 |
+
user_metadata['keyscale'] = key_scale.strip()
|
| 1019 |
+
if time_signature and time_signature.strip():
|
| 1020 |
+
user_metadata['timesignature'] = time_signature.strip()
|
| 1021 |
+
|
| 1022 |
+
# Only pass user_metadata if we have at least one field
|
| 1023 |
+
user_metadata_to_pass = user_metadata if user_metadata else None
|
| 1024 |
+
|
| 1025 |
+
# Convert LM parameters
|
| 1026 |
+
top_k_value = None if not lm_top_k or lm_top_k == 0 else int(lm_top_k)
|
| 1027 |
+
top_p_value = None if not lm_top_p or lm_top_p >= 1.0 else lm_top_p
|
| 1028 |
+
|
| 1029 |
+
# Call format_sample API
|
| 1030 |
+
result = format_sample(
|
| 1031 |
+
llm_handler=llm_handler,
|
| 1032 |
+
caption=caption,
|
| 1033 |
+
lyrics=lyrics,
|
| 1034 |
+
user_metadata=user_metadata_to_pass,
|
| 1035 |
+
temperature=lm_temperature,
|
| 1036 |
+
top_k=top_k_value,
|
| 1037 |
+
top_p=top_p_value,
|
| 1038 |
+
use_constrained_decoding=True,
|
| 1039 |
+
constrained_decoding_debug=constrained_decoding_debug,
|
| 1040 |
+
)
|
| 1041 |
+
|
| 1042 |
+
# Handle error
|
| 1043 |
+
if not result.success:
|
| 1044 |
+
gr.Warning(result.status_message or t("messages.format_failed"))
|
| 1045 |
+
return (
|
| 1046 |
+
gr.update(), # captions - no change
|
| 1047 |
+
gr.update(), # lyrics - no change
|
| 1048 |
+
gr.update(), # bpm - no change
|
| 1049 |
+
gr.update(), # audio_duration - no change
|
| 1050 |
+
gr.update(), # key_scale - no change
|
| 1051 |
+
gr.update(), # vocal_language - no change
|
| 1052 |
+
gr.update(), # time_signature - no change
|
| 1053 |
+
gr.update(), # is_format_caption_state - no change
|
| 1054 |
+
result.status_message or t("messages.format_failed"), # status_output
|
| 1055 |
+
)
|
| 1056 |
+
|
| 1057 |
+
# Success - populate fields
|
| 1058 |
+
gr.Info(t("messages.format_success"))
|
| 1059 |
+
|
| 1060 |
+
return (
|
| 1061 |
+
result.caption, # captions
|
| 1062 |
+
result.lyrics, # lyrics
|
| 1063 |
+
result.bpm, # bpm
|
| 1064 |
+
result.duration if result.duration and result.duration > 0 else -1, # audio_duration
|
| 1065 |
+
result.keyscale, # key_scale
|
| 1066 |
+
result.language, # vocal_language
|
| 1067 |
+
result.timesignature, # time_signature
|
| 1068 |
+
True, # is_format_caption_state - True (LM-formatted)
|
| 1069 |
+
result.status_message, # status_output
|
| 1070 |
+
)
|
| 1071 |
+
|
acestep/gradio_ui/events/results_handlers.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
acestep/gradio_ui/events/training_handlers.py
ADDED
|
@@ -0,0 +1,644 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Event Handlers for Training Tab
|
| 3 |
+
|
| 4 |
+
Contains all event handler functions for the dataset builder and training UI.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import json
|
| 9 |
+
from typing import Any, Dict, List, Tuple, Optional
|
| 10 |
+
from loguru import logger
|
| 11 |
+
import gradio as gr
|
| 12 |
+
|
| 13 |
+
from acestep.training.dataset_builder import DatasetBuilder, AudioSample
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def create_dataset_builder() -> DatasetBuilder:
|
| 17 |
+
"""Create a new DatasetBuilder instance."""
|
| 18 |
+
return DatasetBuilder()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def scan_directory(
|
| 22 |
+
audio_dir: str,
|
| 23 |
+
dataset_name: str,
|
| 24 |
+
custom_tag: str,
|
| 25 |
+
tag_position: str,
|
| 26 |
+
all_instrumental: bool,
|
| 27 |
+
builder_state: Optional[DatasetBuilder],
|
| 28 |
+
) -> Tuple[Any, str, Any, DatasetBuilder]:
|
| 29 |
+
"""Scan a directory for audio files.
|
| 30 |
+
|
| 31 |
+
Returns:
|
| 32 |
+
Tuple of (table_data, status, slider_update, builder_state)
|
| 33 |
+
"""
|
| 34 |
+
if not audio_dir or not audio_dir.strip():
|
| 35 |
+
return [], "❌ Please enter a directory path", gr.Slider(maximum=0, value=0), builder_state
|
| 36 |
+
|
| 37 |
+
# Create or use existing builder
|
| 38 |
+
builder = builder_state if builder_state else DatasetBuilder()
|
| 39 |
+
|
| 40 |
+
# Set metadata before scanning
|
| 41 |
+
builder.metadata.name = dataset_name
|
| 42 |
+
builder.metadata.custom_tag = custom_tag
|
| 43 |
+
builder.metadata.tag_position = tag_position
|
| 44 |
+
builder.metadata.all_instrumental = all_instrumental
|
| 45 |
+
|
| 46 |
+
# Scan directory
|
| 47 |
+
samples, status = builder.scan_directory(audio_dir.strip())
|
| 48 |
+
|
| 49 |
+
if not samples:
|
| 50 |
+
return [], status, gr.Slider(maximum=0, value=0), builder
|
| 51 |
+
|
| 52 |
+
# Set instrumental and tag for all samples
|
| 53 |
+
builder.set_all_instrumental(all_instrumental)
|
| 54 |
+
if custom_tag:
|
| 55 |
+
builder.set_custom_tag(custom_tag, tag_position)
|
| 56 |
+
|
| 57 |
+
# Get table data
|
| 58 |
+
table_data = builder.get_samples_dataframe_data()
|
| 59 |
+
|
| 60 |
+
# Calculate slider max and return as Slider update
|
| 61 |
+
slider_max = max(0, len(samples) - 1)
|
| 62 |
+
|
| 63 |
+
return table_data, status, gr.Slider(maximum=slider_max, value=0), builder
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def auto_label_all(
|
| 67 |
+
dit_handler,
|
| 68 |
+
llm_handler,
|
| 69 |
+
builder_state: Optional[DatasetBuilder],
|
| 70 |
+
skip_metas: bool = False,
|
| 71 |
+
progress=None,
|
| 72 |
+
) -> Tuple[List[List[Any]], str, DatasetBuilder]:
|
| 73 |
+
"""Auto-label all samples in the dataset.
|
| 74 |
+
|
| 75 |
+
Args:
|
| 76 |
+
dit_handler: DiT handler for audio processing
|
| 77 |
+
llm_handler: LLM handler for caption generation
|
| 78 |
+
builder_state: Dataset builder state
|
| 79 |
+
skip_metas: If True, skip LLM labeling. BPM/Key/TimeSig = N/A, Language = unknown for instrumental
|
| 80 |
+
progress: Progress callback
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
Tuple of (table_data, status, builder_state)
|
| 84 |
+
"""
|
| 85 |
+
if builder_state is None:
|
| 86 |
+
return [], "❌ Please scan a directory first", builder_state
|
| 87 |
+
|
| 88 |
+
if not builder_state.samples:
|
| 89 |
+
return [], "❌ No samples to label. Please scan a directory first.", builder_state
|
| 90 |
+
|
| 91 |
+
# If skip_metas is True, just set default values without LLM
|
| 92 |
+
if skip_metas:
|
| 93 |
+
for sample in builder_state.samples:
|
| 94 |
+
sample.bpm = None # Will display as N/A
|
| 95 |
+
sample.keyscale = "N/A"
|
| 96 |
+
sample.timesignature = "N/A"
|
| 97 |
+
# For instrumental, language should be "unknown"
|
| 98 |
+
if sample.is_instrumental:
|
| 99 |
+
sample.language = "unknown"
|
| 100 |
+
else:
|
| 101 |
+
sample.language = "unknown"
|
| 102 |
+
# Use custom tag as caption if set, otherwise use filename
|
| 103 |
+
if builder_state.metadata.custom_tag:
|
| 104 |
+
sample.caption = builder_state.metadata.custom_tag
|
| 105 |
+
else:
|
| 106 |
+
sample.caption = sample.filename
|
| 107 |
+
|
| 108 |
+
table_data = builder_state.get_samples_dataframe_data()
|
| 109 |
+
return table_data, f"✅ Skipped AI labeling. {len(builder_state.samples)} samples set with default values.", builder_state
|
| 110 |
+
|
| 111 |
+
# Check if handlers are initialized
|
| 112 |
+
if dit_handler is None or dit_handler.model is None:
|
| 113 |
+
return builder_state.get_samples_dataframe_data(), "❌ Model not initialized. Please initialize the service first.", builder_state
|
| 114 |
+
|
| 115 |
+
if llm_handler is None or not llm_handler.llm_initialized:
|
| 116 |
+
return builder_state.get_samples_dataframe_data(), "❌ LLM not initialized. Please initialize the service with LLM enabled.", builder_state
|
| 117 |
+
|
| 118 |
+
def progress_callback(msg):
|
| 119 |
+
if progress:
|
| 120 |
+
try:
|
| 121 |
+
progress(msg)
|
| 122 |
+
except:
|
| 123 |
+
pass
|
| 124 |
+
|
| 125 |
+
# Label all samples
|
| 126 |
+
samples, status = builder_state.label_all_samples(
|
| 127 |
+
dit_handler=dit_handler,
|
| 128 |
+
llm_handler=llm_handler,
|
| 129 |
+
progress_callback=progress_callback,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
# Get updated table data
|
| 133 |
+
table_data = builder_state.get_samples_dataframe_data()
|
| 134 |
+
|
| 135 |
+
return table_data, status, builder_state
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def get_sample_preview(
|
| 139 |
+
sample_idx: int,
|
| 140 |
+
builder_state: Optional[DatasetBuilder],
|
| 141 |
+
) -> Tuple[str, str, str, str, Optional[int], str, str, float, str, bool]:
|
| 142 |
+
"""Get preview data for a specific sample.
|
| 143 |
+
|
| 144 |
+
Returns:
|
| 145 |
+
Tuple of (audio_path, filename, caption, lyrics, bpm, keyscale, timesig, duration, language, instrumental)
|
| 146 |
+
"""
|
| 147 |
+
if builder_state is None or not builder_state.samples:
|
| 148 |
+
return None, "", "", "", None, "", "", 0.0, "instrumental", True
|
| 149 |
+
|
| 150 |
+
idx = int(sample_idx)
|
| 151 |
+
if idx < 0 or idx >= len(builder_state.samples):
|
| 152 |
+
return None, "", "", "", None, "", "", 0.0, "instrumental", True
|
| 153 |
+
|
| 154 |
+
sample = builder_state.samples[idx]
|
| 155 |
+
|
| 156 |
+
return (
|
| 157 |
+
sample.audio_path,
|
| 158 |
+
sample.filename,
|
| 159 |
+
sample.caption,
|
| 160 |
+
sample.lyrics,
|
| 161 |
+
sample.bpm,
|
| 162 |
+
sample.keyscale,
|
| 163 |
+
sample.timesignature,
|
| 164 |
+
sample.duration,
|
| 165 |
+
sample.language,
|
| 166 |
+
sample.is_instrumental,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def save_sample_edit(
|
| 171 |
+
sample_idx: int,
|
| 172 |
+
caption: str,
|
| 173 |
+
lyrics: str,
|
| 174 |
+
bpm: Optional[int],
|
| 175 |
+
keyscale: str,
|
| 176 |
+
timesig: str,
|
| 177 |
+
language: str,
|
| 178 |
+
is_instrumental: bool,
|
| 179 |
+
builder_state: Optional[DatasetBuilder],
|
| 180 |
+
) -> Tuple[List[List[Any]], str, DatasetBuilder]:
|
| 181 |
+
"""Save edits to a sample.
|
| 182 |
+
|
| 183 |
+
Returns:
|
| 184 |
+
Tuple of (table_data, status, builder_state)
|
| 185 |
+
"""
|
| 186 |
+
if builder_state is None:
|
| 187 |
+
return [], "❌ No dataset loaded", builder_state
|
| 188 |
+
|
| 189 |
+
idx = int(sample_idx)
|
| 190 |
+
|
| 191 |
+
# Update sample
|
| 192 |
+
sample, status = builder_state.update_sample(
|
| 193 |
+
idx,
|
| 194 |
+
caption=caption,
|
| 195 |
+
lyrics=lyrics if not is_instrumental else "[Instrumental]",
|
| 196 |
+
bpm=int(bpm) if bpm else None,
|
| 197 |
+
keyscale=keyscale,
|
| 198 |
+
timesignature=timesig,
|
| 199 |
+
language="instrumental" if is_instrumental else language,
|
| 200 |
+
is_instrumental=is_instrumental,
|
| 201 |
+
labeled=True,
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
# Get updated table data
|
| 205 |
+
table_data = builder_state.get_samples_dataframe_data()
|
| 206 |
+
|
| 207 |
+
return table_data, status, builder_state
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def update_settings(
|
| 211 |
+
custom_tag: str,
|
| 212 |
+
tag_position: str,
|
| 213 |
+
all_instrumental: bool,
|
| 214 |
+
builder_state: Optional[DatasetBuilder],
|
| 215 |
+
) -> DatasetBuilder:
|
| 216 |
+
"""Update dataset settings.
|
| 217 |
+
|
| 218 |
+
Returns:
|
| 219 |
+
Updated builder_state
|
| 220 |
+
"""
|
| 221 |
+
if builder_state is None:
|
| 222 |
+
return builder_state
|
| 223 |
+
|
| 224 |
+
if custom_tag:
|
| 225 |
+
builder_state.set_custom_tag(custom_tag, tag_position)
|
| 226 |
+
|
| 227 |
+
builder_state.set_all_instrumental(all_instrumental)
|
| 228 |
+
|
| 229 |
+
return builder_state
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def save_dataset(
|
| 233 |
+
save_path: str,
|
| 234 |
+
dataset_name: str,
|
| 235 |
+
builder_state: Optional[DatasetBuilder],
|
| 236 |
+
) -> str:
|
| 237 |
+
"""Save the dataset to a JSON file.
|
| 238 |
+
|
| 239 |
+
Returns:
|
| 240 |
+
Status message
|
| 241 |
+
"""
|
| 242 |
+
if builder_state is None:
|
| 243 |
+
return "❌ No dataset to save. Please scan a directory first."
|
| 244 |
+
|
| 245 |
+
if not builder_state.samples:
|
| 246 |
+
return "❌ No samples in dataset."
|
| 247 |
+
|
| 248 |
+
if not save_path or not save_path.strip():
|
| 249 |
+
return "❌ Please enter a save path."
|
| 250 |
+
|
| 251 |
+
# Check if any samples are labeled
|
| 252 |
+
labeled_count = builder_state.get_labeled_count()
|
| 253 |
+
if labeled_count == 0:
|
| 254 |
+
return "⚠️ Warning: No samples have been labeled. Consider auto-labeling first.\nSaving anyway..."
|
| 255 |
+
|
| 256 |
+
return builder_state.save_dataset(save_path.strip(), dataset_name)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def load_existing_dataset_for_preprocess(
|
| 260 |
+
dataset_path: str,
|
| 261 |
+
builder_state: Optional[DatasetBuilder],
|
| 262 |
+
) -> Tuple[str, Any, Any, DatasetBuilder, str, str, str, str, Optional[int], str, str, float, str, bool]:
|
| 263 |
+
"""Load an existing dataset JSON file for preprocessing.
|
| 264 |
+
|
| 265 |
+
This allows users to load a previously saved dataset and proceed to preprocessing
|
| 266 |
+
without having to re-scan and re-label.
|
| 267 |
+
|
| 268 |
+
Returns:
|
| 269 |
+
Tuple of (status, table_data, slider_update, builder_state,
|
| 270 |
+
audio_path, filename, caption, lyrics, bpm, keyscale, timesig, duration, language, instrumental)
|
| 271 |
+
"""
|
| 272 |
+
empty_preview = (None, "", "", "", None, "", "", 0.0, "instrumental", True)
|
| 273 |
+
|
| 274 |
+
if not dataset_path or not dataset_path.strip():
|
| 275 |
+
return ("❌ Please enter a dataset path", [], gr.Slider(maximum=0, value=0), builder_state) + empty_preview
|
| 276 |
+
|
| 277 |
+
dataset_path = dataset_path.strip()
|
| 278 |
+
|
| 279 |
+
if not os.path.exists(dataset_path):
|
| 280 |
+
return (f"❌ Dataset not found: {dataset_path}", [], gr.Slider(maximum=0, value=0), builder_state) + empty_preview
|
| 281 |
+
|
| 282 |
+
# Create new builder (don't reuse old state when loading a file)
|
| 283 |
+
builder = DatasetBuilder()
|
| 284 |
+
|
| 285 |
+
# Load the dataset
|
| 286 |
+
samples, status = builder.load_dataset(dataset_path)
|
| 287 |
+
|
| 288 |
+
if not samples:
|
| 289 |
+
return (status, [], gr.Slider(maximum=0, value=0), builder) + empty_preview
|
| 290 |
+
|
| 291 |
+
# Get table data
|
| 292 |
+
table_data = builder.get_samples_dataframe_data()
|
| 293 |
+
|
| 294 |
+
# Calculate slider max
|
| 295 |
+
slider_max = max(0, len(samples) - 1)
|
| 296 |
+
|
| 297 |
+
# Create info text
|
| 298 |
+
labeled_count = builder.get_labeled_count()
|
| 299 |
+
info = f"✅ Loaded dataset: {builder.metadata.name}\n"
|
| 300 |
+
info += f"📊 Samples: {len(samples)} ({labeled_count} labeled)\n"
|
| 301 |
+
info += f"🏷️ Custom Tag: {builder.metadata.custom_tag or '(none)'}\n"
|
| 302 |
+
info += "📝 Ready for preprocessing! You can also edit samples below."
|
| 303 |
+
|
| 304 |
+
# Get first sample preview
|
| 305 |
+
first_sample = builder.samples[0]
|
| 306 |
+
preview = (
|
| 307 |
+
first_sample.audio_path,
|
| 308 |
+
first_sample.filename,
|
| 309 |
+
first_sample.caption,
|
| 310 |
+
first_sample.lyrics,
|
| 311 |
+
first_sample.bpm,
|
| 312 |
+
first_sample.keyscale,
|
| 313 |
+
first_sample.timesignature,
|
| 314 |
+
first_sample.duration,
|
| 315 |
+
first_sample.language,
|
| 316 |
+
first_sample.is_instrumental,
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
return (info, table_data, gr.Slider(maximum=slider_max, value=0), builder) + preview
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def preprocess_dataset(
|
| 323 |
+
output_dir: str,
|
| 324 |
+
dit_handler,
|
| 325 |
+
builder_state: Optional[DatasetBuilder],
|
| 326 |
+
progress=None,
|
| 327 |
+
) -> str:
|
| 328 |
+
"""Preprocess dataset to tensor files for fast training.
|
| 329 |
+
|
| 330 |
+
This converts audio files to VAE latents and text to embeddings.
|
| 331 |
+
|
| 332 |
+
Returns:
|
| 333 |
+
Status message
|
| 334 |
+
"""
|
| 335 |
+
if builder_state is None:
|
| 336 |
+
return "❌ No dataset loaded. Please scan a directory first."
|
| 337 |
+
|
| 338 |
+
if not builder_state.samples:
|
| 339 |
+
return "❌ No samples in dataset."
|
| 340 |
+
|
| 341 |
+
labeled_count = builder_state.get_labeled_count()
|
| 342 |
+
if labeled_count == 0:
|
| 343 |
+
return "❌ No labeled samples. Please auto-label or manually label samples first."
|
| 344 |
+
|
| 345 |
+
if not output_dir or not output_dir.strip():
|
| 346 |
+
return "❌ Please enter an output directory."
|
| 347 |
+
|
| 348 |
+
if dit_handler is None or dit_handler.model is None:
|
| 349 |
+
return "❌ Model not initialized. Please initialize the service first."
|
| 350 |
+
|
| 351 |
+
def progress_callback(msg):
|
| 352 |
+
if progress:
|
| 353 |
+
try:
|
| 354 |
+
progress(msg)
|
| 355 |
+
except:
|
| 356 |
+
pass
|
| 357 |
+
|
| 358 |
+
# Run preprocessing
|
| 359 |
+
output_paths, status = builder_state.preprocess_to_tensors(
|
| 360 |
+
dit_handler=dit_handler,
|
| 361 |
+
output_dir=output_dir.strip(),
|
| 362 |
+
progress_callback=progress_callback,
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
return status
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def load_training_dataset(
|
| 369 |
+
tensor_dir: str,
|
| 370 |
+
) -> str:
|
| 371 |
+
"""Load a preprocessed tensor dataset for training.
|
| 372 |
+
|
| 373 |
+
Returns:
|
| 374 |
+
Info text about the dataset
|
| 375 |
+
"""
|
| 376 |
+
if not tensor_dir or not tensor_dir.strip():
|
| 377 |
+
return "❌ Please enter a tensor directory path"
|
| 378 |
+
|
| 379 |
+
tensor_dir = tensor_dir.strip()
|
| 380 |
+
|
| 381 |
+
if not os.path.exists(tensor_dir):
|
| 382 |
+
return f"❌ Directory not found: {tensor_dir}"
|
| 383 |
+
|
| 384 |
+
if not os.path.isdir(tensor_dir):
|
| 385 |
+
return f"❌ Not a directory: {tensor_dir}"
|
| 386 |
+
|
| 387 |
+
# Check for manifest
|
| 388 |
+
manifest_path = os.path.join(tensor_dir, "manifest.json")
|
| 389 |
+
if os.path.exists(manifest_path):
|
| 390 |
+
try:
|
| 391 |
+
with open(manifest_path, 'r') as f:
|
| 392 |
+
manifest = json.load(f)
|
| 393 |
+
|
| 394 |
+
num_samples = manifest.get("num_samples", 0)
|
| 395 |
+
metadata = manifest.get("metadata", {})
|
| 396 |
+
name = metadata.get("name", "Unknown")
|
| 397 |
+
custom_tag = metadata.get("custom_tag", "")
|
| 398 |
+
|
| 399 |
+
info = f"✅ Loaded preprocessed dataset: {name}\n"
|
| 400 |
+
info += f"📊 Samples: {num_samples} preprocessed tensors\n"
|
| 401 |
+
info += f"🏷️ Custom Tag: {custom_tag or '(none)'}"
|
| 402 |
+
|
| 403 |
+
return info
|
| 404 |
+
except Exception as e:
|
| 405 |
+
logger.warning(f"Failed to read manifest: {e}")
|
| 406 |
+
|
| 407 |
+
# Fallback: count .pt files
|
| 408 |
+
pt_files = [f for f in os.listdir(tensor_dir) if f.endswith('.pt')]
|
| 409 |
+
|
| 410 |
+
if not pt_files:
|
| 411 |
+
return f"❌ No .pt tensor files found in {tensor_dir}"
|
| 412 |
+
|
| 413 |
+
info = f"✅ Found {len(pt_files)} tensor files in {tensor_dir}\n"
|
| 414 |
+
info += "⚠️ No manifest.json found - using all .pt files"
|
| 415 |
+
|
| 416 |
+
return info
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
# Training handlers
|
| 420 |
+
|
| 421 |
+
import time
|
| 422 |
+
import re
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def _format_duration(seconds):
|
| 426 |
+
"""Format seconds to human readable string."""
|
| 427 |
+
seconds = int(seconds)
|
| 428 |
+
if seconds < 60:
|
| 429 |
+
return f"{seconds}s"
|
| 430 |
+
elif seconds < 3600:
|
| 431 |
+
return f"{seconds // 60}m {seconds % 60}s"
|
| 432 |
+
else:
|
| 433 |
+
return f"{seconds // 3600}h {(seconds % 3600) // 60}m"
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
def start_training(
|
| 437 |
+
tensor_dir: str,
|
| 438 |
+
dit_handler,
|
| 439 |
+
lora_rank: int,
|
| 440 |
+
lora_alpha: int,
|
| 441 |
+
lora_dropout: float,
|
| 442 |
+
learning_rate: float,
|
| 443 |
+
train_epochs: int,
|
| 444 |
+
train_batch_size: int,
|
| 445 |
+
gradient_accumulation: int,
|
| 446 |
+
save_every_n_epochs: int,
|
| 447 |
+
training_shift: float,
|
| 448 |
+
training_seed: int,
|
| 449 |
+
lora_output_dir: str,
|
| 450 |
+
training_state: Dict,
|
| 451 |
+
progress=None,
|
| 452 |
+
):
|
| 453 |
+
"""Start LoRA training from preprocessed tensors.
|
| 454 |
+
|
| 455 |
+
This is a generator function that yields progress updates.
|
| 456 |
+
"""
|
| 457 |
+
if not tensor_dir or not tensor_dir.strip():
|
| 458 |
+
yield "❌ Please enter a tensor directory path", "", None, training_state
|
| 459 |
+
return
|
| 460 |
+
|
| 461 |
+
tensor_dir = tensor_dir.strip()
|
| 462 |
+
|
| 463 |
+
if not os.path.exists(tensor_dir):
|
| 464 |
+
yield f"❌ Tensor directory not found: {tensor_dir}", "", None, training_state
|
| 465 |
+
return
|
| 466 |
+
|
| 467 |
+
if dit_handler is None or dit_handler.model is None:
|
| 468 |
+
yield "❌ Model not initialized. Please initialize the service first.", "", None, training_state
|
| 469 |
+
return
|
| 470 |
+
|
| 471 |
+
# Check for required training dependencies
|
| 472 |
+
try:
|
| 473 |
+
from lightning.fabric import Fabric
|
| 474 |
+
from peft import get_peft_model, LoraConfig
|
| 475 |
+
except ImportError as e:
|
| 476 |
+
yield f"❌ Missing required packages: {e}\nPlease install: pip install peft lightning", "", None, training_state
|
| 477 |
+
return
|
| 478 |
+
|
| 479 |
+
training_state["is_training"] = True
|
| 480 |
+
training_state["should_stop"] = False
|
| 481 |
+
|
| 482 |
+
try:
|
| 483 |
+
from acestep.training.trainer import LoRATrainer
|
| 484 |
+
from acestep.training.configs import LoRAConfig as LoRAConfigClass, TrainingConfig
|
| 485 |
+
|
| 486 |
+
# Create configs
|
| 487 |
+
lora_config = LoRAConfigClass(
|
| 488 |
+
r=lora_rank,
|
| 489 |
+
alpha=lora_alpha,
|
| 490 |
+
dropout=lora_dropout,
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
training_config = TrainingConfig(
|
| 494 |
+
shift=training_shift,
|
| 495 |
+
learning_rate=learning_rate,
|
| 496 |
+
batch_size=train_batch_size,
|
| 497 |
+
gradient_accumulation_steps=gradient_accumulation,
|
| 498 |
+
max_epochs=train_epochs,
|
| 499 |
+
save_every_n_epochs=save_every_n_epochs,
|
| 500 |
+
seed=training_seed,
|
| 501 |
+
output_dir=lora_output_dir,
|
| 502 |
+
)
|
| 503 |
+
|
| 504 |
+
import pandas as pd
|
| 505 |
+
|
| 506 |
+
# Initialize training log and loss history
|
| 507 |
+
log_lines = []
|
| 508 |
+
loss_data = pd.DataFrame({"step": [0], "loss": [0.0]})
|
| 509 |
+
|
| 510 |
+
# Start timer
|
| 511 |
+
start_time = time.time()
|
| 512 |
+
|
| 513 |
+
yield f"🚀 Starting training from {tensor_dir}...", "", loss_data, training_state
|
| 514 |
+
|
| 515 |
+
# Create trainer
|
| 516 |
+
trainer = LoRATrainer(
|
| 517 |
+
dit_handler=dit_handler,
|
| 518 |
+
lora_config=lora_config,
|
| 519 |
+
training_config=training_config,
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
# Collect loss history
|
| 523 |
+
step_list = []
|
| 524 |
+
loss_list = []
|
| 525 |
+
|
| 526 |
+
# Train with progress updates using preprocessed tensors
|
| 527 |
+
for step, loss, status in trainer.train_from_preprocessed(tensor_dir, training_state):
|
| 528 |
+
# Calculate elapsed time and ETA
|
| 529 |
+
elapsed_seconds = time.time() - start_time
|
| 530 |
+
time_info = f"⏱️ Elapsed: {_format_duration(elapsed_seconds)}"
|
| 531 |
+
|
| 532 |
+
# Parse "Epoch x/y" from status to calculate ETA
|
| 533 |
+
match = re.search(r"Epoch\s+(\d+)/(\d+)", str(status))
|
| 534 |
+
if match:
|
| 535 |
+
current_ep = int(match.group(1))
|
| 536 |
+
total_ep = int(match.group(2))
|
| 537 |
+
if current_ep > 0:
|
| 538 |
+
eta_seconds = (elapsed_seconds / current_ep) * (total_ep - current_ep)
|
| 539 |
+
time_info += f" | ETA: ~{_format_duration(eta_seconds)}"
|
| 540 |
+
|
| 541 |
+
# Display status with time info
|
| 542 |
+
display_status = f"{status}\n{time_info}"
|
| 543 |
+
|
| 544 |
+
# Terminal log
|
| 545 |
+
log_msg = f"[{_format_duration(elapsed_seconds)}] Step {step}: {status}"
|
| 546 |
+
logger.info(log_msg)
|
| 547 |
+
|
| 548 |
+
# Add to UI log
|
| 549 |
+
log_lines.append(status)
|
| 550 |
+
if len(log_lines) > 15:
|
| 551 |
+
log_lines = log_lines[-15:]
|
| 552 |
+
log_text = "\n".join(log_lines)
|
| 553 |
+
|
| 554 |
+
# Track loss for plot (only valid values)
|
| 555 |
+
if step > 0 and loss is not None and loss == loss: # Check for NaN
|
| 556 |
+
step_list.append(step)
|
| 557 |
+
loss_list.append(float(loss))
|
| 558 |
+
loss_data = pd.DataFrame({"step": step_list, "loss": loss_list})
|
| 559 |
+
|
| 560 |
+
yield display_status, log_text, loss_data, training_state
|
| 561 |
+
|
| 562 |
+
if training_state.get("should_stop", False):
|
| 563 |
+
logger.info("⏹️ Training stopped by user")
|
| 564 |
+
log_lines.append("⏹️ Training stopped by user")
|
| 565 |
+
yield f"⏹️ Stopped ({time_info})", "\n".join(log_lines[-15:]), loss_data, training_state
|
| 566 |
+
break
|
| 567 |
+
|
| 568 |
+
total_time = time.time() - start_time
|
| 569 |
+
training_state["is_training"] = False
|
| 570 |
+
completion_msg = f"✅ Training completed! Total time: {_format_duration(total_time)}"
|
| 571 |
+
|
| 572 |
+
logger.info(completion_msg)
|
| 573 |
+
log_lines.append(completion_msg)
|
| 574 |
+
|
| 575 |
+
yield completion_msg, "\n".join(log_lines[-15:]), loss_data, training_state
|
| 576 |
+
|
| 577 |
+
except Exception as e:
|
| 578 |
+
logger.exception("Training error")
|
| 579 |
+
training_state["is_training"] = False
|
| 580 |
+
import pandas as pd
|
| 581 |
+
empty_df = pd.DataFrame({"step": [], "loss": []})
|
| 582 |
+
yield f"❌ Error: {str(e)}", str(e), empty_df, training_state
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def stop_training(training_state: Dict) -> Tuple[str, Dict]:
|
| 586 |
+
"""Stop the current training process.
|
| 587 |
+
|
| 588 |
+
Returns:
|
| 589 |
+
Tuple of (status, training_state)
|
| 590 |
+
"""
|
| 591 |
+
if not training_state.get("is_training", False):
|
| 592 |
+
return "⚠️ No training in progress", training_state
|
| 593 |
+
|
| 594 |
+
training_state["should_stop"] = True
|
| 595 |
+
return "⏹️ Stopping training...", training_state
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
def export_lora(
|
| 599 |
+
export_path: str,
|
| 600 |
+
lora_output_dir: str,
|
| 601 |
+
) -> str:
|
| 602 |
+
"""Export the trained LoRA weights.
|
| 603 |
+
|
| 604 |
+
Returns:
|
| 605 |
+
Status message
|
| 606 |
+
"""
|
| 607 |
+
if not export_path or not export_path.strip():
|
| 608 |
+
return "❌ Please enter an export path"
|
| 609 |
+
|
| 610 |
+
# Check if there's a trained model to export
|
| 611 |
+
final_dir = os.path.join(lora_output_dir, "final")
|
| 612 |
+
checkpoint_dir = os.path.join(lora_output_dir, "checkpoints")
|
| 613 |
+
|
| 614 |
+
# Prefer final, fallback to checkpoints
|
| 615 |
+
if os.path.exists(final_dir):
|
| 616 |
+
source_path = final_dir
|
| 617 |
+
elif os.path.exists(checkpoint_dir):
|
| 618 |
+
# Find the latest checkpoint
|
| 619 |
+
checkpoints = [d for d in os.listdir(checkpoint_dir) if d.startswith("epoch_")]
|
| 620 |
+
if not checkpoints:
|
| 621 |
+
return "❌ No checkpoints found"
|
| 622 |
+
|
| 623 |
+
checkpoints.sort(key=lambda x: int(x.split("_")[1]))
|
| 624 |
+
latest = checkpoints[-1]
|
| 625 |
+
source_path = os.path.join(checkpoint_dir, latest)
|
| 626 |
+
else:
|
| 627 |
+
return f"❌ No trained model found in {lora_output_dir}"
|
| 628 |
+
|
| 629 |
+
try:
|
| 630 |
+
import shutil
|
| 631 |
+
|
| 632 |
+
export_path = export_path.strip()
|
| 633 |
+
os.makedirs(os.path.dirname(export_path) if os.path.dirname(export_path) else ".", exist_ok=True)
|
| 634 |
+
|
| 635 |
+
if os.path.exists(export_path):
|
| 636 |
+
shutil.rmtree(export_path)
|
| 637 |
+
|
| 638 |
+
shutil.copytree(source_path, export_path)
|
| 639 |
+
|
| 640 |
+
return f"✅ LoRA exported to {export_path}"
|
| 641 |
+
|
| 642 |
+
except Exception as e:
|
| 643 |
+
logger.exception("Export error")
|
| 644 |
+
return f"❌ Export failed: {str(e)}"
|