├── stable_diffusion_api ├── __init__.py ├── api │ ├── __init__.py │ ├── tests │ │ ├── __init__.py │ │ ├── test_in_memory_app.py │ │ ├── test_redis_app.py │ │ ├── test_e2e.py │ │ ├── base.py │ │ └── utils.py │ ├── utils │ │ ├── __init__.py │ │ └── pyfa_converter.py │ ├── redis_app.py │ ├── in_memory_app.py │ └── base.py ├── engine │ ├── __init__.py │ ├── repos │ │ ├── __init__.py │ │ ├── key_value_repo.py │ │ ├── blob_repo.py │ │ ├── messaging_repo.py │ │ └── user_repo.py │ ├── services │ │ ├── __init__.py │ │ ├── event_service.py │ │ ├── task_service.py │ │ ├── status_service.py │ │ └── runner_service.py │ ├── workers │ │ ├── __init__.py │ │ ├── utils.py │ │ ├── in_memory_worker.py │ │ └── redis_worker.py │ └── utils.py └── models │ ├── __init__.py │ ├── blob.py │ ├── results.py │ ├── task.py │ ├── user.py │ ├── events.py │ └── params.py ├── .gitignore ├── deployment ├── run_tests.sh ├── run_redis_app.sh └── run_redis_worker.sh ├── Makefile ├── .env.test ├── .env.example ├── Dockerfile ├── conftest.py ├── pyproject.toml ├── docker-compose.yaml ├── .github └── workflows │ └── ci.yaml ├── README.md ├── colab_runner.ipynb ├── LICENSE └── openapi.yml /stable_diffusion_api/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /stable_diffusion_api/api/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /stable_diffusion_api/api/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /stable_diffusion_api/api/utils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /stable_diffusion_api/engine/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /stable_diffusion_api/models/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /stable_diffusion_api/engine/repos/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /stable_diffusion_api/engine/services/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /stable_diffusion_api/engine/workers/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .env 2 | openapi.yml 3 | !openapi.yml/ 4 | .idea 5 | __pycache__ 6 | dump.rdb 7 | *.swp 8 | -------------------------------------------------------------------------------- /deployment/run_tests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | poetry install --with=test 3 | poetry run pytest -m e2e --e2e -------------------------------------------------------------------------------- /deployment/run_redis_app.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | poetry run uvicorn stable_diffusion_api.api.redis_app:app --host 0.0.0.0 -------------------------------------------------------------------------------- /deployment/run_redis_worker.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | poetry run python -m stable_diffusion_api.engine.workers.redis_worker -------------------------------------------------------------------------------- /stable_diffusion_api/models/blob.py: -------------------------------------------------------------------------------- 1 | from typing_extensions import TypeAlias 2 | 3 | BlobUrl: TypeAlias = str 4 | BlobToken: TypeAlias = str 5 | BlobId: TypeAlias = str 6 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | test: 2 | docker-compose --env-file .env.test up --abort-on-container-exit --exit-code-from e2e_tests --force-recreate --build api redis_worker e2e_tests 3 | 4 | run: 5 | docker-compose up --abort-on-container-exit --force-recreate --build api redis_worker 6 | -------------------------------------------------------------------------------- /stable_diffusion_api/models/results.py: -------------------------------------------------------------------------------- 1 | import pydantic 2 | 3 | from stable_diffusion_api.models.blob import BlobUrl 4 | from stable_diffusion_api.models.params import ParamsUnion 5 | 6 | 7 | class GeneratedBlob(pydantic.BaseModel): 8 | blob_url: BlobUrl 9 | parameters_used: ParamsUnion 10 | -------------------------------------------------------------------------------- /.env.test: -------------------------------------------------------------------------------- 1 | SECRET_KEY=30a1590ae015eac4908095904d6dc0e086a61d1a6acd6058f0560adfe5b253e5 2 | PRINT_LINK_WITH_TOKEN= 3 | BASE_URL=http://localhost:8000 4 | ENABLE_PUBLIC_ACCESS=1 5 | ENABLE_SIGNUP= 6 | REDIS_HOST=redis 7 | REDIS_PORT=6379 8 | REDIS_PASSWORD=jdfhefo1e1928h1o2389r123fdjq92edh12pd12ed2d12d 9 | HUGGINGFACE_TOKEN= 10 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | SECRET_KEY=30a1590ae015eac4908095904d6dc0e086a61d1a6acd6058f0560adfe5b253e5 2 | PRINT_LINK_WITH_TOKEN=1 3 | ENABLE_PUBLIC_ACCESS=0 4 | ENABLE_SIGNUP=0 5 | BASE_URL=http://localhost:8000 6 | REDIS_HOST=redis 7 | REDIS_PORT=6379 8 | REDIS_PASSWORD=jdfhefo1e1928h1o2389r123fdjq92edh12pd12ed2d12d 9 | HUGGINGFACE_TOKEN=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 10 | -------------------------------------------------------------------------------- /stable_diffusion_api/models/task.py: -------------------------------------------------------------------------------- 1 | import uuid 2 | 3 | import pydantic 4 | from typing_extensions import TypeAlias 5 | 6 | from stable_diffusion_api.models.params import ParamsUnion 7 | from stable_diffusion_api.models.user import User 8 | 9 | TaskId: TypeAlias = str 10 | 11 | 12 | class Task(pydantic.BaseModel): 13 | parameters: ParamsUnion 14 | 15 | user: User 16 | task_id: TaskId = pydantic.Field(default_factory=lambda: TaskId(uuid.uuid4())) 17 | -------------------------------------------------------------------------------- /stable_diffusion_api/models/user.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | from typing_extensions import TypeAlias 3 | 4 | import pydantic 5 | 6 | Username: TypeAlias = str 7 | SessionId: TypeAlias = str 8 | 9 | DefaultUsername: Username = "all" 10 | 11 | 12 | class AuthenticationError(Exception): 13 | pass 14 | 15 | 16 | class AuthToken(pydantic.BaseModel): 17 | access_token: str 18 | token_type: str 19 | 20 | 21 | class UserBase(pydantic.BaseModel): 22 | username: Username 23 | 24 | 25 | class User(UserBase): 26 | session_id: SessionId 27 | 28 | 29 | class UserInDB(UserBase): 30 | hashed_password: str 31 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.10 2 | 3 | # Configure Poetry 4 | ENV POETRY_VERSION=1.2.0 5 | ENV POETRY_HOME=/opt/poetry 6 | ENV POETRY_VENV=/opt/poetry-venv 7 | ENV POETRY_CACHE_DIR=/opt/.cache 8 | 9 | # Install poetry separated from system interpreter 10 | RUN python3 -m venv $POETRY_VENV \ 11 | && $POETRY_VENV/bin/pip install -U pip setuptools \ 12 | && $POETRY_VENV/bin/pip install poetry==${POETRY_VERSION} 13 | 14 | # Add `poetry` to PATH 15 | ENV PATH="${PATH}:${POETRY_VENV}/bin" 16 | 17 | WORKDIR /app 18 | 19 | # Install dependencies 20 | COPY poetry.lock pyproject.toml ./ 21 | RUN poetry install --no-root 22 | 23 | COPY . /app 24 | -------------------------------------------------------------------------------- /stable_diffusion_api/api/redis_app.py: -------------------------------------------------------------------------------- 1 | from stable_diffusion_api.api.base import AppConfig, create_app 2 | from stable_diffusion_api.engine.repos.blob_repo import RedisBlobRepo 3 | from stable_diffusion_api.engine.repos.key_value_repo import RedisKeyValueRepo 4 | from stable_diffusion_api.engine.repos.messaging_repo import RedisMessagingRepo 5 | from stable_diffusion_api.engine.repos.user_repo import RedisUserRepo 6 | 7 | app_config = AppConfig( 8 | blob_repo_class=RedisBlobRepo, 9 | messaging_repo_class=RedisMessagingRepo, 10 | user_repo_class=RedisUserRepo, 11 | key_value_repo_class=RedisKeyValueRepo, 12 | ) 13 | 14 | app = create_app(app_config) 15 | -------------------------------------------------------------------------------- /conftest.py: -------------------------------------------------------------------------------- 1 | # content of conftest.py 2 | 3 | import pytest 4 | import asyncio 5 | 6 | 7 | def pytest_addoption(parser): 8 | parser.addoption( 9 | "--e2e", action="store_true", default=False, help="run e2e e2e_tests" 10 | ) 11 | 12 | 13 | def pytest_collection_modifyitems(config, items): 14 | if config.getoption("--e2e"): 15 | # --e2e given in cli: do not skip e2e e2e_tests 16 | return 17 | skip_e2e = pytest.mark.skip(reason="need --e2e option to run") 18 | for item in items: 19 | if "e2e" in item.keywords: 20 | item.add_marker(skip_e2e) 21 | 22 | 23 | # override the scope of the event loop, by default it is function scoped 24 | @pytest.fixture(scope="session") 25 | def event_loop(): 26 | loop = asyncio.get_event_loop() 27 | yield loop 28 | loop.close() 29 | -------------------------------------------------------------------------------- /stable_diffusion_api/models/events.py: -------------------------------------------------------------------------------- 1 | from typing import Union, Literal 2 | 3 | import pydantic 4 | 5 | from stable_diffusion_api.models.results import GeneratedBlob 6 | from stable_diffusion_api.models.task import TaskId 7 | from stable_diffusion_api.models.user import SessionId 8 | 9 | 10 | class Event(pydantic.BaseModel): 11 | event_type: str 12 | 13 | task_id: TaskId 14 | 15 | 16 | class PendingEvent(Event): 17 | event_type: Literal['pending'] 18 | 19 | 20 | class StartedEvent(Event): 21 | event_type: Literal['started'] 22 | 23 | 24 | class AbortedEvent(Event): 25 | event_type: Literal['aborted'] 26 | 27 | reason: str 28 | 29 | 30 | class FinishedEvent(Event): 31 | event_type: Literal["finished"] 32 | 33 | result: GeneratedBlob 34 | 35 | 36 | EventUnion = Union[tuple(Event.__subclasses__())] # type: ignore 37 | -------------------------------------------------------------------------------- /stable_diffusion_api/api/tests/test_in_memory_app.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | 3 | import pytest 4 | from httpx import AsyncClient 5 | from asgi_lifespan import LifespanManager 6 | 7 | from stable_diffusion_api.api.tests.base import BaseTestApp 8 | 9 | from stable_diffusion_api.api.tests.utils import AsyncioTestClient, LocalAppClient 10 | from stable_diffusion_api.api.in_memory_app import fastapi_app 11 | from stable_diffusion_api.engine.workers.in_memory_worker import create_runner 12 | 13 | 14 | class TestInMemoryApp(BaseTestApp): 15 | _runner_task = None 16 | 17 | @classmethod 18 | def get_client(cls): 19 | loop = asyncio.get_event_loop() 20 | if cls._runner_task is None: 21 | cls._runner_task = loop.create_task(create_runner()) 22 | return LocalAppClient( 23 | AsyncClient(app=fastapi_app, base_url="http://testserver"), 24 | AsyncioTestClient(event_loop=loop, 25 | app=fastapi_app), 26 | LifespanManager(fastapi_app), 27 | ) 28 | -------------------------------------------------------------------------------- /stable_diffusion_api/engine/workers/utils.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import os 3 | from typing import Coroutine 4 | 5 | from stable_diffusion_api.models.task import Task 6 | 7 | 8 | def get_runner_coroutine(task_listener, runner_service) -> Coroutine[Task, None, None]: 9 | async def runner_loop(): 10 | try: 11 | async for task in task_listener.listen(): 12 | await runner_service.run_task(task) 13 | except Exception as e: 14 | print(f"Error running task: {e}") 15 | 16 | return runner_loop() 17 | 18 | 19 | def get_local_blob_repo_params(): 20 | # TODO move away from hosting blobs alongside the API 21 | # using an external image storage service is preferable, helps to avoid duplicating 22 | # the base blob url and encryption parameters in the api AND each runner for token generation 23 | base_url = os.environ.get("BASE_URL", "http://localhost:8000") 24 | return dict( 25 | base_blob_url=base_url + "/blob", 26 | secret_key=os.environ["SECRET_KEY"], 27 | algorithm="HS256", 28 | ) 29 | -------------------------------------------------------------------------------- /stable_diffusion_api/api/in_memory_app.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | 3 | from stable_diffusion_api.api.base import AppConfig, create_app 4 | from stable_diffusion_api.engine.repos.blob_repo import InMemoryBlobRepo 5 | from stable_diffusion_api.engine.repos.key_value_repo import InMemoryKeyValueRepo 6 | from stable_diffusion_api.engine.repos.messaging_repo import InMemoryMessagingRepo 7 | from stable_diffusion_api.engine.repos.user_repo import InMemoryUserRepo 8 | from stable_diffusion_api.engine.workers.in_memory_worker import create_runner 9 | 10 | app_config = AppConfig( 11 | blob_repo_class=InMemoryBlobRepo, 12 | messaging_repo_class=InMemoryMessagingRepo, 13 | user_repo_class=InMemoryUserRepo, 14 | key_value_repo_class=InMemoryKeyValueRepo, 15 | ) 16 | 17 | fastapi_app = create_app(app_config) 18 | 19 | 20 | _runner_task = None 21 | 22 | 23 | async def app(scope, receive, send): 24 | global _runner_task 25 | if _runner_task is None: 26 | loop = asyncio.get_event_loop() 27 | _runner_task = loop.create_task(create_runner()) 28 | await fastapi_app(scope, receive, send) 29 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "stable-diffusion-api" 3 | version = "0.1.0" 4 | description = "" 5 | authors = ["Rafael Irgolic "] 6 | license = "GNU Affero General Public License" 7 | readme = "README.md" 8 | packages = [{include = "stable_diffusion_api"}] 9 | 10 | [tool.poetry.dependencies] 11 | python = "^3.10" 12 | python-jose = "^3.3.0" 13 | PyYAML = "^6.0" 14 | requests = "^2.28.1" 15 | requests-toolbelt = "^0.10.0" 16 | fastapi = "^0.85.0" 17 | typing-extensions = "^4.4.0" 18 | passlib = "^1.7.4" 19 | redis = "^4.3.4" 20 | aioredis = "^2.0.1" 21 | python-multipart = "^0.0.5" 22 | uvicorn = "^0.18.3" 23 | diffusers = "0.6" 24 | pillow = "^9.2.0" 25 | torch = "^1.12.1" 26 | transformers = "^4.23.1" 27 | scipy = "^1.9.2" 28 | bcrypt = "^4.0.1" 29 | 30 | [tool.poetry.group.dev.dependencies] 31 | pyright = "^1.1.274" 32 | 33 | 34 | [tool.poetry.group.test.dependencies] 35 | pytest = "^7.1.3" 36 | pytest-asyncio = "^0.19.0" 37 | websockets = "^10.3" 38 | httpx = "^0.23.0" 39 | asgi-lifespan = ">=1.0.0,<2.0.0" 40 | 41 | [build-system] 42 | requires = ["poetry-core"] 43 | build-backend = "poetry.core.masonry.api" 44 | -------------------------------------------------------------------------------- /stable_diffusion_api/api/tests/test_redis_app.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | 4 | import pytest 5 | import redis 6 | from asgi_lifespan import LifespanManager 7 | from httpx import AsyncClient 8 | 9 | from stable_diffusion_api.api import redis_app 10 | from stable_diffusion_api.api.tests.base import BaseTestApp 11 | from stable_diffusion_api.api.tests.utils import AsyncioTestClient, LocalAppClient 12 | from stable_diffusion_api.engine.utils import load_redis 13 | from stable_diffusion_api.engine.workers.redis_worker import create_runner 14 | 15 | logger = logging.getLogger(__name__) 16 | 17 | try: 18 | r = load_redis() 19 | r.ping() 20 | except redis.exceptions.RedisError as e: 21 | logger.error(f"Redis is not available: {e}") 22 | pytest.skip(f"Could not connect to redis instance, skipping redis api tests", allow_module_level=True) 23 | 24 | 25 | class TestLiveRedisApp(BaseTestApp): 26 | _runner_task = None 27 | 28 | @classmethod 29 | def get_client(cls): 30 | loop = asyncio.get_event_loop() 31 | if cls._runner_task is None: 32 | cls._runner_task = loop.create_task(create_runner()) 33 | return LocalAppClient( 34 | AsyncClient(app=redis_app.app, base_url="http://testserver"), 35 | AsyncioTestClient(event_loop=loop, 36 | app=redis_app.app), 37 | LifespanManager(redis_app.app), 38 | ) 39 | -------------------------------------------------------------------------------- /stable_diffusion_api/engine/repos/key_value_repo.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from typing import Optional 3 | 4 | from stable_diffusion_api.engine.utils import get_redis 5 | 6 | 7 | class KeyValueRepo: 8 | def store(self, collection: str, key: str, value: str) -> None: 9 | raise NotImplementedError 10 | 11 | def retrieve(self, collection: str, key: str) -> Optional[str]: 12 | raise NotImplementedError 13 | 14 | def exists(self, collection: str, key: str) -> bool: 15 | raise NotImplementedError 16 | 17 | 18 | class InMemoryKeyValueRepo(KeyValueRepo): 19 | _store = defaultdict(dict) 20 | 21 | def store(self, collection: str, key: str, value: str) -> None: 22 | self._store[collection][key] = value 23 | 24 | def retrieve(self, collection: str, key: str) -> Optional[str]: 25 | return self._store[collection].get(key, None) 26 | 27 | def exists(self, collection: str, key: str) -> bool: 28 | return key in self._store[collection] 29 | 30 | 31 | class RedisKeyValueRepo(KeyValueRepo): 32 | def __init__(self): 33 | self.redis = get_redis() 34 | 35 | def store(self, collection: str, key: str, value: str) -> None: 36 | self.redis.hset(collection, key, value) 37 | 38 | def retrieve(self, collection: str, key: str) -> Optional[str]: 39 | v = self.redis.hget(collection, key) 40 | if v is None: 41 | return None 42 | return v.decode('utf-8') 43 | 44 | def exists(self, collection: str, key: str) -> bool: 45 | return self.redis.hexists(collection, key) 46 | -------------------------------------------------------------------------------- /stable_diffusion_api/api/tests/test_e2e.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import os 3 | from unittest import mock 4 | 5 | import pytest 6 | from httpx import AsyncClient 7 | from requests_toolbelt import sessions 8 | 9 | from stable_diffusion_api.api.tests.base import BaseTestApp 10 | from stable_diffusion_api.api.tests.utils import RemoteAppClient 11 | 12 | 13 | @pytest.mark.e2e 14 | class TestRedisAppE2E(BaseTestApp): 15 | @classmethod 16 | def get_client(cls): 17 | return RemoteAppClient( 18 | # sessions.BaseUrlSession(base_url=os.environ.get('API_URL', 'http://127.0.0.1:8000')) 19 | AsyncClient(base_url=os.environ.get('API_URL', 'http://127.0.0.1:8000')), 20 | ) 21 | 22 | @pytest.mark.asyncio 23 | async def test_cancel_sync_txt2img( 24 | self, 25 | client, 26 | websocket, 27 | dummy_txt2img_params, 28 | ): 29 | coro = client.get('/txt2img', params=dummy_txt2img_params) 30 | task = asyncio.create_task(coro) 31 | await asyncio.sleep(0.1) 32 | task.cancel() 33 | 34 | # check events 35 | await self.assert_websocket_received({ 36 | 'event_type': 'pending', 37 | 'task_id': mock.ANY, 38 | }, websocket) 39 | 40 | await self.assert_websocket_received({ 41 | 'event_type': 'started', 42 | 'task_id': mock.ANY, 43 | }, websocket) 44 | 45 | await self.assert_websocket_received({ 46 | 'event_type': 'aborted', 47 | 'task_id': mock.ANY, 48 | 'reason': 'Task cancelled by user', 49 | }, websocket) 50 | -------------------------------------------------------------------------------- /stable_diffusion_api/engine/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import typing 3 | 4 | import aioredis 5 | import pydantic 6 | import redis 7 | 8 | from stable_diffusion_api.models.user import SessionId 9 | 10 | T = typing.TypeVar('T', bound=pydantic.BaseModel) 11 | 12 | 13 | # redis 14 | 15 | 16 | def load_redis(): 17 | host = os.environ.get('REDIS_HOST', 'localhost') 18 | port = int(os.environ.get('REDIS_PORT', 6379)) 19 | password = os.environ.get('REDIS_PASSWORD', None) 20 | r = redis.Redis( 21 | host=host, 22 | port=port, 23 | password=password, 24 | ) 25 | r.ping() 26 | return r 27 | 28 | 29 | redis_client = None 30 | 31 | 32 | def get_redis(): 33 | global redis_client 34 | if redis_client is None: 35 | redis_client = load_redis() 36 | return redis_client 37 | 38 | 39 | aioredis_client = None 40 | 41 | 42 | def load_aioredis(): 43 | host = os.environ.get('REDIS_HOST', 'localhost') 44 | port = int(os.environ.get('REDIS_PORT', 6379)) 45 | password = os.environ.get('REDIS_PASSWORD', None) 46 | return aioredis.Redis( 47 | host=host, 48 | port=port, 49 | password=password, 50 | ) 51 | 52 | 53 | def get_aioredis(): 54 | global aioredis_client 55 | if aioredis_client is None: 56 | aioredis_client = load_aioredis() 57 | return aioredis_client 58 | 59 | 60 | # serialize/deserialize session id with events 61 | 62 | 63 | def _serialize_message(session_id: SessionId, model: pydantic.BaseModel) -> str: 64 | return "{" + f'"{session_id}": {model.json()}' + "}" 65 | 66 | 67 | def _deserialize_message(message: str, model_class: typing.Type[T]) -> tuple[SessionId, T]: 68 | session_id, event = next(iter(pydantic.parse_raw_as(dict[SessionId, model_class], message).items())) 69 | return session_id, event 70 | -------------------------------------------------------------------------------- /stable_diffusion_api/engine/services/event_service.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from typing import AsyncIterator, Optional 3 | 4 | import pydantic 5 | 6 | from stable_diffusion_api.engine.repos.blob_repo import BlobRepo 7 | from stable_diffusion_api.engine.repos.key_value_repo import KeyValueRepo 8 | from stable_diffusion_api.engine.repos.messaging_repo import MessagingRepo 9 | from stable_diffusion_api.engine.services.status_service import StatusService 10 | from stable_diffusion_api.engine.utils import _serialize_message, _deserialize_message 11 | from stable_diffusion_api.models.events import EventUnion 12 | from stable_diffusion_api.models.user import SessionId 13 | 14 | logger = logging.getLogger(__name__) 15 | 16 | 17 | class EventService: 18 | def __init__( 19 | self, 20 | messaging_repo: MessagingRepo, 21 | status_service: StatusService, 22 | ): 23 | self.messaging_repo = messaging_repo 24 | self.status_service = status_service 25 | 26 | def send_event(self, session_id: SessionId, event: EventUnion): 27 | # store latest task event 28 | self.status_service.store_event(event) 29 | # serialize and push session_id + event 30 | msg = _serialize_message(session_id, event) 31 | self.messaging_repo.publish('event', msg) 32 | 33 | 34 | class EventListener: 35 | def __init__( 36 | self, 37 | messaging_repo: MessagingRepo, 38 | ): 39 | self.messaging_repo = messaging_repo 40 | 41 | async def initialize(self): 42 | await self.messaging_repo.subscribe('event') 43 | 44 | async def listen(self) -> AsyncIterator[tuple[SessionId, EventUnion]]: 45 | async for data in self.messaging_repo.listen(): 46 | if data is None: 47 | continue 48 | yield _deserialize_message(data, EventUnion) 49 | -------------------------------------------------------------------------------- /stable_diffusion_api/engine/services/task_service.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from typing import AsyncIterator 3 | 4 | import pydantic 5 | 6 | from stable_diffusion_api.engine.repos.messaging_repo import MessagingRepo 7 | from stable_diffusion_api.engine.services.event_service import EventService 8 | from stable_diffusion_api.engine.services.status_service import StatusService 9 | from stable_diffusion_api.models.events import PendingEvent 10 | from stable_diffusion_api.models.task import Task 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | 15 | class TaskService: 16 | def __init__( 17 | self, 18 | messaging_repo: MessagingRepo, 19 | event_service: EventService, 20 | status_service: StatusService, 21 | ): 22 | self.messaging_repo = messaging_repo 23 | self.event_service = event_service 24 | self.status_service = status_service 25 | 26 | def push_task(self, task: Task) -> None: 27 | # register task 28 | self.status_service.store_task(task) 29 | # advertise task pending status 30 | self.event_service.send_event( 31 | task.user.session_id, 32 | PendingEvent( 33 | event_type="pending", 34 | task_id=task.task_id, 35 | ) 36 | ) 37 | # push task 38 | self.messaging_repo.push('task_queue', task.json()) 39 | 40 | 41 | class TaskListener: 42 | def __init__( 43 | self, 44 | messaging_repo: MessagingRepo, 45 | ): 46 | self.messaging_repo = messaging_repo 47 | 48 | async def get_task(self) -> Task: 49 | task_json = await self.messaging_repo.pop('task_queue') 50 | return Task.parse_raw(task_json) 51 | 52 | async def listen(self) -> AsyncIterator[Task]: 53 | while True: 54 | yield await self.get_task() 55 | -------------------------------------------------------------------------------- /stable_diffusion_api/engine/services/status_service.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | import pydantic 4 | 5 | from stable_diffusion_api.engine.repos.key_value_repo import KeyValueRepo 6 | from stable_diffusion_api.models.events import EventUnion 7 | from stable_diffusion_api.models.task import TaskId, Task 8 | 9 | 10 | class StatusService: 11 | def __init__( 12 | self, 13 | key_value_repo: KeyValueRepo 14 | ): 15 | self.key_value_repo = key_value_repo 16 | 17 | def store_task(self, task: Task) -> None: 18 | self.key_value_repo.store('task', task.task_id, task.json()) 19 | 20 | def get_task(self, task_id: TaskId) -> Optional[Task]: 21 | task_json = self.key_value_repo.retrieve('task', task_id) 22 | if task_json is None: 23 | return None 24 | return pydantic.parse_raw_as(Task, task_json) 25 | 26 | def store_event(self, event: EventUnion) -> None: 27 | if not self.key_value_repo.exists('task', event.task_id): 28 | raise ValueError(f"Task {event.task_id} does not exist") 29 | # store latest task event 30 | self.key_value_repo.store('task_event', event.task_id, event.json()) 31 | 32 | def get_latest_event(self, task_id: TaskId) -> Optional[EventUnion]: 33 | # retrieve latest task event 34 | event_json = self.key_value_repo.retrieve('task_event', task_id) 35 | if event_json is None: 36 | return None 37 | return pydantic.parse_raw_as(EventUnion, event_json) 38 | 39 | def cancel_task(self, task_id: TaskId) -> None: 40 | task = self.get_task(task_id) 41 | if task is None: 42 | raise ValueError(f"Task {task_id} does not exist") 43 | self.key_value_repo.store('task_cancelled', task_id, 'true') 44 | 45 | def is_task_cancelled(self, task_id: TaskId) -> bool: 46 | return self.key_value_repo.exists('task_cancelled', task_id) 47 | -------------------------------------------------------------------------------- /stable_diffusion_api/engine/workers/in_memory_worker.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | import os 4 | import sys 5 | from typing import Coroutine 6 | 7 | from stable_diffusion_api.engine.repos.blob_repo import InMemoryBlobRepo 8 | from stable_diffusion_api.engine.repos.key_value_repo import InMemoryKeyValueRepo 9 | from stable_diffusion_api.engine.repos.messaging_repo import InMemoryMessagingRepo 10 | from stable_diffusion_api.engine.services.event_service import EventService 11 | from stable_diffusion_api.engine.services.runner_service import RunnerService 12 | from stable_diffusion_api.engine.services.status_service import StatusService 13 | from stable_diffusion_api.engine.services.task_service import TaskListener 14 | from stable_diffusion_api.engine.workers.utils import get_runner_coroutine, get_local_blob_repo_params 15 | from stable_diffusion_api.models.task import Task 16 | 17 | logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) 18 | logger = logging.getLogger(__name__) 19 | 20 | 21 | def create_runner() -> Coroutine[Task, None, None]: 22 | logger.info("Starting in memory worker") 23 | 24 | # instantiate redis messaging repo 25 | messaging_repo = InMemoryMessagingRepo() 26 | 27 | # instantiate runner service 28 | blob_repo = InMemoryBlobRepo(**get_local_blob_repo_params()) 29 | key_value_repo = InMemoryKeyValueRepo() 30 | status_service = StatusService( 31 | key_value_repo=key_value_repo, 32 | ) 33 | event_service = EventService( 34 | messaging_repo=messaging_repo, 35 | status_service=status_service, 36 | ) 37 | runner_service = RunnerService( 38 | blob_repo=blob_repo, 39 | status_service=status_service, 40 | event_service=event_service, 41 | ) 42 | 43 | # listen for tasks 44 | task_listener = TaskListener( 45 | messaging_repo=messaging_repo, 46 | ) 47 | 48 | return get_runner_coroutine(task_listener, runner_service) 49 | -------------------------------------------------------------------------------- /stable_diffusion_api/engine/workers/redis_worker.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | import os 4 | import sys 5 | from typing import Coroutine 6 | 7 | from stable_diffusion_api.engine.repos.blob_repo import RedisBlobRepo 8 | from stable_diffusion_api.engine.repos.key_value_repo import RedisKeyValueRepo 9 | from stable_diffusion_api.engine.repos.messaging_repo import RedisMessagingRepo 10 | from stable_diffusion_api.engine.services.event_service import EventService 11 | from stable_diffusion_api.engine.services.runner_service import RunnerService 12 | from stable_diffusion_api.engine.services.status_service import StatusService 13 | from stable_diffusion_api.engine.services.task_service import TaskListener 14 | from stable_diffusion_api.engine.workers.utils import get_runner_coroutine, get_local_blob_repo_params 15 | from stable_diffusion_api.models.task import Task 16 | 17 | logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) 18 | logger = logging.getLogger(__name__) 19 | 20 | 21 | def create_runner() -> Coroutine[Task, None, None]: 22 | logger.info("Starting redis worker") 23 | 24 | # instantiate redis messaging repo 25 | messaging_repo = RedisMessagingRepo() 26 | 27 | # instantiate runner service 28 | blob_repo = RedisBlobRepo(**get_local_blob_repo_params()) 29 | key_value_repo = RedisKeyValueRepo() 30 | status_service = StatusService( 31 | key_value_repo=key_value_repo, 32 | ) 33 | event_service = EventService( 34 | messaging_repo=messaging_repo, 35 | status_service=status_service, 36 | ) 37 | runner_service = RunnerService( 38 | blob_repo=blob_repo, 39 | status_service=status_service, 40 | event_service=event_service, 41 | ) 42 | 43 | # listen for tasks 44 | task_listener = TaskListener( 45 | messaging_repo=messaging_repo, 46 | ) 47 | 48 | return get_runner_coroutine(task_listener, runner_service) 49 | 50 | 51 | if __name__ == '__main__': 52 | loop = asyncio.get_event_loop() 53 | loop.run_until_complete(create_runner()) 54 | -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | 3 | services: 4 | redis: 5 | image: redis:6.2-alpine 6 | restart: always 7 | # expose: 8 | # - 6379 9 | ports: 10 | - "6379:6379" 11 | command: redis-server /app/deployment/redis.conf --stop-writes-on-bgsave-error no --loglevel debug --requirepass $REDIS_PASSWORD 12 | volumes: 13 | # - redis:/data 14 | - ./:/app 15 | api: 16 | build: . 17 | image: irgolic/stable-diffusion-api:latest 18 | depends_on: 19 | - redis 20 | # expose: 21 | # - 8000 22 | ports: 23 | - "8000:8000" 24 | environment: 25 | SECRET_KEY: $SECRET_KEY 26 | REDIS_HOST: redis 27 | REDIS_PASSWORD: $REDIS_PASSWORD 28 | REDIS_PORT: $REDIS_PORT 29 | PRINT_LINK_WITH_TOKEN: $PRINT_LINK_WITH_TOKEN 30 | ENABLE_PUBLIC_ACCESS: $ENABLE_PUBLIC_ACCESS 31 | ENABLE_SIGNUP: $ENABLE_SIGNUP 32 | links: 33 | - redis 34 | volumes: 35 | - ./:/app 36 | command: deployment/run_redis_app.sh 37 | redis_worker: 38 | image: irgolic/stable-diffusion-api:latest 39 | deploy: 40 | replicas: 5 41 | depends_on: 42 | - redis 43 | environment: 44 | REDIS_HOST: redis 45 | SECRET_KEY: $SECRET_KEY 46 | HUGGINGFACE_TOKEN: $HUGGINGFACE_TOKEN 47 | REDIS_PASSWORD: $REDIS_PASSWORD 48 | REDIS_PORT: $REDIS_PORT 49 | links: 50 | - redis 51 | volumes: 52 | - ./:/app 53 | - ~/.cache/huggingface:/root/.cache/huggingface 54 | entrypoint: deployment/run_redis_worker.sh 55 | e2e_tests: 56 | image: irgolic/stable-diffusion-api:latest 57 | depends_on: 58 | - redis 59 | - api 60 | - redis_worker 61 | environment: 62 | API_URL: http://api:8000 63 | SECRET_KEY: $SECRET_KEY 64 | REDIS_HOST: redis 65 | REDIS_PASSWORD: $REDIS_PASSWORD 66 | REDIS_PORT: $REDIS_PORT 67 | PRINT_LINK_WITH_TOKEN: $PRINT_LINK_WITH_TOKEN 68 | ENABLE_PUBLIC_ACCESS: $ENABLE_PUBLIC_ACCESS 69 | ENABLE_SIGNUP: $ENABLE_SIGNUP 70 | links: 71 | - redis 72 | - api 73 | volumes: 74 | - ./:/app 75 | command: deployment/run_tests.sh 76 | -------------------------------------------------------------------------------- /stable_diffusion_api/engine/repos/blob_repo.py: -------------------------------------------------------------------------------- 1 | import os 2 | import typing 3 | import uuid 4 | from typing import Union, Optional 5 | 6 | from jose import jwt 7 | import jose.exceptions 8 | from typing_extensions import TypeAlias 9 | 10 | from stable_diffusion_api.engine.utils import get_redis 11 | from stable_diffusion_api.models.blob import BlobUrl, BlobId, BlobToken 12 | from stable_diffusion_api.models.user import Username 13 | import requests 14 | 15 | 16 | class BlobRepo: 17 | def put_blob(self, blob: bytes) -> BlobUrl: 18 | raise NotImplementedError 19 | 20 | def get_blob(self, blob_url: BlobUrl) -> Optional[bytes]: 21 | return requests.get(blob_url).content 22 | 23 | 24 | class LocalBlobRepo(BlobRepo): 25 | def __init__( 26 | self, 27 | base_blob_url: str, 28 | secret_key: str, 29 | algorithm: str, 30 | ): 31 | self.base_blob_url = base_blob_url 32 | self.secret_key = secret_key 33 | self.algorithm = algorithm 34 | 35 | def __make_token(self, blob_id: BlobId) -> BlobToken: 36 | return BlobToken(jwt.encode({"blob_id": blob_id}, 37 | self.secret_key, 38 | algorithm=self.algorithm)) 39 | 40 | def __verify_token(self, blob_token: BlobToken) -> Optional[BlobId]: 41 | try: 42 | return BlobId(jwt.decode(blob_token, 43 | self.secret_key, 44 | algorithms=[self.algorithm])["blob_id"]) 45 | except jose.exceptions.JWTError: 46 | return None 47 | 48 | def __make_url(self, blob_id: BlobId) -> BlobUrl: 49 | blob_token = self.__make_token(blob_id) 50 | 51 | return BlobUrl(f"{self.base_blob_url}/{blob_token}") 52 | 53 | def put_blob(self, blob: bytes) -> BlobUrl: 54 | blob_id = BlobId(uuid.uuid4()) 55 | self._store_blob(blob_id, blob) 56 | return self.__make_url(blob_id) 57 | 58 | def get_blob_by_token(self, blob_token: BlobToken) -> Optional[bytes]: 59 | blob_id = self.__verify_token(blob_token) 60 | if blob_id is None: 61 | return None 62 | return self._retrieve_blob(blob_id) 63 | 64 | def get_blob(self, blob_url: BlobUrl) -> Optional[bytes]: 65 | if not blob_url.startswith(self.base_blob_url): 66 | return super().get_blob(blob_url) 67 | blob_token = blob_url.removeprefix(self.base_blob_url + "/") 68 | 69 | return self.get_blob_by_token(blob_token) 70 | 71 | def _store_blob(self, blob_id: BlobId, blob: bytes) -> None: 72 | raise NotImplementedError 73 | 74 | def _retrieve_blob(self, blob_id: BlobId) -> Optional[bytes]: 75 | raise NotImplementedError 76 | 77 | 78 | class InMemoryBlobRepo(LocalBlobRepo): 79 | _blobs = {} 80 | 81 | def _store_blob(self, blob_id: BlobId, blob: bytes) -> None: 82 | self._blobs[blob_id] = blob 83 | 84 | def _retrieve_blob(self, blob_id: BlobId) -> Optional[bytes]: 85 | return self._blobs.get(blob_id, None) 86 | 87 | 88 | class RedisBlobRepo(LocalBlobRepo): 89 | def __init__(self, *args, **kwargs): 90 | super().__init__(*args, **kwargs) 91 | self.redis = get_redis() 92 | 93 | def _store_blob(self, blob_id: BlobId, blob: bytes) -> None: 94 | self.redis.hset('blob_data', blob_id, blob) 95 | 96 | def _retrieve_blob(self, blob_id: BlobId) -> Optional[bytes]: 97 | data = self.redis.hget('blob_data', blob_id) 98 | if data is None: 99 | return None 100 | return data 101 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push] 4 | 5 | env: 6 | POETRY_VERSION: 1.2.0 7 | POETRY_URL: https://install.python-poetry.org 8 | REDIS_VERSION: 7.0.5 9 | REDIS_PORT: 6379 10 | REDIS_PASSWORD: ${{ secrets.REDIS_PASSWORD }} 11 | SECRET_KEY: ${{ secrets.SECRET_KEY }} 12 | ENABLE_PUBLIC_ACCESS: 1 13 | PRINT_LINK_WITH_TOKEN: 0 14 | ENABLE_SIGNUP: 0 15 | HUGGINGFACE_TOKEN: ${{ secrets.HUGGINGFACE_TOKEN }} 16 | 17 | jobs: 18 | pyright: 19 | runs-on: ubuntu-latest 20 | timeout-minutes: 10 21 | strategy: 22 | matrix: 23 | python-version: ["3.10"] 24 | 25 | steps: 26 | - name: Checkout 27 | uses: actions/checkout@v2 28 | 29 | # Poetry cache depends on OS, Python version and Poetry version. 30 | - name: Cache Poetry cache 31 | uses: actions/cache@v3 32 | with: 33 | path: ~/.cache/pypoetry 34 | key: poetry-cache-${{ runner.os }}-${{ matrix.python-version }}-${{ env.POETRY_VERSION }} 35 | 36 | # virtualenv cache depends on OS, Python version and `poetry.lock` (and optionally workflow files). 37 | - name: Cache Packages 38 | uses: actions/cache@v3 39 | with: 40 | path: ~/.local 41 | key: poetry-${{ runner.os }}-${{ matrix.python-version }}-${{ hashFiles('**/poetry.lock') }}-${{ hashFiles('.github/workflows/*.yml') }} 42 | 43 | - name: Set up Python ${{ env.PYTHON_VERSION }} 44 | uses: actions/setup-python@v2 45 | with: 46 | python-version: ${{ matrix.python-version }} 47 | 48 | - name: Install Poetry 49 | run: | 50 | curl -sSL ${{ env.POETRY_URL }} | python - --version ${{ env.POETRY_VERSION }} 51 | echo "$HOME/.local/bin" >> $GITHUB_PATH 52 | 53 | - name: Install Dependencies 54 | run: poetry install --with dev 55 | 56 | - name: Run Pyright 57 | run: poetry run pyright 58 | pytest-fast: 59 | runs-on: ubuntu-latest 60 | timeout-minutes: 10 61 | # needs: pyright 62 | strategy: 63 | matrix: 64 | python-version: [ "3.10" ] 65 | 66 | steps: 67 | - name: Checkout 68 | uses: actions/checkout@v2 69 | 70 | # Poetry cache depends on OS, Python version and Poetry version. 71 | - name: Cache Poetry cache 72 | uses: actions/cache@v3 73 | with: 74 | path: ~/.cache/pypoetry 75 | key: poetry-cache-${{ runner.os }}-${{ matrix.python-version }}-${{ env.POETRY_VERSION }} 76 | 77 | # virtualenv cache depends on OS, Python version and `poetry.lock` (and optionally workflow files). 78 | - name: Cache Packages 79 | uses: actions/cache@v3 80 | with: 81 | path: ~/.local 82 | key: poetry-${{ runner.os }}-${{ matrix.python-version }}-${{ hashFiles('**/poetry.lock') }}-${{ hashFiles('.github/workflows/*.yml') }} 83 | 84 | - name: Set up Python ${{ env.PYTHON_VERSION }} 85 | uses: actions/setup-python@v2 86 | with: 87 | python-version: ${{ matrix.python-version }} 88 | 89 | - name: Install Poetry 90 | run: | 91 | curl -sSL ${{ env.POETRY_URL }} | python - --version ${{ env.POETRY_VERSION }} 92 | echo "$HOME/.local/bin" >> $GITHUB_PATH 93 | 94 | - name: Install Dependencies 95 | run: poetry install --with test 96 | 97 | - name: Start Redis 98 | run: docker run -d -p ${{ env.REDIS_PORT }}:${{ env.REDIS_PORT }} redis:${{ env.REDIS_VERSION }} redis-server 99 | --requirepass ${{ env.REDIS_PASSWORD }} 100 | --port ${{ env.REDIS_PORT }} 101 | 102 | - name: Run Tests 103 | run: poetry run pytest -s 104 | end-to-end: 105 | runs-on: ubuntu-latest 106 | timeout-minutes: 15 107 | # needs: pyright 108 | steps: 109 | - uses: actions/checkout@v2 110 | 111 | - name: E2E docker-compose tests 112 | run: make test 113 | -------------------------------------------------------------------------------- /stable_diffusion_api/engine/repos/messaging_repo.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | from collections import defaultdict 4 | from datetime import datetime 5 | from typing import Sequence, Union, AsyncIterable, AsyncIterator 6 | 7 | from stable_diffusion_api.engine.utils import get_aioredis, get_redis 8 | 9 | logger = logging.getLogger(__name__) 10 | 11 | 12 | class MessagingRepo: 13 | ######## 14 | # Pubsub 15 | ######## 16 | 17 | def publish(self, topic: str, message: str) -> None: 18 | raise NotImplementedError 19 | 20 | async def subscribe(self, topic: str) -> None: 21 | raise NotImplementedError 22 | 23 | async def listen(self) -> AsyncIterator[str]: 24 | raise NotImplementedError 25 | yield # noqa, without this pyright can't tell that this is a generator, and can't wrap return type 26 | 27 | ####### 28 | # Queue 29 | ####### 30 | 31 | def push(self, queue: str, message: str) -> None: 32 | raise NotImplementedError 33 | 34 | async def pop(self, queue: Union[str, Sequence[str]]) -> str: 35 | raise NotImplementedError 36 | 37 | 38 | _in_memory_topics: dict[str, list[tuple[datetime, str]]] = defaultdict(list) 39 | _in_memory_queues: dict[str, list[str]] = defaultdict(list) 40 | 41 | 42 | class InMemoryMessagingRepo(MessagingRepo): 43 | def __init__(self): 44 | self.subscribed_topics = set() 45 | self.seen_topic_messages = set() 46 | 47 | def publish(self, topic: str, message: str) -> None: 48 | _in_memory_topics[topic].append((datetime.now(), message)) 49 | 50 | # def timed_remove(): 51 | # time.sleep(1) 52 | # if message in _in_memory_topics[topic]: 53 | # _in_memory_topics[topic].remove(message) 54 | # threading.Thread(target=timed_remove).start() 55 | 56 | async def subscribe(self, topic: str) -> None: 57 | self.subscribed_topics.add(topic) 58 | 59 | async def listen(self) -> AsyncIterator[str]: 60 | displayed = defaultdict(list) 61 | while True: 62 | for topic in self.subscribed_topics: 63 | for message in _in_memory_topics[topic]: 64 | if message not in displayed[topic]: 65 | _, payload = message 66 | yield payload 67 | displayed[topic].append(message) 68 | await asyncio.sleep(0.1) 69 | 70 | def push(self, queue: str, message: str) -> None: 71 | _in_memory_queues[queue].append(message) 72 | 73 | async def pop(self, queue: Union[str, Sequence[str]]) -> str: 74 | queues = [queue] if isinstance(queue, str) else queue 75 | while True: 76 | if not any(_in_memory_queues[q] for q in queues): 77 | await asyncio.sleep(0.1) 78 | continue 79 | for q in queues: 80 | if _in_memory_queues[q]: 81 | return _in_memory_queues[q].pop(0) 82 | await asyncio.sleep(0.1) 83 | 84 | 85 | class RedisMessagingRepo(MessagingRepo): 86 | def __init__(self): 87 | self.redis = get_redis() 88 | self.aioredis = get_aioredis() 89 | self.pubsub = self.aioredis.pubsub() 90 | 91 | def publish(self, topic: str, message: str) -> None: 92 | num = self.redis.publish(topic, message) 93 | logger.debug(f'Published message to {topic} for {num} subscribers') 94 | 95 | async def subscribe(self, topic: str) -> None: 96 | logger.debug(f'Subscribing to topic: {topic}') 97 | await self.pubsub.subscribe(topic) 98 | 99 | async def listen(self) -> AsyncIterator[str]: 100 | async for message in self.pubsub.listen(): 101 | if message is None: 102 | continue 103 | data = message['data'] 104 | if data == 1: 105 | continue 106 | yield data 107 | 108 | def push(self, queue: str, message: str) -> None: 109 | self.redis.lpush(queue, message) 110 | 111 | async def pop(self, queue: Union[str, Sequence[str]]) -> str: 112 | _, message = await self.aioredis.brpop(queue) 113 | return message 114 | -------------------------------------------------------------------------------- /stable_diffusion_api/api/utils/pyfa_converter.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | from typing import Callable, Any, Type, Union, List 3 | 4 | import typing 5 | from fastapi import Depends, Form, Query, Body 6 | from pydantic import BaseModel 7 | from pydantic.fields import ModelField, FieldInfo 8 | 9 | 10 | # plucked from dotX12/pyfa-converter (MIT), for use until tiangolo/fastapi#4700 is fixed 11 | 12 | 13 | class PydanticConverterUtils: 14 | @classmethod 15 | def param_maker( 16 | cls, field: ModelField, _type: Callable[..., FieldInfo] 17 | ) -> FieldInfo: 18 | if field.required is True: 19 | return cls.__fill_params(param=_type, model_field=field, default=...) 20 | return cls.__fill_params(param=_type, model_field=field, default=field.default) 21 | 22 | @classmethod 23 | def __fill_params( 24 | cls, param: Callable[..., FieldInfo], model_field: ModelField, default: Any 25 | ) -> FieldInfo: 26 | return param( 27 | default=default or None, 28 | alias=model_field.field_info.alias or None, 29 | title=model_field.field_info.title or None, 30 | description=model_field.field_info.description or None, 31 | gt=model_field.field_info.gt or None, 32 | # ge=model_field.field_info.ge or None, 33 | lt=model_field.field_info.lt or None, 34 | # le=model_field.field_info.le or None, 35 | min_length=model_field.field_info.min_length or None, 36 | max_length=model_field.field_info.max_length or None, 37 | regex=model_field.field_info.regex or None, 38 | **model_field.field_info.extra, 39 | ) 40 | 41 | @classmethod 42 | def override_signature_parameters( 43 | cls, 44 | model: Type[BaseModel], 45 | param_maker: Callable[[ModelField], Any], 46 | ) -> List[inspect.Parameter]: 47 | return [ 48 | inspect.Parameter( 49 | name=field.alias, 50 | kind=inspect.Parameter.POSITIONAL_ONLY, 51 | default=param_default, 52 | annotation=field.outer_type_, 53 | ) 54 | for field in model.__fields__.values() 55 | if (param_default := param_maker(field)) is not None 56 | ] 57 | 58 | 59 | class PydanticConverter(PydanticConverterUtils): 60 | @classmethod 61 | def reformat_model_signature( 62 | cls, 63 | model_cls: Type[BaseModel], 64 | _type: Any, 65 | ) -> Union[Type[BaseModel], Type["PydanticConverter"]]: 66 | """ 67 | Adds an `query` class method to decorated models. The `query` class 68 | method can be used with `FastAPI` endpoints. 69 | Args: 70 | model_cls: The model class to decorate. 71 | _type: literal query, form, body, etc... 72 | Returns: 73 | The decorated class. 74 | """ 75 | _type_var_name = str(_type.__name__).lower() 76 | 77 | def make_form_parameter(field: ModelField) -> Any: 78 | """ 79 | Converts a field from a `Pydantic` model to the appropriate `FastAPI` 80 | parameter type. 81 | Args: 82 | field: The field to convert. 83 | Returns: 84 | Either the result of `Query`, if the field is not a sub-model, or 85 | the result of `Depends on` if it is. 86 | """ 87 | if typing.get_origin(field.outer_type_) is dict: 88 | return None 89 | if type(field.type_) is type and issubclass(field.type_, BaseModel): 90 | # This is a sub-model. 91 | assert hasattr(field.type_, _type_var_name), ( 92 | f"Sub-model class for {field.name} field must be decorated with" 93 | f" `as_form` too." 94 | ) 95 | attr = getattr(field.type_, _type_var_name) 96 | return Depends(attr) # noqa 97 | else: 98 | return cls.param_maker(field=field, _type=_type) 99 | 100 | new_params = PydanticConverterUtils.override_signature_parameters( 101 | model=model_cls, param_maker=make_form_parameter 102 | ) 103 | 104 | def _as_form(**data) -> Union[BaseModel, PydanticConverter]: 105 | return model_cls(**data) 106 | 107 | sig = inspect.signature(_as_form) 108 | sig = sig.replace(parameters=new_params) 109 | _as_form.__signature__ = sig 110 | setattr(model_cls, _type_var_name, _as_form) 111 | return model_cls 112 | 113 | 114 | class PyFaDepends: 115 | def __new__( 116 | cls, 117 | model: Type[BaseModel], 118 | _type: Callable[..., FieldInfo], 119 | ): 120 | return cls.generate(model=model, _type=_type) 121 | 122 | @classmethod 123 | def generate( 124 | cls, 125 | model: Type[BaseModel], 126 | _type: Callable[..., FieldInfo], 127 | ): 128 | obj = PydanticConverter.reformat_model_signature(model_cls=model, _type=_type) 129 | attr = getattr(obj, str(_type.__name__).lower()) 130 | return Depends(attr) 131 | 132 | 133 | class BodyDepends(PyFaDepends): 134 | _TYPE = Body 135 | 136 | def __new__(cls, model_type: Type[BaseModel]): 137 | return super().generate(model=model_type, _type=cls._TYPE) 138 | 139 | 140 | class FormDepends(PyFaDepends): 141 | _TYPE = Form 142 | 143 | def __new__(cls, model_type: Type[BaseModel]): 144 | return super().generate(model=model_type, _type=cls._TYPE) 145 | 146 | 147 | class QueryDepends(PyFaDepends): 148 | _TYPE = Query 149 | 150 | def __new__(cls, model_type: Type[BaseModel]): 151 | return super().generate(model=model_type, _type=cls._TYPE) 152 | -------------------------------------------------------------------------------- /stable_diffusion_api/engine/repos/user_repo.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | from calendar import timegm 3 | from typing import Optional 4 | 5 | import jose 6 | from jose import jwt 7 | from passlib.context import CryptContext 8 | 9 | from stable_diffusion_api.engine.utils import get_redis 10 | from stable_diffusion_api.models.user import Username, UserInDB, DefaultUsername, UserBase, AuthenticationError, \ 11 | AuthToken, User 12 | 13 | 14 | class UserRepo: 15 | def __init__( 16 | self, 17 | secret_key: str, 18 | algorithm: str, 19 | access_token_expires: datetime.timedelta, 20 | allow_public_token: bool, 21 | ): 22 | self.pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") 23 | self.secret_key = secret_key 24 | self.algorithm = algorithm 25 | self.access_token_expires = access_token_expires 26 | self.allow_public_token = allow_public_token 27 | 28 | def _get_user_by_username(self, username: Username) -> Optional[UserInDB]: 29 | raise NotImplementedError 30 | 31 | def _put_user(self, user: UserInDB) -> None: 32 | raise NotImplementedError 33 | 34 | # def get_user_by_username_and_password(self, username: Username, password: str) -> Optional[User]: 35 | # user_in_db = self._get_user_by_username(username) 36 | # if user_in_db is None: 37 | # return None 38 | # if not self.pwd_context.verify(password, user_in_db.hashed_password): 39 | # raise AuthenticationError("Invalid password") 40 | # return User(**user_in_db.dict()) 41 | 42 | def create_user(self, user: UserBase, password: str) -> None: 43 | if not self.allow_public_token and user.username == DefaultUsername: 44 | raise AuthenticationError("Invalid username") 45 | 46 | if self._get_user_by_username(user.username) is not None: 47 | raise AuthenticationError(f"User {user.username} already exists") 48 | self._put_user(UserInDB( 49 | hashed_password=self.pwd_context.hash(password), 50 | **user.dict(), 51 | )) 52 | 53 | def create_public_token(self) -> AuthToken: 54 | if not self.allow_public_token: 55 | raise RuntimeError("Public token is not allowed") 56 | 57 | user_in_db = self._get_user_by_username(DefaultUsername) 58 | if user_in_db is None: 59 | # default user's password is insecure; the other functions explicitly disallow login with it when disabled 60 | self.create_user(UserBase(username=DefaultUsername), password="password") 61 | try: 62 | return self.create_token_by_username_and_password(DefaultUsername, "password") 63 | except AuthenticationError: 64 | raise RuntimeError(f"Failed to create default token as User 'all'") 65 | 66 | def create_token_by_username_and_password(self, username: Username, password: str) -> AuthToken: 67 | if not self.allow_public_token and username == DefaultUsername: 68 | raise AuthenticationError("Invalid username") 69 | 70 | user_in_db = self._get_user_by_username(username) 71 | if user_in_db is None: 72 | raise AuthenticationError(f"User {username} does not exist") 73 | if not self.pwd_context.verify(password, user_in_db.hashed_password): 74 | raise AuthenticationError("Invalid password") 75 | 76 | username = user_in_db.username 77 | expire = timegm((datetime.datetime.utcnow() + self.access_token_expires).utctimetuple()) 78 | data = { 79 | "sub": username, 80 | "exp": expire, 81 | } 82 | 83 | token_string = jwt.encode(data, self.secret_key, algorithm=self.algorithm) 84 | return AuthToken(access_token=token_string, token_type="bearer") 85 | 86 | def must_get_user_by_token(self, token: str) -> User: 87 | try: 88 | payload = jwt.decode(token, self.secret_key, algorithms=[self.algorithm]) 89 | except jose.JWTError: 90 | raise AuthenticationError("Invalid token") 91 | 92 | expire = payload.get("exp") 93 | if expire is None: 94 | raise AuthenticationError("Invalid token") 95 | 96 | if datetime.datetime.utcfromtimestamp(expire) < datetime.datetime.utcnow(): 97 | raise AuthenticationError("Token expired") 98 | 99 | username = payload.get("sub") 100 | if username is None or (not self.allow_public_token and username == DefaultUsername): 101 | raise AuthenticationError("Invalid token") 102 | 103 | # very unlikely for token not to be individual per retrieval from the same user, 104 | # because of the 'expire' part. so just encode it deterministically to make a session id 105 | # TODO revisit this 106 | session_id = jwt.encode( 107 | {'hehe': token + 'ARBITREAARY_PHR4SE+WOOHOO'}, 108 | self.secret_key, 109 | algorithm=self.algorithm 110 | ) 111 | 112 | user_in_db = self._get_user_by_username(username) 113 | if user_in_db is None: 114 | raise AuthenticationError("Invalid token") 115 | return User( 116 | **user_in_db.dict(), 117 | session_id=session_id, 118 | ) 119 | 120 | 121 | class InMemoryUserRepo(UserRepo): 122 | _in_memory_users = {} 123 | 124 | def _get_user_by_username(self, username: Username) -> Optional[UserInDB]: 125 | return self._in_memory_users.get(username) 126 | 127 | def _put_user(self, user: UserInDB) -> None: 128 | self._in_memory_users[user.username] = user 129 | 130 | 131 | class RedisUserRepo(UserRepo): 132 | def __init__(self, *args, **kwargs): 133 | super().__init__(*args, **kwargs) 134 | self.redis = get_redis() 135 | 136 | def _get_user_by_username(self, username: Username) -> Optional[UserInDB]: 137 | json_user = self.redis.hget('user', username) 138 | if json_user is None: 139 | return None 140 | return UserInDB.parse_raw(json_user) 141 | 142 | def _put_user(self, user: UserInDB) -> None: 143 | self.redis.hset('user', user.username, user.json()) 144 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

