cheekeong2025 commited on
Commit
1829e05
Β·
verified Β·
1 Parent(s): 87c4e84

Update loader.py

Browse files
Files changed (1) hide show
  1. loader.py +35 -124
loader.py CHANGED
@@ -1,145 +1,56 @@
1
- # loader.py β€” robust public proxy for PRIVATE Static Space (resolve + raw, root + static, SPA dirs)
2
  import os
3
- import mimetypes
4
- from urllib.parse import urljoin
5
- from typing import Optional, Tuple
6
-
7
  from fastapi import FastAPI, Request
8
- from fastapi.responses import Response, HTMLResponse, PlainTextResponse, JSONResponse
9
  import httpx
10
 
11
  app = FastAPI()
12
 
13
- # ==== Config from Secrets ====
14
- SPACE_ID = os.getenv("PRIVATE_SPACE_ID") # e.g. "cheekeong2025/iip-grading"
15
- HF_TOKEN = os.getenv("HF_TOKEN") # must have read access
16
- REVISION = os.getenv("REVISION", "main") # branch/tag/commit (defaults to main)
17
- # =============================
18
 
19
- if not SPACE_ID:
20
  raise RuntimeError(
21
- "PRIVATE_SPACE_ID is not set. Add it in Settings β†’ Repository secrets (e.g. 'cheekeong2025/iip-grading')."
 
 
22
  )
23
- if not HF_TOKEN:
24
- raise RuntimeError("HF_TOKEN is not set. Add a token with READ access to the private Space.")
25
-
26
- HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}
27
- BASE_RESOLVE = f"https://huggingface.co/spaces/{SPACE_ID}/resolve/{REVISION}/"
28
- BASE_RAW = f"https://huggingface.co/spaces/{SPACE_ID}/raw/{REVISION}/"
29
-
30
- def join(base: str, path: str) -> str:
31
- return urljoin(base, path.lstrip("/"))
32
-
33
- def with_query(url: str, request: Request) -> str:
34
- q = str(request.url.query or "")
35
- return f"{url}?{q}" if q else url
36
-
37
- def looks_like_file(path: str) -> bool:
38
- return "." in path.split("/")[-1]
39
-
40
- def guess_mime(path: str, default: str = "application/octet-stream") -> str:
41
- if path.endswith("/") or path == "":
42
- return "text/html; charset=utf-8"
43
- mime, _ = mimetypes.guess_type(path)
44
- return mime or default
45
-
46
- async def try_get(client: httpx.AsyncClient, url: str) -> httpx.Response:
47
- r = await client.get(url, headers=HEADERS)
48
- print(f"[proxy] GET {url} -> {r.status_code}")
49
- return r
50
-
51
- async def fetch_variants(client: httpx.AsyncClient, path: str, request: Request) -> Tuple[httpx.Response, str]:
52
- """
53
- Try variants in this order (stop at first 200):
54
- resolve:path
55
- resolve:static/path
56
- if dir β†’ resolve:path/index.html
57
- if dir β†’ resolve:static/path/index.html
58
- raw:path
59
- raw:static/path
60
- if dir β†’ raw:path/index.html
61
- if dir β†’ raw:static/path/index.html
62
- Returns (response, tried_description)
63
- """
64
- as_dir = not looks_like_file(path)
65
- variants = []
66
-
67
- # resolve
68
- variants.append(("resolve", join(BASE_RESOLVE, path)))
69
- variants.append(("resolve", join(BASE_RESOLVE, f"static/{path.lstrip('/')}")))
70
- if as_dir:
71
- variants.append(("resolve", join(BASE_RESOLVE, path.rstrip("/") + "/index.html")))
72
- variants.append(("resolve", join(BASE_RESOLVE, f"static/{path.rstrip('/')}/index.html")))
73
-
74
- # raw
75
- variants.append(("raw", join(BASE_RAW, path)))
76
- variants.append(("raw", join(BASE_RAW, f"static/{path.lstrip('/')}")))
77
- if as_dir:
78
- variants.append(("raw", join(BASE_RAW, path.rstrip("/") + "/index.html")))
79
- variants.append(("raw", join(BASE_RAW, f"static/{path.rstrip('/')}/index.html")))
80
-
81
- last = None
82
- tried = []
83
- for kind, base_url in variants:
84
- url = with_query(base_url, request)
85
- r = await try_get(client, url)
86
- tried.append(f"{kind}:{base_url}")
87
- if r.status_code == 200:
88
- return r, " -> ".join(tried)
89
- last = r
90
 
