|
|
|
from typing import Dict, Any |
|
from transformers import AutoProcessor, MusicgenForConditionalGeneration |
|
import torch |
|
import numpy as np |
|
|
|
class EndpointHandler: |
|
def __init__(self, path=""): |
|
|
|
self.processor = AutoProcessor.from_pretrained(path) |
|
self.model = MusicgenForConditionalGeneration.from_pretrained( |
|
path, |
|
torch_dtype=torch.float16 |
|
).to("cuda") |
|
|
|
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]: |
|
""" |
|
Args: |
|
data (Dict): The request data, containing: |
|
- inputs (Dict): Contains 'prompt' and optional 'duration' |
|
- parameters (Dict, optional): Generation parameters |
|
""" |
|
|
|
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) |
|
|
|
|
|
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(): |
|
outputs = self.model.generate(**inputs, **generation_params) |
|
|
|
|
|
generated_audio = outputs.cpu().numpy().tolist() |
|
|
|
return [{"generated_audio": generated_audio}] |