sushilideaclan01 commited on
Commit
45ef06a
·
1 Parent(s): a18335a

Fix: Mount Next.js static files directly, use Response instead of StreamingResponse for better compatibility

Browse files
Files changed (1) hide show
  1. main.py +16 -8
main.py CHANGED
@@ -8,7 +8,7 @@ from contextlib import asynccontextmanager
8
  from fastapi import FastAPI, HTTPException, Request, Response, Depends
9
  from fastapi.middleware.cors import CORSMiddleware
10
  from fastapi.staticfiles import StaticFiles
11
- from fastapi.responses import FileResponse, StreamingResponse
12
  from pydantic import BaseModel, Field
13
  from typing import Optional, List, Literal, Any, Dict
14
  import os
@@ -85,6 +85,11 @@ async def add_cache_headers(request: Request, call_next):
85
  os.makedirs(settings.output_dir, exist_ok=True)
86
  app.mount("/images", StaticFiles(directory=settings.output_dir), name="images")
87
 
 
 
 
 
 
88
 
89
  # Request/Response schemas
90
  class GenerateRequest(BaseModel):
@@ -335,8 +340,7 @@ async def root():
335
  async with httpx.AsyncClient(timeout=30.0) as client:
336
  response = await client.get("http://localhost:3000/")
337
  # Return full response (not streaming) for better HF compatibility
338
- from fastapi.responses import Response
339
- return Response(
340
  content=response.content,
341
  status_code=response.status_code,
342
  headers={k: v for k, v in response.headers.items() if k.lower() not in ['content-encoding', 'transfer-encoding', 'content-length']},
@@ -344,7 +348,7 @@ async def root():
344
  )
345
  except httpx.RequestError:
346
  # Return a simple HTML page if frontend is not ready yet
347
- return Response(
348
  content="<html><head><meta http-equiv='refresh' content='2'></head><body><h1>Loading...</h1></body></html>",
349
  status_code=200,
350
  media_type="text/html"
@@ -1181,6 +1185,10 @@ async def frontend_proxy(path: str, request: StarletteRequest):
1181
  if path.startswith("image/") or path.startswith("images/"):
1182
  raise HTTPException(status_code=404, detail="API endpoint not found")
1183
 
 
 
 
 
1184
  # Check if this is a GET for data endpoints (with specific patterns)
1185
  if request.method == "GET":
1186
  for route in api_get_routes:
@@ -1207,11 +1215,11 @@ async def frontend_proxy(path: str, request: StarletteRequest):
1207
  follow_redirects=True,
1208
  )
1209
 
1210
- # Return response
1211
- return StreamingResponse(
1212
- response.iter_bytes(),
1213
  status_code=response.status_code,
1214
- headers=dict(response.headers),
1215
  media_type=response.headers.get("content-type"),
1216
  )
1217
  except httpx.RequestError:
 
8
  from fastapi import FastAPI, HTTPException, Request, Response, Depends
9
  from fastapi.middleware.cors import CORSMiddleware
10
  from fastapi.staticfiles import StaticFiles
11
+ from fastapi.responses import FileResponse, StreamingResponse, Response as FastAPIResponse
12
  from pydantic import BaseModel, Field
13
  from typing import Optional, List, Literal, Any, Dict
14
  import os
 
85
  os.makedirs(settings.output_dir, exist_ok=True)
86
  app.mount("/images", StaticFiles(directory=settings.output_dir), name="images")
87
 
88
+ # Serve Next.js static files directly (better performance than proxying)
89
+ frontend_static_path = os.path.join(os.path.dirname(__file__), "frontend", ".next", "static")
90
+ if os.path.exists(frontend_static_path):
91
+ app.mount("/_next/static", StaticFiles(directory=frontend_static_path), name="nextjs_static")
92
+
93
 
94
  # Request/Response schemas
95
  class GenerateRequest(BaseModel):
 
340
  async with httpx.AsyncClient(timeout=30.0) as client:
341
  response = await client.get("http://localhost:3000/")
342
  # Return full response (not streaming) for better HF compatibility
343
+ return FastAPIResponse(
 
344
  content=response.content,
345
  status_code=response.status_code,
346
  headers={k: v for k, v in response.headers.items() if k.lower() not in ['content-encoding', 'transfer-encoding', 'content-length']},
 
348
  )
349
  except httpx.RequestError:
350
  # Return a simple HTML page if frontend is not ready yet
351
+ return FastAPIResponse(
352
  content="<html><head><meta http-equiv='refresh' content='2'></head><body><h1>Loading...</h1></body></html>",
353
  status_code=200,
354
  media_type="text/html"
 
1185
  if path.startswith("image/") or path.startswith("images/"):
1186
  raise HTTPException(status_code=404, detail="API endpoint not found")
1187
 
1188
+ # Skip static files - they're mounted directly
1189
+ if path.startswith("_next/static/"):
1190
+ raise HTTPException(status_code=404, detail="Static file not found")
1191
+
1192
  # Check if this is a GET for data endpoints (with specific patterns)
1193
  if request.method == "GET":
1194
  for route in api_get_routes:
 
1215
  follow_redirects=True,
1216
  )
1217
 
1218
+ # Return full response (not streaming) for better compatibility
1219
+ return FastAPIResponse(
1220
+ content=response.content,
1221
  status_code=response.status_code,
1222
+ headers={k: v for k, v in response.headers.items() if k.lower() not in ['content-encoding', 'transfer-encoding', 'content-length']},
1223
  media_type=response.headers.get("content-type"),
1224
  )
1225
  except httpx.RequestError: