cheekeong2025 commited on
Commit
be0f3f7
·
verified ·
1 Parent(s): 32b7769

Create loader.py

Browse files
Files changed (1) hide show
  1. loader.py +56 -0
loader.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # loader.py — Public proxy loader for private static Hugging Face Space
2
+ import os
3
+ from fastapi import FastAPI, Request
4
+ from fastapi.responses import Response, HTMLResponse, PlainTextResponse
5
+ import httpx
6
+
7
+ app = FastAPI()
8
+
9
+ # ========= CONFIG =========
10
+ PRIVATE_STATIC_URL = os.getenv("PRIVATE_STATIC_URL")
11
+ HF_TOKEN = os.getenv("HF_TOKEN")
12
+
13
+ if not PRIVATE_STATIC_URL:
14
+ raise RuntimeError(
15
+ "❌ PRIVATE_STATIC_URL is not set.\n"
16
+ "Go to your Hugging Face Space → Settings → Repository secrets\n"
17
+ "and add PRIVATE_STATIC_URL=https://cheekeong2025-iip-grading.static.hf.space"
18
+ )
19
+
20
+ if not HF_TOKEN:
21
+ print("[loader] ⚠️ Warning: HF_TOKEN not set — attempting anonymous access.")
22
+
23
+ HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
24
+ # ===========================
25
+
26
+
27
+ @app.get("/")
28
+ async def root():
29
+ """Serve the index.html from the private static Space."""
30
+ async with httpx.AsyncClient(timeout=None) as client:
31
+ try:
32
+ r = await client.get(PRIVATE_STATIC_URL, headers=HEADERS)
33
+ r.raise_for_status()
34
+ except Exception as e:
35
+ return PlainTextResponse(f"Error fetching root: {e}", status_code=500)
36
+ return HTMLResponse(r.text, status_code=r.status_code)
37
+
38
+
39
+ @app.get("/{path:path}")
40
+ async def proxy(path: str, request: Request):
41
+ """Proxy all static assets (CSS, JS, images, etc.) from the private Space."""
42
+ url = f"{PRIVATE_STATIC_URL.rstrip('/')}/{path}"
43
+ try:
44
+ async with httpx.AsyncClient(timeout=None) as client:
45
+ r = await client.get(url, headers=HEADERS)
46
+ r.raise_for_status()
47
+ except Exception as e:
48
+ return PlainTextResponse(f"Error fetching {url}: {e}", status_code=500)
49
+
50
+ content_type = r.headers.get("content-type", "text/plain")
51
+ return Response(content=r.content, media_type=content_type, status_code=r.status_code)
52
+
53
+
54
+ @app.get("/health")
55
+ async def health():
56
+ return {"status": "ok", "source": PRIVATE_STATIC_URL}