File size: 12,919 Bytes
772e34b | 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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 | #!/usr/bin/env python3
"""Verify and unpack Grounding-EvalData, then write local release path configs.
Python 3.9+ standard library only. No downloads, inference, or uploads are made.
"""
from __future__ import annotations
import argparse
import glob
import hashlib
import json
import os
from pathlib import Path, PurePosixPath, PureWindowsPath
import re
import shutil
import sys
import tarfile
import tempfile
DATA_PATHS = {
'images': 'images',
'screenspot_pro': 'ScreenSpot-Pro',
'screenspot_v2': 'ScreenSpot-v2',
'osworld_g': 'OSWorld-G',
'refspatial': 'RefSpatial-Bench',
'refcoco': 'RefCOCO',
'refcocoplus': 'RefCOCOplus',
'refcocog': 'RefCOCOg',
'gam_robospatial_context': 'RoboSpatial-Home/data/context-00000-of-00001.parquet',
'gam_osworld_g': 'OSWorld-G/OSWorld-G.json',
'gam_screenspot_pro': 'ScreenSpot-Pro/annotations/*.json',
'gam_screenspot_v2_1': 'ScreenSpot-v2/screenspot_desktop_v2.json',
'gam_screenspot_v2_2': 'ScreenSpot-v2/screenspot_mobile_v2.json',
'gam_screenspot_v2_3': 'ScreenSpot-v2/screenspot_web_v2.json',
}
ANNOTATIONS = {
'gam_coco': 'box_eval/COCO.jsonl',
'gam_lvis': 'box_eval/LVIS.jsonl',
'gam_refcocog_test': 'box_eval/RefCOCOg_test.jsonl',
'gam_refcocog_val': 'box_eval/RefCOCOg_val.jsonl',
'gam_humanref': 'box_eval/HumanRef.jsonl',
'gam_m6doc': 'box_eval/M6Doc.jsonl',
'gam_doclaynet': 'box_eval/DocLayNet.jsonl',
'gam_hiertext': 'box_eval/HierText.jsonl',
'gam_totaltext': 'box_eval/TotalText.jsonl',
'gam_icdar2015': 'box_eval/IC15.jsonl',
'gam_sroie': 'box_eval/SROIE.jsonl',
'gam_visdrone': 'box_eval/VisDrone.jsonl',
'gam_dense200': 'box_eval/Dense200.jsonl',
'gam_rex_point_coco': 'point_eval/COCO.jsonl',
'gam_rex_point_refcocog_test': 'point_eval/RefCOCOg_test.jsonl',
'gam_rex_point_lvis': 'point_eval/LVIS.jsonl',
'gam_rex_point_visdrone': 'point_eval/VisDrone.jsonl',
'gam_rex_point_dense200': 'point_eval/Dense200.jsonl',
'gam_rex_point_refcocog_val': 'point_eval/RefCOCOg_val.jsonl',
'gam_rex_point_humanref': 'point_eval/HumanRef.jsonl',
'gam_visual_coco': 'visual_prompt_eval/COCO.jsonl',
'gam_visual_lvis': 'visual_prompt_eval/LVIS.jsonl',
'gam_visual_dense200': 'visual_prompt_eval/Dense200.jsonl',
'gam_fsc147': 'visual_prompt_eval/FSCD_test.jsonl',
}
def relative_path(value, allow_dot=False):
if not isinstance(value, str) or not value or '\x00' in value or '\\' in value:
raise ValueError(f'Unsafe relative path: {value!r}')
path = PurePosixPath(value)
if path.is_absolute() or PureWindowsPath(value).drive or '..' in path.parts:
raise ValueError(f'Unsafe relative path: {value!r}')
if str(path) == '.' and not allow_dot:
raise ValueError(f'Empty relative path: {value!r}')
return Path(*path.parts)
def sha256(path):
digest = hashlib.sha256()
with path.open('rb') as handle:
for block in iter(lambda: handle.read(8 * 1024 * 1024), b''):
digest.update(block)
return digest.hexdigest()
def safe_destination(root, relative):
destination = root / relative
for part in (root, *destination.parents, destination):
if part.is_symlink():
raise ValueError(f'Refusing symlink destination: {part}')
if not destination.resolve().is_relative_to(root.resolve()):
raise ValueError(f'Path escapes output root: {relative}')
return destination
def verify_bundle(repo, manifest):
"""Verify every checksum entry and require checksums for loose evaluation data."""
checksums = {}
checksum_path = repo / 'SHA256SUMS'
if not checksum_path.is_file():
raise FileNotFoundError(f'Missing checksum inventory: {checksum_path}')
for number, line in enumerate(checksum_path.read_text(encoding='utf-8').splitlines(), 1):
if not line.strip():
continue
match = re.fullmatch(r'([0-9a-fA-F]{64}) [ *](.+)', line)
if not match:
raise ValueError(f'Malformed SHA256SUMS line {number}')
name = relative_path(match.group(2)).as_posix()
if name in checksums:
raise ValueError(f'Duplicate checksum entry: {name}')
checksums[name] = match.group(1).lower()
archives = manifest.get('archives')
if not isinstance(archives, list) or not archives:
raise ValueError('package_manifest.json must contain a nonempty archives list')
archive_names = set()
missing = []
for item in archives:
name = relative_path(item['path']).as_posix()
if name in archive_names:
raise ValueError(f'Duplicate archive manifest entry: {name}')
archive_names.add(name)
relative_path(item.get('extract_to', '.'), allow_dot=True)
digest = item.get('sha256', '').lower()
if not re.fullmatch(r'[0-9a-f]{64}', digest):
raise ValueError(f'Missing or invalid archive SHA256: {name}')
if name not in checksums or checksums[name] != digest:
raise ValueError(f'Archive checksum absent or inconsistent: {name}')
source = repo / name
if not source.is_file():
missing.append(f"{name}; tasks={item.get('tasks', [])}; source={item.get('source_url', '')}")
elif item.get('bytes') is not None and source.stat().st_size != item['bytes']:
raise ValueError(f'Archive size mismatch: {name}')
if missing:
raise FileNotFoundError('Missing required archives:\n ' + '\n '.join(missing))
for name in [*(f'_annotations/{name}' for name in ANNOTATIONS.values()),
'support/OCR/Challenge4_Test_Task1_GT.zip']:
if name not in checksums:
raise ValueError(f'Evaluation input is absent from SHA256SUMS: {name}')
for index, (name, expected) in enumerate(checksums.items(), 1):
path = repo / relative_path(name)
if not path.is_file():
raise FileNotFoundError(f'Missing checksummed file: {name}')
if path.is_symlink() or not path.resolve().is_relative_to(repo):
raise ValueError(f'Refusing checksum path outside bundle or symlink: {name}')
if sha256(path) != expected:
raise ValueError(f'SHA256 mismatch: {name}')
if name in archive_names:
print(f'Verified {name} ({index}/{len(checksums)} checksum entries)', flush=True)
print(f'All {len(checksums)} checksums verified.', flush=True)
return archives
def extract_archive(source, root):
"""Extract regular files/directories only; never replace different existing data."""
root.mkdir(parents=True, exist_ok=True)
seen = set()
written = skipped = 0
with tarfile.open(source, mode='r|*') as archive:
for member in archive:
relative = relative_path(member.name, allow_dot=member.isdir())
normalized = str(relative)
if normalized in seen and not member.isdir():
raise ValueError(f'Duplicate archive member: {member.name}')
seen.add(normalized)
if not (member.isdir() or member.isfile()) or member.issym() or member.islnk():
raise ValueError(f'Unsupported archive member type: {member.name}')
destination = safe_destination(root, relative)
if member.isdir():
destination.mkdir(parents=True, exist_ok=True)
continue
destination.parent.mkdir(parents=True, exist_ok=True)
if destination.exists() and not destination.is_file():
raise ValueError(f'Existing path is not a regular file: {destination}')
content = archive.extractfile(member)
if content is None:
raise ValueError(f'Cannot read archive member: {member.name}')
fd, temporary_name = tempfile.mkstemp(prefix='.grounding-extract-', dir=destination.parent)
temporary = Path(temporary_name)
try:
with os.fdopen(fd, 'wb') as output, content:
shutil.copyfileobj(content, output, length=1024 * 1024)
if temporary.stat().st_size != member.size:
raise ValueError(f'Truncated archive member: {member.name}')
if destination.exists():
if destination.stat().st_size != member.size or sha256(destination) != sha256(temporary):
raise FileExistsError(f'Refusing to replace different existing file: {destination}')
skipped += 1
else:
temporary.chmod(0o644)
os.replace(temporary, destination)
written += 1
finally:
temporary.unlink(missing_ok=True)
return written, skipped
def make_data_paths(repo, data_root):
paths = {key: str(data_root / value) for key, value in DATA_PATHS.items()}
paths.update({key: str(repo / '_annotations' / value) for key, value in ANNOTATIONS.items()})
paths['icdar2015_dontcare'] = str(repo / 'support/OCR/Challenge4_Test_Task1_GT.zip')
return paths
def write_config(path, paths):
text = '# Generated by Grounding-EvalData prepare_data.py; paths refer to this machine.\n'
text += '\n'.join(f'{key}: {json.dumps(value, ensure_ascii=False)}' for key, value in paths.items()) + '\n'
if path.is_symlink():
raise ValueError(f'Refusing symlink config: {path}')
if path.exists():
if path.read_text(encoding='utf-8') != text:
raise FileExistsError(f'Existing config differs; preserve or rename it first: {path}')
else:
with path.open('x', encoding='utf-8') as handle:
handle.write(text)
print(f'Path configuration: {path}', flush=True)
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--archives-dir', type=Path, default=Path(__file__).resolve().parents[1],
help='HF repository root containing package_manifest.json and SHA256SUMS')
parser.add_argument('--data-root', type=Path, help='Directory for extracted evaluation data')
parser.add_argument('--code-root', action='append', type=Path, default=[],
help='GroundAnything or GroundingPI checkout; repeat for both releases')
parser.add_argument('--verify-only', action='store_true', help='Verify all package hashes without extraction')
args = parser.parse_args(argv)
if not args.verify_only and args.data_root is None:
parser.error('--data-root is required unless --verify-only is selected')
repo = args.archives_dir.expanduser().resolve(strict=True)
manifest = json.loads((repo / 'package_manifest.json').read_text(encoding='utf-8'))
archives = verify_bundle(repo, manifest)
if args.verify_only:
return 0
data_root = args.data_root.expanduser().resolve()
code_roots = [path.expanduser().resolve(strict=True) for path in args.code_root]
for code_root in code_roots:
if not (code_root / 'configs/datasets.yaml').is_file() or not (code_root / 'scripts/evaluate.py').is_file():
raise ValueError(f'Not a supported release checkout: {code_root}')
data_root.mkdir(parents=True, exist_ok=True)
for item in archives:
destination = safe_destination(data_root, relative_path(item.get('extract_to', '.'), allow_dot=True))
print(f'Extracting {item["path"]} -> {destination}', flush=True)
written, skipped = extract_archive(repo / relative_path(item['path']), destination)
print(f' {written} files written, {skipped} identical files reused', flush=True)
paths = make_data_paths(repo, data_root)
missing = [f'{key}: {value}' for key, value in paths.items() if not glob.glob(value)]
if missing:
raise FileNotFoundError('Unpacked data does not satisfy release paths:\n ' + '\n '.join(missing))
outputs = [root / 'configs/datasets.local.yaml' for root in code_roots]
if not outputs:
outputs = [data_root / 'datasets.local.yaml']
for output in outputs:
write_config(output, paths)
print('\nIn each full-suite evaluation YAML, set:')
print(' data_root: ' + json.dumps(str(data_root)))
print(' datasets: ' + ('configs/datasets.local.yaml' if code_roots else json.dumps(str(outputs[0]))))
print(' mode: GAM')
print(' limit: null')
print('Keep model/service settings from the corresponding release and select its documented 30 or 34 tasks.')
print('Then run: .venv-eval/bin/python scripts/evaluate.py <your-full-suite.yaml> --dry-run')
print('Path checks passed; this does not execute model inference or establish evaluation scores.')
return 0
if __name__ == '__main__':
try:
raise SystemExit(main())
except (OSError, ValueError, KeyError, tarfile.TarError) as exc:
print(f'ERROR: {exc}', file=sys.stderr)
raise SystemExit(2)
|