Datasets:
Download code/evaluation-code/ent400-a06a1576/apps/console/tools/render_run.py from VEHwang/cocogni4d: direct link, hf CLI and curl.
- Browser
- Download file 11.5 kB
-
https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/ent400-a06a1576/apps/console/tools/render_run.py
- Command line
-
hf download hf://datasets/VEHwang/cocogni4d/code/evaluation-code/ent400-a06a1576/apps/console/tools/render_run.py
-
curl -L -o render_run.py https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/ent400-a06a1576/apps/console/tools/render_run.py
11.5 kB
| """Bounded rendering of a generated run; native dependencies stay in the child.""" | |
| import argparse | |
| from concurrent.futures import ThreadPoolExecutor | |
| import fcntl | |
| import json | |
| import math | |
| import os | |
| import queue | |
| from pathlib import Path | |
| import shlex | |
| import signal | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import time | |
| REPO = Path(__file__).resolve().parents[3] | |
| DEFAULT_RENDER_CMD = (shlex.quote(sys.executable) + ' -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}') | |
| # 渲染墙钟约为剧本时长的 4.7 倍(10-22 GPU 19032:90 s 剧本 425.7 s),时限取它的 2 倍再取整到 10 倍; | |
| # 一律 900 s 时 360 s 剧本必超时。 | |
| RENDER_S_PER_SCRIPT_S = 10 | |
| def segment_timeout(segment, floor): | |
| span = json.loads((segment / 'script.json').read_text()).get('span_s') # [起, 止] 世界秒(gen/export.py) | |
| return max(floor, math.ceil(RENDER_S_PER_SCRIPT_S * (float(span[1]) - float(span[0])))) if span else floor | |
| def command_for(segment, out, template=None, max_wall_s=900): | |
| values = dict(segment_dir=str(segment), out_dir=str(out), max_wall_s=str(int(max_wall_s))) | |
| template = template or DEFAULT_RENDER_CMD | |
| if '{capability}' in template: | |
| script = json.loads((segment / 'script.json').read_text()) | |
| values['capability'] = str(Path(script['generator']['house']) / 'capability.json') | |
| # Split before substitution: a path with spaces or shell syntax stays one argument. | |
| return [token.format(**values) for token in shlex.split(template)] | |
| def _render(segment, out, argv, timeout, cancelled): | |
| begin = time.monotonic() | |
| reason = None | |
| try: | |
| if cancelled(): | |
| raise RuntimeError('渲染已取消') | |
| if out.exists(): | |
| raise RuntimeError('渲染输出已存在但缺少完成包;保留失败产物,请使用新运行目录') | |
| with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr: | |
| child = subprocess.Popen(argv, cwd=REPO, stdout=stdout, stderr=stderr, start_new_session=True) | |
| try: | |
| deadline = begin + timeout | |
| while child.poll() is None: | |
| if cancelled(): | |
| raise RuntimeError('渲染已取消') | |
| remaining = deadline - time.monotonic() | |
| if remaining <= 0: | |
| raise TimeoutError('渲染超时(%s秒)' % timeout) | |
| try: | |
| child.wait(timeout=min(.1, remaining)) | |
| except subprocess.TimeoutExpired: | |
| pass | |
| except BaseException: | |
| try: | |
| os.killpg(child.pid, signal.SIGKILL) | |
| except ProcessLookupError: | |
| pass | |
| child.wait() | |
| raise | |
| finally: | |
| stderr.seek(0, 2) | |
| stderr.seek(max(0, stderr.tell() - 8000)) | |
| tail = stderr.read().decode('utf-8', errors='replace')[-2000:] | |
| if child.returncode: | |
| reason = tail or '渲染进程退出%d' % child.returncode | |
| elif not (out / 'r/observation/artifact.json').is_file(): | |
| reason = '渲染进程退出0但缺少 r/observation/artifact.json' | |
| except Exception as exc: | |
| reason = str(exc) | |
| if 'tail' in locals() and tail: | |
| reason += '\n' + tail | |
| return dict(state='render_failed' if reason else 'rendered', | |
| seconds=time.monotonic() - begin, reason=reason) | |
| def _native_jobs(plans): | |
| """Recognize the standard Habitat command; custom renderers stay per segment.""" | |
| groups={};single=[] | |
| fields={'--script','--capability','--assets','--spec','--out','--max-wall-s'} | |
| for segment,out,argv,limit in plans: | |
| try: | |
| index=argv.index('render-script') | |
| if argv[index-1]!='embodied_pipeline.runtime.render_cli':raise ValueError() | |
| tail=argv[index+1:] | |
| if len(tail)%2:raise ValueError() | |
| flags=dict(zip(tail[::2],tail[1::2])) | |
| if set(flags)!=fields:raise ValueError() | |
| key=(tuple(argv[:index]),flags['--capability']) | |
| groups.setdefault(key,[]).append((segment,out,argv,limit,flags)) | |
| except ValueError:single.append((segment,out,argv,limit)) | |
| return groups,single | |
| def _render_native_group(group,events,cancelled): | |
| begin=time.monotonic();remaining=list(group);child=None;reason=None | |
| try: | |
| with tempfile.TemporaryDirectory(prefix='native-render-') as tmp, tempfile.TemporaryFile() as stderr: | |
| jobs=[] | |
| for segment,out,argv,limit,flags in group: | |
| if out.exists():raise RuntimeError('渲染输出已存在但缺少完成包;请使用新运行目录') | |
| jobs.append({k[2:]:v for k,v in flags.items() if k!='--max-wall-s'}) | |
| manifest=Path(tmp)/'jobs.json';manifest.write_text(json.dumps(jobs)) | |
| prefix=group[0][2][:group[0][2].index('render-script')] | |
| argv=prefix+['render-batch','--backend','habitat','--jobs',str(manifest), | |
| '--max-wall-s',str(max(x[3] for x in group))] | |
| if cancelled():raise RuntimeError('渲染已取消') | |
| child=subprocess.Popen(argv,cwd=REPO,stdout=subprocess.DEVNULL,stderr=stderr,start_new_session=True) | |
| job_started=begin | |
| while remaining: | |
| segment,out,_,limit,_=remaining[0] | |
| artifact=out/'r/observation/artifact.json';failure=out/'r/attempt-failure.json' | |
| if artifact.is_file() or failure.is_file(): | |
| error=None if artifact.is_file() else json.loads(failure.read_text()).get('reason','渲染失败') | |
| events.put((segment,dict(state='rendered' if error is None else 'render_failed', | |
| seconds=time.monotonic()-job_started,reason=error))) | |
| remaining.pop(0);job_started=time.monotonic();continue | |
| if cancelled():raise RuntimeError('渲染已取消') | |
| if time.monotonic()-job_started>=limit:raise TimeoutError('渲染超时(%s秒)'%limit) | |
| if child.poll() is not None: | |
| stderr.seek(0,2);stderr.seek(max(0,stderr.tell()-2000)) | |
| raise RuntimeError(stderr.read().decode('utf-8',errors='replace')[-2000:] or '渲染进程缺少完成包') | |
| time.sleep(.05) | |
| child.wait(timeout=10) | |
| except Exception as exc:reason=str(exc) | |
| finally: | |
| if child is not None and child.poll() is None: | |
| try:os.killpg(child.pid,signal.SIGKILL) | |
| except ProcessLookupError:pass | |
| child.wait() | |
| for segment,_,_,_,_ in remaining: | |
| events.put((segment,dict(state='render_failed',seconds=time.monotonic()-begin,reason=reason or '渲染进程失败'))) | |
| def render_run(run_dir, workers=2, timeout=900, render_cmd=None, dry_run=False, | |
| on_segment=None, cancelled=None): | |
| """Return counts and per-segment states; callbacks execute on the caller thread. | |
| An artifact's presence is a scheduling skip, not a claim of media validation. | |
| Dry runs print argv without creating any files or taking the writer lock. | |
| """ | |
| root = Path(run_dir).resolve() | |
| if type(workers) is not int or workers < 1 or not math.isfinite(timeout) or timeout <= 0: | |
| raise ValueError('workers和timeout必须为正数,workers须为整数') | |
| if not (root / 'out').is_dir(): | |
| raise ValueError('运行目录缺少 out/') | |
| segments = sorted(p for p in (root / 'out').iterdir() if p.is_dir()) | |
| result = dict(rendered=0, failed=0, skipped=0, seconds={}) | |
| states = {} | |
| def record(segment, row): | |
| states[segment.name] = row | |
| result['seconds'][segment.name] = row['seconds'] | |
| key = dict(rendered='rendered', render_failed='failed', skipped='skipped')[row['state']] | |
| result[key] += 1 | |
| if on_segment: | |
| on_segment(segment.name, row) | |
| def planned(segment): | |
| return command_for(segment, root / 'r' / segment.name, render_cmd, segment_timeout(segment, timeout)) | |
| for segment in [s for s in segments if not (s / 'script.json').is_file()]: | |
| segments.remove(segment) | |
| record(segment, dict(state='skipped', seconds=0., reason='段目录里没有 script.json(生成没成),不渲染')) | |
| if dry_run: | |
| for segment in segments: | |
| if not (root / 'r' / segment.name / 'r/observation/artifact.json').is_file(): | |
| print(shlex.join(planned(segment))) | |
| return result, states | |
| with (root / '.render.lock').open('a') as lock: | |
| fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) | |
| errors = root / 'render-errors' | |
| errors.mkdir(exist_ok=True) | |
| with (root / 'render-commands.txt').open('a') as commands, ThreadPoolExecutor(max_workers=workers) as pool: | |
| pending = {};plans=[];events=queue.Queue() | |
| for segment in segments: | |
| out=root/'r'/segment.name | |
| if (out/'r/observation/artifact.json').is_file(): | |
| record(segment,dict(state='skipped',seconds=0.,reason='已有观测包;未重新核验媒体'));continue | |
| try: | |
| argv=planned(segment);commands.write(shlex.join(argv)+'\n');commands.flush() | |
| out.parent.mkdir(exist_ok=True) | |
| plans.append((segment,out,argv,segment_timeout(segment,timeout))) | |
| except Exception as exc:record(segment,dict(state='render_failed',seconds=0.,reason=str(exc))) | |
| groups,single=_native_jobs(plans) | |
| for group in groups.values():pending[pool.submit(_render_native_group,group,events,cancelled or (lambda:False))]=None | |
| for segment,out,argv,limit in single: | |
| pending[pool.submit(_render,segment,out,argv,limit,cancelled or (lambda:False))]=segment | |
| while pending or not events.empty(): | |
| try:segment,row=events.get(timeout=.05);record(segment,row) | |
| except queue.Empty:pass | |
| for future in list(pending): | |
| if future.done(): | |
| segment=pending.pop(future) | |
| result_row=future.result() | |
| if segment is not None:record(segment,result_row) | |
| for name, row in states.items(): | |
| if row['state'] == 'render_failed': | |
| path = errors / (name + '.txt') | |
| # Keep the first failure evidence on retries. | |
| if not path.exists(): | |
| path.write_text(row['reason'][-2000:] + '\n') | |
| return result, states | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--run', required=True, type=Path) | |
| parser.add_argument('--workers', type=int, default=2) | |
| parser.add_argument('--timeout', type=float, default=900) | |
| parser.add_argument('--render-cmd') | |
| parser.add_argument('--dry-run', action='store_true') | |
| args = parser.parse_args() | |
| result, _ = render_run(args.run, args.workers, args.timeout, args.render_cmd, args.dry_run) | |
| if not args.dry_run: | |
| print(json.dumps(result, ensure_ascii=False)) | |
| return int(bool(result['failed'])) | |
| if __name__ == '__main__': | |
| raise SystemExit(main()) | |