|
|
|
from typing import Dict, Any |
|
from transformers import AutoProcessor, MusicgenForConditionalGeneration |
|
import torch |
|
|
|
class EndpointHandler: |
|
def __init__(self, path=""): |
|
"""Initialize the model and processor.""" |
|
self.processor = AutoProcessor.from_pretrained(path) |
|
self.model = MusicgenForConditionalGeneration.from_pretrained( |
|
path, |
|
torch_dtype=torch.float16, |
|
device_map="auto" |
|
).to("cuda") |
|
|
|
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]: |
|
"""Process the input data and generate audio.""" |
|
try: |
|
|
|
inputs = data.pop("inputs", data) |
|
parameters = data.pop("parameters", {}) |
|
|
|
|
|
prompt = inputs.get("prompt", "") |
|
duration = inputs.get("duration", 30) |
|
|
|
|
|
samples_per_token = 1024 |
|
sampling_rate = 32000 |
|
max_new_tokens = int((duration * sampling_rate) / samples_per_token) |
|
|
|
|
|
model_inputs = self.processor( |
|
text=[prompt], |
|
padding=True, |
|
return_tensors="pt" |
|
).to("cuda") |
|
|
|
|
|
generation_params = { |
|
"do_sample": True, |
|
"guidance_scale": 3, |
|
"max_new_tokens": max_new_tokens |
|
} |
|
|
|
|
|
generation_params.update(parameters) |
|
|
|
|
|
with torch.cuda.amp.autocast(): |
|
audio_values = self.model.generate(**model_inputs, **generation_params) |
|
|
|
|
|
audio_data = audio_values.cpu().numpy().tolist() |
|
|
|
return [{"generated_audio": audio_data}] |
|
|
|
except Exception as e: |
|
return {"error": str(e)} |