Create handler.py
#2
by
DOBSON001
- opened
- handler.py +32 -0
handler.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import pipeline # 或模型特定库,如 cosyvoice
|
| 3 |
+
from cosyvoice.cli.cosyvoice import CosyVoice # CosyVoice 示例,换成你的模型
|
| 4 |
+
|
| 5 |
+
class EndpointHandler:
|
| 6 |
+
def __init__(self, model):
|
| 7 |
+
self.model = CosyVoice('path/to/model') # 加载模型
|
| 8 |
+
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 9 |
+
self.model.to(self.device)
|
| 10 |
+
|
| 11 |
+
def __call__(self, data):
|
| 12 |
+
inputs = data.get('inputs', 'Default text')
|
| 13 |
+
parameters = data.get('parameters', {})
|
| 14 |
+
language = parameters.get('language', 'en')
|
| 15 |
+
duration = parameters.get('duration', 30)
|
| 16 |
+
|
| 17 |
+
# 生成唱歌音频
|
| 18 |
+
audio = self.model.generate(inputs, language=language, singing_mode=True) # 唱歌参数
|
| 19 |
+
|
| 20 |
+
# 返回 base64 WAV
|
| 21 |
+
import io
|
| 22 |
+
import base64
|
| 23 |
+
buffer = io.BytesIO()
|
| 24 |
+
torch.save(audio, buffer)
|
| 25 |
+
audio_b64 = base64.b64encode(buffer.getvalue()).decode()
|
| 26 |
+
|
| 27 |
+
return {'audio': audio_b64}
|
| 28 |
+
|
| 29 |
+
# 入口
|
| 30 |
+
def query_endpoint(payload):
|
| 31 |
+
handler = EndpointHandler(None) # 初始化
|
| 32 |
+
return handler(payload)
|