File size: 21,957 Bytes
e3ac746 9e2d0e8 e3ac746 5bc2ec0 e3ac746 5bc2ec0 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 be0a4ad 7e3f77a be0a4ad e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 be0a4ad 7e3f77a 56eb0fe 7e3f77a 56eb0fe 9e2d0e8 e3ac746 9e2d0e8 e3ac746 5bc2ec0 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 5bc2ec0 e3ac746 9e2d0e8 5bc2ec0 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 e3ac746 9e2d0e8 be0a4ad |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 |
# handler.py
import base64
import io
import os
import traceback
from typing import Any, Dict, Optional, Tuple
import numpy as np
import soundfile as sf
try:
import torch
except Exception:
torch = None
class EndpointHandler:
"""
Hugging Face Inference Endpoints custom handler for ACE-Step 1.5.
Supported request shapes:
{
"inputs": {
"prompt": "upbeat pop rap, emotional guitar",
"lyrics": "[Verse] ...",
"duration_sec": 12,
"sample_rate": 44100,
"seed": 42,
"guidance_scale": 7.0,
"steps": 8,
"use_lm": true,
"simple_prompt": false,
"instrumental": false,
"allow_fallback": false
}
}
Or simple mode:
{
"inputs": "upbeat pop rap with emotional guitar"
}
Notes:
- This handler uses ACE-Step's official Python API internally.
- Fallback sine generation is disabled by default so model failures are explicit.
"""
def __init__(self, path: str = ""):
self.path = path
self.project_root = os.path.dirname(os.path.abspath(__file__))
self.model_repo = os.getenv("ACE_MODEL_REPO", "ACE-Step/Ace-Step1.5")
self.config_path = os.getenv("ACE_CONFIG_PATH", "acestep-v15-turbo")
self.lm_model_path = os.getenv("ACE_LM_MODEL_PATH", "acestep-5Hz-lm-1.7B")
self.lm_backend = os.getenv("ACE_LM_BACKEND", "pt")
self.download_source = os.getenv("ACE_DOWNLOAD_SOURCE", "huggingface")
self.default_sr = int(os.getenv("DEFAULT_SAMPLE_RATE", "44100"))
self.enable_fallback = self._to_bool(os.getenv("ACE_ENABLE_FALLBACK"), False)
self.init_lm_on_start = self._to_bool(os.getenv("ACE_INIT_LLM"), False)
self.skip_init = self._to_bool(os.getenv("ACE_SKIP_INIT"), False)
self.device = "cuda" if (torch is not None and torch.cuda.is_available()) else "cpu"
self.dtype = "float16" if self.device == "cuda" else "float32"
self.model_loaded = False
self.model_error: Optional[str] = None
self.init_details: Dict[str, Any] = {}
self.dit_handler = None
self.llm_handler = None
self.llm_initialized = False
self.llm_error: Optional[str] = None
self._GenerationParams = None
self._GenerationConfig = None
self._generate_music = None
self._create_sample = None
if self.skip_init:
self.model_error = "Initialization skipped because ACE_SKIP_INIT=true"
else:
self._init_model()
# --------------------------
# Initialization
# --------------------------
def _init_model(self) -> None:
err_msgs = []
# ACE-Step dynamic config imports layer_type_validation from transformers.
# Some endpoint base images ship a transformers build without this helper.
self._patch_transformers_layer_validation()
# Some CUDA/torch combinations used by managed endpoint images don't support
# sorting bool tensors on CUDA. ACE-Step/Transformers paths can hit this.
self._patch_torch_sort_bool_cuda()
try:
from acestep.handler import AceStepHandler
from acestep.inference import GenerationConfig, GenerationParams, create_sample, generate_music
from acestep.llm_inference import LLMHandler
except Exception as e:
self.model_error = f"ACE-Step import failed: {type(e).__name__}: {e}"
return
self._GenerationParams = GenerationParams
self._GenerationConfig = GenerationConfig
self._generate_music = generate_music
self._create_sample = create_sample
try:
self.dit_handler = AceStepHandler()
prefer_source = self.download_source if self.download_source in {"huggingface", "modelscope"} else None
init_status, ok = self.dit_handler.initialize_service(
project_root=self.project_root,
config_path=self.config_path,
device=self.device,
use_flash_attention=False,
compile_model=False,
offload_to_cpu=False,
offload_dit_to_cpu=False,
prefer_source=prefer_source,
)
self.init_details["dit_status"] = init_status
if not ok:
raise RuntimeError(init_status)
except Exception as e:
err_msgs.append(f"DiT init failed: {type(e).__name__}: {e}")
try:
self.llm_handler = LLMHandler()
if self.init_lm_on_start:
self._ensure_llm_initialized()
except Exception as e:
err_msgs.append(f"LLM bootstrap failed: {type(e).__name__}: {e}")
if err_msgs:
self.model_loaded = False
self.model_error = " | ".join(err_msgs)
return
self.model_loaded = True
self.model_error = None
@staticmethod
def _patch_transformers_layer_validation() -> None:
try:
from transformers import configuration_utils as cu
except Exception:
return
if hasattr(cu, "layer_type_validation"):
return
def _fallback_layer_type_validation(layer_types, num_hidden_layers=None):
if layer_types is None:
return
if not isinstance(layer_types, (list, tuple)):
raise TypeError("`layer_types` must be a list/tuple")
if num_hidden_layers is not None and len(layer_types) != int(num_hidden_layers):
raise ValueError("`layer_types` length must match `num_hidden_layers`")
cu.layer_type_validation = _fallback_layer_type_validation
@staticmethod
def _patch_torch_sort_bool_cuda() -> None:
if torch is None or not hasattr(torch, "sort"):
return
if getattr(torch.sort, "__name__", "") == "_sort_bool_cuda_compat":
return
_orig_sort = torch.sort
_orig_tensor_sort = getattr(torch.Tensor, "sort", None)
_orig_argsort = getattr(torch, "argsort", None)
_orig_tensor_argsort = getattr(torch.Tensor, "argsort", None)
def _sort_bool_cuda_compat(input_tensor, *args, **kwargs):
if (
isinstance(input_tensor, torch.Tensor)
and input_tensor.is_cuda
and input_tensor.dtype == torch.bool
):
out = _orig_sort(input_tensor.to(torch.uint8), *args, **kwargs)
values = out.values.to(torch.bool) if hasattr(out, "values") else out[0].to(torch.bool)
indices = out.indices if hasattr(out, "indices") else out[1]
return values, indices
return _orig_sort(input_tensor, *args, **kwargs)
_sort_bool_cuda_compat.__name__ = "_sort_bool_cuda_compat"
torch.sort = _sort_bool_cuda_compat
if callable(_orig_tensor_sort):
def _tensor_sort_bool_cuda_compat(self, *args, **kwargs):
if self.is_cuda and self.dtype == torch.bool:
out = _orig_tensor_sort(self.to(torch.uint8), *args, **kwargs)
values = out.values.to(torch.bool) if hasattr(out, "values") else out[0].to(torch.bool)
indices = out.indices if hasattr(out, "indices") else out[1]
return values, indices
return _orig_tensor_sort(self, *args, **kwargs)
_tensor_sort_bool_cuda_compat.__name__ = "_tensor_sort_bool_cuda_compat"
torch.Tensor.sort = _tensor_sort_bool_cuda_compat
if callable(_orig_argsort):
def _argsort_bool_cuda_compat(input_tensor, *args, **kwargs):
if (
isinstance(input_tensor, torch.Tensor)
and input_tensor.is_cuda
and input_tensor.dtype == torch.bool
):
return _orig_argsort(input_tensor.to(torch.uint8), *args, **kwargs)
return _orig_argsort(input_tensor, *args, **kwargs)
_argsort_bool_cuda_compat.__name__ = "_argsort_bool_cuda_compat"
torch.argsort = _argsort_bool_cuda_compat
if callable(_orig_tensor_argsort):
def _tensor_argsort_bool_cuda_compat(self, *args, **kwargs):
if self.is_cuda and self.dtype == torch.bool:
return _orig_tensor_argsort(self.to(torch.uint8), *args, **kwargs)
return _orig_tensor_argsort(self, *args, **kwargs)
_tensor_argsort_bool_cuda_compat.__name__ = "_tensor_argsort_bool_cuda_compat"
torch.Tensor.argsort = _tensor_argsort_bool_cuda_compat
def _ensure_llm_initialized(self) -> bool:
if self.llm_handler is None:
self.llm_error = "LLM handler is not available"
return False
if self.llm_initialized:
return True
try:
checkpoint_dir = os.path.join(self.project_root, "checkpoints")
status, ok = self.llm_handler.initialize(
checkpoint_dir=checkpoint_dir,
lm_model_path=self.lm_model_path,
backend=self.lm_backend,
device=self.device,
offload_to_cpu=False,
)
self.init_details["llm_status"] = status
if not ok:
self.llm_error = status
self.llm_initialized = False
return False
self.llm_error = None
self.llm_initialized = True
return True
except Exception as e:
self.llm_error = f"LLM init exception: {type(e).__name__}: {e}"
self.llm_initialized = False
return False
# --------------------------
# Audio helpers
# --------------------------
@staticmethod
def _as_float32(audio: Any) -> np.ndarray:
if isinstance(audio, np.ndarray):
arr = audio
elif torch is not None and isinstance(audio, torch.Tensor):
arr = audio.detach().cpu().numpy()
else:
arr = np.asarray(audio)
if arr.ndim == 2 and arr.shape[0] in (1, 2) and arr.shape[1] > arr.shape[0]:
arr = arr.T
if arr.dtype != np.float32:
arr = arr.astype(np.float32)
return np.clip(arr, -1.0, 1.0)
@staticmethod
def _wav_b64(audio: np.ndarray, sr: int) -> str:
bio = io.BytesIO()
sf.write(bio, audio, sr, format="WAV")
return base64.b64encode(bio.getvalue()).decode("utf-8")
@staticmethod
def _fallback_sine(duration_sec: int, sr: int, seed: int) -> np.ndarray:
rng = np.random.default_rng(seed)
t = np.linspace(0, duration_sec, int(sr * duration_sec), endpoint=False)
y = (0.07 * np.sin(2 * np.pi * 440 * t) + 0.01 * rng.standard_normal(len(t))).astype(np.float32)
return np.clip(y, -1.0, 1.0)
# --------------------------
# Request normalization
# --------------------------
@staticmethod
def _to_bool(value: Any, default: bool = False) -> bool:
if value is None:
return default
if isinstance(value, bool):
return value
if isinstance(value, (int, float)):
return bool(value)
if isinstance(value, str):
return value.strip().lower() in {"1", "true", "t", "yes", "y", "on"}
return default
@staticmethod
def _to_int(value: Any, default: int) -> int:
try:
return int(value)
except Exception:
return default
@staticmethod
def _to_float(value: Any, default: float) -> float:
try:
return float(value)
except Exception:
return default
@staticmethod
def _pick_text(inputs: Dict[str, Any], *keys: str) -> str:
for key in keys:
v = inputs.get(key)
if v is None:
continue
s = str(v).strip()
if s:
return s
return ""
def _normalize_request(self, data: Dict[str, Any]) -> Dict[str, Any]:
raw_inputs = data.get("inputs", data)
if isinstance(raw_inputs, str):
raw_inputs = {"prompt": raw_inputs, "simple_prompt": True}
if not isinstance(raw_inputs, dict):
raise ValueError("`inputs` must be an object or string")
prompt = self._pick_text(raw_inputs, "prompt", "query", "caption", "text", "description")
lyrics = self._pick_text(raw_inputs, "lyrics")
simple_prompt = self._to_bool(raw_inputs.get("simple_prompt"), False) or self._to_bool(
raw_inputs.get("simple"), False
)
instrumental = self._to_bool(raw_inputs.get("instrumental"), False)
if not lyrics and (instrumental or simple_prompt):
lyrics = "[Instrumental]"
duration_sec = self._to_int(raw_inputs.get("duration_sec", raw_inputs.get("duration", 12)), 12)
duration_sec = max(10, min(duration_sec, 600))
sample_rate = self._to_int(raw_inputs.get("sample_rate", self.default_sr), self.default_sr)
sample_rate = max(8000, min(sample_rate, 48000))
seed = self._to_int(raw_inputs.get("seed", 42), 42)
guidance_scale = self._to_float(raw_inputs.get("guidance_scale", 7.0), 7.0)
steps = self._to_int(raw_inputs.get("steps", raw_inputs.get("inference_steps", 8)), 8)
steps = max(1, min(steps, 200))
use_lm = self._to_bool(raw_inputs.get("use_lm", raw_inputs.get("thinking", True)), True)
allow_fallback = self._to_bool(raw_inputs.get("allow_fallback"), self.enable_fallback)
return {
"prompt": prompt,
"lyrics": lyrics,
"duration_sec": duration_sec,
"sample_rate": sample_rate,
"seed": seed,
"guidance_scale": guidance_scale,
"steps": steps,
"use_lm": use_lm,
"instrumental": instrumental,
"simple_prompt": simple_prompt,
"allow_fallback": allow_fallback,
}
# --------------------------
# ACE-Step invocation
# --------------------------
def _build_generation_inputs(self, req: Dict[str, Any], llm_ready: bool) -> Tuple[Dict[str, Any], Dict[str, Any]]:
caption = req["prompt"]
lyrics = req["lyrics"]
extras: Dict[str, Any] = {
"simple_expansion_used": False,
"simple_expansion_error": None,
}
bpm = None
keyscale = ""
timesignature = ""
vocal_language = "unknown"
duration = float(req["duration_sec"])
if req["simple_prompt"] and req["use_lm"] and llm_ready and caption:
try:
sample = self._create_sample(
llm_handler=self.llm_handler,
query=caption,
instrumental=req["instrumental"],
)
if getattr(sample, "success", False):
caption = getattr(sample, "caption", "") or caption
lyrics = getattr(sample, "lyrics", "") or lyrics
bpm = getattr(sample, "bpm", None)
keyscale = getattr(sample, "keyscale", "") or ""
timesignature = getattr(sample, "timesignature", "") or ""
vocal_language = getattr(sample, "language", "") or "unknown"
sample_duration = getattr(sample, "duration", None)
if sample_duration:
duration = float(sample_duration)
extras["simple_expansion_used"] = True
else:
extras["simple_expansion_error"] = getattr(sample, "error", "create_sample failed")
except Exception as e:
extras["simple_expansion_error"] = f"{type(e).__name__}: {e}"
params = self._GenerationParams(
task_type="text2music",
caption=caption,
lyrics=lyrics,
instrumental=req["instrumental"],
duration=duration,
inference_steps=req["steps"],
guidance_scale=req["guidance_scale"],
seed=req["seed"],
bpm=bpm,
keyscale=keyscale,
timesignature=timesignature,
vocal_language=vocal_language,
thinking=bool(req["use_lm"] and llm_ready),
use_cot_metas=bool(req["use_lm"] and llm_ready),
use_cot_caption=bool(req["use_lm"] and llm_ready and not req["simple_prompt"]),
use_cot_language=bool(req["use_lm"] and llm_ready),
)
config = self._GenerationConfig(
batch_size=1,
allow_lm_batch=False,
use_random_seed=False,
seeds=[req["seed"]],
audio_format="wav",
)
extras["resolved_prompt"] = caption
extras["resolved_lyrics"] = lyrics
extras["resolved_duration"] = duration
return {"params": params, "config": config}, extras
def _call_model(self, req: Dict[str, Any]) -> Tuple[np.ndarray, int, Dict[str, Any]]:
if not self.model_loaded or self.dit_handler is None:
raise RuntimeError(self.model_error or "Model is not loaded")
llm_ready = False
if req["use_lm"]:
llm_ready = self._ensure_llm_initialized()
generation_inputs, extras = self._build_generation_inputs(req, llm_ready)
result = self._generate_music(
self.dit_handler,
self.llm_handler if llm_ready else None,
generation_inputs["params"],
generation_inputs["config"],
save_dir=None,
progress=None,
)
if not getattr(result, "success", False):
raise RuntimeError(getattr(result, "error", "generation failed"))
audios = getattr(result, "audios", None) or []
if not audios:
raise RuntimeError("generation succeeded but no audio was returned")
first = audios[0]
audio_tensor = first.get("tensor") if isinstance(first, dict) else None
if audio_tensor is None:
raise RuntimeError("generated audio tensor is missing")
sample_rate = int(first.get("sample_rate", req["sample_rate"]))
status_message = getattr(result, "status_message", "")
meta = {
"llm_requested": req["use_lm"],
"llm_initialized": llm_ready,
"llm_error": self.llm_error,
"status_message": status_message,
}
meta.update(extras)
return self._as_float32(audio_tensor), sample_rate, meta
# --------------------------
# Endpoint entry
# --------------------------
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
try:
req = self._normalize_request(data)
used_fallback = False
runtime_meta: Dict[str, Any] = {}
try:
audio, out_sr, runtime_meta = self._call_model(req)
except Exception as model_exc:
self.model_error = f"Inference failed: {type(model_exc).__name__}: {model_exc}"
if not req["allow_fallback"]:
raise RuntimeError(self.model_error)
used_fallback = True
audio = self._fallback_sine(req["duration_sec"], req["sample_rate"], req["seed"])
out_sr = req["sample_rate"]
return {
"audio_base64_wav": self._wav_b64(audio, out_sr),
"sample_rate": int(out_sr),
"duration_sec": int(req["duration_sec"]),
"used_fallback": used_fallback,
"model_loaded": self.model_loaded,
"model_repo": self.model_repo,
"model_error": self.model_error,
"meta": {
"device": self.device,
"dtype": self.dtype,
"prompt_len": len(req["prompt"]),
"lyrics_len": len(req["lyrics"]),
"seed": req["seed"],
"guidance_scale": req["guidance_scale"],
"steps": req["steps"],
"use_lm": req["use_lm"],
"simple_prompt": req["simple_prompt"],
"instrumental": req["instrumental"],
"allow_fallback": req["allow_fallback"],
"resolved_prompt": runtime_meta.get("resolved_prompt", req["prompt"]),
"resolved_lyrics": runtime_meta.get("resolved_lyrics", req["lyrics"]),
"simple_expansion_used": runtime_meta.get("simple_expansion_used", False),
"simple_expansion_error": runtime_meta.get("simple_expansion_error"),
"llm_requested": runtime_meta.get("llm_requested", False),
"llm_initialized": runtime_meta.get("llm_initialized", False),
"llm_error": runtime_meta.get("llm_error"),
"status_message": runtime_meta.get("status_message", ""),
"init_details": self.init_details,
},
}
except Exception as e:
return {
"error": f"{type(e).__name__}: {e}",
"traceback": traceback.format_exc(limit=4),
"audio_base64_wav": None,
"sample_rate": None,
"duration_sec": None,
"used_fallback": False,
"model_loaded": self.model_loaded,
"model_repo": self.model_repo,
"model_error": self.model_error,
"meta": {
"device": self.device,
"dtype": self.dtype,
"init_details": self.init_details,
"llm_error": self.llm_error,
},
}
|