InvokeAI/invokeai/app/api_app.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

153 lines
4.8 KiB
Python
Raw Normal View History

# Copyright (c) 2022 Kyle Schouviller (https://github.com/kyle0654)
import asyncio
from inspect import signature
2023-03-03 06:02:00 +00:00
import uvicorn
2023-05-01 20:27:44 +00:00
import invokeai.backend.util.logging as logger
from fastapi import FastAPI
2023-03-03 06:02:00 +00:00
from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from fastapi.staticfiles import StaticFiles
from fastapi_events.handlers.local import local_handler
2023-03-03 06:02:00 +00:00
from fastapi_events.middleware import EventHandlerASGIMiddleware
from pydantic.schema import schema
2023-03-03 06:02:00 +00:00
from .api.dependencies import ApiDependencies
from .api.routers import images, sessions, models
from .api.sockets import SocketIO
from .invocations.baseinvocation import BaseInvocation
from .services.config import InvokeAIWebConfig, get_invokeai_config
# Create the app
# TODO: create this all in a method so configuration/etc. can be passed in?
2023-03-03 06:02:00 +00:00
app = FastAPI(title="Invoke AI", docs_url=None, redoc_url=None)
# Add event handler
event_handler_id: int = id(app)
app.add_middleware(
EventHandlerASGIMiddleware,
2023-03-03 06:02:00 +00:00
handlers=[
local_handler
], # TODO: consider doing this in services to support different configurations
middleware_id=event_handler_id,
)
socket_io = SocketIO(app)
web_config = {}
2023-03-03 06:02:00 +00:00
# Add startup event to load dependencies
2023-03-03 06:02:00 +00:00
@app.on_event("startup")
async def startup_event():
ApiDependencies.initialize(
config=web_config, event_handler_id=event_handler_id, logger=logger
)
2023-03-03 06:02:00 +00:00
# Shut down threads
2023-03-03 06:02:00 +00:00
@app.on_event("shutdown")
async def shutdown_event():
ApiDependencies.shutdown()
2023-03-03 06:02:00 +00:00
# Include all routers
# TODO: REMOVE
# app.include_router(
# invocation.invocation_router,
# prefix = '/api')
2023-03-03 06:02:00 +00:00
app.include_router(sessions.session_router, prefix="/api")
app.include_router(images.images_router, prefix="/api")
app.include_router(models.models_router, prefix="/api")
# Build a custom OpenAPI to include all outputs
# TODO: can outputs be included on metadata of invocation schemas somehow?
def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
2023-03-03 06:02:00 +00:00
title=app.title,
description="An API for invoking AI image operations",
version="1.0.0",
routes=app.routes,
)
# Add all outputs
all_invocations = BaseInvocation.get_invocations()
output_types = set()
output_type_titles = dict()
for invoker in all_invocations:
output_type = signature(invoker.invoke).return_annotation
output_types.add(output_type)
output_schemas = schema(output_types, ref_prefix="#/components/schemas/")
2023-03-03 06:02:00 +00:00
for schema_key, output_schema in output_schemas["definitions"].items():
openapi_schema["components"]["schemas"][schema_key] = output_schema
# TODO: note that we assume the schema_key here is the TYPE.__name__
# This could break in some cases, figure out a better way to do it
2023-03-03 06:02:00 +00:00
output_type_titles[schema_key] = output_schema["title"]
# Add a reference to the output type to additionalProperties of the invoker schema
for invoker in all_invocations:
invoker_name = invoker.__name__
output_type = signature(invoker.invoke).return_annotation
output_type_title = output_type_titles[output_type.__name__]
invoker_schema = openapi_schema["components"]["schemas"][invoker_name]
2023-03-03 06:02:00 +00:00
outputs_ref = {"$ref": f"#/components/schemas/{output_type_title}"}
invoker_schema["output"] = outputs_ref
app.openapi_schema = openapi_schema
return app.openapi_schema
2023-03-03 06:02:00 +00:00
app.openapi = custom_openapi
# Override API doc favicons
2023-03-03 06:02:00 +00:00
app.mount("/static", StaticFiles(directory="static/dream_web"), name="static")
@app.get("/docs", include_in_schema=False)
def overridden_swagger():
2023-03-03 06:02:00 +00:00
return get_swagger_ui_html(
openapi_url=app.openapi_url,
title=app.title,
2023-03-03 06:02:00 +00:00
swagger_favicon_url="/static/favicon.ico",
)
2023-03-03 06:02:00 +00:00
@app.get("/redoc", include_in_schema=False)
def overridden_redoc():
2023-03-03 06:02:00 +00:00
return get_redoc_html(
openapi_url=app.openapi_url,
title=app.title,
2023-03-03 06:02:00 +00:00
redoc_favicon_url="/static/favicon.ico",
)
2023-03-03 06:02:00 +00:00
def invoke_api():
# parse command-line settings, environment and the init file
# (this is a module global)
global web_config
web_config = get_invokeai_config(InvokeAIWebConfig)
app.add_middleware(
CORSMiddleware,
allow_origins=web_config.allow_origins,
allow_credentials=web_config.allow_credentials,
allow_methods=web_config.allow_methods,
allow_headers=web_config.allow_headers,
)
# Start our own event loop for eventing usage
loop = asyncio.new_event_loop()
config = uvicorn.Config(app=app, host=web_config.host, port=web_config.port, loop=loop)
2023-03-03 06:02:00 +00:00
# Use access_log to turn off logging
server = uvicorn.Server(config)
loop.run_until_complete(server.serve())
if __name__ == "__main__":
invoke_api()