File size: 5,430 Bytes
9756876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a35b6f
9756876
 
 
 
 
 
 
 
 
 
 
 
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
"""Optional provider bootstrap on the GPU host, never in the constrained HF builder.

All dependencies, Python and source are pinned. No source video or Gemini call is
involved. The API starts separately and advertises this model only after setup.
"""
import fcntl
import os
from pathlib import Path
import shutil
import subprocess
import sys
from baseball_batting.motion_adapters import GVHMR_REVISION
from baseball_batting.storage import atomic_json

ROOT=Path(__file__).resolve().parents[1]


def installation_environment():
    env=dict(os.environ)
    for name in ('BASEBALL_API_KEY','GOOGLE_API_KEY','HF_TOKEN','HUGGING_FACE_HUB_TOKEN'):env.pop(name,None)
    env.update(MAX_JOBS='1',OMP_NUM_THREADS='2',UV_CONCURRENT_DOWNLOADS='2',UV_LINK_MODE='copy',MPLBACKEND='Agg')
    return env


def launch_optional_setup():
    """Nonblocking startup. An absent licensed asset cannot delay or disable SAM."""
    if os.environ.get('BASEBALL_GVHMR_SKIP_SETUP')=='1':return False
    root=Path(os.environ.get('BASEBALL_DATA_ROOT','/data'));root.mkdir(parents=True,exist_ok=True)
    from baseball_batting.gvhmr_runtime import configured_record
    if configured_record():return False
    body=os.environ.get('BASEBALL_SMPLX_MODEL_PATH')
    if body and not Path(body).is_file():
        atomic_json(root/'gvhmr-setup-status.json',{'status':'unavailable','reason_code':'gvhmr_smplx_file_missing'})
        return False
    if not (os.environ.get('BASEBALL_SMPLX_MODEL_PATH') or os.environ.get('BASEBALL_SMPLX_REPO')):
        atomic_json(root/'gvhmr-setup-status.json',{'status':'unavailable','reason_code':'gvhmr_smplx_license_asset_required'})
        return False
    env=dict(os.environ);env.pop('BASEBALL_API_KEY',None);env.pop('GOOGLE_API_KEY',None)
    with (root/'gvhmr-setup-private.log').open('ab') as log:
        subprocess.Popen([sys.executable,'-m','tools.setup_gvhmr_api_worker'],env=env,
            stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
    return True


def main():
    root=Path(os.environ.get('BASEBALL_DATA_ROOT','/data'));root.mkdir(parents=True,exist_ok=True)
    status=root/'gvhmr-setup-status.json'
    with (root/'.gvhmr-setup.lock').open('a') as lock:
        try:fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
        except BlockingIOError:return 0
        def state(reason):atomic_json(status,{'status':'installing_runtime','reason_code':reason})
        try:
            from baseball_batting.gvhmr_runtime import configured_record
            if configured_record():return 0
            if not (os.environ.get('BASEBALL_SMPLX_MODEL_PATH') or os.environ.get('BASEBALL_SMPLX_REPO')):
                atomic_json(status,{'status':'unavailable','reason_code':'gvhmr_smplx_license_asset_required'});return 1
            env=installation_environment()
            def run(*args,**kwargs):
                return subprocess.run([str(a) for a in args],env=kwargs.pop('env',env),check=True,timeout=1800,**kwargs)
            worker=Path('/opt/gvhmr-runtime/bin/python')
            if not worker.is_file():
                state('gvhmr_runtime_installing')
                bootstrap=root/'.gvhmr-bootstrap';uv=bootstrap/'bin/python'
                if not uv.is_file():run(sys.executable,'-m','venv',bootstrap)
                run(uv,'-m','pip','install','--no-cache-dir','uv==0.9.10')
                env['UV_PYTHON_INSTALL_DIR']=str(root/'gvhmr-python')
                run(uv,'-m','uv','python','install','3.10')
                runtime=root/'.runtime-gvhmr';worker=runtime/'bin/python'
                if worker.is_file() and subprocess.run([str(worker),'-m','pip','--version'],env=env,capture_output=True).returncode:
                    shutil.rmtree(runtime)
                if not worker.is_file():run(uv,'-m','uv','venv','--python','3.10','--seed',runtime)
                run(worker,'-m','pip','install','--no-cache-dir','-r',ROOT/'requirements-gvhmr.txt')
            source=Path(os.environ.get('BASEBALL_GVHMR_SOURCE',str(root/'gvhmr-source')))
            if not (source/'.git').is_dir():
                run('git','init',source);run('git','-C',source,'remote','add','origin','https://github.com/zju3dv/GVHMR.git')
                run('git','-C',source,'fetch','--depth=1','origin',GVHMR_REVISION)
                run('git','-C',source,'checkout','--detach',GVHMR_REVISION)
            check_env={**env,'PYTHONPATH':str(source)+os.pathsep+str(ROOT)}
            run(worker,ROOT/'tools/check_gvhmr_runtime.py',env=check_env)
            run(worker,'-c','from baseball_batting.gvhmr_pose_worker import run; from baseball_batting.motion_refine_worker import load_adapter; from baseball_batting.motion_refinement import fit_window',env=check_env)
            state('gvhmr_assets_installing')
            provider_env=dict(os.environ,BASEBALL_GVHMR_SOURCE=str(source),PYTHONPATH=str(ROOT))
            provider_env.pop('BASEBALL_API_KEY',None);provider_env.pop('GOOGLE_API_KEY',None)
            # This is the only step that receives normal approved HF credentials.
            run(worker,'-m','tools.prepare_gvhmr_assets',env=provider_env)
            return 0
        except Exception as error:
            atomic_json(status,{'status':'unavailable','reason_code':'gvhmr_runtime_setup_failed','error_type':type(error).__name__})
            print('GVHMR optional runtime setup failed: '+type(error).__name__,flush=True);return 1


if __name__=='__main__':raise SystemExit(main())