Deploy habadashi_login gateway
Browse filesFiles changed (4)
- README.md+60
- app.py+106-17
- bootstrap.py+54-12
- requirements.txt+1
34 unmodified lines35363734 unmodified lines3. User logs in with Supabase credentials4. On successful login, ver20 Gradio app is mounted at `/app/`5. User profile and organization info loaded from `profiles` table34 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969734 unmodified lines3. User logs in with Supabase credentials4. On successful login, ver20 Gradio app is mounted at `/app/`5. User profile and organization info loaded from `profiles` table## Startup Phase LoggingThe application logs structured startup phases to help diagnose issues. Look for these phase markers in the logs:### Expected Startup Sequence1. `[STARTUP_META]` - Environment and configuration info2. `[PHASE] bootstrap_start` - Begin downloading private app3. `[PHASE] bootstrap_end success=true` - Private app downloaded4. `[PHASE] supabase_init_start` - Initialize Supabase client5. `[PHASE] supabase_init_end success=true` - Supabase ready6. `[PHASE] fastapi_init_start/end` - FastAPI app created7. `[PHASE] create_ui_start/end` - Login UI created8. `[PHASE] import_ver20_start` - Import ver20 app9. `[PHASE] import_ver20_end success=true` - Ver20 loaded10. `[PHASE] mount_login_start/end` - Login UI mounted11. `[PHASE] mount_app_start/end` - Ver20 app mounted12. `[STARTUP_COMPLETE]` - All phases complete### Health Check EndpointOnce started, check the health endpoint:```bashcurl https://your-space.hf.space/healthz```Expected response:```json{"ok": true,"ver20_loaded": true,"private_app_dir": "./private_app"}```### Debugging Startup FailuresIf the Space fails to start or restarts repeatedly:1. **Check the last phase reached** in logs2. **Look for `[ERROR]` and `[TRACEBACK]` markers** after the last phase3. **Common failure points:**- `bootstrap_end success=false` - HF_TOKEN missing or invalid- `supabase_init_end success=false` - SUPABASE_URL/KEY missing- `import_ver20_end success=false` - Ver20 app.py structure issue- No phases after `mount_app_end` - Port binding or health check issue### Request LoggingAll HTTP requests are logged with:- `[REQUEST]` - Incoming request (method, path)- `[RESPONSE]` - Response status and durationExample:```[REQUEST] method=GET path=/[RESPONSE] method=GET path=/ status=307 duration=0.015s```
5 unmodified lines678910111213141 unmodified line16171819202122231 unmodified line252627282930313233343536373839404142434445464748495051525354555657585960616263641 unmodified line666768697071727317 unmodified lines9192939495969798991001011021031041051061071081091101111121131141151161171181191201211221 unmodified line1241251261271281291301311321331341351361371381391401411 unmodified line1431441451461471485 unmodified linesimport osimport sysfrom pathlib import Pathfrom fastapi import FastAPI, Request, Depends, HTTPExceptionfrom fastapi.responses import RedirectResponseimport gradio as grfrom supabase import create_client, Client1 unmodified linefrom bootstrap import download_private_appfrom login import create_login_ui# --- Bootstrap: Download private app at startup ---print("π Starting Habadashi Login Gateway...")try:private_app_dir = download_private_app()1 unmodified lineprivate_app_path = str(private_app_dir.resolve())if private_app_path not in sys.path:sys.path.insert(0, private_app_path)print(f"β Added to Python path: {private_app_path}")except Exception as e:print(f"β Failed to bootstrap private app: {e}")print("β οΈ Application will start but /app/ route will not work")private_app_dir = None# --- Supabase Setup ---SUPABASE_URL = os.environ.get("SUPABASE_URL")SUPABASE_KEY = os.environ.get("SUPABASE_KEY")if not SUPABASE_URL or not SUPABASE_KEY:raise ValueError("SUPABASE_URL and SUPABASE_KEY must be set in environment variables. ""Please configure them in HF Space Secrets.")supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)# --- FastAPI App ---app = FastAPI()# --- Authentication Handler (for login UI) ---def handle_login(email, password):"""Handle login attempt via Supabase"""try:res = supabase.auth.sign_in_with_password({"email": email, "password": password})if res.session:return (gr.update(visible=False),gr.update(visible=True, value=f"### β γγ°γ€γ³ζε: {email}"),res.session.access_token)except Exception as e:return gr.update(), gr.update(value=f"β γ¨γ©γΌ: {str(e)}"), None# --- Authentication Dependency ---1 unmodified line"""Verify token from cookie and fetch user profile"""token = request.cookies.get("sb_access_token")print(f"--- Auth Check ---")print(f"Token present: {bool(token)}")if not token:return None17 unmodified lines"org_name": (profile_data.get("organizations") or {}).get("name")}print(f"Auth Success: {user_dict['email']}")return user_dictexcept Exception as e:print(f"Auth Error: {e}")return None# --- Create UI instances ---login_ui = create_login_ui(handle_login)# Import ver20 app (Gradio Blocks)ver20_app = Noneif private_app_dir:try:# Import app module from downloaded private appfrom app import app as ver20_blocksver20_app = ver20_blocksprint("β Successfully imported ver20 Gradio app")except Exception as e:print(f"β Failed to import ver20 app: {e}")print(f" Make sure ver20/app.py exports 'app' variable (Gradio Blocks)")# --- Routes ---@app.get("/")async def root(user=Depends(get_current_user)):"""Root route - redirect to login or app based on auth status"""if isinstance(user, dict) and user.get("user_id"):return RedirectResponse(url="/app/")return RedirectResponse(url="/login/")1 unmodified line@app.get("/logout")async def logout():"""Logout route - clear cookie and redirect to login"""response = RedirectResponse(url="/login/")response.delete_cookie("sb_access_token")return response# --- Mount Gradio UIs ---# Login UI (public)app = gr.mount_gradio_app(app, login_ui, path="/login")# Ver20 App (protected)if ver20_app:app = gr.mount_gradio_app(app, ver20_app, path="/app", auth_dependency=get_current_user)print("β Mounted ver20 app at /app/ (protected)")else:# Fallback: simple placeholder if ver20 failed to loadwith gr.Blocks() as fallback_ui:1 unmodified linegr.Markdown("The private application failed to load. Please check logs.")app = gr.mount_gradio_app(app, fallback_ui, path="/app", auth_dependency=get_current_user)print("β οΈ Mounted fallback UI at /app/ (ver20 failed to load)")print("π Habadashi Login Gateway ready!")5 unmodified lines678910111213141516171 unmodified line1920212223242526272829303132333435363738394041421 unmodified line44454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211 unmodified line12312412512612712812917 unmodified lines1471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851 unmodified line1871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192201 unmodified line2222232242252262272282292302312322332342352362375 unmodified linesimport osimport sysimport timeimport tracebackfrom pathlib import Pathfrom fastapi import FastAPI, Request, Depends, HTTPExceptionfrom fastapi.responses import RedirectResponse, JSONResponsefrom starlette.middleware.base import BaseHTTPMiddlewareimport gradio as grfrom supabase import create_client, Client1 unmodified linefrom bootstrap import download_private_appfrom login import create_login_ui# --- Startup Meta Info ---print("=" * 80)print("π Starting Habadashi Login Gateway")print("=" * 80)print(f"[STARTUP_META] Python version: {sys.version}")print(f"[STARTUP_META] CWD: {os.getcwd()}")print(f"[STARTUP_META] PORT: {os.environ.get('PORT', 'not set')}")print(f"[STARTUP_META] SPACE_ID: {os.environ.get('SPACE_ID', 'not set')}")print(f"[STARTUP_META] SPACE_HOST: {os.environ.get('SPACE_HOST', 'not set')}")print(f"[STARTUP_META] GRADIO_SERVER_NAME: {os.environ.get('GRADIO_SERVER_NAME', 'not set')}")print(f"[STARTUP_META] GRADIO_SERVER_PORT: {os.environ.get('GRADIO_SERVER_PORT', 'not set')}")print(f"[STARTUP_META] HF_TOKEN: {'***set***' if os.environ.get('HF_TOKEN') else 'NOT SET'}")print(f"[STARTUP_META] SUPABASE_URL: {'***set***' if os.environ.get('SUPABASE_URL') else 'NOT SET'}")print(f"[STARTUP_META] SUPABASE_KEY: {'***set***' if os.environ.get('SUPABASE_KEY') else 'NOT SET'}")print("=" * 80)# --- Bootstrap: Download private app at startup ---print("[PHASE] bootstrap_start")try:private_app_dir = download_private_app()1 unmodified lineprivate_app_path = str(private_app_dir.resolve())if private_app_path not in sys.path:sys.path.insert(0, private_app_path)print(f"[PHASE] bootstrap_end success=true path={private_app_path}")except Exception as e:print(f"[PHASE] bootstrap_end success=false")print(f"[ERROR] Bootstrap failed: {e}")print(f"[TRACEBACK]\n{traceback.format_exc()}")print("β οΈ Application will start but /app/ route will not work")private_app_dir = None# --- Supabase Setup ---print("[PHASE] supabase_init_start")SUPABASE_URL = os.environ.get("SUPABASE_URL")SUPABASE_KEY = os.environ.get("SUPABASE_KEY")if not SUPABASE_URL or not SUPABASE_KEY:print("[ERROR] SUPABASE_URL and/or SUPABASE_KEY not set")raise ValueError("SUPABASE_URL and SUPABASE_KEY must be set in environment variables. ""Please configure them in HF Space Secrets.")try:supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)print(f"[PHASE] supabase_init_end success=true")except Exception as e:print(f"[PHASE] supabase_init_end success=false")print(f"[ERROR] Supabase init failed: {e}")print(f"[TRACEBACK]\n{traceback.format_exc()}")raise# --- FastAPI App ---print("[PHASE] fastapi_init_start")app = FastAPI()print("[PHASE] fastapi_init_end")# --- Request Logging Middleware ---class RequestLoggingMiddleware(BaseHTTPMiddleware):async def dispatch(self, request: Request, call_next):start_time = time.time()path = request.url.pathmethod = request.methodprint(f"[REQUEST] method={method} path={path}")try:response = await call_next(request)duration = time.time() - start_timeprint(f"[RESPONSE] method={method} path={path} status={response.status_code} duration={duration:.3f}s")return responseexcept Exception as e:duration = time.time() - start_timeprint(f"[RESPONSE] method={method} path={path} status=500 duration={duration:.3f}s error={e}")raiseapp.add_middleware(RequestLoggingMiddleware)print("[MIDDLEWARE] RequestLoggingMiddleware added")# --- Authentication Handler (for login UI) ---def handle_login(email, password):"""Handle login attempt via Supabase"""print(f"[AUTH] Login attempt for: {email}")try:res = supabase.auth.sign_in_with_password({"email": email, "password": password})if res.session:print(f"[AUTH] Login successful: {email}")return (gr.update(visible=False),gr.update(visible=True, value=f"### β γγ°γ€γ³ζε: {email}"),res.session.access_token)except Exception as e:print(f"[AUTH] Login failed for {email}: {e}")return gr.update(), gr.update(value=f"β γ¨γ©γΌ: {str(e)}"), None# --- Authentication Dependency ---1 unmodified line"""Verify token from cookie and fetch user profile"""token = request.cookies.get("sb_access_token")print(f"[AUTH_CHECK] Token present: {bool(token)}")if not token:return None17 unmodified lines"org_name": (profile_data.get("organizations") or {}).get("name")}print(f"[AUTH_CHECK] Success: user={user_dict['email']} role={user_dict['role']}")return user_dictexcept Exception as e:print(f"[AUTH_CHECK] Failed: {e}")return None# --- Create UI instances ---print("[PHASE] create_ui_start")login_ui = create_login_ui(handle_login)print("[PHASE] create_ui_end component=login_ui")# Import ver20 app (Gradio Blocks)print("[PHASE] import_ver20_start")ver20_app = Noneif private_app_dir:try:# Import app module from downloaded private appfrom app import app as ver20_blocksver20_app = ver20_blocksprint(f"[PHASE] import_ver20_end success=true type={type(ver20_app)}")except Exception as e:print(f"[PHASE] import_ver20_end success=false")print(f"[ERROR] Failed to import ver20 app: {e}")print(f"[TRACEBACK]\n{traceback.format_exc()}")else:print(f"[PHASE] import_ver20_end success=false reason=bootstrap_failed")# --- Routes ---@app.get("/")async def root(user=Depends(get_current_user)):"""Root route - redirect to login or app based on auth status"""print(f"[ROUTE] / accessed, user_authenticated={isinstance(user, dict) and user.get('user_id')}")if isinstance(user, dict) and user.get("user_id"):return RedirectResponse(url="/app/")return RedirectResponse(url="/login/")1 unmodified line@app.get("/logout")async def logout():"""Logout route - clear cookie and redirect to login"""print(f"[ROUTE] /logout accessed")response = RedirectResponse(url="/login/")response.delete_cookie("sb_access_token")return response@app.get("/healthz")async def healthz():"""Health check endpoint"""status = {"ok": True,"ver20_loaded": ver20_app is not None,"private_app_dir": str(private_app_dir) if private_app_dir else None}print(f"[HEALTHZ] {status}")return JSONResponse(content=status)print("[ROUTES] Root, logout, and healthz routes registered")# --- Mount Gradio UIs ---print("[PHASE] mount_login_start")app = gr.mount_gradio_app(app, login_ui, path="/login")print("[PHASE] mount_login_end path=/login")# Ver20 App (protected)print("[PHASE] mount_app_start")if ver20_app:app = gr.mount_gradio_app(app, ver20_app, path="/app", auth_dependency=get_current_user)print("[PHASE] mount_app_end path=/app protected=true ver20=true")else:# Fallback: simple placeholder if ver20 failed to loadwith gr.Blocks() as fallback_ui:1 unmodified linegr.Markdown("The private application failed to load. Please check logs.")app = gr.mount_gradio_app(app, fallback_ui, path="/app", auth_dependency=get_current_user)print("[PHASE] mount_app_end path=/app protected=true ver20=false fallback=true")print("=" * 80)print("π Habadashi Login Gateway Ready!")print("=" * 80)print(f"[STARTUP_COMPLETE] All phases completed successfully")print(f"[STARTUP_COMPLETE] Access URLs:")print(f" - Root: /")print(f" - Login: /login/")print(f" - App: /app/")print(f" - Health: /healthz")print(f" - Logout: /logout")print("=" * 80)
10 unmodified lines1112131415161718192010 unmodified lines313233343536373839404142434445464748495051525354555657585960616263646566676869707172737410 unmodified lines"""Get HF_TOKEN from environment variable"""token = os.environ.get("HF_TOKEN")if not token:raise ValueError("HF_TOKEN not found. Please set HF_TOKEN environment variable ""in HF Space Secrets to access private repository.")return tokendef download_private_app(force_download: bool = False):10 unmodified linesrepo_type = "space"local_dir = Path("./private_app")# Check if already downloaded (skip if exists and not forced)if local_dir.exists() and not force_download:# Verify essential files existapp_py = local_dir / "app.py"if app_py.exists():print(f"β Private app already downloaded: {local_dir}")return local_dirprint(f"π Downloading private app from {repo_id}...")try:token = get_hf_token()# Download entire Space repositorysnapshot_download(repo_id=repo_id,repo_type=repo_type,local_dir=str(local_dir),local_dir_use_symlinks=False,token=token,)print(f"β Download complete: {local_dir}")# Verify essential structureapp_py = local_dir / "app.py"if not app_py.exists():raise FileNotFoundError(f"app.py not found in downloaded repository. "f"Expected at: {app_py}")return local_direxcept Exception as e:print(f"β Failed to download private app: {e}")raiseif __name__ == "__main__":# Test downloaddownload_private_app()10 unmodified lines11121314151617181920212210 unmodified lines3334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511610 unmodified lines"""Get HF_TOKEN from environment variable"""token = os.environ.get("HF_TOKEN")if not token:print("[BOOTSTRAP_ERROR] HF_TOKEN not found in environment")raise ValueError("HF_TOKEN not found. Please set HF_TOKEN environment variable ""in HF Space Secrets to access private repository.")print("[BOOTSTRAP] HF_TOKEN found (length: ***)")return tokendef download_private_app(force_download: bool = False):10 unmodified linesrepo_type = "space"local_dir = Path("./private_app")print(f"[BOOTSTRAP] Starting download")print(f"[BOOTSTRAP] repo_id={repo_id} repo_type={repo_type}")print(f"[BOOTSTRAP] local_dir={local_dir} force_download={force_download}")print(f"[BOOTSTRAP] local_dir.exists()={local_dir.exists()}")# Check if already downloaded (skip if exists and not forced)if local_dir.exists() and not force_download:# Verify essential files existapp_py = local_dir / "app.py"print(f"[BOOTSTRAP] Checking cache: app.py exists={app_py.exists()}")if app_py.exists():print(f"[BOOTSTRAP] Using cached download: {local_dir}")# Verify structure_verify_downloaded_structure(local_dir)return local_direlse:print(f"[BOOTSTRAP] Cache invalid (app.py missing), will re-download")print(f"[BOOTSTRAP] Starting fresh download from {repo_id}...")try:token = get_hf_token()# Download entire Space repository (removed local_dir_use_symlinks - deprecated)print(f"[BOOTSTRAP] Calling snapshot_download...")snapshot_download(repo_id=repo_id,repo_type=repo_type,local_dir=str(local_dir),token=token,)print(f"[BOOTSTRAP] Download complete: {local_dir}")# Verify essential structure_verify_downloaded_structure(local_dir)return local_direxcept Exception as e:print(f"[BOOTSTRAP_ERROR] Download failed: {e}")import tracebackprint(f"[TRACEBACK]\n{traceback.format_exc()}")raisedef _verify_downloaded_structure(local_dir: Path):"""Verify downloaded structure has essential components"""print(f"[BOOTSTRAP_VERIFY] Checking downloaded structure...")essential_files = ["app.py","requirements.txt",]essential_dirs = ["lib","exec","core","presentation",]for file_name in essential_files:file_path = local_dir / file_nameexists = file_path.exists()print(f"[BOOTSTRAP_VERIFY] {file_name}: {'EXISTS' if exists else 'MISSING'}")if not exists and file_name == "app.py":raise FileNotFoundError(f"Critical file missing: {file_name}. "f"Expected at: {file_path}")for dir_name in essential_dirs:dir_path = local_dir / dir_nameexists = dir_path.exists() and dir_path.is_dir()print(f"[BOOTSTRAP_VERIFY] {dir_name}/: {'EXISTS' if exists else 'MISSING'}")print(f"[BOOTSTRAP_VERIFY] Verification complete")if __name__ == "__main__":# Test downloaddownload_private_app()
123456# Public Gateway dependenciesfastapiuvicornsupabasepython-multiparthuggingface_hub1234567# Public Gateway dependenciesfastapiuvicorngradiosupabasepython-multiparthuggingface_hub
README.md+60
app.py+106-17
bootstrap.py+54-12
requirements.txt+1