91
- # nothing 200; return last attempt (or 404-ish) and the tried list for debug
92
- return last, " -> ".join(tried)
93
 
94
- @app.get("/health")
95
- async def health():
96
- return {"status": "ok", "space": SPACE_ID, "revision": REVISION, "source": "resolve/raw"}
97
 
98
- @app.get("/_debug/fetch/{path:path}")
99
- async def debug_fetch(path: str, request: Request):
100
- """Manual debugging endpoint to see the exact chain we try and the final status."""
101
- try:
102
- async with httpx.AsyncClient(timeout=None, follow_redirects=True) as client:
103
- r, tried = await fetch_variants(client, path, request)
104
- return JSONResponse({"status": r.status_code, "content_type": r.headers.get("content-type"), "tried": tried})
105
- except Exception as e:
106
- return JSONResponse({"error": str(e)}, status_code=500)
107
 
108
  @app.get("/")
109
- async def root(request: Request):
110
- """
111
- Serve index.html robustly:
112
- - Try index.html (resolve/raw, root/static)
113
- - If that fails, try repo root as a last resort
114
- """
115
- try:
116
- async with httpx.AsyncClient(timeout=None, follow_redirects=True) as client:
117
- r, tried = await fetch_variants(client, "index.html", request)
118
- if r.status_code == 404:
119
- r, tried2 = await fetch_variants(client, "", request)
120
- tried += " || " + tried2
121
- except Exception as e:
122
- return PlainTextResponse(f"Error fetching root: {e}", status_code=500)
123
 
124
- ctype = r.headers.get("content-type", "text/html; charset=utf-8")
125
- print(f"[root] final status={r.status_code}, ctype={ctype}")
126
- # If HTML, decode text; else serve bytes
127
- if "text/html" in ctype:
128
- return HTMLResponse(r.text, status_code=r.status_code, media_type=ctype)
129
- return Response(content=r.content, status_code=r.status_code, media_type=ctype)
130
 
131
  @app.get("/{path:path}")
132
  async def proxy(path: str, request: Request):
133
- """
134
- Proxy all assets (CSS, JS, images, fonts, SPA routes).
135
- Tries resolve + raw, root + static, and directory index.html fallbacks.
136
- """
137
  try:
138
- async with httpx.AsyncClient(timeout=None, follow_redirects=True) as client:
139
- r, tried = await fetch_variants(client, path, request)
 
140
  except Exception as e:
141
- return PlainTextResponse(f"Error fetching {path}: {e}", status_code=500)
 
 
 
 
142
 
143
- ctype = r.headers.get("content-type") or guess_mime(path)
144
- print(f"[proxy] path={path} final status={r.status_code}, ctype={ctype}")
145
- return Response(content=r.content, media_type=ctype, status_code=r.status_code)
 
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_SPACE_ID = os.getenv("PRIVATE_SPACE_ID")
11
+ HF_TOKEN = os.getenv("HF_TOKEN")
 
 
12
 
13
+ if not PRIVATE_SPACE_ID:
14
  raise RuntimeError(
15
+ "❌ PRIVATE_SPACE_ID is not set.\n"
16
+ "Go to your Hugging Face Space β†’ Settings β†’ Repository secrets\n"
17
+ "and add PRIVATE_SPACE_ID=cheekeong2025/iip-grading"
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}