Datasets:
Stage scaling-v1 verified data; training defaults unchanged
Browse files
scaling_v1/loader/small/media-manifest.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
scaling_v1/loader/tools/input_sequences.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Source-evidenced input semantics; container type is not temporal semantics.
|
| 2 |
+
|
| 3 |
+
Frame groups refer to the rendered RGB image list (mask assets are not frames).
|
| 4 |
+
Never invent fps/timestamps. Unknown multi-image provenance stays unknown.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def spacevista_sequence_contract(raw, media):
|
| 10 |
+
paths = [m["path"] for m in sorted(media, key=lambda m: m["order"]) if m["media_type"] == "image"]
|
| 11 |
+
if len(paths) != len(set(paths)):
|
| 12 |
+
raise ValueError("Canonical RGB media paths must be unique for SpaceVista")
|
| 13 |
+
lookup = {path: i for i, path in enumerate(paths)}
|
| 14 |
+
groups = []
|
| 15 |
+
for sequence in raw.get("videos") or []:
|
| 16 |
+
if not sequence:
|
| 17 |
+
continue
|
| 18 |
+
try:
|
| 19 |
+
groups.append([lookup[str(path)] for path in sequence])
|
| 20 |
+
except KeyError as error:
|
| 21 |
+
raise ValueError("Source frame missing from canonical media") from error
|
| 22 |
+
# SpaceVista's imported single-/multi-view examples also use `videos`.
|
| 23 |
+
# Only verified capture-path families are promoted to video frame sequences.
|
| 24 |
+
temporal_groups = []
|
| 25 |
+
for group in groups:
|
| 26 |
+
selected = [paths[i] for i in group]
|
| 27 |
+
certified = all(path.startswith(("uco3d_frames/", "wildrgbd_frames/", "DL3DV_frames/",
|
| 28 |
+
"SpaceR_frames/")) or "/video_color/" in path for path in selected)
|
| 29 |
+
if len(group) > 1 and certified:
|
| 30 |
+
temporal_groups.append(group)
|
| 31 |
+
if temporal_groups and len(temporal_groups) == len(groups):
|
| 32 |
+
semantic = "video_frame_sequence" if len(groups) == 1 else "multiple_video_frame_sequences"
|
| 33 |
+
evidence = "original_videos_groups_and_capture_path_family"
|
| 34 |
+
elif len(paths) == 1:
|
| 35 |
+
semantic, evidence = "single_image", "one_rgb_input"
|
| 36 |
+
else:
|
| 37 |
+
semantic, evidence = "multi_image_unresolved", "source_groups_preserved_temporal_provenance_unverified"
|
| 38 |
+
return {"semantic_modality": semantic, "frame_groups": groups,
|
| 39 |
+
"video_frame_groups": temporal_groups, "modality_evidence": evidence,
|
| 40 |
+
"timing_available": False, "source_sequence_count": len(groups),
|
| 41 |
+
"original_frame_occurrences": sum(map(len, groups))}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def input_contract(row, spacevista_contract=None):
|
| 45 |
+
media = sorted(row["media"], key=lambda m: m["order"])
|
| 46 |
+
images = [m for m in media if m["media_type"] == "image"]
|
| 47 |
+
if any(m["media_type"] == "video" for m in media):
|
| 48 |
+
return {"semantic_modality": "video_file", "frame_groups": [], "video_frame_groups": [],
|
| 49 |
+
"modality_evidence": "video_container", "timing_available": True}
|
| 50 |
+
if row["source"] == "spacevista":
|
| 51 |
+
if spacevista_contract is None:
|
| 52 |
+
raise ValueError("SpaceVista requires its original sequence contract")
|
| 53 |
+
return dict(spacevista_contract)
|
| 54 |
+
if row["source"] == "cavqa" and len(images) > 1:
|
| 55 |
+
group = list(range(len(images)))
|
| 56 |
+
return {"semantic_modality": "video_frame_sequence", "frame_groups": [group],
|
| 57 |
+
"video_frame_groups": [group], "modality_evidence": "cavqa_support_frames_reference_last",
|
| 58 |
+
"timing_available": False, "reference_image_index": len(images) - 1}
|
| 59 |
+
return {"semantic_modality": "single_image" if len(images) == 1 else "multi_image_unresolved",
|
| 60 |
+
"frame_groups": [list(range(len(images)))], "video_frame_groups": [],
|
| 61 |
+
"modality_evidence": "one_rgb_input" if len(images) == 1 else "no_temporal_provenance",
|
| 62 |
+
"timing_available": False}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def grouped_video_frames(images, contract):
|
| 66 |
+
result = []
|
| 67 |
+
for group in contract["video_frame_groups"]:
|
| 68 |
+
if any(not isinstance(i, int) or i < 0 or i >= len(images) for i in group):
|
| 69 |
+
raise ValueError("Frame group index outside rendered images")
|
| 70 |
+
result.append([images[i] for i in group])
|
| 71 |
+
return result
|
scaling_v1/loader/tools/load_stage3_data.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Load Stage-3 Small locally or from HF, preserving visual grounding.
|
| 3 |
+
|
| 4 |
+
Example:
|
| 5 |
+
python load_stage3_small.py --split train --limit 8 --cache /scratch/my-small
|
| 6 |
+
Requires huggingface_hub, pyarrow, requests, pillow, numpy; av for video smoke.
|
| 7 |
+
Place small_training.py and input_sequences.py beside this script when using
|
| 8 |
+
the HF tools directory. Video frame sequences preserve source order without
|
| 9 |
+
inventing timestamps; consume visual_inputs rather than duplicating images.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import hashlib
|
| 15 |
+
import io
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import time
|
| 19 |
+
import threading
|
| 20 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import pyarrow.parquet as pq
|
| 24 |
+
import requests
|
| 25 |
+
from huggingface_hub import HfApi, hf_hub_download, hf_hub_url
|
| 26 |
+
try:
|
| 27 |
+
from stage3_measurement.small_training import render_images
|
| 28 |
+
from stage3_measurement.input_sequences import input_contract, grouped_video_frames
|
| 29 |
+
except ImportError:
|
| 30 |
+
from small_training import render_images
|
| 31 |
+
from input_sequences import input_contract, grouped_video_frames
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class SmallDataset:
|
| 35 |
+
def __init__(self, cache, revision=None, release_dir=None, local_media_root=None,
|
| 36 |
+
max_cache_gib=80, repo='AnchorSR/TrainingData_Stage3', config='small', metadata_prefix=''):
|
| 37 |
+
if config not in ('small','large'):
|
| 38 |
+
raise ValueError('config must be small or large')
|
| 39 |
+
self.config=config
|
| 40 |
+
self.metadata_prefix=metadata_prefix.strip('/')+'/' if metadata_prefix else ''
|
| 41 |
+
self.repo=repo
|
| 42 |
+
self.cache=Path(cache)
|
| 43 |
+
self.cache.mkdir(parents=True,exist_ok=True)
|
| 44 |
+
self.release_dir=Path(release_dir) if release_dir else None
|
| 45 |
+
self.local_media_root=Path(local_media_root) if local_media_root else None
|
| 46 |
+
self.revision=revision or (None if release_dir else HfApi().dataset_info(repo).sha)
|
| 47 |
+
self.max_cache_bytes=int(max_cache_gib*1024**3)
|
| 48 |
+
self.sessions=threading.local()
|
| 49 |
+
self.account_lock=threading.Lock()
|
| 50 |
+
manifest=json.loads(self.file(f'{self.metadata_prefix}{config}/media-manifest.json').read_text())
|
| 51 |
+
self.sequence_contracts={}
|
| 52 |
+
self.sequence_contract_required=manifest.get('sequence_contract_required',False)
|
| 53 |
+
if manifest.get('sequence_contract_path'):
|
| 54 |
+
for batch in pq.ParquetFile(self.file(manifest['sequence_contract_path'])).iter_batches():
|
| 55 |
+
for item in batch.to_pylist():
|
| 56 |
+
self.sequence_contracts[item['source_record_id']]=json.loads(item['sequence_contract_json'])
|
| 57 |
+
self.split_paths=manifest.get('split_paths',{s:f'{config}/{s}/' for s in ('train','validation','test')})
|
| 58 |
+
self.media_revision=manifest['input_revision']
|
| 59 |
+
self.index={}
|
| 60 |
+
for batch in pq.ParquetFile(self.file(f'{self.metadata_prefix}{config}/asset-index.parquet')).iter_batches():
|
| 61 |
+
for row in batch.to_pylist():
|
| 62 |
+
self.index[(row['source'],row['media_path'])]=row
|
| 63 |
+
self.assets_dir=self.cache/'assets'
|
| 64 |
+
self.assets_dir.mkdir(exist_ok=True)
|
| 65 |
+
self.cache_bytes=sum(p.stat().st_size for p in self.assets_dir.iterdir() if p.is_file())
|
| 66 |
+
|
| 67 |
+
def file(self,relative):
|
| 68 |
+
if self.release_dir:
|
| 69 |
+
return self.release_dir/relative
|
| 70 |
+
return Path(hf_hub_download(self.repo,relative,repo_type='dataset',revision=self.revision,
|
| 71 |
+
local_dir=self.cache/'metadata'))
|
| 72 |
+
|
| 73 |
+
def rows(self,split='train'):
|
| 74 |
+
prefix=self.split_paths[split]
|
| 75 |
+
if self.release_dir:
|
| 76 |
+
paths=sorted(str(p.relative_to(self.release_dir)) for p in (self.release_dir/prefix).glob('*.parquet'))
|
| 77 |
+
else:
|
| 78 |
+
paths=sorted(p for p in HfApi().list_repo_files(self.repo,repo_type='dataset',revision=self.revision)
|
| 79 |
+
if p.startswith(prefix) and p.endswith('.parquet'))
|
| 80 |
+
for path in paths:
|
| 81 |
+
for batch in pq.ParquetFile(self.file(path)).iter_batches(batch_size=256):
|
| 82 |
+
yield from batch.to_pylist()
|
| 83 |
+
|
| 84 |
+
def _evict(self,required):
|
| 85 |
+
if required>self.max_cache_bytes:
|
| 86 |
+
raise ValueError('Single asset exceeds configured cache size')
|
| 87 |
+
if self.cache_bytes+required<=self.max_cache_bytes:
|
| 88 |
+
return
|
| 89 |
+
files=sorted((p for p in self.assets_dir.iterdir() if p.is_file() and not p.name.endswith('.tmp')),
|
| 90 |
+
key=lambda p:p.stat().st_mtime)
|
| 91 |
+
for p in files:
|
| 92 |
+
size=p.stat().st_size
|
| 93 |
+
p.unlink();self.cache_bytes-=size
|
| 94 |
+
if self.cache_bytes+required<=self.max_cache_bytes:
|
| 95 |
+
return
|
| 96 |
+
|
| 97 |
+
def asset_path(self,source,path):
|
| 98 |
+
if not hasattr(self.sessions,'http'):
|
| 99 |
+
self.sessions.http=requests.Session()
|
| 100 |
+
asset=self.index[(source,path)]
|
| 101 |
+
name=hashlib.sha256((self.media_revision+source+path).encode()).hexdigest()+Path(path).suffix
|
| 102 |
+
target=self.assets_dir/name
|
| 103 |
+
if target.exists() and target.stat().st_size==asset['size']:
|
| 104 |
+
os.utime(target,None)
|
| 105 |
+
return target
|
| 106 |
+
self._evict(asset['size'])
|
| 107 |
+
tmp=target.with_suffix(target.suffix+'.tmp')
|
| 108 |
+
start=asset['offset'];end=start+asset['size']-1
|
| 109 |
+
local=self.local_media_root/asset['tar_path'] if self.local_media_root else None
|
| 110 |
+
for attempt in range(5):
|
| 111 |
+
try:
|
| 112 |
+
digest=hashlib.sha256()
|
| 113 |
+
with tmp.open('wb') as out:
|
| 114 |
+
if local and local.exists():
|
| 115 |
+
with local.open('rb') as handle:
|
| 116 |
+
handle.seek(start);remaining=asset['size']
|
| 117 |
+
while remaining:
|
| 118 |
+
chunk=handle.read(min(4*1024**2,remaining))
|
| 119 |
+
if not chunk: raise IOError('Short local TAR read')
|
| 120 |
+
out.write(chunk);digest.update(chunk);remaining-=len(chunk)
|
| 121 |
+
else:
|
| 122 |
+
url=hf_hub_url(self.repo,asset['tar_path'],repo_type='dataset',revision=self.media_revision)
|
| 123 |
+
with self.sessions.http.get(url,headers={'Range':f'bytes={start}-{end}'},stream=True,timeout=(30,120)) as response:
|
| 124 |
+
response.raise_for_status()
|
| 125 |
+
if response.status_code!=206 or not response.headers.get('Content-Range','').startswith(f'bytes {start}-{end}/'):
|
| 126 |
+
raise IOError('Server did not honor exact byte range; refusing full TAR download')
|
| 127 |
+
for chunk in response.iter_content(4*1024**2):
|
| 128 |
+
out.write(chunk);digest.update(chunk)
|
| 129 |
+
if tmp.stat().st_size!=asset['size']:
|
| 130 |
+
raise IOError('Asset length mismatch')
|
| 131 |
+
if asset.get('sha256') and digest.hexdigest()!=asset['sha256']:
|
| 132 |
+
raise IOError('Asset checksum mismatch')
|
| 133 |
+
tmp.replace(target)
|
| 134 |
+
with self.account_lock:self.cache_bytes+=asset['size']
|
| 135 |
+
return target
|
| 136 |
+
except Exception:
|
| 137 |
+
tmp.unlink(missing_ok=True)
|
| 138 |
+
if attempt==4: raise
|
| 139 |
+
time.sleep(2**attempt)
|
| 140 |
+
|
| 141 |
+
def read_asset(self,source,path):
|
| 142 |
+
return self.asset_path(source,path).read_bytes()
|
| 143 |
+
|
| 144 |
+
def prefetch(self,row,workers=4):
|
| 145 |
+
# One row at a time; reserve enough free cache before parallel downloads.
|
| 146 |
+
# A separate HTTP session is maintained per worker thread.
|
| 147 |
+
keys=list(dict.fromkeys((row['source'],m['path']) for m in row['media']))
|
| 148 |
+
required=sum(self.index[k]['size'] for k in keys)
|
| 149 |
+
if required>self.max_cache_bytes:
|
| 150 |
+
raise ValueError('This sample exceeds the media cache budget; increase max_cache_gib')
|
| 151 |
+
missing=[]
|
| 152 |
+
for source,path in keys:
|
| 153 |
+
name=hashlib.sha256((self.media_revision+source+path).encode()).hexdigest()+Path(path).suffix
|
| 154 |
+
target=self.assets_dir/name
|
| 155 |
+
if target.exists() and target.stat().st_size==self.index[(source,path)]['size']:
|
| 156 |
+
os.utime(target,None)
|
| 157 |
+
else:missing.append((source,path))
|
| 158 |
+
self._evict(sum(self.index[k]['size'] for k in missing))
|
| 159 |
+
with ThreadPoolExecutor(max_workers=workers) as pool:
|
| 160 |
+
list(pool.map(lambda k:self.asset_path(*k),missing))
|
| 161 |
+
|
| 162 |
+
def sample(self,row):
|
| 163 |
+
self.prefetch(row)
|
| 164 |
+
images=render_images(row,self.read_asset)
|
| 165 |
+
videos=[str(self.asset_path(row['source'],m['path'])) for m in row['media'] if m['media_type']=='video']
|
| 166 |
+
contract=self.sequence_contracts.get(row.get('source_record_id')) if row['source']=='spacevista' else None
|
| 167 |
+
if row['source']=='spacevista' and contract is None and not self.sequence_contract_required:
|
| 168 |
+
# Old release has no source grouping index. Do not infer a video
|
| 169 |
+
# solely from several image files; legacy images remain usable.
|
| 170 |
+
contract={'semantic_modality':'single_image' if len(images)==1 else 'multi_image_unresolved',
|
| 171 |
+
'frame_groups':[list(range(len(images)))], 'video_frame_groups':[],
|
| 172 |
+
'modality_evidence':'legacy_release_without_sequence_index','timing_available':False}
|
| 173 |
+
contract=input_contract(row,contract)
|
| 174 |
+
groups=grouped_video_frames(images,contract)
|
| 175 |
+
grouped_indices={i for group in contract['video_frame_groups'] for i in group}
|
| 176 |
+
# A processor adapter should consume visual_inputs, OR the legacy
|
| 177 |
+
# images/videos pair, never both (otherwise frames are duplicated).
|
| 178 |
+
visual_inputs={'images':[im for i,im in enumerate(images) if i not in grouped_indices],
|
| 179 |
+
'video_frame_sequences':groups,'video_files':videos,
|
| 180 |
+
'sequence_timestamps_sec':None}
|
| 181 |
+
return {'sample_id':row['sample_id'],'question':row['training_question'],
|
| 182 |
+
'answer':row['training_answer'],'images':images,'videos':videos,
|
| 183 |
+
'task_type':row['task_type'],'source':row['source'],
|
| 184 |
+
'input_contract':contract,'visual_inputs':visual_inputs}
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
Stage3Dataset=SmallDataset
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def main():
|
| 191 |
+
p=argparse.ArgumentParser(description=__doc__)
|
| 192 |
+
p.add_argument('--cache',required=True)
|
| 193 |
+
p.add_argument('--revision')
|
| 194 |
+
p.add_argument('--release-dir')
|
| 195 |
+
p.add_argument('--local-media-root')
|
| 196 |
+
p.add_argument('--metadata-prefix',default='',help='Release-candidate metadata path; leave empty for published Small/Large')
|
| 197 |
+
p.add_argument('--split',choices=['train','validation','test','video_validation','video_test'],default='train')
|
| 198 |
+
p.add_argument('--config',choices=['small','large'],default='small')
|
| 199 |
+
p.add_argument('--limit',type=int,default=8)
|
| 200 |
+
p.add_argument('--max-cache-gib',type=float,default=80)
|
| 201 |
+
args=p.parse_args()
|
| 202 |
+
ds=SmallDataset(args.cache,args.revision,args.release_dir,args.local_media_root,args.max_cache_gib,config=args.config,metadata_prefix=args.metadata_prefix)
|
| 203 |
+
for i,row in enumerate(ds.rows(args.split)):
|
| 204 |
+
if i>=args.limit: break
|
| 205 |
+
sample=ds.sample(row)
|
| 206 |
+
print(json.dumps({k:v for k,v in sample.items() if k not in ('images','visual_inputs')},ensure_ascii=False))
|
| 207 |
+
print('image sizes:',[im.size for im in sample['images']])
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
if __name__=='__main__':
|
| 211 |
+
main()
|
scaling_v1/loader/tools/small_training.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Standalone helpers for Stage-3 Small: answer targets and visual grounding.
|
| 2 |
+
|
| 3 |
+
No model-generated labels are used. Images stay at their original resolution;
|
| 4 |
+
the training model's own processor is responsible for resize/token budgets.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import io
|
| 9 |
+
import json
|
| 10 |
+
import math
|
| 11 |
+
import re
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def prepare_record(row):
|
| 15 |
+
row = dict(row)
|
| 16 |
+
question = re.sub(r'<(?:image|video)>\s*', '', row['question']).strip()
|
| 17 |
+
original_target = row['target_answer']
|
| 18 |
+
row['upstream_target_answer'] = original_target
|
| 19 |
+
row['upstream_original_unit'] = row['original_unit']
|
| 20 |
+
corrections = []
|
| 21 |
+
scalar = row.get('original_value')
|
| 22 |
+
unit = row.get('original_unit')
|
| 23 |
+
dimension = row['measurement_dimension']
|
| 24 |
+
if dimension == 'angle' and scalar is not None:
|
| 25 |
+
# The released angular task families in these sources use degrees.
|
| 26 |
+
if unit != 'deg':
|
| 27 |
+
corrections.append('angular_unit_restored_to_degrees')
|
| 28 |
+
unit = row['original_unit'] = 'deg'
|
| 29 |
+
row['canonical_unit'] = 'rad'
|
| 30 |
+
row['canonical_value_si'] = float(scalar) * math.pi / 180
|
| 31 |
+
if not re.search(r'degrees?|radians?|°',question,re.I):
|
| 32 |
+
question += '\nReport the angle in degrees.'
|
| 33 |
+
if scalar is not None and dimension != 'compound':
|
| 34 |
+
if not math.isfinite(scalar) or not unit:
|
| 35 |
+
raise ValueError(f"Invalid scalar target: {row['sample_id']}")
|
| 36 |
+
number_only = re.search(r'(?i)(?:single|one|a) number only|only (?:a |one )?number|without units?|no units|only (?:the )?numerical value',question)
|
| 37 |
+
answer = f'{scalar:.10g}' if number_only else f'{scalar:.10g} {unit}'
|
| 38 |
+
else:
|
| 39 |
+
answer = row['raw_answer'].strip()
|
| 40 |
+
if re.search(r'<answer>\s*</answer>|between the <answer>|between <answer>',question,re.I):
|
| 41 |
+
answer = '<answer>' + answer + '</answer>'
|
| 42 |
+
annotations = json.loads(row['spatial_annotations']) if row.get('spatial_annotations') else {}
|
| 43 |
+
if annotations.get('2dbox') and 'red' not in question.lower():
|
| 44 |
+
question += '\nThe red bounding box identifies the target object.'
|
| 45 |
+
if answer != original_target:
|
| 46 |
+
corrections.append('answer_target_normalized')
|
| 47 |
+
row['training_question'] = question
|
| 48 |
+
row['training_answer'] = answer
|
| 49 |
+
row['target_answer'] = answer
|
| 50 |
+
row['small_corrections'] = corrections
|
| 51 |
+
return row
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def render_images(row, read_asset):
|
| 55 |
+
"""Read RGB frames in source order and draw released boxes/points/masks.
|
| 56 |
+
|
| 57 |
+
read_asset(source, logical_path) must return file bytes. A video container
|
| 58 |
+
is returned separately by the loader, and decoded by the model processor.
|
| 59 |
+
"""
|
| 60 |
+
import numpy as np
|
| 61 |
+
from PIL import Image, ImageDraw
|
| 62 |
+
source = row['source']
|
| 63 |
+
items = sorted((m for m in row['media'] if m['media_type']=='image'),key=lambda m:m['order'])
|
| 64 |
+
images = [Image.open(io.BytesIO(read_asset(source,m['path']))).convert('RGB') for m in items]
|
| 65 |
+
a = json.loads(row['spatial_annotations']) if row.get('spatial_annotations') else {}
|
| 66 |
+
palette=[(255,0,0),(0,128,255),(0,255,0),(255,215,0)]
|
| 67 |
+
def point_coords(coords, image):
|
| 68 |
+
if a.get('coord_type') == 'normalized_1000':
|
| 69 |
+
return [v*(image.width if i%2==0 else image.height)/1000 for i,v in enumerate(coords)]
|
| 70 |
+
if a.get('coord_type') in ('normalized','relative','norm'):
|
| 71 |
+
return [v*(image.width if i%2==0 else image.height) for i,v in enumerate(coords)]
|
| 72 |
+
return coords
|
| 73 |
+
boxes = list(a.get('bboxes') or [])
|
| 74 |
+
if a.get('2dbox'):
|
| 75 |
+
boxes.append({'image_index':0,'coords':a['2dbox'],'color':'red'})
|
| 76 |
+
dual = a.get('dual_bbox')
|
| 77 |
+
if dual:
|
| 78 |
+
if isinstance(dual,list):
|
| 79 |
+
boxes.extend(dual)
|
| 80 |
+
else:
|
| 81 |
+
raise ValueError('Unsupported dual_bbox format; refuse ungrounded input')
|
| 82 |
+
for ordinal,b in enumerate(boxes):
|
| 83 |
+
index = int(b.get('image_index',0))
|
| 84 |
+
image = images[index]
|
| 85 |
+
xy = point_coords(b['coords'],image)
|
| 86 |
+
if len(xy)!=4:
|
| 87 |
+
raise ValueError('Invalid bbox')
|
| 88 |
+
xy=[min(xy[0],xy[2]),min(xy[1],xy[3]),max(xy[0],xy[2]),max(xy[1],xy[3])]
|
| 89 |
+
ImageDraw.Draw(image).rectangle(xy,outline=b.get('color') or palette[ordinal%4],width=max(2,round(max(image.size)/300)))
|
| 90 |
+
for ordinal,p in enumerate(a.get('points') or []):
|
| 91 |
+
image=images[int(p.get('image_index',0))]
|
| 92 |
+
coords=p['coords']
|
| 93 |
+
if len(coords)==1:coords=coords[0]
|
| 94 |
+
# SpaceVista's pinned official renderer explicitly interprets points
|
| 95 |
+
# as [y,x], despite the abbreviated README schema saying [x,y].
|
| 96 |
+
if source=='spacevista':coords=[coords[1],coords[0]]
|
| 97 |
+
x,y=point_coords(coords,image)
|
| 98 |
+
radius=max(3,round(max(image.size)/150))
|
| 99 |
+
ImageDraw.Draw(image).ellipse((x-radius,y-radius,x+radius,y+radius),fill=p.get('color') or palette[ordinal%4])
|
| 100 |
+
mask_ordinal=0
|
| 101 |
+
for mask in a.get('masks') or []:
|
| 102 |
+
index=next(i for i,m in enumerate(items) if m['path']==mask['image_path'])
|
| 103 |
+
labels=np.load(io.BytesIO(read_asset(source,mask['mask_path'])),allow_pickle=False)
|
| 104 |
+
labels=np.squeeze(labels)
|
| 105 |
+
if labels.ndim not in (2,3):
|
| 106 |
+
raise ValueError(f'Unsupported mask shape {labels.shape}')
|
| 107 |
+
ids=mask.get('object_ids')
|
| 108 |
+
if labels.ndim==3 and labels.shape[0]<16 and labels.shape[0]!=labels.shape[1]:
|
| 109 |
+
labels=np.moveaxis(labels,0,2)
|
| 110 |
+
if ids is None:ids=[None]
|
| 111 |
+
for object_id in ids:
|
| 112 |
+
if labels.ndim==2:
|
| 113 |
+
selected=labels!=0 if object_id is None or labels.dtype==bool else labels==int(object_id)
|
| 114 |
+
else:
|
| 115 |
+
selected=(labels!=0).any(axis=2) if object_id is None else labels[:,:,int(object_id)]!=0
|
| 116 |
+
alpha=Image.fromarray((selected.astype('uint8')*100),mode='L').resize(images[index].size,Image.Resampling.NEAREST)
|
| 117 |
+
tint=Image.new('RGB',images[index].size,palette[mask_ordinal%4])
|
| 118 |
+
images[index]=Image.composite(tint,images[index],alpha)
|
| 119 |
+
mask_ordinal+=1
|
| 120 |
+
return images
|