shaoyz commited on
Commit
78c1fdd
·
verified ·
1 Parent(s): 85c3bfc

HOT3D approved raw v1.0 batch 1

Browse files
HOT3D/raw/data/Aria/P0001_10a27bf7/Hot3DAria_v4.0.0_P0001_10a27bf7_ground_truth.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ffcb990b1cd6f89c24bf3a93c0d707be2eb78bd581b561bab7694f909ee9dfd
3
+ size 4770860
HOT3D/raw/data/Aria/P0001_10a27bf7/Hot3DAria_v4.0.0_P0001_10a27bf7_hand_data.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:45378e89461f6b5ec2cbf80d22a4e12abbfc570e29850cd23c10c5b1827f0fd1
3
+ size 6957367
HOT3D/raw/doc/PUBLICATION.md ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # HOT3D publication layout
2
+
3
+ [Standardized data](https://huggingface.co/datasets/ParityLab/Hand-Datasets-Raw/tree/main/HOT3D/shared-v1.0)
4
+
5
+ [Original archives](https://huggingface.co/datasets/ParityLab/Hand-Datasets-Raw/tree/main/HOT3D/raw)
6
+
7
+ Local raw archives are retained. Temporary files and runtime logs are excluded.
8
+ Upload completion is recorded separately after all files match fixed remote commits.
HOT3D/raw/doc/SOURCES.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HOT3D Aria 原始数据盘点与全新下载
2
+
3
+ 2026-09-18。用户确认仅处理 Aria,不下载 Quest;与 ARCTIC 并行,最多两个活动数据集。最新要求为从头下载,不复用已有数据;官方 ZIP 保持 ZIP,不展开,VRS 原样保留。此前提出的展开目录方案已撤销,未对本轮 raw 执行解压。
4
+
5
+ 本机旧目录 `F:/_research/dataset/dreamhand/datasets/HOT3D` 有 198 个序列。旧下载器明确筛选 RGB `214-1`,现存 VRS 合计 238.35 GB;官方 Aria 原始 VRS 清单合计 329.36 GB。现存媒体是派生子集,不能把它们改名后当作完整原始 VRS。
6
+
7
+ | 信息 | 本机旧目录现状 | 本次补齐方式 |
8
+ |---|---|---|
9
+ | 相机图像 | 198 份筛选后 RGB VRS;未保留两路灰度流 | 下载全部 198 份官方 main_vrs,保留原字节和所有流 |
10
+ | 手 MANO | 198 个序列有对应 JSONL 文件;是否缺帧仍需试点核验 | 下载原 hand_data ZIP,同时原样保留包内其他字段 |
11
+ | 相机模型、头显轨迹、同步 | 198 个序列有选取的文件 | 保留完整 ground_truth、MPS 标定、MPS 轨迹与 summary ZIP |
12
+ | 物体轨迹 dynamic_objects | 旧目录中 0 个对应文件 | 从完整 ground_truth 原包补齐,按官方标注可用性处理 |
13
+ | 手/物体 2D 框及可见性 | 旧目录中 0 个 box2d_hands/objects 文件 | 从 ground_truth 原包补齐 |
14
+ | 帧有效性、QA 等 masks CSV | 旧目录中 0 个 mask_hand_visible 文件 | 保留 ground_truth 包内全部 masks;这些是逐帧标志,不是像素分割图 |
15
+ | 物体几何、纹理与材质 | 试点有官方 hot3d_models.zip | 全新下载原 ZIP、官方仓库 object_models 的 33 个 GLB 与 models_info.json |
16
+ | 深度、像素分割 | 当前 Aria 原始下载清单未列出对应模态 | 不虚构为实测深度或现成分割;后续若从模型渲染,应明确是派生结果 |
17
+ | Quest | 本次不处理 | 用户明确排除 |
18
+
19
+ “文件存在/包可下载”不等于每一帧有完整标注。训练/测试与 GT 可用性仍按官方 metadata 和实际轨迹检查,不用 198 个文件推断 198 个完整监督序列。
20
+
21
+ 目标为 `E:/hand-datasets/HOT3D/raw/{data,script,doc}`。临时分片、断点状态、带时效的下载链接及日志均放 `tmp`;不上传日志和下载链接。原包不解压。旧 F 盘数据与前一次 E 盘尝试数据均不复用;本轮重新通过官方下载所有文件,仅允许本次 fresh_download_run 内断点续传。下载使用官方清单的 URL/大小/SHA1,附加计算 SHA256;ZIP 还检查全部成员 CRC。官方普通 Git 小文件核对 blob SHA1。原始包在发布后仍留在本地。
22
+
23
+ 官方默认下载器会解压 ZIP;项目适配器沿用官方清单、文件分组和摘要校验,改为保留压缩包,并增加断点续传、流式写入及 400 GB 空间余量检查。官方脚本固定提交快照保存在 raw/script/official。
24
+
25
+ 当前六类 Aria 包加物体资产的 raw 合计约 336.4 GB。预算同时为 ARCTIC 未完成 raw 预留空间,并额外留出 100 GB 临时/试点预算和 400 GB 空闲。这里只批准下载阶段容量;全量 share 必须在试点后重新计算峰值。
26
+
27
+ 校验通过清单写入 `raw/doc/file_checksums.json`,总体清单为 `raw/doc/download_manifest.json`。下载完成后先进行独立序列试点和本地人工审核;此盘点不代表转换验收通过。
28
+
29
+ 来源:[HOT3D 官方下载说明](https://github.com/facebookresearch/hot3d/blob/146b34afef8c1a32adeef7e981c070109f225c87/README.md)、[官方数据性质说明](https://facebookresearch.github.io/hot3d/)、[官方物体模型](https://huggingface.co/datasets/bop-benchmark/hot3d/tree/30fe9674782f32e1e5edba98476b6ff4300132c5/object_models)。
HOT3D/raw/doc/download_manifest.json ADDED
The diff for this file is too large to render. See raw diff
 
HOT3D/raw/doc/file_checksums.json ADDED
The diff for this file is too large to render. See raw diff
 
HOT3D/raw/doc/official_manifest_metadata.json ADDED
The diff for this file is too large to render. See raw diff
 
HOT3D/raw/script/download_hot3d_raw.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fresh-download official HOT3D Aria raw; preserve ZIPs and complete VRS unchanged."""
2
+ from __future__ import annotations
3
+ import hashlib
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ import shutil
8
+ import sys
9
+ import time
10
+ import traceback
11
+ import zipfile
12
+ import threading
13
+ from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
14
+ from urllib.parse import urlsplit
15
+ import requests
16
+ from download_recovery import SlowDownload, IncompleteDownload, error_fields, save_json
17
+
18
+ WORK = Path(__file__).resolve().parents[1]
19
+ ROOT = Path('E:/hand-datasets/HOT3D')
20
+ TMP = ROOT / 'tmp'
21
+ RESERVE = 400_000_000_000
22
+ FRESH_RUN = '2026-09-18-aria-fresh'
23
+ TLS=threading.local();LATEST={};LATEST_LOCK=threading.Lock();STOP=threading.Event()
24
+ GROUPS = ['ground_truth', 'hand_data', 'mps_slam_calibration',
25
+ 'mps_slam_trajectories', 'mps_slam_summary', 'main_vrs']
26
+
27
+
28
+ def load(p):
29
+ return json.loads(p.read_text(encoding='utf-8'))
30
+
31
+
32
+ def save(p, data):
33
+ save_json(p, data)
34
+
35
+
36
+ def status(stage, **fields):
37
+ value=dict(stage=stage, time=time.strftime('%Y-%m-%dT%H:%M:%S%z'), pid=os.getpid(), **fields)
38
+ worker=getattr(TLS,'worker',None)
39
+ if worker is None:save(TMP/'download-status.json',value)
40
+ else:
41
+ with LATEST_LOCK:LATEST[worker]=value
42
+ save(TMP/'workers'/f'{worker}.json',value)
43
+
44
+
45
+ def client(proxy=False):
46
+ s = requests.Session()
47
+ s.trust_env = False
48
+ if proxy:
49
+ s.proxies = {'http': 'http://127.0.0.1:7897', 'https': 'http://127.0.0.1:7897'}
50
+ return s
51
+
52
+
53
+ def safe(base, rel):
54
+ p = (base / rel).resolve()
55
+ assert p.is_relative_to(base.resolve()) and p != base.resolve()
56
+ return p
57
+
58
+
59
+ def digests(path):
60
+ sha1, sha256 = hashlib.sha1(), hashlib.sha256()
61
+ git = hashlib.sha1(f'blob {path.stat().st_size}\0'.encode())
62
+ with path.open('rb') as f:
63
+ for chunk in iter(lambda: f.read(4 * 1024 * 1024), b''):
64
+ sha1.update(chunk); sha256.update(chunk); git.update(chunk)
65
+ return {'sha1': sha1.hexdigest(), 'sha256': sha256.hexdigest(), 'git_blob_sha1': git.hexdigest()}
66
+
67
+
68
+ def matches(result, item):
69
+ return all(result[alg] == item[alg] for alg in ('sha1', 'sha256', 'git_blob_sha1') if item.get(alg))
70
+
71
+
72
+ def validate(path, item):
73
+ assert path.stat().st_size == item['size'], 'size mismatch'
74
+ result = digests(path)
75
+ assert matches(result, item), 'official content digest mismatch'
76
+ if item['path'].lower().endswith('.zip'):
77
+ with zipfile.ZipFile(path) as z:
78
+ assert z.testzip() is None, 'ZIP CRC mismatch'
79
+ result['zip_crc'] = 'passed_all_members'
80
+ result.update(size=path.stat().st_size, official_digest_match=True)
81
+ return result
82
+
83
+
84
+ def prepare():
85
+ plan_path = ROOT / 'raw/doc/download_manifest.json'
86
+ if plan_path.exists():
87
+ plan = load(plan_path)
88
+ assert plan['scope'] == 'Aria only; all source VRS streams; no Quest'
89
+ assert plan.get('fresh_download_run') == FRESH_RUN, 'Separate previous data before starting the fresh run'
90
+ plan['raw_storage'] = 'Official ZIP archives, complete VRS and loose assets; no extraction or stream filtering'
91
+ save(plan_path, plan)
92
+ return plan
93
+ source = WORK / 'datasets/HOT3D/_private/Hot3DAria_download_urls.json'
94
+ cdn = load(source)
95
+ revision = (WORK / 'tmp/hot3d-official-revision.txt').read_text().strip()
96
+ asset_index = load(WORK / 'tmp/hot3d-official-assets.json')
97
+ for rel in ['raw/data', 'raw/doc', 'raw/script/official', 'tmp/downloads', 'tmp/private']:
98
+ (ROOT / rel).mkdir(parents=True, exist_ok=True)
99
+ files, urls, unavailable = [], {}, []
100
+ for seq, entries in cdn['sequences'].items():
101
+ for group in GROUPS:
102
+ entry = entries.get(group, {})
103
+ if not entry.get('download_url'):
104
+ unavailable.append({'sequence': seq, 'group': group})
105
+ continue
106
+ rel = f'Aria/{seq}/{entry["filename"]}'
107
+ safe(ROOT / 'raw/data', rel)
108
+ assert len(entry['sha1sum']) == 40 and entry['file_size_bytes'] > 0
109
+ assert urlsplit(entry['download_url']).hostname.endswith('.fbcdn.net')
110
+ files.append({'path': rel, 'sequence': seq, 'group': group, 'size': entry['file_size_bytes'],
111
+ 'sha1': entry['sha1sum'], 'source_locator': f'Hot3DAria_download_urls.json#/sequences/{seq}/{group}'})
112
+ urls[rel] = entry['download_url']
113
+ for entry in asset_index['files']:
114
+ if entry['type'] != 'file':
115
+ continue
116
+ rel = 'assets/' + entry['path']
117
+ item = {'path': rel, 'group': 'object_models', 'size': entry['size'],
118
+ 'source_locator': f'https://huggingface.co/datasets/{asset_index["repo"]}/blob/{asset_index["revision"]}/{entry["path"]}'}
119
+ if entry.get('lfs'):
120
+ item['sha256'] = entry['lfs']['oid']
121
+ else:
122
+ item['git_blob_sha1'] = entry['oid']
123
+ files.append(item)
124
+ urls[rel] = f'https://huggingface.co/datasets/{asset_index["repo"]}/resolve/{asset_index["revision"]}/{entry["path"]}'
125
+ # Download and retain the official model ZIP anew.
126
+ model_rel = 'assets/hot3d_models.zip'
127
+ files.append({'path': model_rel, 'group': 'object_models_archive', 'size': 137336584,
128
+ 'sha256': '7b004ed35bcef4242ac50040cfb44140c37de4e37ce023a00affcf0f20a58f64',
129
+ 'source_locator': f'https://huggingface.co/datasets/{asset_index["repo"]}/blob/{asset_index["revision"]}/hot3d_models.zip'})
130
+ urls[model_rel] = f'https://huggingface.co/datasets/{asset_index["repo"]}/resolve/{asset_index["revision"]}/hot3d_models.zip'
131
+ # Keep signed download links in local temporary state, not in distributable docs.
132
+ save(TMP / 'private/download_urls.json', urls)
133
+ shutil.copyfile(source, TMP / 'private/Hot3DAria_download_urls.json')
134
+ save(ROOT / 'raw/doc/official_manifest_metadata.json', {'sequence_config': cdn['sequence_config'],
135
+ 'source_file_sha256': hashlib.sha256(source.read_bytes()).hexdigest(), 'files': files})
136
+ sources = []
137
+ official_paths = ['README.md', 'VERSIONS.md', 'hot3d/data_downloader/dataset_downloader_base.py',
138
+ 'hot3d/data_downloader/dataset_downloader_base_main.py',
139
+ 'hot3d/data_downloader/dataset_download_status_manager.py', 'hot3d/data_downloader/utils.py']
140
+ with client(True) as s:
141
+ for rel in official_paths:
142
+ url = f'https://raw.githubusercontent.com/facebookresearch/hot3d/{revision}/{rel}'
143
+ r = s.get(url, timeout=(15,40)); r.raise_for_status()
144
+ dest = safe(ROOT / 'raw/script/official', rel); dest.parent.mkdir(parents=True, exist_ok=True); dest.write_bytes(r.content)
145
+ sources.append({'path': dest.relative_to(ROOT).as_posix(), 'url': url, 'sha256': hashlib.sha256(r.content).hexdigest()})
146
+ # Download phase only: reserve unfinished ARCTIC raw plus bounded temporary/pilot work.
147
+ arctic = load(Path('E:/hand-datasets/ARCTIC/raw/doc/download_manifest.json'))
148
+ arctic_done = load(Path('E:/hand-datasets/ARCTIC/raw/doc/archive_checksums.json'))
149
+ arctic_remaining = max(0, arctic['space_plan']['raw_budget_bytes'] - sum(x['size'] for x in arctic_done.values()))
150
+ total = sum(x['size'] for x in files)
151
+ peak_additional = total + arctic_remaining + 100_000_000_000
152
+ assert shutil.disk_usage(ROOT).free > RESERVE + peak_additional, 'Insufficient concurrent raw download budget'
153
+ plan = {'dataset': 'HOT3D', 'release': cdn['sequence_config']['release'],
154
+ 'fresh_download_run': FRESH_RUN, 'reuse_previous_data': False,
155
+ 'scope': 'Aria only; all source VRS streams; no Quest', 'sequence_count': len(cdn['sequences']),
156
+ 'official_repo_revision': revision, 'asset_repo_revision': asset_index['revision'],
157
+ 'files': files, 'files_total': len(files), 'bytes_total': total, 'official_sources': sources,
158
+ 'missing_source_groups': unavailable,
159
+ 'excluded_groups': ['Quest', 'video_main_rgb (preview duplicate)', 'mps_eye_gaze', 'mps_slam_points', 'mps_artifacts'],
160
+ 'space_plan': {'hot3d_raw_bytes': total, 'arctic_remaining_raw_budget_bytes': arctic_remaining,
161
+ 'temporary_and_pilot_budget_bytes': 100_000_000_000, 'minimum_free_bytes': RESERVE,
162
+ 'full_share_processing': 'Rebudget after representative pilot; not started by this downloader.'}}
163
+ save(plan_path, plan)
164
+ shutil.copyfile(__file__, ROOT/'raw/script/download_hot3d_raw.py')
165
+ status('manifest_ready', files_total=len(files), bytes_total=total)
166
+ return plan
167
+
168
+
169
+ def fetch(item, index, total, verified, urls):
170
+ dest = safe(ROOT / 'raw/data', item['path']); dest.parent.mkdir(parents=True, exist_ok=True)
171
+ old = verified.get(item['path'])
172
+ if old:
173
+ assert old.get('fresh_download_run') == FRESH_RUN
174
+ if dest.exists():
175
+ if old and old.get('official_digest_match') and dest.stat().st_size == old['size'] and dest.stat().st_mtime_ns == old['mtime_ns'] and matches(old, item):
176
+ return old
177
+ # A fresh-run file may have been renamed just before interruption, before indexing.
178
+ result = validate(dest, item)
179
+ return dict(result, mtime_ns=dest.stat().st_mtime_ns, acquisition='current_fresh_run_revalidated', fresh_download_run=FRESH_RUN)
180
+ part = safe(TMP / 'downloads', item['path'] + '.part'); part.parent.mkdir(parents=True, exist_ok=True)
181
+ meta = part.with_suffix('.resume.json')
182
+ url = urls[item['path']]
183
+ for attempt in range(6):
184
+ proxy = urlsplit(url).hostname == 'huggingface.co' or attempt >= 2
185
+ try:
186
+ if STOP.is_set():raise RuntimeError('Worker group stopped')
187
+ offset = part.stat().st_size if part.exists() else 0
188
+ assert offset <= item['size'], 'Partial file larger than official size'
189
+ if offset < item['size']:
190
+ assert shutil.disk_usage(ROOT).free > RESERVE + item['size'] - offset
191
+ headers = {'Accept-Encoding': 'identity'}
192
+ if offset:
193
+ headers['Range'] = f'bytes={offset}-'
194
+ if meta.exists() and load(meta).get('validator'):
195
+ headers['If-Range'] = load(meta)['validator']
196
+ status('downloading', file=item['path'], file_index=index, files_total=total, bytes_downloaded=offset,
197
+ bytes_total=item['size'], completed_files=len(verified), network='proxy' if proxy else 'direct')
198
+ with client(proxy) as s, s.get(url, headers=headers, stream=True, timeout=(15,75)) as response:
199
+ response.raise_for_status()
200
+ assert 'text/html' not in response.headers.get('Content-Type',''), 'HTML response instead of raw'
201
+ if response.status_code == 206:
202
+ cr = response.headers.get('Content-Range','')
203
+ assert cr.startswith(f'bytes {offset}-') and int(cr.split('/')[-1]) == item['size']
204
+ else:
205
+ offset = 0
206
+ save(meta, {'validator': response.headers.get('ETag') or response.headers.get('Last-Modified'), 'size': item['size']})
207
+ last = time.monotonic(); window_bytes = offset; rate_start=last; rate_bytes=offset
208
+ with part.open('ab' if offset else 'wb') as out:
209
+ for chunk in response.iter_content(256*1024):
210
+ if not chunk: continue
211
+ if STOP.is_set():raise RuntimeError('Worker group stopped')
212
+ out.write(chunk); offset += len(chunk)
213
+ assert offset <= item['size'], 'Response larger than official size'
214
+ now = time.monotonic()
215
+ if now-rate_start >= 120:
216
+ if (offset-rate_bytes)/(now-rate_start) < 256*1024:
217
+ raise SlowDownload('Slow transfer; preserve partial and reconnect')
218
+ rate_start=now; rate_bytes=offset
219
+ if now-last >= 20:
220
+ assert shutil.disk_usage(ROOT).free > RESERVE
221
+ status('downloading', file=item['path'], file_index=index, files_total=total,
222
+ bytes_downloaded=offset, bytes_total=item['size'], completed_files=len(verified),
223
+ download_MBps=round((offset-window_bytes)/(now-last)/1e6,3), network='proxy' if proxy else 'direct')
224
+ last=now; window_bytes=offset
225
+ received_size = part.stat().st_size
226
+ if received_size < item['size']:
227
+ raise IncompleteDownload(received_size, item['size'])
228
+ status('verifying_file', file=item['path'], file_index=index, files_total=total, completed_files=len(verified))
229
+ try:
230
+ result = validate(part, item)
231
+ except AssertionError:
232
+ part.replace(part.with_name(part.name + '.invalid-' + str(int(time.time()))))
233
+ meta.unlink(missing_ok=True)
234
+ raise
235
+ part.replace(dest); meta.unlink(missing_ok=True)
236
+ return dict(result, mtime_ns=dest.stat().st_mtime_ns, acquisition='official_download', fresh_download_run=FRESH_RUN)
237
+ except Exception as e:
238
+ fields=error_fields(e)
239
+ status('retrying', file=item['path'], attempt=attempt+1, completed_files=len(verified), **fields)
240
+ if not fields['retryable']: raise
241
+ if attempt==5: raise
242
+ time.sleep(min(2**attempt,16))
243
+
244
+
245
+ def worker_fetch(item,index,total,verified,urls):
246
+ TLS.worker=threading.current_thread().name.replace('_','-')
247
+ status('starting_file',file=item['path'],bytes_downloaded=0,download_MBps=0)
248
+ try:return fetch(item,index,total,verified,urls)
249
+ finally:status('idle',download_MBps=0)
250
+
251
+
252
+ def main():
253
+ plan = prepare()
254
+ if '--prepare-only' in sys.argv: return
255
+ state = load(WORK/'tmp/dataset-work-state.json')
256
+ assert 'HOT3D' in state['active'] and len(state['active']) <= 2
257
+ urls = load(TMP/'private/download_urls.json')
258
+ record = ROOT/'raw/doc/file_checksums.json'
259
+ verified = load(record) if record.exists() else {}
260
+ # Download the model ZIP and small model assets before sequence downloads.
261
+ files = sorted(plan['files'], key=lambda x: (0 if x['group']=='object_models_archive' else 1 if x['group']=='object_models' else 2, x['path'] if x['group'].startswith('object_') else ''))
262
+ workers=max(1,min(2,int(os.environ.get('HOT3D_DOWNLOAD_WORKERS','2'))))
263
+ with ThreadPoolExecutor(max_workers=workers,thread_name_prefix='hot3d') as pool:
264
+ pending={pool.submit(worker_fetch,item,index,len(files),verified,urls):item for index,item in enumerate(files,1)}
265
+ try:
266
+ while pending:
267
+ done,_=wait(pending,timeout=20,return_when=FIRST_COMPLETED)
268
+ for future in done:
269
+ item=pending.pop(future);verified[item['path']]=future.result();save(record,verified)
270
+ with LATEST_LOCK:active=[dict(v) for v in LATEST.values() if v['stage']!='idle']
271
+ status('downloading',files_total=len(files),completed_files=len(verified),bytes_verified=sum(v['size'] for v in verified.values()),download_workers=workers,download_MBps=round(sum(v.get('download_MBps',0) for v in active if v['stage']=='downloading'),3),active_files=active,network='direct_preferred')
272
+ except BaseException:
273
+ STOP.set()
274
+ for future in pending:future.cancel()
275
+ raise
276
+ status('raw_complete_verified', files_total=len(verified), bytes_total=sum(x['size'] for x in verified.values()), scope=plan['scope'], raw_storage='official_archives_and_complete_vrs')
277
+ state=load(WORK/'tmp/dataset-work-state.json');state['active']['HOT3D']['stage']='raw_complete_awaiting_pilot';save(WORK/'tmp/dataset-work-state.json',state)
278
+
279
+
280
+ if __name__ == '__main__':
281
+ try: main()
282
+ except Exception as exc:
283
+ status('failed', **error_fields(exc), failure_location=[{'file':Path(f.filename).name,'line':f.lineno,'function':f.name} for f in traceback.extract_tb(exc.__traceback__)])
284
+ raise SystemExit(1)
HOT3D/raw/script/download_recovery.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Classify retryable download failures without recording credentials or URLs."""
2
+ import errno
3
+ import json
4
+ import time
5
+ import requests
6
+
7
+
8
+ class SlowDownload(requests.RequestException):
9
+ pass
10
+
11
+
12
+ class IncompleteDownload(requests.RequestException):
13
+ """The HTTP stream ended before all expected bytes arrived; keep the partial."""
14
+ def __init__(self, received_size, expected_size):
15
+ super().__init__('HTTP stream ended before expected file size')
16
+ self.received_size = received_size
17
+ self.expected_size = expected_size
18
+
19
+
20
+ def save_json(path, value):
21
+ """Publish metadata atomically; tolerate brief Windows reader/AV sharing locks."""
22
+ path.parent.mkdir(parents=True, exist_ok=True)
23
+ temporary = path.with_name(path.name + '.next')
24
+ text = json.dumps(value, ensure_ascii=False, indent=2) + '\n'
25
+ for attempt in range(8):
26
+ try:
27
+ temporary.write_text(text, encoding='utf-8')
28
+ temporary.replace(path)
29
+ return
30
+ except PermissionError as error:
31
+ # Do not classify disk failures, persistent permission failures, or
32
+ # integrity errors as retryable network failures.
33
+ if getattr(error, 'winerror', None) not in (5, 32, 33) or attempt == 7:
34
+ raise
35
+ time.sleep(min(0.1 * 2**attempt, 1.0))
36
+
37
+
38
+ def error_fields(error):
39
+ response = getattr(error, 'response', None)
40
+ code = getattr(response, 'status_code', None)
41
+ if isinstance(error, requests.HTTPError):
42
+ retryable = code in (408, 425, 429, 500, 502, 503, 504)
43
+ else:
44
+ retryable = isinstance(error, requests.RequestException)
45
+ result = {'error_type': type(error).__name__, 'retryable': retryable,
46
+ 'http_status': code, 'winerror': getattr(error, 'winerror', None),
47
+ 'disk_space_error': getattr(error, 'errno', None) == errno.ENOSPC}
48
+ if isinstance(error, IncompleteDownload):
49
+ result.update(received_size=error.received_size, expected_size=error.expected_size)
50
+ return result
HOT3D/raw/script/official/README.md ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HOT3D Toolkit
2
+
3
+ This repository hosts an official toolkit for [HOT3D](https://facebookresearch.github.io/hot3d/), an egocentric dataset for 3D hand and object tracking.
4
+
5
+ The toolkit offers:
6
+
7
+ - An API for downloading and using the full HOT3D dataset provided in a [VRS](https://github.com/facebookresearch/vrs)-based format (see [tutorial](https://github.com/facebookresearch/hot3d/blob/main/hot3d/HOT3D_Tutorial.ipynb)).
8
+ - An API for [HOT3D-Clips](https://github.com/facebookresearch/hot3d/tree/main/hot3d/clips) which is a curated HOT3D subset provided in the [Webdataset](https://github.com/webdataset/webdataset) format and used in [BOP Challenge 2024](https://bop.felk.cvut.cz/challenges/bop-challenge-2024) and [Multiview Egocentric Hand Tracking Challenge](https://github.com/facebookresearch/hand_tracking_toolkit?tab=readme-ov-file#evaluation).
9
+
10
+ Resources:
11
+ - [HOT3D homepage](https://facebookresearch.github.io/hot3d/)
12
+ - [Download full HOT3D dataset from projectaria.com](https://www.projectaria.com/datasets/hot3D/)
13
+ - [Download HOT3D-Clips from Hugging Face](https://huggingface.co/datasets/bop-benchmark/hot3d)
14
+ - [Read HOT3D paper](https://arxiv.org/pdf/2411.19167)
15
+
16
+ The following instructions are relevant if you want to use the full HOT3D dataset in the VRS-based format. For HOT3D-Clips, please refer to the [dedicated page](https://github.com/facebookresearch/hot3d/tree/main/hot3d/clips).
17
+
18
+ ## Step 1: Install the downloader
19
+
20
+ This Python repository can be used with Pixi and Conda environments and can run on:
21
+
22
+ * x64 Linux distributions of:
23
+ * Fedora 36, 37, 38
24
+ * Ubuntu jammy (22.04 LTS) and focal (20.04 LTS)
25
+ * Mac Intel or Mac ARM-based (M1) with MacOS 11 (Big Sur) or newer
26
+
27
+ Python 3.9+ (3.10+ if you are on [Apple Silicon](https://support.apple.com/en-us/116943)).
28
+
29
+
30
+ ### Using Pixi
31
+
32
+ [Pixi](https://prefix.dev/) is a package management tool for developers. Developers can install libraries and applications in a reproducible way, which makes it easier to install and use a Python environment for the HOT3D API.
33
+
34
+ ```
35
+ # 1. Install pixi
36
+ curl -fsSL https://pixi.sh/install.sh | bash
37
+
38
+ # 2. Checkout this repository
39
+ git clone https://github.com/facebookresearch/hot3d.git
40
+ cd hot3d/hot3d
41
+
42
+ # 3. Call `pixi install` to setup the environment
43
+ pixi install
44
+
45
+ # 4. (Optional) Install the third-party dependencies required for hands, by reviewing and accepting the licenses provided on the corresponding third-party repositories
46
+ pixi run setup_hands
47
+
48
+ ```
49
+
50
+ #### A quick introduction to the [PIXI environment](https://prefix.dev/)
51
+ - Execute Pixi environment commands from within the `hot3d` folder.
52
+ - The Pixi environment is located in the `.pixi` folder.
53
+ - Activate the Pixi HOT3D environment by using the command `pixi shell`.
54
+ - Exit the Pixi HOT3D environment by typing `exit`.
55
+ - Remove the environment by executing the command `rm -rf .pixi`.
56
+
57
+
58
+ ### Using Conda
59
+
60
+ [Conda](https://conda.io/projects/conda/en/latest/index.html) is a package manager used for managing software environments and dependencies in data science and scientific computing.
61
+
62
+ ```
63
+ # 1. Install conda -> https://conda.io/projects/conda/en/latest/user-guide/getting-started.html
64
+ # 2. Create your environment
65
+ conda create --name hot3d
66
+ conda activate hot3d
67
+
68
+ # 2. Install dependencies
69
+ python3 -m ensurepip
70
+ python3 -m pip install projectaria_tools==1.5.1 torch requests rerun-sdk==0.16.0
71
+ python3 -m pip install vrs
72
+ python3 -m pip install matplotlib
73
+
74
+ # 3. (Optional) Install the third-party dependencies required for hands by reviewing and accepting the licenses provided on the corresponding third-party repositories
75
+ python3 -m pip install 'git+https://github.com/vchoutas/smplx.git'
76
+ python3 -m pip install 'git+https://github.com/mattloper/chumpy'
77
+ ```
78
+
79
+ #### A quick introduction to the [CONDA environment](https://docs.conda.io/projects/conda/en/4.6.1/user-guide/tasks/manage-environments.html#managing-environments)
80
+
81
+ - Activate the Conda HOT3D environment by executing `conda activate hot3d`.
82
+ - Exit the Conda HOT3D environment using `conda deactivate`.
83
+ - Remove the Conda HOT3D environment by executing `conda remove --name hot3d --all`.
84
+
85
+
86
+ ## Step 2: Sign up and get the download links file
87
+
88
+ 1. Review the [HOT3D license agreement](https://www.projectaria.com/datasets/hot3d/license/).
89
+ * Examine the specific licenses applicable to the data types you wish to use, such as Sequence, Hand annotations, and 3D object models.
90
+ 2. Go to the [HOT3D website](https://www.projectaria.com/datasets/hot3D/) and sign up.
91
+ * Scroll down to the bottom of the page.
92
+ * Enter your email and select **Access the Datasets**.
93
+ 3. The HOT3D page will be refreshed to contain instructions and download links
94
+ * The download view is ephemeral, keep the tab open to access instructions and links
95
+ * Download links that last for 14 days
96
+ * Enter your email again on the HOT3D main page to get fresh links
97
+ 4. Select the Download button for any of the data types:
98
+ * “Download the HOT3D Aria Dataset"
99
+ * "Download the HOT3D Quest Dataset"
100
+ * "Download the HOT3D Assets Dataset"
101
+ 5. These will swiftly download JSON files with urls that the downloader will use
102
+
103
+
104
+ ## Step 3: Download the data
105
+ Use the HOT3D downloader to download some, or all of the data.
106
+
107
+ ```
108
+ # 1. Activate your environment (assuming from the hot3d folder):
109
+ # conda: conda activate hot3d
110
+ # pixi: pixi shell
111
+
112
+ # 2. Go to the hot3d/data_downloader directory
113
+ cd hot3d/data_downloader
114
+ mkdir -p ../dataset
115
+
116
+ # 3. Run the dataset downloader
117
+ # Download HOT3D Object Library data
118
+ python3 dataset_downloader_base_main.py -c Hot3DAssets_download_urls.json -o ../dataset --sequence_name all
119
+
120
+ # Download one HOT3D Aria data sequence
121
+ python3 dataset_downloader_base_main.py -c Hot3DAria_download_urls.json -o ../dataset --sequence_name P0003_c701bd11 --data_types all
122
+ # Type answer `y`
123
+
124
+ # Download one HOT3D Quest data sequence
125
+ python3 dataset_downloader_base_main.py -c Hot3DQuest_download_urls.json -o ../dataset --sequence_name P0002_1464cbdc --data_types all
126
+ # Type answer `y`
127
+ ```
128
+
129
+ **Tip:** To download all sequences in a download links JSON file (such as the HOT3D Object Library data in step 3), pass sequence_name as 'all'.
130
+
131
+ ## Step 4: Run the dataset viewer
132
+
133
+ ### Viewing objects and headset pose trajectory
134
+ ```
135
+ python3 viewer.py --sequence_folder <PATH>/hot3d_dataset/P0003_c701bd11 --object_library_folder <PATH>/hot3d_dataset/assets/
136
+ ```
137
+
138
+ When using `pixi`, you can directly launch the viewer without explicitly activating the environment by using the following command:
139
+ ```
140
+ pixi run viewer --sequence_folder <PATH>/hot3d_dataset/P0003_c701bd11 --object_library_folder <PATH>/hot3d_dataset/assets/
141
+ ```
142
+
143
+ ### Using hand annotations
144
+
145
+ Hand pose annotations in HOT3D are provided in the [UmeTrack](https://github.com/facebookresearch/UmeTrack) and [MANO](https://mano.is.tue.mpg.de/) formats. Both hand poses annotation are accessible in the API by using either the `mano_hand_data_provider`, `umetrack_hand_data_provider` property once the `Hot3dDataProvider` is initialized. In order to choose the representation for the viewer, use the following:
146
+
147
+ #### UmeTrack
148
+
149
+ ```
150
+ python3 viewer.py --sequence_folder <PATH>/hot3d_dataset/P0003_c701bd11--object_library_folder <PATH>/hot3d_dataset/assets --hand_type UMETRACK
151
+ ```
152
+
153
+ #### MANO
154
+
155
+ Hand annotations in the MANO format can be downloaded after accepting their [license agreement](https://mano.is.tue.mpg.de/).
156
+ - HOT3D only requires the `MANO_RIGHT.pkl` and `MANO_LEFT.pkl` files for loading and rendering of hand poses. These files can be obtained from the `mano_v1_2.zip` file located in the "Models & Code" section of the `MANO` website. After downloading, extract the zip file to your local disk, and the `*.pkl` files can be found at the following path: `mano_v1_2/models/`.
157
+
158
+ ```
159
+ python3 viewer.py --sequence_folder <PATH>/hot3d_dataset/P0003_c701bd11 --object_library_folder <PATH>/hot3d_dataset/assets --mano_model_folder <PATH>/mano_v1_2/models/ --hand_type MANO
160
+ ```
161
+
162
+ ## Step 5: Run the python notebook tutorial
163
+
164
+ ```
165
+ # Assuming you have downloaded the Aria `P0003_c701bd11` sequence and the object library above.
166
+ #
167
+ # Install Jupyter Notebook for your environment:
168
+ python3 -m pip install Jupyter
169
+ # Run Jupyter and open the notebook (conda)
170
+ jupyter notebook ./HOT3D_Tutorial.ipynb
171
+ # Run Jupyter and open the notebook (pixi, use a direct path to ensure jupyter will take the right python path)
172
+ .pixi/envs/default/bin/jupyter notebook ./HOT3D_Tutorial.ipynb
173
+ ```
174
+
175
+
176
+ ## Step6: Mastering the dataset and its API
177
+
178
+ ### Using the HOT3D dataset API
179
+
180
+ - Please refer to our notebook [tutorial](./hot3d/HOT3D_Tutorial.ipynb). The notebook explains how to instantiate a `Hot3dDataProvider` from a HOT3D sequence folder and how to use its API to retrieve each data modality (images, GT hand & object poses, ...).
181
+
182
+
183
+ ### Using "mask files"
184
+
185
+ HOT3D utilizes mask files to identify and flag specific timestamps based on a particular property. For instance, we can use masks to mark specific timestamps in a camera stream as having inaccurate object pose (as determined through manual QA) or as having an over-saturated image. These masks can be combined using logical AND/OR operations to create a custom mask that meets the end user's requirements.
186
+
187
+ Here is a list of the exported mask files:
188
+
189
+ | File | Description |
190
+ | -- | -- |
191
+ | mask_object_pose_available.csv | True if all dynamic objects in the scene have a valid pose, and false if even one object is missing a pose. The accuracy of the poses is not evaluated. |
192
+ | mask_hand_pose_available.csv | True if both right and left hands have a valid pose, and false if even one hand is missing a pose. The accuracy of the poses is not evaluated. |
193
+ | mask_headset_pose_available.csv | True if the headset has a valid pose, and false otherwise. The accuracy of the poses is not evaluated. |
194
+ | mask_object_visibility.csv | True if at least one object is visible in the camera frame, false otherwise. Visibility is computed based on the pose, and accuracy of the pose is not evaluated. |
195
+ | mask_hand_visible.csv | True if at least one hand is visible in the camera frame, false otherwise. Visibility is computed based on the pose, and accuracy of the pose is not evaluated. |
196
+ | mask_good_exposure.csv | True if sufficient pixels on the hand and dynamic objects visible in the frame are not over-exposed, false otherwise. Visibility is computed based on the pose, and accuracy of the pose is not evaluated. |
197
+ | mask_qa_pass.csv | True if manual QA indicated no issues with the pose of the objects and hands visible in a camera stream, false otherwise. |
198
+
199
+ The masks are saved in csv format, with each row indicating the validity of the mask for a given timestamp and camera stream_id:
200
+ ```
201
+ timestamp[ns],stream_id,mask
202
+ 43986008190448,214-1,True
203
+ 43986008283010,1201-2,True
204
+ 43986008283023,1201-1,True
205
+ 43986041551363,214-1,True
206
+ 43986041643100,1201-2,True
207
+ 43986041643113,1201-1,True
208
+ 43986074878771,214-1,False
209
+ 43986074971171,1201-2,False
210
+ 43986074971184,1201-1,False
211
+ 43986108202591,214-1,True
212
+ ```
213
+
214
+ Here is how to load the mask files and combine them with a logical operator:
215
+
216
+ ```
217
+ # Mask API example:
218
+ # Let's check that we have at least a hand and an object that is visible in a given stream
219
+ #
220
+
221
+ import os
222
+ from projectaria_tools.core.stream_id import StreamId
223
+ from data_loaders.loader_masks import combine_mask_data, load_mask_data, MaskData
224
+
225
+ sequence_folder = "<PATH>/hot3d_dataset/P0003_c701bd11/"
226
+
227
+ # Select the desired masks
228
+ example_mask_list = [
229
+ # Use the masks that depicting the visibility status
230
+ "masks/mask_hand_visible.csv",
231
+ "masks/mask_object_visible.csv",
232
+ ]
233
+
234
+ # Load the referred masks
235
+ mask_data_list = []
236
+ for it in example_mask_list:
237
+ if os.path.exists(os.path.join(sequence_folder, it)):
238
+ ret = load_mask_data(os.path.join(sequence_folder, it))
239
+ mask_data_list.append(ret)
240
+
241
+ # Combine the masks (you can choose logical "and"/"or")
242
+ output = combine_mask_data(mask_data_list, "and")
243
+
244
+ # Get the number of frames where we can see at least a hand and an object
245
+ num_timestamps_with_at_least_a_hand_and_object_visible = output.num_true(StreamId("214-1"))
246
+ print(f"Number of frames containing at least a hand and object visible: {num_timestamps_with_at_least_a_hand_and_object_visible}")
247
+
248
+ total_frame_count = output.length(StreamId("214-1"))
249
+ print(f"Total sequence frames: {total_frame_count}")
250
+ ```
251
+
252
+ ## Test/Train split
253
+
254
+ The sequences corresponding to the following participant ids are defining the TEST set, and so does not have any GT information
255
+ `TEST_SET_PARTICIPANT_ID = ["P0004", "P0005", "P0006", "P0008", "P0016", "P0020"]`
256
+
257
+ i.e:
258
+ - sequence `P0003_c701bd11` belong to the TRAIN set
259
+ - sequence `P0004_a59ab32e` belong to the TEST set
260
+
261
+ Note that the information is also shared in the `metadata.json` file under the field `gt_available_status` or can be accessed directly via the `Hot3dDataProvider -> get_sequence_metadata` API call.
262
+
263
+ ## License
264
+
265
+ - [HOT3D API](https://github.com/facebookresearch/hot3d) (aka. this repository) is released by Meta under the [Apache 2.0 license](LICENSE)
266
+ - [HOT3D dataset](https://www.projectaria.com/datasets/hot3d/) is released under the [HOT3D license agreement](https://www.projectaria.com/datasets/hot3d/license/)
267
+ - Using hands annotation requires installation of [SMPLX/MANO](https://github.com/vchoutas/smplx) third-party dependencies, please review and agree to their license listed on their website.
268
+
269
+
270
+ ## Contributing
271
+
272
+ Go to [Contributing](.github/CONTRIBUTING.md) and the [Code of Conduct](.github/CODE_OF_CONDUCT.md).
HOT3D/raw/script/official/VERSIONS.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # HOT3D versions
2
+
3
+ This file records shipped versions of the full HOT3D dataset available via [projectaria.com](https://www.projectaria.com/datasets/hot3D/).
4
+
5
+ Only the last version is available for download. To find out what version you have, look for the field "version" in the "metadata.json" files stored in the sequence folders.
6
+
7
+ - v1 (June 17, 2024): Initial release
8
+ - v2 (July 3, 2024): More accurate thumbs on Mano hands
9
+ - v3 (December 19, 2024): Updated visibility scores in box2d_hands/objects.csv
HOT3D/raw/script/official/hot3d/data_downloader/dataset_download_status_manager.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import json
16
+ from typing import Final, List
17
+
18
+ DOWNLOAD_STATUS_FILE: Final[str] = ".download_status.json"
19
+
20
+
21
+ class DatasetDownloadStatusManager:
22
+ def __init__(self, data_groups: List[str]):
23
+ self.status = {data_group: False for data_group in data_groups}
24
+
25
+ # Read status file from json and assign to status
26
+ def from_json(self, json_path: str) -> None:
27
+ try:
28
+ with open(json_path, "r") as f:
29
+ data = json.load(f)
30
+ for expected_data_group in self.status:
31
+ if expected_data_group not in data:
32
+ error = f"{DOWNLOAD_STATUS_FILE} is missing data group {expected_data_group}.\n"
33
+ error += f"Your data may be out of date, try clearing {DOWNLOAD_STATUS_FILE} in your sequence path"
34
+ raise Exception(error)
35
+ self.status = data
36
+ except Exception as e:
37
+ print(f"[warning]: cannot read status json. {e}")
38
+
39
+ def to_json(self, json_path: str):
40
+ try:
41
+ json_object = json.dumps(self.status, indent=4)
42
+ with open(json_path, "w") as outfile:
43
+ outfile.write(json_object)
44
+ except Exception as e:
45
+ print(f"[warning]: can not write status json. {e}")
46
+
47
+ def set_download_status(self, data_type: str, value: bool):
48
+ if data_type not in self.status:
49
+ raise Exception(f"data type {data_type} is not supported")
50
+ self.status[data_type] = value
51
+
52
+ def get_download_status(self, data_type: str) -> bool:
53
+ return self.status[data_type]
HOT3D/raw/script/official/hot3d/data_downloader/dataset_downloader_base.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import shutil
19
+ import tempfile
20
+ from pathlib import Path
21
+ from typing import List, Optional, Tuple
22
+ from zipfile import is_zipfile, ZipFile
23
+
24
+ import requests
25
+ from dataset_download_status_manager import (
26
+ DatasetDownloadStatusManager,
27
+ DOWNLOAD_STATUS_FILE,
28
+ )
29
+ from requests.adapters import HTTPAdapter
30
+ from requests.packages.urllib3.util.retry import Retry
31
+ from tqdm import tqdm
32
+ from utils import load_data_groups_from_cdn
33
+
34
+ CHUCK_SIZE_BYTE = 8192
35
+ STATUS_CODE_DEFAULT = 404
36
+
37
+
38
+ DATA_TYPE_TO_SAVE_PATH = {
39
+ "mps_eye_gaze": os.path.join("mps", "eye_gaze"),
40
+ "mps_slam_trajectories": os.path.join("mps", "slam"),
41
+ "mps_slam_points": os.path.join("mps", "slam"),
42
+ "mps_slam_calibration": os.path.join("mps", "slam"),
43
+ "mps_slam_summary": os.path.join("mps", "slam"),
44
+ "mps_hand_tracking": os.path.join("mps", "hand_tracking"),
45
+ }
46
+
47
+
48
+ def calculate_file_sha1(file_path: str) -> str:
49
+ sha1 = hashlib.sha1()
50
+ with open(file_path, "rb") as file:
51
+ chunk = file.read(4096) # Read the file in 4KB chunks
52
+ while chunk:
53
+ sha1.update(chunk)
54
+ chunk = file.read(4096)
55
+
56
+ sha1_sum = sha1.hexdigest()
57
+ return sha1_sum
58
+
59
+
60
+ class DatasetDownloaderBase:
61
+ __KEY_URL: str = "download_url"
62
+ __KEY_FILENAME: str = "filename"
63
+ __KEY_CHECKSUM: str = "sha1sum"
64
+
65
+ def __init__(
66
+ self,
67
+ cdn_file: str,
68
+ data_types: List[str],
69
+ sequences: Optional[List[str]] = None,
70
+ overwrite: bool = False,
71
+ ):
72
+ # add slam summary if any slam data is requested
73
+ if "mps_slam_summary" not in data_types:
74
+ if (
75
+ "mps_slam_trajectories" in data_types
76
+ or "mps_slam_calibration" in data_types
77
+ or "mps_slam_points" in data_types
78
+ ):
79
+ data_types.append("mps_slam_summary")
80
+
81
+ self.data_types_selected = data_types
82
+ self.overwrite = overwrite
83
+
84
+ # load cdn file
85
+ with open(cdn_file, "r") as f:
86
+ cdn_file_data = json.load(f)
87
+ if "sequences" not in cdn_file_data:
88
+ raise Exception("invalid cdn_file, missing key: sequences")
89
+ self.sequences_data = cdn_file_data["sequences"]
90
+ if "sequence_config" not in cdn_file_data:
91
+ raise Exception("invalid cdn_file, missing key: sequence_config")
92
+ self.sequence_config = cdn_file_data["sequence_config"]
93
+
94
+ self.sequences = sequences
95
+ if sequences is None:
96
+ self.sequences = self.__get_all_sequences()
97
+
98
+ self.data_types_all = load_data_groups_from_cdn(cdn_file)
99
+
100
+ def download_data(self, output_folder: str):
101
+ if not os.path.exists(output_folder):
102
+ print(f"Creating local output folder {output_folder}")
103
+ os.makedirs(output_folder)
104
+
105
+ # download sequences
106
+ responses = {}
107
+ for sequence in self.sequences:
108
+ responses[sequence] = self.__download_sequence(
109
+ sequence=sequence,
110
+ output_folder=output_folder,
111
+ )
112
+ num_success_sequences = sum(1 for sequence in responses if responses[sequence])
113
+ print(
114
+ f"{num_success_sequences} of {len(self.sequences)} sequences are successfully downloaded"
115
+ )
116
+
117
+ def __download_sequence(
118
+ self,
119
+ sequence: str,
120
+ output_folder: str,
121
+ ) -> bool:
122
+ output_folder_seq = os.path.join(output_folder, sequence)
123
+ print(f"downloading sequence {sequence} to {output_folder_seq}")
124
+
125
+ if sequence not in self.sequences_data:
126
+ print(f"sequence {sequence} is not available in the selected data group")
127
+ return False
128
+
129
+ if not os.path.exists(output_folder_seq):
130
+ os.makedirs(output_folder_seq)
131
+
132
+ # check last download status
133
+ status_manager = DatasetDownloadStatusManager(self.data_types_all)
134
+ status_json = os.path.join(output_folder_seq, DOWNLOAD_STATUS_FILE)
135
+ if os.path.exists(status_json):
136
+ status_manager.from_json(status_json)
137
+
138
+ final_success = True
139
+ for data_type in self.data_types_selected:
140
+ # skip the data which has already been downloaded if overwrite is not set
141
+ if not self.overwrite and status_manager.get_download_status(data_type):
142
+ print(f"skip downloading datatype {data_type} since already downloaded")
143
+ continue
144
+ data_type_download_is_success = True
145
+ is_success, status_code = self.__download_data_from_url(
146
+ sequence=sequence,
147
+ data_type=data_type,
148
+ output_folder=output_folder_seq,
149
+ )
150
+ if not is_success:
151
+ data_type_download_is_success = False
152
+ final_success = False
153
+ print(f"{data_type} is NOT downloaded with error code {status_code}")
154
+
155
+ # log download status for each data_type
156
+ status_manager.set_download_status(data_type, data_type_download_is_success)
157
+
158
+ # write the download status to json
159
+ status_manager.to_json(status_json)
160
+ return final_success
161
+
162
+ def __download_data_from_url(
163
+ self,
164
+ sequence: str,
165
+ data_type: str,
166
+ output_folder: str,
167
+ ) -> Tuple[bool, int]:
168
+ status_code = STATUS_CODE_DEFAULT
169
+ is_success = True
170
+ sequence_data = self.sequences_data[sequence]
171
+
172
+ if data_type not in sequence_data:
173
+ print(f"Data type {data_type} is not available for sequence: {sequence}")
174
+ return is_success, status_code
175
+
176
+ network_link = sequence_data[data_type][self.__KEY_URL]
177
+ if not network_link:
178
+ print(
179
+ f"Url for sequence '{sequence}', data type '{data_type}' is not available"
180
+ )
181
+ return is_success, status_code
182
+
183
+ try:
184
+ with tempfile.TemporaryDirectory() as local_tmp_path:
185
+ download_filename = sequence_data[data_type][self.__KEY_FILENAME]
186
+ download_file_path = os.path.join(local_tmp_path, download_filename)
187
+ sha1sum = sequence_data[data_type][self.__KEY_CHECKSUM]
188
+ session = requests.Session()
189
+ # allow retry on errors of too many requests (429), internal server error (500),
190
+ # bad gateway (502), service unavailable (503), or gateway timeout (504)
191
+
192
+ retries = Retry(
193
+ total=5,
194
+ backoff_factor=2, # final try is 2*(2**5) = 64 seconds
195
+ status_forcelist=[429, 500, 502, 503, 504],
196
+ )
197
+
198
+ session.mount("https://", HTTPAdapter(max_retries=retries))
199
+
200
+ with session.get(network_link, stream=True, timeout=10) as r:
201
+ # r.raise_for_status()
202
+ total_size_in_bytes = int(r.headers.get("content-length", 0))
203
+
204
+ _, _, free_disk_in_bytes = shutil.disk_usage("/")
205
+ if free_disk_in_bytes < total_size_in_bytes:
206
+ raise Exception(
207
+ f"Insufficient disk space for sequence '{sequence}' data type '{data_type}'. Required \
208
+ {total_size_in_bytes} bytes, available {free_disk_in_bytes} bytes"
209
+ )
210
+ with open(download_file_path, "wb") as f:
211
+ print(f"Serializing to {download_file_path}")
212
+ progress_bar = tqdm(
213
+ total=total_size_in_bytes, unit="iB", unit_scale=True
214
+ )
215
+ for chunk in r.iter_content(chunk_size=CHUCK_SIZE_BYTE):
216
+ # serialize chunk of 8KB
217
+ progress_bar.update(len(chunk))
218
+ f.write(chunk)
219
+ progress_bar.close()
220
+ status_code = r.status_code
221
+ # raise exception if download fails and skip the unzip part below
222
+ r.raise_for_status()
223
+
224
+ calculated_checksum = calculate_file_sha1(download_file_path)
225
+ if sha1sum != calculated_checksum:
226
+ error = f"different checksum value for sequence '{sequence}' and data type '{data_type}'\n"
227
+ error += f"Calculated checksum: {calculated_checksum}, expected checksum: {sha1sum}"
228
+ raise Exception(error)
229
+
230
+ if is_zipfile(download_file_path):
231
+ # unzip and reorganize
232
+ with ZipFile(download_file_path) as zip_ref:
233
+ unzipped_top_dir_name = sequence
234
+ unzipped_dir = os.path.join(
235
+ local_tmp_path, unzipped_top_dir_name
236
+ )
237
+ if not os.path.exists(unzipped_dir):
238
+ os.makedirs(unzipped_dir)
239
+
240
+ # MOVE MPS FILES
241
+ if data_type in DATA_TYPE_TO_SAVE_PATH.keys():
242
+ zip_ref.extractall(output_folder)
243
+ for local_path in zip_ref.namelist():
244
+ abs_path = os.path.join(output_folder, local_path)
245
+ if os.path.isfile(abs_path):
246
+ move_filename = os.path.basename(abs_path)
247
+ move_path = os.path.join(
248
+ Path(abs_path).parent,
249
+ DATA_TYPE_TO_SAVE_PATH[data_type],
250
+ )
251
+ os.makedirs(move_path, exist_ok=True)
252
+ shutil.move(
253
+ abs_path, os.path.join(move_path, move_filename)
254
+ )
255
+ else:
256
+ zip_ref.extractall(output_folder)
257
+ else:
258
+ output_filename = os.path.join(output_folder, download_filename)
259
+ if data_type == "main_vrs":
260
+ basename_old = os.path.basename(output_filename)
261
+ basename_new = "recording.vrs"
262
+ output_filename = output_filename.replace(
263
+ basename_old, basename_new
264
+ )
265
+ shutil.copyfile(
266
+ download_file_path,
267
+ output_filename,
268
+ )
269
+ except Exception as e:
270
+ # Handle request exceptions (e.g., ConnectionError, TooManyRedirects, etc.)
271
+ print(f"An error occurred: {e}. Status code: {status_code}")
272
+ is_success = False
273
+
274
+ return is_success, status_code
275
+
276
+ def __get_all_sequences(self) -> List[str]:
277
+ return list(self.sequences_data.keys())
HOT3D/raw/script/official/hot3d/data_downloader/dataset_downloader_base_main.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import argparse
16
+
17
+ from dataset_downloader_base import DatasetDownloaderBase
18
+ from utils import load_data_groups_from_cdn, load_sequences_list_from_cdn
19
+
20
+
21
+ def parse_args():
22
+ parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
23
+ parser.add_argument(
24
+ "-c",
25
+ "--cdn_file",
26
+ dest="cdn_file",
27
+ type=str,
28
+ required=True,
29
+ default=None,
30
+ help="input file listing the CDN urls",
31
+ )
32
+
33
+ parser.add_argument(
34
+ "-o",
35
+ "--output_folder",
36
+ dest="output_folder",
37
+ type=str,
38
+ required=True,
39
+ help="output folder for storing the downloaded dataset locally",
40
+ )
41
+
42
+ parser.add_argument(
43
+ "-w",
44
+ "--overwrite",
45
+ dest="overwrite",
46
+ action="store_true",
47
+ required=False,
48
+ default=False,
49
+ help="""
50
+ If set, re-download and overwrite sequences which have been downloaded before
51
+ """,
52
+ )
53
+
54
+ parser.add_argument(
55
+ "-d",
56
+ "--data_types",
57
+ dest="data_types",
58
+ nargs="+",
59
+ required=False,
60
+ default=[],
61
+ help="""
62
+ List (space separated) of data types to download for each sequence.
63
+ To get a list of all data types available for this dataset, leave this blank and it will list all options.
64
+ If not set, and IFF single data type exists, it will will be downloaded automatically",
65
+ """,
66
+ )
67
+
68
+ parser.add_argument(
69
+ "-l",
70
+ "--sequence_names",
71
+ dest="sequence_names",
72
+ nargs="+",
73
+ required=False,
74
+ help="a list of sequence names (separated by space) to be downloaded. If not set, all sequences will be downloaded",
75
+ )
76
+
77
+ return parser.parse_args()
78
+
79
+
80
+ def main():
81
+ args = parse_args()
82
+
83
+ all_data_groups = load_data_groups_from_cdn(args.cdn_file)
84
+ all_data_groups_list = list(all_data_groups.keys())
85
+ # remove slam summary since this gets downloaded automatically if any slam data is requested
86
+ if "mps_slam_summary" in all_data_groups_list:
87
+ all_data_groups_list.remove("mps_slam_summary")
88
+
89
+ # If sequence_names is specified as "all", retrieve all sequences from the CDN file
90
+ if len(args.sequence_names) == 1 and "all" in args.sequence_names:
91
+ args.sequence_names = load_sequences_list_from_cdn(args.cdn_file)
92
+
93
+ # If data_types are not specified, ask the user to specify one
94
+ # If only one data type is available, automatically download it
95
+ if len(args.data_types) == 0 and len(all_data_groups_list) > 1:
96
+ print("-d(, --data_types) must be specified")
97
+ print("Available data types include:")
98
+ for i in range(len(all_data_groups_list)):
99
+ print(f"{i}: {all_data_groups_list[i]}")
100
+ exit(1)
101
+ elif len(all_data_groups_list) == 1:
102
+ args.data_types = [0] # Download the only existing data type available
103
+ elif "all" in args.data_types:
104
+ args.data_types = [i for i in range(len(all_data_groups_list))]
105
+
106
+ data_types = []
107
+ for input_data_type in args.data_types:
108
+ data_types.append(all_data_groups_list[int(input_data_type)])
109
+
110
+ if args.sequence_names is None:
111
+ download_all = (
112
+ input(
113
+ """
114
+ -l(, --sequence_names) is not specified.
115
+ Do you want to download all sequences? [y/n]
116
+ """
117
+ ).lower()
118
+ == "y"
119
+ )
120
+ if not download_all:
121
+ print("Please rerun the command with -l(, --sequence_names) specified.")
122
+ print(
123
+ "Here is the list of available sequences:\n",
124
+ load_sequences_list_from_cdn(args.cdn_file),
125
+ )
126
+ exit(1)
127
+ else:
128
+ print(f"Downloading the following sequences: {args.sequence_names}")
129
+
130
+ downloader = DatasetDownloaderBase(
131
+ cdn_file=args.cdn_file,
132
+ data_types=data_types,
133
+ sequences=args.sequence_names,
134
+ overwrite=args.overwrite,
135
+ )
136
+ downloader.download_data(output_folder=args.output_folder)
137
+
138
+
139
+ if __name__ == "__main__":
140
+ main()
HOT3D/raw/script/official/hot3d/data_downloader/utils.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import json
16
+ import os
17
+ from typing import Dict, Final, List
18
+
19
+
20
+ ###########################################################################
21
+
22
+ # We require AT LEAST ONE of these files for eye_gaze
23
+ MPS_EYE_GAZE_FILES_REQUIRED: Final[List[str]] = [
24
+ "general_eye_gaze.csv",
25
+ "generalized_eye_gaze.csv",
26
+ "personalized_eye_gaze.csv",
27
+ "calibrated_eye_gaze.csv",
28
+ ]
29
+
30
+ MPS_EYE_GAZE_FILES: Final[List[str]] = MPS_EYE_GAZE_FILES_REQUIRED + ["summary.json"]
31
+
32
+ # We requires ALL of these SLAM files
33
+ MPS_SLAM_FILES_REQUIRED: Final[List[str]] = [
34
+ "closed_loop_trajectory.csv",
35
+ "open_loop_trajectory.csv",
36
+ "online_calibration.jsonl",
37
+ "semidense_observations.csv.gz",
38
+ ]
39
+
40
+ MPS_SLAM_FILES: Final[List[str]] = MPS_SLAM_FILES_REQUIRED + [
41
+ "semidense_points.csv.gz",
42
+ "global_points.csv.gz",
43
+ "summary.json",
44
+ ]
45
+
46
+ MPS_FOLDER: Final[str] = "mps"
47
+ MPS_SLAM_FOLDER: Final[str] = "slam"
48
+ MPS_EYE_GAZE_FOLDER: Final[str] = "eye_gaze"
49
+
50
+ MPS_SLAM_GROUP_FILES: Final[Dict[str, List[str]]] = {
51
+ "mps_slam_trajectories": [MPS_SLAM_FILES[0], MPS_SLAM_FILES[1]],
52
+ "mps_slam_calibration": [MPS_SLAM_FILES[2]],
53
+ "mps_slam_points": [
54
+ MPS_SLAM_FILES[3],
55
+ MPS_SLAM_FILES[4],
56
+ MPS_SLAM_FILES[5],
57
+ ],
58
+ "mps_slam_summary": [MPS_SLAM_FILES[6]],
59
+ }
60
+ MPS_DATA_GROUP_FILES: Final[Dict[str, List[str]]] = {
61
+ **MPS_SLAM_GROUP_FILES,
62
+ **{
63
+ "mps_eye_gaze": MPS_EYE_GAZE_FILES,
64
+ },
65
+ }
66
+ ###########################################################################
67
+
68
+
69
+ # Load the list of sequences listed from the cdn file
70
+ def load_sequences_list_from_cdn(cdn_file: str) -> List[str]:
71
+ if not os.path.exists(cdn_file):
72
+ raise Exception("CDN file does not exist")
73
+
74
+ # load sequences from cdn file
75
+ sequences_list = []
76
+ with open(cdn_file, "r") as f:
77
+ cdn_file_data = json.load(f)
78
+ if "sequences" not in cdn_file_data:
79
+ raise Exception("invalid cdn_file, missing key: sequences")
80
+ sequences_list = cdn_file_data["sequences"].keys()
81
+ return sequences_list
82
+
83
+
84
+ # Load a list of data group name to all files included in that data group
85
+ def load_data_groups_from_cdn(cdn_file: str) -> Dict[str, List[str]]:
86
+ if not os.path.exists(cdn_file):
87
+ raise Exception("CDN file does not exist")
88
+
89
+ # load sequence_config from cdn file
90
+ sequence_config = {}
91
+ with open(cdn_file, "r") as f:
92
+ cdn_file_data = json.load(f)
93
+ if "sequence_config" not in cdn_file_data:
94
+ raise Exception("invalid cdn_file, missing key: sequence_config")
95
+ sequence_config = cdn_file_data["sequence_config"]
96
+
97
+ data_groups = {}
98
+
99
+ # load main vrs data group
100
+ if "main" not in sequence_config:
101
+ raise Exception("invalid cdn_file, missing key: sequence_config/main")
102
+ main_data = sequence_config["main"]
103
+ if "recording" not in main_data:
104
+ raise Exception("invalid cdn_file, missing key: sequence_config/main/recording")
105
+
106
+ # Only add "recording" and "mps" data if they are defined as different than None
107
+ if main_data["recording"] != "None":
108
+ data_groups["main_vrs"] = main_data["recording"]
109
+ if main_data["mps"] != "None":
110
+ # next add mps data groups which are predefined
111
+ data_groups.update(MPS_DATA_GROUP_FILES)
112
+
113
+ # load custom data groups for this dataset
114
+ if "data_groups" not in sequence_config:
115
+ raise Exception("invalid cdn_file, missing key: sequence_config/data_groups")
116
+
117
+ for data_group, files in sequence_config["data_groups"].items():
118
+ data_groups[data_group] = files
119
+
120
+ return data_groups