voice-changer/server/restapi/MMVC_Rest.py

113 lines
4.2 KiB
Python
Raw Normal View History

2023-05-18 18:59:13 +03:00
import os
import sys
2023-04-27 17:38:25 +03:00
from fastapi import FastAPI, Request, Response, HTTPException
2022-12-31 12:27:38 +03:00
from fastapi.routing import APIRoute
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
2023-04-27 17:38:25 +03:00
from fastapi.exceptions import RequestValidationError
2022-12-31 12:27:38 +03:00
from typing import Callable
2023-08-14 05:23:53 +03:00
from mods.log_control import VoiceChangaerLogger
2022-12-31 12:27:38 +03:00
from voice_changer.VoiceChangerManager import VoiceChangerManager
from restapi.MMVC_Rest_Hello import MMVC_Rest_Hello
from restapi.MMVC_Rest_VoiceChanger import MMVC_Rest_VoiceChanger
2022-12-31 12:56:23 +03:00
from restapi.MMVC_Rest_Fileuploader import MMVC_Rest_Fileuploader
2023-11-04 08:14:18 +03:00
from const import MODEL_DIR_STATIC, UPLOAD_DIR, getFrontendPath, TMP_DIR
2023-05-28 21:29:29 +03:00
from voice_changer.utils.VoiceChangerParams import VoiceChangerParams
2022-12-31 14:25:28 +03:00
2023-08-14 05:23:53 +03:00
logger = VoiceChangaerLogger.get_instance().getLogger()
2022-12-31 14:25:28 +03:00
2022-12-31 12:27:38 +03:00
class ValidationErrorLoggingRoute(APIRoute):
def get_route_handler(self) -> Callable:
original_route_handler = super().get_route_handler()
async def custom_route_handler(request: Request) -> Response:
try:
return await original_route_handler(request)
2023-05-07 23:51:24 +03:00
except RequestValidationError as exc: # type: ignore
2022-12-31 12:27:38 +03:00
print("Exception", request.url, str(exc))
body = await request.body()
detail = {"errors": exc.errors(), "body": body.decode()}
raise HTTPException(status_code=422, detail=detail)
return custom_route_handler
2023-02-14 23:02:51 +03:00
2022-12-31 12:27:38 +03:00
class MMVC_Rest:
2023-04-27 17:38:25 +03:00
_instance = None
2022-12-31 12:27:38 +03:00
@classmethod
2023-05-28 21:29:29 +03:00
def get_instance(
cls,
voiceChangerManager: VoiceChangerManager,
voiceChangerParams: VoiceChangerParams,
):
2023-04-27 17:38:25 +03:00
if cls._instance is None:
2023-08-14 05:23:53 +03:00
logger.info("[Voice Changer] MMVC_Rest initializing...")
2022-12-31 12:27:38 +03:00
app_fastapi = FastAPI()
app_fastapi.router.route_class = ValidationErrorLoggingRoute
app_fastapi.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app_fastapi.mount(
2023-04-27 17:38:25 +03:00
"/front",
StaticFiles(directory=f"{getFrontendPath()}", html=True),
name="static",
)
2022-12-31 12:27:38 +03:00
app_fastapi.mount(
2023-04-27 17:38:25 +03:00
"/trainer",
StaticFiles(directory=f"{getFrontendPath()}", html=True),
name="static",
)
2022-12-31 12:27:38 +03:00
app_fastapi.mount(
2023-04-27 17:38:25 +03:00
"/recorder",
StaticFiles(directory=f"{getFrontendPath()}", html=True),
name="static",
)
2023-11-04 08:14:18 +03:00
app_fastapi.mount("/tmp", StaticFiles(directory=f"{TMP_DIR}"), name="static")
app_fastapi.mount("/upload_dir", StaticFiles(directory=f"{UPLOAD_DIR}"), name="static")
2023-12-02 20:50:51 +03:00
try:
app_fastapi.mount("/model_dir_static", StaticFiles(directory=f"{MODEL_DIR_STATIC}"), name="static")
except Exception as e:
print("Locating model_dir_static failed", e)
2023-05-18 18:59:13 +03:00
if sys.platform.startswith("darwin"):
p1 = os.path.dirname(sys._MEIPASS)
p2 = os.path.dirname(p1)
p3 = os.path.dirname(p2)
2023-05-28 21:29:29 +03:00
model_dir = os.path.join(p3, voiceChangerParams.model_dir)
2023-05-18 18:59:13 +03:00
print("mac model_dir:", model_dir)
app_fastapi.mount(
2023-05-28 21:29:29 +03:00
f"/{voiceChangerParams.model_dir}",
StaticFiles(directory=model_dir),
name="static",
2023-05-18 18:59:13 +03:00
)
else:
app_fastapi.mount(
2023-05-28 21:29:29 +03:00
f"/{voiceChangerParams.model_dir}",
StaticFiles(directory=voiceChangerParams.model_dir),
name="static",
2023-05-18 18:59:13 +03:00
)
2022-12-31 12:27:38 +03:00
restHello = MMVC_Rest_Hello()
app_fastapi.include_router(restHello.router)
restVoiceChanger = MMVC_Rest_VoiceChanger(voiceChangerManager)
app_fastapi.include_router(restVoiceChanger.router)
2022-12-31 12:56:23 +03:00
fileUploader = MMVC_Rest_Fileuploader(voiceChangerManager)
app_fastapi.include_router(fileUploader.router)
2022-12-31 12:27:38 +03:00
cls._instance = app_fastapi
2023-08-14 05:23:53 +03:00
logger.info("[Voice Changer] MMVC_Rest initializing... done.")
2022-12-31 12:27:38 +03:00
return cls._instance
return cls._instance