#!/usr/bin/env python3 """Create a complete evaluation recipe for the published GroundingPI/GroundAnything suite. Requires PyYAML from the release evaluation environment. Does not contact the model service, change the template, overwrite existing recipes, or execute evaluation. """ from __future__ import annotations import argparse from datetime import datetime, timezone import json from pathlib import Path import re import shlex import sys import uuid try: import yaml except ImportError: raise SystemExit('PyYAML is required. Run with the release .venv-eval/bin/python, or install PyYAML.') SUITE_COUNTS = {'groundingpi34': 34, 'groundanything30': 30} def checkout_path(root, value, label): source = Path(value).expanduser() result = (source if source.is_absolute() else root / source).resolve() if not result.is_relative_to(root): raise ValueError(f'{label} must be inside the code checkout: {value}') return result def create_recipe(code_root, template, data_root, suite, output, suites_file): code_root = Path(code_root).expanduser().resolve(strict=True) data_root = Path(data_root).expanduser().resolve(strict=True) if not data_root.is_dir(): raise ValueError(f'Data root is not a directory: {data_root}') template = checkout_path(code_root, template, 'Template') output = checkout_path(code_root, output, 'Output') if output.exists(): raise FileExistsError(f'Refusing to overwrite existing output: {output}') path_config = code_root / 'configs/datasets.local.yaml' if not path_config.is_file(): raise FileNotFoundError(f'Missing {path_config}; run prepare_data.py with --code-root first.') local_paths = yaml.safe_load(path_config.read_text(encoding='utf-8')) if not isinstance(local_paths, dict) or not isinstance(local_paths.get('images'), str): raise ValueError(f'Missing images path in {path_config}; regenerate it with prepare_data.py.') configured_images = Path(local_paths['images']).expanduser() if not configured_images.is_absolute(): configured_images = data_root / configured_images expected_images = (data_root / 'images').resolve() if configured_images.resolve() != expected_images: raise ValueError( f'Data root mismatch: {path_config} maps images to {configured_images.resolve()}, ' f'but --data-root requires {expected_images}. ' 'Use the data root from prepare_data.py or regenerate the local path configuration.' ) registry_file = code_root / 'configs/eval/tasks.json' registry = json.loads(registry_file.read_text(encoding='utf-8')) suites = json.loads(Path(suites_file).read_text(encoding='utf-8')) tasks = suites[suite] if not isinstance(tasks, list) or any(not isinstance(task, str) for task in tasks): raise ValueError(f'Invalid task list for suite: {suite}') if len(tasks) != SUITE_COUNTS[suite] or len(set(tasks)) != len(tasks): raise ValueError(f'{suite} requires exactly {SUITE_COUNTS[suite]} unique tasks') unknown = sorted(set(tasks) - set(registry)) if unknown: raise ValueError(f'Tasks absent from checkout registry: {unknown}') config = yaml.safe_load(template.read_text(encoding='utf-8')) if not isinstance(config, dict): raise ValueError('Evaluation template must contain a YAML mapping') required = {'model_path', 'api_url', 'output_root'} if required - config.keys(): raise ValueError(f'Incomplete evaluation template: missing {sorted(required - config.keys())}') stamp = datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S') + '_' + uuid.uuid4().hex[:10] template_label = re.sub(r'[^a-zA-Z0-9_-]', '_', template.stem) config.update( mode='GAM', tasks=tasks, data_root=str(data_root), datasets='configs/datasets.local.yaml', limit=None, run_id=f'{suite}_{template_label}_{stamp}', ) output.parent.mkdir(parents=True, exist_ok=True) with output.open('x', encoding='utf-8') as handle: handle.write('# Generated from ' + str(template.relative_to(code_root)) + '; model/service settings retained.\n') yaml.safe_dump(config, handle, sort_keys=False, allow_unicode=True) return output, config def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--code-root', type=Path, required=True, help='Published release checkout') parser.add_argument('--template', required=True, help='Template path relative to checkout, e.g. configs/eval/dlm.yaml') parser.add_argument('--data-root', type=Path, required=True, help='Extracted data directory used by prepare_data.py') parser.add_argument('--suite', choices=tuple(SUITE_COUNTS), required=True) parser.add_argument('--output', required=True, help='New recipe path inside checkout, e.g. configs/eval/full_denoise.yaml') args = parser.parse_args(argv) suites_file = Path(__file__).resolve().parents[1] / 'configs/suites.json' output, config = create_recipe(args.code_root, args.template, args.data_root, args.suite, args.output, suites_file) root = args.code_root.expanduser().resolve() relative = str(output.relative_to(root)) print(f'Created {output}') print(f'Selected {len(config["tasks"])} tasks; run_id={config["run_id"]}') print('Review the model path, API URL/model ID, and service contract against your running service.') print('From the checkout directory, validate local inputs:') print(' .venv-eval/bin/python scripts/evaluate.py ' + shlex.quote(relative) + ' --dry-run') print('After validation, start evaluation:') print(' python3 run.py eval --config ' + shlex.quote(relative)) return 0 if __name__ == '__main__': try: raise SystemExit(main()) except (OSError, ValueError, KeyError, yaml.YAMLError) as exc: print(f'ERROR: {exc}', file=sys.stderr) raise SystemExit(2)