👸 Stable Diffusion API 🐕

2 | 3 |

4 | 5 | OpenApi Specification 6 | 7 | 8 | Google Colab 9 | 10 | 11 | Discord 12 | 13 |

14 | 15 |

16 | Lightweight API for txt2Img, img2Img and inpainting, built with 17 | 🤗 diffusers 18 |

19 | 20 | ## Quickstart 21 | 22 | Run it on [Google Colab](https://colab.research.google.com/github/irgolic/stable-diffusion-api/blob/master/colab_runner.ipynb), 23 | or see [running instructions](#running) to use it locally. 24 | 25 | The API prints a link on startup, which invokes txt2img when visited in the browser. 26 | 27 | Join our [Discord server](https://discord.gg/UXQfCRpYSC) for help, or to let me know what you'd like to see. 28 | 29 | ## Usage 30 | 31 | Visit the API url in your browser [synchronously](#synchronous-interface) at 32 | `/txt2img`, `/img2img` or `/inpaint`, and append parameters with `?prompt=corgi&model=...`. 33 | 34 | Or generate a client library in any popular programming language with the [OpenApi specification]( 35 | https://editor.swagger.io/?url=https://raw.githubusercontent.com/irgolic/stable-diffusion-api/master/openapi.yml), 36 | and implement it [asynchronously](#asynchronous-interface). 37 | 38 | ### Features 39 | 40 | Supported parameters: 41 | - `prompt`: text prompt **(required)**, e.g. `corgi with a top hat` 42 | - `negative_prompt`: negative prompt, e.g. `monocle` 43 | - `model`: model name, default `CompVis/stable-diffusion-v1-4` 44 | - `steps`: number of steps, default `20` 45 | - `guidance`: relatedness to `prompt`, default `7.5` 46 | - `scheduler`: either `plms`, `ddim`, or `k-lms` 47 | - `seed`: randomness seed for reproducibility, default `None` 48 | - `safety_filter`: enable safety checker, default `true` 49 | 50 | Txt2Img also supports: 51 | - `width`: image width, default `512` 52 | - `height`: image height, default `512` 53 | 54 | Img2Img also supports: 55 | - `initial_image`: URL of image to be transformed **(required)** 56 | - `strength`: how much to change the image, default `0.8` 57 | 58 | Inpainting also supports: 59 | - `initial_image`: URL of image to be transformed **(required)** 60 | - `mask`: URL of mask image **(required)** 61 | 62 | `POST /blob` to upload a new image to local storage, and get a URL. 63 | 64 | 65 | ### Authentication 66 | 67 | The token is passed either among query parameters (`/txt2img?token=...`), or via the `Authorization` header 68 | as a `Bearer` token [(OAuth2 Bearer Authentication)](https://swagger.io/docs/specification/authentication/bearer-authentication/). 69 | 70 | To disable authentication and allow generation of public tokens at `POST /token/all`, 71 | set environment variable `ENABLE_PUBLIC_ACCESS=1`. 72 | 73 | To allow users to sign up at `POST /user`, 74 | set environment variable `ENABLE_SIGNUP=1`. 75 | Registered users can generate their own tokens at `POST /token/{username}`. 76 | 77 | ### Synchronous Interface 78 | 79 | For convenience, the API provides synchronous endpoints at `GET /txt2img`, `GET /img2img`, and `GET /inpaint`. 80 | 81 | To print a browser-accessible URL upon startup (i.e., `http://localhost:8000/txt2img?prompt=corgi&steps=5?token=...`), 82 | set environment variable `PRINT_LINK_WITH_TOKEN=1` (set by default in `.env.example`). 83 | 84 | If the connection is dropped (i.e., you navigate away from the page), 85 | the API will automatically cancel the request and free up resources. 86 | 87 | It is preferable to use the asynchronous interface for production use. 88 | 89 | ### Asynchronous Interface 90 | 91 | `POST /task` with either `Txt2ImgParams`, `Img2ImgParams` or `InpaintParams` to start a task, and get a `task_id`. 92 | 93 | `GET /task/{task_id}` to get the last `event` broadcast by the task, or subscribe to the websocket endpoint `/events?token=` to get a stream of events as they occur. 94 | 95 | Event types: 96 | - PendingEvent 97 | - StartedEvent 98 | - FinishedEvent (with `blob_url` and `parameters_used`) 99 | - AbortedEvent (with `reason`) 100 | 101 | To cancel a task, `DELETE /task/{task_id}`. 102 | 103 | ## Running 104 | 105 | ### Installing 106 | 107 | Install a virtual environment with python 3.10 and poetry. 108 | 109 | #### Conda (for example) 110 | 111 | Setup [MiniConda](https://docs.conda.io/en/latest/miniconda.html) and create a new environment with python 3.10. 112 | 113 | ```bash 114 | conda create -n sda python=3.10 115 | conda activate sda 116 | ``` 117 | 118 | #### Poetry 119 | 120 | Setup [Poetry](https://python-poetry.org/docs/#installation) and install the dependencies. 121 | 122 | ```bash 123 | poetry install 124 | ``` 125 | 126 | ### Environment Variables 127 | 128 | Copy `.env.example` to `.env`: 129 | 130 | ```bash 131 | cp .env.example .env 132 | ``` 133 | 134 | Genereate a new `SECRET_KEY`, and replace the one from the example: 135 | 136 | ```bash 137 | openssl rand -hex 32 138 | ``` 139 | 140 | The various environment variables are: 141 | 142 | - `SECRET_KEY`: The secret key used to sign the JWT tokens. 143 | - `PRINT_LINK_WITH_TOKEN`: Whether to print a link with the token to the console on startup. 144 | - `ENABLE_PUBLIC_ACCESS`: Whether to enable public token generation (anything except empty string enables it). 145 | - `ENABLE_SIGNUP`: Whether to enable user signup (anything except empty string enables it). 146 | - `BASE_URL`: Used to build link with token printed upon startup and local storage blob URLs. 147 | - `REDIS_HOST`: The host of the Redis server. 148 | - `REDIS_PORT`: The port of the Redis server. 149 | - `REDIS_PASSWORD`: The password of the Redis server. 150 | - `HUGGINGFACE_TOKEN`: The token used by the worker to access the Hugging Face API. 151 | 152 | ### Docker Compose 153 | 154 | Run the API and five workers, with redis as intermediary, and docker compose to manage the containers. 155 | 156 | ```bash 157 | make run 158 | ``` 159 | 160 | ### Multi Process 161 | 162 | Or invoke processes on multiple machines, starting the API with: 163 | 164 | ```bash 165 | poetry run uvicorn stable_diffusion_api.api.redis_app:app 166 | ``` 167 | 168 | And the worker(s) with: 169 | 170 | ```bash 171 | poetry run python -m stable_diffusion_api.engine.worker.redis_worker 172 | ``` 173 | 174 | ### Single Process 175 | 176 | Or run the API and worker in a single process. 177 | 178 | ```bash 179 | poetry run uvicorn stable_diffusion_api.api.in_memory_app:app 180 | ``` -------------------------------------------------------------------------------- /stable_diffusion_api/models/params.py: -------------------------------------------------------------------------------- 1 | from typing import Optional, Union, Literal 2 | 3 | import pydantic 4 | import typing 5 | 6 | from stable_diffusion_api.models.blob import BlobUrl 7 | 8 | 9 | class Params(pydantic.BaseModel): 10 | params_type: str 11 | _endpoint_stem: typing.ClassVar[str] 12 | 13 | class Config: 14 | extra = pydantic.Extra.forbid 15 | 16 | # pipeline: str = pydantic.Field( 17 | # description="The pipeline to use for the task. " 18 | # "One of: " 19 | # "the *file name* of a community pipeline hosted on GitHub under " 20 | # "https://github.com/huggingface/diffusers/tree/main/examples/community " 21 | # "(e.g., 'clip_guided_stable_diffusion'), " 22 | # "*a path* to a *directory* containing a file called `pipeline.py` " 23 | # "(e.g., './my_pipeline_directory/'.), or " 24 | # "the *repo id* of a custom pipeline hosted on huggingface. " 25 | # "See [Loading and Creating Custom Pipelines]" 26 | # "(https://huggingface.co/docs/diffusers/main/en/using-diffusers/custom_pipelines). " 27 | # ) 28 | # pipeline_method: Optional[str] = pydantic.Field( 29 | # description="The method to call on the pipeline. " 30 | # "If unspecified, the pipeline itself will be called.", 31 | # ) 32 | _pipeline: str = pydantic.PrivateAttr() 33 | _pipeline_method: Optional[str] = pydantic.PrivateAttr(None) 34 | 35 | model: str = pydantic.Field( 36 | default="CompVis/stable-diffusion-v1-4", 37 | description="The model to use for image generation. " 38 | "One of: " 39 | "the *repo id* of a pretrained pipeline hosted on huggingface " 40 | "(e.g. 'CompVis/stable-diffusion-v1-4'), " 41 | "*a path* to a *directory* containing pipeline weights, " 42 | "(e.g., './my_model_directory/'). ", 43 | ) 44 | 45 | prompt: str = pydantic.Field( 46 | description="The prompt to guide image generation." 47 | ) 48 | negative_prompt: Optional[str] = pydantic.Field( 49 | default=None, 50 | description="The prompt to dissuade image generation. " 51 | "Ignored when not using guidance (i.e., if `guidance` is `1`)." 52 | ) 53 | steps: int = pydantic.Field( 54 | default=20, 55 | description="The number of denoising steps. " 56 | "More denoising steps usually lead to a higher quality image at the expense of slower inference." 57 | ) 58 | guidance: float = pydantic.Field( 59 | default=7.5, 60 | minimum=1.0, 61 | description="Higher guidance encourages generation closely linked to `prompt`, " 62 | "usually at the expense of lower image quality. " 63 | "Try using more steps to improve image quality when using high guidance. " 64 | "Guidance is disabled by setting `guidance` to `1`. " 65 | "`guidance` is defined as `w` of equation 2. of " 66 | "[ImagenPaper](https://arxiv.org/pdf/2205.11487.pdf). " 67 | "See also: [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598)." 68 | ) 69 | scheduler: Literal["plms", "ddim", "k-lms"] = pydantic.Field( 70 | default="plms", 71 | description="The scheduler to use for image generation. " 72 | "Currently only 'plms', 'ddim', and 'k-lms', are supported." 73 | ) 74 | safety_filter: bool = pydantic.Field( 75 | default=True, 76 | description="Ensure that you abide by the conditions of the Stable Diffusion license and " 77 | "do not expose unfiltered results in services or applications open to the public. " 78 | "For more information, please see https://github.com/huggingface/diffusers/pull/254", 79 | ) 80 | seed: Optional[int] = pydantic.Field( 81 | default=None, 82 | description="The randomness seed to use for image generation. " 83 | "If not set, a random seed is used." 84 | ) 85 | 86 | 87 | class Txt2ImgParams(Params): 88 | params_type: Literal['txt2img'] = "txt2img" 89 | 90 | _endpoint_stem = "txt2img" 91 | _pipeline = pydantic.PrivateAttr("lpw_stable_diffusion") 92 | _pipeline_method = pydantic.PrivateAttr("text2img") 93 | 94 | width: int = pydantic.Field( 95 | default=512, 96 | description="The pixel width of the generated image.") 97 | height: int = pydantic.Field( 98 | default=512, 99 | description="The pixel height of the generated image.") 100 | 101 | 102 | class Img2ImgParams(Params): 103 | params_type: Literal['img2img'] = 'img2img' 104 | 105 | _endpoint_stem = "img2img" 106 | _pipeline = pydantic.PrivateAttr("lpw_stable_diffusion") 107 | _pipeline_method = pydantic.PrivateAttr("img2img") 108 | 109 | initial_image: BlobUrl = pydantic.Field( 110 | description="The image to use as input for image generation. " 111 | "The image must have a width and height divisible by 8. " 112 | ) 113 | strength: float = pydantic.Field( 114 | default=0.8, 115 | minimum=0.0, 116 | maximum=1.0, 117 | description="Conceptually, indicates how much to transform the image. " 118 | "The image will be used as a starting point, adding more noise to it the larger the `strength`. " 119 | "The number of denoising steps depends on the amount of noise initially added. " 120 | "When `strength` is 1, it becomes pure noise, " 121 | "and the denoising process will run for the full number of iterations specified in `steps`. " 122 | "A value of 1, therefore, works like Txt2Img, essentially ignoring the reference image." 123 | ) 124 | 125 | 126 | class InpaintParams(Params): 127 | params_type: Literal['inpaint'] = 'inpaint' 128 | 129 | _endpoint_stem = "inpaint" 130 | _pipeline = pydantic.PrivateAttr("lpw_stable_diffusion") 131 | _pipeline_method = pydantic.PrivateAttr("inpaint") 132 | 133 | model: str = pydantic.Field( 134 | default="runwayml/stable-diffusion-inpainting", 135 | description="The model to use for image generation, e.g. 'runwayml/stable-diffusion-inpainting'.", 136 | ) 137 | 138 | initial_image: BlobUrl = pydantic.Field( 139 | description="The image to use as input for image generation. " 140 | "It must have a width and height divisible by 8. " 141 | ) 142 | mask: BlobUrl = pydantic.Field( 143 | description="The mask to use for image generation. " 144 | "It must have the same width and height as the initial image. " 145 | "It will be converted to a black-and-white image, " 146 | "wherein white indicates the area to be inpainted." 147 | ) 148 | 149 | 150 | ParamsUnion = Union[tuple(Params.__subclasses__())] # type: ignore 151 | -------------------------------------------------------------------------------- /colab_runner.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "provenance": [], 7 | "collapsed_sections": [], 8 | "toc_visible": true 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "language_info": { 15 | "name": "python" 16 | }, 17 | "accelerator": "GPU" 18 | }, 19 | "cells": [ 20 | { 21 | "cell_type": "code", 22 | "source": [ 23 | "#@markdown # Connect GPU\n", 24 | "\n", 25 | "#@markdown If it fails to connect to a GPU, go to Runtime -> Change runtime type, and select 'GPU' from the Hardware accelerator dropdown.\n", 26 | "\n", 27 | "!nvidia-smi -L" 28 | ], 29 | "metadata": { 30 | "cellView": "form", 31 | "id": "mbp2yZA0QxZV", 32 | "pycharm": { 33 | "is_executing": true 34 | } 35 | }, 36 | "execution_count": null, 37 | "outputs": [] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "source": [ 42 | "#@markdown # Clone git repo\n", 43 | "\n", 44 | "!git clone https://github.com/irgolic/stable-diffusion-api\n", 45 | "%cd /content/stable-diffusion-api" 46 | ], 47 | "metadata": { 48 | "id": "vjZsZgYMQxew", 49 | "cellView": "form", 50 | "pycharm": { 51 | "is_executing": true 52 | } 53 | }, 54 | "execution_count": null, 55 | "outputs": [] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "source": [ 60 | "#@markdown # Setup Miniconda\n", 61 | "\n", 62 | "import sys\n", 63 | "!wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh\n", 64 | "!chmod +x Miniconda3-latest-Linux-x86_64.sh\n", 65 | "!bash ./Miniconda3-latest-Linux-x86_64.sh -b -f -p /usr/local\n", 66 | "sys.path.append('/usr/local/lib/python3.7/site-packages/')\n", 67 | "!rm Miniconda3-latest-Linux-x86_64.sh" 68 | ], 69 | "metadata": { 70 | "id": "BhyRyzW7R2cT", 71 | "cellView": "form", 72 | "pycharm": { 73 | "is_executing": true 74 | } 75 | }, 76 | "execution_count": null, 77 | "outputs": [] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "source": [ 82 | "#@markdown # Install python3.10\n", 83 | "!conda install python=\"3.10\" -y" 84 | ], 85 | "metadata": { 86 | "id": "QMeDdvMkQva-", 87 | "cellView": "form", 88 | "pycharm": { 89 | "is_executing": true 90 | } 91 | }, 92 | "execution_count": null, 93 | "outputs": [] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "source": [ 98 | "#@markdown # Install poetry\n", 99 | "\n", 100 | "!pip install -q --pre poetry\n", 101 | "!poetry --version" 102 | ], 103 | "metadata": { 104 | "cellView": "form", 105 | "id": "ZoRnhnjT6IXc", 106 | "pycharm": { 107 | "is_executing": true 108 | } 109 | }, 110 | "execution_count": null, 111 | "outputs": [] 112 | }, 113 | { 114 | "cell_type": "code", 115 | "source": [ 116 | "#@markdown # Install dependencies\n", 117 | "\n", 118 | "%cd /content/stable-diffusion-api\n", 119 | "!poetry install\n", 120 | "\n", 121 | "# For URL forwarding in Colab\n", 122 | "!npm install -g localtunnel" 123 | ], 124 | "metadata": { 125 | "cellView": "form", 126 | "id": "FRx1jwET6nb7", 127 | "pycharm": { 128 | "is_executing": true 129 | } 130 | }, 131 | "execution_count": null, 132 | "outputs": [] 133 | }, 134 | { 135 | "cell_type": "code", 136 | "source": [ 137 | "#@markdown # Environment Variables\n", 138 | "\n", 139 | "#@markdown ### Access Control:\n", 140 | "PRINT_LINK_WITH_TOKEN = True #@param {type:\"boolean\"}\n", 141 | "ENABLE_SIGNUP = False #@param {type:\"boolean\"}\n", 142 | "ENABLE_PUBLIC_ACCESS = False #@param {type:\"boolean\"}\n", 143 | "#@markdown ### Get token from [HuggingFace](https://huggingface.co/docs/hub/security-tokens):\n", 144 | "HUGGINGFACE_TOKEN = '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' #@param {type:\"string\"}\n", 145 | "\n", 146 | "import os\n", 147 | "\n", 148 | "env_vars = {}\n", 149 | "\n", 150 | "env_vars['PRINT_LINK_WITH_TOKEN'] = '1' if PRINT_LINK_WITH_TOKEN else '0'\n", 151 | "env_vars['ENABLE_SIGNUP'] = '1' if ENABLE_SIGNUP else '0'\n", 152 | "env_vars['ENABLE_PUBLIC_ACCESS'] = '1' if ENABLE_PUBLIC_ACCESS else '0'\n", 153 | "env_vars['SECRET_KEY'], = !openssl rand -hex 32\n", 154 | "env_vars['HUGGINGFACE_TOKEN'] = HUGGINGFACE_TOKEN\n", 155 | "\n", 156 | "for name, value in env_vars.items():\n", 157 | " os.environ[name] = value" 158 | ], 159 | "metadata": { 160 | "id": "88VjK6naQFT0", 161 | "cellView": "form" 162 | }, 163 | "execution_count": null, 164 | "outputs": [] 165 | }, 166 | { 167 | "cell_type": "code", 168 | "source": [ 169 | "#@markdown # Run Server\n", 170 | "#@markdown Localtunnel is used to serve google colab to an external URL. 🙏\n", 171 | "#@markdown\n", 172 | "#@markdown The first time you call /txt2img in your browser it will likely time out; let the model cache, and try again. The cached model persists restarting the code cell.\n", 173 | "#@markdown\n", 174 | "#@markdown localtunnel cuts off requests that last too long, and also does not forward http disconnects, meaning that the API will not automatically cancel image generation when navigating away from the page.\n", 175 | "#@markdown\n", 176 | "#@markdown If anyone knows an actively maintained alternative to localtunnel, please drop on by our [Discord server](https://discord.gg/UXQfCRpYSC).\n", 177 | "%cd /content/stable-diffusion-api\n", 178 | "\n", 179 | "import time\n", 180 | "\n", 181 | "# get localtunnel URL\n", 182 | "!nohup lt -p 8000 > lt.log 2>&1 &\n", 183 | "local_tunnel_url = None\n", 184 | "prefix = \"your url is: \"\n", 185 | "while local_tunnel_url is None:\n", 186 | " with open('lt.log', 'r') as testwritefile:\n", 187 | " lt_log = testwritefile.read()\n", 188 | " if not lt_log:\n", 189 | " time.sleep(0.25)\n", 190 | " continue\n", 191 | " print(lt_log)\n", 192 | " if not lt_log.startswith(prefix):\n", 193 | " raise RuntimeError('Unexpected value in localtunnel log: ' + lt_log)\n", 194 | " local_tunnel_url = lt_log[len(prefix):].strip()\n", 195 | "\n", 196 | "# BASE_URL only controls the printed link\n", 197 | "os.environ['BASE_URL'] = local_tunnel_url\n", 198 | "\n", 199 | "# run in memory (TODO run multiple processes intermediated by redis)\n", 200 | "!poetry run uvicorn stable_diffusion_api.api.in_memory_app:app" 201 | ], 202 | "metadata": { 203 | "id": "dSlL_wCSgHJ3", 204 | "pycharm": { 205 | "is_executing": true 206 | }, 207 | "cellView": "form" 208 | }, 209 | "execution_count": null, 210 | "outputs": [] 211 | } 212 | ] 213 | } -------------------------------------------------------------------------------- /stable_diffusion_api/engine/services/runner_service.py: -------------------------------------------------------------------------------- 1 | import io 2 | import logging 3 | import os 4 | from typing import Any, Optional 5 | 6 | import PIL.Image 7 | import numpy as np 8 | import torch 9 | from diffusers import StableDiffusionPipeline, DDIMScheduler, LMSDiscreteScheduler, StableDiffusionImg2ImgPipeline, \ 10 | StableDiffusionInpaintPipeline, DiffusionPipeline 11 | 12 | from stable_diffusion_api.engine.repos.blob_repo import BlobRepo 13 | from stable_diffusion_api.engine.services.event_service import EventService 14 | from stable_diffusion_api.engine.services.status_service import StatusService 15 | from stable_diffusion_api.models.blob import BlobUrl 16 | from stable_diffusion_api.models.events import FinishedEvent, StartedEvent, AbortedEvent 17 | from stable_diffusion_api.models.params import Txt2ImgParams, Img2ImgParams, InpaintParams, Params 18 | from stable_diffusion_api.models.results import GeneratedBlob 19 | from stable_diffusion_api.models.task import Task, TaskId 20 | from stable_diffusion_api.models.user import User, Username 21 | 22 | logger = logging.getLogger(__name__) 23 | 24 | 25 | class TaskCancelledException(Exception): 26 | pass 27 | 28 | 29 | class RunnerService: 30 | def __init__( 31 | self, 32 | blob_repo: BlobRepo, 33 | status_service: StatusService, 34 | event_service: EventService, 35 | ): 36 | self.blob_repo = blob_repo 37 | self.status_service = status_service 38 | self.event_service = event_service 39 | 40 | self.cached_kwargs: Optional[dict[str, Any]] = None 41 | self.cached_pipeline = None 42 | 43 | def get_img(self, blob_url: BlobUrl, is_mask: bool = False): 44 | # extract image blob into `init_image` pipe kwarg 45 | blob = self.blob_repo.get_blob(blob_url) 46 | if blob is None: 47 | raise ValueError(f'Blob not found: {blob_url}') 48 | image = PIL.Image.open(io.BytesIO(blob)) 49 | if is_mask: 50 | # adapted from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_inpaint_legacy.preprocess_mask 51 | # instead of shrinking it down by 8 times, resize it to 64 x 64 (latent space size) 52 | mask = image.convert('L') 53 | # w, h = mask.size 54 | # w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32 55 | mask = mask.resize((64, 64), resample=PIL.Image.NEAREST) 56 | mask = np.array(mask).astype(np.float32) / 255.0 57 | mask = np.tile(mask, (4, 1, 1)) 58 | mask = mask[None].transpose(0, 1, 2, 3) # what does this step do? 59 | mask = 1 - mask # repaint white, keep black 60 | mask = torch.from_numpy(mask) 61 | return mask 62 | return image.convert('RGB') 63 | 64 | def pipeline_callback( 65 | self, 66 | task_id: TaskId, 67 | step: int, 68 | timestep: int, 69 | latents: torch.FloatTensor, 70 | ): 71 | if self.status_service.is_task_cancelled(task_id): 72 | raise TaskCancelledException() 73 | # TODO update progress and save intermediate results 74 | 75 | def get_arguments(self, task: Task, device: str) -> tuple[dict[str, Any], dict[str, Any], Optional[str]]: 76 | params = task.parameters 77 | 78 | # set model 79 | pipeline_kwargs: dict[str, Any] = { 80 | 'pretrained_model_name_or_path': params.model 81 | } 82 | 83 | # set token 84 | if "HUGGINGFACE_TOKEN" in os.environ: 85 | pipeline_kwargs['use_auth_token'] = os.environ["HUGGINGFACE_TOKEN"] 86 | 87 | # optionally disable safety filter 88 | if not params.safety_filter: 89 | pipeline_kwargs['safety_checker'] = None 90 | 91 | # pick scheduler 92 | match params.scheduler: 93 | case "plms": 94 | pass # default scheduler 95 | case "ddim": 96 | pipeline_kwargs['scheduler'] = DDIMScheduler( 97 | beta_start=0.00085, 98 | beta_end=0.012, 99 | beta_schedule="scaled_linear", 100 | clip_sample=False, 101 | set_alpha_to_one=False 102 | ) 103 | case "k-lms": 104 | pipeline_kwargs['scheduler'] = LMSDiscreteScheduler( 105 | beta_start=0.00085, 106 | beta_end=0.012, 107 | beta_schedule="scaled_linear" 108 | ) 109 | 110 | # construct generator, set seed if params.seed is not None 111 | generator = torch.Generator(device) 112 | if params.seed is None: 113 | params.seed = generator.seed() 114 | else: 115 | generator.manual_seed(params.seed) 116 | 117 | # extract common pipe kwargs 118 | pipe_kwargs: dict[str, Any] = dict( 119 | prompt=params.prompt, 120 | num_inference_steps=params.steps, 121 | guidance_scale=params.guidance, 122 | negative_prompt=params.negative_prompt, 123 | generator=generator, 124 | ) 125 | 126 | # prepare pipeline 127 | pipeline_kwargs.update( 128 | custom_pipeline=params._pipeline, 129 | ) 130 | if isinstance(params, Txt2ImgParams): 131 | pipe_kwargs.update( 132 | height=params.height, 133 | width=params.width, 134 | ) 135 | elif isinstance(params, Img2ImgParams): 136 | init_image = self.get_img(params.initial_image) 137 | pipe_kwargs.update( 138 | strength=params.strength, 139 | init_image=init_image, 140 | ) 141 | elif isinstance(params, InpaintParams): 142 | init_image = self.get_img(params.initial_image) 143 | mask_image = self.get_img(params.mask, is_mask=True) 144 | pipe_kwargs.update( 145 | init_image=init_image, 146 | mask_image=mask_image, 147 | ) 148 | else: 149 | raise ValueError(f'Unknown params type: {params}') 150 | 151 | return pipeline_kwargs, pipe_kwargs, params._pipeline_method 152 | 153 | def save_img(self, img: PIL.Image.Image, task: Task) -> GeneratedBlob: 154 | # convert pillow image to png bytes 155 | img_byte_arr = io.BytesIO() 156 | img.save(img_byte_arr, format='PNG') 157 | img_bytes = img_byte_arr.getvalue() 158 | 159 | # save blob 160 | blob_url = self.blob_repo.put_blob(img_bytes) 161 | 162 | return GeneratedBlob( 163 | blob_url=blob_url, 164 | parameters_used=task.parameters, 165 | ) 166 | 167 | async def run_task(self, task: Task) -> None: 168 | logger.info(f'Handle task: {task}') 169 | 170 | # started event 171 | self.event_service.send_event( 172 | task.user.session_id, 173 | StartedEvent( 174 | event_type="started", 175 | task_id=task.task_id, 176 | ) 177 | ) 178 | 179 | # pick device 180 | device = "cuda" if torch.cuda.is_available() else "cpu" 181 | 182 | # extract parameters 183 | pipeline_kwargs, pipe_kwargs, pipe_method_name = self.get_arguments(task, device) 184 | 185 | try: 186 | # create or reuse pipeline 187 | if self.cached_pipeline is not None and self.cached_kwargs == pipeline_kwargs: 188 | # reuse cached pipeline 189 | pipe = self.cached_pipeline 190 | else: 191 | # create pipeline 192 | pipe = DiffusionPipeline.from_pretrained(**pipeline_kwargs) 193 | pipe.to(device) 194 | self.cached_kwargs = pipeline_kwargs 195 | self.cached_pipeline = pipe 196 | 197 | # determine pipeline method 198 | if pipe_method_name is None: 199 | pipe_method = pipe 200 | else: 201 | pipe_method = getattr(pipe, pipe_method_name) 202 | 203 | # run pipeline 204 | output = pipe_method( 205 | **pipe_kwargs, 206 | callback=lambda step, timestep, latents: self.pipeline_callback(task.task_id, step, timestep, latents) 207 | ) 208 | 209 | # get output 210 | img = output.images[0] 211 | except TaskCancelledException: 212 | logger.info(f'Task cancelled by user: {task}') 213 | self.event_service.send_event( 214 | task.user.session_id, 215 | AbortedEvent( 216 | event_type="aborted", 217 | task_id=task.task_id, 218 | reason="Task cancelled by user", 219 | ) 220 | ) 221 | return 222 | except Exception as e: 223 | logger.error(f'Error while handling task: {task}', exc_info=True) 224 | self.event_service.send_event( 225 | task.user.session_id, 226 | AbortedEvent( 227 | event_type="aborted", 228 | task_id=task.task_id, 229 | reason="Internal error: " + str(e), 230 | ) 231 | ) 232 | return 233 | 234 | # save image 235 | generated_image = self.save_img(img, task) 236 | 237 | # finished event 238 | self.event_service.send_event( 239 | task.user.session_id, 240 | FinishedEvent( 241 | event_type="finished", 242 | task_id=task.task_id, 243 | result=generated_image, 244 | ) 245 | ) 246 | -------------------------------------------------------------------------------- /stable_diffusion_api/api/tests/base.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import io 3 | import json 4 | import urllib.parse 5 | from typing import Any 6 | from unittest import mock 7 | 8 | import pytest 9 | import pytest_asyncio 10 | import requests 11 | 12 | from stable_diffusion_api.api.tests.utils import AppClient 13 | 14 | 15 | class BaseTestApp: 16 | @classmethod 17 | def get_client(cls) -> AppClient: 18 | raise NotImplementedError 19 | 20 | # fixtures 21 | 22 | @pytest_asyncio.fixture(scope="function") 23 | async def client(self): 24 | async with self.get_client() as c: 25 | yield c 26 | 27 | @pytest_asyncio.fixture(scope="function") 28 | async def websocket(self, client): 29 | await client.set_public_token() 30 | async with client.websocket_connect() as ws: 31 | yield ws 32 | ws.close() 33 | 34 | @pytest.fixture 35 | def common_params(self): 36 | return { 37 | "model": "hf-internal-testing/tiny-stable-diffusion-pipe", 38 | "prompt": "corgi wearing a top hat", 39 | "steps": 2, 40 | "safety_filter": False, 41 | } 42 | 43 | @pytest.fixture 44 | def resolved_common_params(self, common_params): 45 | return common_params | { 46 | 'negative_prompt': None, 47 | 'guidance': 7.5, 48 | 'scheduler': 'plms', 49 | 'seed': mock.ANY, 50 | } 51 | 52 | @pytest.fixture 53 | def dummy_txt2img_params(self, common_params): 54 | return common_params | { 55 | "params_type": "txt2img", 56 | } 57 | 58 | @pytest.fixture 59 | def resolved_dummy_txt2img_params(self, resolved_common_params): 60 | return resolved_common_params | { 61 | "params_type": "txt2img", 62 | 'width': 512, 63 | 'height': 512, 64 | } 65 | 66 | @pytest.fixture 67 | def dummy_img2img_params(self, common_params): 68 | return common_params | { 69 | "params_type": "img2img", 70 | 'initial_image': mock.ANY, 71 | } 72 | 73 | @pytest.fixture 74 | def resolved_dummy_img2img_params(self, resolved_common_params): 75 | return resolved_common_params | { 76 | "params_type": "img2img", 77 | 'initial_image': mock.ANY, 78 | "strength": 0.8, 79 | } 80 | 81 | @pytest.fixture 82 | def dummy_inpaint_params(self, common_params): 83 | return common_params | { 84 | "params_type": "inpaint", 85 | 'initial_image': mock.ANY, 86 | "mask": mock.ANY, 87 | } 88 | 89 | @pytest.fixture 90 | def resolved_dummy_inpaint_params(self, resolved_common_params): 91 | return resolved_common_params | { 92 | "params_type": "inpaint", 93 | 'initial_image': mock.ANY, 94 | "mask": mock.ANY, 95 | } 96 | 97 | # helper methods 98 | 99 | @staticmethod 100 | async def assert_websocket_received(event_dict: dict[str, Any], websocket) -> dict[str, Any]: 101 | # blocks indefinitely until the event is received 102 | ws_event = json.loads(json.loads(await websocket.recv())) 103 | assert ws_event == event_dict, ws_event 104 | return ws_event 105 | 106 | @staticmethod 107 | async def assert_websocket_eventually_received(event_dict: dict[str, Any], websocket) -> dict[str, Any]: 108 | while True: 109 | ws_event = json.loads(json.loads(await websocket.recv())) 110 | if ws_event == event_dict: 111 | return ws_event 112 | 113 | async def assert_poll_status(self, client, task_id, expected_event) -> dict[str, Any]: 114 | while True: 115 | response = await client.get(f'/task/{task_id}') 116 | assert response.status_code == 200 117 | event = response.json() 118 | if event == expected_event: 119 | return event 120 | await asyncio.sleep(0.1) 121 | 122 | async def post_task( 123 | self, 124 | client, 125 | params: dict[str, Any], 126 | resolved_params: dict[str, Any], 127 | websocket=None 128 | ) -> dict[str, Any]: 129 | response = await client.post('/task', json=params) 130 | assert response.status_code == 200 131 | task_id = response.json() 132 | 133 | expected_event = { 134 | 'event_type': 'finished', 135 | 'task_id': task_id, 136 | 'result': { 137 | 'blob_url': mock.ANY, 138 | 'parameters_used': resolved_params, 139 | } 140 | } 141 | 142 | if websocket is not None: 143 | # pending event 144 | await self.assert_websocket_received({ 145 | 'event_type': 'pending', 146 | 'task_id': task_id, 147 | }, websocket) 148 | 149 | # started event 150 | await self.assert_websocket_received({ 151 | 'event_type': 'started', 152 | 'task_id': task_id, 153 | }, websocket) 154 | 155 | # finished event 156 | await self.assert_websocket_received(expected_event, websocket) 157 | 158 | poll_event = await self.assert_poll_status(client, task_id, expected_event) 159 | return poll_event 160 | 161 | async def get_blob(self, client, blob_url: str) -> requests.Response: 162 | path = urllib.parse.urlparse(blob_url).path 163 | response = await client.get(path) 164 | assert response.status_code == 200 165 | return response 166 | 167 | async def post_blob(self, client, data: bytes) -> requests.Response: 168 | response = await client.post('/blob', files={ 169 | "blob_data": ("filename", io.BytesIO(data), "image/png"), 170 | }) 171 | assert response.status_code == 200 172 | return response 173 | 174 | # tests 175 | 176 | @pytest.mark.asyncio 177 | async def test_txt2img_2img_inpaint_with_token( 178 | self, 179 | client, 180 | websocket, # token is automatically set in the websocket fixture 181 | dummy_txt2img_params, 182 | resolved_dummy_txt2img_params, 183 | dummy_img2img_params, 184 | resolved_dummy_img2img_params, 185 | dummy_inpaint_params, 186 | resolved_dummy_inpaint_params, 187 | ): 188 | finished_event = await self.post_task( 189 | client, 190 | dummy_txt2img_params, 191 | resolved_dummy_txt2img_params, 192 | websocket=websocket, 193 | ) 194 | 195 | # assert seed got set after randomization 196 | assert finished_event['result']['parameters_used']['seed'] is not None 197 | 198 | generated_image_blob_url = finished_event['result']['blob_url'] 199 | 200 | # download the blob 201 | response = await self.get_blob(client, generated_image_blob_url) 202 | 203 | # upload the blob 204 | img_bytes = response.content 205 | upload_response = await self.post_blob(client, img_bytes) 206 | uploaded_blob_url = upload_response.json() 207 | 208 | # use manual seed 209 | manual_seed = 42 210 | 211 | # run the generated image through img2img 212 | finished_event = await self.post_task( 213 | client, 214 | dummy_img2img_params | { 215 | "initial_image": uploaded_blob_url, 216 | 'seed': manual_seed, 217 | }, 218 | resolved_dummy_img2img_params | { 219 | "initial_image": uploaded_blob_url, 220 | 'seed': manual_seed, 221 | }, 222 | websocket, 223 | ) 224 | 225 | # download the blob (and do nothing with it) 226 | generated_image_blob_url = finished_event['result']['blob_url'] 227 | await self.get_blob(client, generated_image_blob_url) 228 | 229 | # run the generated image with the previous image as mask through inpaint 230 | finished_event = await self.post_task( 231 | client, 232 | dummy_inpaint_params | { 233 | "initial_image": uploaded_blob_url, 234 | "mask": generated_image_blob_url, 235 | }, 236 | resolved_dummy_inpaint_params | { 237 | "initial_image": uploaded_blob_url, 238 | "mask": generated_image_blob_url, 239 | }, 240 | websocket, 241 | ) 242 | 243 | # download the blob (and do nothing with it) 244 | generated_image_blob_url = finished_event['result']['blob_url'] 245 | await self.get_blob(client, generated_image_blob_url) 246 | 247 | @pytest.mark.asyncio 248 | async def test_txt2img_2img_without_token( 249 | self, 250 | client, 251 | dummy_txt2img_params, 252 | resolved_dummy_txt2img_params, 253 | dummy_img2img_params, 254 | resolved_dummy_img2img_params, 255 | ): 256 | finished_event = await self.post_task(client, dummy_txt2img_params, resolved_dummy_txt2img_params) 257 | 258 | generated_image_blob_url = finished_event['result']['blob_url'] 259 | 260 | # download the blob 261 | response = await self.get_blob(client, generated_image_blob_url) 262 | 263 | # upload the blob 264 | img_bytes = response.content 265 | upload_response = await self.post_blob(client, img_bytes) 266 | uploaded_blob_url = upload_response.json() 267 | 268 | # use manual seed 269 | manual_seed = 42 270 | 271 | # run the generated image through img2img 272 | finished_event = await self.post_task( 273 | client, 274 | dummy_img2img_params | { 275 | "initial_image": uploaded_blob_url, 276 | 'seed': manual_seed, 277 | }, 278 | resolved_dummy_img2img_params | { 279 | "initial_image": uploaded_blob_url, 280 | 'seed': manual_seed, 281 | }, 282 | ) 283 | 284 | generated_image_blob_url = finished_event['result']['blob_url'] 285 | 286 | # download the blob (and do nothing with it) 287 | await self.get_blob(client, generated_image_blob_url) 288 | 289 | @pytest.mark.asyncio 290 | async def test_sync_txt2img( 291 | self, 292 | client, 293 | dummy_txt2img_params, 294 | resolved_dummy_txt2img_params, 295 | ): 296 | response = await client.get('/txt2img', params=dummy_txt2img_params) 297 | assert response.status_code == 200 298 | assert response.headers['Content-Type'] == 'application/json' 299 | 300 | generated_image = response.json() 301 | assert generated_image['parameters_used'] == resolved_dummy_txt2img_params 302 | 303 | @pytest.mark.asyncio 304 | async def test_cancel_task( 305 | self, 306 | client, 307 | websocket, 308 | dummy_txt2img_params, 309 | ): 310 | # create task 311 | response = await client.post('/task', json=dummy_txt2img_params) 312 | assert response.status_code == 200 313 | task_id = response.json() 314 | 315 | # cancel task 316 | response = await client.delete(f'/task/{task_id}') 317 | assert response.status_code == 204 318 | 319 | # check events 320 | await self.assert_websocket_received({ 321 | 'event_type': 'pending', 322 | 'task_id': task_id, 323 | }, websocket) 324 | 325 | await self.assert_websocket_received({ 326 | 'event_type': 'started', 327 | 'task_id': task_id, 328 | }, websocket) 329 | 330 | aborted_event = { 331 | 'event_type': 'aborted', 332 | 'task_id': task_id, 333 | 'reason': 'Task cancelled by user', 334 | } 335 | 336 | await self.assert_websocket_received(aborted_event, websocket) 337 | await self.assert_poll_status(client, task_id, aborted_event) 338 | -------------------------------------------------------------------------------- /stable_diffusion_api/api/tests/utils.py: -------------------------------------------------------------------------------- 1 | from typing import Union, Optional, Any, Sequence, MutableMapping 2 | 3 | from asgi_lifespan import LifespanManager 4 | from requests import PreparedRequest, Session, Response 5 | from requests_toolbelt import sessions 6 | import websockets.client 7 | 8 | import asyncio 9 | import json 10 | import requests.adapters 11 | from urllib.parse import unquote, urljoin, urlsplit 12 | from httpx import AsyncClient 13 | 14 | from starlette.testclient import ( 15 | TestClient, 16 | ASGI3App, 17 | ) 18 | from starlette.types import Scope, Message 19 | from starlette.websockets import WebSocketDisconnect 20 | 21 | 22 | class AsyncioWebSocketTestSession: 23 | def __init__( 24 | self, 25 | app: ASGI3App, 26 | scope: Scope, 27 | event_loop: asyncio.AbstractEventLoop, 28 | receive_queue: asyncio.Queue, 29 | send_queue: asyncio.Queue, 30 | ) -> None: 31 | self.event_loop = event_loop 32 | self.app = app 33 | self.scope = scope 34 | self.accepted_subprotocol = None 35 | self._receive_queue = receive_queue 36 | self._send_queue = send_queue 37 | 38 | async def __aenter__(self) -> "AsyncioWebSocketTestSession": 39 | self.event_loop.create_task(self._run()) 40 | await self.send({"type": "websocket.connect"}) 41 | message = await self.receive() 42 | assert message['type'] == 'websocket.accept' 43 | 44 | self.accepted_subprotocol = message.get("subprotocol", None) 45 | return self 46 | 47 | async def __aexit__(self, *args: Any) -> None: 48 | await self.close(1000) 49 | 50 | while not self._send_queue.empty(): 51 | message = await self._send_queue.get() 52 | if isinstance(message, BaseException): 53 | raise message 54 | 55 | async def _run(self) -> None: 56 | """ 57 | The sub-thread in which the websocket session runs. 58 | """ 59 | scope = self.scope 60 | receive = self._asgi_receive 61 | send = self._asgi_send 62 | try: 63 | await self.app(scope, receive, send) 64 | except BaseException as exc: 65 | await self._send_queue.put(exc) 66 | raise 67 | 68 | async def _asgi_receive(self) -> Message: 69 | while self._receive_queue.empty(): 70 | await asyncio.sleep(0) 71 | return await self._receive_queue.get() 72 | 73 | async def _asgi_send(self, message: Message) -> None: 74 | await self._send_queue.put(message) 75 | 76 | def _raise_on_close(self, message: Message) -> None: 77 | if message["type"] == "websocket.close": 78 | raise WebSocketDisconnect(message.get("code", 1000)) 79 | 80 | async def send(self, message: Message) -> None: 81 | await self._receive_queue.put(message) 82 | 83 | async def send_text(self, data: str) -> None: 84 | await self.send({"type": "websocket.receive", "text": data}) 85 | 86 | async def send_bytes(self, data: bytes) -> None: 87 | await self.send({"type": "websocket.receive", "bytes": data}) 88 | 89 | async def send_json(self, data: Any, mode: str = "text") -> None: 90 | assert mode in ["text", "binary"] 91 | text = json.dumps(data) 92 | if mode == "text": 93 | return await self.send({"type": "websocket.receive", "text": text}) 94 | 95 | return await self.send({"type": "websocket.receive", "bytes": text.encode("utf-8")}) 96 | 97 | async def close(self, code: int = 1000) -> None: 98 | await self.send({"type": "websocket.disconnect", "code": code}) 99 | 100 | async def receive(self) -> Message: 101 | while True: 102 | try: 103 | message = self._send_queue.get_nowait() 104 | 105 | if isinstance(message, BaseException): 106 | raise message 107 | 108 | return message 109 | except asyncio.queues.QueueEmpty: 110 | await asyncio.sleep(0.1) 111 | 112 | async def recv(self) -> str: 113 | message = await self.receive() 114 | self._raise_on_close(message) 115 | return message["text"] 116 | 117 | async def receive_bytes(self) -> bytes: 118 | message = await self.receive() 119 | self._raise_on_close(message) 120 | return message["bytes"] 121 | 122 | async def receive_json(self, mode: str = "text") -> Any: 123 | assert mode in ["text", "binary"] 124 | message = await self.receive() 125 | self._raise_on_close(message) 126 | 127 | if mode == "text": 128 | text = message["text"] 129 | else: 130 | text = message["bytes"].decode("utf-8") 131 | 132 | return json.loads(text) 133 | 134 | 135 | class _Upgrade(Exception): 136 | def __init__(self, session: AsyncioWebSocketTestSession) -> None: 137 | self.session = session 138 | 139 | 140 | class _AsyncioASGIAdapter(requests.adapters.HTTPAdapter): 141 | def __init__( 142 | self, 143 | app: ASGI3App, 144 | event_loop: asyncio.AbstractEventLoop, 145 | receive_queue: asyncio.Queue, 146 | send_queue: asyncio.Queue, 147 | raise_server_exceptions: bool = True, 148 | root_path: str = "", 149 | ) -> None: 150 | super().__init__() 151 | self.event_loop = event_loop 152 | self.app = app 153 | self.raise_server_exceptions = raise_server_exceptions 154 | self.root_path = root_path 155 | self.receive_queue = receive_queue 156 | self.send_queue = send_queue 157 | 158 | def send( 159 | self, 160 | request: PreparedRequest, 161 | *args: Any, 162 | **kwargs: Any 163 | ) -> None: 164 | scheme, netloc, path, query, fragment = ( 165 | str(item) for item in urlsplit(request.url) 166 | ) 167 | 168 | default_port = {"http": 80, "ws": 80, "https": 443, "wss": 443}[scheme] 169 | 170 | if ":" in netloc: 171 | host, port_string = netloc.split(":", 1) 172 | port = int(port_string) 173 | else: 174 | host = netloc 175 | port = default_port 176 | 177 | # Include the 'host' header. 178 | if "host" in request.headers: 179 | headers: list[tuple[bytes, bytes]] = [] 180 | elif port == default_port: 181 | headers = [(b"host", host.encode())] 182 | else: 183 | headers = [(b"host", (f"{host}:{port}").encode())] 184 | 185 | # Include other request headers. 186 | headers += [ 187 | (key.lower().encode(), value.encode()) 188 | for key, value in request.headers.items() 189 | ] 190 | 191 | if scheme not in {"ws", "wss"}: 192 | raise ValueError('Available only for websockets connection') 193 | 194 | subprotocol = request.headers.get("sec-websocket-protocol", None) 195 | 196 | if subprotocol is None: 197 | subprotocols: Sequence[str] = [] 198 | else: 199 | subprotocols = [value.strip() for value in subprotocol.split(",")] 200 | 201 | scope = { 202 | "type": "websocket", 203 | "path": unquote(path), 204 | "root_path": self.root_path, 205 | "scheme": scheme, 206 | "query_string": query.encode(), 207 | "headers": headers, 208 | "client": ["testclient", 50000], 209 | "server": [host, port], 210 | "subprotocols": subprotocols, 211 | } 212 | session = AsyncioWebSocketTestSession( 213 | self.app, 214 | scope, 215 | self.event_loop, 216 | receive_queue=self.receive_queue, 217 | send_queue=self.send_queue 218 | 219 | ) 220 | raise _Upgrade(session) 221 | 222 | 223 | class AsyncioTestClient(Session): 224 | def __init__( 225 | self, 226 | app: ASGI3App, 227 | base_url: str = "http://testserver", 228 | raise_server_exceptions: bool = True, 229 | root_path: str = "", 230 | event_loop: Optional[asyncio.AbstractEventLoop] = None 231 | ) -> None: 232 | super().__init__() 233 | 234 | self.receive_queue = asyncio.Queue() 235 | self.send_queue = asyncio.Queue() 236 | self.event_loop = event_loop or asyncio.get_event_loop() 237 | 238 | adapter = _AsyncioASGIAdapter( 239 | app, 240 | event_loop=self.event_loop, 241 | receive_queue=self.receive_queue, 242 | send_queue=self.send_queue, 243 | raise_server_exceptions=raise_server_exceptions, 244 | root_path=root_path, 245 | ) 246 | self.mount("http://", adapter) 247 | self.mount("https://", adapter) 248 | self.mount("ws://", adapter) 249 | self.mount("wss://", adapter) 250 | self.headers.update({"user-agent": "testclient"}) 251 | self.app = app 252 | self.base_url = base_url 253 | 254 | def websocket_connect( 255 | self, 256 | url: str, 257 | subprotocols: Optional[Sequence[str]] = None, 258 | **kwargs: Any 259 | ) -> Any: 260 | url = urljoin("ws://testserver", url) 261 | 262 | headers = kwargs.get("headers", {}) 263 | headers.setdefault("connection", "upgrade") 264 | headers.setdefault("sec-websocket-key", "testserver==") 265 | headers.setdefault("sec-websocket-version", "13") 266 | 267 | if subprotocols is not None: 268 | headers.setdefault("sec-websocket-protocol", ", ".join(subprotocols)) 269 | 270 | kwargs["headers"] = headers 271 | 272 | try: 273 | super().request("GET", url, **kwargs) 274 | except _Upgrade as exc: 275 | session = exc.session 276 | else: 277 | raise RuntimeError("Expected WebSocket upgrade") # pragma: no cover 278 | 279 | return session 280 | 281 | 282 | class AppClient: 283 | def __init__( 284 | self, 285 | client: AsyncClient, 286 | ): 287 | self.client = client 288 | 289 | self.headers = {} 290 | self.ws_stem = f'/events' 291 | 292 | async def set_public_token(self): 293 | response = await self.client.post('/token/all') 294 | token = response.json()['access_token'] 295 | self.set_token(token) 296 | 297 | def set_token(self, token: str): 298 | self.headers = { 299 | "Authorization": f"Bearer {token}", 300 | } 301 | self.ws_stem = f'/events?token={token}' 302 | 303 | async def get(self, *args, **kwargs): 304 | return await self.client.get(*args, **kwargs, headers=self.headers) 305 | 306 | async def post(self, *args, **kwargs): 307 | return await self.client.post(*args, **kwargs, headers=self.headers) 308 | 309 | async def delete(self, *args, **kwargs): 310 | return await self.client.delete(*args, **kwargs, headers=self.headers) 311 | 312 | async def __aenter__(self, *args, **kwargs): 313 | await self.client.__aenter__(*args, **kwargs) 314 | return self 315 | 316 | async def __aexit__(self, *args, **kwargs): 317 | await self.client.__aexit__(*args, **kwargs) 318 | 319 | def websocket_connect(self): 320 | raise NotImplementedError 321 | 322 | 323 | class LocalAppClient(AppClient): 324 | def __init__(self, client: AsyncClient, 325 | ws_client: AsyncioTestClient, 326 | lifespan_manager: LifespanManager): 327 | super().__init__(client) 328 | self.ws_client = ws_client 329 | self.lifespan = lifespan_manager 330 | 331 | def websocket_connect(self): 332 | return self.ws_client.websocket_connect(self.ws_stem) 333 | 334 | async def __aenter__(self, *args, **kwargs): 335 | await self.lifespan.__aenter__(*args, **kwargs) 336 | return await super().__aenter__(*args, **kwargs) 337 | 338 | async def __aexit__(self, *args, **kwargs): 339 | await super().__aexit__(*args, **kwargs) 340 | await self.lifespan.__aexit__(*args, **kwargs) 341 | 342 | 343 | class RemoteAppClient(AppClient): 344 | def websocket_connect(self): 345 | ws_base_url = str(self.client.base_url).replace('http', 'ws') 346 | ws_url = f'{ws_base_url}{self.ws_stem}' 347 | return websockets.client.connect(ws_url) 348 | -------------------------------------------------------------------------------- /stable_diffusion_api/api/base.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import os 3 | import datetime 4 | import uuid 5 | from collections import defaultdict 6 | from typing import Type, Union, Optional, AsyncGenerator 7 | 8 | import bcrypt 9 | import pydantic 10 | import typing 11 | import yaml 12 | from fastapi.openapi.utils import get_openapi 13 | 14 | from fastapi import FastAPI, Depends, websockets, Query, HTTPException, File, UploadFile 15 | from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm 16 | from starlette import status 17 | from starlette.requests import Request 18 | from starlette.responses import Response 19 | 20 | from stable_diffusion_api.api.utils.pyfa_converter import QueryDepends 21 | from stable_diffusion_api.engine.repos.blob_repo import BlobRepo, LocalBlobRepo 22 | from stable_diffusion_api.engine.repos.key_value_repo import KeyValueRepo 23 | from stable_diffusion_api.engine.repos.messaging_repo import MessagingRepo 24 | from stable_diffusion_api.engine.repos.user_repo import UserRepo 25 | from stable_diffusion_api.engine.services.event_service import EventListener, EventService 26 | from stable_diffusion_api.engine.services.status_service import StatusService 27 | from stable_diffusion_api.engine.services.task_service import TaskService 28 | from stable_diffusion_api.models.blob import BlobToken, BlobUrl 29 | from stable_diffusion_api.models.events import EventUnion, FinishedEvent, AbortedEvent 30 | from stable_diffusion_api.models.results import GeneratedBlob 31 | from stable_diffusion_api.models.params import Txt2ImgParams, Img2ImgParams, ParamsUnion 32 | from stable_diffusion_api.models.task import TaskId, Task 33 | from stable_diffusion_api.models.user import UserBase, AuthenticationError, User, AuthToken 34 | 35 | 36 | class AppConfig(pydantic.BaseModel): 37 | blob_repo_class: Type[BlobRepo] 38 | key_value_repo_class: Type[KeyValueRepo] 39 | messaging_repo_class: Type[MessagingRepo] 40 | user_repo_class: Type[UserRepo] 41 | 42 | SECRET_KEY: str = pydantic.Field(default_factory=lambda: os.environ["SECRET_KEY"]) 43 | ALGORITHM: str = "HS256" 44 | ACCESS_TOKEN_EXPIRE_MINUTES: int = 240 45 | BASE_URL: str = os.environ.get("BASE_URL", "http://localhost:8000") 46 | 47 | PRINT_LINK_WITH_TOKEN: bool = pydantic.Field(default_factory=lambda: os.environ["PRINT_LINK_WITH_TOKEN"] == "1") 48 | ENABLE_PUBLIC_ACCESS: bool = pydantic.Field(default_factory=lambda: os.environ["ENABLE_PUBLIC_ACCESS"] == "1") 49 | ENABLE_SIGNUP: bool = pydantic.Field(default_factory=lambda: os.environ["ENABLE_SIGNUP"] == "1") 50 | 51 | 52 | def create_app(app_config: AppConfig) -> FastAPI: 53 | app = FastAPI( 54 | title="Stable Diffusion Server", 55 | ) 56 | 57 | ### 58 | # Authentication 59 | ### 60 | 61 | async def construct_user_repo(): 62 | return app_config.user_repo_class( 63 | secret_key=app_config.SECRET_KEY, 64 | algorithm=app_config.ALGORITHM, 65 | access_token_expires=datetime.timedelta(minutes=app_config.ACCESS_TOKEN_EXPIRE_MINUTES), 66 | allow_public_token=app_config.ENABLE_PUBLIC_ACCESS, 67 | ) 68 | 69 | credentials_exception = HTTPException( 70 | status_code=status.HTTP_401_UNAUTHORIZED, 71 | detail="Could not validate credentials", 72 | headers={"WWW-Authenticate": "Bearer"}, 73 | ) 74 | 75 | # Optional bearer token handler 76 | optional_oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token", auto_error=False) 77 | 78 | async def get_user( 79 | header_token: Optional[str] = Depends(optional_oauth2_scheme), 80 | query_token: Optional[str] = Query(default=None, alias="token", include_in_schema=False), 81 | user_repo: UserRepo = Depends(construct_user_repo) 82 | ) -> User: 83 | token = header_token or query_token 84 | 85 | if token is None: 86 | if not app_config.ENABLE_PUBLIC_ACCESS: 87 | raise credentials_exception 88 | 89 | # create an ephemeral public user session 90 | # no token means no way to receive events on websocket (auth per session identified by token) 91 | # can still poll task status and use blobs though (auth by username, i.e. "all") 92 | token = user_repo.create_public_token().access_token 93 | 94 | try: 95 | return user_repo.must_get_user_by_token(token) 96 | except AuthenticationError: 97 | raise credentials_exception 98 | 99 | @app.post("/token", response_model=AuthToken) 100 | async def login_access_token(form_data: OAuth2PasswordRequestForm = Depends(), 101 | user_repo: UserRepo = Depends(construct_user_repo)) -> AuthToken: 102 | try: 103 | return user_repo.create_token_by_username_and_password(form_data.username, form_data.password) 104 | except AuthenticationError: 105 | raise credentials_exception 106 | 107 | @app.post("/token/all", response_model=AuthToken) 108 | async def public_access_token(user_repo: UserRepo = Depends(construct_user_repo)) -> AuthToken: 109 | if not app_config.ENABLE_PUBLIC_ACCESS: 110 | raise HTTPException(status_code=403, detail="Public token is disabled") 111 | return user_repo.create_public_token() 112 | 113 | @app.post("/user/{username}", response_model=UserBase) 114 | async def signup(username: str, 115 | password: str, 116 | user_repo: UserRepo = Depends(construct_user_repo)) -> UserBase: 117 | if not app_config.ENABLE_SIGNUP: 118 | raise HTTPException(status_code=403, detail="Signup is disabled") 119 | user = UserBase( 120 | username=username, 121 | ) 122 | user_repo.create_user(user, password) 123 | return user 124 | 125 | ### 126 | # Engine 127 | ### 128 | 129 | async def construct_messaging_repo() -> MessagingRepo: 130 | return app_config.messaging_repo_class() 131 | 132 | async def construct_key_value_repo() -> KeyValueRepo: 133 | return app_config.key_value_repo_class() 134 | 135 | async def construct_status_service( 136 | key_value_repo: KeyValueRepo = Depends(construct_key_value_repo), 137 | ) -> StatusService: 138 | return StatusService( 139 | key_value_repo=key_value_repo, 140 | ) 141 | 142 | async def construct_event_service( 143 | messaging_repo: MessagingRepo = Depends(construct_messaging_repo), 144 | status_service: StatusService = Depends(construct_status_service), 145 | ) -> EventService: 146 | return EventService( 147 | messaging_repo=messaging_repo, 148 | status_service=status_service, 149 | ) 150 | 151 | async def construct_task_service( 152 | messaging_repo: MessagingRepo = Depends(construct_messaging_repo), 153 | event_service: EventService = Depends(construct_event_service), 154 | status_service: StatusService = Depends(construct_status_service), 155 | ): 156 | return TaskService( 157 | messaging_repo=messaging_repo, 158 | event_service=event_service, 159 | status_service=status_service, 160 | ) 161 | 162 | async def construct_blob_repo() -> BlobRepo: 163 | if issubclass(app_config.blob_repo_class, LocalBlobRepo): 164 | return app_config.blob_repo_class( 165 | base_blob_url=app_config.BASE_URL + "/blob", 166 | secret_key=app_config.SECRET_KEY, 167 | algorithm=app_config.ALGORITHM, 168 | ) 169 | return app_config.blob_repo_class() 170 | 171 | ### 172 | # Event listener 173 | ### 174 | 175 | queues_by_session_id: dict[str, list[asyncio.Queue]] = defaultdict(list) 176 | queues_by_task_id: dict[TaskId, list[asyncio.Queue]] = defaultdict(list) 177 | 178 | listener_ready: bool = False 179 | 180 | async def event_listener(): 181 | nonlocal listener_ready 182 | 183 | # instantiate the event listener 184 | listener = EventListener( 185 | messaging_repo=app_config.messaging_repo_class(), 186 | ) 187 | 188 | # initialize listener 189 | await listener.initialize() 190 | listener_ready = True 191 | 192 | async for session_id, event in listener.listen(): 193 | for queue in queues_by_session_id[session_id]: 194 | await queue.put(event) 195 | for queue in queues_by_task_id[event.task_id]: 196 | await queue.put(event) 197 | 198 | listener_task: Optional[asyncio.Task] = None 199 | 200 | @app.on_event("startup") 201 | async def startup_event(): 202 | nonlocal listener_task 203 | listener_task = asyncio.create_task(event_listener()) 204 | # only start the app when the listener is ready 205 | while not listener_ready: 206 | await asyncio.sleep(0.1) 207 | 208 | @app.on_event("shutdown") 209 | async def shutdown_event(): 210 | nonlocal listener_task 211 | nonlocal listener_ready 212 | queues_by_session_id.clear() 213 | queues_by_task_id.clear() 214 | if listener_task is not None: 215 | listener_task.cancel() 216 | listener_task = None 217 | listener_ready = False 218 | 219 | async def subscribe_to_session(session_id: str) -> AsyncGenerator[EventUnion, None]: 220 | queue = asyncio.Queue() 221 | queues_by_session_id[session_id].append(queue) 222 | try: 223 | while True: 224 | yield await queue.get() 225 | finally: 226 | queues_by_session_id[session_id].remove(queue) 227 | 228 | async def subscribe_to_task(task_id: TaskId) -> AsyncGenerator[EventUnion, None]: 229 | queue = asyncio.Queue() 230 | queues_by_task_id[task_id].append(queue) 231 | try: 232 | while True: 233 | yield await queue.get() 234 | finally: 235 | queues_by_task_id[task_id].remove(queue) 236 | 237 | ### 238 | # Asynchronous API 239 | ### 240 | 241 | @app.post("/task", response_model=TaskId) 242 | async def create_task( 243 | parameters: ParamsUnion, 244 | task_service: TaskService = Depends(construct_task_service), 245 | user: User = Depends(get_user), 246 | ) -> TaskId: 247 | task = Task( 248 | parameters=parameters, 249 | user=user, 250 | ) 251 | task_service.push_task(task) 252 | return task.task_id 253 | 254 | @app.get("/task/{task_id}", response_model=EventUnion) 255 | async def poll_task_status( 256 | task_id: TaskId, 257 | response: Response, 258 | status_service: StatusService = Depends(construct_status_service), 259 | user: User = Depends(get_user), 260 | ) -> EventUnion: 261 | response.headers["Cache-Control"] = "no-cache, no-store" # don't cache poll requests 262 | 263 | task = status_service.get_task(task_id) 264 | if task is None or task.user.username != user.username: 265 | raise HTTPException(status_code=404, detail="Task not found") 266 | event = status_service.get_latest_event(task_id) 267 | if event is None: 268 | raise RuntimeError("Task exists but no event found") 269 | return event 270 | 271 | @app.delete("/task/{task_id}", responses={ 272 | 204: {"description": "Task cancelled"}, 273 | 404: {"description": "Task not found"}, 274 | }) 275 | async def delete_task( 276 | task_id: TaskId, 277 | status_service: StatusService = Depends(construct_status_service), 278 | user: User = Depends(get_user), 279 | ): 280 | task = status_service.get_task(task_id) 281 | if task is None or task.user.username != user.username: 282 | raise HTTPException(status_code=404, detail="Task not found") 283 | status_service.cancel_task(task.task_id) 284 | return Response(status_code=204) 285 | 286 | ### 287 | # Blobs (eventually to be replaced with a proper object store, and pre-signed POST/GET URLs) 288 | ### 289 | 290 | @app.get( 291 | "/blob/{blob_token}", 292 | responses={ 293 | 200: { 294 | "content": {"image/png": {}} 295 | }, 296 | 404: { 297 | "description": "Blob not found", 298 | } 299 | }, 300 | include_in_schema=False, 301 | ) 302 | async def get_blob( 303 | blob_token: BlobToken, 304 | blob_repo: LocalBlobRepo = Depends(construct_blob_repo), 305 | ) -> Response: 306 | blob = blob_repo.get_blob_by_token(blob_token) 307 | if blob is None: 308 | raise HTTPException(status_code=404, detail="Blob not found") 309 | return Response(content=blob, media_type="image/png") 310 | 311 | @app.post( 312 | "/blob", 313 | response_model=BlobUrl, 314 | ) 315 | async def post_blob( 316 | blob_data: UploadFile = File(), 317 | blob_repo: LocalBlobRepo = Depends(construct_blob_repo), 318 | ) -> BlobUrl: 319 | return blob_repo.put_blob(blob_data.file.read()) 320 | 321 | ### 322 | # Synchronous API (convenience wrappers for the asynchronous API) 323 | ### 324 | 325 | async def wait_task_finished( 326 | task: Task, 327 | request: Request, 328 | status_service: StatusService, 329 | ) -> FinishedEvent: 330 | async def get_finished_event_or_raise(): 331 | async for ev in subscribe_to_task(task.task_id): 332 | if isinstance(ev, AbortedEvent): 333 | raise HTTPException(status_code=500, detail=ev.reason) 334 | if isinstance(ev, FinishedEvent): 335 | return ev 336 | raise RuntimeError("Event stream ended unexpectedly") 337 | 338 | async def disconnect_listener() -> None: 339 | while not await request.is_disconnected(): 340 | await asyncio.sleep(0.1) 341 | 342 | done, pending = await asyncio.wait([get_finished_event_or_raise(), disconnect_listener()], 343 | return_when=asyncio.FIRST_COMPLETED) 344 | 345 | for aio_task in pending: 346 | aio_task.cancel() 347 | 348 | if await request.is_disconnected(): 349 | status_service.cancel_task(task.task_id) 350 | raise HTTPException(status_code=499, detail="Client disconnected") 351 | 352 | event = done.pop().result() 353 | if event is None: 354 | raise RuntimeError("Event stream ended unexpectedly") 355 | return event 356 | 357 | for param_type in typing.get_args(ParamsUnion): 358 | @app.get( 359 | f'/{param_type._endpoint_stem}', 360 | summary=param_type._endpoint_stem, 361 | ) 362 | async def get_endpoint( 363 | request: Request, 364 | parameters: param_type = QueryDepends(param_type), # type: ignore 365 | user: User = Depends(get_user), 366 | task_service: TaskService = Depends(construct_task_service), 367 | status_service: StatusService = Depends(construct_status_service), 368 | ) -> GeneratedBlob: 369 | task = Task( 370 | parameters=parameters, 371 | user=user, 372 | ) 373 | task_service.push_task(task) 374 | event = await wait_task_finished(task, request, status_service) 375 | return event.result 376 | 377 | ### 378 | # Websocket 379 | ### 380 | 381 | async def get_ws_user( 382 | websocket: websockets.WebSocket, 383 | token: Union[str, None] = Query(default=None), 384 | user_repo: UserRepo = Depends(construct_user_repo), 385 | ) -> User: 386 | if token is None: 387 | await websocket.close(code=1008, reason="Missing token") 388 | raise HTTPException(status_code=401, detail="Unauthorized") 389 | 390 | try: 391 | return user_repo.must_get_user_by_token(token) 392 | except AuthenticationError: 393 | await websocket.close(code=1008, reason="Invalid token") 394 | raise HTTPException(status_code=401, detail="User not found") 395 | 396 | @app.websocket('/events') 397 | async def websocket_endpoint( 398 | websocket: websockets.WebSocket, 399 | user: User = Depends(get_ws_user), 400 | ): 401 | await websocket.accept() 402 | async for event in subscribe_to_session(user.session_id): 403 | await websocket.send_json(event.json()) 404 | await websocket.close() 405 | 406 | ### 407 | # OpenAPI 408 | ### 409 | 410 | openapi_schema = app.openapi() 411 | with open('openapi.yml', 'w') as f: 412 | yaml.dump(openapi_schema, f) 413 | 414 | ### 415 | # Create default user 416 | ### 417 | 418 | def print_link_with_token() -> None: 419 | # construct token repo 420 | user_repo = app_config.user_repo_class( 421 | secret_key=app_config.SECRET_KEY, 422 | algorithm=app_config.ALGORITHM, 423 | access_token_expires=datetime.timedelta(minutes=app_config.ACCESS_TOKEN_EXPIRE_MINUTES), 424 | allow_public_token=app_config.ENABLE_PUBLIC_ACCESS, 425 | ) 426 | 427 | # create default user 428 | username = "default_" + str(uuid.uuid4()) 429 | password = bcrypt.hashpw(str(uuid.uuid4()).encode(), bcrypt.gensalt()).decode() 430 | user_repo.create_user(user=UserBase(username=username), password=password) 431 | token = user_repo.create_token_by_username_and_password(username=username, password=password) 432 | 433 | # print link 434 | print(f"Try visiting {app_config.BASE_URL}/txt2img?" 435 | f"prompt=corgi&" 436 | f"steps=20&" 437 | f"model=CompVis/stable-diffusion-v1-4&" 438 | f"token={token.access_token}") 439 | 440 | if app_config.PRINT_LINK_WITH_TOKEN: 441 | print_link_with_token() 442 | 443 | return app 444 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /openapi.yml: -------------------------------------------------------------------------------- 1 | components: 2 | schemas: 3 | AbortedEvent: 4 | properties: 5 | event_type: 6 | enum: 7 | - aborted 8 | title: Event Type 9 | type: string 10 | reason: 11 | title: Reason 12 | type: string 13 | task_id: 14 | title: Task Id 15 | type: string 16 | required: 17 | - event_type 18 | - task_id 19 | - reason 20 | title: AbortedEvent 21 | type: object 22 | AuthToken: 23 | properties: 24 | access_token: 25 | title: Access Token 26 | type: string 27 | token_type: 28 | title: Token Type 29 | type: string 30 | required: 31 | - access_token 32 | - token_type 33 | title: AuthToken 34 | type: object 35 | Body_login_access_token_token_post: 36 | properties: 37 | client_id: 38 | title: Client Id 39 | type: string 40 | client_secret: 41 | title: Client Secret 42 | type: string 43 | grant_type: 44 | pattern: password 45 | title: Grant Type 46 | type: string 47 | password: 48 | title: Password 49 | type: string 50 | scope: 51 | default: '' 52 | title: Scope 53 | type: string 54 | username: 55 | title: Username 56 | type: string 57 | required: 58 | - username 59 | - password 60 | title: Body_login_access_token_token_post 61 | type: object 62 | Body_post_blob_blob_post: 63 | properties: 64 | blob_data: 65 | format: binary 66 | title: Blob Data 67 | type: string 68 | required: 69 | - blob_data 70 | title: Body_post_blob_blob_post 71 | type: object 72 | FinishedEvent: 73 | properties: 74 | event_type: 75 | enum: 76 | - finished 77 | title: Event Type 78 | type: string 79 | result: 80 | $ref: '#/components/schemas/GeneratedBlob' 81 | task_id: 82 | title: Task Id 83 | type: string 84 | required: 85 | - event_type 86 | - task_id 87 | - result 88 | title: FinishedEvent 89 | type: object 90 | GeneratedBlob: 91 | properties: 92 | blob_url: 93 | title: Blob Url 94 | type: string 95 | parameters_used: 96 | anyOf: 97 | - $ref: '#/components/schemas/Txt2ImgParams' 98 | - $ref: '#/components/schemas/Img2ImgParams' 99 | - $ref: '#/components/schemas/InpaintParams' 100 | title: Parameters Used 101 | required: 102 | - blob_url 103 | - parameters_used 104 | title: GeneratedBlob 105 | type: object 106 | HTTPValidationError: 107 | properties: 108 | detail: 109 | items: 110 | $ref: '#/components/schemas/ValidationError' 111 | title: Detail 112 | type: array 113 | title: HTTPValidationError 114 | type: object 115 | Img2ImgParams: 116 | additionalProperties: false 117 | properties: 118 | guidance: 119 | default: 7.5 120 | description: 'Higher guidance encourages generation closely linked to `prompt`, 121 | usually at the expense of lower image quality. Try using more steps to 122 | improve image quality when using high guidance. Guidance is disabled by 123 | setting `guidance` to `1`. `guidance` is defined as `w` of equation 2. 124 | of [ImagenPaper](https://arxiv.org/pdf/2205.11487.pdf). See also: [Classifier-Free 125 | Diffusion Guidance](https://arxiv.org/abs/2207.12598).' 126 | minimum: 1.0 127 | title: Guidance 128 | type: number 129 | initial_image: 130 | description: 'The image to use as input for image generation. The image 131 | must have a width and height divisible by 8. ' 132 | title: Initial Image 133 | type: string 134 | model: 135 | default: CompVis/stable-diffusion-v1-4 136 | description: 'The model to use for image generation. One of: the *repo id* 137 | of a pretrained pipeline hosted on huggingface (e.g. ''CompVis/stable-diffusion-v1-4''), 138 | *a path* to a *directory* containing pipeline weights, (e.g., ''./my_model_directory/''). ' 139 | title: Model 140 | type: string 141 | negative_prompt: 142 | description: The prompt to dissuade image generation. Ignored when not using 143 | guidance (i.e., if `guidance` is `1`). 144 | title: Negative Prompt 145 | type: string 146 | params_type: 147 | default: img2img 148 | enum: 149 | - img2img 150 | title: Params Type 151 | type: string 152 | prompt: 153 | description: The prompt to guide image generation. 154 | title: Prompt 155 | type: string 156 | safety_filter: 157 | default: true 158 | description: Ensure that you abide by the conditions of the Stable Diffusion 159 | license and do not expose unfiltered results in services or applications 160 | open to the public. For more information, please see https://github.com/huggingface/diffusers/pull/254 161 | title: Safety Filter 162 | type: boolean 163 | scheduler: 164 | default: plms 165 | description: The scheduler to use for image generation. Currently only 'plms', 166 | 'ddim', and 'k-lms', are supported. 167 | enum: 168 | - plms 169 | - ddim 170 | - k-lms 171 | title: Scheduler 172 | type: string 173 | seed: 174 | description: The randomness seed to use for image generation. If not set, 175 | a random seed is used. 176 | title: Seed 177 | type: integer 178 | steps: 179 | default: 20 180 | description: The number of denoising steps. More denoising steps usually 181 | lead to a higher quality image at the expense of slower inference. 182 | title: Steps 183 | type: integer 184 | strength: 185 | default: 0.8 186 | description: Conceptually, indicates how much to transform the image. The 187 | image will be used as a starting point, adding more noise to it the larger 188 | the `strength`. The number of denoising steps depends on the amount of 189 | noise initially added. When `strength` is 1, it becomes pure noise, and 190 | the denoising process will run for the full number of iterations specified 191 | in `steps`. A value of 1, therefore, works like Txt2Img, essentially ignoring 192 | the reference image. 193 | maximum: 1.0 194 | minimum: 0.0 195 | title: Strength 196 | type: number 197 | required: 198 | - prompt 199 | - initial_image 200 | title: Img2ImgParams 201 | type: object 202 | InpaintParams: 203 | additionalProperties: false 204 | properties: 205 | guidance: 206 | default: 7.5 207 | description: 'Higher guidance encourages generation closely linked to `prompt`, 208 | usually at the expense of lower image quality. Try using more steps to 209 | improve image quality when using high guidance. Guidance is disabled by 210 | setting `guidance` to `1`. `guidance` is defined as `w` of equation 2. 211 | of [ImagenPaper](https://arxiv.org/pdf/2205.11487.pdf). See also: [Classifier-Free 212 | Diffusion Guidance](https://arxiv.org/abs/2207.12598).' 213 | minimum: 1.0 214 | title: Guidance 215 | type: number 216 | initial_image: 217 | description: 'The image to use as input for image generation. It must have 218 | a width and height divisible by 8. ' 219 | title: Initial Image 220 | type: string 221 | mask: 222 | description: The mask to use for image generation. It must have the same 223 | width and height as the initial image. It will be converted to a black-and-white 224 | image, wherein white indicates the area to be inpainted. 225 | title: Mask 226 | type: string 227 | model: 228 | default: runwayml/stable-diffusion-inpainting 229 | description: The model to use for image generation, e.g. 'runwayml/stable-diffusion-inpainting'. 230 | title: Model 231 | type: string 232 | negative_prompt: 233 | description: The prompt to dissuade image generation. Ignored when not using 234 | guidance (i.e., if `guidance` is `1`). 235 | title: Negative Prompt 236 | type: string 237 | params_type: 238 | default: inpaint 239 | enum: 240 | - inpaint 241 | title: Params Type 242 | type: string 243 | prompt: 244 | description: The prompt to guide image generation. 245 | title: Prompt 246 | type: string 247 | safety_filter: 248 | default: true 249 | description: Ensure that you abide by the conditions of the Stable Diffusion 250 | license and do not expose unfiltered results in services or applications 251 | open to the public. For more information, please see https://github.com/huggingface/diffusers/pull/254 252 | title: Safety Filter 253 | type: boolean 254 | scheduler: 255 | default: plms 256 | description: The scheduler to use for image generation. Currently only 'plms', 257 | 'ddim', and 'k-lms', are supported. 258 | enum: 259 | - plms 260 | - ddim 261 | - k-lms 262 | title: Scheduler 263 | type: string 264 | seed: 265 | description: The randomness seed to use for image generation. If not set, 266 | a random seed is used. 267 | title: Seed 268 | type: integer 269 | steps: 270 | default: 20 271 | description: The number of denoising steps. More denoising steps usually 272 | lead to a higher quality image at the expense of slower inference. 273 | title: Steps 274 | type: integer 275 | required: 276 | - prompt 277 | - initial_image 278 | - mask 279 | title: InpaintParams 280 | type: object 281 | PendingEvent: 282 | properties: 283 | event_type: 284 | enum: 285 | - pending 286 | title: Event Type 287 | type: string 288 | task_id: 289 | title: Task Id 290 | type: string 291 | required: 292 | - event_type 293 | - task_id 294 | title: PendingEvent 295 | type: object 296 | StartedEvent: 297 | properties: 298 | event_type: 299 | enum: 300 | - started 301 | title: Event Type 302 | type: string 303 | task_id: 304 | title: Task Id 305 | type: string 306 | required: 307 | - event_type 308 | - task_id 309 | title: StartedEvent 310 | type: object 311 | Txt2ImgParams: 312 | additionalProperties: false 313 | properties: 314 | guidance: 315 | default: 7.5 316 | description: 'Higher guidance encourages generation closely linked to `prompt`, 317 | usually at the expense of lower image quality. Try using more steps to 318 | improve image quality when using high guidance. Guidance is disabled by 319 | setting `guidance` to `1`. `guidance` is defined as `w` of equation 2. 320 | of [ImagenPaper](https://arxiv.org/pdf/2205.11487.pdf). See also: [Classifier-Free 321 | Diffusion Guidance](https://arxiv.org/abs/2207.12598).' 322 | minimum: 1.0 323 | title: Guidance 324 | type: number 325 | height: 326 | default: 512 327 | description: The pixel height of the generated image. 328 | title: Height 329 | type: integer 330 | model: 331 | default: CompVis/stable-diffusion-v1-4 332 | description: 'The model to use for image generation. One of: the *repo id* 333 | of a pretrained pipeline hosted on huggingface (e.g. ''CompVis/stable-diffusion-v1-4''), 334 | *a path* to a *directory* containing pipeline weights, (e.g., ''./my_model_directory/''). ' 335 | title: Model 336 | type: string 337 | negative_prompt: 338 | description: The prompt to dissuade image generation. Ignored when not using 339 | guidance (i.e., if `guidance` is `1`). 340 | title: Negative Prompt 341 | type: string 342 | params_type: 343 | default: txt2img 344 | enum: 345 | - txt2img 346 | title: Params Type 347 | type: string 348 | prompt: 349 | description: The prompt to guide image generation. 350 | title: Prompt 351 | type: string 352 | safety_filter: 353 | default: true 354 | description: Ensure that you abide by the conditions of the Stable Diffusion 355 | license and do not expose unfiltered results in services or applications 356 | open to the public. For more information, please see https://github.com/huggingface/diffusers/pull/254 357 | title: Safety Filter 358 | type: boolean 359 | scheduler: 360 | default: plms 361 | description: The scheduler to use for image generation. Currently only 'plms', 362 | 'ddim', and 'k-lms', are supported. 363 | enum: 364 | - plms 365 | - ddim 366 | - k-lms 367 | title: Scheduler 368 | type: string 369 | seed: 370 | description: The randomness seed to use for image generation. If not set, 371 | a random seed is used. 372 | title: Seed 373 | type: integer 374 | steps: 375 | default: 20 376 | description: The number of denoising steps. More denoising steps usually 377 | lead to a higher quality image at the expense of slower inference. 378 | title: Steps 379 | type: integer 380 | width: 381 | default: 512 382 | description: The pixel width of the generated image. 383 | title: Width 384 | type: integer 385 | required: 386 | - prompt 387 | title: Txt2ImgParams 388 | type: object 389 | UserBase: 390 | properties: 391 | username: 392 | title: Username 393 | type: string 394 | required: 395 | - username 396 | title: UserBase 397 | type: object 398 | ValidationError: 399 | properties: 400 | loc: 401 | items: 402 | anyOf: 403 | - type: string 404 | - type: integer 405 | title: Location 406 | type: array 407 | msg: 408 | title: Message 409 | type: string 410 | type: 411 | title: Error Type 412 | type: string 413 | required: 414 | - loc 415 | - msg 416 | - type 417 | title: ValidationError 418 | type: object 419 | securitySchemes: 420 | OAuth2PasswordBearer: 421 | flows: 422 | password: 423 | scopes: {} 424 | tokenUrl: token 425 | type: oauth2 426 | info: 427 | title: Stable Diffusion Server 428 | version: 0.1.0 429 | openapi: 3.0.2 430 | paths: 431 | /blob: 432 | post: 433 | operationId: post_blob_blob_post 434 | requestBody: 435 | content: 436 | multipart/form-data: 437 | schema: 438 | $ref: '#/components/schemas/Body_post_blob_blob_post' 439 | required: true 440 | responses: 441 | '200': 442 | content: 443 | application/json: 444 | schema: 445 | title: Response Post Blob Blob Post 446 | type: string 447 | description: Successful Response 448 | '422': 449 | content: 450 | application/json: 451 | schema: 452 | $ref: '#/components/schemas/HTTPValidationError' 453 | description: Validation Error 454 | summary: Post Blob 455 | /img2img: 456 | get: 457 | operationId: get_endpoint_img2img_get 458 | parameters: 459 | - in: query 460 | name: params_type 461 | required: false 462 | schema: 463 | default: img2img 464 | enum: 465 | - img2img 466 | title: Params Type 467 | type: string 468 | - description: 'The model to use for image generation. One of: the *repo id* 469 | of a pretrained pipeline hosted on huggingface (e.g. ''CompVis/stable-diffusion-v1-4''), 470 | *a path* to a *directory* containing pipeline weights, (e.g., ''./my_model_directory/''). ' 471 | in: query 472 | name: model 473 | required: false 474 | schema: 475 | default: CompVis/stable-diffusion-v1-4 476 | description: 'The model to use for image generation. One of: the *repo id* 477 | of a pretrained pipeline hosted on huggingface (e.g. ''CompVis/stable-diffusion-v1-4''), 478 | *a path* to a *directory* containing pipeline weights, (e.g., ''./my_model_directory/''). ' 479 | title: Model 480 | type: string 481 | - description: The prompt to guide image generation. 482 | in: query 483 | name: prompt 484 | required: true 485 | schema: 486 | description: The prompt to guide image generation. 487 | title: Prompt 488 | type: string 489 | - description: The prompt to dissuade image generation. Ignored when not using 490 | guidance (i.e., if `guidance` is `1`). 491 | in: query 492 | name: negative_prompt 493 | required: false 494 | schema: 495 | description: The prompt to dissuade image generation. Ignored when not using 496 | guidance (i.e., if `guidance` is `1`). 497 | title: Negative Prompt 498 | type: string 499 | - description: The number of denoising steps. More denoising steps usually lead 500 | to a higher quality image at the expense of slower inference. 501 | in: query 502 | name: steps 503 | required: false 504 | schema: 505 | default: 20 506 | description: The number of denoising steps. More denoising steps usually 507 | lead to a higher quality image at the expense of slower inference. 508 | title: Steps 509 | type: integer 510 | - description: 'Higher guidance encourages generation closely linked to `prompt`, 511 | usually at the expense of lower image quality. Try using more steps to improve 512 | image quality when using high guidance. Guidance is disabled by setting 513 | `guidance` to `1`. `guidance` is defined as `w` of equation 2. of [ImagenPaper](https://arxiv.org/pdf/2205.11487.pdf). 514 | See also: [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).' 515 | in: query 516 | name: guidance 517 | required: false 518 | schema: 519 | default: 7.5 520 | description: 'Higher guidance encourages generation closely linked to `prompt`, 521 | usually at the expense of lower image quality. Try using more steps to 522 | improve image quality when using high guidance. Guidance is disabled by 523 | setting `guidance` to `1`. `guidance` is defined as `w` of equation 2. 524 | of [ImagenPaper](https://arxiv.org/pdf/2205.11487.pdf). See also: [Classifier-Free 525 | Diffusion Guidance](https://arxiv.org/abs/2207.12598).' 526 | minimum: 1.0 527 | title: Guidance 528 | type: number 529 | - description: The scheduler to use for image generation. Currently only 'plms', 530 | 'ddim', and 'k-lms', are supported. 531 | in: query 532 | name: scheduler 533 | required: false 534 | schema: 535 | default: plms 536 | description: The scheduler to use for image generation. Currently only 'plms', 537 | 'ddim', and 'k-lms', are supported. 538 | enum: 539 | - plms 540 | - ddim 541 | - k-lms 542 | title: Scheduler 543 | type: string 544 | - description: Ensure that you abide by the conditions of the Stable Diffusion 545 | license and do not expose unfiltered results in services or applications 546 | open to the public. For more information, please see https://github.com/huggingface/diffusers/pull/254 547 | in: query 548 | name: safety_filter 549 | required: false 550 | schema: 551 | default: true 552 | description: Ensure that you abide by the conditions of the Stable Diffusion 553 | license and do not expose unfiltered results in services or applications 554 | open to the public. For more information, please see https://github.com/huggingface/diffusers/pull/254 555 | title: Safety Filter 556 | type: boolean 557 | - description: The randomness seed to use for image generation. If not set, 558 | a random seed is used. 559 | in: query 560 | name: seed 561 | required: false 562 | schema: 563 | description: The randomness seed to use for image generation. If not set, 564 | a random seed is used. 565 | title: Seed 566 | type: integer 567 | - description: 'The image to use as input for image generation. The image must 568 | have a width and height divisible by 8. ' 569 | in: query 570 | name: initial_image 571 | required: true 572 | schema: 573 | description: 'The image to use as input for image generation. The image 574 | must have a width and height divisible by 8. ' 575 | title: Initial Image 576 | type: string 577 | - description: Conceptually, indicates how much to transform the image. The 578 | image will be used as a starting point, adding more noise to it the larger 579 | the `strength`. The number of denoising steps depends on the amount of noise 580 | initially added. When `strength` is 1, it becomes pure noise, and the denoising 581 | process will run for the full number of iterations specified in `steps`. 582 | A value of 1, therefore, works like Txt2Img, essentially ignoring the reference 583 | image. 584 | in: query 585 | name: strength 586 | required: false 587 | schema: 588 | default: 0.8 589 | description: Conceptually, indicates how much to transform the image. The 590 | image will be used as a starting point, adding more noise to it the larger 591 | the `strength`. The number of denoising steps depends on the amount of 592 | noise initially added. When `strength` is 1, it becomes pure noise, and 593 | the denoising process will run for the full number of iterations specified 594 | in `steps`. A value of 1, therefore, works like Txt2Img, essentially ignoring 595 | the reference image. 596 | maximum: 1.0 597 | minimum: 0.0 598 | title: Strength 599 | type: number 600 | responses: 601 | '200': 602 | content: 603 | application/json: 604 | schema: {} 605 | description: Successful Response 606 | '422': 607 | content: 608 | application/json: 609 | schema: 610 | $ref: '#/components/schemas/HTTPValidationError' 611 | description: Validation Error 612 | security: 613 | - OAuth2PasswordBearer: [] 614 | summary: img2img 615 | /inpaint: 616 | get: 617 | operationId: get_endpoint_inpaint_get 618 | parameters: 619 | - in: query 620 | name: params_type 621 | required: false 622 | schema: 623 | default: inpaint 624 | enum: 625 | - inpaint 626 | title: Params Type 627 | type: string 628 | - description: The model to use for image generation, e.g. 'runwayml/stable-diffusion-inpainting'. 629 | in: query 630 | name: model 631 | required: false 632 | schema: 633 | default: runwayml/stable-diffusion-inpainting 634 | description: The model to use for image generation, e.g. 'runwayml/stable-diffusion-inpainting'. 635 | title: Model 636 | type: string 637 | - description: The prompt to guide image generation. 638 | in: query 639 | name: prompt 640 | required: true 641 | schema: 642 | description: The prompt to guide image generation. 643 | title: Prompt 644 | type: string 645 | - description: The prompt to dissuade image generation. Ignored when not using 646 | guidance (i.e., if `guidance` is `1`). 647 | in: query 648 | name: negative_prompt 649 | required: false 650 | schema: 651 | description: The prompt to dissuade image generation. Ignored when not using 652 | guidance (i.e., if `guidance` is `1`). 653 | title: Negative Prompt 654 | type: string 655 | - description: The number of denoising steps. More denoising steps usually lead 656 | to a higher quality image at the expense of slower inference. 657 | in: query 658 | name: steps 659 | required: false 660 | schema: 661 | default: 20 662 | description: The number of denoising steps. More denoising steps usually 663 | lead to a higher quality image at the expense of slower inference. 664 | title: Steps 665 | type: integer 666 | - description: 'Higher guidance encourages generation closely linked to `prompt`, 667 | usually at the expense of lower image quality. Try using more steps to improve 668 | image quality when using high guidance. Guidance is disabled by setting 669 | `guidance` to `1`. `guidance` is defined as `w` of equation 2. of [ImagenPaper](https://arxiv.org/pdf/2205.11487.pdf). 670 | See also: [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).' 671 | in: query 672 | name: guidance 673 | required: false 674 | schema: 675 | default: 7.5 676 | description: 'Higher guidance encourages generation closely linked to `prompt`, 677 | usually at the expense of lower image quality. Try using more steps to 678 | improve image quality when using high guidance. Guidance is disabled by 679 | setting `guidance` to `1`. `guidance` is defined as `w` of equation 2. 680 | of [ImagenPaper](https://arxiv.org/pdf/2205.11487.pdf). See also: [Classifier-Free 681 | Diffusion Guidance](https://arxiv.org/abs/2207.12598).' 682 | minimum: 1.0 683 | title: Guidance 684 | type: number 685 | - description: The scheduler to use for image generation. Currently only 'plms', 686 | 'ddim', and 'k-lms', are supported. 687 | in: query 688 | name: scheduler 689 | required: false 690 | schema: 691 | default: plms 692 | description: The scheduler to use for image generation. Currently only 'plms', 693 | 'ddim', and 'k-lms', are supported. 694 | enum: 695 | - plms 696 | - ddim 697 | - k-lms 698 | title: Scheduler 699 | type: string 700 | - description: Ensure that you abide by the conditions of the Stable Diffusion 701 | license and do not expose unfiltered results in services or applications 702 | open to the public. For more information, please see https://github.com/huggingface/diffusers/pull/254 703 | in: query 704 | name: safety_filter 705 | required: false 706 | schema: 707 | default: true 708 | description: Ensure that you abide by the conditions of the Stable Diffusion 709 | license and do not expose unfiltered results in services or applications 710 | open to the public. For more information, please see https://github.com/huggingface/diffusers/pull/254 711 | title: Safety Filter 712 | type: boolean 713 | - description: The randomness seed to use for image generation. If not set, 714 | a random seed is used. 715 | in: query 716 | name: seed 717 | required: false 718 | schema: 719 | description: The randomness seed to use for image generation. If not set, 720 | a random seed is used. 721 | title: Seed 722 | type: integer 723 | - description: 'The image to use as input for image generation. It must have 724 | a width and height divisible by 8. ' 725 | in: query 726 | name: initial_image 727 | required: true 728 | schema: 729 | description: 'The image to use as input for image generation. It must have 730 | a width and height divisible by 8. ' 731 | title: Initial Image 732 | type: string 733 | - description: The mask to use for image generation. It must have the same width 734 | and height as the initial image. It will be converted to a black-and-white 735 | image, wherein white indicates the area to be inpainted. 736 | in: query 737 | name: mask 738 | required: true 739 | schema: 740 | description: The mask to use for image generation. It must have the same 741 | width and height as the initial image. It will be converted to a black-and-white 742 | image, wherein white indicates the area to be inpainted. 743 | title: Mask 744 | type: string 745 | responses: 746 | '200': 747 | content: 748 | application/json: 749 | schema: {} 750 | description: Successful Response 751 | '422': 752 | content: 753 | application/json: 754 | schema: 755 | $ref: '#/components/schemas/HTTPValidationError' 756 | description: Validation Error 757 | security: 758 | - OAuth2PasswordBearer: [] 759 | summary: inpaint 760 | /task: 761 | post: 762 | operationId: create_task_task_post 763 | requestBody: 764 | content: 765 | application/json: 766 | schema: 767 | anyOf: 768 | - $ref: '#/components/schemas/Txt2ImgParams' 769 | - $ref: '#/components/schemas/Img2ImgParams' 770 | - $ref: '#/components/schemas/InpaintParams' 771 | title: Parameters 772 | required: true 773 | responses: 774 | '200': 775 | content: 776 | application/json: 777 | schema: 778 | title: Response Create Task Task Post 779 | type: string 780 | description: Successful Response 781 | '422': 782 | content: 783 | application/json: 784 | schema: 785 | $ref: '#/components/schemas/HTTPValidationError' 786 | description: Validation Error 787 | security: 788 | - OAuth2PasswordBearer: [] 789 | summary: Create Task 790 | /task/{task_id}: 791 | delete: 792 | operationId: delete_task_task__task_id__delete 793 | parameters: 794 | - in: path 795 | name: task_id 796 | required: true 797 | schema: 798 | title: Task Id 799 | type: string 800 | responses: 801 | '200': 802 | content: 803 | application/json: 804 | schema: {} 805 | description: Successful Response 806 | '204': 807 | description: Task cancelled 808 | '404': 809 | description: Task not found 810 | '422': 811 | content: 812 | application/json: 813 | schema: 814 | $ref: '#/components/schemas/HTTPValidationError' 815 | description: Validation Error 816 | security: 817 | - OAuth2PasswordBearer: [] 818 | summary: Delete Task 819 | get: 820 | operationId: poll_task_status_task__task_id__get 821 | parameters: 822 | - in: path 823 | name: task_id 824 | required: true 825 | schema: 826 | title: Task Id 827 | type: string 828 | responses: 829 | '200': 830 | content: 831 | application/json: 832 | schema: 833 | anyOf: 834 | - $ref: '#/components/schemas/PendingEvent' 835 | - $ref: '#/components/schemas/StartedEvent' 836 | - $ref: '#/components/schemas/AbortedEvent' 837 | - $ref: '#/components/schemas/FinishedEvent' 838 | title: Response Poll Task Status Task Task Id Get 839 | description: Successful Response 840 | '422': 841 | content: 842 | application/json: 843 | schema: 844 | $ref: '#/components/schemas/HTTPValidationError' 845 | description: Validation Error 846 | security: 847 | - OAuth2PasswordBearer: [] 848 | summary: Poll Task Status 849 | /token: 850 | post: 851 | operationId: login_access_token_token_post 852 | requestBody: 853 | content: 854 | application/x-www-form-urlencoded: 855 | schema: 856 | $ref: '#/components/schemas/Body_login_access_token_token_post' 857 | required: true 858 | responses: 859 | '200': 860 | content: 861 | application/json: 862 | schema: 863 | $ref: '#/components/schemas/AuthToken' 864 | description: Successful Response 865 | '422': 866 | content: 867 | application/json: 868 | schema: 869 | $ref: '#/components/schemas/HTTPValidationError' 870 | description: Validation Error 871 | summary: Login Access Token 872 | /token/all: 873 | post: 874 | operationId: public_access_token_token_all_post 875 | responses: 876 | '200': 877 | content: 878 | application/json: 879 | schema: 880 | $ref: '#/components/schemas/AuthToken' 881 | description: Successful Response 882 | summary: Public Access Token 883 | /txt2img: 884 | get: 885 | operationId: get_endpoint_txt2img_get 886 | parameters: 887 | - in: query 888 | name: params_type 889 | required: false 890 | schema: 891 | default: txt2img 892 | enum: 893 | - txt2img 894 | title: Params Type 895 | type: string 896 | - description: 'The model to use for image generation. One of: the *repo id* 897 | of a pretrained pipeline hosted on huggingface (e.g. ''CompVis/stable-diffusion-v1-4''), 898 | *a path* to a *directory* containing pipeline weights, (e.g., ''./my_model_directory/''). ' 899 | in: query 900 | name: model 901 | required: false 902 | schema: 903 | default: CompVis/stable-diffusion-v1-4 904 | description: 'The model to use for image generation. One of: the *repo id* 905 | of a pretrained pipeline hosted on huggingface (e.g. ''CompVis/stable-diffusion-v1-4''), 906 | *a path* to a *directory* containing pipeline weights, (e.g., ''./my_model_directory/''). ' 907 | title: Model 908 | type: string 909 | - description: The prompt to guide image generation. 910 | in: query 911 | name: prompt 912 | required: true 913 | schema: 914 | description: The prompt to guide image generation. 915 | title: Prompt 916 | type: string 917 | - description: The prompt to dissuade image generation. Ignored when not using 918 | guidance (i.e., if `guidance` is `1`). 919 | in: query 920 | name: negative_prompt 921 | required: false 922 | schema: 923 | description: The prompt to dissuade image generation. Ignored when not using 924 | guidance (i.e., if `guidance` is `1`). 925 | title: Negative Prompt 926 | type: string 927 | - description: The number of denoising steps. More denoising steps usually lead 928 | to a higher quality image at the expense of slower inference. 929 | in: query 930 | name: steps 931 | required: false 932 | schema: 933 | default: 20 934 | description: The number of denoising steps. More denoising steps usually 935 | lead to a higher quality image at the expense of slower inference. 936 | title: Steps 937 | type: integer 938 | - description: 'Higher guidance encourages generation closely linked to `prompt`, 939 | usually at the expense of lower image quality. Try using more steps to improve 940 | image quality when using high guidance. Guidance is disabled by setting 941 | `guidance` to `1`. `guidance` is defined as `w` of equation 2. of [ImagenPaper](https://arxiv.org/pdf/2205.11487.pdf). 942 | See also: [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).' 943 | in: query 944 | name: guidance 945 | required: false 946 | schema: 947 | default: 7.5 948 | description: 'Higher guidance encourages generation closely linked to `prompt`, 949 | usually at the expense of lower image quality. Try using more steps to 950 | improve image quality when using high guidance. Guidance is disabled by 951 | setting `guidance` to `1`. `guidance` is defined as `w` of equation 2. 952 | of [ImagenPaper](https://arxiv.org/pdf/2205.11487.pdf). See also: [Classifier-Free 953 | Diffusion Guidance](https://arxiv.org/abs/2207.12598).' 954 | minimum: 1.0 955 | title: Guidance 956 | type: number 957 | - description: The scheduler to use for image generation. Currently only 'plms', 958 | 'ddim', and 'k-lms', are supported. 959 | in: query 960 | name: scheduler 961 | required: false 962 | schema: 963 | default: plms 964 | description: The scheduler to use for image generation. Currently only 'plms', 965 | 'ddim', and 'k-lms', are supported. 966 | enum: 967 | - plms 968 | - ddim 969 | - k-lms 970 | title: Scheduler 971 | type: string 972 | - description: Ensure that you abide by the conditions of the Stable Diffusion 973 | license and do not expose unfiltered results in services or applications 974 | open to the public. For more information, please see https://github.com/huggingface/diffusers/pull/254 975 | in: query 976 | name: safety_filter 977 | required: false 978 | schema: 979 | default: true 980 | description: Ensure that you abide by the conditions of the Stable Diffusion 981 | license and do not expose unfiltered results in services or applications 982 | open to the public. For more information, please see https://github.com/huggingface/diffusers/pull/254 983 | title: Safety Filter 984 | type: boolean 985 | - description: The randomness seed to use for image generation. If not set, 986 | a random seed is used. 987 | in: query 988 | name: seed 989 | required: false 990 | schema: 991 | description: The randomness seed to use for image generation. If not set, 992 | a random seed is used. 993 | title: Seed 994 | type: integer 995 | - description: The pixel width of the generated image. 996 | in: query 997 | name: width 998 | required: false 999 | schema: 1000 | default: 512 1001 | description: The pixel width of the generated image. 1002 | title: Width 1003 | type: integer 1004 | - description: The pixel height of the generated image. 1005 | in: query 1006 | name: height 1007 | required: false 1008 | schema: 1009 | default: 512 1010 | description: The pixel height of the generated image. 1011 | title: Height 1012 | type: integer 1013 | responses: 1014 | '200': 1015 | content: 1016 | application/json: 1017 | schema: {} 1018 | description: Successful Response 1019 | '422': 1020 | content: 1021 | application/json: 1022 | schema: 1023 | $ref: '#/components/schemas/HTTPValidationError' 1024 | description: Validation Error 1025 | security: 1026 | - OAuth2PasswordBearer: [] 1027 | summary: txt2img 1028 | /user/{username}: 1029 | post: 1030 | operationId: signup_user__username__post 1031 | parameters: 1032 | - in: path 1033 | name: username 1034 | required: true 1035 | schema: 1036 | title: Username 1037 | type: string 1038 | - in: query 1039 | name: password 1040 | required: true 1041 | schema: 1042 | title: Password 1043 | type: string 1044 | responses: 1045 | '200': 1046 | content: 1047 | application/json: 1048 | schema: 1049 | $ref: '#/components/schemas/UserBase' 1050 | description: Successful Response 1051 | '422': 1052 | content: 1053 | application/json: 1054 | schema: 1055 | $ref: '#/components/schemas/HTTPValidationError' 1056 | description: Validation Error 1057 | summary: Signup 1058 | --------------------------------------------------------------------------------