#!/usr/bin/env python3 """Read-only interpreter/package provenance capture; no secrets/model downloads.""" import argparse,hashlib,importlib.metadata as md,importlib.util,json,os,platform,re,subprocess,sys,sysconfig from pathlib import Path from urllib.parse import urlparse,urlunparse CORE={'torch','torchvision','torchaudio','transformers','tokenizers','huggingface-hub','diffusers','diffsynth','accelerate','peft','ms-swift','deepspeed','flash-attn','vllm','verl','flash-linear-attention','tilelang','triton','ray','tensordict','torchcodec','numpy','scipy','pandas','pyarrow','pillow','opencv-python','opencv-python-headless','safetensors','qwen-vl-utils'} MODULES=['torch','torchvision','torchaudio','transformers','tokenizers','huggingface_hub','diffusers','diffsynth','accelerate','peft','swift','verl','vllm','fla','tilelang','triton','cv2','numpy'] def normalized(x):return re.sub('[-_.]+','-',x).lower() def redact(value): text=str(value) text=re.sub(r'\b(?:hf_|ghp_|github_pat_|sk-|pk-)[A-Za-z0-9_-]{20,}','[REDACTED]',text) text=re.sub(r'/pfs/[^/\s\"\']+','/local/workspace',text) text=re.sub(r'/root/','/local/home/',text) return text def safe_url(value): u=urlparse(value) if u.scheme=='file':return {'type':'local_source','portable':False,'directory_name':Path(u.path).name} clean_netloc=u.hostname or '' if u.port:clean_netloc+=':'+str(u.port) return {'type':'network_source','url':urlunparse((u.scheme,clean_netloc,u.path,'','',''))} def run(command): p=subprocess.run(command,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,env={**os.environ,'PYTHONDONTWRITEBYTECODE':'1','HF_HUB_OFFLINE':'1','TRANSFORMERS_OFFLINE':'1','MODELSCOPE_OFFLINE':'1'},timeout=180) return {'exit_code':p.returncode,'output':redact(p.stdout[-20000:])} def main(): p=argparse.ArgumentParser(description=__doc__);p.add_argument('--name',required=True);p.add_argument('--out',type=Path,required=True);p.add_argument('--private-out',type=Path,required=True);p.add_argument('--gpu-basic-check',action='store_true');a=p.parse_args();a.out.mkdir(parents=True,exist_ok=True);a.private_out.mkdir(parents=True,exist_ok=True) packages={};origins={};raw_origins={} for d in md.distributions(): name=d.metadata.get('Name') if not name:continue key=normalized(name);packages[key]=d.version if key in CORE: req=d.requires or [] origins[key]={'version':d.version,'requires_dist':req,'installer':(d.read_text('INSTALLER') or '').strip()} direct=d.read_text('direct_url.json') if direct: obj=json.loads(direct);raw_origins[key]=obj;origins[key]['origin']=safe_url(obj.get('url','')) for extra in ('vcs_info','dir_info','archive_info'): if extra in obj:origins[key][extra]=obj[extra] modules={};private_modules={} for name in MODULES: try:s=importlib.util.find_spec(name) except Exception as e:modules[name]={'found':False,'error_type':type(e).__name__};continue if not s:modules[name]={'found':False};continue path=s.origin;private_modules[name]=path modules[name]={'found':True,'module_file':Path(path).name if path else None} if path and Path(path).is_file():modules[name]['entry_file_sha256']=hashlib.sha256(Path(path).read_bytes()).hexdigest() check=run([sys.executable,'-m','pip','check']) conda=[];prefix=Path(sys.prefix) if (prefix/'conda-meta').is_dir(): for meta in sorted((prefix/'conda-meta').glob('*.json')): d=json.loads(meta.read_text());url=d.get('url') if url and 'file://' not in url: clean=safe_url(url)['url'];conda.append(clean+('#'+d['md5'] if d.get('md5') else '')) (a.out/'conda-explicit-linux-64.txt').write_text('@EXPLICIT\n'+'\n'.join(conda)+'\n') gpu={'checked':False,'training_or_model_inference_run':False} if a.gpu_basic_check: result=run([sys.executable,'-c',"import json,torch; d={'torch':torch.__version__,'cuda_runtime':torch.version.cuda,'cuda_available':torch.cuda.is_available(),'arch_list':torch.cuda.get_arch_list()};\nif torch.cuda.is_available():\n d.update(gpu=torch.cuda.get_device_name(0),capability=list(torch.cuda.get_device_capability(0)));x=torch.ones((2,2),device='cuda',dtype=torch.bfloat16);d['tiny_bfloat16_result']=float(x.sum());torch.cuda.synchronize()\nprint(json.dumps(d))"]) gpu={'checked':True,'basic_tensor_check':result,'training_or_model_inference_run':False} snapshot={'profile':a.name,'capture_scope':'observed current retained runtime; not proof of original launch-time environment', 'python':platform.python_version(),'implementation':platform.python_implementation(),'SOABI':sysconfig.get_config_var('SOABI'),'machine':platform.machine(),'platform':platform.system(),'libc':list(platform.libc_ver()), 'packages':dict(sorted(packages.items())),'core_package_provenance':origins,'module_presence':modules,'pip_check':check,'GPU':gpu, 'original_environment_modified':False,'credentials_included':False} text=json.dumps(snapshot,ensure_ascii=False,indent=2)+'\n' if re.search(r'\b(?:hf_|ghp_|github_pat_|sk-|pk-)[A-Za-z0-9_-]{25,}',text):raise ValueError('Unsafe credential-like capture') (a.out/'environment.snapshot.json').write_text(text) (a.out/'requirements.observed-full.lock.txt').write_text('\n'.join(k+'=='+v for k,v in sorted(packages.items()))+'\n') (a.private_out/(a.name+'.private.json')).write_text(json.dumps({'python_executable':sys.executable,'prefix':sys.prefix,'module_paths':private_modules,'raw_direct_origins':raw_origins},indent=2)+'\n') print(json.dumps({'profile':a.name,'python':snapshot['python'],'packages':len(packages),'core_versions':{k:packages.get(k) for k in sorted(CORE) if k in packages},'pip_check_exit':check['exit_code'],'GPU_basic_check':gpu},indent=2),flush=True) if __name__=='__main__':main()