mendeld commited on
Commit
c6aaa21
·
verified ·
1 Parent(s): 5499291

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -154
app.py DELETED
@@ -1,154 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import os
4
- import secrets
5
- from pathlib import Path
6
-
7
- # ZeroGPU: import spaces before other GPU-sensitive modules.
8
- try:
9
- import spaces
10
- except ImportError: # Local lint/test fallback; ZeroGPU provides the real package.
11
- class _SpacesFallback:
12
- @staticmethod
13
- def GPU(*args, **kwargs):
14
- def deco(fn):
15
- return fn
16
- return deco
17
- spaces = _SpacesFallback()
18
- import gradio as gr
19
- import uvicorn
20
- from fastapi import FastAPI, Request
21
- from fastapi.middleware.cors import CORSMiddleware
22
- from fastapi.responses import JSONResponse, FileResponse
23
- from starlette.middleware.base import BaseHTTPMiddleware
24
- from starlette.middleware.sessions import SessionMiddleware
25
-
26
- from bh56_core import BH56_VERSION, STORE, admin_auth
27
- from bh56_ui import BASE_CSS, PAGE_JS, build_admin_ui, build_student_ui
28
-
29
-
30
- os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False")
31
- os.environ.setdefault("HF_HUB_DISABLE_TELEMETRY", "1")
32
- os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
33
-
34
- SESSION_SECRET = os.getenv("BH56_SESSION_SECRET", "")
35
- if not SESSION_SECRET:
36
- # A Space Secret is strongly recommended. This runtime-only value is safer
37
- # than hardcoding a secret in a public Space, but sessions reset on restart.
38
- SESSION_SECRET = secrets.token_urlsafe(48)
39
- print("[BH56 security] BH56_SESSION_SECRET is not configured; using a temporary runtime secret.")
40
-
41
- MAIN_ADMIN_PASSWORD = os.getenv("BH56_MAIN_ADMIN_PASSWORD", "")
42
- if not MAIN_ADMIN_PASSWORD:
43
- print("[BH56 security] BH56_MAIN_ADMIN_PASSWORD is not configured. /admin login will not accept the main account until it is set as a Space Secret.")
44
-
45
- app = FastAPI(
46
- title=f"Artificial Chachma (AC) {BH56_VERSION}",
47
- docs_url=None,
48
- redoc_url=None,
49
- openapi_url=None,
50
- )
51
- app.add_middleware(SessionMiddleware, secret_key=SESSION_SECRET, https_only=True, same_site="lax", max_age=1800)
52
-
53
- # Keep CORS restrictive. Embedding the page in an iframe does not require broad
54
- # cross-origin API access. Add origins only when a separate trusted frontend
55
- # truly needs XHR access.
56
- allowed_origins = [x.strip() for x in os.getenv("BH56_CORS_ORIGINS", "https://5bcheder.com,https://www.5bcheder.com").split(",") if x.strip()]
57
- app.add_middleware(
58
- CORSMiddleware,
59
- allow_origins=allowed_origins,
60
- allow_credentials=True,
61
- allow_methods=["GET", "POST"],
62
- allow_headers=["Content-Type", "Authorization", "X-Requested-With"],
63
- )
64
-
65
-
66
- class SecurityHeadersMiddleware(BaseHTTPMiddleware):
67
- async def dispatch(self, request: Request, call_next):
68
- response = await call_next(request)
69
- frame_ancestors = os.getenv(
70
- "BH56_FRAME_ANCESTORS",
71
- "'self' https://huggingface.co https://*.huggingface.co https://5bcheder.com https://www.5bcheder.com https://*.hf.space",
72
- )
73
- response.headers["X-Content-Type-Options"] = "nosniff"
74
- response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
75
- response.headers["Permissions-Policy"] = "geolocation=(self), microphone=(self), camera=()"
76
- response.headers["Content-Security-Policy"] = f"frame-ancestors {frame_ancestors};"
77
- response.headers["Cache-Control"] = "no-store" if request.url.path.startswith("/admin") else "private, max-age=0"
78
- return response
79
-
80
-
81
- app.add_middleware(SecurityHeadersMiddleware)
82
-
83
-
84
- ICON_PATH = Path(__file__).with_name("ac_app_icon.png")
85
-
86
- @app.get("/ac_app_icon.png", include_in_schema=False)
87
- def ac_app_icon():
88
- return FileResponse(str(ICON_PATH), media_type="image/png", headers={"Cache-Control":"public, max-age=86400"})
89
-
90
- @app.get("/health")
91
- def health():
92
- return JSONResponse({
93
- "ok": True,
94
- "name": "Artificial Chachma (AC)",
95
- "version": BH56_VERSION,
96
- "persistent_storage": STORE.persistent_enabled,
97
- })
98
-
99
-
100
- student_ui = build_student_ui()
101
- admin_ui = build_admin_ui()
102
-
103
- # IMPORTANT: mount /admin first. Then mount the student app at /. This keeps the
104
- # student URL clean while still providing a separate protected admin URL.
105
- app = gr.mount_gradio_app(
106
- app,
107
- admin_ui,
108
- path="/admin",
109
- auth=admin_auth,
110
- auth_message="AC Admin — authorized administrators only.",
111
- footer_links=[],
112
- show_error=False,
113
- max_file_size="25mb",
114
- enable_monitoring=False,
115
- mcp_server=False,
116
- ssr_mode=False,
117
- pwa=True,
118
- favicon_path=str(ICON_PATH),
119
- theme=gr.themes.Soft(),
120
- css=BASE_CSS,
121
- js=PAGE_JS,
122
- )
123
- app = gr.mount_gradio_app(
124
- app,
125
- student_ui,
126
- path="/",
127
- footer_links=[],
128
- show_error=False,
129
- max_file_size="25mb",
130
- enable_monitoring=False,
131
- mcp_server=False,
132
- ssr_mode=False,
133
- pwa=True,
134
- favicon_path=str(ICON_PATH),
135
- theme=gr.themes.Soft(primary_hue="blue"),
136
- css=BASE_CSS,
137
- js=PAGE_JS,
138
- )
139
-
140
-
141
- # With custom FastAPI mounting, some ZeroGPU runtimes do not see the normal
142
- # Blocks.launch() startup hook. This guarded call reports decorated @spaces.GPU
143
- # functions to ZeroGPU when the helper is available, and is harmless otherwise.
144
- try:
145
- import spaces.zero as _spaces_zero
146
- if hasattr(_spaces_zero, "startup"):
147
- _spaces_zero.startup()
148
- except Exception as exc:
149
- print(f"[BH56 ZeroGPU] startup report note: {exc}")
150
-
151
-
152
- if __name__ == "__main__":
153
- port = int(os.getenv("GRADIO_SERVER_PORT", os.getenv("PORT", "7860")))
154
- uvicorn.run(app, host="0.0.0.0", port=port, log_level="info")