Nagesh Muralidhar commited on
Commit
fee9ffa
·
1 Parent(s): 1700fb6

Fix frontend build and serving process

Browse files
Files changed (3) hide show
  1. Dockerfile +24 -15
  2. app.py +64 -15
  3. build_frontend.sh +61 -2
Dockerfile CHANGED
@@ -13,30 +13,39 @@ RUN apt-get update && \
13
  && apt-get clean \
14
  && rm -rf /var/lib/apt/lists/*
15
 
 
 
 
16
  # Copy the application code
17
  COPY . .
18
 
19
- # Make sure static directory exists and has the index.html file
20
- RUN mkdir -p ./static && \
21
- if [ ! -f "./static/index.html" ]; then \
22
- echo "WARNING: No index.html found in static directory"; \
23
- else \
24
- echo "Found index.html in static directory"; \
25
- fi
26
-
27
- # Create directories for temp files
28
- RUN mkdir -p temp_audio temp
29
 
30
  # Execute the build frontend script to prepare frontend code
31
- RUN chmod +x build_frontend.sh && ./build_frontend.sh || echo "Frontend build script failed but continuing"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  # Install backend dependencies
34
  RUN pip install --no-cache-dir -r requirements.txt
35
 
36
- # Verify the static files
37
- RUN ls -la ./static && \
38
- if [ -f "./static/index.html" ]; then echo "Frontend index.html found"; else echo "WARNING: Frontend index.html not found"; fi
39
-
40
  # Default environment variables
41
  ENV PORT=7860
42
  ENV HOST=0.0.0.0
 
13
  && apt-get clean \
14
  && rm -rf /var/lib/apt/lists/*
15
 
16
+ # Create directories for temp files
17
+ RUN mkdir -p temp_audio temp static
18
+
19
  # Copy the application code
20
  COPY . .
21
 
22
+ # List directory contents
23
+ RUN ls -la
 
 
 
 
 
 
 
 
24
 
25
  # Execute the build frontend script to prepare frontend code
26
+ RUN chmod +x build_frontend.sh && \
27
+ ./build_frontend.sh && \
28
+ echo "Frontend build script completed successfully"
29
+
30
+ # Verify the static files
31
+ RUN echo "Checking static directory contents:" && \
32
+ ls -la ./static && \
33
+ if [ -f "./static/index.html" ]; then \
34
+ echo "Frontend index.html found"; \
35
+ else \
36
+ echo "WARNING: Frontend index.html not found in static directory"; \
37
+ exit 1; \
38
+ fi && \
39
+ if [ -d "./static/assets" ]; then \
40
+ echo "Frontend assets directory found"; \
41
+ ls -la ./static/assets; \
42
+ else \
43
+ echo "WARNING: Frontend assets directory not found"; \
44
+ fi
45
 
46
  # Install backend dependencies
47
  RUN pip install --no-cache-dir -r requirements.txt
48
 
 
 
 
 
49
  # Default environment variables
50
  ENV PORT=7860
51
  ENV HOST=0.0.0.0
app.py CHANGED
@@ -64,11 +64,14 @@ frontend_app.add_middleware(
64
  allow_headers=["*"],
65
  )
66
 
67
- # Mount static directory
 
 
68
  if static_path.exists():
69
- frontend_app.mount("/static", StaticFiles(directory=str(static_path)), name="static")
 
70
 
71
- # Root route handler
72
  @frontend_app.get("/", response_class=HTMLResponse)
73
  async def read_root():
74
  logger.info(f"Serving index.html from {index_path}")
@@ -85,12 +88,50 @@ async def read_root():
85
  async def status():
86
  return {"status": "ok", "message": "PodCraft API is running"}
87
 
88
- # Check if static directory exists with index.html
89
- static_index_exists = static_path.exists() and index_path.exists()
90
- logger.info(f"Static path exists: {static_path.exists()}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  if static_path.exists():
92
- logger.info(f"Static directory contents: {os.listdir(static_path)}")
93
- logger.info(f"Static index exists: {index_path.exists()}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
  try:
96
  # Try to import the backend app
@@ -99,9 +140,6 @@ try:
99
  # Now create a merged app that prioritizes frontend routes
100
  app = FastAPI(title="PodCraft")
101
 
102
- # Add frontend app routes to the main app
103
- app.mount("/", frontend_app)
104
-
105
  # Add CORS middleware
106
  app.add_middleware(
107
  CORSMiddleware,
@@ -111,10 +149,21 @@ try:
111
  allow_headers=["*"],
112
  )
113
 
114
- # Forward specific backend API routes
115
- @app.get("/api/{path:path}")
116
- async def api_route(request: Request, path: str):
117
- return await backend_app.handle_request(request)
 
 
 
 
 
 
 
 
 
 
 
118
 
119
  app_to_run = app
120
  logger.info("Using merged application (frontend + backend)")
 
64
  allow_headers=["*"],
65
  )
66
 
67
+ # Check if static directory exists with index.html
68
+ static_index_exists = static_path.exists() and index_path.exists()
69
+ logger.info(f"Static path exists: {static_path.exists()}")
70
  if static_path.exists():
71
+ logger.info(f"Static directory contents: {os.listdir(static_path)}")
72
+ logger.info(f"Static index exists: {index_path.exists()}")
73
 
74
+ # Root route handler - must come before mounting static files
75
  @frontend_app.get("/", response_class=HTMLResponse)
76
  async def read_root():
77
  logger.info(f"Serving index.html from {index_path}")
 
88
  async def status():
89
  return {"status": "ok", "message": "PodCraft API is running"}
90
 
91
+ # Serve specific file types with correct Content-Type
92
+ @frontend_app.get("/assets/{file_path:path}")
93
+ async def serve_assets(file_path: str):
94
+ file_full_path = static_path / "assets" / file_path
95
+
96
+ if not file_full_path.exists() or not file_full_path.is_file():
97
+ logger.warning(f"Asset file not found: {file_full_path}")
98
+ raise HTTPException(status_code=404, detail="Asset file not found")
99
+
100
+ # Determine content type based on file extension
101
+ content_type = None
102
+ if file_path.endswith(".js"):
103
+ content_type = "application/javascript"
104
+ elif file_path.endswith(".css"):
105
+ content_type = "text/css"
106
+ elif file_path.endswith(".svg"):
107
+ content_type = "image/svg+xml"
108
+ elif file_path.endswith(".png"):
109
+ content_type = "image/png"
110
+ elif file_path.endswith(".jpg") or file_path.endswith(".jpeg"):
111
+ content_type = "image/jpeg"
112
+
113
+ logger.info(f"Serving asset: {file_path} with content-type: {content_type}")
114
+ return FileResponse(file_full_path, media_type=content_type)
115
+
116
+ # Now mount the static directory AFTER defining the root handler
117
  if static_path.exists():
118
+ frontend_app.mount("/static", StaticFiles(directory=str(static_path)), name="static")
119
+
120
+ # Catch-all route to serve index.html for client-side routing
121
+ @frontend_app.get("/{full_path:path}")
122
+ async def catch_all(full_path: str):
123
+ # Skip API paths
124
+ if full_path.startswith("api/") or full_path.startswith("docs") or full_path.startswith("openapi.json"):
125
+ raise HTTPException(status_code=404, detail="Not found")
126
+
127
+ logger.info(f"Catch-all route hit for path: {full_path}, serving index.html")
128
+ # For any other path, serve index.html to support client-side routing
129
+ if index_path.exists():
130
+ with open(index_path, "r") as f:
131
+ content = f.read()
132
+ return HTMLResponse(content=content)
133
+ else:
134
+ return HTMLResponse(content="Index file not found", status_code=404)
135
 
136
  try:
137
  # Try to import the backend app
 
140
  # Now create a merged app that prioritizes frontend routes
141
  app = FastAPI(title="PodCraft")
142
 
 
 
 
143
  # Add CORS middleware
144
  app.add_middleware(
145
  CORSMiddleware,
 
149
  allow_headers=["*"],
150
  )
151
 
152
+ # Include the backend app routes
153
+ # This imports all routes from the backend_app into our main app
154
+ from fastapi import APIRouter
155
+ backend_router = APIRouter()
156
+
157
+ # Import all routes from backend_app
158
+ for route in backend_app.routes:
159
+ backend_router.routes.append(route)
160
+
161
+ # Add the backend routes
162
+ app.include_router(backend_router)
163
+
164
+ # Mount the frontend app at the root - this should be last
165
+ # so that API routes take precedence but frontend handles all other routes
166
+ app.mount("/", frontend_app)
167
 
168
  app_to_run = app
169
  logger.info("Using merged application (frontend + backend)")
build_frontend.sh CHANGED
@@ -1,12 +1,50 @@
1
  #!/bin/bash
2
 
3
- # This script is used to pull the latest frontend code during the build process
4
  # It is called from the Dockerfile
5
 
6
  set -e # Exit on error
7
 
 
 
 
 
 
 
8
  if [ -d "frontend/podcraft" ]; then
9
- echo "Frontend code already exists"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  else
11
  echo "Frontend code not found, creating a fallback UI"
12
  mkdir -p frontend/podcraft/public
@@ -356,7 +394,28 @@ EOF
356
  EOF
357
 
358
  echo "Created fallback frontend code"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
359
  fi
360
 
 
 
361
  # Make the script executable
362
  chmod +x $0
 
1
  #!/bin/bash
2
 
3
+ # This script is used to build and prepare the frontend code during the Docker build process
4
  # It is called from the Dockerfile
5
 
6
  set -e # Exit on error
7
 
8
+ echo "Starting frontend build process..."
9
+
10
+ # Clear the static directory but create it if it doesn't exist
11
+ mkdir -p ./static
12
+ rm -rf ./static/*
13
+
14
  if [ -d "frontend/podcraft" ]; then
15
+ echo "Frontend code found, attempting to build..."
16
+
17
+ # Navigate to the frontend directory
18
+ cd frontend/podcraft
19
+
20
+ # Check if package.json exists
21
+ if [ -f "package.json" ]; then
22
+ echo "Installing frontend dependencies..."
23
+ npm install --quiet || { echo "npm install failed"; exit 1; }
24
+
25
+ echo "Building frontend application..."
26
+ npm run build || { echo "npm build failed"; exit 1; }
27
+
28
+ # Check if the build directory exists
29
+ if [ -d "dist" ]; then
30
+ echo "Build successful, copying files to static directory..."
31
+ cp -r dist/* ../../static/
32
+ echo "Frontend build files copied to static directory"
33
+
34
+ # List the contents of the static directory to verify
35
+ echo "Static directory contents:"
36
+ ls -la ../../static/
37
+ else
38
+ echo "ERROR: Build directory 'dist' not found after build"
39
+ exit 1
40
+ fi
41
+ else
42
+ echo "ERROR: package.json not found in frontend/podcraft"
43
+ exit 1
44
+ fi
45
+
46
+ # Return to the original directory
47
+ cd ../..
48
  else
49
  echo "Frontend code not found, creating a fallback UI"
50
  mkdir -p frontend/podcraft/public
 
394
  EOF
395
 
396
  echo "Created fallback frontend code"
397
+
398
+ # Try to build and copy the fallback UI
399
+ cd frontend/podcraft
400
+ npm install --quiet || { echo "npm install failed for fallback UI"; exit 1; }
401
+ npm run build || { echo "npm build failed for fallback UI"; exit 1; }
402
+
403
+ if [ -d "dist" ]; then
404
+ echo "Fallback UI build successful, copying files to static directory..."
405
+ cp -r dist/* ../../static/
406
+ echo "Fallback UI build files copied to static directory"
407
+ else
408
+ echo "ERROR: Fallback UI build directory 'dist' not found"
409
+ # Copy our static HTML directly as last resort
410
+ echo "Copying static HTML file as last resort..."
411
+ cp index.html ../../static/
412
+ fi
413
+
414
+ # Return to the original directory
415
+ cd ../..
416
  fi
417
 
418
+ echo "Frontend build process completed"
419
+
420
  # Make the script executable
421
  chmod +x $0