WACATW commited on
Commit
f3fe32c
·
verified ·
1 Parent(s): 4b3372c

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -0
app.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hugging Face Space 入口(SDK: Gradio + ZeroGPU,业务 FastAPI 挂载于 Gradio 的 ASGI 应用)
2
+
3
+ ZeroGPU 平台强制要求:Space 启动时检测到 @spaces.GPU 装饰函数且调用
4
+ demo.launch()。本文件提供占位 GPU 函数与 Gradio demo;真正的业务
5
+ (前端页面 + /api/*)由 FastAPI 应用 main.app 提供。
6
+
7
+ 挂载策略(关键):HF 可能以 python app.py 运行,也可能 import 本模块
8
+ 后自行调用 demo.launch()。为保证两种方式下挂载都生效,这里 monkey-
9
+ patch 了 demo.launch:无论谁调用,启动 Gradio 后都会立即把 cc_app
10
+ 挂到 Gradio 底层 ASGI 应用(demo.app),并把根路径 / 指回云相机页面。
11
+
12
+ _gpu_probe 仅为满足平台检测,业务从不调用,不消耗 GPU 免费配额。
13
+ """
14
+ import threading
15
+ from pathlib import Path
16
+
17
+ import gradio as gr
18
+ import spaces # noqa: F401 (ZeroGPU 镜像自带)
19
+ from starlette.responses import FileResponse
20
+ from starlette.routing import Route
21
+
22
+ from main import app as cc_app
23
+
24
+ INDEX = Path(__file__).parent / "index.html"
25
+
26
+ print("[CC] module loaded", flush=True)
27
+
28
+
29
+ @spaces.GPU
30
+ def _gpu_probe(): # ZeroGPU 平台检测占位函数(业务不调用)
31
+ return "ok"
32
+
33
+
34
+ with gr.Blocks() as demo:
35
+ gr.Markdown("云端相机")
36
+
37
+ demo.queue()
38
+
39
+ _setup_done = False
40
+
41
+
42
+ def _setup():
43
+ """把业务 FastAPI 挂载到 Gradio 底层应用(幂等)"""
44
+ global _setup_done
45
+ if _setup_done:
46
+ return
47
+ fa = demo.app
48
+ print("[CC] demo.app:", type(fa).__module__ + "." + type(fa).__name__, flush=True)
49
+ print("[CC] server_port:", getattr(demo, "server_port", None), flush=True)
50
+ print("[CC] routes:", str([getattr(r, "path", type(r).__name__) for r in fa.router.routes])[:200], flush=True)
51
+ fa.mount("/", cc_app)
52
+
53
+ async def _index(request):
54
+ return FileResponse(INDEX)
55
+
56
+ fa.router.routes.insert(0, Route("/", _index, methods=["GET"]))
57
+ # 兜底:把业务路由直接复制到最前(绕过 Mount 匹配问题)
58
+ fa.router.routes = cc_app.router.routes + fa.router.routes
59
+ print("[CC] routes after:", str([getattr(r, "path", type(r).__name__) for r in fa.router.routes])[:260], flush=True)
60
+ _setup_done = True
61
+ print("[CC] setup complete", flush=True)
62
+
63
+
64
+ _orig_launch = demo.launch
65
+
66
+
67
+ def _launch_wrapper(*args, **kwargs):
68
+ result = _orig_launch(*args, **kwargs)
69
+ _setup()
70
+ return result
71
+
72
+
73
+ demo.launch = _launch_wrapper
74
+
75
+
76
+ if __name__ == "__main__":
77
+ print("[CC] main block executing", flush=True)
78
+ demo.launch(prevent_thread_lock=True, quiet=True)
79
+ # 保持主线程存活,防止进程退出导致服务关闭
80
+ threading.Event().wait()