Spaces:
Running
Running
Download app/server.py from lilyjeongwon/math-tutor: direct link, hf CLI and curl.
- Browser
- Download file 10.1 kB
-
https://huggingface.co/spaces/lilyjeongwon/math-tutor/resolve/main/app/server.py
- Command line
-
hf download hf://spaces/lilyjeongwon/math-tutor/app/server.py
-
curl -L -o server.py https://huggingface.co/spaces/lilyjeongwon/math-tutor/resolve/main/app/server.py
10.1 kB
| """๋ก๊ทธ์ธ์ด ๋ถ์ ์๋ฒ: Gradio ํ๋ฉด ์์ ๋ก๊ทธ์ธ ๋ฌธ์ ์ธ์๋๋ค. | |
| ์คํ (์ ์ฅ์ ๋ฃจํธ์์): python -m app.server | |
| ํ์ํ ํ๊ฒฝ๋ณ์ (PowerShell ์์ $env:์ด๋ฆ="๊ฐ" ์ผ๋ก ์ค์ . ์ฑํ ยท์ฝ๋ยทGitHub ์ ์ ์ง ๋ง์ธ์): | |
| SUPABASE_URL https://<ํ๋ก์ ํธID>.supabase.co | |
| SUPABASE_SERVICE_KEY ์๋ฒ ๋น๋ฐ ํค (sb_secret_...) -- DB ์กฐํ์ฉ, ๋ธ๋ผ์ฐ์ ๋ก ๋๊ฐ์ง ์์ | |
| SUPABASE_PUBLISHABLE_KEY ๊ณต๊ฐ์ฉ ํค (sb_publishable_...) -- ๋ก๊ทธ์ธ API ํธ์ถ์ฉ (์์ผ๋ฉด ์ ํค๋ก ๋์ฒด) | |
| APP_SECRET ์ฟ ํค ์๋ช ์ฉ ์์ ๋ฌธ์์ด (24์ ์ด์). ๋ฐ๊พธ๋ฉด ๋ชจ๋ ๋ค์ ๋ก๊ทธ์ธํด์ผ ํจ | |
| BASE_URL ์ด ์ฑ์ ์ฃผ์ (๊ธฐ๋ณธ http://localhost:7860) | |
| ์ ํ: PORT(๊ธฐ๋ณธ 7860), HOST(๊ธฐ๋ณธ 127.0.0.1), STUDENT_POOL=draft (ํ์์๊ฒ๋ ๊ฒ์ ์ ๋ฌธ์ ๋ฅผ ๋ณด์ฌ ์ค) | |
| ์ฃผ์ ๊ตฌ์กฐ | |
| /login ๋ก๊ทธ์ธ ์๋ด ํ๋ฉด /login/start ๊ตฌ๊ธ ๋ก๊ทธ์ธ ์์ /auth/callback ๋ก๊ทธ์ธ ๋ณต๊ท ์ง์ | |
| /logout ๋ก๊ทธ์์ /app ๋ฌธ์ ํ์ด ํ๋ฉด (๋ก๊ทธ์ธํ ์ฌ๋๋ง) | |
| """ | |
| from __future__ import annotations | |
| import html | |
| import inspect | |
| import os | |
| import sys | |
| import urllib.parse | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[1])) | |
| from starlette.requests import Request # noqa: E402 | |
| from starlette.responses import HTMLResponse, PlainTextResponse, RedirectResponse # noqa: E402 | |
| from app import auth # noqa: E402 | |
| PAGE = """<!DOCTYPE html><html lang="ko"><head><meta charset="utf-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1"><title>์ํ AI ํํฐ</title> | |
| <style> | |
| body{{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center; | |
| background:linear-gradient(135deg,#4338ca,#0ea5e9);font-family:system-ui,-apple-system,"Malgun Gothic",sans-serif;color:#1f2937}} | |
| .card{{background:#fff;border-radius:24px;padding:36px 28px;max-width:360px;width:calc(100% - 40px);text-align:center;box-shadow:0 20px 50px rgba(0,0,0,.25)}} | |
| h1{{margin:0 0 6px;font-size:1.6rem}} p{{line-height:1.6;margin:10px 0}} .sub{{color:#6b7280;font-size:.92rem}} | |
| a.btn{{display:block;margin-top:22px;padding:15px;border-radius:14px;background:#4f46e5;color:#fff;text-decoration:none;font-weight:700;font-size:1.05rem}} | |
| .err{{color:#b91c1c;font-weight:600}} | |
| </style></head><body><div class="card">{body}</div></body></html>""" | |
| def page(body: str, status: int = 200) -> HTMLResponse: | |
| return HTMLResponse(PAGE.format(body=body), status_code=status) | |
| def build_routes(cfg: auth.Config, http=auth.http_json) -> list[tuple[str, object]]: | |
| """(๊ฒฝ๋ก, ์ฒ๋ฆฌ ํจ์) ๋ชฉ๋ก. ํจ์๋ Request ๋ฅผ ๋ฐ์ ์๋ต์ ๋๋ ค์ค๋ค.""" | |
| base_host = urllib.parse.urlparse(cfg.base_url).netloc | |
| def current(request: Request): | |
| return auth.user_from_cookies(request.cookies, cfg.secret) | |
| base_name = base_host.split(":")[0] | |
| LOCAL = {"localhost", "127.0.0.1"} | |
| def wrong_host(request: Request): | |
| """๋ด PC ์์ localhost ๋์ 127.0.0.1 ๋ก(๋๋ ๋ฐ๋๋ก) ์ ์ํ๋ฉด ์ฟ ํค๊ฐ ๊ฐ๋ผ์ ธ ๋ก๊ทธ์ธ์ด ๊นจ์ง๋ค -> ์ ์ ์ฃผ์๋ก ๋๋ ค๋ณด๋. | |
| ๋ฐฐํฌ(https ๋๋ฉ์ธ) ํ๊ฒฝ์์๋ ํ๋ก์ ๋๋ฌธ์ Host ๊ฐ ๋ฌ๋ผ ๋ณด์ผ ์ ์์ผ๋ฏ๋ก ์ด ์ฒ๋ฆฌ๋ฅผ ํ์ง ์๋๋ค.""" | |
| h = (request.headers.get("host") or "").split(":")[0] | |
| if base_name in LOCAL and h in LOCAL and h != base_name: | |
| return RedirectResponse(cfg.base_url + request.url.path, status_code=303) | |
| return None | |
| async def home(request: Request): | |
| if wrong_host(request): | |
| return wrong_host(request) | |
| return RedirectResponse("/app" if current(request) else "/login", status_code=303) | |
| async def login(request: Request): | |
| if wrong_host(request): | |
| return wrong_host(request) | |
| if current(request): | |
| return RedirectResponse("/app", status_code=303) | |
| # ํ๊น ํ์ด์ค ํ๋ฉด(์ก์) ์์์ ์ด๋ ธ์ ๋ ๊ตฌ๊ธ์ด ๋ก๊ทธ์ธ์ ๋ง์ผ๋ฏ๋ก, ๋๋ ์ ๋ ์ก์๋ฅผ ๋ฒ์ด๋ ์ ์ฒด ์ฐฝ์ผ๋ก ์ด๋ํ๋ค. | |
| return page('<h1>๐งฎ ์ํ AI ํํฐ</h1><p>์๋ ! ํ๊ต์์ ๋ฑ๋กํ<br><b>๊ตฌ๊ธ ๊ณ์ </b>์ผ๋ก ๋ค์ด์.</p>' | |
| '<a class="btn" target="_top" href="/login/start">Google๋ก ๋ก๊ทธ์ธ</a>' | |
| '<p class="sub">๋ฑ๋ก๋์ง ์์ ๊ณ์ ์ ๋ค์ด์ฌ ์ ์์ด์.</p>' | |
| '<p class="sub">๋ก๊ทธ์ธ ํ๋ฉด์ด ์ ์ด๋ฆฌ๋ฉด ์ฃผ์์ฐฝ์<br><b>' + html.escape(base_host) + '</b><br>์ ์ง์ ์ ๋ ฅํ์ธ์.</p>') | |
| async def login_start(request: Request): | |
| if wrong_host(request): | |
| return wrong_host(request) | |
| verifier, challenge = auth.make_pkce() | |
| resp = RedirectResponse(auth.authorize_url(cfg, challenge), status_code=303) | |
| resp.set_cookie(auth.PKCE_COOKIE, auth.sign({"v": verifier}, cfg.secret, auth.PKCE_TTL), | |
| max_age=auth.PKCE_TTL, httponly=True, samesite="lax", secure=cfg.secure_cookie, path="/") | |
| return resp | |
| def fail(reason: str, why: str = "", request: Request | None = None): | |
| # ์๋ฒ ์ฐฝ์๋ง ๋จ๊ธฐ๋ ์ง๋จ ์ค (์ด๋ฉ์ผยทํค๋ ์ ์ง ์์) | |
| host = request.headers.get("host") if request is not None else "" | |
| print(f"[๋ก๊ทธ์ธ ๊ฑฐ์ ] ์ฌ์ ={why or 'unknown'} ์ ์์ฃผ์={host}", flush=True) | |
| resp = page('<h1>๋ก๊ทธ์ธํ ์ ์์ด์</h1><p class="err">%s</p>' | |
| '<a class="btn" target="_top" href="/login">์ฒ์์ผ๋ก</a>' % html.escape(reason), 403) | |
| resp.delete_cookie(auth.PKCE_COOKIE, path="/") | |
| return resp | |
| async def callback(request: Request): | |
| q = request.query_params | |
| if q.get("error") or q.get("error_description"): | |
| # ๋ช ๋จ์ ์์ผ๋ฉด Supabase ๊ฐ ๊ฐ์ ๋จ๊ณ์์ ๊ฑฐ์ ํ๊ณ '๊ฐ์ ์ค ์ค๋ฅ'๋ก ์๋ ค ์ค๋ค | |
| return fail("ํ์ฉ ๋ช ๋จ์ ์๋ ๊ณ์ ์ด๊ฑฐ๋ ๋ก๊ทธ์ธ์ด ์ทจ์๋์ด์. ์ ์๋๊ป ๋ฑ๋ก์ ์์ฒญํด ์ฃผ์ธ์.", | |
| "provider_error:" + str(q.get("error_code") or q.get("error") or ""), request) | |
| code = q.get("code") | |
| pk = auth.verify(request.cookies.get(auth.PKCE_COOKIE), cfg.secret) | |
| if not code or not pk or not pk.get("v"): | |
| why = ("code_missing" if not code else | |
| "pkce_cookie_missing" if not request.cookies.get(auth.PKCE_COOKIE) else "pkce_cookie_invalid_or_expired") | |
| return fail("๋ก๊ทธ์ธ ์๊ฐ์ด ์ง๋ฌ๊ฑฐ๋ ์๋ชป๋ ์ ๊ทผ์ด์์. ์ฒ์๋ถํฐ ๋ค์ ์๋ํด ์ฃผ์ธ์.", why, request) | |
| try: | |
| user = auth.login_user(cfg, code, pk["v"], http) | |
| except auth.AuthError as e: | |
| return fail(e.reason, e.code, request) | |
| resp = RedirectResponse("/app", status_code=303) | |
| resp.set_cookie(auth.SESSION_COOKIE, auth.sign(user, cfg.secret, auth.SESSION_TTL), | |
| max_age=auth.SESSION_TTL, httponly=True, samesite="lax", secure=cfg.secure_cookie, path="/") | |
| resp.delete_cookie(auth.PKCE_COOKIE, path="/") | |
| return resp | |
| async def logout(request: Request): | |
| resp = RedirectResponse("/login", status_code=303) | |
| resp.delete_cookie(auth.SESSION_COOKIE, path="/") | |
| resp.delete_cookie(auth.PKCE_COOKIE, path="/") | |
| return resp | |
| async def healthz(request: Request): | |
| return PlainTextResponse("ok") | |
| return [("/", home), ("/login", login), ("/login/start", login_start), | |
| ("/auth/callback", callback), ("/logout", logout), ("/healthz", healthz)] | |
| class Guard: | |
| """/app ์๋๋ ๋ก๊ทธ์ธํ ์ฌ๋๋ง. ์๋๋ฉด /login ์ผ๋ก ๋๋ ค๋ณด๋ธ๋ค. (์์ ASGI ๋ผ์ Gradio ์ ์ค์๊ฐ ํต์ ์ ๋ฐฉํดํ์ง ์์)""" | |
| PROTECTED = ("/app", "/me", "/teacher", "/admin") # ๋ก๊ทธ์ธ ํ์ํ ๊ณณ (๊ฐ ํ๋ฉด์ ์ญํ ํ์ธ์ ํ๋ฉด์ด ๋ฐ๋ก ํจ) | |
| def __init__(self, app, secret: str, protect=None): | |
| if protect is None: | |
| protect = self.PROTECTED | |
| self.app, self.secret = app, secret | |
| self.protect = (protect,) if isinstance(protect, str) else tuple(protect) | |
| def guarded(self, path: str) -> bool: | |
| return any(path == p or path.startswith(p + "/") for p in self.protect) | |
| async def __call__(self, scope, receive, send): | |
| if scope["type"] in ("http", "websocket") and self.guarded(scope["path"]): | |
| if not auth.user_from_cookies(Request(scope).cookies, self.secret): | |
| if scope["type"] == "http": | |
| await RedirectResponse("/login", status_code=303)(scope, receive, send) | |
| else: | |
| await send({"type": "websocket.close", "code": 1008}) | |
| return | |
| await self.app(scope, receive, send) | |
| def create_app(): | |
| cfg = auth.Config.from_env() | |
| missing = cfg.problems() | |
| if missing: | |
| sys.exit("[์ค๋จ] ํ๊ฒฝ๋ณ์๊ฐ ํ์ํฉ๋๋ค: " + ", ".join(missing)) | |
| os.environ["TUTOR_AUTH"] = "on" # ํ๋ฉด(main.py)์ด ๋ก๊ทธ์ธ ๋ชจ๋๋ก ๋ง๋ค์ด์ง๊ฒ ํจ | |
| os.environ["APP_SECRET"] = cfg.secret | |
| from fastapi import FastAPI | |
| import gradio as gr | |
| from app import main as ui | |
| app = FastAPI() | |
| for path, fn in build_routes(cfg): | |
| app.add_route(path, fn, methods=["GET"]) | |
| from app import dashboards | |
| for path, fn, methods in dashboards.routes(cfg, on_mentor_change=ui.clear_mentor_cache): | |
| app.add_route(path, fn, methods=methods) | |
| app.add_middleware(Guard, secret=cfg.secret) | |
| extra = {k: v for k, v in ui.LAUNCH_CSS.items() if k in inspect.signature(gr.mount_gradio_app).parameters} | |
| return gr.mount_gradio_app(app, ui.demo, path="/app", **extra) | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(create_app(), host=os.environ.get("HOST", "127.0.0.1"), port=int(os.environ.get("PORT", "7860")), | |
| proxy_headers=True, forwarded_allow_ips="*") # ํ๊น ํ์ด์ค ๊ฐ์ ํ๋ก์ ๋ค์์ https ์ฃผ์๋ฅผ ์ฌ๋ฐ๋ฅด๊ฒ ์ธ์ | |