Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

整理: 設定機能を API Router でモジュール化 #1158

Merged
merged 6 commits into from
Apr 14, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 12 additions & 53 deletions run.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

import soundfile
import uvicorn
from fastapi import Body, Depends, FastAPI, Form, HTTPException
from fastapi import Body, Depends, FastAPI, HTTPException
from fastapi import Path as FAPath
from fastapi import Query, Request, Response
from fastapi.middleware.cors import CORSMiddleware
Expand All @@ -31,6 +31,11 @@
from starlette.responses import FileResponse

from voicevox_engine import __version__
from voicevox_engine.app.dependencies import (
check_disabled_mutable_api,
deprecated_mutable_api,
)
from voicevox_engine.app.routers import setting
from voicevox_engine.cancellable_engine import CancellableEngine
from voicevox_engine.core.core_adapter import CoreAdapter
from voicevox_engine.core.core_initializer import initialize_cores
Expand Down Expand Up @@ -73,7 +78,7 @@
from voicevox_engine.preset.Preset import Preset
from voicevox_engine.preset.PresetError import PresetError
from voicevox_engine.preset.PresetManager import PresetManager
from voicevox_engine.setting.Setting import CorsPolicyMode, Setting
from voicevox_engine.setting.Setting import CorsPolicyMode
from voicevox_engine.setting.SettingLoader import USER_SETTING_PATH, SettingHandler
from voicevox_engine.tts_pipeline.kana_converter import create_kana, parse_kana
from voicevox_engine.tts_pipeline.tts_engine import (
Expand Down Expand Up @@ -219,13 +224,8 @@ async def block_origin_middleware(
status_code=403, content={"detail": "Origin not allowed"}
)

# 許可されていないAPIを無効化する
async def check_disabled_mutable_api() -> None:
if disable_mutable_api:
raise HTTPException(
status_code=403,
detail="エンジンの静的なデータを変更するAPIは無効化されています",
)
if disable_mutable_api:
deprecated_mutable_api.enable = False

engine_manifest_data = EngineManifestLoader(
engine_root() / "engine_manifest.json", engine_root()
Expand Down Expand Up @@ -1307,52 +1307,11 @@ async def validate_kana(
detail=ParseKanaBadRequest(err).dict(),
)

@app.get("/setting", response_class=Response, tags=["設定"])
def setting_get(request: Request) -> Response:
"""
設定ページを返します。
"""
settings = setting_loader.load()

brand_name = engine_manifest_data.brand_name
cors_policy_mode = settings.cors_policy_mode
allow_origin = settings.allow_origin

if allow_origin is None:
allow_origin = ""

return setting_ui_template.TemplateResponse(
"ui.html",
{
"request": request,
"brand_name": brand_name,
"cors_policy_mode": cors_policy_mode.value,
"allow_origin": allow_origin,
},
app.include_router(
setting.generate_router(
setting_loader, engine_manifest_data, setting_ui_template
)

@app.post(
"/setting",
response_class=Response,
tags=["設定"],
dependencies=[Depends(check_disabled_mutable_api)],
)
def setting_post(
cors_policy_mode: CorsPolicyMode = Form(), # noqa
allow_origin: str | None = Form(default=None), # noqa
) -> Response:
"""
設定を更新します。
"""
settings = Setting(
cors_policy_mode=cors_policy_mode,
allow_origin=allow_origin,
)

# 更新した設定へ上書き
setting_loader.save(settings)

return Response(status_code=204)

# BaseLibraryInfo/VvlibManifestモデルはAPIとして表には出ないが、エディタ側で利用したいので、手動で追加する
# ref: https://fastapi.tiangolo.com/advanced/extending-openapi/#modify-the-openapi-schema
Expand Down
Empty file added voicevox_engine/app/__init__.py
Empty file.
21 changes: 21 additions & 0 deletions voicevox_engine/app/dependencies.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from dataclasses import dataclass

from fastapi import HTTPException


# 許可されていないAPIを無効化する
@dataclass
class MutableAPI:
enable: bool = True


# FIXME: グローバル変数が複数ファイルに分散しているため、DI 等で局所化する
deprecated_mutable_api = MutableAPI()


async def check_disabled_mutable_api() -> None:
if not deprecated_mutable_api.enable:
raise HTTPException(
status_code=403,
detail="エンジンの静的なデータを変更するAPIは無効化されています",
)
Empty file.
68 changes: 68 additions & 0 deletions voicevox_engine/app/routers/setting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
"""設定機能を提供する API Router"""

from fastapi import APIRouter, Depends, Form, Request, Response
from fastapi.templating import Jinja2Templates

from voicevox_engine.engine_manifest.EngineManifest import EngineManifest
from voicevox_engine.setting.Setting import CorsPolicyMode, Setting
from voicevox_engine.setting.SettingLoader import SettingHandler

from ..dependencies import check_disabled_mutable_api


def generate_router(
setting_loader: SettingHandler,
engine_manifest_data: EngineManifest,
setting_ui_template: Jinja2Templates,
) -> APIRouter:
"""設定 API Router を生成する"""
router = APIRouter()

@router.get("/setting", response_class=Response, tags=["設定"])
def setting_get(request: Request) -> Response:
"""
設定ページを返します。
"""
settings = setting_loader.load()

brand_name = engine_manifest_data.brand_name
cors_policy_mode = settings.cors_policy_mode
allow_origin = settings.allow_origin

if allow_origin is None:
allow_origin = ""

return setting_ui_template.TemplateResponse(
"ui.html",
{
"request": request,
"brand_name": brand_name,
"cors_policy_mode": cors_policy_mode.value,
"allow_origin": allow_origin,
},
)

@router.post(
"/setting",
response_class=Response,
tags=["設定"],
dependencies=[Depends(check_disabled_mutable_api)],
)
def setting_post(
cors_policy_mode: CorsPolicyMode = Form(), # noqa
allow_origin: str | None = Form(default=None), # noqa
) -> Response:
"""
設定を更新します。
"""
settings = Setting(
cors_policy_mode=cors_policy_mode,
allow_origin=allow_origin,
)

# 更新した設定へ上書き
setting_loader.save(settings)

return Response(status_code=204)

return router
Loading