main.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import time
  2. from fastapi import FastAPI, Request
  3. from fastapi.staticfiles import StaticFiles
  4. from fastapi import HTTPException
  5. from fastapi.middleware.wsgi import WSGIMiddleware
  6. from fastapi.middleware.cors import CORSMiddleware
  7. from starlette.exceptions import HTTPException as StarletteHTTPException
  8. from apps.ollama.main import app as ollama_app
  9. from apps.openai.main import app as openai_app
  10. from apps.audio.main import app as audio_app
  11. from apps.web.main import app as webui_app
  12. from apps.rag.main import app as rag_app
  13. from config import ENV, FRONTEND_BUILD_DIR
  14. class SPAStaticFiles(StaticFiles):
  15. async def get_response(self, path: str, scope):
  16. try:
  17. return await super().get_response(path, scope)
  18. except (HTTPException, StarletteHTTPException) as ex:
  19. if ex.status_code == 404:
  20. return await super().get_response("index.html", scope)
  21. else:
  22. raise ex
  23. app = FastAPI(docs_url="/docs" if ENV == "dev" else None, redoc_url=None)
  24. origins = ["*"]
  25. app.add_middleware(
  26. CORSMiddleware,
  27. allow_origins=origins,
  28. allow_credentials=True,
  29. allow_methods=["*"],
  30. allow_headers=["*"],
  31. )
  32. @app.middleware("http")
  33. async def check_url(request: Request, call_next):
  34. start_time = int(time.time())
  35. response = await call_next(request)
  36. process_time = int(time.time()) - start_time
  37. response.headers["X-Process-Time"] = str(process_time)
  38. return response
  39. app.mount("/api/v1", webui_app)
  40. app.mount("/ollama/api", ollama_app)
  41. app.mount("/openai/api", openai_app)
  42. app.mount("/audio/api/v1", audio_app)
  43. app.mount("/rag/api/v1", rag_app)
  44. app.mount(
  45. "/",
  46. SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
  47. name="spa-static-files",
  48. )