voice-changer/server/restapi/MMVC_Rest_VoiceChanger.py

61 lines
1.8 KiB
Python
Raw Normal View History

2023-02-17 07:10:17 +03:00
import base64
import struct
2022-12-31 12:06:57 +03:00
import numpy as np
2023-01-08 14:28:57 +03:00
import traceback
2022-12-31 12:06:57 +03:00
from fastapi import APIRouter
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from voice_changer.VoiceChangerManager import VoiceChangerManager
from pydantic import BaseModel
import threading
2023-02-17 07:10:17 +03:00
2022-12-31 12:06:57 +03:00
class VoiceModel(BaseModel):
timestamp: int
buffer: str
2023-02-17 07:10:17 +03:00
2022-12-31 12:06:57 +03:00
class MMVC_Rest_VoiceChanger:
2023-02-17 07:10:17 +03:00
def __init__(self, voiceChangerManager: VoiceChangerManager):
2022-12-31 12:06:57 +03:00
self.voiceChangerManager = voiceChangerManager
self.router = APIRouter()
self.router.add_api_route("/test", self.test, methods=["POST"])
2023-02-17 07:10:17 +03:00
2022-12-31 12:06:57 +03:00
self.tlock = threading.Lock()
def test(self, voice: VoiceModel):
try:
timestamp = voice.timestamp
buffer = voice.buffer
wav = base64.b64decode(buffer)
if wav == 0:
samplerate, data = read("dummy.wav")
unpackedData = data
else:
unpackedData = np.array(struct.unpack(
'<%sh' % (len(wav) // struct.calcsize('<h')), wav))
# write("logs/received_data.wav", 24000,
# unpackedData.astype(np.int16))
self.tlock.acquire()
2023-02-17 07:10:17 +03:00
changedVoice = self.voiceChangerManager.changeVoice(unpackedData)
2022-12-31 12:06:57 +03:00
self.tlock.release()
2023-03-15 00:39:33 +03:00
changedVoiceBase64 = base64.b64encode(changedVoice[0]).decode('utf-8')
2022-12-31 12:06:57 +03:00
data = {
"timestamp": timestamp,
"changedVoiceBase64": changedVoiceBase64
}
json_compatible_item_data = jsonable_encoder(data)
return JSONResponse(content=json_compatible_item_data)
except Exception as e:
print("REQUEST PROCESSING!!!! EXCEPTION!!!", e)
print(traceback.format_exc())
2023-01-08 14:28:57 +03:00
self.tlock.release()
2022-12-31 12:06:57 +03:00
return str(e)