added handler.py
Browse files- handler.py +38 -0
handler.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, List, Any
|
2 |
+
from transformers import AutoProcessor, MusicgenForConditionalGeneration
|
3 |
+
import torch
|
4 |
+
|
5 |
+
class EndpointHandler:
|
6 |
+
def __init__(self, path=""):
|
7 |
+
# load model and processor
|
8 |
+
self.processor = AutoProcessor.from_pretrained(path)
|
9 |
+
self.model = MusicgenForConditionalGeneration.from_pretrained(path, torch_dtype=torch.float16)
|
10 |
+
self.model.to('cuda')
|
11 |
+
|
12 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
13 |
+
"""
|
14 |
+
Args:
|
15 |
+
data (:dict:):
|
16 |
+
The payload with the text prompt and generation parameters.
|
17 |
+
"""
|
18 |
+
|
19 |
+
inputs = data.pop("inputs", data)
|
20 |
+
params = data.pop("parameters", None)
|
21 |
+
|
22 |
+
inputs = self.processor(
|
23 |
+
text=[inputs],
|
24 |
+
padding=True,
|
25 |
+
return_tensors="pt"
|
26 |
+
).to('cuda')
|
27 |
+
|
28 |
+
if params is not None:
|
29 |
+
with torch.cuda.amp.autocast():
|
30 |
+
outputs = self.model.generate(**inputs, **params)
|
31 |
+
else:
|
32 |
+
with torch.cuda.amp.autocast():
|
33 |
+
outputs = self.model.generate(**inputs)
|
34 |
+
|
35 |
+
pred = outputs[0].cpu().numpy().tolist()
|
36 |
+
|
37 |
+
return [{"audio": pred, "sr": self.model.config.sampling_rate}]
|
38 |
+
|