skroed commited on
Commit
14d732b
1 Parent(s): bb4095b

add: handler.py

Browse files
Files changed (1) hide show
  1. handler.py +45 -0
handler.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict
2
+
3
+ import torch
4
+ from transformers import AutoProcessor, MusicgenForConditionalGeneration
5
+
6
+
7
+ class EndpointHandler:
8
+ def __init__(self, path=""):
9
+ # load model and processor from path
10
+ self.processor = AutoProcessor.from_pretrained(path)
11
+ self.model = MusicgenForConditionalGeneration.from_pretrained(
12
+ path, torch_dtype=torch.float16
13
+ ).to("cuda")
14
+
15
+ def __call__(self, data: Dict[str, Any]) -> Dict[str, str]:
16
+ """
17
+ Args:
18
+ data (:dict:):
19
+ The payload with the text prompt and generation parameters.
20
+ """
21
+ # process input
22
+ inputs = data.pop("inputs", data)
23
+ parameters = data.pop("parameters", None)
24
+
25
+ # preprocess
26
+ inputs = self.processor(
27
+ text=[inputs],
28
+ padding=True,
29
+ return_tensors="pt",
30
+ ).to("cuda")
31
+
32
+ # pass inputs with all kwargs in data
33
+ if parameters is not None:
34
+ with torch.autocast("cuda"):
35
+ outputs = self.model.generate(**inputs, **parameters)
36
+ else:
37
+ with torch.autocast("cuda"):
38
+ outputs = self.model.generate(
39
+ **inputs,
40
+ )
41
+
42
+ # postprocess the prediction
43
+ prediction = outputs[0].cpu().numpy().tolist()
44
+
45
+ return [{"generated_audio": prediction}]