main.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. from bs4 import BeautifulSoup
  2. import json
  3. import markdown
  4. import time
  5. from fastapi import FastAPI, Request
  6. from fastapi.staticfiles import StaticFiles
  7. from fastapi import HTTPException
  8. from fastapi.middleware.wsgi import WSGIMiddleware
  9. from fastapi.middleware.cors import CORSMiddleware
  10. from starlette.exceptions import HTTPException as StarletteHTTPException
  11. from apps.ollama.main import app as ollama_app
  12. from apps.openai.main import app as openai_app
  13. from apps.audio.main import app as audio_app
  14. from apps.images.main import app as images_app
  15. from apps.rag.main import app as rag_app
  16. from apps.web.main import app as webui_app
  17. from config import WEBUI_NAME, ENV, VERSION, CHANGELOG, FRONTEND_BUILD_DIR
  18. class SPAStaticFiles(StaticFiles):
  19. async def get_response(self, path: str, scope):
  20. try:
  21. return await super().get_response(path, scope)
  22. except (HTTPException, StarletteHTTPException) as ex:
  23. if ex.status_code == 404:
  24. return await super().get_response("index.html", scope)
  25. else:
  26. raise ex
  27. app = FastAPI(docs_url="/docs" if ENV == "dev" else None, redoc_url=None)
  28. origins = ["*"]
  29. app.add_middleware(
  30. CORSMiddleware,
  31. allow_origins=origins,
  32. allow_credentials=True,
  33. allow_methods=["*"],
  34. allow_headers=["*"],
  35. )
  36. @app.middleware("http")
  37. async def check_url(request: Request, call_next):
  38. start_time = int(time.time())
  39. response = await call_next(request)
  40. process_time = int(time.time()) - start_time
  41. response.headers["X-Process-Time"] = str(process_time)
  42. return response
  43. app.mount("/api/v1", webui_app)
  44. app.mount("/ollama/api", ollama_app)
  45. app.mount("/openai/api", openai_app)
  46. app.mount("/images/api/v1", images_app)
  47. app.mount("/audio/api/v1", audio_app)
  48. app.mount("/rag/api/v1", rag_app)
  49. @app.get("/api/config")
  50. async def get_app_config():
  51. return {
  52. "status": True,
  53. "name": WEBUI_NAME,
  54. "version": VERSION,
  55. "images": images_app.state.ENABLED,
  56. "default_models": webui_app.state.DEFAULT_MODELS,
  57. "default_prompt_suggestions": webui_app.state.DEFAULT_PROMPT_SUGGESTIONS,
  58. }
  59. @app.get("/api/changelog")
  60. async def get_app_changelog():
  61. return CHANGELOG
  62. app.mount("/static", StaticFiles(directory="static"), name="static")
  63. app.mount(
  64. "/",
  65. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  66. name="spa-static-files",
  67. )