File size: 6,023 Bytes
87485e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
"""Gradio课程入口:兼容ZeroGPU启动登记,识别仍使用原浏览器/CPU路径。"""
import os
from contextlib import asynccontextmanager

# 必须在导入Gradio/MediaPipe之前关闭遥测并指定可写缓存,适配HF运行账号。
os.environ.setdefault('GRADIO_ANALYTICS_ENABLED', 'False')
os.environ.setdefault('MPLCONFIGDIR', '/tmp/matplotlib' if os.name != 'nt' else os.path.join(os.environ.get('TEMP', '.'), 'vision-lab-matplotlib'))

# ZeroGPU要求在CUDA相关库之前导入spaces;平台注册和模型推理是不同流程。
import spaces
from spaces.config import Config as SpacesConfig
import gradio as gr
import uvicorn
from fastapi import FastAPI
from server import app as lab_app, health


BOOT_RELEASE = '20261013-zero-1'
LAYOUT_RELEASE = '20261013-layout-2'
ZEROGPU_STATUS = {'enabled': SpacesConfig.zero_gpu, 'startupReported': False,
                  'registeredGpuFunctions': 0}


@spaces.GPU(duration=5)
def gpu_runtime_check():
    """仅供维护人员按需核实CUDA;课程识别、页面加载和启动均不调用它。"""
    try:
        import torch
    except ImportError:
        return {'available': False, 'note': 'PyTorch is not installed in this local CPU environment.'}
    if not torch.cuda.is_available():
        return {'available': False, 'note': 'No CUDA device is available in this environment.'}
    # 使用真实CUDA小运算检验调度后的设备;不生成或替代任何识别结果。
    checksum = torch.arange(16, device='cuda').square().sum().item()
    return {'available': True, 'device': torch.cuda.get_device_name(0),
            'checksum': checksum, 'expectedChecksum': 1240}


def report_zerogpu_startup():
    """挂载式Gradio没有执行Blocks.launch,须显式发送SDK启动登记且只发送一次。"""
    if not SpacesConfig.zero_gpu or ZEROGPU_STATUS['startupReported']:
        return
    import spaces.zero as zero_runtime
    from spaces.zero.decorator import decorated_cache
    startup = getattr(zero_runtime, 'startup', None)
    if not callable(startup) or not decorated_cache:
        raise RuntimeError('ZeroGPU startup registration is unavailable. Install the supplied requirements.txt.')
    # 使用固定spaces版本的原生协议;上报失败必须阻止启动,不能显示虚假的成功状态。
    startup()
    ZEROGPU_STATUS.update(startupReported=True,
                          registeredGpuFunctions=len(set(decorated_cache.values())))
    print(f'[{BOOT_RELEASE}] ZeroGPU startup report accepted; recognition uses browser/CPU.', flush=True)


@asynccontextmanager
async def lifespan(application):
    """先向平台登记,再加载CPU手势模型;保留模型原有释放机制。"""
    report_zerogpu_startup()
    async with lab_app.router.lifespan_context(application):
        yield


def runtime_health():
    """原健康结果另附启动补丁标识,方便线上核对,无图片/GPU请求。"""
    return {**health(), 'runtimePatch': BOOT_RELEASE, 'layoutPatch': LAYOUT_RELEASE,
            'zeroGpu': dict(ZEROGPU_STATUS)}


# 采用官方Gradio挂载接口;父服务负责一次性加载CPU模型,页面与模型保持同源。
app = FastAPI(lifespan=lifespan,
              docs_url=None, redoc_url=None, openapi_url=None)
app.mount('/lab', lab_app)
app.add_api_route('/api/health', runtime_health, methods=['GET'])

# HF父窗口会根据内容测高;课程窗口只按子页面自身的内容高度变化,不能依赖父视口高度。
LAB_CSS = '''
.gradio-container{max-width:100%!important;padding:0!important;min-height:0!important}
#vision-host{padding:0!important;margin:0!important;border:0!important}
#vision-lab{display:block;width:100%;height:1100px;min-height:0;border:0}
footer{display:none!important}
'''

# 同源子页面的body高度不随iframe视口增高,避免HF外层自动测高与内层互相放大。
# ResizeObserver覆盖切换任务、语言及识别结果;有限上界防止意外内容形成无限循环。
LAB_RESIZE_JS = '''() => {
  const frame = document.getElementById('vision-lab');
  if (!frame) return;
  let observer;
  const attach = () => {
    if (observer) observer.disconnect();
    const body = frame.contentDocument?.body;
    if (!body) return;
    const sync = () => {
      const height = Math.min(12000, Math.max(640, Math.ceil(body.getBoundingClientRect().height) + 3));
      if (Math.abs(frame.getBoundingClientRect().height - height) > 1) frame.style.height = `${height}px`;
    };
    observer = new ResizeObserver(sync);
    observer.observe(body);
    sync();
  };
  frame.addEventListener('load', attach);
  if (frame.contentDocument?.readyState === 'complete') attach();
}'''

with gr.Blocks(title='AI-Powered Image Recognition', css=LAB_CSS,
               js=LAB_RESIZE_JS,
               fill_height=False,
               analytics_enabled=False) as demo:
    # 同源页面完整复用已验证的课程界面;保留EN/中文、上传、叠加图和JSON导出。
    gr.HTML('<iframe id="vision-lab" title="AI-Powered Image Recognition" '
            f'data-layout-build="{LAYOUT_RELEASE}" src="/lab/" scrolling="no" '
            'allow="clipboard-write"></iframe>', elem_id='vision-host', container=False)
    # 登记真实Gradio维护接口,不增加学生操作步骤,也不在加载时触发GPU。
    # 仅显式调用该API时使用ZeroGPU额度;不把CPU模型包进GPU装饰器。
    diagnostic = gr.Button('GPU runtime check', visible=False)
    diagnostic_result = gr.JSON(visible=False)
    diagnostic.click(gpu_runtime_check, inputs=[], outputs=diagnostic_result,
                     api_name='gpu_runtime_check', show_api=False, concurrency_limit=1)

app = gr.mount_gradio_app(app, demo, path='/', show_api=False, ssr_mode=False)

if __name__ == '__main__':
    # ZeroGPU的PORT可属于平台代理,应用绑定7860;本地可独立设置APP_PORT。
    uvicorn.run(app, host='0.0.0.0', port=int(os.environ.get('APP_PORT', '7860')),
                access_log=False)