Deploy habadashi_login gateway
Browse files- README.md +60 -0
- app.py +106 -17
- bootstrap.py +54 -12
- requirements.txt +1 -0
README.md
CHANGED
|
@@ -35,3 +35,63 @@ Public gateway with Supabase authentication that dynamically loads the private v
|
|
| 35 |
3. User logs in with Supabase credentials
|
| 36 |
4. On successful login, ver20 Gradio app is mounted at `/app/`
|
| 37 |
5. User profile and organization info loaded from `profiles` table
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
3. User logs in with Supabase credentials
|
| 36 |
4. On successful login, ver20 Gradio app is mounted at `/app/`
|
| 37 |
5. User profile and organization info loaded from `profiles` table
|
| 38 |
+
|
| 39 |
+
## Startup Phase Logging
|
| 40 |
+
|
| 41 |
+
The application logs structured startup phases to help diagnose issues. Look for these phase markers in the logs:
|
| 42 |
+
|
| 43 |
+
### Expected Startup Sequence
|
| 44 |
+
|
| 45 |
+
1. `[STARTUP_META]` - Environment and configuration info
|
| 46 |
+
2. `[PHASE] bootstrap_start` - Begin downloading private app
|
| 47 |
+
3. `[PHASE] bootstrap_end success=true` - Private app downloaded
|
| 48 |
+
4. `[PHASE] supabase_init_start` - Initialize Supabase client
|
| 49 |
+
5. `[PHASE] supabase_init_end success=true` - Supabase ready
|
| 50 |
+
6. `[PHASE] fastapi_init_start/end` - FastAPI app created
|
| 51 |
+
7. `[PHASE] create_ui_start/end` - Login UI created
|
| 52 |
+
8. `[PHASE] import_ver20_start` - Import ver20 app
|
| 53 |
+
9. `[PHASE] import_ver20_end success=true` - Ver20 loaded
|
| 54 |
+
10. `[PHASE] mount_login_start/end` - Login UI mounted
|
| 55 |
+
11. `[PHASE] mount_app_start/end` - Ver20 app mounted
|
| 56 |
+
12. `[STARTUP_COMPLETE]` - All phases complete
|
| 57 |
+
|
| 58 |
+
### Health Check Endpoint
|
| 59 |
+
|
| 60 |
+
Once started, check the health endpoint:
|
| 61 |
+
|
| 62 |
+
```bash
|
| 63 |
+
curl https://your-space.hf.space/healthz
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
Expected response:
|
| 67 |
+
```json
|
| 68 |
+
{
|
| 69 |
+
"ok": true,
|
| 70 |
+
"ver20_loaded": true,
|
| 71 |
+
"private_app_dir": "./private_app"
|
| 72 |
+
}
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
### Debugging Startup Failures
|
| 76 |
+
|
| 77 |
+
If the Space fails to start or restarts repeatedly:
|
| 78 |
+
|
| 79 |
+
1. **Check the last phase reached** in logs
|
| 80 |
+
2. **Look for `[ERROR]` and `[TRACEBACK]` markers** after the last phase
|
| 81 |
+
3. **Common failure points:**
|
| 82 |
+
- `bootstrap_end success=false` - HF_TOKEN missing or invalid
|
| 83 |
+
- `supabase_init_end success=false` - SUPABASE_URL/KEY missing
|
| 84 |
+
- `import_ver20_end success=false` - Ver20 app.py structure issue
|
| 85 |
+
- No phases after `mount_app_end` - Port binding or health check issue
|
| 86 |
+
|
| 87 |
+
### Request Logging
|
| 88 |
+
|
| 89 |
+
All HTTP requests are logged with:
|
| 90 |
+
- `[REQUEST]` - Incoming request (method, path)
|
| 91 |
+
- `[RESPONSE]` - Response status and duration
|
| 92 |
+
|
| 93 |
+
Example:
|
| 94 |
+
```
|
| 95 |
+
[REQUEST] method=GET path=/
|
| 96 |
+
[RESPONSE] method=GET path=/ status=307 duration=0.015s
|
| 97 |
+
```
|
app.py
CHANGED
|
@@ -6,9 +6,12 @@ Public Space that loads private ver20 app dynamically
|
|
| 6 |
|
| 7 |
import os
|
| 8 |
import sys
|
|
|
|
|
|
|
| 9 |
from pathlib import Path
|
| 10 |
from fastapi import FastAPI, Request, Depends, HTTPException
|
| 11 |
-
from fastapi.responses import RedirectResponse
|
|
|
|
| 12 |
import gradio as gr
|
| 13 |
from supabase import create_client, Client
|
| 14 |
|
|
@@ -16,8 +19,24 @@ from supabase import create_client, Client
|
|
| 16 |
from bootstrap import download_private_app
|
| 17 |
from login import create_login_ui
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
# --- Bootstrap: Download private app at startup ---
|
| 20 |
-
print("
|
| 21 |
try:
|
| 22 |
private_app_dir = download_private_app()
|
| 23 |
|
|
@@ -25,40 +44,78 @@ try:
|
|
| 25 |
private_app_path = str(private_app_dir.resolve())
|
| 26 |
if private_app_path not in sys.path:
|
| 27 |
sys.path.insert(0, private_app_path)
|
| 28 |
-
print(f"
|
| 29 |
|
| 30 |
except Exception as e:
|
| 31 |
-
print(f"
|
|
|
|
|
|
|
| 32 |
print("โ ๏ธ Application will start but /app/ route will not work")
|
| 33 |
private_app_dir = None
|
| 34 |
|
| 35 |
# --- Supabase Setup ---
|
|
|
|
| 36 |
SUPABASE_URL = os.environ.get("SUPABASE_URL")
|
| 37 |
SUPABASE_KEY = os.environ.get("SUPABASE_KEY")
|
| 38 |
|
| 39 |
if not SUPABASE_URL or not SUPABASE_KEY:
|
|
|
|
| 40 |
raise ValueError(
|
| 41 |
"SUPABASE_URL and SUPABASE_KEY must be set in environment variables. "
|
| 42 |
"Please configure them in HF Space Secrets."
|
| 43 |
)
|
| 44 |
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
# --- FastAPI App ---
|
|
|
|
| 48 |
app = FastAPI()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
# --- Authentication Handler (for login UI) ---
|
| 51 |
def handle_login(email, password):
|
| 52 |
"""Handle login attempt via Supabase"""
|
|
|
|
| 53 |
try:
|
| 54 |
res = supabase.auth.sign_in_with_password({"email": email, "password": password})
|
| 55 |
if res.session:
|
|
|
|
| 56 |
return (
|
| 57 |
gr.update(visible=False),
|
| 58 |
gr.update(visible=True, value=f"### โ
ใญใฐใคใณๆๅ: {email}"),
|
| 59 |
res.session.access_token
|
| 60 |
)
|
| 61 |
except Exception as e:
|
|
|
|
| 62 |
return gr.update(), gr.update(value=f"โ ใจใฉใผ: {str(e)}"), None
|
| 63 |
|
| 64 |
# --- Authentication Dependency ---
|
|
@@ -66,8 +123,7 @@ def get_current_user(request: Request):
|
|
| 66 |
"""Verify token from cookie and fetch user profile"""
|
| 67 |
token = request.cookies.get("sb_access_token")
|
| 68 |
|
| 69 |
-
print(f"
|
| 70 |
-
print(f"Token present: {bool(token)}")
|
| 71 |
|
| 72 |
if not token:
|
| 73 |
return None
|
|
@@ -91,32 +147,39 @@ def get_current_user(request: Request):
|
|
| 91 |
"org_name": (profile_data.get("organizations") or {}).get("name")
|
| 92 |
}
|
| 93 |
|
| 94 |
-
print(f"
|
| 95 |
return user_dict
|
| 96 |
|
| 97 |
except Exception as e:
|
| 98 |
-
print(f"
|
| 99 |
return None
|
| 100 |
|
| 101 |
# --- Create UI instances ---
|
|
|
|
| 102 |
login_ui = create_login_ui(handle_login)
|
|
|
|
| 103 |
|
| 104 |
# Import ver20 app (Gradio Blocks)
|
|
|
|
| 105 |
ver20_app = None
|
| 106 |
if private_app_dir:
|
| 107 |
try:
|
| 108 |
# Import app module from downloaded private app
|
| 109 |
from app import app as ver20_blocks
|
| 110 |
ver20_app = ver20_blocks
|
| 111 |
-
print("
|
| 112 |
except Exception as e:
|
| 113 |
-
print(f"
|
| 114 |
-
print(f"
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
# --- Routes ---
|
| 117 |
@app.get("/")
|
| 118 |
async def root(user=Depends(get_current_user)):
|
| 119 |
"""Root route - redirect to login or app based on auth status"""
|
|
|
|
| 120 |
if isinstance(user, dict) and user.get("user_id"):
|
| 121 |
return RedirectResponse(url="/app/")
|
| 122 |
return RedirectResponse(url="/login/")
|
|
@@ -124,18 +187,34 @@ async def root(user=Depends(get_current_user)):
|
|
| 124 |
@app.get("/logout")
|
| 125 |
async def logout():
|
| 126 |
"""Logout route - clear cookie and redirect to login"""
|
|
|
|
| 127 |
response = RedirectResponse(url="/login/")
|
| 128 |
response.delete_cookie("sb_access_token")
|
| 129 |
return response
|
| 130 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
# --- Mount Gradio UIs ---
|
| 132 |
-
|
| 133 |
app = gr.mount_gradio_app(app, login_ui, path="/login")
|
|
|
|
| 134 |
|
| 135 |
# Ver20 App (protected)
|
|
|
|
| 136 |
if ver20_app:
|
| 137 |
app = gr.mount_gradio_app(app, ver20_app, path="/app", auth_dependency=get_current_user)
|
| 138 |
-
print("
|
| 139 |
else:
|
| 140 |
# Fallback: simple placeholder if ver20 failed to load
|
| 141 |
with gr.Blocks() as fallback_ui:
|
|
@@ -143,6 +222,16 @@ else:
|
|
| 143 |
gr.Markdown("The private application failed to load. Please check logs.")
|
| 144 |
|
| 145 |
app = gr.mount_gradio_app(app, fallback_ui, path="/app", auth_dependency=get_current_user)
|
| 146 |
-
print("
|
| 147 |
-
|
| 148 |
-
print("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
import os
|
| 8 |
import sys
|
| 9 |
+
import time
|
| 10 |
+
import traceback
|
| 11 |
from pathlib import Path
|
| 12 |
from fastapi import FastAPI, Request, Depends, HTTPException
|
| 13 |
+
from fastapi.responses import RedirectResponse, JSONResponse
|
| 14 |
+
from starlette.middleware.base import BaseHTTPMiddleware
|
| 15 |
import gradio as gr
|
| 16 |
from supabase import create_client, Client
|
| 17 |
|
|
|
|
| 19 |
from bootstrap import download_private_app
|
| 20 |
from login import create_login_ui
|
| 21 |
|
| 22 |
+
# --- Startup Meta Info ---
|
| 23 |
+
print("=" * 80)
|
| 24 |
+
print("๐ Starting Habadashi Login Gateway")
|
| 25 |
+
print("=" * 80)
|
| 26 |
+
print(f"[STARTUP_META] Python version: {sys.version}")
|
| 27 |
+
print(f"[STARTUP_META] CWD: {os.getcwd()}")
|
| 28 |
+
print(f"[STARTUP_META] PORT: {os.environ.get('PORT', 'not set')}")
|
| 29 |
+
print(f"[STARTUP_META] SPACE_ID: {os.environ.get('SPACE_ID', 'not set')}")
|
| 30 |
+
print(f"[STARTUP_META] SPACE_HOST: {os.environ.get('SPACE_HOST', 'not set')}")
|
| 31 |
+
print(f"[STARTUP_META] GRADIO_SERVER_NAME: {os.environ.get('GRADIO_SERVER_NAME', 'not set')}")
|
| 32 |
+
print(f"[STARTUP_META] GRADIO_SERVER_PORT: {os.environ.get('GRADIO_SERVER_PORT', 'not set')}")
|
| 33 |
+
print(f"[STARTUP_META] HF_TOKEN: {'***set***' if os.environ.get('HF_TOKEN') else 'NOT SET'}")
|
| 34 |
+
print(f"[STARTUP_META] SUPABASE_URL: {'***set***' if os.environ.get('SUPABASE_URL') else 'NOT SET'}")
|
| 35 |
+
print(f"[STARTUP_META] SUPABASE_KEY: {'***set***' if os.environ.get('SUPABASE_KEY') else 'NOT SET'}")
|
| 36 |
+
print("=" * 80)
|
| 37 |
+
|
| 38 |
# --- Bootstrap: Download private app at startup ---
|
| 39 |
+
print("[PHASE] bootstrap_start")
|
| 40 |
try:
|
| 41 |
private_app_dir = download_private_app()
|
| 42 |
|
|
|
|
| 44 |
private_app_path = str(private_app_dir.resolve())
|
| 45 |
if private_app_path not in sys.path:
|
| 46 |
sys.path.insert(0, private_app_path)
|
| 47 |
+
print(f"[PHASE] bootstrap_end success=true path={private_app_path}")
|
| 48 |
|
| 49 |
except Exception as e:
|
| 50 |
+
print(f"[PHASE] bootstrap_end success=false")
|
| 51 |
+
print(f"[ERROR] Bootstrap failed: {e}")
|
| 52 |
+
print(f"[TRACEBACK]\n{traceback.format_exc()}")
|
| 53 |
print("โ ๏ธ Application will start but /app/ route will not work")
|
| 54 |
private_app_dir = None
|
| 55 |
|
| 56 |
# --- Supabase Setup ---
|
| 57 |
+
print("[PHASE] supabase_init_start")
|
| 58 |
SUPABASE_URL = os.environ.get("SUPABASE_URL")
|
| 59 |
SUPABASE_KEY = os.environ.get("SUPABASE_KEY")
|
| 60 |
|
| 61 |
if not SUPABASE_URL or not SUPABASE_KEY:
|
| 62 |
+
print("[ERROR] SUPABASE_URL and/or SUPABASE_KEY not set")
|
| 63 |
raise ValueError(
|
| 64 |
"SUPABASE_URL and SUPABASE_KEY must be set in environment variables. "
|
| 65 |
"Please configure them in HF Space Secrets."
|
| 66 |
)
|
| 67 |
|
| 68 |
+
try:
|
| 69 |
+
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 70 |
+
print(f"[PHASE] supabase_init_end success=true")
|
| 71 |
+
except Exception as e:
|
| 72 |
+
print(f"[PHASE] supabase_init_end success=false")
|
| 73 |
+
print(f"[ERROR] Supabase init failed: {e}")
|
| 74 |
+
print(f"[TRACEBACK]\n{traceback.format_exc()}")
|
| 75 |
+
raise
|
| 76 |
|
| 77 |
# --- FastAPI App ---
|
| 78 |
+
print("[PHASE] fastapi_init_start")
|
| 79 |
app = FastAPI()
|
| 80 |
+
print("[PHASE] fastapi_init_end")
|
| 81 |
+
|
| 82 |
+
# --- Request Logging Middleware ---
|
| 83 |
+
class RequestLoggingMiddleware(BaseHTTPMiddleware):
|
| 84 |
+
async def dispatch(self, request: Request, call_next):
|
| 85 |
+
start_time = time.time()
|
| 86 |
+
path = request.url.path
|
| 87 |
+
method = request.method
|
| 88 |
+
|
| 89 |
+
print(f"[REQUEST] method={method} path={path}")
|
| 90 |
+
|
| 91 |
+
try:
|
| 92 |
+
response = await call_next(request)
|
| 93 |
+
duration = time.time() - start_time
|
| 94 |
+
print(f"[RESPONSE] method={method} path={path} status={response.status_code} duration={duration:.3f}s")
|
| 95 |
+
return response
|
| 96 |
+
except Exception as e:
|
| 97 |
+
duration = time.time() - start_time
|
| 98 |
+
print(f"[RESPONSE] method={method} path={path} status=500 duration={duration:.3f}s error={e}")
|
| 99 |
+
raise
|
| 100 |
+
|
| 101 |
+
app.add_middleware(RequestLoggingMiddleware)
|
| 102 |
+
print("[MIDDLEWARE] RequestLoggingMiddleware added")
|
| 103 |
|
| 104 |
# --- Authentication Handler (for login UI) ---
|
| 105 |
def handle_login(email, password):
|
| 106 |
"""Handle login attempt via Supabase"""
|
| 107 |
+
print(f"[AUTH] Login attempt for: {email}")
|
| 108 |
try:
|
| 109 |
res = supabase.auth.sign_in_with_password({"email": email, "password": password})
|
| 110 |
if res.session:
|
| 111 |
+
print(f"[AUTH] Login successful: {email}")
|
| 112 |
return (
|
| 113 |
gr.update(visible=False),
|
| 114 |
gr.update(visible=True, value=f"### โ
ใญใฐใคใณๆๅ: {email}"),
|
| 115 |
res.session.access_token
|
| 116 |
)
|
| 117 |
except Exception as e:
|
| 118 |
+
print(f"[AUTH] Login failed for {email}: {e}")
|
| 119 |
return gr.update(), gr.update(value=f"โ ใจใฉใผ: {str(e)}"), None
|
| 120 |
|
| 121 |
# --- Authentication Dependency ---
|
|
|
|
| 123 |
"""Verify token from cookie and fetch user profile"""
|
| 124 |
token = request.cookies.get("sb_access_token")
|
| 125 |
|
| 126 |
+
print(f"[AUTH_CHECK] Token present: {bool(token)}")
|
|
|
|
| 127 |
|
| 128 |
if not token:
|
| 129 |
return None
|
|
|
|
| 147 |
"org_name": (profile_data.get("organizations") or {}).get("name")
|
| 148 |
}
|
| 149 |
|
| 150 |
+
print(f"[AUTH_CHECK] Success: user={user_dict['email']} role={user_dict['role']}")
|
| 151 |
return user_dict
|
| 152 |
|
| 153 |
except Exception as e:
|
| 154 |
+
print(f"[AUTH_CHECK] Failed: {e}")
|
| 155 |
return None
|
| 156 |
|
| 157 |
# --- Create UI instances ---
|
| 158 |
+
print("[PHASE] create_ui_start")
|
| 159 |
login_ui = create_login_ui(handle_login)
|
| 160 |
+
print("[PHASE] create_ui_end component=login_ui")
|
| 161 |
|
| 162 |
# Import ver20 app (Gradio Blocks)
|
| 163 |
+
print("[PHASE] import_ver20_start")
|
| 164 |
ver20_app = None
|
| 165 |
if private_app_dir:
|
| 166 |
try:
|
| 167 |
# Import app module from downloaded private app
|
| 168 |
from app import app as ver20_blocks
|
| 169 |
ver20_app = ver20_blocks
|
| 170 |
+
print(f"[PHASE] import_ver20_end success=true type={type(ver20_app)}")
|
| 171 |
except Exception as e:
|
| 172 |
+
print(f"[PHASE] import_ver20_end success=false")
|
| 173 |
+
print(f"[ERROR] Failed to import ver20 app: {e}")
|
| 174 |
+
print(f"[TRACEBACK]\n{traceback.format_exc()}")
|
| 175 |
+
else:
|
| 176 |
+
print(f"[PHASE] import_ver20_end success=false reason=bootstrap_failed")
|
| 177 |
|
| 178 |
# --- Routes ---
|
| 179 |
@app.get("/")
|
| 180 |
async def root(user=Depends(get_current_user)):
|
| 181 |
"""Root route - redirect to login or app based on auth status"""
|
| 182 |
+
print(f"[ROUTE] / accessed, user_authenticated={isinstance(user, dict) and user.get('user_id')}")
|
| 183 |
if isinstance(user, dict) and user.get("user_id"):
|
| 184 |
return RedirectResponse(url="/app/")
|
| 185 |
return RedirectResponse(url="/login/")
|
|
|
|
| 187 |
@app.get("/logout")
|
| 188 |
async def logout():
|
| 189 |
"""Logout route - clear cookie and redirect to login"""
|
| 190 |
+
print(f"[ROUTE] /logout accessed")
|
| 191 |
response = RedirectResponse(url="/login/")
|
| 192 |
response.delete_cookie("sb_access_token")
|
| 193 |
return response
|
| 194 |
|
| 195 |
+
@app.get("/healthz")
|
| 196 |
+
async def healthz():
|
| 197 |
+
"""Health check endpoint"""
|
| 198 |
+
status = {
|
| 199 |
+
"ok": True,
|
| 200 |
+
"ver20_loaded": ver20_app is not None,
|
| 201 |
+
"private_app_dir": str(private_app_dir) if private_app_dir else None
|
| 202 |
+
}
|
| 203 |
+
print(f"[HEALTHZ] {status}")
|
| 204 |
+
return JSONResponse(content=status)
|
| 205 |
+
|
| 206 |
+
print("[ROUTES] Root, logout, and healthz routes registered")
|
| 207 |
+
|
| 208 |
# --- Mount Gradio UIs ---
|
| 209 |
+
print("[PHASE] mount_login_start")
|
| 210 |
app = gr.mount_gradio_app(app, login_ui, path="/login")
|
| 211 |
+
print("[PHASE] mount_login_end path=/login")
|
| 212 |
|
| 213 |
# Ver20 App (protected)
|
| 214 |
+
print("[PHASE] mount_app_start")
|
| 215 |
if ver20_app:
|
| 216 |
app = gr.mount_gradio_app(app, ver20_app, path="/app", auth_dependency=get_current_user)
|
| 217 |
+
print("[PHASE] mount_app_end path=/app protected=true ver20=true")
|
| 218 |
else:
|
| 219 |
# Fallback: simple placeholder if ver20 failed to load
|
| 220 |
with gr.Blocks() as fallback_ui:
|
|
|
|
| 222 |
gr.Markdown("The private application failed to load. Please check logs.")
|
| 223 |
|
| 224 |
app = gr.mount_gradio_app(app, fallback_ui, path="/app", auth_dependency=get_current_user)
|
| 225 |
+
print("[PHASE] mount_app_end path=/app protected=true ver20=false fallback=true")
|
| 226 |
+
|
| 227 |
+
print("=" * 80)
|
| 228 |
+
print("๐ Habadashi Login Gateway Ready!")
|
| 229 |
+
print("=" * 80)
|
| 230 |
+
print(f"[STARTUP_COMPLETE] All phases completed successfully")
|
| 231 |
+
print(f"[STARTUP_COMPLETE] Access URLs:")
|
| 232 |
+
print(f" - Root: /")
|
| 233 |
+
print(f" - Login: /login/")
|
| 234 |
+
print(f" - App: /app/")
|
| 235 |
+
print(f" - Health: /healthz")
|
| 236 |
+
print(f" - Logout: /logout")
|
| 237 |
+
print("=" * 80)
|
bootstrap.py
CHANGED
|
@@ -11,10 +11,12 @@ def get_hf_token():
|
|
| 11 |
"""Get HF_TOKEN from environment variable"""
|
| 12 |
token = os.environ.get("HF_TOKEN")
|
| 13 |
if not token:
|
|
|
|
| 14 |
raise ValueError(
|
| 15 |
"HF_TOKEN not found. Please set HF_TOKEN environment variable "
|
| 16 |
"in HF Space Secrets to access private repository."
|
| 17 |
)
|
|
|
|
| 18 |
return token
|
| 19 |
|
| 20 |
def download_private_app(force_download: bool = False):
|
|
@@ -31,44 +33,84 @@ def download_private_app(force_download: bool = False):
|
|
| 31 |
repo_type = "space"
|
| 32 |
local_dir = Path("./private_app")
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
# Check if already downloaded (skip if exists and not forced)
|
| 35 |
if local_dir.exists() and not force_download:
|
| 36 |
# Verify essential files exist
|
| 37 |
app_py = local_dir / "app.py"
|
|
|
|
| 38 |
if app_py.exists():
|
| 39 |
-
print(f"
|
|
|
|
|
|
|
| 40 |
return local_dir
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
print(f"
|
| 43 |
|
| 44 |
try:
|
| 45 |
token = get_hf_token()
|
| 46 |
|
| 47 |
-
# Download entire Space repository
|
|
|
|
| 48 |
snapshot_download(
|
| 49 |
repo_id=repo_id,
|
| 50 |
repo_type=repo_type,
|
| 51 |
local_dir=str(local_dir),
|
| 52 |
-
local_dir_use_symlinks=False,
|
| 53 |
token=token,
|
| 54 |
)
|
| 55 |
|
| 56 |
-
print(f"
|
| 57 |
|
| 58 |
# Verify essential structure
|
| 59 |
-
|
| 60 |
-
if not app_py.exists():
|
| 61 |
-
raise FileNotFoundError(
|
| 62 |
-
f"app.py not found in downloaded repository. "
|
| 63 |
-
f"Expected at: {app_py}"
|
| 64 |
-
)
|
| 65 |
|
| 66 |
return local_dir
|
| 67 |
|
| 68 |
except Exception as e:
|
| 69 |
-
print(f"
|
|
|
|
|
|
|
| 70 |
raise
|
| 71 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
if __name__ == "__main__":
|
| 73 |
# Test download
|
| 74 |
download_private_app()
|
|
|
|
| 11 |
"""Get HF_TOKEN from environment variable"""
|
| 12 |
token = os.environ.get("HF_TOKEN")
|
| 13 |
if not token:
|
| 14 |
+
print("[BOOTSTRAP_ERROR] HF_TOKEN not found in environment")
|
| 15 |
raise ValueError(
|
| 16 |
"HF_TOKEN not found. Please set HF_TOKEN environment variable "
|
| 17 |
"in HF Space Secrets to access private repository."
|
| 18 |
)
|
| 19 |
+
print("[BOOTSTRAP] HF_TOKEN found (length: ***)")
|
| 20 |
return token
|
| 21 |
|
| 22 |
def download_private_app(force_download: bool = False):
|
|
|
|
| 33 |
repo_type = "space"
|
| 34 |
local_dir = Path("./private_app")
|
| 35 |
|
| 36 |
+
print(f"[BOOTSTRAP] Starting download")
|
| 37 |
+
print(f"[BOOTSTRAP] repo_id={repo_id} repo_type={repo_type}")
|
| 38 |
+
print(f"[BOOTSTRAP] local_dir={local_dir} force_download={force_download}")
|
| 39 |
+
print(f"[BOOTSTRAP] local_dir.exists()={local_dir.exists()}")
|
| 40 |
+
|
| 41 |
# Check if already downloaded (skip if exists and not forced)
|
| 42 |
if local_dir.exists() and not force_download:
|
| 43 |
# Verify essential files exist
|
| 44 |
app_py = local_dir / "app.py"
|
| 45 |
+
print(f"[BOOTSTRAP] Checking cache: app.py exists={app_py.exists()}")
|
| 46 |
if app_py.exists():
|
| 47 |
+
print(f"[BOOTSTRAP] Using cached download: {local_dir}")
|
| 48 |
+
# Verify structure
|
| 49 |
+
_verify_downloaded_structure(local_dir)
|
| 50 |
return local_dir
|
| 51 |
+
else:
|
| 52 |
+
print(f"[BOOTSTRAP] Cache invalid (app.py missing), will re-download")
|
| 53 |
|
| 54 |
+
print(f"[BOOTSTRAP] Starting fresh download from {repo_id}...")
|
| 55 |
|
| 56 |
try:
|
| 57 |
token = get_hf_token()
|
| 58 |
|
| 59 |
+
# Download entire Space repository (removed local_dir_use_symlinks - deprecated)
|
| 60 |
+
print(f"[BOOTSTRAP] Calling snapshot_download...")
|
| 61 |
snapshot_download(
|
| 62 |
repo_id=repo_id,
|
| 63 |
repo_type=repo_type,
|
| 64 |
local_dir=str(local_dir),
|
|
|
|
| 65 |
token=token,
|
| 66 |
)
|
| 67 |
|
| 68 |
+
print(f"[BOOTSTRAP] Download complete: {local_dir}")
|
| 69 |
|
| 70 |
# Verify essential structure
|
| 71 |
+
_verify_downloaded_structure(local_dir)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
return local_dir
|
| 74 |
|
| 75 |
except Exception as e:
|
| 76 |
+
print(f"[BOOTSTRAP_ERROR] Download failed: {e}")
|
| 77 |
+
import traceback
|
| 78 |
+
print(f"[TRACEBACK]\n{traceback.format_exc()}")
|
| 79 |
raise
|
| 80 |
|
| 81 |
+
def _verify_downloaded_structure(local_dir: Path):
|
| 82 |
+
"""Verify downloaded structure has essential components"""
|
| 83 |
+
print(f"[BOOTSTRAP_VERIFY] Checking downloaded structure...")
|
| 84 |
+
|
| 85 |
+
essential_files = [
|
| 86 |
+
"app.py",
|
| 87 |
+
"requirements.txt",
|
| 88 |
+
]
|
| 89 |
+
|
| 90 |
+
essential_dirs = [
|
| 91 |
+
"lib",
|
| 92 |
+
"exec",
|
| 93 |
+
"core",
|
| 94 |
+
"presentation",
|
| 95 |
+
]
|
| 96 |
+
|
| 97 |
+
for file_name in essential_files:
|
| 98 |
+
file_path = local_dir / file_name
|
| 99 |
+
exists = file_path.exists()
|
| 100 |
+
print(f"[BOOTSTRAP_VERIFY] {file_name}: {'EXISTS' if exists else 'MISSING'}")
|
| 101 |
+
if not exists and file_name == "app.py":
|
| 102 |
+
raise FileNotFoundError(
|
| 103 |
+
f"Critical file missing: {file_name}. "
|
| 104 |
+
f"Expected at: {file_path}"
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
for dir_name in essential_dirs:
|
| 108 |
+
dir_path = local_dir / dir_name
|
| 109 |
+
exists = dir_path.exists() and dir_path.is_dir()
|
| 110 |
+
print(f"[BOOTSTRAP_VERIFY] {dir_name}/: {'EXISTS' if exists else 'MISSING'}")
|
| 111 |
+
|
| 112 |
+
print(f"[BOOTSTRAP_VERIFY] Verification complete")
|
| 113 |
+
|
| 114 |
if __name__ == "__main__":
|
| 115 |
# Test download
|
| 116 |
download_private_app()
|
requirements.txt
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
# Public Gateway dependencies
|
| 2 |
fastapi
|
| 3 |
uvicorn
|
|
|
|
| 4 |
supabase
|
| 5 |
python-multipart
|
| 6 |
huggingface_hub
|
|
|
|
| 1 |
# Public Gateway dependencies
|
| 2 |
fastapi
|
| 3 |
uvicorn
|
| 4 |
+
gradio
|
| 5 |
supabase
|
| 6 |
python-multipart
|
| 7 |
huggingface_hub
|