"""Reproduce la evaluación o el entrenamiento en una carpeta nueva. Ejecutar con Python 3.10.12 y las versiones de requirements.txt instaladas. Por defecto se evalúan los pesos incluidos: no se vuelve a entrenar. """ from pathlib import Path import argparse import hashlib import json import shutil import subprocess import sys import urllib.request import zipfile BASE = Path(__file__).resolve().parent RUNS = { 'SnowballTarget': ('SnowballTarget.x86_64', 'Hugo_SnowballTarget_30nov2026', 6600), 'Pyramids': ('Pyramids', 'Hugo_PyramidsRND_30nov2026', 6700), } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('environment', choices=RUNS) parser.add_argument('--train', action='store_true', help='Entrenar desde cero antes de evaluar.') parser.add_argument('--workspace', type=Path, help='Carpeta nueva; no se sobrescribe trabajo anterior.') args = parser.parse_args() name = args.environment executable, run_id, port = RUNS[name] work = (args.workspace or BASE / f'reproduction_{name}').resolve() if work.exists() and any(work.iterdir()): parser.error(f'La carpeta ya contiene archivos: {work}. Elija otra con --workspace.') work.mkdir(parents=True, exist_ok=True) source = next(x for x in json.loads((BASE / 'environment_sources.json').read_text()) if x['environment'] == name) archive = work / f'{name}.zip' urllib.request.urlretrieve(source['source'], archive) digest = hashlib.sha256(archive.read_bytes()).hexdigest() if digest != source['sha256']: raise RuntimeError(f'El binario ha cambiado; SHA-256 esperado {source["sha256"]}, recibido {digest}.') archive_root = work / 'environments' archive_root.mkdir(parents=True) destination = archive_root / name with zipfile.ZipFile(archive) as z: for member in z.infolist(): path = (archive_root / member.filename).resolve() if not path.is_relative_to(archive_root.resolve()): raise RuntimeError('Ruta inesperada en el ZIP oficial.') z.extractall(archive_root) binary = next(destination.rglob(executable)) if binary.parent != destination: raise RuntimeError('La estructura del archivo descargado ha cambiado.') for file in destination.rglob('*'): if file.is_file() and (file == binary or file.suffix == '.so'): file.chmod(0o755) for filename in ('run_training.py', 'evaluate_unity.py'): shutil.copy2(BASE / filename, work / filename) shutil.copy2(BASE / 'config.yaml', work / 'config.yaml') if args.train: command = [sys.executable, 'run_training.py', 'config.yaml', f'--env={binary}', f'--run-id={run_id}', '--results-dir=results', '--no-graphics', f'--base-port={port}', '--num-envs=1', '--seed=42', '--time-scale=20', '--torch-device=cpu'] subprocess.run(command, cwd=work, check=True) else: model_directory = work / 'results' / run_id model_directory.mkdir(parents=True) shutil.copy2(BASE / f'{name}.onnx', model_directory / f'{name}.onnx') subprocess.run([sys.executable, 'evaluate_unity.py', name], cwd=work, check=True) print(f'Evaluación completada: {work / "evaluations" / name}') if __name__ == '__main__': main()