Yuvvan Talreja commited on
Commit
881f8b5
·
1 Parent(s): 422dc44

Middleware and Proxy Fix

Browse files
Files changed (3) hide show
  1. fastapi_app.py +32 -4
  2. middleware.py +32 -0
  3. templates/index.html +5 -1
fastapi_app.py CHANGED
@@ -2,6 +2,7 @@ from fastapi import FastAPI, Request, HTTPException, Response, Body
2
  from fastapi.responses import JSONResponse, HTMLResponse, FileResponse
3
  from fastapi.staticfiles import StaticFiles
4
  from fastapi.templating import Jinja2Templates
 
5
  import os
6
  import base64
7
  import numpy as np
@@ -14,13 +15,35 @@ import logging
14
  from pydantic import BaseModel
15
  from typing import Optional, Dict, Any, List
16
  from topic_segmenter import TopicSegmenter
 
17
 
18
- app = FastAPI(title="Flowify", description="Audio transcription and topic segmentation API")
19
  logging.basicConfig(level=logging.INFO)
 
 
 
 
 
 
20
 
21
- # Configure templates and static files
22
  templates = Jinja2Templates(directory="templates")
23
- app.mount("/static", StaticFiles(directory="static"), name="static")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
  # Models and locks
26
  models = {}
@@ -38,7 +61,12 @@ class ModelCheck(BaseModel):
38
 
39
  @app.get("/", response_class=HTMLResponse)
40
  async def index(request: Request):
41
- return templates.TemplateResponse("index.html", {"request": request})
 
 
 
 
 
42
 
43
  def get_model(model_name):
44
  """Load and cache the model"""
 
2
  from fastapi.responses import JSONResponse, HTMLResponse, FileResponse
3
  from fastapi.staticfiles import StaticFiles
4
  from fastapi.templating import Jinja2Templates
5
+ from starlette.staticfiles import StaticFiles as StarletteStaticFiles
6
  import os
7
  import base64
8
  import numpy as np
 
15
  from pydantic import BaseModel
16
  from typing import Optional, Dict, Any, List
17
  from topic_segmenter import TopicSegmenter
18
+ from middleware import HTTPSProxyMiddleware
19
 
20
+ # Configure logging
21
  logging.basicConfig(level=logging.INFO)
22
+ logger = logging.getLogger(__name__)
23
+
24
+ app = FastAPI(title="Flowify", description="Audio transcription and topic segmentation API")
25
+
26
+ # Add custom middleware for HTTPS handling
27
+ app.add_middleware(HTTPSProxyMiddleware)
28
 
29
+ # Configure templates with HTTPS handling
30
  templates = Jinja2Templates(directory="templates")
31
+
32
+ # Custom static file handling to ensure proper URL scheme
33
+ class SecureStaticFiles(StarletteStaticFiles):
34
+ def __init__(self, *args, **kwargs):
35
+ super().__init__(*args, **kwargs)
36
+
37
+ async def get_response(self, path, scope):
38
+ # Force scope to use HTTPS when behind proxy
39
+ if "headers" in scope and any(h[0] == b"x-forwarded-proto" and h[1] == b"https" for h in scope["headers"]):
40
+ scope["scheme"] = "https"
41
+
42
+ response = await super().get_response(path, scope)
43
+ return response
44
+
45
+ # Mount static files with secure handler
46
+ app.mount("/static", SecureStaticFiles(directory="static"), name="static")
47
 
48
  # Models and locks
49
  models = {}
 
61
 
62
  @app.get("/", response_class=HTMLResponse)
63
  async def index(request: Request):
64
+ logger.info(f"Serving index.html with base_url={request.base_url}, url={request.url}")
65
+
66
+ # Ensure template knows the correct scheme
67
+ context = {"request": request}
68
+
69
+ return templates.TemplateResponse("index.html", context)
70
 
71
  def get_model(model_name):
72
  """Load and cache the model"""
middleware.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from starlette.middleware.base import BaseHTTPMiddleware
2
+ from starlette.responses import RedirectResponse
3
+ from fastapi import Request
4
+ import logging
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ class HTTPSProxyMiddleware(BaseHTTPMiddleware):
9
+ """Middleware to handle HTTPS for proxied applications like Hugging Face Spaces."""
10
+
11
+ async def dispatch(self, request: Request, call_next):
12
+ """
13
+ Dispatches the middleware.
14
+
15
+ 1. Modifies the request headers to ensure proper URL scheme
16
+ 2. Logs details about the request for debugging
17
+ """
18
+ # Log original request info for debugging
19
+ logger.info(f"Original request: scheme={request.url.scheme}, url={request.url}")
20
+
21
+ # Detect if we're behind a proxy that's forwarding HTTPS as HTTP
22
+ forwarded_proto = request.headers.get("X-Forwarded-Proto")
23
+
24
+ # If we have a forwarded proto header and it's HTTPS,
25
+ # modify the request's scope to ensure URLs are generated with HTTPS
26
+ if forwarded_proto == "https" and request.url.scheme == "http":
27
+ logger.info("Detected HTTPS behind proxy, updating request scope")
28
+ request.scope["scheme"] = "https"
29
+
30
+ # Continue processing the request
31
+ response = await call_next(request)
32
+ return response
templates/index.html CHANGED
@@ -5,9 +5,13 @@
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
  <title>Flowify</title>
7
 
8
- <link rel="stylesheet" href="{{ url_for('static', path='styles.css') }}">
 
9
  <link type="text/css" rel="stylesheet" href="https://unpkg.com/jsmind@0.8.6/style/jsmind.css" />
10
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
 
 
 
11
  </head>
12
  <body>
13
  <div class="app-container">
 
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
  <title>Flowify</title>
7
 
8
+ <!-- Force HTTPS for the static assets -->
9
+ <link rel="stylesheet" href="{{ request.url_for('static', path='styles.css') }}">
10
  <link type="text/css" rel="stylesheet" href="https://unpkg.com/jsmind@0.8.6/style/jsmind.css" />
11
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
12
+
13
+ <!-- Add base tag to ensure all relative URLs use the correct scheme -->
14
+ <base href="{{ request.url }}">
15
  </head>
16
  <body>
17
  <div class="app-container">