Enning commited on
Commit
d46cf03
·
1 Parent(s): 51027f0

Upload 2 files

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