| 140 | |
| 141 | |
| 142 | def start_proxy(): |
| 143 | # proxy |
| 144 | from easydiffusion.server import server_api |
| 145 | from fastapi import FastAPI, Request |
| 146 | from fastapi.responses import Response |
| 147 | import json |
| 148 | |
| 149 | URI_PREFIX = "/webui" |
| 150 | |
| 151 | webui_proxy = FastAPI(root_path=f"{URI_PREFIX}", docs_url="/swagger") |
| 152 | |
| 153 | @webui_proxy.get("{uri:path}") |
| 154 | def proxy_get(uri: str, req: Request): |
| 155 | if uri == "/openapi-proxy.json": |
| 156 | uri = "/openapi.json" |
| 157 | |
| 158 | res = webui_common.webui_get(uri, headers=req.headers) |
| 159 | |
| 160 | content = res.content |
| 161 | headers = dict(res.headers) |
| 162 | |
| 163 | if uri == "/docs": |
| 164 | content = res.text.replace("url: '/openapi.json'", f"url: '{URI_PREFIX}/openapi-proxy.json'") |
| 165 | elif uri == "/openapi.json": |
| 166 | content = res.json() |
| 167 | content["paths"] = {f"{URI_PREFIX}{k}": v for k, v in content["paths"].items()} |
| 168 | content = json.dumps(content) |
| 169 | |
| 170 | if isinstance(content, str): |
| 171 | content = bytes(content, encoding="utf-8") |
| 172 | headers["content-length"] = str(len(content)) |
| 173 | |
| 174 | # Return the same response back to the client |
| 175 | return Response(content=content, status_code=res.status_code, headers=headers) |
| 176 | |
| 177 | @webui_proxy.post("{uri:path}") |
| 178 | async def proxy_post(uri: str, req: Request): |
| 179 | body = await req.body() |
| 180 | res = webui_common.webui_post(uri, data=body, headers=req.headers) |
| 181 | |
| 182 | # Return the same response back to the client |
| 183 | return Response(content=res.content, status_code=res.status_code, headers=dict(res.headers)) |
| 184 | |
| 185 | server_api.mount(f"{URI_PREFIX}", webui_proxy) |
| 186 | |
| 187 | |
| 188 | def uninstall_backend(): |