#!/usr/bin/env python3 """一个配置文件起三个台(生成配置台、剧本验收台、渲染验收台)。 python3 apps/console/up.py --config consoles.json # 先体检,过了再起服务 python3 apps/console/up.py --config consoles.json --check # 只体检 配置只写仓库外的东西(三个 Python 环境、房子能力目录、场景目录、数据目录、端口),样例见 apps/console/consoles.example.json。生成器就是这份检出本身,提交号取 HEAD;问法目录和证据登记取仓库里的。 体检每条不过都写出缺什么、怎么补,全过才起服务;起来后打印三个台的地址。 """ import argparse import json import os from pathlib import Path import shutil import socket import subprocess import sys REPO = Path(__file__).resolve().parents[2] sys.path.insert(0, str(REPO)) from apps.console.server.review_layout import IMPORTS_DIR, ReviewLayoutError CONSOLE = REPO / 'apps/console' RENDER = ('env PYTHONPATH={repo} OPENBLAS_NUM_THREADS=1 {python} -B -m embodied_pipeline.runtime.render_cli render-script ' '--script {{segment_dir}} --capability {{capability}} --assets {{segment_dir}}/assets.json ' '--spec {{segment_dir}}/spec.json --out {{out_dir}}/r --max-wall-s {{max_wall_s}}') # 各环境要能导入的包:控制台本身、生成器(也出题)、渲染 IMPORTS = {'console': ['numpy', 'scipy'], 'generator': ['numpy', 'scipy', 'embodied_pipeline.gen.run', 'embodied_pipeline.prover'], 'render': ['habitat_sim', 'scipy', 'PIL', 'embodied_pipeline.runtime.render_cli']} def imports(python, modules): code = 'import importlib,sys\nfor m in sys.argv[1:]:\n try: importlib.import_module(m)\n except Exception as e: print(m, type(e).__name__, e)' try: r = subprocess.run([python, '-c', code, *modules], capture_output=True, text=True, timeout=120, env={**os.environ, 'PYTHONPATH': str(REPO)}, cwd=REPO) except (OSError, subprocess.TimeoutExpired) as exc: return f'{python} 跑不起来:{exc}' missing = (r.stdout + r.stderr).strip() return f'{python} 导入失败:{missing[-400:]}' if missing or r.returncode else None def check(cfg): """返回 [(项, 问题或 None)]。""" rows = [] for role, modules in IMPORTS.items(): if role == 'render' and not cfg.get('render', True): continue python = cfg.get('python', {}).get(role) rows.append((f'{role} 环境', imports(python, modules) if python else f'配置里缺 python.{role}')) cap = Path(cfg.get('capability_root', '')) houses = sorted(p.name for p in cap.glob('*/capability.json')) if cap.is_dir() else [] rows.append(('房子能力目录', None if houses else f'{cap} 下没有 */capability.json(见 apps/console/README.md“快速上手”)')) cat = cfg.get('scene_catalog') rows.append(('场景目录', None if not cat or (Path(cat) / 'catalog.json').is_file() else f'{cat}/catalog.json 不存在(catalog_build.py 的产出;不配则屏1 没有场景预览)')) rows.append(('前端', None if (CONSOLE / 'web/dist/index.html').is_file() else '没构建:cd apps/console && npm ci && npm run build')) head = subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=REPO, capture_output=True, text=True) dirty = subprocess.run(['git', 'status', '--porcelain', '--untracked-files=no'], cwd=REPO, capture_output=True, text=True) rows.append(('检出', '不是 git 检出' if head.returncode else ('有未提交改动,生成器拒跑(GENERATOR_DIRTY):先提交或 git stash' if dirty.stdout.strip() else None))) gen = cfg.get('python', {}).get('generator') plans = gen and subprocess.run([gen, '-B', '-c', 'from embodied_pipeline.prover import compile as c; c.fresh() or c.main()'], cwd=REPO, capture_output=True, text=True, timeout=60) rows.append(('出题计划', None if plans and plans.returncode == 0 else f'plans.json 编不出(屏1 的版本支持和出题都读它):{(plans.stderr.strip().splitlines() or ["缺 python.generator"])[-1] if plans else "缺 python.generator"}')) if cfg.get('render', True): gpu = shutil.which('nvidia-smi') and subprocess.run(['nvidia-smi', '-L'], capture_output=True, text=True).stdout.strip() rows.append(('GPU', None if gpu else '看不到 GPU(nvidia-smi -L 为空);没有 GPU 就在配置里写 "render": false')) if os.environ.get('CUDA_VISIBLE_DEVICES') == '': rows.append(('GPU', 'CUDA_VISIBLE_DEVICES 是空串,渲染会找不到卡;本脚本起服务时会去掉它')) missing = [tool for tool in ('ffmpeg', 'ffprobe') if not shutil.which(tool)] # the renderer encodes and probes the mp4s rows.append(('视频编码', f'找不到 {"、".join(missing)};渲染要用它们编码和核对录像' if missing else None)) with socket.socket() as s: busy = s.connect_ex(('127.0.0.1', int(cfg.get('port', 19040)))) == 0 rows.append(('端口', f'{cfg.get("port", 19040)} 已被占用' if busy else None)) return rows, head.stdout.strip() def serve_args(cfg, commit): data = Path(cfg['data_dir']).resolve() legacy = data / 'screen3' if legacy.is_dir() and any(legacy.iterdir()): # 新版不读这里,放行会让这些段和题目静默消失 raise ReviewLayoutError(f'{legacy} 里有旧布局的本地导入,新版不会读取;先迁到 {data / IMPORTS_DIR} 或移走,再启动') for sub in ('runs', 'notes', IMPORTS_DIR): (data / sub).mkdir(parents=True, exist_ok=True) py = cfg['python'] argv = [py['console'], '-B', str(CONSOLE / 'serve.py'), '--port', str(cfg.get('port', 19040)), '--root', f'local={data / IMPORTS_DIR}', '--notes-dir', str(data / 'notes'), '--np-catalog', str(REPO / 'spec/questions'), '--np-evidence-packages', str(REPO / 'embodied_pipeline/prover/plans.json'), '--np-generation-dir', str(data / 'runs'), '--np-generator-checkout', str(REPO), '--np-generator-commit', commit, '--np-generator-python', py['generator'], '--np-capability-root', str(Path(cfg['capability_root']).resolve()), '--np-gen-config-checkout', str(REPO), '--np-gen-config-python', py['generator'], '--np-convert-python', py['console']] if cfg.get('scene_catalog'): argv += ['--np-catalog-dir', str(Path(cfg['scene_catalog']).resolve())] if cfg.get('render', True): argv += ['--np-render-cmd', RENDER.format(repo=REPO, python=py['render'])] for alias, path in (cfg.get('extra_roots') or {}).items(): argv += ['--root', f'{alias}={path}'] # The render review page reads the packs written after each render (server/review_pack.py) under the runs dir. argv += ['--evidence-data', str(cfg.get('evidence_data') or data / 'runs')] return argv def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--config', required=True, type=Path) parser.add_argument('--check', action='store_true', help='只体检,不起服务') args = parser.parse_args() cfg = json.loads(args.config.read_text()) rows, commit = check(cfg) for item, problem in rows: print(('✗ ' if problem else '✓ ') + item + (':' + problem if problem else ''), flush=True) bad = [r for r in rows if r[1] and not r[1].startswith('CUDA_VISIBLE_DEVICES')] if bad: sys.exit(f'体检 {len(bad)} 项不过,没起服务') if args.check: return port = cfg.get('port', 19040) print(f'起服务(生成器 = 本检出 {commit[:12]})。三个台:\n' f' 生成配置台 http://127.0.0.1:{port}/#/config (结果 /#/results)\n' f' 剧本验收台 http://127.0.0.1:{port}/#/segments\n' f' 渲染验收台 http://127.0.0.1:{port}/evidence/evidence.html', flush=True) print(f'从自己电脑打开:VS Code 端口面板转发 {port},或 ssh -N -L {port}:127.0.0.1:{port} <登录这台的 ssh 参数>' '(见 apps/console/README.md“在 GPU 服务器上:从自己电脑打开”)', flush=True) env = {k: v for k, v in os.environ.items() if not (k == 'CUDA_VISIBLE_DEVICES' and v == '')} os.execve(cfg['python']['console'], serve_args(cfg, commit), env) if __name__ == '__main__': main()