Organize HOT3D and ARCTIC shared scripts
Browse files- ARCTIC/shared-v1.0/script/internal/arctic_object_review.py +37 -38
- ARCTIC/shared-v1.0/script/internal/finalize_arctic_objects_review.py +142 -144
- ARCTIC/shared-v1.0/script/internal/fresh_sequence_common.py +209 -212
- ARCTIC/shared-v1.0/script/internal/pilot_build.py +207 -209
- ARCTIC/shared-v1.0/script/internal/preprocess_fresh_full.py +8 -7
- ARCTIC/shared-v1.0/script/internal/render_full_sequence_review.py +256 -256
- ARCTIC/shared-v1.0/script/internal/review_fresh_sequence_pilots.py +223 -225
- ARCTIC/shared-v1.0/script/internal/sequence_pilot_common.py +51 -53
- HOT3D/shared-v1.0/script/internal/apply_hot3d_qa.py +65 -65
- HOT3D/shared-v1.0/script/internal/fresh_sequence_common.py +209 -212
- HOT3D/shared-v1.0/script/internal/pilot_build.py +207 -209
- HOT3D/shared-v1.0/script/internal/preprocess_fresh_full.py +8 -7
- HOT3D/shared-v1.0/script/internal/render_full_sequence_review.py +256 -256
- HOT3D/shared-v1.0/script/internal/review_fresh_sequence_pilots.py +223 -225
- HOT3D/shared-v1.0/script/internal/sequence_pilot_common.py +51 -53
ARCTIC/shared-v1.0/script/internal/arctic_object_review.py
CHANGED
|
@@ -60,8 +60,8 @@ def prepare(item):
|
|
| 60 |
|
| 61 |
def check_geometry(item,p):
|
| 62 |
seq,sid,oid,seqid,doc,tmp=context(item);m,frames,structure=validate_view(p);cam=m['camera_id'];ref=load(doc/'reference.json')
|
| 63 |
-
with np.load(tmp/'reference.npz') as loaded:a={k:loaded[k] for k in loaded.files}
|
| 64 |
-
ix=np.array([int(f['source_frame_id'])-ref['ioi_offset'] for f in frames]);known=(ix>=0)&(ix<len(a['object_world']))
|
| 65 |
assert [f['source_annotation_index'] for f in frames]==[int(j) if ok else None for j,ok in zip(ix,known)]
|
| 66 |
E=arr(p/'camera/extrinsic.pt');K=arr(p/'camera/intrinsic.pt');op=p/'annotation/object'/oid;meta=load(op/'metainfo.json')
|
| 67 |
vertices=np.array([[float(x) for x in row.split()[1:4]] for row in (p/meta['mesh_ref']).read_text().splitlines() if row.startswith('v ')])
|
|
@@ -162,59 +162,58 @@ def object_page(item):
|
|
| 162 |
|
| 163 |
STYLE='body{font:16px/1.6 system-ui;max-width:1550px;margin:24px auto;padding:0 20px;background:#f2f5f9;color:#162137}section,header{background:white;padding:20px;margin:18px 0;border-radius:10px}video,img{max-width:100%}table{border-collapse:collapse;width:100%}td,th{border:1px solid #ccd3de;padding:8px;text-align:left}.warn{color:#9b4414}a{color:#1265a7}'
|
| 164 |
|
| 165 |
-
def write_object_html(r):
|
| 166 |
-
doc=DOC/r['object'];status=r['agent_visual_review'];cards=''
|
| 167 |
-
review_text=html.escape(status.get('summary',status['status']))
|
| 168 |
-
if status.get('notes'):review_text+='<ul>'+''.join('<li>'+html.escape(n)+'</li>' for n in status['notes'])+'</ul>'
|
| 169 |
for v in r['views']:
|
| 170 |
vv=v['video'];cards+=f'<section><h2>Camera {v["camera_id"]} · {vv["frames"]}帧</h2><video controls preload="metadata" src="{vv["video_ref"]}"></video><p>几何数值检查通过;暗帧候选索引:{r["dark_candidates"][v["camera_id"]]}。有效MANO左右:{vv["mano_valid_counts"]}。</p></section>'
|
| 171 |
page=f'<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>ARCTIC {r["object"]} 完整序列验收</title><style>{STYLE}</style><header><a href="../index.html">全部物体</a><h1>{r["object"]} · {r["sequence"]}</h1><p>固定相机6、{r["camera_frames"]}个相机帧,全部已渲染。最大几何数值差{r["maximum_geometry_error_m"]:.3g}米。<a href="report.json">完整结果</a> · <a href="reference.json">官方对照及反例测试</a></p><p class="warn">代理视觉检查:{html.escape(json.dumps(status,ensure_ascii=False))};用户人工确认待完成,不自动全量或上传。</p><p>左:shared原图;中:源参数诊断投影;右:shared当前valid监督。顶盖紫、底座绿,左手青、右手橙。透视线框显示遮挡面,不是分割。播放30fps仅用于预览,源采集FPS未知。</p><p>暗帧指标仅作候选;除已有laptop曝光规则外,未添加按帧号的人工屏蔽。该序列通过不代表该物体全部序列通过。</p></header>'+cards+'<section><h2>资产及纹理</h2><video controls src="'+r['asset_preview']['video_ref']+'"></video></section><section><h2>视觉抽查对照(不代替完整视频)</h2>'+''.join(f'<a href="{f}"><img src="{f}"></a>' for f in r['contact_sheets'])+'</section><script>document.querySelectorAll("video").forEach(v=>v.addEventListener("play",()=>document.querySelectorAll("video").forEach(o=>{if(o!==v)o.pause()})));</script></html>'
|
| 172 |
-
page=page.replace(html.escape(json.dumps(status,ensure_ascii=False)),review_text)
|
| 173 |
-
page=page.replace('<p class="warn">代理视觉检查:','<div class="warn">代理视觉检查:').replace('用户人工确认待完成,不自动全量或上传。</p>','用户人工确认待完成,不自动全量或上传。</div>')
|
| 174 |
-
(doc/'index.html').write_text(page,encoding='utf-8')
|
| 175 |
|
| 176 |
def overview(selection):
|
| 177 |
rows=[];reports=[]
|
| 178 |
for item in selection['objects']:
|
| 179 |
doc=DOC/item['object'];p=doc/'report.json'
|
| 180 |
if p.exists():
|
| 181 |
-
r=load(p);reports.append(r);state='数值通过;'+('视觉已抽查(见问题记录)' if r['agent_visual_review']['status']=='reviewed_with_findings' else '视觉待检查');count=r['camera_frames'];link=f'<a href="{item["object"]}/index.html">{item["object"]}</a>'
|
| 182 |
else:state='制作中';count='—';link=item['object']
|
| 183 |
rows.append(f'<tr><td>{link}</td><td>{item["sequence"]}</td><td>{count}</td><td>{state}</td></tr>')
|
| 184 |
DOC.mkdir(parents=True,exist_ok=True)
|
| 185 |
-
player=''
|
| 186 |
-
if reports:
|
| 187 |
-
options=''.join(f'<option value="{r["object"]}">{r["object"]} · {r["camera_frames"]}帧</option>' for r in reports)
|
| 188 |
-
player='<section><h2>固定相机6,切换物体</h2><label>物体 <select id="object-picker">'+options+'</select></label> · <a id="object-detail">该物体检查记录与原图对照</a><p id="object-result"></p><video id="object-video" controls preload="metadata" style="width:100%"></video></section>'
|
| 189 |
-
data={r['object']:{'video':r['object']+'/'+r['views'][0]['video']['video_ref'],'summary':r['agent_visual_review'].get('summary','数值通过;视觉检查待完成')} for r in reports}
|
| 190 |
-
player+='<script>const objects='+json.dumps(data,ensure_ascii=False)+';const picker=document.getElementById("object-picker"),video=document.getElementById("object-video");function choose(){const k=picker.value;video.pause();video.src=objects[k].video;document.getElementById("object-detail").href=k+"/index.html";document.getElementById("object-result").textContent=objects[k].summary;video.load();}picker.addEventListener("change",choose);choose();</script>'
|
| 191 |
-
(DOC/'index.html').write_text(f'<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>ARCTIC 11种物体完整序列验收</title><style>{STYLE}</style><header><h1>ARCTIC · 11种物体逐项验收</h1><p>新增组统一采用s06的固定相机6,11种物体各一段完整序列;相机内外参保持一致。<a href="../index.html">原s09 laptop九路相机预览</a>保留。按明显开合幅度选择较短完整序列,不裁切源帧。</p><p>已完成{len(reports)}/11种物体。<a href="selection.json">选择依据</a> · <a href="REPORT.md">验收结论</a> · <a href="report.json">总报告</a></p><p class="warn">自动数值通过≠图像对齐无误≠用户人工通过。未开始全量处理或上传。</p></header>'+player+'<section><table><tr><th>物体/完整视频</th><th>序列</th><th>相机帧数</th><th>检查状态</th></tr>'+''.join(rows)+'</table></section></html>',encoding='utf-8')
|
| 192 |
save(DOC/'selection.json',selection);save(DOC/'report.json',{'scope':'11 whole sequences, fixed subject s06 and fixed static camera 6; original laptop 9-camera group retained separately','completed_objects':len(reports),'expected_objects':11,'objects':[{'object':r['object'],'sequence':r['sequence'],'camera_frames':r['camera_frames'],'maximum_geometry_error_m':r['maximum_geometry_error_m'],'agent_visual_review':r['agent_visual_review']} for r in reports],'human_review':'pending','full_preprocessing_authorized':False,'upload_authorized':False})
|
| 193 |
|
| 194 |
-
def run():
|
| 195 |
selection=load(SELECTION);TMP.mkdir(parents=True,exist_ok=True);DOC.mkdir(parents=True,exist_ok=True)
|
| 196 |
state=load(WORK/'tmp/dataset-work-state.json');state['active']['ARCTIC'].update(stage='pilot_all_objects_rendering',object_review_scope=selection['objects']);save(WORK/'tmp/dataset-work-state.json',state)
|
| 197 |
setup('ARCTIC','eleven_object_review');overview(selection)
|
| 198 |
-
def launch(item):
|
| 199 |
-
seq,sid,oid,seqid,doc,tmp=context(item)
|
| 200 |
-
for cam in selection['cameras']:
|
| 201 |
-
log=tmp/f'worker-{cam}.log'
|
| 202 |
-
with log.open('ab') as f:
|
| 203 |
-
proc=subprocess.run([sys.executable,'-u',str(Path(__file__).resolve()),'worker','--object',oid,'--camera',cam],stdout=f,stderr=subprocess.STDOUT)
|
| 204 |
-
if proc.returncode:raise RuntimeError(f'{oid} camera {cam} failed, see {log}')
|
| 205 |
-
return item
|
| 206 |
-
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
|
| 207 |
-
futures=[]
|
| 208 |
-
for item in selection['objects']:
|
| 209 |
-
prepare(item)
|
| 210 |
-
if (context(item)[4]/'report.json').exists():print('RESUME_OBJECT',item['object'],flush=True);continue
|
| 211 |
-
futures.append(pool.submit(launch,item))
|
| 212 |
-
for future in concurrent.futures.as_completed(futures):
|
| 213 |
-
item=future.result();object_page(item);overview(selection)
|
| 214 |
-
save(TMP/'status.json',{'object':item['object'],'stage':'converting_rendering','completed_views_total':len(list(DOC.glob('*/checks/*-complete.json')))})
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
save(TMP/'status.json',{'stage':'all_objects_rendered_pending_visual_inspection','completed_views_total':len(selection['objects'])*len(selection['cameras'])})
|
| 218 |
print('ALL_OBJECTS_RENDERED',flush=True)
|
| 219 |
|
| 220 |
if __name__=='__main__':
|
|
|
|
| 60 |
|
| 61 |
def check_geometry(item,p):
|
| 62 |
seq,sid,oid,seqid,doc,tmp=context(item);m,frames,structure=validate_view(p);cam=m['camera_id'];ref=load(doc/'reference.json')
|
| 63 |
+
with np.load(tmp/'reference.npz') as loaded:a={k:loaded[k] for k in loaded.files}
|
| 64 |
+
ix=np.array([int(f['source_frame_id'])-ref['ioi_offset'] for f in frames]);known=(ix>=0)&(ix<len(a['object_world']))
|
| 65 |
assert [f['source_annotation_index'] for f in frames]==[int(j) if ok else None for j,ok in zip(ix,known)]
|
| 66 |
E=arr(p/'camera/extrinsic.pt');K=arr(p/'camera/intrinsic.pt');op=p/'annotation/object'/oid;meta=load(op/'metainfo.json')
|
| 67 |
vertices=np.array([[float(x) for x in row.split()[1:4]] for row in (p/meta['mesh_ref']).read_text().splitlines() if row.startswith('v ')])
|
|
|
|
| 162 |
|
| 163 |
STYLE='body{font:16px/1.6 system-ui;max-width:1550px;margin:24px auto;padding:0 20px;background:#f2f5f9;color:#162137}section,header{background:white;padding:20px;margin:18px 0;border-radius:10px}video,img{max-width:100%}table{border-collapse:collapse;width:100%}td,th{border:1px solid #ccd3de;padding:8px;text-align:left}.warn{color:#9b4414}a{color:#1265a7}'
|
| 164 |
|
| 165 |
+
def write_object_html(r):
|
| 166 |
+
doc=DOC/r['object'];status=r['agent_visual_review'];cards=''
|
| 167 |
+
review_text=html.escape(status.get('summary',status['status']))
|
| 168 |
+
if status.get('notes'):review_text+='<ul>'+''.join('<li>'+html.escape(n)+'</li>' for n in status['notes'])+'</ul>'
|
| 169 |
for v in r['views']:
|
| 170 |
vv=v['video'];cards+=f'<section><h2>Camera {v["camera_id"]} · {vv["frames"]}帧</h2><video controls preload="metadata" src="{vv["video_ref"]}"></video><p>几何数值检查通过;暗帧候选索引:{r["dark_candidates"][v["camera_id"]]}。有效MANO左右:{vv["mano_valid_counts"]}。</p></section>'
|
| 171 |
page=f'<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>ARCTIC {r["object"]} 完整序列验收</title><style>{STYLE}</style><header><a href="../index.html">全部物体</a><h1>{r["object"]} · {r["sequence"]}</h1><p>固定相机6、{r["camera_frames"]}个相机帧,全部已渲染。最大几何数值差{r["maximum_geometry_error_m"]:.3g}米。<a href="report.json">完整结果</a> · <a href="reference.json">官方对照及反例测试</a></p><p class="warn">代理视觉检查:{html.escape(json.dumps(status,ensure_ascii=False))};用户人工确认待完成,不自动全量或上传。</p><p>左:shared原图;中:源参数诊断投影;右:shared当前valid监督。顶盖紫、底座绿,左手青、右手橙。透视线框显示遮挡面,不是分割。播放30fps仅用于预览,源采集FPS未知。</p><p>暗帧指标仅作候选;除已有laptop曝光规则外,未添加按帧号的人工屏蔽。该序列通过不代表该物体全部序列通过。</p></header>'+cards+'<section><h2>资产及纹理</h2><video controls src="'+r['asset_preview']['video_ref']+'"></video></section><section><h2>视觉抽查对照(不代替完整视频)</h2>'+''.join(f'<a href="{f}"><img src="{f}"></a>' for f in r['contact_sheets'])+'</section><script>document.querySelectorAll("video").forEach(v=>v.addEventListener("play",()=>document.querySelectorAll("video").forEach(o=>{if(o!==v)o.pause()})));</script></html>'
|
| 172 |
+
page=page.replace(html.escape(json.dumps(status,ensure_ascii=False)),review_text)
|
| 173 |
+
page=page.replace('<p class="warn">代理视觉检查:','<div class="warn">代理视觉检查:').replace('用户人工确认待完成,不自动全量或上传。</p>','用户人工确认待完成,不自动全量或上传。</div>')
|
| 174 |
+
(doc/'index.html').write_text(page,encoding='utf-8')
|
| 175 |
|
| 176 |
def overview(selection):
|
| 177 |
rows=[];reports=[]
|
| 178 |
for item in selection['objects']:
|
| 179 |
doc=DOC/item['object'];p=doc/'report.json'
|
| 180 |
if p.exists():
|
| 181 |
+
r=load(p);reports.append(r);state='数值通过;'+('视觉已抽查(见问题记录)' if r['agent_visual_review']['status']=='reviewed_with_findings' else '视觉待检查');count=r['camera_frames'];link=f'<a href="{item["object"]}/index.html">{item["object"]}</a>'
|
| 182 |
else:state='制作中';count='—';link=item['object']
|
| 183 |
rows.append(f'<tr><td>{link}</td><td>{item["sequence"]}</td><td>{count}</td><td>{state}</td></tr>')
|
| 184 |
DOC.mkdir(parents=True,exist_ok=True)
|
| 185 |
+
player=''
|
| 186 |
+
if reports:
|
| 187 |
+
options=''.join(f'<option value="{r["object"]}">{r["object"]} · {r["camera_frames"]}帧</option>' for r in reports)
|
| 188 |
+
player='<section><h2>固定相机6,切换物体</h2><label>物体 <select id="object-picker">'+options+'</select></label> · <a id="object-detail">该物体检查记录与原图对照</a><p id="object-result"></p><video id="object-video" controls preload="metadata" style="width:100%"></video></section>'
|
| 189 |
+
data={r['object']:{'video':r['object']+'/'+r['views'][0]['video']['video_ref'],'summary':r['agent_visual_review'].get('summary','数值通过;视觉检查待完成')} for r in reports}
|
| 190 |
+
player+='<script>const objects='+json.dumps(data,ensure_ascii=False)+';const picker=document.getElementById("object-picker"),video=document.getElementById("object-video");function choose(){const k=picker.value;video.pause();video.src=objects[k].video;document.getElementById("object-detail").href=k+"/index.html";document.getElementById("object-result").textContent=objects[k].summary;video.load();}picker.addEventListener("change",choose);choose();</script>'
|
| 191 |
+
(DOC/'index.html').write_text(f'<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>ARCTIC 11种物体完整序列验收</title><style>{STYLE}</style><header><h1>ARCTIC · 11种物体逐项验收</h1><p>新增组统一采用s06的固定相机6,11种物体各一段完整序列;相机内外参保持一致。<a href="../index.html">原s09 laptop九路相机预览</a>保留。按明显开合幅度选择较短完整序列,不裁切源帧。</p><p>已完成{len(reports)}/11种物体。<a href="selection.json">选择依据</a> · <a href="REPORT.md">验收结论</a> · <a href="report.json">总报告</a></p><p class="warn">自动数值通过≠图像对齐无误≠用户人工通过。未开始全量处理或上传。</p></header>'+player+'<section><table><tr><th>物体/完整视频</th><th>序列</th><th>相机帧数</th><th>检查状态</th></tr>'+''.join(rows)+'</table></section></html>',encoding='utf-8')
|
| 192 |
save(DOC/'selection.json',selection);save(DOC/'report.json',{'scope':'11 whole sequences, fixed subject s06 and fixed static camera 6; original laptop 9-camera group retained separately','completed_objects':len(reports),'expected_objects':11,'objects':[{'object':r['object'],'sequence':r['sequence'],'camera_frames':r['camera_frames'],'maximum_geometry_error_m':r['maximum_geometry_error_m'],'agent_visual_review':r['agent_visual_review']} for r in reports],'human_review':'pending','full_preprocessing_authorized':False,'upload_authorized':False})
|
| 193 |
|
| 194 |
+
def run():
|
| 195 |
selection=load(SELECTION);TMP.mkdir(parents=True,exist_ok=True);DOC.mkdir(parents=True,exist_ok=True)
|
| 196 |
state=load(WORK/'tmp/dataset-work-state.json');state['active']['ARCTIC'].update(stage='pilot_all_objects_rendering',object_review_scope=selection['objects']);save(WORK/'tmp/dataset-work-state.json',state)
|
| 197 |
setup('ARCTIC','eleven_object_review');overview(selection)
|
| 198 |
+
def launch(item):
|
| 199 |
+
seq,sid,oid,seqid,doc,tmp=context(item)
|
| 200 |
+
for cam in selection['cameras']:
|
| 201 |
+
log=tmp/f'worker-{cam}.log'
|
| 202 |
+
with log.open('ab') as f:
|
| 203 |
+
proc=subprocess.run([sys.executable,'-u',str(Path(__file__).resolve()),'worker','--object',oid,'--camera',cam],stdout=f,stderr=subprocess.STDOUT)
|
| 204 |
+
if proc.returncode:raise RuntimeError(f'{oid} camera {cam} failed, see {log}')
|
| 205 |
+
return item
|
| 206 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
|
| 207 |
+
futures=[]
|
| 208 |
+
for item in selection['objects']:
|
| 209 |
+
prepare(item)
|
| 210 |
+
if (context(item)[4]/'report.json').exists():print('RESUME_OBJECT',item['object'],flush=True);continue
|
| 211 |
+
futures.append(pool.submit(launch,item))
|
| 212 |
+
for future in concurrent.futures.as_completed(futures):
|
| 213 |
+
item=future.result();object_page(item);overview(selection)
|
| 214 |
+
save(TMP/'status.json',{'object':item['object'],'stage':'converting_rendering','completed_views_total':len(list(DOC.glob('*/checks/*-complete.json')))})
|
| 215 |
+
# Do not repopulate the organized script root while rendering review artifacts.
|
| 216 |
+
save(TMP/'status.json',{'stage':'all_objects_rendered_pending_visual_inspection','completed_views_total':len(selection['objects'])*len(selection['cameras'])})
|
|
|
|
| 217 |
print('ALL_OBJECTS_RENDERED',flush=True)
|
| 218 |
|
| 219 |
if __name__=='__main__':
|
ARCTIC/shared-v1.0/script/internal/finalize_arctic_objects_review.py
CHANGED
|
@@ -1,144 +1,142 @@
|
|
| 1 |
-
"""Assemble evidence after the bounded eleven-object review; never authorizes production."""
|
| 2 |
-
from arctic_object_review import *
|
| 3 |
-
from html.parser import HTMLParser
|
| 4 |
-
from urllib.parse import unquote, urlsplit
|
| 5 |
-
|
| 6 |
-
NOTES=WORK/'tmp/arctic-object-visual-review.json'
|
| 7 |
-
|
| 8 |
-
def asset_contacts():
|
| 9 |
-
selection=load(SELECTION);outputs=[]
|
| 10 |
-
for item in selection['objects']:
|
| 11 |
-
_,_,oid,seqid,doc,tmp=context(item)
|
| 12 |
-
video=doc/'assets'/f'{oid}.mp4'
|
| 13 |
-
if not video.exists():continue
|
| 14 |
-
asset=asset_preview(OUT/'data'/seqid/'6'/'annotation/object'/oid,video)
|
| 15 |
-
r=load(doc/'report.json');r['asset_preview']=asset;save(doc/'report.json',r)
|
| 16 |
-
target=tmp/'asset-angles.jpg'
|
| 17 |
-
command([FF,'-v','error','-y','-threads','2','-i',video,'-vf',
|
| 18 |
-
'select=eq(n\\,12)+eq(n\\,36)+eq(n\\,60),scale=480:-1,tile=3x1',
|
| 19 |
-
'-frames:v','1','-threads','2',target])
|
| 20 |
-
outputs.append((oid,target))
|
| 21 |
-
for group,start in enumerate(range(0,len(outputs),6),1):
|
| 22 |
-
chosen=outputs[start:start+6];images=[Image.open(p).convert('RGB') for _,p in chosen]
|
| 23 |
-
height=max(im.height for im in images)+32
|
| 24 |
-
sheet=Image.new('RGB',(1440,height*len(images)),(20,20,20));draw=ImageDraw.Draw(sheet)
|
| 25 |
-
for i,((oid,_),im) in enumerate(zip(chosen,images)):
|
| 26 |
-
draw.text((10,i*height+6),f'{oid}: turntable frames 12 / 36 / 60',fill='white')
|
| 27 |
-
sheet.paste(im,(0,i*height+32))
|
| 28 |
-
target=DOC/f'assets-contact-{group}.jpg';sheet.save(target,quality=94);print(target,flush=True)
|
| 29 |
-
|
| 30 |
-
class Links(HTMLParser):
|
| 31 |
-
def __init__(self):super().__init__();self.links=[]
|
| 32 |
-
def handle_starttag(self,tag,attrs):
|
| 33 |
-
for k,v in attrs:
|
| 34 |
-
if k in ('href','src','poster') and v:self.links.append(v)
|
| 35 |
-
|
| 36 |
-
def finalize():
|
| 37 |
-
selection=load(SELECTION);notes=json.loads(NOTES.read_text(encoding='utf-8-sig'))
|
| 38 |
-
assert set(notes)=={x['object'] for x in selection['objects']}
|
| 39 |
-
assert load(TMP/'status.json')['stage'] in ('all_objects_rendered_pending_visual_inspection','review_complete_pending_user')
|
| 40 |
-
reports=[];cameras=[];extra=[];old=load(DOC.parent/'report.json')
|
| 41 |
-
for item in selection['objects']:
|
| 42 |
-
seq,sid,oid,seqid,doc,tmp=context(item);r=load(doc/'report.json');p=OUT/'data'/seqid/'6'
|
| 43 |
-
assert r['reference']['ioi_offset']==1 and r['camera_frames']==r['reference']['annotation_frames']+1
|
| 44 |
-
assert notes[oid]['status']=='reviewed_with_findings' and notes[oid].get('asset_visual_review')
|
| 45 |
-
r['agent_visual_review']=notes[oid]
|
| 46 |
-
r['agent_visual_review']['inspected_frame_indices']=r['views'][0]['visual_sample_indices']
|
| 47 |
-
r['agent_visual_review']['entire_video_watched']=False
|
| 48 |
-
r['agent_visual_review']['sample_method']='beginning/end, uniform temporal samples, joint-angle extremes; exact indices recorded'
|
| 49 |
-
K=arr(p/'camera/intrinsic.pt');E=arr(p/'camera/extrinsic.pt')
|
| 50 |
-
assert np.array_equal(K,np.broadcast_to(K[0],K.shape)) and np.array_equal(E,np.broadcast_to(E[0],E.shape))
|
| 51 |
-
cameras.append((K[0],E[0]))
|
| 52 |
-
m=load(p/'metainfo.json');assert not m['components']['mano'].get('valid_policy',{}).get('local_excluded_frame_indices')
|
| 53 |
-
m['sampling']['selection']='Every released image of this selected camera in the complete official sequence ZIP; boundary images without annotations retained'
|
| 54 |
-
save(p/'metainfo.json',m)
|
| 55 |
-
view=r['views'][0];v=doc/view['video']['video_ref'];assert digest(v)==view['video']['video_sha256']
|
| 56 |
-
decoded=framehash(['-i',str(v)]);assert len(decoded)==r['camera_frames']
|
| 57 |
-
asset=doc/r['asset_preview']['video_ref'];assert len(framehash(['-i',str(asset)]))==72
|
| 58 |
-
texture_checks=[]
|
| 59 |
-
with zipfile.ZipFile(BASE/'raw/data/meta.zip') as z:
|
| 60 |
-
for f in (p/f'annotation/object/{oid}/assets').rglob('*'):
|
| 61 |
-
if f.suffix.lower() in ('.mtl','.jpg','.jpeg','.png'):
|
| 62 |
-
source=z.read(f'meta/object_vtemplates/{oid}/'+f.name)
|
| 63 |
-
assert f.read_bytes()==source
|
| 64 |
-
texture_checks.append({'file':f.name,'sha256':digest(f),'raw_bytes_equal':True})
|
| 65 |
-
r['delivery_checks']={'preview_fully_decoded_frames':len(decoded),'preview_sha256':digest(v),
|
| 66 |
-
'asset_preview_frames':72,'asset_video_sha256':digest(asset),'texture_and_material_files':texture_checks}
|
| 67 |
-
save(doc/'report.json',r);write_object_html(r);reports.append(r)
|
| 68 |
-
extra.append({'object':oid,'preview_frames':len(decoded),'asset_frames':72,'texture_files_checked':len(texture_checks)})
|
| 69 |
-
print('FINAL_CHECK',oid,len(decoded),flush=True)
|
| 70 |
-
assert all(np.array_equal(k,cameras[0][0]) and np.array_equal(e,cameras[0][1]) for k,e in cameras)
|
| 71 |
-
oldviews=old['full_video_views'];assert len(oldviews)==9
|
| 72 |
-
for v in oldviews:assert digest(DOC.parent/v['video_ref'])==v['video_sha256']
|
| 73 |
-
# The same canonical laptop asset is shared by both review groups; fix its
|
| 74 |
-
# original report's texture preview too, without touching its nine frame videos.
|
| 75 |
-
laptop=next(r for r in reports if r['object']=='laptop')
|
| 76 |
-
shutil.copyfile(DOC/'laptop'/laptop['asset_preview']['video_ref'],DOC.parent/'assets/laptop.mp4')
|
| 77 |
-
old['asset_previews']=[laptop['asset_preview']]
|
| 78 |
-
overview(selection)
|
| 79 |
-
total=sum(r['camera_frames'] for r in reports);n=sum(len(r['views'][0]['visual_sample_indices']) for r in reports)
|
| 80 |
-
maximum=max(r['maximum_geometry_error_m'] for r in reports)
|
| 81 |
-
rows='\n'.join(f'| [{r["object"]}]({r["object"]}/index.html) | {r["sequence"]} | {r["camera_frames"]} | {r["maximum_geometry_error_m"]:.3g} | {r["agent_visual_review"]["summary"]} |' for r in reports)
|
| 82 |
-
text=f'''# ARCTIC 11种物体验收结果
|
| 83 |
-
|
| 84 |
-
[固定相机切换物体](index.html) · [原laptop九视角](../index.html) · [方法](README.md)
|
| 85 |
-
|
| 86 |
-
新增组:s06、静态相机6,11个完整序列,共{total}帧;内外参逐帧恒定且在11个物体间完全一致。原s09/laptop_use_03九视角视频摘要未变。
|
| 87 |
-
|
| 88 |
-
**转换数值检查通过;源图像和标注质量仍有已知问题,用户确认待完成。** 不据此启动全量处理或上传。
|
| 89 |
-
|
| 90 |
-
| 物体 | 完整序列 | 帧数 | 最大几何差/m | 视觉抽查结果 |
|
| 91 |
-
|---|---|---:|---:|---|
|
| 92 |
-
{rows}
|
| 93 |
-
|
| 94 |
-
## 检查边界
|
| 95 |
-
|
| 96 |
-
- 数值:全部有标注帧、全部物体顶点/关键点和双手MANO几何,对照raw及固定官方实现;最大差{maximum:.6g}m,容差2e-5m。交换部件、反转关节角、误用毫米的反例在11个物体上均被检出。
|
| 97 |
-
- 媒体:全部原JPEG包和统一解码RGB逐帧一致;完整预览视频再次全部解码,无缺帧/解码错误。MP4仅用于doc展示,不替代原码流MKV。
|
| 98 |
-
- 视觉:实际查看{n}个原图/投影对照时刻(每段的起止、均匀样本及开合极值),检查资产旋转预览的3个方位。完整视频已全部渲染;代理未逐帧人工观看全部视频。
|
| 99 |
-
- 模态:MANO、物体姿态/铰接/32个模板关键点、内外参、同步索引、RGB、资产纹理、valid均有检查/展示。未提供的深度、像素分割、接触、源visibility没有伪造。
|
| 100 |
-
- 开头暗帧与局部手指贴合误差如实记录;本轮没有修改按帧号的排除mask。末帧无源动捕标注是源范围边界,RGB保留、几何valid=false。
|
| 101 |
-
- 数值忠实不证明原标注准确;本次检查11种物体各一段,不能推导其它所有序列质量通过。
|
| 102 |
-
|
| 103 |
-
[资产预览抽查1](assets-contact-1.jpg) · [资产预览抽查2](assets-contact-2.jpg)
|
| 104 |
-
'''
|
| 105 |
-
(DOC/'REPORT.md').write_text(text,encoding='utf-8')
|
| 106 |
-
summary=load(DOC/'report.json');summary.update(camera_parameter_equality='exact_across_all_11_views_and_all_frames',
|
| 107 |
-
total_frames=total,visually_inspected_frame_count=n,maximum_geometry_error_m=maximum,
|
| 108 |
-
original_nine_camera_videos_unchanged=True,delivery_checks=extra,known_issues=['Source dark opening frames','Residual hand-to-image fit differences','Source annotation absent on final image'],
|
| 109 |
-
interpretation='All-frame faithful conversion passed; sampled visual review has findings; source quality and human acceptance not asserted')
|
| 110 |
-
save(DOC/'report.json',summary)
|
| 111 |
-
# Add navigation to the original page without rebuilding or replacing its nine videos.
|
| 112 |
-
home=DOC.parent/'index.html';body=home.read_text(encoding='utf-8');marker='id="eleven-object-review"'
|
| 113 |
-
if marker not in body:
|
| 114 |
-
body=body.replace('</header>','<p id="eleven-object-review"><strong>新增:</strong><a href="objects/index.html">固定相机6,切换11种物体的完整序列预览</a> · <a href="objects/REPORT.md">逐物体验收结果</a></p></header>',1)
|
| 115 |
-
home.write_text(body,encoding='utf-8')
|
| 116 |
-
mapping=OUT/'doc/RAW_TO_SHARED.md';body=mapping.read_text(encoding='utf-8')
|
| 117 |
-
if '## 新增固定相机物体组' not in body:
|
| 118 |
-
body+='\n## 新增固定相机物体组\n\n在原s09/laptop_use_03九视角之外,新增s06相机6的11物体完整序列。字段规则相同,具体选择、来源、帧数和校验见[逐物体报告](validation/objects/REPORT.md)及[来源摘要](validation/objects/source-manifest.json)。本组ioi_offset=1,图像编号减1对应标注索引;末图超出标注范围,保留RGB且几何valid=false。本组前两帧暗图只记录,没有套用旧s09曝光排除。仍非全量验收。\n'
|
| 119 |
-
mapping.write_text(body,encoding='utf-8')
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
parts
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
save(
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
if
|
| 143 |
-
parser=argparse.ArgumentParser();parser.add_argument('mode',choices=['assets','finalize']);args=parser.parse_args()
|
| 144 |
-
asset_contacts() if args.mode=='assets' else finalize()
|
|
|
|
| 1 |
+
"""Assemble evidence after the bounded eleven-object review; never authorizes production."""
|
| 2 |
+
from arctic_object_review import *
|
| 3 |
+
from html.parser import HTMLParser
|
| 4 |
+
from urllib.parse import unquote, urlsplit
|
| 5 |
+
|
| 6 |
+
NOTES=WORK/'tmp/arctic-object-visual-review.json'
|
| 7 |
+
|
| 8 |
+
def asset_contacts():
|
| 9 |
+
selection=load(SELECTION);outputs=[]
|
| 10 |
+
for item in selection['objects']:
|
| 11 |
+
_,_,oid,seqid,doc,tmp=context(item)
|
| 12 |
+
video=doc/'assets'/f'{oid}.mp4'
|
| 13 |
+
if not video.exists():continue
|
| 14 |
+
asset=asset_preview(OUT/'data'/seqid/'6'/'annotation/object'/oid,video)
|
| 15 |
+
r=load(doc/'report.json');r['asset_preview']=asset;save(doc/'report.json',r)
|
| 16 |
+
target=tmp/'asset-angles.jpg'
|
| 17 |
+
command([FF,'-v','error','-y','-threads','2','-i',video,'-vf',
|
| 18 |
+
'select=eq(n\\,12)+eq(n\\,36)+eq(n\\,60),scale=480:-1,tile=3x1',
|
| 19 |
+
'-frames:v','1','-threads','2',target])
|
| 20 |
+
outputs.append((oid,target))
|
| 21 |
+
for group,start in enumerate(range(0,len(outputs),6),1):
|
| 22 |
+
chosen=outputs[start:start+6];images=[Image.open(p).convert('RGB') for _,p in chosen]
|
| 23 |
+
height=max(im.height for im in images)+32
|
| 24 |
+
sheet=Image.new('RGB',(1440,height*len(images)),(20,20,20));draw=ImageDraw.Draw(sheet)
|
| 25 |
+
for i,((oid,_),im) in enumerate(zip(chosen,images)):
|
| 26 |
+
draw.text((10,i*height+6),f'{oid}: turntable frames 12 / 36 / 60',fill='white')
|
| 27 |
+
sheet.paste(im,(0,i*height+32))
|
| 28 |
+
target=DOC/f'assets-contact-{group}.jpg';sheet.save(target,quality=94);print(target,flush=True)
|
| 29 |
+
|
| 30 |
+
class Links(HTMLParser):
|
| 31 |
+
def __init__(self):super().__init__();self.links=[]
|
| 32 |
+
def handle_starttag(self,tag,attrs):
|
| 33 |
+
for k,v in attrs:
|
| 34 |
+
if k in ('href','src','poster') and v:self.links.append(v)
|
| 35 |
+
|
| 36 |
+
def finalize():
|
| 37 |
+
selection=load(SELECTION);notes=json.loads(NOTES.read_text(encoding='utf-8-sig'))
|
| 38 |
+
assert set(notes)=={x['object'] for x in selection['objects']}
|
| 39 |
+
assert load(TMP/'status.json')['stage'] in ('all_objects_rendered_pending_visual_inspection','review_complete_pending_user')
|
| 40 |
+
reports=[];cameras=[];extra=[];old=load(DOC.parent/'report.json')
|
| 41 |
+
for item in selection['objects']:
|
| 42 |
+
seq,sid,oid,seqid,doc,tmp=context(item);r=load(doc/'report.json');p=OUT/'data'/seqid/'6'
|
| 43 |
+
assert r['reference']['ioi_offset']==1 and r['camera_frames']==r['reference']['annotation_frames']+1
|
| 44 |
+
assert notes[oid]['status']=='reviewed_with_findings' and notes[oid].get('asset_visual_review')
|
| 45 |
+
r['agent_visual_review']=notes[oid]
|
| 46 |
+
r['agent_visual_review']['inspected_frame_indices']=r['views'][0]['visual_sample_indices']
|
| 47 |
+
r['agent_visual_review']['entire_video_watched']=False
|
| 48 |
+
r['agent_visual_review']['sample_method']='beginning/end, uniform temporal samples, joint-angle extremes; exact indices recorded'
|
| 49 |
+
K=arr(p/'camera/intrinsic.pt');E=arr(p/'camera/extrinsic.pt')
|
| 50 |
+
assert np.array_equal(K,np.broadcast_to(K[0],K.shape)) and np.array_equal(E,np.broadcast_to(E[0],E.shape))
|
| 51 |
+
cameras.append((K[0],E[0]))
|
| 52 |
+
m=load(p/'metainfo.json');assert not m['components']['mano'].get('valid_policy',{}).get('local_excluded_frame_indices')
|
| 53 |
+
m['sampling']['selection']='Every released image of this selected camera in the complete official sequence ZIP; boundary images without annotations retained'
|
| 54 |
+
save(p/'metainfo.json',m)
|
| 55 |
+
view=r['views'][0];v=doc/view['video']['video_ref'];assert digest(v)==view['video']['video_sha256']
|
| 56 |
+
decoded=framehash(['-i',str(v)]);assert len(decoded)==r['camera_frames']
|
| 57 |
+
asset=doc/r['asset_preview']['video_ref'];assert len(framehash(['-i',str(asset)]))==72
|
| 58 |
+
texture_checks=[]
|
| 59 |
+
with zipfile.ZipFile(BASE/'raw/data/meta.zip') as z:
|
| 60 |
+
for f in (p/f'annotation/object/{oid}/assets').rglob('*'):
|
| 61 |
+
if f.suffix.lower() in ('.mtl','.jpg','.jpeg','.png'):
|
| 62 |
+
source=z.read(f'meta/object_vtemplates/{oid}/'+f.name)
|
| 63 |
+
assert f.read_bytes()==source
|
| 64 |
+
texture_checks.append({'file':f.name,'sha256':digest(f),'raw_bytes_equal':True})
|
| 65 |
+
r['delivery_checks']={'preview_fully_decoded_frames':len(decoded),'preview_sha256':digest(v),
|
| 66 |
+
'asset_preview_frames':72,'asset_video_sha256':digest(asset),'texture_and_material_files':texture_checks}
|
| 67 |
+
save(doc/'report.json',r);write_object_html(r);reports.append(r)
|
| 68 |
+
extra.append({'object':oid,'preview_frames':len(decoded),'asset_frames':72,'texture_files_checked':len(texture_checks)})
|
| 69 |
+
print('FINAL_CHECK',oid,len(decoded),flush=True)
|
| 70 |
+
assert all(np.array_equal(k,cameras[0][0]) and np.array_equal(e,cameras[0][1]) for k,e in cameras)
|
| 71 |
+
oldviews=old['full_video_views'];assert len(oldviews)==9
|
| 72 |
+
for v in oldviews:assert digest(DOC.parent/v['video_ref'])==v['video_sha256']
|
| 73 |
+
# The same canonical laptop asset is shared by both review groups; fix its
|
| 74 |
+
# original report's texture preview too, without touching its nine frame videos.
|
| 75 |
+
laptop=next(r for r in reports if r['object']=='laptop')
|
| 76 |
+
shutil.copyfile(DOC/'laptop'/laptop['asset_preview']['video_ref'],DOC.parent/'assets/laptop.mp4')
|
| 77 |
+
old['asset_previews']=[laptop['asset_preview']]
|
| 78 |
+
overview(selection)
|
| 79 |
+
total=sum(r['camera_frames'] for r in reports);n=sum(len(r['views'][0]['visual_sample_indices']) for r in reports)
|
| 80 |
+
maximum=max(r['maximum_geometry_error_m'] for r in reports)
|
| 81 |
+
rows='\n'.join(f'| [{r["object"]}]({r["object"]}/index.html) | {r["sequence"]} | {r["camera_frames"]} | {r["maximum_geometry_error_m"]:.3g} | {r["agent_visual_review"]["summary"]} |' for r in reports)
|
| 82 |
+
text=f'''# ARCTIC 11种物体验收结果
|
| 83 |
+
|
| 84 |
+
[固定相机切换物体](index.html) · [原laptop九视角](../index.html) · [方法](README.md)
|
| 85 |
+
|
| 86 |
+
新增组:s06、静态相机6,11个完整序列,共{total}帧;内外参逐帧恒定且在11个物体间完全一致。原s09/laptop_use_03九视角视频摘要未变。
|
| 87 |
+
|
| 88 |
+
**转换数值检查通过;源图像和标注质量仍有已知问题,用户确认待完成。** 不据此启动全量处理或上传。
|
| 89 |
+
|
| 90 |
+
| 物体 | 完整序列 | 帧数 | 最大几何差/m | 视觉抽查结果 |
|
| 91 |
+
|---|---|---:|---:|---|
|
| 92 |
+
{rows}
|
| 93 |
+
|
| 94 |
+
## 检查边界
|
| 95 |
+
|
| 96 |
+
- 数值:全部有标注帧、全部物体顶点/关键点和双手MANO几何,对照raw及固定官方实现;最大差{maximum:.6g}m,容差2e-5m。交换部件、反转关节角、误用毫米的反例在11个物体上均被检出。
|
| 97 |
+
- 媒体:全部原JPEG包和统一解码RGB逐帧一致;完整预览视频再次全部解码,无缺帧/解码错误。MP4仅用于doc展示,不替代原码流MKV。
|
| 98 |
+
- 视觉:实际查看{n}个原图/投影对照时刻(每段的起止、均匀样本及开合极值),检查资产旋转预览的3个方位。完整视频已全部渲染;代理未逐帧人工观看全部视频。
|
| 99 |
+
- 模态:MANO、物体姿态/铰接/32个模板关键点、内外参、同步索引、RGB、资产纹理、valid均有检查/展示。未提供的深度、像素分割、接触、源visibility没有伪造。
|
| 100 |
+
- 开头暗帧与局部手指贴合误差如实记录;本轮没有修改按帧号的排除mask。末帧无源动捕标注是源范围边界,RGB保留、几何valid=false。
|
| 101 |
+
- 数值忠实不证明原标注准确;本次检查11种物体各一段,不能推导其它所有序列质量通过。
|
| 102 |
+
|
| 103 |
+
[资产预览抽查1](assets-contact-1.jpg) · [资产预览抽查2](assets-contact-2.jpg)
|
| 104 |
+
'''
|
| 105 |
+
(DOC/'REPORT.md').write_text(text,encoding='utf-8')
|
| 106 |
+
summary=load(DOC/'report.json');summary.update(camera_parameter_equality='exact_across_all_11_views_and_all_frames',
|
| 107 |
+
total_frames=total,visually_inspected_frame_count=n,maximum_geometry_error_m=maximum,
|
| 108 |
+
original_nine_camera_videos_unchanged=True,delivery_checks=extra,known_issues=['Source dark opening frames','Residual hand-to-image fit differences','Source annotation absent on final image'],
|
| 109 |
+
interpretation='All-frame faithful conversion passed; sampled visual review has findings; source quality and human acceptance not asserted')
|
| 110 |
+
save(DOC/'report.json',summary)
|
| 111 |
+
# Add navigation to the original page without rebuilding or replacing its nine videos.
|
| 112 |
+
home=DOC.parent/'index.html';body=home.read_text(encoding='utf-8');marker='id="eleven-object-review"'
|
| 113 |
+
if marker not in body:
|
| 114 |
+
body=body.replace('</header>','<p id="eleven-object-review"><strong>新增:</strong><a href="objects/index.html">固定相机6,切换11种物体的完整序列预览</a> · <a href="objects/REPORT.md">逐物体验收结果</a></p></header>',1)
|
| 115 |
+
home.write_text(body,encoding='utf-8')
|
| 116 |
+
mapping=OUT/'doc/RAW_TO_SHARED.md';body=mapping.read_text(encoding='utf-8')
|
| 117 |
+
if '## 新增固定相机物体组' not in body:
|
| 118 |
+
body+='\n## 新增固定相机物体组\n\n在原s09/laptop_use_03九视角之外,新增s06相机6的11物体完整序列。字段规则相同,具体选择、来源、帧数和校验见[逐物体报告](validation/objects/REPORT.md)及[来源摘要](validation/objects/source-manifest.json)。本组ioi_offset=1,图像编号减1对应标注索引;末图超出标注范围,保留RGB且几何valid=false。本组前两帧暗图只记录,没有套用旧s09曝光排除。仍非全量验收。\n'
|
| 119 |
+
mapping.write_text(body,encoding='utf-8')
|
| 120 |
+
manifest=[{'path':p.relative_to(OUT).as_posix(),'sha256':digest(p)} for p in sorted((OUT/'script').rglob('*.py'))]
|
| 121 |
+
save(DOC/'script-manifest.json',manifest)
|
| 122 |
+
old.setdefault('previous_script_manifest_before_object_review',old['script_manifest']);old['script_manifest']=manifest
|
| 123 |
+
old['additional_fixed_camera_group']={'report_ref':'objects/report.json','sequence_count':11,'camera_id':'6','subject_id':'s06','human_review':'pending'}
|
| 124 |
+
save(DOC.parent/'report.json',old)
|
| 125 |
+
missing=[]
|
| 126 |
+
for page in [home,*DOC.rglob('*.html')]:
|
| 127 |
+
parser=Links();parser.feed(page.read_text(encoding='utf-8'))
|
| 128 |
+
for url in parser.links:
|
| 129 |
+
parts=urlsplit(url)
|
| 130 |
+
if parts.scheme or not parts.path:continue
|
| 131 |
+
if not (page.parent/unquote(parts.path)).exists():missing.append([str(page),url])
|
| 132 |
+
assert not missing,missing
|
| 133 |
+
artifacts=[{'path':p.relative_to(DOC).as_posix(),'size':p.stat().st_size,'sha256':digest(p)} for p in sorted(DOC.rglob('*')) if p.is_file() and p.name!='artifact-manifest.json']
|
| 134 |
+
save(DOC/'artifact-manifest.json',{'files':artifacts,'offline_html_links':'passed','log_files_in_report':False})
|
| 135 |
+
status={'stage':'review_complete_pending_user','completed_views_total':11,'human_review':'pending','report':str(DOC/'index.html'),'full_preprocessing_authorized':False,'upload_authorized':False}
|
| 136 |
+
save(TMP/'status.json',status);save(DOC.parent/'status.json',status)
|
| 137 |
+
state=load(WORK/'tmp/dataset-work-state.json');state['active']['ARCTIC'].update(stage='pilot_two_group_review_awaiting_human_review',object_review_report=str(DOC/'index.html'),object_review_completed=11);save(WORK/'tmp/dataset-work-state.json',state)
|
| 138 |
+
print('FINALIZED',total,n,maximum,flush=True)
|
| 139 |
+
|
| 140 |
+
if __name__=='__main__':
|
| 141 |
+
parser=argparse.ArgumentParser();parser.add_argument('mode',choices=['assets','finalize']);args=parser.parse_args()
|
| 142 |
+
asset_contacts() if args.mode=='assets' else finalize()
|
|
|
|
|
|
ARCTIC/shared-v1.0/script/internal/fresh_sequence_common.py
CHANGED
|
@@ -1,212 +1,209 @@
|
|
| 1 |
-
"""Helpers for the fresh ARCTIC/HOT3D whole-sequence v1.0 pilots.
|
| 2 |
-
|
| 3 |
-
Original archives are read only. Temporary extraction is outside raw.
|
| 4 |
-
Licensed MANO weights stay in the local model directory and are never published.
|
| 5 |
-
"""
|
| 6 |
-
from sequence_pilot_world import camera_mano, Mano
|
| 7 |
-
from pilot_build import *
|
| 8 |
-
from scipy.spatial.transform import Rotation
|
| 9 |
-
import hashlib
|
| 10 |
-
import re
|
| 11 |
-
import time
|
| 12 |
-
import trimesh
|
| 13 |
-
from concurrent.futures import ThreadPoolExecutor,wait,FIRST_COMPLETED
|
| 14 |
-
from contextlib import contextmanager
|
| 15 |
-
|
| 16 |
-
DATA_ROOT = Path('E:/hand-datasets')
|
| 17 |
-
RELEASE = 'shared-v1.0'
|
| 18 |
-
RUN = 'fresh-sequence-pilot-20260920'
|
| 19 |
-
VRS = WORK/'scripts/tools/vrs_env/Library/bin/vrs.exe'
|
| 20 |
-
MEDIA_POOL=None
|
| 21 |
-
MEDIA_PENDING=[]
|
| 22 |
-
MEDIA_WORKERS=1
|
| 23 |
-
MEDIA_POLICY='legacy_full_pixels'
|
| 24 |
-
OUTPUT_OVERRIDE=None
|
| 25 |
-
TMP_OVERRIDE=None
|
| 26 |
-
|
| 27 |
-
@contextmanager
|
| 28 |
-
def media_pipeline(workers=1,policy='jpeg-packets-all-rgb-sample16/v1'):
|
| 29 |
-
global MEDIA_POOL,MEDIA_PENDING,MEDIA_WORKERS,MEDIA_POLICY
|
| 30 |
-
assert MEDIA_POOL is None and not MEDIA_PENDING
|
| 31 |
-
MEDIA_WORKERS=workers;MEDIA_POLICY=policy
|
| 32 |
-
MEDIA_POOL=ThreadPoolExecutor(max_workers=workers)
|
| 33 |
-
try:
|
| 34 |
-
yield
|
| 35 |
-
for future in MEDIA_PENDING:future.result()
|
| 36 |
-
finally:
|
| 37 |
-
MEDIA_POOL.shutdown(wait=True,cancel_futures=True)
|
| 38 |
-
MEDIA_POOL=None;MEDIA_PENDING=[];MEDIA_POLICY='legacy_full_pixels'
|
| 39 |
-
|
| 40 |
-
def submit_media(view,members_factory):
|
| 41 |
-
global MEDIA_PENDING
|
| 42 |
-
def execute():
|
| 43 |
-
jpeg_video(view,members_factory());view.m['pilot_complete']=True;view.finish()
|
| 44 |
-
if MEDIA_POOL is None:execute();return
|
| 45 |
-
# Bound pending views and source/video spools, not only running FFmpeg tasks.
|
| 46 |
-
while len(MEDIA_PENDING)>=MEDIA_WORKERS:
|
| 47 |
-
finished,_=wait(MEDIA_PENDING,return_when=FIRST_COMPLETED)
|
| 48 |
-
for future in finished:future.result()
|
| 49 |
-
MEDIA_PENDING=[f for f in MEDIA_PENDING if f not in finished]
|
| 50 |
-
MEDIA_PENDING.append(MEDIA_POOL.submit(execute))
|
| 51 |
-
|
| 52 |
-
def digest(p):
|
| 53 |
-
h=hashlib.sha256()
|
| 54 |
-
with Path(p).open('rb') as f:
|
| 55 |
-
for b in iter(lambda:f.read(4*1024*1024),b''): h.update(b)
|
| 56 |
-
return h.hexdigest()
|
| 57 |
-
|
| 58 |
-
def native_npy_bytes(data):
|
| 59 |
-
f=io.BytesIO(data);version=np.lib.format.read_magic(f)
|
| 60 |
-
shape,order,dtype=np.lib.format._read_array_header(f,version)
|
| 61 |
-
if dtype.hasobject:return Restricted(f,encoding='latin1').load().item()
|
| 62 |
-
return np.frombuffer(f.read(),dtype=dtype).reshape(shape,order='F' if order else 'C').copy()
|
| 63 |
-
|
| 64 |
-
def command(args):
|
| 65 |
-
r=subprocess.run([str(x) for x in args],capture_output=True)
|
| 66 |
-
if r.returncode:raise RuntimeError(r.stderr.decode(errors='replace')[-3000:])
|
| 67 |
-
return r.stdout
|
| 68 |
-
|
| 69 |
-
def framehash(args,copy=False):
|
| 70 |
-
output=command([FF,'-v','error','-threads','2','-noautorotate',*args,'-map','0:v:0',
|
| 71 |
-
*(['-c:v','copy'] if copy else ['-pix_fmt','rgb24','-threads','2']),
|
| 72 |
-
'-f','framehash','-hash','sha256','-fps_mode','passthrough','pipe:1']).decode()
|
| 73 |
-
return [(int(r.split(',')[-2]),r.split(',')[-1].strip()) for r in output.splitlines() if r and not r.startswith('#')]
|
| 74 |
-
|
| 75 |
-
def jpeg_video(view, members):
|
| 76 |
-
"""members is a fresh iterator of (locator, JPEG bytes). Verify every packet/frame."""
|
| 77 |
-
if MEDIA_POLICY!='legacy_full_pixels':
|
| 78 |
-
from accelerated_media import write_video
|
| 79 |
-
return write_video(view,members)
|
| 80 |
-
temporary=view.tmp/f'{view.m["sequence_id"]}__{view.m["camera_id"]}.mjpeg'
|
| 81 |
-
temporary.parent.mkdir(parents=True,exist_ok=True)
|
| 82 |
-
hashes=[]
|
| 83 |
-
with temporary.open('wb') as out:
|
| 84 |
-
for locator,b in members:
|
| 85 |
-
assert b[:2]==b'\xff\xd8',locator
|
| 86 |
-
hashes.append((len(b),hashlib.sha256(b).hexdigest()));out.write(b)
|
| 87 |
-
assert len(hashes)==view.T
|
| 88 |
-
dst=view.p/'observation/rgb.mkv';dst.parent.mkdir(parents=True,exist_ok=True)
|
| 89 |
-
source=['-f','image2pipe','-framerate','1','-c:v','mjpeg','-i',str(temporary)]
|
| 90 |
-
command([FF,'-v','error','-y',*source,'-map','0:v:0','-c:v','copy',dst])
|
| 91 |
-
packet=framehash(['-i',str(dst)],True)
|
| 92 |
-
assert packet==hashes,'source JPEG packets changed in MKV'
|
| 93 |
-
before=framehash(source);after=framehash(['-i',str(dst)])
|
| 94 |
-
assert before==after and len(before)==view.T,'RGB decoding differs'
|
| 95 |
-
w,h=view.m['camera']['image_size'];assert all(n==w*h*3 for n,_ in after)
|
| 96 |
-
info=subprocess.run([FF,'-hide_banner','-i',str(dst)],capture_output=True).stderr.decode(errors='replace')
|
| 97 |
-
line=next(s.strip() for s in info.splitlines() if 'Video: mjpeg' in s)
|
| 98 |
-
pixel=re.search(r'Video: mjpeg[^,]*,\s*(\w+)',line).group(1)
|
| 99 |
-
version=command([FF,'-version']).decode().splitlines()[0]
|
| 100 |
-
view.component('rgb','observation/rgb.mkv','rgb/uint8/v1',['T','height','width','channel'],np.ones(view.T,bool),
|
| 101 |
-
source=view.source,method='Original JPEG packets copied from raw into MKV; no recompression or rotation',
|
| 102 |
-
storage={'profile':'mkv/mjpeg_copy/v1','codec':'mjpeg','pixel_format':pixel,'encoded_size':[w,h],
|
| 103 |
-
'source_lossy':True,'decoder':{'name':'ffmpeg','version':version,'output_pixel_format':'rgb24','autorotate':False,'source_color_declaration':'unknown','actual_stream_description':line},
|
| 104 |
-
'encoder_parameters':{'mode':'stream_copy','version':version}},storage_fps=1,timebase_role='index_only')
|
| 105 |
-
view.checks.append({'test':'all_source_JPEG_packets_and_RGB_pixels_exact','passed':True,'frames':view.T,
|
| 106 |
-
'packet_manifest_sha256':hashlib.sha256(json.dumps(hashes).encode()).hexdigest(),
|
| 107 |
-
'pixel_manifest_sha256':hashlib.sha256(json.dumps(after).encode()).hexdigest(),'output_bytes':dst.stat().st_size})
|
| 108 |
-
save(view.tmp/'media_checks'/f'{view.m["sequence_id"]}__{view.m["camera_id"]}.json',{'packets':hashes,'pixels':after})
|
| 109 |
-
# This precise file was created by this call within the current run's temporary directory.
|
| 110 |
-
assert temporary.resolve().is_relative_to(view.tmp.resolve());temporary.unlink()
|
| 111 |
-
|
| 112 |
-
class FreshView:
|
| 113 |
-
def __init__(self,dataset,seq,cam,ids,size,source):
|
| 114 |
-
self.root=(OUTPUT_OVERRIDE/dataset/RELEASE if OUTPUT_OVERRIDE else DATA_ROOT/dataset/RELEASE);self.p=self.root/'data'/seq/cam
|
| 115 |
-
self.tmp=(TMP_OVERRIDE/dataset/RUN if TMP_OVERRIDE else DATA_ROOT/dataset/'tmp'/RUN);self.p.mkdir(parents=True,exist_ok=True)
|
| 116 |
-
self.T=len(ids);self.source=source;self.checks=[]
|
| 117 |
-
self.m={'schema_version':'hand-warehouse/1.0','storage_revision':'lossless-video-2026-09-18',
|
| 118 |
-
'dataset_id':dataset,'release_id':RELEASE,'sequence_id':seq,'camera_id':cam,
|
| 119 |
-
'sample_type':'video','num_frames':self.T,'hand_slots':['left','right'],
|
| 120 |
-
'sampling':{'type':'dense','source_fps':None,'frames_ref':'camera/frames.jsonl','selection':'all released images in selected complete source sequence'},
|
| 121 |
-
'camera':{'model':'unknown','schema_id':None,'image_size':size},'split':'unknown','components':{},'pilot':True}
|
| 122 |
-
self.frames=[{'frame_index':i,'source_frame_id':str(fid),'timestamp_ns':None,'clock_domain':None,
|
| 123 |
-
'source_locator':dict(source,source_frame_id=str(fid))} for i,fid in enumerate(ids)]
|
| 124 |
-
def component(self,name,path,schema,axes,valid,source=None,method='source values retained',kind='format_conversion',**kw):
|
| 125 |
-
valid=np.asarray(valid,bool);vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix();tensor(self.p/vp,valid)
|
| 126 |
-
self.m['components'][name]={'available':True,'schema_id':schema,'data_ref':path,'axes':axes,
|
| 127 |
-
'valid_ref':vp,'valid_axes':axes[:valid.ndim],'provenance':{'kind':kind,'method':method},
|
| 128 |
-
'source_locator':source or self.source,**kw}
|
| 129 |
-
def array(self,name,path,schema,data,valid,axes,**kw):
|
| 130 |
-
a=np.asarray(data,np.float32).copy();valid=np.asarray(valid,bool)
|
| 131 |
-
assert a.shape[0]==self.T and a.shape[:valid.ndim]==valid.shape
|
| 132 |
-
assert np.isfinite(a[valid]).all(),name
|
| 133 |
-
a[~valid]=np.nan;tensor(self.p/path,a)
|
| 134 |
-
self.component(name,path,schema,axes,valid,**kw)
|
| 135 |
-
restored=torch.load(self.p/path,map_location='cpu',weights_only=True).numpy()
|
| 136 |
-
assert np.array_equal(a,restored,equal_nan=True)
|
| 137 |
-
self.checks.append({'test':'tensor_exact_roundtrip','file':path,'shape':list(a.shape),'valid_count':int(valid.sum()),'passed':True})
|
| 138 |
-
def attribute(self,parent,path,data,axes,source,meaning):
|
| 139 |
-
data=np.asarray(data,np.float32);valid=np.isfinite(data)
|
| 140 |
-
assert ((data[valid]>=0)&(data[valid]<=1)).all()
|
| 141 |
-
vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix();tensor(self.p/path,data);tensor(self.p/vp,valid)
|
| 142 |
-
self.m['components'][parent].setdefault('attributes',{})['visibility']={'data_ref':path,'valid_ref':vp,
|
| 143 |
-
'axes':axes,'valid_axes':axes,'dtype':'float32','visibility_type':'ratio','meaning':meaning,
|
| 144 |
-
'provenance':{'kind':'source','method':'native HOT3D visibility ratio retained in [0,1]; misleading [%] header is not a percentage scale'},'source_locator':source}
|
| 145 |
-
def mesh(self,oid,path,source):
|
| 146 |
-
self.component('object_'+oid+'_mesh',path,'mesh/obj/v1',['vertex','coordinate'],np.array(True),source=source,
|
| 147 |
-
method='Object vertices in metres; topology, material and texture dependencies retained',static=True,unit='m',coordinate_frame='object')
|
| 148 |
-
def finish(self):
|
| 149 |
-
lines(self.p/'camera/frames.jsonl',self.frames);save(self.p/'metainfo.json',self.m)
|
| 150 |
-
save(self.tmp/'checks'/f'{self.m["sequence_id"]}__{self.m["camera_id"]}.json',{'checks':self.checks,'frames':self.T,'input':self.source})
|
| 151 |
-
print('CONVERTED',self.m['dataset_id'],self.m['sequence_id'],self.m['camera_id'],self.T,flush=True)
|
| 152 |
-
|
| 153 |
-
def assert_se3(a):
|
| 154 |
-
a=np.asarray(a);assert a.shape[-2:]==(4,4)
|
| 155 |
-
# A component may exist while QA leaves no usable poses in this view.
|
| 156 |
-
if a.size==0:return
|
| 157 |
-
assert np.isfinite(a).all() and np.allclose(a[...,3,:],[0,0,0,1],atol=1e-6)
|
| 158 |
-
r=a[...,:3,:3];assert np.max(np.abs(r@np.swapaxes(r,-1,-2)-np.eye(3)))<2e-5
|
| 159 |
-
assert np.max(np.abs(np.linalg.det(r)-1))<2e-5
|
| 160 |
-
|
| 161 |
-
def setup(dataset,seq):
|
| 162 |
-
base=DATA_ROOT/dataset;out=base/RELEASE
|
| 163 |
-
for folder in ['doc','script','doc/validation']: (out/folder).mkdir(parents=True,exist_ok=True)
|
| 164 |
-
for f in ['CONTRACT.md','schema.json']:shutil.copyfile(WORK/'distribution/hand-warehouse-1.0'/f,out/'doc'/f)
|
| 165 |
-
save(out/'doc/validation/status.json',{'stage':'building_sequence_pilot','human_review':'pending','sequence_id':seq,'full_preprocessing_authorized':False,'upload_authorized':False})
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
if
|
| 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 |
-
else:
|
| 211 |
-
K,D=params;uv[good]=cv2.projectPoints(xyz[good],np.zeros(3),np.zeros(3),K,D)[0].reshape(-1,2)
|
| 212 |
-
return uv
|
|
|
|
| 1 |
+
"""Helpers for the fresh ARCTIC/HOT3D whole-sequence v1.0 pilots.
|
| 2 |
+
|
| 3 |
+
Original archives are read only. Temporary extraction is outside raw.
|
| 4 |
+
Licensed MANO weights stay in the local model directory and are never published.
|
| 5 |
+
"""
|
| 6 |
+
from sequence_pilot_world import camera_mano, Mano
|
| 7 |
+
from pilot_build import *
|
| 8 |
+
from scipy.spatial.transform import Rotation
|
| 9 |
+
import hashlib
|
| 10 |
+
import re
|
| 11 |
+
import time
|
| 12 |
+
import trimesh
|
| 13 |
+
from concurrent.futures import ThreadPoolExecutor,wait,FIRST_COMPLETED
|
| 14 |
+
from contextlib import contextmanager
|
| 15 |
+
|
| 16 |
+
DATA_ROOT = Path('E:/hand-datasets')
|
| 17 |
+
RELEASE = 'shared-v1.0'
|
| 18 |
+
RUN = 'fresh-sequence-pilot-20260920'
|
| 19 |
+
VRS = WORK/'scripts/tools/vrs_env/Library/bin/vrs.exe'
|
| 20 |
+
MEDIA_POOL=None
|
| 21 |
+
MEDIA_PENDING=[]
|
| 22 |
+
MEDIA_WORKERS=1
|
| 23 |
+
MEDIA_POLICY='legacy_full_pixels'
|
| 24 |
+
OUTPUT_OVERRIDE=None
|
| 25 |
+
TMP_OVERRIDE=None
|
| 26 |
+
|
| 27 |
+
@contextmanager
|
| 28 |
+
def media_pipeline(workers=1,policy='jpeg-packets-all-rgb-sample16/v1'):
|
| 29 |
+
global MEDIA_POOL,MEDIA_PENDING,MEDIA_WORKERS,MEDIA_POLICY
|
| 30 |
+
assert MEDIA_POOL is None and not MEDIA_PENDING
|
| 31 |
+
MEDIA_WORKERS=workers;MEDIA_POLICY=policy
|
| 32 |
+
MEDIA_POOL=ThreadPoolExecutor(max_workers=workers)
|
| 33 |
+
try:
|
| 34 |
+
yield
|
| 35 |
+
for future in MEDIA_PENDING:future.result()
|
| 36 |
+
finally:
|
| 37 |
+
MEDIA_POOL.shutdown(wait=True,cancel_futures=True)
|
| 38 |
+
MEDIA_POOL=None;MEDIA_PENDING=[];MEDIA_POLICY='legacy_full_pixels'
|
| 39 |
+
|
| 40 |
+
def submit_media(view,members_factory):
|
| 41 |
+
global MEDIA_PENDING
|
| 42 |
+
def execute():
|
| 43 |
+
jpeg_video(view,members_factory());view.m['pilot_complete']=True;view.finish()
|
| 44 |
+
if MEDIA_POOL is None:execute();return
|
| 45 |
+
# Bound pending views and source/video spools, not only running FFmpeg tasks.
|
| 46 |
+
while len(MEDIA_PENDING)>=MEDIA_WORKERS:
|
| 47 |
+
finished,_=wait(MEDIA_PENDING,return_when=FIRST_COMPLETED)
|
| 48 |
+
for future in finished:future.result()
|
| 49 |
+
MEDIA_PENDING=[f for f in MEDIA_PENDING if f not in finished]
|
| 50 |
+
MEDIA_PENDING.append(MEDIA_POOL.submit(execute))
|
| 51 |
+
|
| 52 |
+
def digest(p):
|
| 53 |
+
h=hashlib.sha256()
|
| 54 |
+
with Path(p).open('rb') as f:
|
| 55 |
+
for b in iter(lambda:f.read(4*1024*1024),b''): h.update(b)
|
| 56 |
+
return h.hexdigest()
|
| 57 |
+
|
| 58 |
+
def native_npy_bytes(data):
|
| 59 |
+
f=io.BytesIO(data);version=np.lib.format.read_magic(f)
|
| 60 |
+
shape,order,dtype=np.lib.format._read_array_header(f,version)
|
| 61 |
+
if dtype.hasobject:return Restricted(f,encoding='latin1').load().item()
|
| 62 |
+
return np.frombuffer(f.read(),dtype=dtype).reshape(shape,order='F' if order else 'C').copy()
|
| 63 |
+
|
| 64 |
+
def command(args):
|
| 65 |
+
r=subprocess.run([str(x) for x in args],capture_output=True)
|
| 66 |
+
if r.returncode:raise RuntimeError(r.stderr.decode(errors='replace')[-3000:])
|
| 67 |
+
return r.stdout
|
| 68 |
+
|
| 69 |
+
def framehash(args,copy=False):
|
| 70 |
+
output=command([FF,'-v','error','-threads','2','-noautorotate',*args,'-map','0:v:0',
|
| 71 |
+
*(['-c:v','copy'] if copy else ['-pix_fmt','rgb24','-threads','2']),
|
| 72 |
+
'-f','framehash','-hash','sha256','-fps_mode','passthrough','pipe:1']).decode()
|
| 73 |
+
return [(int(r.split(',')[-2]),r.split(',')[-1].strip()) for r in output.splitlines() if r and not r.startswith('#')]
|
| 74 |
+
|
| 75 |
+
def jpeg_video(view, members):
|
| 76 |
+
"""members is a fresh iterator of (locator, JPEG bytes). Verify every packet/frame."""
|
| 77 |
+
if MEDIA_POLICY!='legacy_full_pixels':
|
| 78 |
+
from accelerated_media import write_video
|
| 79 |
+
return write_video(view,members)
|
| 80 |
+
temporary=view.tmp/f'{view.m["sequence_id"]}__{view.m["camera_id"]}.mjpeg'
|
| 81 |
+
temporary.parent.mkdir(parents=True,exist_ok=True)
|
| 82 |
+
hashes=[]
|
| 83 |
+
with temporary.open('wb') as out:
|
| 84 |
+
for locator,b in members:
|
| 85 |
+
assert b[:2]==b'\xff\xd8',locator
|
| 86 |
+
hashes.append((len(b),hashlib.sha256(b).hexdigest()));out.write(b)
|
| 87 |
+
assert len(hashes)==view.T
|
| 88 |
+
dst=view.p/'observation/rgb.mkv';dst.parent.mkdir(parents=True,exist_ok=True)
|
| 89 |
+
source=['-f','image2pipe','-framerate','1','-c:v','mjpeg','-i',str(temporary)]
|
| 90 |
+
command([FF,'-v','error','-y',*source,'-map','0:v:0','-c:v','copy',dst])
|
| 91 |
+
packet=framehash(['-i',str(dst)],True)
|
| 92 |
+
assert packet==hashes,'source JPEG packets changed in MKV'
|
| 93 |
+
before=framehash(source);after=framehash(['-i',str(dst)])
|
| 94 |
+
assert before==after and len(before)==view.T,'RGB decoding differs'
|
| 95 |
+
w,h=view.m['camera']['image_size'];assert all(n==w*h*3 for n,_ in after)
|
| 96 |
+
info=subprocess.run([FF,'-hide_banner','-i',str(dst)],capture_output=True).stderr.decode(errors='replace')
|
| 97 |
+
line=next(s.strip() for s in info.splitlines() if 'Video: mjpeg' in s)
|
| 98 |
+
pixel=re.search(r'Video: mjpeg[^,]*,\s*(\w+)',line).group(1)
|
| 99 |
+
version=command([FF,'-version']).decode().splitlines()[0]
|
| 100 |
+
view.component('rgb','observation/rgb.mkv','rgb/uint8/v1',['T','height','width','channel'],np.ones(view.T,bool),
|
| 101 |
+
source=view.source,method='Original JPEG packets copied from raw into MKV; no recompression or rotation',
|
| 102 |
+
storage={'profile':'mkv/mjpeg_copy/v1','codec':'mjpeg','pixel_format':pixel,'encoded_size':[w,h],
|
| 103 |
+
'source_lossy':True,'decoder':{'name':'ffmpeg','version':version,'output_pixel_format':'rgb24','autorotate':False,'source_color_declaration':'unknown','actual_stream_description':line},
|
| 104 |
+
'encoder_parameters':{'mode':'stream_copy','version':version}},storage_fps=1,timebase_role='index_only')
|
| 105 |
+
view.checks.append({'test':'all_source_JPEG_packets_and_RGB_pixels_exact','passed':True,'frames':view.T,
|
| 106 |
+
'packet_manifest_sha256':hashlib.sha256(json.dumps(hashes).encode()).hexdigest(),
|
| 107 |
+
'pixel_manifest_sha256':hashlib.sha256(json.dumps(after).encode()).hexdigest(),'output_bytes':dst.stat().st_size})
|
| 108 |
+
save(view.tmp/'media_checks'/f'{view.m["sequence_id"]}__{view.m["camera_id"]}.json',{'packets':hashes,'pixels':after})
|
| 109 |
+
# This precise file was created by this call within the current run's temporary directory.
|
| 110 |
+
assert temporary.resolve().is_relative_to(view.tmp.resolve());temporary.unlink()
|
| 111 |
+
|
| 112 |
+
class FreshView:
|
| 113 |
+
def __init__(self,dataset,seq,cam,ids,size,source):
|
| 114 |
+
self.root=(OUTPUT_OVERRIDE/dataset/RELEASE if OUTPUT_OVERRIDE else DATA_ROOT/dataset/RELEASE);self.p=self.root/'data'/seq/cam
|
| 115 |
+
self.tmp=(TMP_OVERRIDE/dataset/RUN if TMP_OVERRIDE else DATA_ROOT/dataset/'tmp'/RUN);self.p.mkdir(parents=True,exist_ok=True)
|
| 116 |
+
self.T=len(ids);self.source=source;self.checks=[]
|
| 117 |
+
self.m={'schema_version':'hand-warehouse/1.0','storage_revision':'lossless-video-2026-09-18',
|
| 118 |
+
'dataset_id':dataset,'release_id':RELEASE,'sequence_id':seq,'camera_id':cam,
|
| 119 |
+
'sample_type':'video','num_frames':self.T,'hand_slots':['left','right'],
|
| 120 |
+
'sampling':{'type':'dense','source_fps':None,'frames_ref':'camera/frames.jsonl','selection':'all released images in selected complete source sequence'},
|
| 121 |
+
'camera':{'model':'unknown','schema_id':None,'image_size':size},'split':'unknown','components':{},'pilot':True}
|
| 122 |
+
self.frames=[{'frame_index':i,'source_frame_id':str(fid),'timestamp_ns':None,'clock_domain':None,
|
| 123 |
+
'source_locator':dict(source,source_frame_id=str(fid))} for i,fid in enumerate(ids)]
|
| 124 |
+
def component(self,name,path,schema,axes,valid,source=None,method='source values retained',kind='format_conversion',**kw):
|
| 125 |
+
valid=np.asarray(valid,bool);vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix();tensor(self.p/vp,valid)
|
| 126 |
+
self.m['components'][name]={'available':True,'schema_id':schema,'data_ref':path,'axes':axes,
|
| 127 |
+
'valid_ref':vp,'valid_axes':axes[:valid.ndim],'provenance':{'kind':kind,'method':method},
|
| 128 |
+
'source_locator':source or self.source,**kw}
|
| 129 |
+
def array(self,name,path,schema,data,valid,axes,**kw):
|
| 130 |
+
a=np.asarray(data,np.float32).copy();valid=np.asarray(valid,bool)
|
| 131 |
+
assert a.shape[0]==self.T and a.shape[:valid.ndim]==valid.shape
|
| 132 |
+
assert np.isfinite(a[valid]).all(),name
|
| 133 |
+
a[~valid]=np.nan;tensor(self.p/path,a)
|
| 134 |
+
self.component(name,path,schema,axes,valid,**kw)
|
| 135 |
+
restored=torch.load(self.p/path,map_location='cpu',weights_only=True).numpy()
|
| 136 |
+
assert np.array_equal(a,restored,equal_nan=True)
|
| 137 |
+
self.checks.append({'test':'tensor_exact_roundtrip','file':path,'shape':list(a.shape),'valid_count':int(valid.sum()),'passed':True})
|
| 138 |
+
def attribute(self,parent,path,data,axes,source,meaning):
|
| 139 |
+
data=np.asarray(data,np.float32);valid=np.isfinite(data)
|
| 140 |
+
assert ((data[valid]>=0)&(data[valid]<=1)).all()
|
| 141 |
+
vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix();tensor(self.p/path,data);tensor(self.p/vp,valid)
|
| 142 |
+
self.m['components'][parent].setdefault('attributes',{})['visibility']={'data_ref':path,'valid_ref':vp,
|
| 143 |
+
'axes':axes,'valid_axes':axes,'dtype':'float32','visibility_type':'ratio','meaning':meaning,
|
| 144 |
+
'provenance':{'kind':'source','method':'native HOT3D visibility ratio retained in [0,1]; misleading [%] header is not a percentage scale'},'source_locator':source}
|
| 145 |
+
def mesh(self,oid,path,source):
|
| 146 |
+
self.component('object_'+oid+'_mesh',path,'mesh/obj/v1',['vertex','coordinate'],np.array(True),source=source,
|
| 147 |
+
method='Object vertices in metres; topology, material and texture dependencies retained',static=True,unit='m',coordinate_frame='object')
|
| 148 |
+
def finish(self):
|
| 149 |
+
lines(self.p/'camera/frames.jsonl',self.frames);save(self.p/'metainfo.json',self.m)
|
| 150 |
+
save(self.tmp/'checks'/f'{self.m["sequence_id"]}__{self.m["camera_id"]}.json',{'checks':self.checks,'frames':self.T,'input':self.source})
|
| 151 |
+
print('CONVERTED',self.m['dataset_id'],self.m['sequence_id'],self.m['camera_id'],self.T,flush=True)
|
| 152 |
+
|
| 153 |
+
def assert_se3(a):
|
| 154 |
+
a=np.asarray(a);assert a.shape[-2:]==(4,4)
|
| 155 |
+
# A component may exist while QA leaves no usable poses in this view.
|
| 156 |
+
if a.size==0:return
|
| 157 |
+
assert np.isfinite(a).all() and np.allclose(a[...,3,:],[0,0,0,1],atol=1e-6)
|
| 158 |
+
r=a[...,:3,:3];assert np.max(np.abs(r@np.swapaxes(r,-1,-2)-np.eye(3)))<2e-5
|
| 159 |
+
assert np.max(np.abs(np.linalg.det(r)-1))<2e-5
|
| 160 |
+
|
| 161 |
+
def setup(dataset,seq):
|
| 162 |
+
base=DATA_ROOT/dataset;out=base/RELEASE
|
| 163 |
+
for folder in ['doc','script','doc/validation']: (out/folder).mkdir(parents=True,exist_ok=True)
|
| 164 |
+
for f in ['CONTRACT.md','schema.json']:shutil.copyfile(WORK/'distribution/hand-warehouse-1.0'/f,out/'doc'/f)
|
| 165 |
+
save(out/'doc/validation/status.json',{'stage':'building_sequence_pilot','human_review':'pending','sequence_id':seq,'full_preprocessing_authorized':False,'upload_authorized':False})
|
| 166 |
+
# The organized script bundle is already self-contained; runtime work must not repopulate its root.
|
| 167 |
+
(base/'tmp'/RUN).mkdir(parents=True,exist_ok=True)
|
| 168 |
+
|
| 169 |
+
def object_textured_assets(z,prefix,target):
|
| 170 |
+
target.mkdir(parents=True,exist_ok=True)
|
| 171 |
+
for name in z.namelist():
|
| 172 |
+
if not name.startswith(prefix) or name.endswith('/'):continue
|
| 173 |
+
rel=Path(name[len(prefix):]);dest=target/rel
|
| 174 |
+
assert dest.resolve().is_relative_to(target.resolve());dest.parent.mkdir(parents=True,exist_ok=True)
|
| 175 |
+
if dest.suffix.lower() in ('.obj','.mtl','.jpg','.jpeg','.png'):
|
| 176 |
+
b=z.read(name)
|
| 177 |
+
if dest.suffix=='.obj':
|
| 178 |
+
rows=b.decode().splitlines()
|
| 179 |
+
for i,row in enumerate(rows):
|
| 180 |
+
if row.startswith('v '):
|
| 181 |
+
v=row.split();v[1:4]=[format(float(x)/1000,'.17g') for x in v[1:4]];rows[i]=' '.join(v)
|
| 182 |
+
b=('\n'.join(rows)+'\n').encode()
|
| 183 |
+
dest.write_bytes(b)
|
| 184 |
+
repair_arctic_material_refs(target)
|
| 185 |
+
|
| 186 |
+
def repair_arctic_material_refs(target):
|
| 187 |
+
"""Repair a source filename mismatch only when material identifiers agree."""
|
| 188 |
+
material=target/'material.mtl'
|
| 189 |
+
if not material.exists():return
|
| 190 |
+
ids={x.split(maxsplit=1)[1] for x in material.read_text().splitlines() if x.startswith('newmtl ')}
|
| 191 |
+
for obj in target.glob('*.obj'):
|
| 192 |
+
text=obj.read_text();rows=text.splitlines();used={x.split(maxsplit=1)[1] for x in rows if x.startswith('usemtl ')}
|
| 193 |
+
if 'mtllib material_0.mtl' in rows and not (target/'material_0.mtl').exists():
|
| 194 |
+
assert used and used.issubset(ids),(obj,used,ids)
|
| 195 |
+
obj.write_text(text.replace('mtllib material_0.mtl','mtllib material.mtl'))
|
| 196 |
+
|
| 197 |
+
def project_points(xyz,camera,params):
|
| 198 |
+
xyz=np.asarray(xyz,float);uv=np.full((len(xyz),2),np.nan);good=np.isfinite(xyz).all(1)&(xyz[:,2]>1e-6)
|
| 199 |
+
if camera=='fisheye624':
|
| 200 |
+
p=np.asarray(params);xy=xyz[good,:2]/xyz[good,2,None];r=np.linalg.norm(xy,axis=1);th=np.arctan(r)
|
| 201 |
+
radial=th*(1+sum(p[3+i]*th**(2*i+2) for i in range(6)))
|
| 202 |
+
xy=xy*np.divide(radial,r,out=np.ones_like(r),where=r>1e-12)[:,None]
|
| 203 |
+
x,y=xy.T;rr=x*x+y*y
|
| 204 |
+
xd=x+(2*x*x+rr)*p[9]+2*x*y*p[10]+p[11]*rr+p[12]*rr*rr
|
| 205 |
+
yd=y+(2*y*y+rr)*p[10]+2*x*y*p[9]+p[13]*rr+p[14]*rr*rr
|
| 206 |
+
uv[good]=p[0]*np.stack([xd,yd],1)+p[1:3]
|
| 207 |
+
else:
|
| 208 |
+
K,D=params;uv[good]=cv2.projectPoints(xyz[good],np.zeros(3),np.zeros(3),K,D)[0].reshape(-1,2)
|
| 209 |
+
return uv
|
|
|
|
|
|
|
|
|
ARCTIC/shared-v1.0/script/internal/pilot_build.py
CHANGED
|
@@ -1,209 +1,207 @@
|
|
| 1 |
-
"""Small, source-traceable dataset pilot. Originals are copied, never edited.
|
| 2 |
-
|
| 3 |
-
Run with Python + numpy + torch + Pillow + opencv and imageio-ffmpeg.
|
| 4 |
-
Optional runtime installed at tmp/pilot-runtime. Outputs: hand-datasets/.
|
| 5 |
-
"""
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
import argparse, codecs, collections, csv, io, json, pickle, shutil, subprocess, sys, zipfile
|
| 8 |
-
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tmp/pilot-runtime'))
|
| 9 |
-
import numpy as np
|
| 10 |
-
import torch
|
| 11 |
-
from PIL import Image, ImageDraw
|
| 12 |
-
import cv2
|
| 13 |
-
from pilot_fetch import ROOT, sha
|
| 14 |
-
|
| 15 |
-
WORK=ROOT.parent
|
| 16 |
-
OLD=WORK/'datasets'
|
| 17 |
-
sys.path.insert(0,str(WORK/'tmp/pilot-runtime'))
|
| 18 |
-
import imageio_ffmpeg
|
| 19 |
-
FF=imageio_ffmpeg.get_ffmpeg_exe()
|
| 20 |
-
N=16
|
| 21 |
-
|
| 22 |
-
def save(p,value):
|
| 23 |
-
p.parent.mkdir(parents=True,exist_ok=True)
|
| 24 |
-
p.write_text(json.dumps(value,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
|
| 25 |
-
def lines(p,rows):
|
| 26 |
-
p.parent.mkdir(parents=True,exist_ok=True)
|
| 27 |
-
p.write_text(''.join(json.dumps(x,ensure_ascii=False,allow_nan=False)+'\n' for x in rows),encoding='utf-8')
|
| 28 |
-
def tensor(p,a):
|
| 29 |
-
p.parent.mkdir(parents=True,exist_ok=True);torch.save(torch.as_tensor(np.asarray(a).copy()),p)
|
| 30 |
-
def load(p):return json.loads(p.read_text(encoding='utf-8'))
|
| 31 |
-
|
| 32 |
-
class Restricted(pickle.Unpickler):
|
| 33 |
-
def find_class(self,module,name):
|
| 34 |
-
allowed={('numpy.core.multiarray','_reconstruct'):np.core.multiarray._reconstruct,
|
| 35 |
-
('numpy._core.multiarray','_reconstruct'):np.core.multiarray._reconstruct,
|
| 36 |
-
('numpy','ndarray'):np.ndarray,('numpy','dtype'):np.dtype,
|
| 37 |
-
('numpy.core.numeric','_frombuffer'):np.core.numeric._frombuffer,
|
| 38 |
-
('numpy._core.numeric','_frombuffer'):np.core.numeric._frombuffer,
|
| 39 |
-
('_codecs','encode'):codecs.encode,
|
| 40 |
-
('collections','OrderedDict'):collections.OrderedDict,
|
| 41 |
-
('torch._utils','_rebuild_tensor_v2'):torch._utils._rebuild_tensor_v2,
|
| 42 |
-
('torch.storage','_load_from_bytes'):lambda b:torch.load(io.BytesIO(b),map_location='cpu',weights_only=True)}
|
| 43 |
-
if (module,name) not in allowed:raise pickle.UnpicklingError(f'Unsupported class: {module}.{name}')
|
| 44 |
-
return allowed[(module,name)]
|
| 45 |
-
def read_pickle(p):
|
| 46 |
-
with p.open('rb') as f:return Restricted(f,encoding='latin1').load()
|
| 47 |
-
|
| 48 |
-
class Build:
|
| 49 |
-
def __init__(self,name):
|
| 50 |
-
self.name=name;self.base=ROOT/name;self.out=self.base/'pilot-v0';self.refs=[];self.views=[];self.checks=[]
|
| 51 |
-
for p in ['raw/doc','raw/script','raw/data','pilot-v0/doc','pilot-v0/script','pilot-v0/data']:(self.base/p).mkdir(parents=True,exist_ok=True)
|
| 52 |
-
def copy(self,src):
|
| 53 |
-
rel=src.relative_to(OLD/self.name);dst=self.base/'raw/data/local_subset'/rel
|
| 54 |
-
dst.parent.mkdir(parents=True,exist_ok=True)
|
| 55 |
-
if not dst.exists():shutil.copyfile(src,dst)
|
| 56 |
-
source_hash=sha(src);assert sha(dst)==source_hash
|
| 57 |
-
self.refs.append({'source':str(src),'stored':str(dst.relative_to(self.base)), 'sha256':source_hash,'bytes':src.stat().st_size,'kind':'historical_extracted_file_copy','official_archive_verified':False})
|
| 58 |
-
return dst
|
| 59 |
-
def view(self,seq,cam,ids,**meta):
|
| 60 |
-
p=self.out/'data'/seq/cam;p.mkdir(parents=True,exist_ok=True)
|
| 61 |
-
m={'schema_version':'pilot-v0','dataset':self.name,'sequence_id':seq,'camera_id':cam,'num_frames':len(ids),'fps':None,'split':None,'view_type':None,'time_semantics':'unknown','missing_modalities':{},**meta}
|
| 62 |
-
self.views.append((p,m))
|
| 63 |
-
lines(p/'frames.jsonl',[{'frame_index':i,'source_frame_id':str(s),'timestamp_ns':None,'clock_domain':None} for i,s in enumerate(ids)])
|
| 64 |
-
return p,m
|
| 65 |
-
def video(self,p,arrays):
|
| 66 |
-
a=np.stack(arrays);h,w=a.shape[1:3]
|
| 67 |
-
pixel='rgb24' if a.ndim==4 else ('gray16le' if a.dtype==np.uint16 else 'gray')
|
| 68 |
-
if pixel=='gray16le':a=a.astype('<u2')
|
| 69 |
-
a=np.ascontiguousarray(a);p.parent.mkdir(parents=True,exist_ok=True)
|
| 70 |
-
command=[FF,'-hide_banner','-loglevel','error','-y','-f','rawvideo','-pixel_format',pixel,'-video_size',f'{w}x{h}','-framerate','1','-i','pipe:0','-an','-c:v','ffv1','-level','3','-g','1',str(p)]
|
| 71 |
-
subprocess.run(command,input=a.tobytes(),check=True,capture_output=True)
|
| 72 |
-
decoded=subprocess.run([FF,'-v','error','-i',str(p),'-f','rawvideo','-pix_fmt',pixel,'pipe:1'],check=True,capture_output=True).stdout
|
| 73 |
-
assert decoded==a.tobytes(),f'Lossless roundtrip failed: {p}'
|
| 74 |
-
self.checks.append({'file':str(p.relative_to(self.out)),'test':'decode_all_frames_pixel_exact','passed':True,'frames':len(a),'dtype':str(a.dtype),'shape':list(a.shape)})
|
| 75 |
-
return {'codec':'FFV1','pixel_format':pixel,'container_fps':1,'container_time_is_capture_time':False}
|
| 76 |
-
def finish(self,notes):
|
| 77 |
-
for p,m in self.views:save(p/'metainfo.json',m)
|
| 78 |
-
save(self.base/'raw/doc/local_subset_manifest.json',self.refs)
|
| 79 |
-
report={'dataset':self.name,'views':len(self.views),'observations':sum(m['num_frames'] for _,m in self.views),'checks':self.checks,'notes':notes,'status':'partial' if notes else 'passed'}
|
| 80 |
-
save(self.out/'doc/report.json',report)
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
(self.out/'
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
tensor(p/'camera/
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
rgb=
|
| 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 |
-
m['
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
b.
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
m['
|
| 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 |
-
f=
|
| 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 |
-
save(ROOT/name/'pilot-v0/doc/build_error.json',{'error':str(e)});raise
|
| 209 |
-
if __name__=='__main__':main()
|
|
|
|
| 1 |
+
"""Small, source-traceable dataset pilot. Originals are copied, never edited.
|
| 2 |
+
|
| 3 |
+
Run with Python + numpy + torch + Pillow + opencv and imageio-ffmpeg.
|
| 4 |
+
Optional runtime installed at tmp/pilot-runtime. Outputs: hand-datasets/.
|
| 5 |
+
"""
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import argparse, codecs, collections, csv, io, json, pickle, shutil, subprocess, sys, zipfile
|
| 8 |
+
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tmp/pilot-runtime'))
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
from PIL import Image, ImageDraw
|
| 12 |
+
import cv2
|
| 13 |
+
from pilot_fetch import ROOT, sha
|
| 14 |
+
|
| 15 |
+
WORK=ROOT.parent
|
| 16 |
+
OLD=WORK/'datasets'
|
| 17 |
+
sys.path.insert(0,str(WORK/'tmp/pilot-runtime'))
|
| 18 |
+
import imageio_ffmpeg
|
| 19 |
+
FF=imageio_ffmpeg.get_ffmpeg_exe()
|
| 20 |
+
N=16
|
| 21 |
+
|
| 22 |
+
def save(p,value):
|
| 23 |
+
p.parent.mkdir(parents=True,exist_ok=True)
|
| 24 |
+
p.write_text(json.dumps(value,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
|
| 25 |
+
def lines(p,rows):
|
| 26 |
+
p.parent.mkdir(parents=True,exist_ok=True)
|
| 27 |
+
p.write_text(''.join(json.dumps(x,ensure_ascii=False,allow_nan=False)+'\n' for x in rows),encoding='utf-8')
|
| 28 |
+
def tensor(p,a):
|
| 29 |
+
p.parent.mkdir(parents=True,exist_ok=True);torch.save(torch.as_tensor(np.asarray(a).copy()),p)
|
| 30 |
+
def load(p):return json.loads(p.read_text(encoding='utf-8'))
|
| 31 |
+
|
| 32 |
+
class Restricted(pickle.Unpickler):
|
| 33 |
+
def find_class(self,module,name):
|
| 34 |
+
allowed={('numpy.core.multiarray','_reconstruct'):np.core.multiarray._reconstruct,
|
| 35 |
+
('numpy._core.multiarray','_reconstruct'):np.core.multiarray._reconstruct,
|
| 36 |
+
('numpy','ndarray'):np.ndarray,('numpy','dtype'):np.dtype,
|
| 37 |
+
('numpy.core.numeric','_frombuffer'):np.core.numeric._frombuffer,
|
| 38 |
+
('numpy._core.numeric','_frombuffer'):np.core.numeric._frombuffer,
|
| 39 |
+
('_codecs','encode'):codecs.encode,
|
| 40 |
+
('collections','OrderedDict'):collections.OrderedDict,
|
| 41 |
+
('torch._utils','_rebuild_tensor_v2'):torch._utils._rebuild_tensor_v2,
|
| 42 |
+
('torch.storage','_load_from_bytes'):lambda b:torch.load(io.BytesIO(b),map_location='cpu',weights_only=True)}
|
| 43 |
+
if (module,name) not in allowed:raise pickle.UnpicklingError(f'Unsupported class: {module}.{name}')
|
| 44 |
+
return allowed[(module,name)]
|
| 45 |
+
def read_pickle(p):
|
| 46 |
+
with p.open('rb') as f:return Restricted(f,encoding='latin1').load()
|
| 47 |
+
|
| 48 |
+
class Build:
|
| 49 |
+
def __init__(self,name):
|
| 50 |
+
self.name=name;self.base=ROOT/name;self.out=self.base/'pilot-v0';self.refs=[];self.views=[];self.checks=[]
|
| 51 |
+
for p in ['raw/doc','raw/script','raw/data','pilot-v0/doc','pilot-v0/script','pilot-v0/data']:(self.base/p).mkdir(parents=True,exist_ok=True)
|
| 52 |
+
def copy(self,src):
|
| 53 |
+
rel=src.relative_to(OLD/self.name);dst=self.base/'raw/data/local_subset'/rel
|
| 54 |
+
dst.parent.mkdir(parents=True,exist_ok=True)
|
| 55 |
+
if not dst.exists():shutil.copyfile(src,dst)
|
| 56 |
+
source_hash=sha(src);assert sha(dst)==source_hash
|
| 57 |
+
self.refs.append({'source':str(src),'stored':str(dst.relative_to(self.base)), 'sha256':source_hash,'bytes':src.stat().st_size,'kind':'historical_extracted_file_copy','official_archive_verified':False})
|
| 58 |
+
return dst
|
| 59 |
+
def view(self,seq,cam,ids,**meta):
|
| 60 |
+
p=self.out/'data'/seq/cam;p.mkdir(parents=True,exist_ok=True)
|
| 61 |
+
m={'schema_version':'pilot-v0','dataset':self.name,'sequence_id':seq,'camera_id':cam,'num_frames':len(ids),'fps':None,'split':None,'view_type':None,'time_semantics':'unknown','missing_modalities':{},**meta}
|
| 62 |
+
self.views.append((p,m))
|
| 63 |
+
lines(p/'frames.jsonl',[{'frame_index':i,'source_frame_id':str(s),'timestamp_ns':None,'clock_domain':None} for i,s in enumerate(ids)])
|
| 64 |
+
return p,m
|
| 65 |
+
def video(self,p,arrays):
|
| 66 |
+
a=np.stack(arrays);h,w=a.shape[1:3]
|
| 67 |
+
pixel='rgb24' if a.ndim==4 else ('gray16le' if a.dtype==np.uint16 else 'gray')
|
| 68 |
+
if pixel=='gray16le':a=a.astype('<u2')
|
| 69 |
+
a=np.ascontiguousarray(a);p.parent.mkdir(parents=True,exist_ok=True)
|
| 70 |
+
command=[FF,'-hide_banner','-loglevel','error','-y','-f','rawvideo','-pixel_format',pixel,'-video_size',f'{w}x{h}','-framerate','1','-i','pipe:0','-an','-c:v','ffv1','-level','3','-g','1',str(p)]
|
| 71 |
+
subprocess.run(command,input=a.tobytes(),check=True,capture_output=True)
|
| 72 |
+
decoded=subprocess.run([FF,'-v','error','-i',str(p),'-f','rawvideo','-pix_fmt',pixel,'pipe:1'],check=True,capture_output=True).stdout
|
| 73 |
+
assert decoded==a.tobytes(),f'Lossless roundtrip failed: {p}'
|
| 74 |
+
self.checks.append({'file':str(p.relative_to(self.out)),'test':'decode_all_frames_pixel_exact','passed':True,'frames':len(a),'dtype':str(a.dtype),'shape':list(a.shape)})
|
| 75 |
+
return {'codec':'FFV1','pixel_format':pixel,'container_fps':1,'container_time_is_capture_time':False}
|
| 76 |
+
def finish(self,notes):
|
| 77 |
+
for p,m in self.views:save(p/'metainfo.json',m)
|
| 78 |
+
save(self.base/'raw/doc/local_subset_manifest.json',self.refs)
|
| 79 |
+
report={'dataset':self.name,'views':len(self.views),'observations':sum(m['num_frames'] for _,m in self.views),'checks':self.checks,'notes':notes,'status':'partial' if notes else 'passed'}
|
| 80 |
+
save(self.out/'doc/report.json',report)
|
| 81 |
+
# Script provenance is supplied by the organized bundle and validation manifests.
|
| 82 |
+
files=[{'path':str(p.relative_to(self.out)), 'bytes':p.stat().st_size,'sha256':sha(p)} for p in sorted((self.out/'data').rglob('*')) if p.is_file()]
|
| 83 |
+
save(self.out/'doc/output_manifest.json',files)
|
| 84 |
+
print(json.dumps(report,ensure_ascii=False),flush=True)
|
| 85 |
+
return report
|
| 86 |
+
|
| 87 |
+
def h2o():
|
| 88 |
+
b=Build('H2O');src=OLD/'H2O/subject4_ego/h1/0/cam4';ids=list(range(N))
|
| 89 |
+
p,m=b.view('subject4_h1_0','cam4',ids,split='test',view_type='ego',time_semantics='ordered_source_frames; acquisition FPS not yet verified')
|
| 90 |
+
for folder in ['rgb','depth','hand_pose','hand_pose_mano','cam_pose']:
|
| 91 |
+
for i in ids:b.copy(src/folder/f'{i:06d}.{ "png" if folder in ["rgb","depth"] else "txt"}')
|
| 92 |
+
intr=np.loadtxt(b.copy(src/'cam_intrinsics.txt'));fx,fy,cx,cy,w,h=intr
|
| 93 |
+
tensor(p/'camera/intrinsic.pt',np.array([[fx,0,cx],[0,fy,cy],[0,0,1]],np.float32))
|
| 94 |
+
ext=np.stack([np.loadtxt(src/'cam_pose'/f'{i:06d}.txt').reshape(4,4) for i in ids])
|
| 95 |
+
tensor(p/'camera/extrinsic.pt',np.linalg.inv(ext).astype(np.float32))
|
| 96 |
+
m['camera']={'model':'pinhole','width':int(w),'height':int(h),'extrinsic':'T_camera_from_world','source_extrinsic':'T_world_from_camera','unit':'m','distortion':'not supplied in selected intrinsics'}
|
| 97 |
+
a=np.stack([np.loadtxt(src/'hand_pose_mano'/f'{i:06d}.txt').reshape(2,62) for i in ids])
|
| 98 |
+
valid=a[:,:,0]==1;motion=np.concatenate([a[:,:,4:52],a[:,:,52:62],a[:,:,1:4]],axis=-1).astype(np.float32)
|
| 99 |
+
motion[~valid]=np.nan;tensor(p/'annotation/mano/motion.pt',motion);tensor(p/'annotation/mano/valid_flag.pt',valid)
|
| 100 |
+
m['mano']={'layout':['pose_axis_angle:48','betas:10','translation:3'],'shape':[N,2,61],'slots':['left','right'],'coordinate_frame':'camera','translation_unit':'m','flat_hand_mean':True,'model_version':'not supplied; MANO model not bundled','valid_flag':'source annotation flag, not visibility','geometry_validation':'not_tested; model unavailable'}
|
| 101 |
+
joints=np.stack([np.loadtxt(src/'hand_pose'/f'{i:06d}.txt').reshape(2,64) for i in ids]);tensor(p/'annotation/keypoints/xyz.pt',joints[:,:,1:].reshape(N,2,21,3).astype(np.float32));tensor(p/'annotation/keypoints/valid_flag.pt',joints[:,:,0]==1)
|
| 102 |
+
rgb=[np.asarray(Image.open(src/'rgb'/f'{i:06d}.png').convert('RGB')) for i in ids]
|
| 103 |
+
depth=[np.asarray(Image.open(src/'depth'/f'{i:06d}.png'),dtype=np.uint16) for i in ids]
|
| 104 |
+
m['rgb']=b.video(p/'observation/rgb.mkv',rgb);m['depth']={**b.video(p/'observation/depth.mkv',depth),'unit':'mm','scale_to_meters':0.001,'invalid_value':0,'rgb_registration':'not_tested'}
|
| 105 |
+
m['missing_modalities']={'object':'not present in selected historical subset','segmentation':'no native mask in selected subset'}
|
| 106 |
+
# Independent check: 3D keypoint projections must be finite where the source flags valid.
|
| 107 |
+
xyz=joints[:,:,1:].reshape(N,2,21,3);projection=xyz@np.array([[fx,0,cx],[0,fy,cy],[0,0,1]]).T
|
| 108 |
+
uv=projection[...,:2]/projection[...,2:];assert np.isfinite(uv[joints[:,:,0]==1]).all()
|
| 109 |
+
image=Image.fromarray(rgb[0]);draw=ImageDraw.Draw(image)
|
| 110 |
+
for side in range(2):
|
| 111 |
+
for u,v in uv[0,side]:draw.ellipse((u-3,v-3,u+3,v+3),fill=('red' if side==0 else 'cyan'))
|
| 112 |
+
image.save(b.out/'doc/keypoints_overlay.png')
|
| 113 |
+
return b.finish(['MANO geometry not rendered; model asset unavailable. RGB-depth registration not tested. No native segmentation or object input in subset.'])
|
| 114 |
+
|
| 115 |
+
def visor():
|
| 116 |
+
b=Build('VISOR');raw=b.base/'raw/data/GroundTruth-SparseAnnotations';jp=raw/'annotations/train/P01_03.json';zp=raw/'rgb_frames/train/P01/P01_03.zip'
|
| 117 |
+
source=load(jp);annotations=source['video_annotations'][:N]
|
| 118 |
+
ids=[x['image']['name'] for x in annotations];p,m=b.view('P01_03','ego',ids,split='train',view_type='ego',time_semantics='sparse_annotations; use source frame IDs; MKV timestamps are storage indices')
|
| 119 |
+
rgbs=[];masks=[];records=[]
|
| 120 |
+
with zipfile.ZipFile(zp) as z:
|
| 121 |
+
assert z.testzip() is None
|
| 122 |
+
for i,frame in enumerate(annotations):
|
| 123 |
+
rgb=np.asarray(Image.open(io.BytesIO(z.read(frame['image']['name']))).convert('RGB'));rgbs.append(rgb)
|
| 124 |
+
mask=np.zeros((1080,1920),np.uint16);entities=[]
|
| 125 |
+
for value,entity in enumerate(frame['annotations'],1):
|
| 126 |
+
# Same polygon rasterization primitive and integer conversion as official VISOR-VIS.
|
| 127 |
+
polygons=[np.asarray(poly,dtype=np.int32) for poly in entity['segments'] if len(poly)>=3]
|
| 128 |
+
if polygons:cv2.fillPoly(mask,polygons,int(value))
|
| 129 |
+
entities.append({'mask_value':value,'instance_id':entity['id'],'track_id':None,'source':{k:v for k,v in entity.items() if k!='segments'}})
|
| 130 |
+
if mask.shape!=rgb.shape[:2]:mask=cv2.resize(mask,(rgb.shape[1],rgb.shape[0]),interpolation=cv2.INTER_NEAREST)
|
| 131 |
+
masks.append(mask);records.append({'frame_index':i,'source_frame_id':frame['image']['name'],'subsequence':frame['image']['subsequence'],'annotation_valid':True,'instances':entities})
|
| 132 |
+
assert set(np.unique(mask)) <= {0,*[x['mask_value'] for x in entities]}
|
| 133 |
+
m['rgb']=b.video(p/'observation/rgb.mkv',rgbs);m['segmentation']={**b.video(p/'annotation/segmentation/mask.mkv',masks),'provenance':'native_sparse_polygon_rasterized','background_value':0,'background_semantics':'unlabeled/background; source is not globally exhaustive','ignore_value':None,'polygon_canvas':[1920,1080],'overlap_policy':'source annotation order; last polygon wins','track_id':'unknown; no heuristic tracking'}
|
| 134 |
+
lines(p/'annotation/segmentation/instances.jsonl',records)
|
| 135 |
+
m['missing_modalities']={'mano':'not supplied','depth':'not supplied','camera':'not supplied','object_pose_mesh':'not supplied'}
|
| 136 |
+
im=rgbs[2].copy();mask=masks[2];colors=np.array([[0,0,0],[240,70,70],[70,240,90],[70,100,240],[230,190,60],[150,80,200]],np.uint8)
|
| 137 |
+
used=mask>0;im[used]=(im[used]*0.55+colors[mask[used]%len(colors)]*0.45).astype(np.uint8)
|
| 138 |
+
Image.fromarray(im).save(b.out/'doc/segmentation_overlay.png')
|
| 139 |
+
b.checks.append({'test':'official_zip_crc_all_members','passed':True,'members':len(zipfile.ZipFile(zp).namelist())})
|
| 140 |
+
b.checks.append({'test':'all_mask_values_resolve_to_frame_instances','passed':True})
|
| 141 |
+
return b.finish([])
|
| 142 |
+
|
| 143 |
+
def rhd():
|
| 144 |
+
b=Build('RHD');src=OLD/'RHD/RHD_published_v2/evaluation';ann=read_pickle(b.copy(src/'anno_evaluation.pickle'))
|
| 145 |
+
for i in range(N):
|
| 146 |
+
p,m=b.view(f'evaluation_{i:05d}','camera',[i],split='evaluation',time_semantics='independent_image')
|
| 147 |
+
rgb=np.asarray(Image.open(b.copy(src/'color'/f'{i:05d}.png')).convert('RGB'))
|
| 148 |
+
depth=np.asarray(Image.open(b.copy(src/'depth'/f'{i:05d}.png')).convert('RGB'),dtype=np.uint16)
|
| 149 |
+
code=depth[:,:,0]*256+depth[:,:,1]
|
| 150 |
+
m['rgb']=b.video(p/'observation/rgb.mkv',[rgb]);m['depth']={**b.video(p/'observation/depth.mkv',[code]),'encoding':'source R*256+G','metric_unit':None,'metric_conversion_status':'not_tested; preserved integer code only'}
|
| 151 |
+
tensor(p/'camera/intrinsic.pt',ann[i]['K']);tensor(p/'annotation/keypoints/xyz.pt',ann[i]['xyz'].reshape(1,2,21,3));tensor(p/'annotation/keypoints/uv.pt',ann[i]['uv_vis'][:,:2].reshape(1,2,21,2));tensor(p/'annotation/keypoints/visible.pt',(ann[i]['uv_vis'][:,2]==1).reshape(1,2,21))
|
| 152 |
+
m['keypoints']={'unit':'m','layout':'source 42-joint order reshaped as 2x21','hand_order':['left','right'],'joint_order':'official RHD: wrist then thumb/index/middle/ring/pinky, fingers tip-to-palm','definition_reference':'raw/doc/dataset_README.txt','visibility':'per joint; invisible does not mean unannotated'}
|
| 153 |
+
m['missing_modalities']={'mano':'not supplied by source','segmentation':'omitted by historical downloader','extrinsic':'not supplied in selected annotations'}
|
| 154 |
+
return b.finish(['Depth metric conversion pending; segmentation absent from historical input.'])
|
| 155 |
+
|
| 156 |
+
def freihand():
|
| 157 |
+
b=Build('FreiHAND');src=OLD/'FreiHAND';K=load(b.copy(src/'training_K.json'));mano=load(b.copy(src/'training_mano.json'));scale=load(b.copy(src/'training_scale.json'))
|
| 158 |
+
for base in range(4):
|
| 159 |
+
for variant in range(4):
|
| 160 |
+
i=base+variant*32560;p,m=b.view(f'training_{base:08d}',f'variant_{variant}',[i],split='training',time_semantics='independent_image',base_sample_id=str(base),variant_id=variant)
|
| 161 |
+
m['camera_group_semantics']='image_variant_not_physical_camera';m['physical_camera_id']=None
|
| 162 |
+
rgb=np.asarray(Image.open(b.copy(src/'training/rgb'/f'{i:08d}.jpg')).convert('RGB'));m['rgb']=b.video(p/'observation/rgb.mkv',[rgb])
|
| 163 |
+
tensor(p/'camera/intrinsic.pt',np.asarray(K[base],np.float32));tensor(p/'annotation/mano/source_theta.pt',np.asarray(mano[base],np.float32));tensor(p/'annotation/mano/source_scale.pt',np.asarray(scale[base],np.float32))
|
| 164 |
+
m['mano']={'source_theta_layout':['pose48','shape10','uv_root2','scale1'],'motion_status':'not_generated','reason':'To recover MANO translation, official code subtracts posed joint 9 from backprojected root. Requires correct MANO model; last three source values are not translation.'}
|
| 165 |
+
m['missing_modalities']={'depth':'not supplied','segmentation':'not present in historical input','extrinsic':'not supplied','normalized_mano':'model dependency unresolved'}
|
| 166 |
+
return b.finish(['Preserved source MANO theta; no misleading motion.pt produced. Correct model needed for normalized translation.'])
|
| 167 |
+
|
| 168 |
+
def hoi4d():
|
| 169 |
+
b=Build('HOI4D');rel=Path('ZY20210800001/H1/C20/N18/S286/s01/T1');src=OLD/'HOI4D/Hand_pose/handpose_left_hand'/rel
|
| 170 |
+
files=sorted(src.glob('*.pickle'),key=lambda p:int(p.stem))[:N];ids=[x.stem for x in files]
|
| 171 |
+
p,m=b.view('H1_C20_N18_S286_s01_T1','ZY20210800001',ids,view_type='ego',time_semantics='annotation_frame_ids_only')
|
| 172 |
+
a=np.full((len(ids),2,61),np.nan,np.float32);v=np.zeros((len(ids),2),bool);uv=np.full((len(ids),2,21,2),np.nan,np.float32)
|
| 173 |
+
for i,frame in enumerate(ids):
|
| 174 |
+
for side,folder in enumerate(['handpose_left_hand','handpose_right_hand']):
|
| 175 |
+
f=OLD/'HOI4D/Hand_pose'/folder/rel/(frame+'.pickle')
|
| 176 |
+
if not f.exists():continue
|
| 177 |
+
x=read_pickle(b.copy(f));a[i,side]=np.concatenate([x['poseCoeff'].reshape(-1),x['beta'].reshape(-1),x['trans'].reshape(-1)]);v[i,side]=True;uv[i,side]=x['kps2D']
|
| 178 |
+
tensor(p/'annotation/mano/motion.pt',a);tensor(p/'annotation/mano/valid_flag.pt',v);tensor(p/'annotation/keypoints/uv.pt',uv)
|
| 179 |
+
tensor(p/'camera/intrinsic.pt',np.load(b.copy(OLD/'HOI4D/camera_params/ZY20210800001/intrin.npy'),allow_pickle=False))
|
| 180 |
+
m['mano']={'layout':['pose_axis_angle48','betas10','translation3'],'slots':['left','right'],'translation_unit':'m','coordinate_frame':'camera','flat_hand_mean':True,'valid_flag':'source file present and parsed; not visibility','geometry_validation':'not_tested'}
|
| 181 |
+
m['missing_modalities']={'rgb':'not downloaded','depth':'not downloaded','segmentation':'not downloaded','extrinsic':'not available in selected subset','object':'not available in selected subset'}
|
| 182 |
+
return b.finish(['Annotation-only mini; no matching RGB/depth/segmentation downloaded. MANO geometry not rendered.'])
|
| 183 |
+
|
| 184 |
+
def reinterhand():
|
| 185 |
+
b=Build('ReInterHand');src=next(p for p in sorted((OLD/'ReInterHand').glob('m--*')) if (p/'mano_fits/params').exists());files=sorted((src/'mano_fits/params').glob('*_left.json'))[:N];ids=[x.stem.rsplit('_',1)[0] for x in files]
|
| 186 |
+
# Capture-level poses have no established camera transform in current local subset.
|
| 187 |
+
p,m=b.view(src.name,'source_unresolved',ids,time_semantics='capture_annotations_only; not a camera observation')
|
| 188 |
+
rows=[]
|
| 189 |
+
for frame in ids:
|
| 190 |
+
row={'source_frame_id':frame,'hands':{}}
|
| 191 |
+
for side in ['left','right']:
|
| 192 |
+
f=src/'mano_fits/params'/f'{frame}_{side}.json'
|
| 193 |
+
if f.exists():row['hands'][side]=load(b.copy(f))
|
| 194 |
+
rows.append(row)
|
| 195 |
+
lines(p/'annotation/mano/source_parameters.jsonl',rows)
|
| 196 |
+
m['missing_modalities']={'rgb':'not extracted from incomplete archive set','camera':'not available','normalized_mano':'source-to-camera mapping unresolved'}
|
| 197 |
+
m['not_a_real_camera']=True
|
| 198 |
+
return b.finish(['Source-only annotation sample. source_unresolved is an explicit staging group, not an invented camera.'])
|
| 199 |
+
|
| 200 |
+
def main():
|
| 201 |
+
parser=argparse.ArgumentParser();parser.add_argument('--dataset',nargs='*',default=['VISOR','H2O','RHD','FreiHAND','HOI4D','ReInterHand']);args=parser.parse_args()
|
| 202 |
+
funcs={'VISOR':visor,'H2O':h2o,'RHD':rhd,'FreiHAND':freihand,'HOI4D':hoi4d,'ReInterHand':reinterhand}
|
| 203 |
+
for name in args.dataset:
|
| 204 |
+
try:funcs[name]()
|
| 205 |
+
except Exception as e:
|
| 206 |
+
save(ROOT/name/'pilot-v0/doc/build_error.json',{'error':str(e)});raise
|
| 207 |
+
if __name__=='__main__':main()
|
|
|
|
|
|
ARCTIC/shared-v1.0/script/internal/preprocess_fresh_full.py
CHANGED
|
@@ -28,10 +28,10 @@ def atomic(p,value):
|
|
| 28 |
|
| 29 |
def temporary(ds):return DATA_ROOT/ds/'tmp'/JOB
|
| 30 |
|
| 31 |
-
PRODUCTION_SCRIPTS=
|
| 32 |
|
| 33 |
def code_manifest():
|
| 34 |
-
return [{'path':'script/'+f,'sha256':digest(
|
| 35 |
|
| 36 |
def verify_completed(ds,row,source):
|
| 37 |
root=DATA_ROOT/ds/RELEASE;record=temporary(ds)/'completed'/f'{row["sequence_id"]}.json';done=load(record)
|
|
@@ -75,9 +75,11 @@ def migrate_completed(ds):
|
|
| 75 |
|
| 76 |
def snapshot_scripts(ds):
|
| 77 |
root=DATA_ROOT/ds/RELEASE
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
| 81 |
|
| 82 |
def inputs(ds):
|
| 83 |
base=DATA_ROOT/ds
|
|
@@ -178,8 +180,7 @@ def approve():
|
|
| 178 |
docprod=doc/'full';docprod.mkdir(parents=True,exist_ok=True)
|
| 179 |
atomic(docprod/'plan.json',p['datasets'][ds])
|
| 180 |
(docprod/'README.md').write_text('# 全量预处理\n\n试点已获用户确认。逐序列转换、逐帧码流/像素和几何校验,完成后另建随机抽查报告。原始包保留,不自动上传。\n\n每个序列的正式自动检查在本目录sequences/;运行日志和进度只在数据集tmp。断点以输入官方摘要及全部输出文件摘要核验。\n\nHOT3D测试集未发布手物姿态真值:保留RGB、相机和物体资产,姿态及可见性缺省。ARCTIC仅保留已确认s09/laptop的曝光排除,其它序列不新增帧号屏蔽。\n',encoding='utf-8')
|
| 181 |
-
|
| 182 |
-
shutil.copyfile(WORK/'scripts'/f,root/'script'/f)
|
| 183 |
atomic(WORK/'tmp/dataset-work-state.json',state)
|
| 184 |
|
| 185 |
def official_arctic_check(row,views):
|
|
|
|
| 28 |
|
| 29 |
def temporary(ds):return DATA_ROOT/ds/'tmp'/JOB
|
| 30 |
|
| 31 |
+
PRODUCTION_SCRIPTS=sorted(p.name for p in SCRIPT.parent.glob('*.py'))
|
| 32 |
|
| 33 |
def code_manifest():
|
| 34 |
+
return [{'path':'script/internal/'+f,'sha256':digest(SCRIPT.parent/f)} for f in PRODUCTION_SCRIPTS]
|
| 35 |
|
| 36 |
def verify_completed(ds,row,source):
|
| 37 |
root=DATA_ROOT/ds/RELEASE;record=temporary(ds)/'completed'/f'{row["sequence_id"]}.json';done=load(record)
|
|
|
|
| 75 |
|
| 76 |
def snapshot_scripts(ds):
|
| 77 |
root=DATA_ROOT/ds/RELEASE
|
| 78 |
+
target=root/'script/internal';target.mkdir(parents=True,exist_ok=True)
|
| 79 |
+
for f in PRODUCTION_SCRIPTS:
|
| 80 |
+
src=SCRIPT.parent/f;dst=target/f
|
| 81 |
+
if src.resolve()!=dst.resolve():shutil.copyfile(src,dst)
|
| 82 |
+
atomic(root/'doc/validation/full/script-manifest.json',{'created_at':now(),'scope':'Current organized production implementation under script/internal; earlier manifests retain historical paths and hashes','files':code_manifest()})
|
| 83 |
|
| 84 |
def inputs(ds):
|
| 85 |
base=DATA_ROOT/ds
|
|
|
|
| 180 |
docprod=doc/'full';docprod.mkdir(parents=True,exist_ok=True)
|
| 181 |
atomic(docprod/'plan.json',p['datasets'][ds])
|
| 182 |
(docprod/'README.md').write_text('# 全量预处理\n\n试点已获用户确认。逐序列转换、逐帧码流/像素和几何校验,完成后另建随机抽查报告。原始包保留,不自动上传。\n\n每个序列的正式自动检查在本目录sequences/;运行日志和进度只在数据集tmp。断点以输入官方摘要及全部输出文件摘要核验。\n\nHOT3D测试集未发布手物姿态真值:保留RGB、相机和物体资产,姿态及可见性缺省。ARCTIC仅保留已确认s09/laptop的曝光排除,其它序列不新增帧号屏蔽。\n',encoding='utf-8')
|
| 183 |
+
snapshot_scripts(ds)
|
|
|
|
| 184 |
atomic(WORK/'tmp/dataset-work-state.json',state)
|
| 185 |
|
| 186 |
def official_arctic_check(row,views):
|
ARCTIC/shared-v1.0/script/internal/render_full_sequence_review.py
CHANGED
|
@@ -1,256 +1,256 @@
|
|
| 1 |
-
"""Full-frame, all-camera diagnostic videos read from actual shared tensors/media.
|
| 2 |
-
|
| 3 |
-
Preview MP4 is explicitly display-only; warehouse MKV packets remain untouched.
|
| 4 |
-
"""
|
| 5 |
-
from fresh_sequence_common import *
|
| 6 |
-
from review_fresh_sequence_pilots import arr, validate_view, project_for_view
|
| 7 |
-
from datetime import datetime
|
| 8 |
-
import html
|
| 9 |
-
|
| 10 |
-
VIDEO_RUN='full-video-review-v2'
|
| 11 |
-
CELL=512
|
| 12 |
-
WIDTH=3*CELL
|
| 13 |
-
HEIGHT=800
|
| 14 |
-
COLORS=[(110,255,100),(255,80,210),(240,220,60),(90,180,255),(190,160,255),(255,120,140)]
|
| 15 |
-
|
| 16 |
-
def text(im,txt,xy,color=(235,235,235),size=.5):cv2.putText(im,txt,xy,cv2.FONT_HERSHEY_SIMPLEX,size,color,1,cv2.LINE_AA)
|
| 17 |
-
|
| 18 |
-
def fast_edges(im,uv,edges,color):
|
| 19 |
-
xy=uv[edges];good=np.isfinite(xy).all((1,2)) & (np.max(np.nan_to_num(np.abs(xy),nan=CELL*20),axis=(1,2))<CELL*12)
|
| 20 |
-
xy=xy[good];xy=xy[np.linalg.norm(xy[:,0]-xy[:,1],axis=1)<CELL*.7]
|
| 21 |
-
if len(xy):cv2.polylines(im,np.rint(xy).astype(np.int32),False,color,1,cv2.LINE_AA)
|
| 22 |
-
|
| 23 |
-
def dots(im,uv,color,radius=2):
|
| 24 |
-
good=np.isfinite(uv).all(1)&(uv[:,0]>=0)&(uv[:,0]<im.shape[1])&(uv[:,1]>=0)&(uv[:,1]<im.shape[0])
|
| 25 |
-
xy=np.rint(uv[good]).astype(int);xy[:,0]=np.clip(xy[:,0],0,im.shape[1]-1);xy[:,1]=np.clip(xy[:,1],0,im.shape[0]-1)
|
| 26 |
-
for d in range(max(1,radius)):
|
| 27 |
-
im[np.clip(xy[:,1]+d,0,im.shape[0]-1),xy[:,0]]=color
|
| 28 |
-
im[xy[:,1],np.clip(xy[:,0]+d,0,im.shape[1]-1)]=color
|
| 29 |
-
|
| 30 |
-
def model_vertices(motion,valid,side,fix):
|
| 31 |
-
model=Mano(['left','right'][side])
|
| 32 |
-
if side==0 and fix:
|
| 33 |
-
model.data['shapedirs'][:,0]*=-1
|
| 34 |
-
with torch.no_grad():model.layer.shapedirs[:,0]*=-1
|
| 35 |
-
verts=np.full((len(motion),778,3),np.nan,np.float32);joints=np.full((len(motion),16,3),np.nan,np.float32)
|
| 36 |
-
ids=np.flatnonzero(valid[:,side])
|
| 37 |
-
for start in range(0,len(ids),64):
|
| 38 |
-
ix=ids[start:start+64];a=motion[ix,side];verts[ix],_,joints[ix]=model.geometry(a[:,:48],a[:,48:58],a[:,58:])
|
| 39 |
-
faces=np.asarray(model.layer.faces);edges=np.unique(np.sort(np.concatenate([faces[:,[0,1]],faces[:,[1,2]],faces[:,[2,0]]]),axis=1),axis=0)
|
| 40 |
-
return verts,joints,edges
|
| 41 |
-
|
| 42 |
-
def encoder(path,fps,log,size=(WIDTH,HEIGHT)):
|
| 43 |
-
path.parent.mkdir(parents=True,exist_ok=True)
|
| 44 |
-
return subprocess.Popen([str(FF),'-v','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s',f'{size[0]}x{size[1]}','-r',str(fps),'-i','pipe:0',
|
| 45 |
-
'-an','-c:v','libx264','-preset','veryfast','-crf','19','-pix_fmt','yuv420p','-threads','2','-bf','0','-g','60','-movflags','+faststart',str(path)],stdin=subprocess.PIPE,stderr=log)
|
| 46 |
-
|
| 47 |
-
def read_exact(pipe,n):
|
| 48 |
-
chunks=[];count=0
|
| 49 |
-
while count<n:
|
| 50 |
-
b=pipe.read(n-count)
|
| 51 |
-
if not b:break
|
| 52 |
-
chunks.append(b);count+=len(b)
|
| 53 |
-
return b''.join(chunks)
|
| 54 |
-
|
| 55 |
-
def trajectory_plot(E,width=265,height=145):
|
| 56 |
-
good=np.isfinite(E).all((1,2));xyz=np.full((len(E),3),np.nan)
|
| 57 |
-
xyz[good]=-(np.swapaxes(E[good,:3,:3],1,2)@E[good,:3,3,None])[:,:,0]
|
| 58 |
-
base=np.full((height,width,3),24,np.uint8);xy=xyz[:,[0,2]];valid=np.isfinite(xy).all(1)
|
| 59 |
-
if not valid.any():return base,np.zeros((len(E),2),int),xyz
|
| 60 |
-
lo=np.nanmin(xy,0);hi=np.nanmax(xy,0);span=np.maximum(hi-lo,.05);scale=min((width-24)/span[0],(height-35)/span[1]);pix=(xy-lo)*scale+12
|
| 61 |
-
pix[:,1]=height-12-pix[:,1];pixels=np.nan_to_num(pix).astype(int)
|
| 62 |
-
for i in range(1,len(E)):
|
| 63 |
-
if valid[i-1] and valid[i]:cv2.line(base,tuple(pixels[i-1]),tuple(pixels[i]),(110,110,110),1)
|
| 64 |
-
text(base,'camera world trajectory X/Z (m)',(7,15),size=.38)
|
| 65 |
-
return base,pixels,xyz
|
| 66 |
-
|
| 67 |
-
def object_specs(p,source):
|
| 68 |
-
result=[]
|
| 69 |
-
for k,op in enumerate(sorted((p/'annotation/object').glob('*'))):
|
| 70 |
-
if not (op/'pose.pt').exists():continue
|
| 71 |
-
om=load(op/'metainfo.json');rel=op.relative_to(p);mesh=trimesh.load(p/om['mesh_ref'],process=False,force='mesh')
|
| 72 |
-
rawpose=arr(source/rel/'pose.pt');rawvalid=arr(source/rel/'pose_valid.pt');valid=arr(op/'pose_valid.pt')
|
| 73 |
-
spec={'id':om['object_id'],'name':om.get('category_name',om['object_id']),'color':COLORS[k%len(COLORS)],'P':rawpose,'rawvalid':rawvalid,'valid':valid,'op':op}
|
| 74 |
-
if 'vertex_part_ids_ref' in om:
|
| 75 |
-
xyz=np.array([[float(x) for x in r.split()[1:4]] for r in (p/om['mesh_ref']).read_text().splitlines() if r.startswith('v ')])
|
| 76 |
-
part=arr(p/om['vertex_part_ids_ref']);idx=np.arange(0,len(xyz),max(1,len(xyz)//4500))
|
| 77 |
-
spec.update(vertices=xyz[idx],parts=part[idx],top=arr(source/rel/'parts/top/pose.pt'),edges=None,
|
| 78 |
-
keypoints=arr(source/rel/'keypoints/xyz.pt'),joint=arr(source/rel/'joint_state.pt')[:,0])
|
| 79 |
-
else:
|
| 80 |
-
edges=np.asarray(mesh.edges_unique);edges=edges[::max(1,len(edges)//1100)]
|
| 81 |
-
unique,inv=np.unique(edges,return_inverse=True);spec.update(vertices=np.asarray(mesh.vertices)[unique],edges=inv.reshape(-1,2),parts=None)
|
| 82 |
-
spec['visibility']=arr(op/'visibility.pt') if (op/'visibility.pt').exists() else None
|
| 83 |
-
spec['raw_visibility']=arr(source/rel/'visibility.pt') if (source/rel/'visibility.pt').exists() else None
|
| 84 |
-
result.append(spec)
|
| 85 |
-
return result
|
| 86 |
-
|
| 87 |
-
def render_view(p,dataset,qa_data,doc=None,tmp=None,source=None,snapshot_indices=None):
|
| 88 |
-
m,frames,structural=validate_view(p);cam=m['camera_id'];T=m['num_frames'];root=DATA_ROOT/dataset/RELEASE
|
| 89 |
-
doc=doc or root/'doc/validation';tmp=tmp or DATA_ROOT/dataset/'tmp'/VIDEO_RUN;tmp.mkdir(parents=True,exist_ok=True)
|
| 90 |
-
if source is None:
|
| 91 |
-
source=p
|
| 92 |
-
for candidate in [DATA_ROOT/dataset/'tmp'/VIDEO_RUN/'diagnostic'/m['sequence_id']/cam,DATA_ROOT/dataset/'tmp'/VIDEO_RUN/'diagnostic'/cam]:
|
| 93 |
-
if (candidate/'snapshot.json').exists() and Path(load(candidate/'snapshot.json')['source_view']).resolve()==p.resolve():source=candidate;break
|
| 94 |
-
qa=np.array(qa_data[cam]['qa_pass'],bool) if dataset=='HOT3D' and qa_data and qa_data[cam].get('qa_pass') is not None else None
|
| 95 |
-
if 'mano' in m['components']:
|
| 96 |
-
motion=arr(source/'annotation/mano/motion.pt');present=arr(source/'annotation/mano/motion_valid.pt');valid=arr(p/'annotation/mano/motion_valid.pt')
|
| 97 |
-
else:motion=np.full((T,2,61),np.nan);present=np.zeros((T,2),bool);valid=present.copy()
|
| 98 |
-
visibility=arr(p/'annotation/mano/visibility.pt') if (p/'annotation/mano/visibility.pt').exists() else None
|
| 99 |
-
rawvis=arr(source/'annotation/mano/visibility.pt') if (source/'annotation/mano/visibility.pt').exists() else None
|
| 100 |
-
hands=[model_vertices(motion,present,s,m['components'].get('mano',{}).get('model_profile',{}).get('left_shapedirs_fix',False)) for s in range(2)]
|
| 101 |
-
objs=object_specs(p,source);K=arr(p/'camera/intrinsic.pt') if (p/'camera/intrinsic.pt').exists() else np.full((T,3,3),np.nan);D=arr(p/'camera/distortion.pt') if (p/'camera/distortion.pt').exists() else None;E=arr(p/'camera/extrinsic.pt') if (p/'camera/extrinsic.pt').exists() else np.full((T,4,4),np.nan)
|
| 102 |
-
W,H=m['camera']['image_size'];scale0=min(CELL/W,CELL/H);w=int(W*scale0)//2*2;h=int(H*scale0)//2*2;scale=np.array([w/W,h/H])
|
| 103 |
-
fps=m['sampling']['source_fps'] or 30;path=doc/'videos'/f'{cam}-full.mp4';logpath=tmp/f'render-{cam}.log';log=logpath.open('wb')
|
| 104 |
-
dec=subprocess.Popen([str(FF),'-v','error','-threads','2','-noautorotate','-i',str(p/'observation/rgb.mkv'),'-vf',f'scale={w}:{h}','-pix_fmt','rgb24','-fps_mode','passthrough','-f','rawvideo','pipe:1'],stdout=subprocess.PIPE,stderr=log)
|
| 105 |
-
enc=encoder(path,fps,log);traj,tp,world=trajectory_plot(E);rendered=0;exposure=[]
|
| 106 |
-
snapshots=sorted(set(snapshot_indices or [0,1,26,27,179,180,T//4,T//2,3*T//4,T-1]))
|
| 107 |
-
timeline=np.zeros((12,WIDTH,3),np.uint8)
|
| 108 |
-
for x in range(WIDTH):timeline[:,x]=(40,135,65) if qa is not None and qa[min(T-1,x*T//WIDTH)] else ((170,42,50) if qa is not None else (75,80,95))
|
| 109 |
-
for i in range(T):
|
| 110 |
-
b=read_exact(dec.stdout,w*h*3);assert len(b)==w*h*3,(cam,i,'decoder ended early')
|
| 111 |
-
original=np.frombuffer(b,np.uint8).reshape(h,w,3).copy();raw=original.copy();usable=original.copy()
|
| 112 |
-
gray=cv2.cvtColor(cv2.resize(original,(96,96)),cv2.COLOR_RGB2GRAY)
|
| 113 |
-
exposure.append({'frame_index':i,'p95_luma':float(np.percentile(gray,95)),'median_luma':float(np.median(gray))})
|
| 114 |
-
params=K[i] if m['camera']['model']=='fisheye624' else (K[i],D[i] if D is not None else None)
|
| 115 |
-
for side,(verts,joints,edges) in enumerate(hands):
|
| 116 |
-
if not present[i,side]:continue
|
| 117 |
-
uv=project_for_view(verts[i],m,params,scale);color=(0,235,255) if side==0 else (255,135,20)
|
| 118 |
-
fast_edges(raw,uv,edges,color)
|
| 119 |
-
if valid[i,side]:fast_edges(usable,uv,edges,color)
|
| 120 |
-
# White MANO joints are a diagnostic derivation, not a new keypoint component.
|
| 121 |
-
dots(raw,project_for_view(joints[i],m,params,scale),(255,255,255),2)
|
| 122 |
-
if valid[i,side]:dots(usable,project_for_view(joints[i],m,params,scale),(255,255,255),2)
|
| 123 |
-
for obj in objs:
|
| 124 |
-
if not obj['rawvalid'][i]:continue
|
| 125 |
-
P=obj['P'][i];xyz=obj['vertices']@P[:3,:3].T+P[:3,3]
|
| 126 |
-
if obj['parts'] is not None:
|
| 127 |
-
top=obj['top'][i];sel=obj['parts']==1;xyz[sel]=obj['vertices'][sel]@top[:3,:3].T+top[:3,3]
|
| 128 |
-
uv=project_for_view(xyz,m,params,scale)
|
| 129 |
-
for image,enabled in [(raw,True),(usable,obj['valid'][i])]:
|
| 130 |
-
if not enabled:continue
|
| 131 |
-
if obj['edges'] is not None:fast_edges(image,uv,obj['edges'],obj['color'])
|
| 132 |
-
else:
|
| 133 |
-
dots(image,uv[obj['parts']==0],(100,240,90));dots(image,uv[obj['parts']==1],(230,80,230))
|
| 134 |
-
dots(image,project_for_view(obj['keypoints'][i],m,params,scale),(255,255,255),3)
|
| 135 |
-
# Local object axes in metres make pose orientation visible.
|
| 136 |
-
axes=np.vstack([np.zeros(3),np.eye(3)*.045])@P[:3,:3].T+P[:3,3];auv=project_for_view(axes,m,params,scale)
|
| 137 |
-
for j,c in enumerate([(255,60,60),(60,255,60),(60,120,255)]):fast_edges(image,auv,np.array([[0,j+1]]),c)
|
| 138 |
-
canvas=np.full((HEIGHT,WIDTH,3),20,np.uint8)
|
| 139 |
-
for col,(im,label) in enumerate([(original,'SOURCE RGB'),(raw,'NATIVE LABEL DIAGNOSTIC'),(usable,'SHARED USABLE SUPERVISION')]):
|
| 140 |
-
canvas[40+(CELL-h)//2:40+(CELL-h)//2+h,col*CELL+(CELL-w)//2:col*CELL+(CELL-w)//2+w]=im
|
| 141 |
-
text(canvas,label,(col*CELL+12,25),size=.58)
|
| 142 |
-
status='NO OFFICIAL QA PROVIDED' if qa is None else ('OFFICIAL QA PASS' if qa[i] else 'OFFICIAL QA FAIL - NOT SUPERVISION')
|
| 143 |
-
if dataset=='ARCTIC' and i in m['components'].get('mano',{}).get('valid_policy',{}).get('local_excluded_frame_indices',[]):status='LOCAL REVIEW REJECT - NOT HAND SUPERVISION'
|
| 144 |
-
color=(235,195,65) if qa is None else ((80,240,110) if qa[i] else (255,90,90))
|
| 145 |
-
text(canvas,f'{dataset} {cam} index={i}/{T-1} source={frames[i]["source_frame_id"]} {status}',(12,578),color,.6)
|
| 146 |
-
text(canvas,f'MANO source L/R={int(present[i,0])}/{int(present[i,1])} shared valid L/R={int(valid[i,0])}/{int(valid[i,1])} (m/rad)',(12,603),size=.49)
|
| 147 |
-
def vals(a):return 'n/a' if a is None else ','.join('unknown' if not np.isfinite(x) else f'{100*x:.1f}%' for x in np.atleast_1d(a))
|
| 148 |
-
text(canvas,f'visibility native L/R: {vals(rawvis[i] if rawvis is not None else None)} usable: {vals(visibility[i] if visibility is not None else None)}',(12,626),size=.48)
|
| 149 |
-
text(canvas,f'camera={m["camera"]["model"]}; intrinsic '+np.array2string(K[i].ravel()[:5],precision=2),(12,649),size=.45)
|
| 150 |
-
text(canvas,'camera world position (m): '+np.array2string(world[i],precision=3),(12,672),size=.45)
|
| 151 |
-
clock=frames[i]['timestamp_ns'];text(canvas,f'timestamp_ns={clock} clock={frames[i]["clock_domain"]}',(12,695),size=.44)
|
| 152 |
-
text(canvas,f'preview FPS={fps}; '+('capture FPS unknown, playback only' if m['sampling']['source_fps'] is None else 'source capture time is stored separately'),(12,718),size=.44)
|
| 153 |
-
text(canvas,'cyan=left; orange=right; white=derived MANO joints / source object points',(12,741),size=.41)
|
| 154 |
-
text(canvas,'Projection shows hidden surfaces; it is NOT native segmentation.',(12,762),(180,180,180),.43)
|
| 155 |
-
for j,obj in enumerate(objs):
|
| 156 |
-
a=obj['raw_visibility'];v=obj['visibility'];s=f'{obj["name"]}: valid={int(obj["valid"][i])}'
|
| 157 |
-
if a is not None:s+=f' vis={vals(v[i])} (raw {vals(a[i])})'
|
| 158 |
-
if 'joint' in obj:s+=f' hinge={obj["joint"][i]:.3f}rad keypoints=32'
|
| 159 |
-
text(canvas,s,(660,603+j*24),obj['color'],.44)
|
| 160 |
-
tr=traj.copy()
|
| 161 |
-
if np.isfinite(world[i]).all():cv2.circle(tr,tuple(tp[i]),4,(255,220,70),-1)
|
| 162 |
-
canvas[610:755,WIDTH-277:WIDTH-12]=tr
|
| 163 |
-
canvas[-12:]=timeline;cursor=min(WIDTH-1,int(i*WIDTH/T));canvas[-12:,cursor:cursor+2]=255
|
| 164 |
-
enc.stdin.write(canvas.tobytes());rendered+=1
|
| 165 |
-
if i in snapshots:
|
| 166 |
-
snap=doc/'video_snapshots'/cam;snap.mkdir(parents=True,exist_ok=True);Image.fromarray(canvas).save(snap/f'{i:06d}.jpg',quality=92)
|
| 167 |
-
if i%200==0:print('VIDEO_FRAME',dataset,cam,i,T,flush=True)
|
| 168 |
-
assert not dec.stdout.read(1),'extra source frames';dec.stdout.close();assert dec.wait()==0
|
| 169 |
-
enc.stdin.close();assert enc.wait()==0;log.close();assert rendered==T
|
| 170 |
-
packets=framehash(['-i',str(path)],copy=True);assert len(packets)==T
|
| 171 |
-
result={'sequence_id':m['sequence_id'],'camera_id':cam,'frames':T,'rendered_frames':rendered,'video_ref':path.relative_to(doc).as_posix(),'video_sha256':digest(path),'preview_fps':fps,
|
| 172 |
-
'preview_is_training_data':False,'preview_encoding':'H264 CRF19, scaled, display only; shared original MKV unchanged',
|
| 173 |
-
'source_labels_from':'raw-derived diagnostic cache' if source!=p else 'shared unfiltered source-compatible labels',
|
| 174 |
-
'all_source_and_shared_valid_masks_used':True,'structure_checks':structural,'mano_valid_counts':valid.sum(0).tolist(),
|
| 175 |
-
'official_qa_pass_frames':int(qa.sum()) if qa is not None else None,'official_qa_fail_frames':int((~qa).sum()) if qa is not None else None,
|
| 176 |
-
'exposure_diagnostics':{'method':'scaled shared decoded RGB to 96x96 gray; p95<35 flags a candidate only, does not modify valid','suspect_dark_frame_indices':[x['frame_index'] for x in exposure if x['p95_luma']<35]}}
|
| 177 |
-
save(tmp/f'{cam}-exposure.json',exposure)
|
| 178 |
-
save(tmp/f'{cam}-video-result.json',result);print('VIDEO_COMPLETE',dataset,cam,T,flush=True)
|
| 179 |
-
return result
|
| 180 |
-
|
| 181 |
-
def asset_preview(op,out):
|
| 182 |
-
"""Textured point-splat turntable plus the source texture; diagnostic, not photoreal rendering."""
|
| 183 |
-
p=op.parents[2];m=load(op/'metainfo.json');meshpath=p/m['mesh_ref']
|
| 184 |
-
if (op/'assets/mesh_tex.obj').exists():meshpath=op/'assets/mesh_tex.obj'
|
| 185 |
-
mesh=trimesh.load(meshpath,process=False,force='mesh');xyz=np.asarray(mesh.vertices);idx=np.arange(0,len(xyz),max(1,len(xyz)//35000));xyz=xyz[idx]
|
| 186 |
-
texture=getattr(mesh.visual.material,'image',None) if hasattr(mesh.visual,'material') else None
|
| 187 |
-
texture_source=None
|
| 188 |
-
if meshpath.name=='mesh_tex.obj' and op.relative_to(DATA_ROOT).parts[0]=='ARCTIC':
|
| 189 |
-
# The loader can silently return a 2x2 default material. Resolve the
|
| 190 |
-
# official single-texture MTL explicitly instead of accepting that placeholder.
|
| 191 |
-
mtl=[r.split(maxsplit=1)[1] for r in meshpath.read_text().splitlines() if r.startswith('mtllib ')]
|
| 192 |
-
diffuse=[]
|
| 193 |
-
for name in mtl:
|
| 194 |
-
material=meshpath.parent/name
|
| 195 |
-
diffuse.extend(material.parent/r.split(maxsplit=1)[1] for r in material.read_text().splitlines() if r.startswith('map_Kd '))
|
| 196 |
-
diffuse=list(set(diffuse));assert len(diffuse)==1,(meshpath,diffuse)
|
| 197 |
-
assert diffuse[0].resolve().is_relative_to(meshpath.parent.resolve())
|
| 198 |
-
texture=Image.open(diffuse[0]).convert('RGB');assert min(texture.size)>2
|
| 199 |
-
texture_source={'file':diffuse[0].relative_to(p).as_posix(),'sha256':digest(diffuse[0]),'size':list(texture.size),'resolution_method':'explicit official MTL map_Kd; reject loader placeholder'}
|
| 200 |
-
if texture is not None and getattr(mesh.visual,'uv',None) is not None:
|
| 201 |
-
tex=np.asarray(texture.convert('RGB'));uv=np.asarray(mesh.visual.uv)[idx]
|
| 202 |
-
rgb=tex[np.clip(np.rint((1-uv[:,1])*(len(tex)-1)).astype(int),0,len(tex)-1),np.clip(np.rint(uv[:,0]*(tex.shape[1]-1)).astype(int),0,tex.shape[1]-1)]
|
| 203 |
-
else:rgb=np.broadcast_to([150,210,245],xyz.shape).astype(np.uint8)
|
| 204 |
-
extent=np.ptp(xyz,axis=0);xyz=xyz-(xyz.min(0)+xyz.max(0))/2;scale=300/max(np.linalg.norm(extent),.001)
|
| 205 |
-
logpath=DATA_ROOT/op.relative_to(DATA_ROOT).parts[0]/'tmp'/VIDEO_RUN/'assets.log'
|
| 206 |
-
logpath.parent.mkdir(parents=True,exist_ok=True)
|
| 207 |
-
out.parent.mkdir(parents=True,exist_ok=True)
|
| 208 |
-
with logpath.open('ab') as log:
|
| 209 |
-
enc=encoder(out,12,log,size=(800,480))
|
| 210 |
-
for i in range(72):
|
| 211 |
-
image=np.full((480,800,3),24,np.uint8);R=Rotation.from_euler('xy',[.35,i*2*np.pi/72]).as_matrix();v=xyz@R.T
|
| 212 |
-
order=np.argsort(v[:,2]);xy=np.rint(v[:,:2]*scale+[220,220]).astype(int)
|
| 213 |
-
good=(xy[:,0]>=0)&(xy[:,0]<430)&(xy[:,1]>=35)&(xy[:,1]<400);order=order[good[order]]
|
| 214 |
-
for dx,dy in [(0,0),(1,0),(0,1)]:image[np.clip(xy[order,1]+dy,0,479),np.clip(xy[order,0]+dx,0,429)]=rgb[order]
|
| 215 |
-
if texture is not None:
|
| 216 |
-
thumb=texture.convert('RGB');thumb.thumbnail((350,345));image[40:40+thumb.height,440:440+thumb.width]=np.asarray(thumb)
|
| 217 |
-
text(image,m.get('category_name',m['object_id']),(12,25),size=.65)
|
| 218 |
-
text(image,'TEXTURED 3D POINT PREVIEW',(12,420),size=.55);text(image,'SOURCE MATERIAL TEXTURE',(445,420),size=.5)
|
| 219 |
-
text(image,'OBJ extent (m): '+np.array2string(extent,precision=4),(12,450),size=.5);enc.stdin.write(image.tobytes())
|
| 220 |
-
enc.stdin.close();assert enc.wait()==0
|
| 221 |
-
assert len(framehash(['-i',str(out)],copy=True))==72
|
| 222 |
-
return {'object_id':m['object_id'],'video_ref':'assets/'+out.name,'frames':72,'texture_present':texture is not None,'texture_source':texture_source,'extent_m':extent.tolist(),'method':'diagnostic textured point turntable, not photoreal material rendering'}
|
| 223 |
-
|
| 224 |
-
def publish_review(dataset,results,assets):
|
| 225 |
-
root=DATA_ROOT/dataset/RELEASE;doc=root/'doc/validation'
|
| 226 |
-
scope=[('RGB','全部帧原图与逐帧码流/像素校验'),('相机内参/畸变','投影使用声明模型和全部参数;HUD显示相机模型'),('相机外参','全帧姿态、米制相机位置与世界XZ轨迹'),('MANO','逐帧网格线框、派生关节点、左右手valid'),('物体姿态/几何','逐帧轮廓、局部XYZ轴、物体ID'),('材质/纹理','每个物体的原纹理与完整旋转预览')]
|
| 227 |
-
scope+=([('部件/关节','底座/顶盖分别着色,逐帧关节角'),('物体关键点','源32个物体点逐帧叠加'),('visibility','原数据未提供,明确缺省')] if dataset=='ARCTIC' else [('visibility','原值0–1已修正,原生/可用比例同时显示'),('官方QA','完整红绿时间带;QA失败帧保留诊断、停用监督'),('部件/关节、独立物体关键点','本序列无该源模态,不虚构')])
|
| 228 |
-
scope+=[('深度/像素分割/接触','本次raw范围未提供,不以投影或帧筛选CSV冒充')]
|
| 229 |
-
table=''.join(f'<tr><td>{a}</td><td>{b}</td></tr>' for a,b in scope)
|
| 230 |
-
cards=''.join(f'<section><h2>Camera {r["camera_id"]} · {r["frames"]} 帧 · 有效MANO左右 {r["mano_valid_counts"]}</h2><video controls preload="metadata" src="{r["video_ref"]}"></video><p>全部{r["rendered_frames"]}帧已渲染,无码帧跳过。官方QA通过/未通过:{r["official_qa_pass_frames"]}/{r["official_qa_fail_frames"]}(null表示来源无此QA)。</p></section>' for r in results)
|
| 231 |
-
gallery=''.join(f'<section><h3>物体 {a["object_id"]}</h3><video controls loop preload="metadata" src="{a["video_ref"]}"></video><p>纹理点云旋转预览及原始材质图;此预览不证明完整PBR渲染等价。</p></section>' for a in assets)
|
| 232 |
-
known=('已修正转换器颠倒顶盖/底座编码的错误:原parts.json的0是顶盖、1是底座,共享层重新映射为0底座/1顶盖。9路相机前两帧均为源欠曝图,已排除对应几何监督;camera 6 index 270的手部偏移作为已知问题记录,按用户要求撤销单帧屏蔽,恢复原标注和valid。整套试点仍待验收。中栏显示源参数诊断,右栏按当前valid绘制。详见 <a href="ARCTIC_FINDINGS.md">问题与修复证据</a>、<a href="diagnosis/camera6-270-before-after.jpg">修复前后对照</a>
|
| 233 |
-
page=f'''<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{dataset} 完整视频审核 v2</title><style>body{{font:16px/1.7 system-ui;background:#edf1f7;color:#172136;max-width:1550px;margin:25px auto;padding:0 20px}}header,section{{background:white;padding:22px;border-radius:12px;margin-bottom:20px}}video{{width:100%;background:#151515}}h1{{margin:0}}.warn{{color:#a71d2b;font-weight:bold}}table{{border-collapse:collapse;width:100%}}td,th{{border:1px solid #ccd4df;padding:8px;text-align:left}}.assets{{display:grid;grid-template-columns:repeat(auto-fit,minmax(500px,1fr));gap:18px}}a{{color:#1567a3}}</style><header><h1>{dataset} · 完整序列审核 v2</h1><p class="warn">人工确认待完成。旧“抽帧投影通过”结论撤回,本页替代旧报告;尚未全量或发布。</p><p>视频三栏:原图 | 原始标注诊断 | 共享层有效监督。所有相机、所有帧都已渲染;青=左手,橙=右手,其他色=物体/部件,白点=MANO派生关节点或源物体关键点。投影不做遮挡剔除,也不是分割真值。</p><p>{known}</p><p>标注 valid=实际标注存在且数值合法,并通过适用官方QA及已明确登记的本地排除规则;可见性不代替valid,剩余帧不因此自动认定人工通过。诊断中被排除的参数不进入有效监督,raw保留。MP4经过缩放与展示编码,仅为doc预览,训练输入仍是无新增损失的shared MKV。</p><p><a href="REPORT.md">正式说明</a> · <a href="report.json">逐相机检查结果</a> · <a href="../RAW_TO_SHARED.md">字段映射</a> · <a href="../CONTRACT.md">更新后的valid定义</a></p><h2>逐模态检查覆盖</h2><table><tr><th>模态</th><th>检查/可视化方式</th></tr>{table}</table></header>{cards}<h2>物体资产检查</h2><div class="assets">{gallery}</div><script>document.querySelectorAll('video').forEach(v=>v.addEventListener('play',()=>document.querySelectorAll('video').forEach(o=>{{if(o!==v)o.pause()}})));</script></html>'''
|
| 234 |
-
(doc/'index.html').write_text(page,encoding='utf-8')
|
| 235 |
-
old=load(doc/'report.json');old.update(stage='full_video_review_awaiting_human',human_review='pending',review_revision='full-video-v2',
|
| 236 |
-
old_sample_projection_conclusion='withdrawn',full_video_views=results,asset_previews=assets,modality_coverage=[{'modality':a,'check':b} for a,b in scope],known_issues=known,
|
| 237 |
-
agent_visual_inspection={'status':'pending_new_full_video_review','not_equivalent_to_user_approval':True},created_at=datetime.now().astimezone().isoformat())
|
| 238 |
-
old.pop('views',None);old.pop('offline_artifact_check',None);save(doc/'report.json',old)
|
| 239 |
-
save(doc/'status.json',{'stage':'full_video_review_awaiting_human','human_review':'pending','full_preprocessing_authorized':False,'upload_authorized':False})
|
| 240 |
-
rows='\n'.join(f'| {r["camera_id"]} | {r["frames"]} | {r["rendered_frames"]} | {r["mano_valid_counts"]} | {r["official_qa_pass_frames"]} |' for r in results)
|
| 241 |
-
(doc/'REPORT.md').write_text(f'# {dataset} 完整序列审核 v2\n\n[离线完整视频](index.html) · [机器结果](report.json)\n\n人工确认待完成;旧抽帧投影通过结论撤回。{known}\n\n|相机|源帧数|渲染帧数|左右手有效标注帧数|官方QA通过帧数|\n|---|---:|---:|---|---:|\n{rows}\n\n## 逐模态覆盖\n\n'+''.join(f'- {a}:{b}。\n' for a,b in scope)+'\n完整视频表示每帧已渲染,并不等于每帧人工审核通过。被官方QA排除的源标注仅在诊断栏显示;不挪帧、不隐藏原始异常。所有有效性筛选、可见性与图像编码验收分开记录。源标注质量问题无法通过格式转换修好;通过valid屏蔽,并保留raw溯源。\n',encoding='utf-8')
|
| 242 |
-
for f in ['CONTRACT.md','schema.json']:shutil.copyfile(WORK/'distribution/hand-warehouse-1.0'/f,root/'doc'/f)
|
| 243 |
-
|
| 244 |
-
print('FULL_VIDEO_REVIEW_READY',dataset,flush=True)
|
| 245 |
-
|
| 246 |
-
if __name__=='__main__':
|
| 247 |
-
ap=argparse.ArgumentParser();ap.add_argument('dataset',choices=['HOT3D','ARCTIC']);a=ap.parse_args();torch.set_num_threads(3)
|
| 248 |
-
root=DATA_ROOT/a.dataset/RELEASE;qa=load(root/'doc/validation/source_qa.json') if a.dataset=='HOT3D' else None
|
| 249 |
-
# This entry point owns the original single-sequence report. Other review
|
| 250 |
-
# sequences have their own output directories in arctic_object_review.py.
|
| 251 |
-
sequence={'ARCTIC':'s09_laptop_use_03','HOT3D':'P0015_179e1b84'}[a.dataset]
|
| 252 |
-
views=sorted(p.parent for p in (root/'data'/sequence).glob('*/metainfo.json'));results=[]
|
| 253 |
-
for p in views:results.append(render_view(p,a.dataset,qa))
|
| 254 |
-
assets=[]
|
| 255 |
-
for op in sorted((views[0]/'annotation/object').iterdir()):assets.append(asset_preview(op,root/'doc/validation/assets'/f'{op.name}.mp4'))
|
| 256 |
-
publish_review(a.dataset,results,assets)
|
|
|
|
| 1 |
+
"""Full-frame, all-camera diagnostic videos read from actual shared tensors/media.
|
| 2 |
+
|
| 3 |
+
Preview MP4 is explicitly display-only; warehouse MKV packets remain untouched.
|
| 4 |
+
"""
|
| 5 |
+
from fresh_sequence_common import *
|
| 6 |
+
from review_fresh_sequence_pilots import arr, validate_view, project_for_view
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
import html
|
| 9 |
+
|
| 10 |
+
VIDEO_RUN='full-video-review-v2'
|
| 11 |
+
CELL=512
|
| 12 |
+
WIDTH=3*CELL
|
| 13 |
+
HEIGHT=800
|
| 14 |
+
COLORS=[(110,255,100),(255,80,210),(240,220,60),(90,180,255),(190,160,255),(255,120,140)]
|
| 15 |
+
|
| 16 |
+
def text(im,txt,xy,color=(235,235,235),size=.5):cv2.putText(im,txt,xy,cv2.FONT_HERSHEY_SIMPLEX,size,color,1,cv2.LINE_AA)
|
| 17 |
+
|
| 18 |
+
def fast_edges(im,uv,edges,color):
|
| 19 |
+
xy=uv[edges];good=np.isfinite(xy).all((1,2)) & (np.max(np.nan_to_num(np.abs(xy),nan=CELL*20),axis=(1,2))<CELL*12)
|
| 20 |
+
xy=xy[good];xy=xy[np.linalg.norm(xy[:,0]-xy[:,1],axis=1)<CELL*.7]
|
| 21 |
+
if len(xy):cv2.polylines(im,np.rint(xy).astype(np.int32),False,color,1,cv2.LINE_AA)
|
| 22 |
+
|
| 23 |
+
def dots(im,uv,color,radius=2):
|
| 24 |
+
good=np.isfinite(uv).all(1)&(uv[:,0]>=0)&(uv[:,0]<im.shape[1])&(uv[:,1]>=0)&(uv[:,1]<im.shape[0])
|
| 25 |
+
xy=np.rint(uv[good]).astype(int);xy[:,0]=np.clip(xy[:,0],0,im.shape[1]-1);xy[:,1]=np.clip(xy[:,1],0,im.shape[0]-1)
|
| 26 |
+
for d in range(max(1,radius)):
|
| 27 |
+
im[np.clip(xy[:,1]+d,0,im.shape[0]-1),xy[:,0]]=color
|
| 28 |
+
im[xy[:,1],np.clip(xy[:,0]+d,0,im.shape[1]-1)]=color
|
| 29 |
+
|
| 30 |
+
def model_vertices(motion,valid,side,fix):
|
| 31 |
+
model=Mano(['left','right'][side])
|
| 32 |
+
if side==0 and fix:
|
| 33 |
+
model.data['shapedirs'][:,0]*=-1
|
| 34 |
+
with torch.no_grad():model.layer.shapedirs[:,0]*=-1
|
| 35 |
+
verts=np.full((len(motion),778,3),np.nan,np.float32);joints=np.full((len(motion),16,3),np.nan,np.float32)
|
| 36 |
+
ids=np.flatnonzero(valid[:,side])
|
| 37 |
+
for start in range(0,len(ids),64):
|
| 38 |
+
ix=ids[start:start+64];a=motion[ix,side];verts[ix],_,joints[ix]=model.geometry(a[:,:48],a[:,48:58],a[:,58:])
|
| 39 |
+
faces=np.asarray(model.layer.faces);edges=np.unique(np.sort(np.concatenate([faces[:,[0,1]],faces[:,[1,2]],faces[:,[2,0]]]),axis=1),axis=0)
|
| 40 |
+
return verts,joints,edges
|
| 41 |
+
|
| 42 |
+
def encoder(path,fps,log,size=(WIDTH,HEIGHT)):
|
| 43 |
+
path.parent.mkdir(parents=True,exist_ok=True)
|
| 44 |
+
return subprocess.Popen([str(FF),'-v','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s',f'{size[0]}x{size[1]}','-r',str(fps),'-i','pipe:0',
|
| 45 |
+
'-an','-c:v','libx264','-preset','veryfast','-crf','19','-pix_fmt','yuv420p','-threads','2','-bf','0','-g','60','-movflags','+faststart',str(path)],stdin=subprocess.PIPE,stderr=log)
|
| 46 |
+
|
| 47 |
+
def read_exact(pipe,n):
|
| 48 |
+
chunks=[];count=0
|
| 49 |
+
while count<n:
|
| 50 |
+
b=pipe.read(n-count)
|
| 51 |
+
if not b:break
|
| 52 |
+
chunks.append(b);count+=len(b)
|
| 53 |
+
return b''.join(chunks)
|
| 54 |
+
|
| 55 |
+
def trajectory_plot(E,width=265,height=145):
|
| 56 |
+
good=np.isfinite(E).all((1,2));xyz=np.full((len(E),3),np.nan)
|
| 57 |
+
xyz[good]=-(np.swapaxes(E[good,:3,:3],1,2)@E[good,:3,3,None])[:,:,0]
|
| 58 |
+
base=np.full((height,width,3),24,np.uint8);xy=xyz[:,[0,2]];valid=np.isfinite(xy).all(1)
|
| 59 |
+
if not valid.any():return base,np.zeros((len(E),2),int),xyz
|
| 60 |
+
lo=np.nanmin(xy,0);hi=np.nanmax(xy,0);span=np.maximum(hi-lo,.05);scale=min((width-24)/span[0],(height-35)/span[1]);pix=(xy-lo)*scale+12
|
| 61 |
+
pix[:,1]=height-12-pix[:,1];pixels=np.nan_to_num(pix).astype(int)
|
| 62 |
+
for i in range(1,len(E)):
|
| 63 |
+
if valid[i-1] and valid[i]:cv2.line(base,tuple(pixels[i-1]),tuple(pixels[i]),(110,110,110),1)
|
| 64 |
+
text(base,'camera world trajectory X/Z (m)',(7,15),size=.38)
|
| 65 |
+
return base,pixels,xyz
|
| 66 |
+
|
| 67 |
+
def object_specs(p,source):
|
| 68 |
+
result=[]
|
| 69 |
+
for k,op in enumerate(sorted((p/'annotation/object').glob('*'))):
|
| 70 |
+
if not (op/'pose.pt').exists():continue
|
| 71 |
+
om=load(op/'metainfo.json');rel=op.relative_to(p);mesh=trimesh.load(p/om['mesh_ref'],process=False,force='mesh')
|
| 72 |
+
rawpose=arr(source/rel/'pose.pt');rawvalid=arr(source/rel/'pose_valid.pt');valid=arr(op/'pose_valid.pt')
|
| 73 |
+
spec={'id':om['object_id'],'name':om.get('category_name',om['object_id']),'color':COLORS[k%len(COLORS)],'P':rawpose,'rawvalid':rawvalid,'valid':valid,'op':op}
|
| 74 |
+
if 'vertex_part_ids_ref' in om:
|
| 75 |
+
xyz=np.array([[float(x) for x in r.split()[1:4]] for r in (p/om['mesh_ref']).read_text().splitlines() if r.startswith('v ')])
|
| 76 |
+
part=arr(p/om['vertex_part_ids_ref']);idx=np.arange(0,len(xyz),max(1,len(xyz)//4500))
|
| 77 |
+
spec.update(vertices=xyz[idx],parts=part[idx],top=arr(source/rel/'parts/top/pose.pt'),edges=None,
|
| 78 |
+
keypoints=arr(source/rel/'keypoints/xyz.pt'),joint=arr(source/rel/'joint_state.pt')[:,0])
|
| 79 |
+
else:
|
| 80 |
+
edges=np.asarray(mesh.edges_unique);edges=edges[::max(1,len(edges)//1100)]
|
| 81 |
+
unique,inv=np.unique(edges,return_inverse=True);spec.update(vertices=np.asarray(mesh.vertices)[unique],edges=inv.reshape(-1,2),parts=None)
|
| 82 |
+
spec['visibility']=arr(op/'visibility.pt') if (op/'visibility.pt').exists() else None
|
| 83 |
+
spec['raw_visibility']=arr(source/rel/'visibility.pt') if (source/rel/'visibility.pt').exists() else None
|
| 84 |
+
result.append(spec)
|
| 85 |
+
return result
|
| 86 |
+
|
| 87 |
+
def render_view(p,dataset,qa_data,doc=None,tmp=None,source=None,snapshot_indices=None):
|
| 88 |
+
m,frames,structural=validate_view(p);cam=m['camera_id'];T=m['num_frames'];root=DATA_ROOT/dataset/RELEASE
|
| 89 |
+
doc=doc or root/'doc/validation';tmp=tmp or DATA_ROOT/dataset/'tmp'/VIDEO_RUN;tmp.mkdir(parents=True,exist_ok=True)
|
| 90 |
+
if source is None:
|
| 91 |
+
source=p
|
| 92 |
+
for candidate in [DATA_ROOT/dataset/'tmp'/VIDEO_RUN/'diagnostic'/m['sequence_id']/cam,DATA_ROOT/dataset/'tmp'/VIDEO_RUN/'diagnostic'/cam]:
|
| 93 |
+
if (candidate/'snapshot.json').exists() and Path(load(candidate/'snapshot.json')['source_view']).resolve()==p.resolve():source=candidate;break
|
| 94 |
+
qa=np.array(qa_data[cam]['qa_pass'],bool) if dataset=='HOT3D' and qa_data and qa_data[cam].get('qa_pass') is not None else None
|
| 95 |
+
if 'mano' in m['components']:
|
| 96 |
+
motion=arr(source/'annotation/mano/motion.pt');present=arr(source/'annotation/mano/motion_valid.pt');valid=arr(p/'annotation/mano/motion_valid.pt')
|
| 97 |
+
else:motion=np.full((T,2,61),np.nan);present=np.zeros((T,2),bool);valid=present.copy()
|
| 98 |
+
visibility=arr(p/'annotation/mano/visibility.pt') if (p/'annotation/mano/visibility.pt').exists() else None
|
| 99 |
+
rawvis=arr(source/'annotation/mano/visibility.pt') if (source/'annotation/mano/visibility.pt').exists() else None
|
| 100 |
+
hands=[model_vertices(motion,present,s,m['components'].get('mano',{}).get('model_profile',{}).get('left_shapedirs_fix',False)) for s in range(2)]
|
| 101 |
+
objs=object_specs(p,source);K=arr(p/'camera/intrinsic.pt') if (p/'camera/intrinsic.pt').exists() else np.full((T,3,3),np.nan);D=arr(p/'camera/distortion.pt') if (p/'camera/distortion.pt').exists() else None;E=arr(p/'camera/extrinsic.pt') if (p/'camera/extrinsic.pt').exists() else np.full((T,4,4),np.nan)
|
| 102 |
+
W,H=m['camera']['image_size'];scale0=min(CELL/W,CELL/H);w=int(W*scale0)//2*2;h=int(H*scale0)//2*2;scale=np.array([w/W,h/H])
|
| 103 |
+
fps=m['sampling']['source_fps'] or 30;path=doc/'videos'/f'{cam}-full.mp4';logpath=tmp/f'render-{cam}.log';log=logpath.open('wb')
|
| 104 |
+
dec=subprocess.Popen([str(FF),'-v','error','-threads','2','-noautorotate','-i',str(p/'observation/rgb.mkv'),'-vf',f'scale={w}:{h}','-pix_fmt','rgb24','-fps_mode','passthrough','-f','rawvideo','pipe:1'],stdout=subprocess.PIPE,stderr=log)
|
| 105 |
+
enc=encoder(path,fps,log);traj,tp,world=trajectory_plot(E);rendered=0;exposure=[]
|
| 106 |
+
snapshots=sorted(set(snapshot_indices or [0,1,26,27,179,180,T//4,T//2,3*T//4,T-1]))
|
| 107 |
+
timeline=np.zeros((12,WIDTH,3),np.uint8)
|
| 108 |
+
for x in range(WIDTH):timeline[:,x]=(40,135,65) if qa is not None and qa[min(T-1,x*T//WIDTH)] else ((170,42,50) if qa is not None else (75,80,95))
|
| 109 |
+
for i in range(T):
|
| 110 |
+
b=read_exact(dec.stdout,w*h*3);assert len(b)==w*h*3,(cam,i,'decoder ended early')
|
| 111 |
+
original=np.frombuffer(b,np.uint8).reshape(h,w,3).copy();raw=original.copy();usable=original.copy()
|
| 112 |
+
gray=cv2.cvtColor(cv2.resize(original,(96,96)),cv2.COLOR_RGB2GRAY)
|
| 113 |
+
exposure.append({'frame_index':i,'p95_luma':float(np.percentile(gray,95)),'median_luma':float(np.median(gray))})
|
| 114 |
+
params=K[i] if m['camera']['model']=='fisheye624' else (K[i],D[i] if D is not None else None)
|
| 115 |
+
for side,(verts,joints,edges) in enumerate(hands):
|
| 116 |
+
if not present[i,side]:continue
|
| 117 |
+
uv=project_for_view(verts[i],m,params,scale);color=(0,235,255) if side==0 else (255,135,20)
|
| 118 |
+
fast_edges(raw,uv,edges,color)
|
| 119 |
+
if valid[i,side]:fast_edges(usable,uv,edges,color)
|
| 120 |
+
# White MANO joints are a diagnostic derivation, not a new keypoint component.
|
| 121 |
+
dots(raw,project_for_view(joints[i],m,params,scale),(255,255,255),2)
|
| 122 |
+
if valid[i,side]:dots(usable,project_for_view(joints[i],m,params,scale),(255,255,255),2)
|
| 123 |
+
for obj in objs:
|
| 124 |
+
if not obj['rawvalid'][i]:continue
|
| 125 |
+
P=obj['P'][i];xyz=obj['vertices']@P[:3,:3].T+P[:3,3]
|
| 126 |
+
if obj['parts'] is not None:
|
| 127 |
+
top=obj['top'][i];sel=obj['parts']==1;xyz[sel]=obj['vertices'][sel]@top[:3,:3].T+top[:3,3]
|
| 128 |
+
uv=project_for_view(xyz,m,params,scale)
|
| 129 |
+
for image,enabled in [(raw,True),(usable,obj['valid'][i])]:
|
| 130 |
+
if not enabled:continue
|
| 131 |
+
if obj['edges'] is not None:fast_edges(image,uv,obj['edges'],obj['color'])
|
| 132 |
+
else:
|
| 133 |
+
dots(image,uv[obj['parts']==0],(100,240,90));dots(image,uv[obj['parts']==1],(230,80,230))
|
| 134 |
+
dots(image,project_for_view(obj['keypoints'][i],m,params,scale),(255,255,255),3)
|
| 135 |
+
# Local object axes in metres make pose orientation visible.
|
| 136 |
+
axes=np.vstack([np.zeros(3),np.eye(3)*.045])@P[:3,:3].T+P[:3,3];auv=project_for_view(axes,m,params,scale)
|
| 137 |
+
for j,c in enumerate([(255,60,60),(60,255,60),(60,120,255)]):fast_edges(image,auv,np.array([[0,j+1]]),c)
|
| 138 |
+
canvas=np.full((HEIGHT,WIDTH,3),20,np.uint8)
|
| 139 |
+
for col,(im,label) in enumerate([(original,'SOURCE RGB'),(raw,'NATIVE LABEL DIAGNOSTIC'),(usable,'SHARED USABLE SUPERVISION')]):
|
| 140 |
+
canvas[40+(CELL-h)//2:40+(CELL-h)//2+h,col*CELL+(CELL-w)//2:col*CELL+(CELL-w)//2+w]=im
|
| 141 |
+
text(canvas,label,(col*CELL+12,25),size=.58)
|
| 142 |
+
status='NO OFFICIAL QA PROVIDED' if qa is None else ('OFFICIAL QA PASS' if qa[i] else 'OFFICIAL QA FAIL - NOT SUPERVISION')
|
| 143 |
+
if dataset=='ARCTIC' and i in m['components'].get('mano',{}).get('valid_policy',{}).get('local_excluded_frame_indices',[]):status='LOCAL REVIEW REJECT - NOT HAND SUPERVISION'
|
| 144 |
+
color=(235,195,65) if qa is None else ((80,240,110) if qa[i] else (255,90,90))
|
| 145 |
+
text(canvas,f'{dataset} {cam} index={i}/{T-1} source={frames[i]["source_frame_id"]} {status}',(12,578),color,.6)
|
| 146 |
+
text(canvas,f'MANO source L/R={int(present[i,0])}/{int(present[i,1])} shared valid L/R={int(valid[i,0])}/{int(valid[i,1])} (m/rad)',(12,603),size=.49)
|
| 147 |
+
def vals(a):return 'n/a' if a is None else ','.join('unknown' if not np.isfinite(x) else f'{100*x:.1f}%' for x in np.atleast_1d(a))
|
| 148 |
+
text(canvas,f'visibility native L/R: {vals(rawvis[i] if rawvis is not None else None)} usable: {vals(visibility[i] if visibility is not None else None)}',(12,626),size=.48)
|
| 149 |
+
text(canvas,f'camera={m["camera"]["model"]}; intrinsic '+np.array2string(K[i].ravel()[:5],precision=2),(12,649),size=.45)
|
| 150 |
+
text(canvas,'camera world position (m): '+np.array2string(world[i],precision=3),(12,672),size=.45)
|
| 151 |
+
clock=frames[i]['timestamp_ns'];text(canvas,f'timestamp_ns={clock} clock={frames[i]["clock_domain"]}',(12,695),size=.44)
|
| 152 |
+
text(canvas,f'preview FPS={fps}; '+('capture FPS unknown, playback only' if m['sampling']['source_fps'] is None else 'source capture time is stored separately'),(12,718),size=.44)
|
| 153 |
+
text(canvas,'cyan=left; orange=right; white=derived MANO joints / source object points',(12,741),size=.41)
|
| 154 |
+
text(canvas,'Projection shows hidden surfaces; it is NOT native segmentation.',(12,762),(180,180,180),.43)
|
| 155 |
+
for j,obj in enumerate(objs):
|
| 156 |
+
a=obj['raw_visibility'];v=obj['visibility'];s=f'{obj["name"]}: valid={int(obj["valid"][i])}'
|
| 157 |
+
if a is not None:s+=f' vis={vals(v[i])} (raw {vals(a[i])})'
|
| 158 |
+
if 'joint' in obj:s+=f' hinge={obj["joint"][i]:.3f}rad keypoints=32'
|
| 159 |
+
text(canvas,s,(660,603+j*24),obj['color'],.44)
|
| 160 |
+
tr=traj.copy()
|
| 161 |
+
if np.isfinite(world[i]).all():cv2.circle(tr,tuple(tp[i]),4,(255,220,70),-1)
|
| 162 |
+
canvas[610:755,WIDTH-277:WIDTH-12]=tr
|
| 163 |
+
canvas[-12:]=timeline;cursor=min(WIDTH-1,int(i*WIDTH/T));canvas[-12:,cursor:cursor+2]=255
|
| 164 |
+
enc.stdin.write(canvas.tobytes());rendered+=1
|
| 165 |
+
if i in snapshots:
|
| 166 |
+
snap=doc/'video_snapshots'/cam;snap.mkdir(parents=True,exist_ok=True);Image.fromarray(canvas).save(snap/f'{i:06d}.jpg',quality=92)
|
| 167 |
+
if i%200==0:print('VIDEO_FRAME',dataset,cam,i,T,flush=True)
|
| 168 |
+
assert not dec.stdout.read(1),'extra source frames';dec.stdout.close();assert dec.wait()==0
|
| 169 |
+
enc.stdin.close();assert enc.wait()==0;log.close();assert rendered==T
|
| 170 |
+
packets=framehash(['-i',str(path)],copy=True);assert len(packets)==T
|
| 171 |
+
result={'sequence_id':m['sequence_id'],'camera_id':cam,'frames':T,'rendered_frames':rendered,'video_ref':path.relative_to(doc).as_posix(),'video_sha256':digest(path),'preview_fps':fps,
|
| 172 |
+
'preview_is_training_data':False,'preview_encoding':'H264 CRF19, scaled, display only; shared original MKV unchanged',
|
| 173 |
+
'source_labels_from':'raw-derived diagnostic cache' if source!=p else 'shared unfiltered source-compatible labels',
|
| 174 |
+
'all_source_and_shared_valid_masks_used':True,'structure_checks':structural,'mano_valid_counts':valid.sum(0).tolist(),
|
| 175 |
+
'official_qa_pass_frames':int(qa.sum()) if qa is not None else None,'official_qa_fail_frames':int((~qa).sum()) if qa is not None else None,
|
| 176 |
+
'exposure_diagnostics':{'method':'scaled shared decoded RGB to 96x96 gray; p95<35 flags a candidate only, does not modify valid','suspect_dark_frame_indices':[x['frame_index'] for x in exposure if x['p95_luma']<35]}}
|
| 177 |
+
save(tmp/f'{cam}-exposure.json',exposure)
|
| 178 |
+
save(tmp/f'{cam}-video-result.json',result);print('VIDEO_COMPLETE',dataset,cam,T,flush=True)
|
| 179 |
+
return result
|
| 180 |
+
|
| 181 |
+
def asset_preview(op,out):
|
| 182 |
+
"""Textured point-splat turntable plus the source texture; diagnostic, not photoreal rendering."""
|
| 183 |
+
p=op.parents[2];m=load(op/'metainfo.json');meshpath=p/m['mesh_ref']
|
| 184 |
+
if (op/'assets/mesh_tex.obj').exists():meshpath=op/'assets/mesh_tex.obj'
|
| 185 |
+
mesh=trimesh.load(meshpath,process=False,force='mesh');xyz=np.asarray(mesh.vertices);idx=np.arange(0,len(xyz),max(1,len(xyz)//35000));xyz=xyz[idx]
|
| 186 |
+
texture=getattr(mesh.visual.material,'image',None) if hasattr(mesh.visual,'material') else None
|
| 187 |
+
texture_source=None
|
| 188 |
+
if meshpath.name=='mesh_tex.obj' and op.relative_to(DATA_ROOT).parts[0]=='ARCTIC':
|
| 189 |
+
# The loader can silently return a 2x2 default material. Resolve the
|
| 190 |
+
# official single-texture MTL explicitly instead of accepting that placeholder.
|
| 191 |
+
mtl=[r.split(maxsplit=1)[1] for r in meshpath.read_text().splitlines() if r.startswith('mtllib ')]
|
| 192 |
+
diffuse=[]
|
| 193 |
+
for name in mtl:
|
| 194 |
+
material=meshpath.parent/name
|
| 195 |
+
diffuse.extend(material.parent/r.split(maxsplit=1)[1] for r in material.read_text().splitlines() if r.startswith('map_Kd '))
|
| 196 |
+
diffuse=list(set(diffuse));assert len(diffuse)==1,(meshpath,diffuse)
|
| 197 |
+
assert diffuse[0].resolve().is_relative_to(meshpath.parent.resolve())
|
| 198 |
+
texture=Image.open(diffuse[0]).convert('RGB');assert min(texture.size)>2
|
| 199 |
+
texture_source={'file':diffuse[0].relative_to(p).as_posix(),'sha256':digest(diffuse[0]),'size':list(texture.size),'resolution_method':'explicit official MTL map_Kd; reject loader placeholder'}
|
| 200 |
+
if texture is not None and getattr(mesh.visual,'uv',None) is not None:
|
| 201 |
+
tex=np.asarray(texture.convert('RGB'));uv=np.asarray(mesh.visual.uv)[idx]
|
| 202 |
+
rgb=tex[np.clip(np.rint((1-uv[:,1])*(len(tex)-1)).astype(int),0,len(tex)-1),np.clip(np.rint(uv[:,0]*(tex.shape[1]-1)).astype(int),0,tex.shape[1]-1)]
|
| 203 |
+
else:rgb=np.broadcast_to([150,210,245],xyz.shape).astype(np.uint8)
|
| 204 |
+
extent=np.ptp(xyz,axis=0);xyz=xyz-(xyz.min(0)+xyz.max(0))/2;scale=300/max(np.linalg.norm(extent),.001)
|
| 205 |
+
logpath=DATA_ROOT/op.relative_to(DATA_ROOT).parts[0]/'tmp'/VIDEO_RUN/'assets.log'
|
| 206 |
+
logpath.parent.mkdir(parents=True,exist_ok=True)
|
| 207 |
+
out.parent.mkdir(parents=True,exist_ok=True)
|
| 208 |
+
with logpath.open('ab') as log:
|
| 209 |
+
enc=encoder(out,12,log,size=(800,480))
|
| 210 |
+
for i in range(72):
|
| 211 |
+
image=np.full((480,800,3),24,np.uint8);R=Rotation.from_euler('xy',[.35,i*2*np.pi/72]).as_matrix();v=xyz@R.T
|
| 212 |
+
order=np.argsort(v[:,2]);xy=np.rint(v[:,:2]*scale+[220,220]).astype(int)
|
| 213 |
+
good=(xy[:,0]>=0)&(xy[:,0]<430)&(xy[:,1]>=35)&(xy[:,1]<400);order=order[good[order]]
|
| 214 |
+
for dx,dy in [(0,0),(1,0),(0,1)]:image[np.clip(xy[order,1]+dy,0,479),np.clip(xy[order,0]+dx,0,429)]=rgb[order]
|
| 215 |
+
if texture is not None:
|
| 216 |
+
thumb=texture.convert('RGB');thumb.thumbnail((350,345));image[40:40+thumb.height,440:440+thumb.width]=np.asarray(thumb)
|
| 217 |
+
text(image,m.get('category_name',m['object_id']),(12,25),size=.65)
|
| 218 |
+
text(image,'TEXTURED 3D POINT PREVIEW',(12,420),size=.55);text(image,'SOURCE MATERIAL TEXTURE',(445,420),size=.5)
|
| 219 |
+
text(image,'OBJ extent (m): '+np.array2string(extent,precision=4),(12,450),size=.5);enc.stdin.write(image.tobytes())
|
| 220 |
+
enc.stdin.close();assert enc.wait()==0
|
| 221 |
+
assert len(framehash(['-i',str(out)],copy=True))==72
|
| 222 |
+
return {'object_id':m['object_id'],'video_ref':'assets/'+out.name,'frames':72,'texture_present':texture is not None,'texture_source':texture_source,'extent_m':extent.tolist(),'method':'diagnostic textured point turntable, not photoreal material rendering'}
|
| 223 |
+
|
| 224 |
+
def publish_review(dataset,results,assets):
|
| 225 |
+
root=DATA_ROOT/dataset/RELEASE;doc=root/'doc/validation'
|
| 226 |
+
scope=[('RGB','全部帧原图与逐帧码流/像素校验'),('相机内参/畸变','投影使用声明模型和全部参数;HUD显示相机模型'),('相机外参','全帧姿态、米制相机位置与世界XZ轨迹'),('MANO','逐帧网格线框、派生关节点、左右手valid'),('物体姿态/几何','逐帧轮廓、局部XYZ轴、物体ID'),('材质/纹理','每个物体的原纹理与完整旋转预览')]
|
| 227 |
+
scope+=([('部件/关节','底座/顶盖分别着色,逐帧关节角'),('物体关键点','源32个物体点逐帧叠加'),('visibility','原数据未提供,明确缺省')] if dataset=='ARCTIC' else [('visibility','原值0–1已修正,原生/可用比例同时显示'),('官方QA','完整红绿时间带;QA失败帧保留诊断、停用监督'),('部件/关节、独立物体关键点','本序列无该源模态,不虚构')])
|
| 228 |
+
scope+=[('深度/像素分割/接触','本次raw范围未提供,不以投影或帧筛选CSV冒充')]
|
| 229 |
+
table=''.join(f'<tr><td>{a}</td><td>{b}</td></tr>' for a,b in scope)
|
| 230 |
+
cards=''.join(f'<section><h2>Camera {r["camera_id"]} · {r["frames"]} 帧 · 有效MANO左右 {r["mano_valid_counts"]}</h2><video controls preload="metadata" src="{r["video_ref"]}"></video><p>全部{r["rendered_frames"]}帧已渲染,无码帧跳过。官方QA通过/未通过:{r["official_qa_pass_frames"]}/{r["official_qa_fail_frames"]}(null表示来源无此QA)。</p></section>' for r in results)
|
| 231 |
+
gallery=''.join(f'<section><h3>物体 {a["object_id"]}</h3><video controls loop preload="metadata" src="{a["video_ref"]}"></video><p>纹理点云旋转预览及原始材质图;此预览不证明完整PBR渲染等价。</p></section>' for a in assets)
|
| 232 |
+
known=('已修正转换器颠倒顶盖/底座编码的错误:原parts.json的0是顶盖、1是底座,共享层重新映射为0底座/1顶盖。9路相机前两帧均为源欠曝图,已排除对应几何监督;camera 6 index 270的手部偏移作为已知问题记录,按用户要求撤销单帧屏蔽,恢复原标注和valid。整套试点仍待验收。中栏显示源参数诊断,右栏按当前valid绘制。详见 <a href="ARCTIC_FINDINGS.md">问题与修复证据</a>、<a href="diagnosis/camera6-270-before-after.jpg">修复前后对照</a>。预览30fps仅用于播放,不代表真实采集帧率;没有源准确性QA。' if dataset=='ARCTIC' else '原始开头帧存在明显错位,官方QA为False;源头戴位姿开头27帧保持不变,帧号/时间/包顺序均未人为移动。中栏保留原始诊断投影,右栏只绘制当前valid监督。已修正visibility误除100。QA按相机整帧保守筛选,不能断言具体哪个实体错。')
|
| 233 |
+
page=f'''<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{dataset} 完整视频审核 v2</title><style>body{{font:16px/1.7 system-ui;background:#edf1f7;color:#172136;max-width:1550px;margin:25px auto;padding:0 20px}}header,section{{background:white;padding:22px;border-radius:12px;margin-bottom:20px}}video{{width:100%;background:#151515}}h1{{margin:0}}.warn{{color:#a71d2b;font-weight:bold}}table{{border-collapse:collapse;width:100%}}td,th{{border:1px solid #ccd4df;padding:8px;text-align:left}}.assets{{display:grid;grid-template-columns:repeat(auto-fit,minmax(500px,1fr));gap:18px}}a{{color:#1567a3}}</style><header><h1>{dataset} · 完整序列审核 v2</h1><p class="warn">人工确认待完成。旧“抽帧投影通过”结论撤回,本页替代旧报告;尚未全量或发布。</p><p>视频三栏:原图 | 原始标注诊断 | 共享层有效监督。所有相机、所有帧都已渲染;青=左手,橙=右手,其他色=物体/部件,白点=MANO派生关节点或源物体关键点。投影不做遮挡剔除,也不是分割真值。</p><p>{known}</p><p>标注 valid=实际标注存在且数值合法,并通过适用官方QA及已明确登记的本地排除规则;可见性不代替valid,剩余帧不因此自动认定人工通过。诊断中被排除的参数不进入有效监督,raw保留。MP4经过缩放与展示编码,仅为doc预览,训练输入仍是无新增损失的shared MKV。</p><p><a href="REPORT.md">正式说明</a> · <a href="report.json">逐相机检查结果</a> · <a href="../RAW_TO_SHARED.md">字段映射</a> · <a href="../CONTRACT.md">更新后的valid定义</a></p><h2>逐模态检查覆盖</h2><table><tr><th>模态</th><th>检查/可视化方式</th></tr>{table}</table></header>{cards}<h2>物体资产检查</h2><div class="assets">{gallery}</div><script>document.querySelectorAll('video').forEach(v=>v.addEventListener('play',()=>document.querySelectorAll('video').forEach(o=>{{if(o!==v)o.pause()}})));</script></html>'''
|
| 234 |
+
(doc/'index.html').write_text(page,encoding='utf-8')
|
| 235 |
+
old=load(doc/'report.json');old.update(stage='full_video_review_awaiting_human',human_review='pending',review_revision='full-video-v2',
|
| 236 |
+
old_sample_projection_conclusion='withdrawn',full_video_views=results,asset_previews=assets,modality_coverage=[{'modality':a,'check':b} for a,b in scope],known_issues=known,
|
| 237 |
+
agent_visual_inspection={'status':'pending_new_full_video_review','not_equivalent_to_user_approval':True},created_at=datetime.now().astimezone().isoformat())
|
| 238 |
+
old.pop('views',None);old.pop('offline_artifact_check',None);save(doc/'report.json',old)
|
| 239 |
+
save(doc/'status.json',{'stage':'full_video_review_awaiting_human','human_review':'pending','full_preprocessing_authorized':False,'upload_authorized':False})
|
| 240 |
+
rows='\n'.join(f'| {r["camera_id"]} | {r["frames"]} | {r["rendered_frames"]} | {r["mano_valid_counts"]} | {r["official_qa_pass_frames"]} |' for r in results)
|
| 241 |
+
(doc/'REPORT.md').write_text(f'# {dataset} 完整序列审核 v2\n\n[离线完整视频](index.html) · [机器结果](report.json)\n\n人工确认待完成;旧抽帧投影通过结论撤回。{known}\n\n|相机|源帧数|渲染帧数|左右手有效标注帧数|官方QA通过帧数|\n|---|---:|---:|---|---:|\n{rows}\n\n## 逐模态覆盖\n\n'+''.join(f'- {a}:{b}。\n' for a,b in scope)+'\n完整视频表示每帧已渲染,并不等于每帧人工审核通过。被官方QA排除的源标注仅在诊断栏显示;不挪帧、不隐藏原始异常。所有有效性筛选、可见性与图像编码验收分开记录。源标注质量问题无法通过格式转换修好;通过valid屏蔽,并保留raw溯源。\n',encoding='utf-8')
|
| 242 |
+
for f in ['CONTRACT.md','schema.json']:shutil.copyfile(WORK/'distribution/hand-warehouse-1.0'/f,root/'doc'/f)
|
| 243 |
+
# Keep the published script bundle immutable while regenerating review artifacts.
|
| 244 |
+
print('FULL_VIDEO_REVIEW_READY',dataset,flush=True)
|
| 245 |
+
|
| 246 |
+
if __name__=='__main__':
|
| 247 |
+
ap=argparse.ArgumentParser();ap.add_argument('dataset',choices=['HOT3D','ARCTIC']);a=ap.parse_args();torch.set_num_threads(3)
|
| 248 |
+
root=DATA_ROOT/a.dataset/RELEASE;qa=load(root/'doc/validation/source_qa.json') if a.dataset=='HOT3D' else None
|
| 249 |
+
# This entry point owns the original single-sequence report. Other review
|
| 250 |
+
# sequences have their own output directories in arctic_object_review.py.
|
| 251 |
+
sequence={'ARCTIC':'s09_laptop_use_03','HOT3D':'P0015_179e1b84'}[a.dataset]
|
| 252 |
+
views=sorted(p.parent for p in (root/'data'/sequence).glob('*/metainfo.json'));results=[]
|
| 253 |
+
for p in views:results.append(render_view(p,a.dataset,qa))
|
| 254 |
+
assets=[]
|
| 255 |
+
for op in sorted((views[0]/'annotation/object').iterdir()):assets.append(asset_preview(op,root/'doc/validation/assets'/f'{op.name}.mp4'))
|
| 256 |
+
publish_review(a.dataset,results,assets)
|
ARCTIC/shared-v1.0/script/internal/review_fresh_sequence_pilots.py
CHANGED
|
@@ -1,225 +1,223 @@
|
|
| 1 |
-
"""Validate actual shared outputs and create portable, offline pilot reviews.
|
| 2 |
-
|
| 3 |
-
Run after convert_fresh_sequence_pilots.py. Never authorizes full processing.
|
| 4 |
-
"""
|
| 5 |
-
from fresh_sequence_common import *
|
| 6 |
-
import html
|
| 7 |
-
from datetime import datetime
|
| 8 |
-
|
| 9 |
-
def arr(p):
|
| 10 |
-
value=torch.load(p,map_location='cpu',weights_only=True)
|
| 11 |
-
assert isinstance(value,torch.Tensor) and value.device.type=='cpu'
|
| 12 |
-
return value.numpy()
|
| 13 |
-
|
| 14 |
-
def safe_ref(root,ref):
|
| 15 |
-
path=(root/ref).resolve()
|
| 16 |
-
assert path.is_relative_to(root.resolve()) and path.is_file(),ref
|
| 17 |
-
return path
|
| 18 |
-
|
| 19 |
-
def validate_view(p):
|
| 20 |
-
m=load(p/'metainfo.json');T=m['num_frames'];registry=load(WORK/'distribution/hand-warehouse-1.0/schema.json')
|
| 21 |
-
assert m['schema_version']==registry['schema_version'] and m['pilot_complete']
|
| 22 |
-
frames=[json.loads(line) for line in (p/'camera/frames.jsonl').read_text().splitlines()]
|
| 23 |
-
assert len(frames)==T and [f['frame_index'] for f in frames]==list(range(T))
|
| 24 |
-
assert len({f['source_frame_id'] for f in frames})==T
|
| 25 |
-
for frame in frames:
|
| 26 |
-
for match in frame.get('annotation_matches',{}).values():
|
| 27 |
-
if 'available' in match:match['source_record_present']=match.pop('available')
|
| 28 |
-
lines(p/'camera/frames.jsonl',frames)
|
| 29 |
-
summary=[]
|
| 30 |
-
for key,c in m['components'].items():
|
| 31 |
-
assert c['schema_id'] in registry['components'],(key,c['schema_id'])
|
| 32 |
-
assert c['available'] and c['source_locator'] and c['provenance']['kind'] in ['source','derived','format_conversion']
|
| 33 |
-
data=safe_ref(p,c['data_ref']);valid=arr(safe_ref(p,c['valid_ref']))
|
| 34 |
-
assert valid.dtype==bool and valid.ndim==len(c['valid_axes'])
|
| 35 |
-
if data.suffix=='.pt':
|
| 36 |
-
a=arr(data);assert a.dtype==np.float32 and a.shape[0]==T
|
| 37 |
-
assert a.shape[:valid.ndim]==valid.shape and len(c['axes'])==a.ndim
|
| 38 |
-
assert np.isfinite(a[valid]).all() and np.isnan(a[~valid]).all()
|
| 39 |
-
if c['schema_id'] in ['object/rigid/v1','transform/se3/v1']:assert_se3(a[valid])
|
| 40 |
-
if c['schema_id']=='mano/axis_angle61/v1':assert a.shape==(T,2,61)
|
| 41 |
-
elif data.suffix=='.mkv':
|
| 42 |
-
assert c['storage']['profile'] in registry['storage_profiles']
|
| 43 |
-
assert valid.shape==(T,) and valid.all()
|
| 44 |
-
for attr in c.get('attributes',{}).values():
|
| 45 |
-
a=arr(safe_ref(p,attr['data_ref']));b=arr(safe_ref(p,attr['valid_ref']))
|
| 46 |
-
assert b.dtype==bool and a.shape==b.shape
|
| 47 |
-
assert np.isfinite(a[b]).all() and ((a[b]>=0)&(a[b]<=1)).all() and np.isnan(a[~b]).all()
|
| 48 |
-
if 'distortion_ref' in c:
|
| 49 |
-
d=arr(safe_ref(p,c['distortion_ref']));assert d.shape==(T,8) and np.isfinite(d).all()
|
| 50 |
-
summary.append({'component':key,'schema':c['schema_id'],'valid':int(valid.sum()),'total':int(valid.size)})
|
| 51 |
-
for op in sorted((p/'annotation/object').glob('*')):
|
| 52 |
-
om=load(op/'metainfo.json');mesh=safe_ref(p,om['mesh_ref'])
|
| 53 |
-
if 'vertex_part_ids_ref' in om:
|
| 54 |
-
ids=arr(safe_ref(p,om['vertex_part_ids_ref']));assert ids.dtype==np.int64
|
| 55 |
-
assert len(ids)==sum(line.startswith('v ') for line in mesh.read_text().splitlines())
|
| 56 |
-
assert om['topology_id']=='sha256:'+digest(mesh)
|
| 57 |
-
if not (op/'pose.pt').exists():
|
| 58 |
-
assert m.get('omitted_components',{}).get('object_pose')
|
| 59 |
-
else:
|
| 60 |
-
root=arr(op/'pose.pt');top=arr(op/'parts/top/pose.pt');joint=arr(op/'joint_state.pt')[:,0]
|
| 61 |
-
ok=arr(op/'pose_valid.pt');H=np.broadcast_to(np.eye(4),(ok.sum(),4,4)).copy()
|
| 62 |
-
H[:,:3,:3]=Rotation.from_rotvec(np.c_[np.zeros((ok.sum(),2)),-joint[ok]]).as_matrix()
|
| 63 |
-
if ok.any():assert np.max(np.abs(root[ok]@H-top[ok]))<2e-6
|
| 64 |
-
for obj in (op/'assets').glob('*.obj'):
|
| 65 |
-
for row in obj.read_text().splitlines():
|
| 66 |
-
if row.startswith('mtllib '):
|
| 67 |
-
material=safe_ref(obj.parent,row.split(maxsplit=1)[1])
|
| 68 |
-
for r in material.read_text().splitlines():
|
| 69 |
-
if r.lower().startswith('map_kd '):safe_ref(material.parent,r.split(maxsplit=1)[1])
|
| 70 |
-
records=load(DATA_ROOT/m['dataset_id']/'tmp'/RUN/'checks'/f'{m["sequence_id"]}__{m["camera_id"]}.json')['checks']
|
| 71 |
-
assert records and all(x.get('passed',False) for x in records)
|
| 72 |
-
media=next(r for r in records if r['test'] in ['all_source_JPEG_packets_and_RGB_pixels_exact','all_source_JPEG_packets_exact']);assert media['frames']==T
|
| 73 |
-
if media['test']=='all_source_JPEG_packets_exact':
|
| 74 |
-
pixels=next(r for r in records if r['test']=='source_RGB_pixels_exact')
|
| 75 |
-
assert pixels['scope']=='deterministic_sample' and pixels['sampled_frames']==len(pixels['frame_indices']) and pixels['sampled_frames']==min(T,16)
|
| 76 |
-
assert pixels['decoded_from_container'] and pixels['frame_indices']==sorted(set(pixels['frame_indices']))
|
| 77 |
-
if 'mano' not in m['components']:
|
| 78 |
-
assert m.get('omitted_components',{}).get('mano')
|
| 79 |
-
assert not (p/'annotation/mano/motion.pt').exists()
|
| 80 |
-
return m,frames,{'camera_id':m['camera_id'],'frames':T,'components':summary,'conversion_checks':records,'structure_and_references':'passed','mano':'source modality absent, omitted'}
|
| 81 |
-
actual=arr(p/'annotation/mano/motion_valid.pt')
|
| 82 |
-
if m['dataset_id']=='HOT3D':
|
| 83 |
-
src=m['components']['mano']['source_locator']
|
| 84 |
-
with zipfile.ZipFile(DATA_ROOT/'HOT3D'/src['archive']) as z:
|
| 85 |
-
native={r['timestamp_ns']:r['hand_poses'] for r in map(json.loads,z.read(src['member']).splitlines())}
|
| 86 |
-
expected=np.array([[str(side) in native.get(f['annotation_matches']['mano']['source_timestamp_ns'],{}) for side in range(2)] for f in frames],bool)
|
| 87 |
-
else:expected=np.array([[f['source_annotation_index'] is not None]*2 for f in frames],bool)
|
| 88 |
-
if m['dataset_id']=='HOT3D' and m['components']['mano'].get('valid_policy'):
|
| 89 |
-
source=m['components']['mano']['valid_policy']['source_locator']
|
| 90 |
-
with zipfile.ZipFile(DATA_ROOT/'HOT3D'/source['archive']) as z:
|
| 91 |
-
lookup={int(r['timestamp[ns]']):r['mask']=='True' for r in csv.DictReader(io.StringIO(z.read(source['member']).decode())) if r['stream_id']==m['camera_id']}
|
| 92 |
-
qa=[lookup[f['timecode_ns']] for f in frames]
|
| 93 |
-
expected &= np.array(qa,bool)[:,None]
|
| 94 |
-
if m['dataset_id']=='ARCTIC':
|
| 95 |
-
rejected=m['components']['mano'].get('valid_policy',{}).get('local_excluded_frame_indices',[])
|
| 96 |
-
expected[rejected]=False
|
| 97 |
-
assert np.array_equal(expected,actual),'annotation validity disagrees with declared source and QA/local policy'
|
| 98 |
-
records.append({'test':'all_frame_source_annotation_and_QA_policy','passed':True,'left_right_valid_counts':actual.sum(0).tolist(),'frames_without_usable_hand':int((~actual.any(1)).sum())})
|
| 99 |
-
return m,frames,{'camera_id':m['camera_id'],'frames':T,'components':summary,'conversion_checks':records,'structure_and_references':'passed'}
|
| 100 |
-
|
| 101 |
-
def select_images(p,indices,dest):
|
| 102 |
-
dest.mkdir(parents=True,exist_ok=True)
|
| 103 |
-
selection='+'.join(f'eq(n,{i})' for i in indices)
|
| 104 |
-
command([FF,'-v','error','-y','-threads','2','-noautorotate','-i',p/'observation/rgb.mkv',
|
| 105 |
-
'-vf',f"select='{selection}',scale=900:900:force_original_aspect_ratio=decrease",'-fps_mode','vfr',dest/'decoded-%03d.png'])
|
| 106 |
-
output=sorted(dest.glob('decoded-*.png'));assert len(output)==len(indices)
|
| 107 |
-
return dict(zip(indices,output))
|
| 108 |
-
|
| 109 |
-
def project_for_view(points,m,params,scale):
|
| 110 |
-
uv=project_points(points,m['camera']['model'],params)
|
| 111 |
-
if m['camera']['model']=='fisheye624':
|
| 112 |
-
angle=np.arctan2(np.linalg.norm(points[:,:2],axis=1),points[:,2])
|
| 113 |
-
uv[angle>m['camera']['max_solid_angle']]=np.nan
|
| 114 |
-
return uv*scale
|
| 115 |
-
|
| 116 |
-
def draw_edges(canvas,uv,edges,color):
|
| 117 |
-
H,W=canvas.shape[:2]
|
| 118 |
-
for a,b in edges:
|
| 119 |
-
xy=uv[[a,b]]
|
| 120 |
-
if not np.isfinite(xy).all():continue
|
| 121 |
-
if np.max(np.abs(xy))>max(W,H)*20:continue
|
| 122 |
-
xy=np.rint(xy).astype(int)
|
| 123 |
-
if np.linalg.norm(xy[0]-xy[1])>max(W,H)*.35:continue
|
| 124 |
-
ok,start,end=cv2.clipLine((0,0,W,H),tuple(xy[0]),tuple(xy[1]))
|
| 125 |
-
if ok:cv2.line(canvas,start,end,color,1,cv2.LINE_AA)
|
| 126 |
-
|
| 127 |
-
def review_view(p,m,frames,dest):
|
| 128 |
-
T=m['num_frames'];indices=sorted(set([0,1,T//4,T//2,3*T//4,T-1]));imgs=select_images(p,indices,dest)
|
| 129 |
-
K=arr(p/'camera/intrinsic.pt');D=arr(p/'camera/distortion.pt') if (p/'camera/distortion.pt').exists() else None
|
| 130 |
-
motion=arr(p/'annotation/mano/motion.pt');valid=arr(p/'annotation/mano/motion_valid.pt');models=[Mano('left'),Mano('right')]
|
| 131 |
-
if m['components']['mano']['model_profile']['left_shapedirs_fix']:
|
| 132 |
-
models[0].data['shapedirs'][:,0]*=-1
|
| 133 |
-
with torch.no_grad():models[0].layer.shapedirs[:,0]*=-1
|
| 134 |
-
objects=[]
|
| 135 |
-
for op in sorted((p/'annotation/object').iterdir()):
|
| 136 |
-
om=load(op/'metainfo.json');mesh=trimesh.load(p/om['mesh_ref'],process=False,force='mesh')
|
| 137 |
-
if 'vertex_part_ids_ref' in om:
|
| 138 |
-
vertices=np.array([[float(x) for x in r.split()[1:4]] for r in (p/om['mesh_ref']).read_text().splitlines() if r.startswith('v ')])
|
| 139 |
-
# trimesh may split OBJ vertices along UV seams; render exact source-ordered vertices as points.
|
| 140 |
-
objects.append((op,om,vertices,None,arr(op/'pose.pt'),arr(op/'pose_valid.pt'),arr(p/om['vertex_part_ids_ref']),arr(op/'parts/top/pose.pt')))
|
| 141 |
-
else:
|
| 142 |
-
edges=np.asarray(mesh.edges_unique);edges=edges[::max(1,len(edges)//2500)]
|
| 143 |
-
objects.append((op,om,np.asarray(mesh.vertices),edges,arr(op/'pose.pt'),arr(op/'pose_valid.pt'),None,None))
|
| 144 |
-
records=[]
|
| 145 |
-
for i,source in imgs.items():
|
| 146 |
-
original=np.asarray(Image.open(source).convert('RGB'));overlay=original.copy()
|
| 147 |
-
scale=np.array([original.shape[1]/m['camera']['image_size'][0],original.shape[0]/m['camera']['image_size'][1]])
|
| 148 |
-
params=K[i] if m['camera']['model']=='fisheye624' else (K[i],D[i] if D is not None else None)
|
| 149 |
-
for side,model in enumerate(models):
|
| 150 |
-
if not valid[i,side]:continue
|
| 151 |
-
h=motion[i,side];vertices,_,_=model.geometry(h[:48],h[48:58],h[58:]);uv=project_for_view(vertices[0],m,params,scale)
|
| 152 |
-
faces=np.asarray(model.layer.faces);edges=np.concatenate([faces[:,[0,1]],faces[:,[1,2]],faces[:,[2,0]]]);draw_edges(overlay,uv,edges,(0,235,255) if side==0 else (255,135,20))
|
| 153 |
-
palette=[(110,255,100),(255,80,210),(240,220,60),(90,180,255),(190,160,255),(255,120,140)]
|
| 154 |
-
for c,(op,om,vertices,edges,P,ok,parts,top) in enumerate(objects):
|
| 155 |
-
if not ok[i]:continue
|
| 156 |
-
xyz=vertices@P[i,:3,:3].T+P[i,:3,3]
|
| 157 |
-
if parts is not None:xyz[parts==1]=vertices[parts==1]@top[i,:3,:3].T+top[i,:3,3]
|
| 158 |
-
uv=project_for_view(xyz,m,params,scale)
|
| 159 |
-
if edges is not None:draw_edges(overlay,uv,edges,palette[c%len(palette)])
|
| 160 |
-
else:
|
| 161 |
-
for xy in uv[::max(1,len(uv)//6000)]:
|
| 162 |
-
if np.isfinite(xy).all() and 0<=xy[0]<overlay.shape[1] and 0<=xy[1]<overlay.shape[0]:cv2.circle(overlay,tuple(np.rint(xy).astype(int)),1,palette[c%len(palette)],-1)
|
| 163 |
-
blended=cv2.addWeighted(overlay,.8,original,.2,0);output=dest/f'frame-{i:06d}-overlay.png';raw=dest/f'frame-{i:06d}-rgb.png'
|
| 164 |
-
Image.fromarray(blended).save(output);source.replace(raw)
|
| 165 |
-
records.append({'frame_index':i,'source_frame_id':frames[i]['source_frame_id'],'rgb':raw.name,'overlay':output.name,'mano_valid':valid[i].tolist()})
|
| 166 |
-
return records
|
| 167 |
-
|
| 168 |
-
def write_reports(dataset,views):
|
| 169 |
-
base=DATA_ROOT/dataset;root=base/RELEASE;doc=root/'doc';review=doc/'validation';reports=[];cards=[];thumbs=[]
|
| 170 |
-
rawpaths=set()
|
| 171 |
-
for p in views:
|
| 172 |
-
if dataset=='ARCTIC':
|
| 173 |
-
for assets in (p/'annotation/object').glob('*/assets'):repair_arctic_material_refs(assets)
|
| 174 |
-
m,frames,summary=validate_view(p);cam=m['camera_id'];samples=review_view(p,m,frames,review/'images'/cam)
|
| 175 |
-
summary['visual_samples']=samples;reports.append(summary)
|
| 176 |
-
# All actually consumed source files; camera/mano/object locators name source archives.
|
| 177 |
-
rawpaths.add(m['components']['rgb']['source_locator'].get('archive',m['components']['rgb']['source_locator'].get('file')))
|
| 178 |
-
for comp in m['components'].values():
|
| 179 |
-
src=comp['source_locator']
|
| 180 |
-
if 'archive' in src:rawpaths.add(src['archive'])
|
| 181 |
-
if dataset=='ARCTIC':rawpaths.add('raw/data/splits_json.zip')
|
| 182 |
-
for op in (p/'annotation/object').iterdir():
|
| 183 |
-
glb=load(op/'metainfo.json').get('original_glb_ref')
|
| 184 |
-
if glb:rawpaths.add(load(op/'metainfo.json')['original_glb_source_locator']['file'])
|
| 185 |
-
opts=''.join(f'<option value="{i}"'+(' selected' if s['frame_index']==m['num_frames']//2 else '')+f'>index {s["frame_index"]} · source {s["source_frame_id"]} · valid {s["mano_valid"]}</option>' for i,s in enumerate(samples))
|
| 186 |
-
samples_js=json.dumps([{k:(f'images/{cam}/'+s[k] if k in ('rgb','overlay') else s[k]) for k in s} for s in samples])
|
| 187 |
-
cards.append(f'<section class="card" data-samples=\'{html.escape(samples_js,quote=True)}\'><h2>Camera {cam} · {m["camera"]["model"]} · {m["num_frames"]} 帧</h2><select onchange="show(this.closest(\'.card\'))">{opts}</select><label><input type="checkbox" checked onchange="show(this.closest(\'.card\'))"> 显示投影</label><br><a class="zoom" target="_blank"><img alt="共享产物实际帧与投影"></a><p class="caption"></p></section>')
|
| 188 |
-
middle=samples[len(samples)//2];thumb=Image.open(review/'images'/cam/middle['overlay']).convert('RGB');thumb.thumbnail((400,320));tile=Image.new('RGB',(420,355),'#18202b');tile.paste(thumb,((420-thumb.width)//2,28));ImageDraw.Draw(tile).text((10,8),f'{dataset} camera {cam} / frame {middle["frame_index"]}',fill='white');thumbs.append(tile)
|
| 189 |
-
print('REVIEWED',dataset,cam,flush=True)
|
| 190 |
-
cols=3;grid=Image.new('RGB',(cols*420,((len(thumbs)+cols-1)//cols)*355),'#18202b')
|
| 191 |
-
for i,t in enumerate(thumbs):grid.paste(t,((i%cols)*420,(i//cols)*355))
|
| 192 |
-
grid.save(review/'overview.png')
|
| 193 |
-
source_manifest=[]
|
| 194 |
-
ledger=load(base/'raw/doc'/('archive_checksums.json' if dataset=='ARCTIC' else 'file_checksums.json'))
|
| 195 |
-
for rel in sorted(x for x in rawpaths if x):
|
| 196 |
-
file=base/rel;sha=digest(file);record=ledger[rel.removeprefix('raw/data/')]
|
| 197 |
-
assert record['sha256']==sha and record['size']==file.stat().st_size
|
| 198 |
-
assert record.get('official_sha256_match',record.get('official_digest_match')) is True
|
| 199 |
-
if file.suffix=='.zip':assert record['zip_crc']=='passed_all_members'
|
| 200 |
-
if dataset=='HOT3D':assert record['fresh_download_run']=='2026-09-18-aria-fresh'
|
| 201 |
-
source_manifest.append({'path':rel,'bytes':file.stat().st_size,'sha256':sha,'matches_verified_official_download':True,'zip_crc_at_download':record.get('zip_crc')})
|
| 202 |
-
save(doc/'pilot-source-manifest.json',source_manifest)
|
| 203 |
-
script_manifest=[]
|
| 204 |
-
for
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
'
|
| 209 |
-
'
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
if __name__=='__main__':
|
| 225 |
-
raise SystemExit('Static-sample review is retired. Use render_full_sequence_review.py DATASET and finalize_fresh_sequence_review.py; validate_view remains a reusable numeric helper.')
|
|
|
|
| 1 |
+
"""Validate actual shared outputs and create portable, offline pilot reviews.
|
| 2 |
+
|
| 3 |
+
Run after convert_fresh_sequence_pilots.py. Never authorizes full processing.
|
| 4 |
+
"""
|
| 5 |
+
from fresh_sequence_common import *
|
| 6 |
+
import html
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
|
| 9 |
+
def arr(p):
|
| 10 |
+
value=torch.load(p,map_location='cpu',weights_only=True)
|
| 11 |
+
assert isinstance(value,torch.Tensor) and value.device.type=='cpu'
|
| 12 |
+
return value.numpy()
|
| 13 |
+
|
| 14 |
+
def safe_ref(root,ref):
|
| 15 |
+
path=(root/ref).resolve()
|
| 16 |
+
assert path.is_relative_to(root.resolve()) and path.is_file(),ref
|
| 17 |
+
return path
|
| 18 |
+
|
| 19 |
+
def validate_view(p):
|
| 20 |
+
m=load(p/'metainfo.json');T=m['num_frames'];registry=load(WORK/'distribution/hand-warehouse-1.0/schema.json')
|
| 21 |
+
assert m['schema_version']==registry['schema_version'] and m['pilot_complete']
|
| 22 |
+
frames=[json.loads(line) for line in (p/'camera/frames.jsonl').read_text().splitlines()]
|
| 23 |
+
assert len(frames)==T and [f['frame_index'] for f in frames]==list(range(T))
|
| 24 |
+
assert len({f['source_frame_id'] for f in frames})==T
|
| 25 |
+
for frame in frames:
|
| 26 |
+
for match in frame.get('annotation_matches',{}).values():
|
| 27 |
+
if 'available' in match:match['source_record_present']=match.pop('available')
|
| 28 |
+
lines(p/'camera/frames.jsonl',frames)
|
| 29 |
+
summary=[]
|
| 30 |
+
for key,c in m['components'].items():
|
| 31 |
+
assert c['schema_id'] in registry['components'],(key,c['schema_id'])
|
| 32 |
+
assert c['available'] and c['source_locator'] and c['provenance']['kind'] in ['source','derived','format_conversion']
|
| 33 |
+
data=safe_ref(p,c['data_ref']);valid=arr(safe_ref(p,c['valid_ref']))
|
| 34 |
+
assert valid.dtype==bool and valid.ndim==len(c['valid_axes'])
|
| 35 |
+
if data.suffix=='.pt':
|
| 36 |
+
a=arr(data);assert a.dtype==np.float32 and a.shape[0]==T
|
| 37 |
+
assert a.shape[:valid.ndim]==valid.shape and len(c['axes'])==a.ndim
|
| 38 |
+
assert np.isfinite(a[valid]).all() and np.isnan(a[~valid]).all()
|
| 39 |
+
if c['schema_id'] in ['object/rigid/v1','transform/se3/v1']:assert_se3(a[valid])
|
| 40 |
+
if c['schema_id']=='mano/axis_angle61/v1':assert a.shape==(T,2,61)
|
| 41 |
+
elif data.suffix=='.mkv':
|
| 42 |
+
assert c['storage']['profile'] in registry['storage_profiles']
|
| 43 |
+
assert valid.shape==(T,) and valid.all()
|
| 44 |
+
for attr in c.get('attributes',{}).values():
|
| 45 |
+
a=arr(safe_ref(p,attr['data_ref']));b=arr(safe_ref(p,attr['valid_ref']))
|
| 46 |
+
assert b.dtype==bool and a.shape==b.shape
|
| 47 |
+
assert np.isfinite(a[b]).all() and ((a[b]>=0)&(a[b]<=1)).all() and np.isnan(a[~b]).all()
|
| 48 |
+
if 'distortion_ref' in c:
|
| 49 |
+
d=arr(safe_ref(p,c['distortion_ref']));assert d.shape==(T,8) and np.isfinite(d).all()
|
| 50 |
+
summary.append({'component':key,'schema':c['schema_id'],'valid':int(valid.sum()),'total':int(valid.size)})
|
| 51 |
+
for op in sorted((p/'annotation/object').glob('*')):
|
| 52 |
+
om=load(op/'metainfo.json');mesh=safe_ref(p,om['mesh_ref'])
|
| 53 |
+
if 'vertex_part_ids_ref' in om:
|
| 54 |
+
ids=arr(safe_ref(p,om['vertex_part_ids_ref']));assert ids.dtype==np.int64
|
| 55 |
+
assert len(ids)==sum(line.startswith('v ') for line in mesh.read_text().splitlines())
|
| 56 |
+
assert om['topology_id']=='sha256:'+digest(mesh)
|
| 57 |
+
if not (op/'pose.pt').exists():
|
| 58 |
+
assert m.get('omitted_components',{}).get('object_pose')
|
| 59 |
+
else:
|
| 60 |
+
root=arr(op/'pose.pt');top=arr(op/'parts/top/pose.pt');joint=arr(op/'joint_state.pt')[:,0]
|
| 61 |
+
ok=arr(op/'pose_valid.pt');H=np.broadcast_to(np.eye(4),(ok.sum(),4,4)).copy()
|
| 62 |
+
H[:,:3,:3]=Rotation.from_rotvec(np.c_[np.zeros((ok.sum(),2)),-joint[ok]]).as_matrix()
|
| 63 |
+
if ok.any():assert np.max(np.abs(root[ok]@H-top[ok]))<2e-6
|
| 64 |
+
for obj in (op/'assets').glob('*.obj'):
|
| 65 |
+
for row in obj.read_text().splitlines():
|
| 66 |
+
if row.startswith('mtllib '):
|
| 67 |
+
material=safe_ref(obj.parent,row.split(maxsplit=1)[1])
|
| 68 |
+
for r in material.read_text().splitlines():
|
| 69 |
+
if r.lower().startswith('map_kd '):safe_ref(material.parent,r.split(maxsplit=1)[1])
|
| 70 |
+
records=load(DATA_ROOT/m['dataset_id']/'tmp'/RUN/'checks'/f'{m["sequence_id"]}__{m["camera_id"]}.json')['checks']
|
| 71 |
+
assert records and all(x.get('passed',False) for x in records)
|
| 72 |
+
media=next(r for r in records if r['test'] in ['all_source_JPEG_packets_and_RGB_pixels_exact','all_source_JPEG_packets_exact']);assert media['frames']==T
|
| 73 |
+
if media['test']=='all_source_JPEG_packets_exact':
|
| 74 |
+
pixels=next(r for r in records if r['test']=='source_RGB_pixels_exact')
|
| 75 |
+
assert pixels['scope']=='deterministic_sample' and pixels['sampled_frames']==len(pixels['frame_indices']) and pixels['sampled_frames']==min(T,16)
|
| 76 |
+
assert pixels['decoded_from_container'] and pixels['frame_indices']==sorted(set(pixels['frame_indices']))
|
| 77 |
+
if 'mano' not in m['components']:
|
| 78 |
+
assert m.get('omitted_components',{}).get('mano')
|
| 79 |
+
assert not (p/'annotation/mano/motion.pt').exists()
|
| 80 |
+
return m,frames,{'camera_id':m['camera_id'],'frames':T,'components':summary,'conversion_checks':records,'structure_and_references':'passed','mano':'source modality absent, omitted'}
|
| 81 |
+
actual=arr(p/'annotation/mano/motion_valid.pt')
|
| 82 |
+
if m['dataset_id']=='HOT3D':
|
| 83 |
+
src=m['components']['mano']['source_locator']
|
| 84 |
+
with zipfile.ZipFile(DATA_ROOT/'HOT3D'/src['archive']) as z:
|
| 85 |
+
native={r['timestamp_ns']:r['hand_poses'] for r in map(json.loads,z.read(src['member']).splitlines())}
|
| 86 |
+
expected=np.array([[str(side) in native.get(f['annotation_matches']['mano']['source_timestamp_ns'],{}) for side in range(2)] for f in frames],bool)
|
| 87 |
+
else:expected=np.array([[f['source_annotation_index'] is not None]*2 for f in frames],bool)
|
| 88 |
+
if m['dataset_id']=='HOT3D' and m['components']['mano'].get('valid_policy'):
|
| 89 |
+
source=m['components']['mano']['valid_policy']['source_locator']
|
| 90 |
+
with zipfile.ZipFile(DATA_ROOT/'HOT3D'/source['archive']) as z:
|
| 91 |
+
lookup={int(r['timestamp[ns]']):r['mask']=='True' for r in csv.DictReader(io.StringIO(z.read(source['member']).decode())) if r['stream_id']==m['camera_id']}
|
| 92 |
+
qa=[lookup[f['timecode_ns']] for f in frames]
|
| 93 |
+
expected &= np.array(qa,bool)[:,None]
|
| 94 |
+
if m['dataset_id']=='ARCTIC':
|
| 95 |
+
rejected=m['components']['mano'].get('valid_policy',{}).get('local_excluded_frame_indices',[])
|
| 96 |
+
expected[rejected]=False
|
| 97 |
+
assert np.array_equal(expected,actual),'annotation validity disagrees with declared source and QA/local policy'
|
| 98 |
+
records.append({'test':'all_frame_source_annotation_and_QA_policy','passed':True,'left_right_valid_counts':actual.sum(0).tolist(),'frames_without_usable_hand':int((~actual.any(1)).sum())})
|
| 99 |
+
return m,frames,{'camera_id':m['camera_id'],'frames':T,'components':summary,'conversion_checks':records,'structure_and_references':'passed'}
|
| 100 |
+
|
| 101 |
+
def select_images(p,indices,dest):
|
| 102 |
+
dest.mkdir(parents=True,exist_ok=True)
|
| 103 |
+
selection='+'.join(f'eq(n,{i})' for i in indices)
|
| 104 |
+
command([FF,'-v','error','-y','-threads','2','-noautorotate','-i',p/'observation/rgb.mkv',
|
| 105 |
+
'-vf',f"select='{selection}',scale=900:900:force_original_aspect_ratio=decrease",'-fps_mode','vfr',dest/'decoded-%03d.png'])
|
| 106 |
+
output=sorted(dest.glob('decoded-*.png'));assert len(output)==len(indices)
|
| 107 |
+
return dict(zip(indices,output))
|
| 108 |
+
|
| 109 |
+
def project_for_view(points,m,params,scale):
|
| 110 |
+
uv=project_points(points,m['camera']['model'],params)
|
| 111 |
+
if m['camera']['model']=='fisheye624':
|
| 112 |
+
angle=np.arctan2(np.linalg.norm(points[:,:2],axis=1),points[:,2])
|
| 113 |
+
uv[angle>m['camera']['max_solid_angle']]=np.nan
|
| 114 |
+
return uv*scale
|
| 115 |
+
|
| 116 |
+
def draw_edges(canvas,uv,edges,color):
|
| 117 |
+
H,W=canvas.shape[:2]
|
| 118 |
+
for a,b in edges:
|
| 119 |
+
xy=uv[[a,b]]
|
| 120 |
+
if not np.isfinite(xy).all():continue
|
| 121 |
+
if np.max(np.abs(xy))>max(W,H)*20:continue
|
| 122 |
+
xy=np.rint(xy).astype(int)
|
| 123 |
+
if np.linalg.norm(xy[0]-xy[1])>max(W,H)*.35:continue
|
| 124 |
+
ok,start,end=cv2.clipLine((0,0,W,H),tuple(xy[0]),tuple(xy[1]))
|
| 125 |
+
if ok:cv2.line(canvas,start,end,color,1,cv2.LINE_AA)
|
| 126 |
+
|
| 127 |
+
def review_view(p,m,frames,dest):
|
| 128 |
+
T=m['num_frames'];indices=sorted(set([0,1,T//4,T//2,3*T//4,T-1]));imgs=select_images(p,indices,dest)
|
| 129 |
+
K=arr(p/'camera/intrinsic.pt');D=arr(p/'camera/distortion.pt') if (p/'camera/distortion.pt').exists() else None
|
| 130 |
+
motion=arr(p/'annotation/mano/motion.pt');valid=arr(p/'annotation/mano/motion_valid.pt');models=[Mano('left'),Mano('right')]
|
| 131 |
+
if m['components']['mano']['model_profile']['left_shapedirs_fix']:
|
| 132 |
+
models[0].data['shapedirs'][:,0]*=-1
|
| 133 |
+
with torch.no_grad():models[0].layer.shapedirs[:,0]*=-1
|
| 134 |
+
objects=[]
|
| 135 |
+
for op in sorted((p/'annotation/object').iterdir()):
|
| 136 |
+
om=load(op/'metainfo.json');mesh=trimesh.load(p/om['mesh_ref'],process=False,force='mesh')
|
| 137 |
+
if 'vertex_part_ids_ref' in om:
|
| 138 |
+
vertices=np.array([[float(x) for x in r.split()[1:4]] for r in (p/om['mesh_ref']).read_text().splitlines() if r.startswith('v ')])
|
| 139 |
+
# trimesh may split OBJ vertices along UV seams; render exact source-ordered vertices as points.
|
| 140 |
+
objects.append((op,om,vertices,None,arr(op/'pose.pt'),arr(op/'pose_valid.pt'),arr(p/om['vertex_part_ids_ref']),arr(op/'parts/top/pose.pt')))
|
| 141 |
+
else:
|
| 142 |
+
edges=np.asarray(mesh.edges_unique);edges=edges[::max(1,len(edges)//2500)]
|
| 143 |
+
objects.append((op,om,np.asarray(mesh.vertices),edges,arr(op/'pose.pt'),arr(op/'pose_valid.pt'),None,None))
|
| 144 |
+
records=[]
|
| 145 |
+
for i,source in imgs.items():
|
| 146 |
+
original=np.asarray(Image.open(source).convert('RGB'));overlay=original.copy()
|
| 147 |
+
scale=np.array([original.shape[1]/m['camera']['image_size'][0],original.shape[0]/m['camera']['image_size'][1]])
|
| 148 |
+
params=K[i] if m['camera']['model']=='fisheye624' else (K[i],D[i] if D is not None else None)
|
| 149 |
+
for side,model in enumerate(models):
|
| 150 |
+
if not valid[i,side]:continue
|
| 151 |
+
h=motion[i,side];vertices,_,_=model.geometry(h[:48],h[48:58],h[58:]);uv=project_for_view(vertices[0],m,params,scale)
|
| 152 |
+
faces=np.asarray(model.layer.faces);edges=np.concatenate([faces[:,[0,1]],faces[:,[1,2]],faces[:,[2,0]]]);draw_edges(overlay,uv,edges,(0,235,255) if side==0 else (255,135,20))
|
| 153 |
+
palette=[(110,255,100),(255,80,210),(240,220,60),(90,180,255),(190,160,255),(255,120,140)]
|
| 154 |
+
for c,(op,om,vertices,edges,P,ok,parts,top) in enumerate(objects):
|
| 155 |
+
if not ok[i]:continue
|
| 156 |
+
xyz=vertices@P[i,:3,:3].T+P[i,:3,3]
|
| 157 |
+
if parts is not None:xyz[parts==1]=vertices[parts==1]@top[i,:3,:3].T+top[i,:3,3]
|
| 158 |
+
uv=project_for_view(xyz,m,params,scale)
|
| 159 |
+
if edges is not None:draw_edges(overlay,uv,edges,palette[c%len(palette)])
|
| 160 |
+
else:
|
| 161 |
+
for xy in uv[::max(1,len(uv)//6000)]:
|
| 162 |
+
if np.isfinite(xy).all() and 0<=xy[0]<overlay.shape[1] and 0<=xy[1]<overlay.shape[0]:cv2.circle(overlay,tuple(np.rint(xy).astype(int)),1,palette[c%len(palette)],-1)
|
| 163 |
+
blended=cv2.addWeighted(overlay,.8,original,.2,0);output=dest/f'frame-{i:06d}-overlay.png';raw=dest/f'frame-{i:06d}-rgb.png'
|
| 164 |
+
Image.fromarray(blended).save(output);source.replace(raw)
|
| 165 |
+
records.append({'frame_index':i,'source_frame_id':frames[i]['source_frame_id'],'rgb':raw.name,'overlay':output.name,'mano_valid':valid[i].tolist()})
|
| 166 |
+
return records
|
| 167 |
+
|
| 168 |
+
def write_reports(dataset,views):
|
| 169 |
+
base=DATA_ROOT/dataset;root=base/RELEASE;doc=root/'doc';review=doc/'validation';reports=[];cards=[];thumbs=[]
|
| 170 |
+
rawpaths=set()
|
| 171 |
+
for p in views:
|
| 172 |
+
if dataset=='ARCTIC':
|
| 173 |
+
for assets in (p/'annotation/object').glob('*/assets'):repair_arctic_material_refs(assets)
|
| 174 |
+
m,frames,summary=validate_view(p);cam=m['camera_id'];samples=review_view(p,m,frames,review/'images'/cam)
|
| 175 |
+
summary['visual_samples']=samples;reports.append(summary)
|
| 176 |
+
# All actually consumed source files; camera/mano/object locators name source archives.
|
| 177 |
+
rawpaths.add(m['components']['rgb']['source_locator'].get('archive',m['components']['rgb']['source_locator'].get('file')))
|
| 178 |
+
for comp in m['components'].values():
|
| 179 |
+
src=comp['source_locator']
|
| 180 |
+
if 'archive' in src:rawpaths.add(src['archive'])
|
| 181 |
+
if dataset=='ARCTIC':rawpaths.add('raw/data/splits_json.zip')
|
| 182 |
+
for op in (p/'annotation/object').iterdir():
|
| 183 |
+
glb=load(op/'metainfo.json').get('original_glb_ref')
|
| 184 |
+
if glb:rawpaths.add(load(op/'metainfo.json')['original_glb_source_locator']['file'])
|
| 185 |
+
opts=''.join(f'<option value="{i}"'+(' selected' if s['frame_index']==m['num_frames']//2 else '')+f'>index {s["frame_index"]} · source {s["source_frame_id"]} · valid {s["mano_valid"]}</option>' for i,s in enumerate(samples))
|
| 186 |
+
samples_js=json.dumps([{k:(f'images/{cam}/'+s[k] if k in ('rgb','overlay') else s[k]) for k in s} for s in samples])
|
| 187 |
+
cards.append(f'<section class="card" data-samples=\'{html.escape(samples_js,quote=True)}\'><h2>Camera {cam} · {m["camera"]["model"]} · {m["num_frames"]} 帧</h2><select onchange="show(this.closest(\'.card\'))">{opts}</select><label><input type="checkbox" checked onchange="show(this.closest(\'.card\'))"> 显示投影</label><br><a class="zoom" target="_blank"><img alt="共享产物实际帧与投影"></a><p class="caption"></p></section>')
|
| 188 |
+
middle=samples[len(samples)//2];thumb=Image.open(review/'images'/cam/middle['overlay']).convert('RGB');thumb.thumbnail((400,320));tile=Image.new('RGB',(420,355),'#18202b');tile.paste(thumb,((420-thumb.width)//2,28));ImageDraw.Draw(tile).text((10,8),f'{dataset} camera {cam} / frame {middle["frame_index"]}',fill='white');thumbs.append(tile)
|
| 189 |
+
print('REVIEWED',dataset,cam,flush=True)
|
| 190 |
+
cols=3;grid=Image.new('RGB',(cols*420,((len(thumbs)+cols-1)//cols)*355),'#18202b')
|
| 191 |
+
for i,t in enumerate(thumbs):grid.paste(t,((i%cols)*420,(i//cols)*355))
|
| 192 |
+
grid.save(review/'overview.png')
|
| 193 |
+
source_manifest=[]
|
| 194 |
+
ledger=load(base/'raw/doc'/('archive_checksums.json' if dataset=='ARCTIC' else 'file_checksums.json'))
|
| 195 |
+
for rel in sorted(x for x in rawpaths if x):
|
| 196 |
+
file=base/rel;sha=digest(file);record=ledger[rel.removeprefix('raw/data/')]
|
| 197 |
+
assert record['sha256']==sha and record['size']==file.stat().st_size
|
| 198 |
+
assert record.get('official_sha256_match',record.get('official_digest_match')) is True
|
| 199 |
+
if file.suffix=='.zip':assert record['zip_crc']=='passed_all_members'
|
| 200 |
+
if dataset=='HOT3D':assert record['fresh_download_run']=='2026-09-18-aria-fresh'
|
| 201 |
+
source_manifest.append({'path':rel,'bytes':file.stat().st_size,'sha256':sha,'matches_verified_official_download':True,'zip_crc_at_download':record.get('zip_crc')})
|
| 202 |
+
save(doc/'pilot-source-manifest.json',source_manifest)
|
| 203 |
+
script_manifest=[]
|
| 204 |
+
for p in sorted((root/'script').rglob('*.py')):script_manifest.append({'path':p.relative_to(root).as_posix(),'sha256':digest(p)})
|
| 205 |
+
full={'dataset':dataset,'stage':'pilot_awaiting_human_review','human_review':'pending','full_preprocessing_authorized':False,'upload_authorized':False,
|
| 206 |
+
'scope':'One complete selected sequence, every released camera frame; not full-dataset acceptance','views':reports,
|
| 207 |
+
'sources_manifest':'../pilot-source-manifest.json','script_manifest':script_manifest,'preview_selection':'Deterministic boundary and quartile samples per camera; not random or full-dataset review',
|
| 208 |
+
'preview_rendering':'Derived MANO/object projections from shared tensors, not segmentation ground truth; no depth occlusion test, hidden surfaces may be drawn',
|
| 209 |
+
'created_at':datetime.now().astimezone().isoformat()}
|
| 210 |
+
save(review/'report.json',full);save(review/'status.json',{k:full[k] for k in ['dataset','stage','human_review','full_preprocessing_authorized','upload_authorized']})
|
| 211 |
+
notes=('首帧 RGB 存在,动捕标注无对应项,valid=false;已保留。相机 0 使用 rational8 畸变,外部八相机使用官方针孔投影。关节绕父坐标系 -Z 轴旋转,部件点/网格保持米制。' if dataset=='ARCTIC' else 'Aria 三路相机均保留;RGB 与两路灰度均由原 JPEG 直接封装。device time 经官方映射对齐 timecode;原始 visibility 按百分比转 [0,1],独立于标注 valid。三路按时间匹配,不假定相同行号自动同步。')
|
| 212 |
+
if dataset=='HOT3D':notes+=' 每相机双手各806帧有MANO、208帧原始手参数为空;画面中有手但无投影的末尾帧属于源标注缺失,已验证并保留为valid=false。'
|
| 213 |
+
if dataset=='ARCTIC':notes+=' 原始部件OBJ的材质文件名引用错误已在共享层修正为实际存在的material.mtl,材质标识与纹理不变。'
|
| 214 |
+
missing=('本次官方 raw 中无独立深度、像素分割、接触标签、实测手关键点数组。保留 MANO,供任务层按需生成关键点;未把预览投影写成新增标注。' if dataset=='ARCTIC' else '本范围无深度流或像素分割;masks/*.csv 是帧筛选条件,不能当作像素 mask。UmeTrack 与 MPS 替代估计保留在 raw;shared 选择 MANO 和官方 GT 相机。没有额外生成关键点或接触标签。')
|
| 215 |
+
text=f'''<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{dataset} 序列试点审核</title><style>body{{font:16px/1.65 system-ui;background:#f3f5f8;color:#18202b;max-width:1450px;margin:24px auto;padding:0 20px}}header,.card{{background:white;padding:22px;border-radius:14px;margin-bottom:18px}}.status{{color:#9a5800;font-weight:bold}}.grid{{display:grid;grid-template-columns:repeat(auto-fit,minmax(360px,1fr));gap:18px}}.card img{{max-width:100%;max-height:670px;margin-top:12px}}select{{max-width:100%;padding:8px}}a{{color:#1766ab}}label{{display:inline-block;margin:10px}}h1{{margin:0}}.caption{{font-size:14px}}</style><header><h1>{dataset} · 完整序列试点</h1><p class="status">自动校验已完成;人工审核待确认。尚未开始全量预处理或上传。</p><p>共 {len(views)} 路相机、{sum(r['frames'] for r in reports):,} 个相机帧。全部源 JPEG 码流、全部解码 RGB 帧已逐一比较一致;数值转换、有效性和引用检查通过。</p><p>{notes}</p><p>{missing}</p><p>下方是从 shared 实际产物读取的边界及四分位样本。青色=左手,橙色=右手,其余颜色=物体。投影仅用于几何核验,<b>不是源分割,也没有做遮挡剔除</b>。点击图像可放大;取消勾选可查看原图。</p><p><a href="REPORT.md">验收说明</a> · <a href="report.json">机器可读结果</a> · <a href="../RAW_TO_SHARED.md">raw → share 对照</a> · <a href="../CONTRACT.md">约定</a> · <a href="overview.png">全部相机总览</a></p></header><main class="grid">{''.join(cards)}</main><script>function show(card){{let s=JSON.parse(card.dataset.samples)[Number(card.querySelector('select').value)];let path=card.querySelector('input').checked?s.overlay:s.rgb;card.querySelector('img').src=path;card.querySelector('.zoom').href=path;card.querySelector('.caption').textContent='frame_index='+s.frame_index+' / 原帧 '+s.source_frame_id+' / 左右手 valid='+s.mano_valid;}}document.querySelectorAll('.card').forEach(show)</script></html>'''
|
| 216 |
+
(review/'index.html').write_text(text,encoding='utf-8')
|
| 217 |
+
rows='\n'.join(f'| {r["camera_id"]} | {r["frames"]} | '+', '.join(str(x['frame_index']) for x in r['visual_samples'])+' | 通过 |' for r in reports)
|
| 218 |
+
report=f'''# {dataset} 完整序列试点验收\n\n状态:**自动检查通过,人工确认待完成**。本报告不是全量验收或发布许可。\n\n[离线预览](index.html) · [机器结果](report.json) · [原始包摘要](../pilot-source-manifest.json)\n\n| 相机 | 全序列帧数 | 可视化帧索引 | 自动校验 |\n|---|---:|---|---|\n{rows}\n\n## 已验证\n\n- 完整所选序列的每一张源 JPEG 与 MKV 取回的压缩包 SHA256 相同;全部帧在同一 FFmpeg/noautorotate/rgb24 配置下解码字节相同,顺序和数量一致。不是有损重编码。\n- 全部有效 MANO 帧的相机坐标变换与直接变换几何一致;独立源模型配置抽样校验非平手均值/PCA 展开。张量 float32 保存读取一致,invalid 为 NaN,valid 为 bool。\n- SE(3) 正交性、单位与资产引用检查;ARCTIC 部件关节运动与源旋转公式逐帧对照,HOT3D 物体 OBJ 尺度、三角形及纹理像素往返一致。\n- 所有实际组件使用现有注册 schema;没有为缺省模态伪造值。\n\n## 帧对应和缺省范围\n\n{notes}\n\n{missing}\n\n## 人工核验边界\n\n每相机选序列起点、紧邻帧、四分位、中点、四分之三及终点,不是随机抽查。预览只用于核对几何对齐;投影线条/点不是分割真值,遮挡表面可能被画出。数值自洽不等于图像投影正确,请检查所有相机和多个时刻。此处一序列通过不能覆盖全数据集、其他物体或异常序列。全量处理后仍需独立随机抽查和用户发布确认。\n'''
|
| 219 |
+
(review/'REPORT.md').write_text(report,encoding='utf-8')
|
| 220 |
+
return full
|
| 221 |
+
|
| 222 |
+
if __name__=='__main__':
|
| 223 |
+
raise SystemExit('Static-sample review is retired. Use render_full_sequence_review.py DATASET and finalize_fresh_sequence_review.py; validate_view remains a reusable numeric helper.')
|
|
|
|
|
|
ARCTIC/shared-v1.0/script/internal/sequence_pilot_common.py
CHANGED
|
@@ -1,53 +1,51 @@
|
|
| 1 |
-
"""Whole-selection conversion utilities. Never reads previous pilot outputs."""
|
| 2 |
-
from pilot_build import *
|
| 3 |
-
import hashlib
|
| 4 |
-
|
| 5 |
-
RELEASE='shared-sequence-v1.1'
|
| 6 |
-
|
| 7 |
-
class View:
|
| 8 |
-
def __init__(self,dataset,seq,cam,ids,size,source,kind='video',sampling='dense',split='unknown'):
|
| 9 |
-
self.root=ROOT/dataset/RELEASE;self.p=self.root/'data'/seq/cam
|
| 10 |
-
self.p.mkdir(parents=True,exist_ok=True);self.T=len(ids);self.source=source;self.checks=[]
|
| 11 |
-
self.m={'schema_version':'hand-warehouse/1.1','dataset_id':dataset,'release_id':RELEASE,'sequence_id':seq,'camera_id':cam,'sample_type':kind,'num_frames':self.T,'hand_slots':['left','right'],'sampling':{'type':'single' if kind=='image' else sampling,'source_fps':None,'frames_ref':'camera/frames.jsonl'},'camera':{'model':'unknown','schema_id':None,'image_size':size},'components':{},'split':split}
|
| 12 |
-
self.frames=[{'frame_index':i,'source_frame_id':str(fid),'timestamp_ns':None,'clock_domain':None,'source_locator':{**source,'source_frame_id':str(fid)}} for i,fid in enumerate(ids)]
|
| 13 |
-
def add(self,name,path,schema,axes,valid,method='source values retained',**kw):
|
| 14 |
-
vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix()
|
| 15 |
-
tensor(self.p/vp,valid)
|
| 16 |
-
self.m['components'][name]={'available':True,'schema_id':schema,'data_ref':path,'axes':axes,'valid_ref':vp,'valid_axes':axes[:valid.ndim],'provenance':{'kind':'format_conversion','method':method},'source_locator':self.source,**kw}
|
| 17 |
-
def array(self,name,path,schema,a,valid,axes,**kw):
|
| 18 |
-
a=np.asarray(a,np.float32).copy();valid=np.asarray(valid,bool)
|
| 19 |
-
assert a.shape[:valid.ndim]==valid.shape and a.shape[0]==self.T
|
| 20 |
-
assert np.isfinite(a[valid]).all(),name
|
| 21 |
-
a[~valid]=np.nan;tensor(self.p/path,a);self.add(name,path,schema,axes,valid,**kw)
|
| 22 |
-
restored=torch.load(self.p/path,map_location='cpu',weights_only=True).numpy()
|
| 23 |
-
for index in range(self.T):assert np.array_equal(restored[index],a[index],equal_nan=True)
|
| 24 |
-
self.checks.append({'test':'tensor_serialization_exact','file':path,'shape':list(a.shape),'valid_count':int(valid.sum())})
|
| 25 |
-
def video(self,name,path,iterator,mask=False,**kw):
|
| 26 |
-
w,h=self.m['camera']['image_size'];pix='gray16le' if mask else 'rgb24';dtype='<u2' if mask else 'uint8'
|
| 27 |
-
dst=self.p/path;dst.parent.mkdir(parents=True,exist_ok=True);hashes=[]
|
| 28 |
-
proc=subprocess.Popen([FF,'-v','error','-y','-f','rawvideo','-pixel_format',pix,'-video_size',f'{w}x{h}','-framerate','1','-i','pipe:0','-c:v','ffv1','-level','3','-g','1',str(dst)],stdin=subprocess.PIPE)
|
| 29 |
-
try:
|
| 30 |
-
for frame in iterator:
|
| 31 |
-
a=np.asarray(frame,dtype=dtype);assert a.shape==((h,w) if mask else (h,w,3));b=a.tobytes();hashes.append(hashlib.sha256(b).hexdigest());proc.stdin.write(b)
|
| 32 |
-
finally:proc.stdin.close()
|
| 33 |
-
assert proc.wait()==0 and len(hashes)==self.T
|
| 34 |
-
proc=subprocess.Popen([FF,'-v','error','-i',str(dst),'-f','rawvideo','-pix_fmt',pix,'pipe:1'],stdout=subprocess.PIPE)
|
| 35 |
-
nbytes=w*h*(2 if mask else 3)
|
| 36 |
-
for digest in hashes:
|
| 37 |
-
b=proc.stdout.read(nbytes);assert len(b)==nbytes and hashlib.sha256(b).hexdigest()==digest,'video roundtrip'
|
| 38 |
-
assert not proc.stdout.read(1);assert proc.wait()==0
|
| 39 |
-
self.checks.append({'test':'all_frames_pixel_exact_roundtrip','file':path,'frames':self.T})
|
| 40 |
-
self.add(name,path,'segment/uint16_labels/v1' if mask else 'rgb/uint8/v1',['T','height','width'] if mask else ['T','height','width','channel'],np.ones(self.T,bool),storage_fps=1,timebase_role='index_only',**kw)
|
| 41 |
-
def intrinsic(self,K):
|
| 42 |
-
self.m['camera'].update(model='pinhole',schema_id='camera/pinhole/v1')
|
| 43 |
-
self.array('intrinsic','camera/intrinsic.pt','camera/pinhole/v1',np.broadcast_to(K,(self.T,3,3)),np.ones(self.T,bool),['T','row','column'])
|
| 44 |
-
def finish(self):
|
| 45 |
-
lines(self.p/'camera/frames.jsonl',self.frames);save(self.p/'metainfo.json',self.m)
|
| 46 |
-
save(self.root/'doc'/f'{self.m["sequence_id"]}__{self.m["camera_id"]}.checks.json',{'checks':self.checks,'frames':self.T,'input':self.source})
|
| 47 |
-
print('Converted',self.m['dataset_id'],self.m['sequence_id'],self.m['camera_id'],self.T,flush=True)
|
| 48 |
-
|
| 49 |
-
def snapshot(dataset,scripts):
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
names.update(p.name for p in (WORK/'scripts').glob('sequence_pilot_*.py'))
|
| 53 |
-
for name in names:shutil.copyfile(WORK/'scripts'/name,out/name)
|
|
|
|
| 1 |
+
"""Whole-selection conversion utilities. Never reads previous pilot outputs."""
|
| 2 |
+
from pilot_build import *
|
| 3 |
+
import hashlib
|
| 4 |
+
|
| 5 |
+
RELEASE='shared-sequence-v1.1'
|
| 6 |
+
|
| 7 |
+
class View:
|
| 8 |
+
def __init__(self,dataset,seq,cam,ids,size,source,kind='video',sampling='dense',split='unknown'):
|
| 9 |
+
self.root=ROOT/dataset/RELEASE;self.p=self.root/'data'/seq/cam
|
| 10 |
+
self.p.mkdir(parents=True,exist_ok=True);self.T=len(ids);self.source=source;self.checks=[]
|
| 11 |
+
self.m={'schema_version':'hand-warehouse/1.1','dataset_id':dataset,'release_id':RELEASE,'sequence_id':seq,'camera_id':cam,'sample_type':kind,'num_frames':self.T,'hand_slots':['left','right'],'sampling':{'type':'single' if kind=='image' else sampling,'source_fps':None,'frames_ref':'camera/frames.jsonl'},'camera':{'model':'unknown','schema_id':None,'image_size':size},'components':{},'split':split}
|
| 12 |
+
self.frames=[{'frame_index':i,'source_frame_id':str(fid),'timestamp_ns':None,'clock_domain':None,'source_locator':{**source,'source_frame_id':str(fid)}} for i,fid in enumerate(ids)]
|
| 13 |
+
def add(self,name,path,schema,axes,valid,method='source values retained',**kw):
|
| 14 |
+
vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix()
|
| 15 |
+
tensor(self.p/vp,valid)
|
| 16 |
+
self.m['components'][name]={'available':True,'schema_id':schema,'data_ref':path,'axes':axes,'valid_ref':vp,'valid_axes':axes[:valid.ndim],'provenance':{'kind':'format_conversion','method':method},'source_locator':self.source,**kw}
|
| 17 |
+
def array(self,name,path,schema,a,valid,axes,**kw):
|
| 18 |
+
a=np.asarray(a,np.float32).copy();valid=np.asarray(valid,bool)
|
| 19 |
+
assert a.shape[:valid.ndim]==valid.shape and a.shape[0]==self.T
|
| 20 |
+
assert np.isfinite(a[valid]).all(),name
|
| 21 |
+
a[~valid]=np.nan;tensor(self.p/path,a);self.add(name,path,schema,axes,valid,**kw)
|
| 22 |
+
restored=torch.load(self.p/path,map_location='cpu',weights_only=True).numpy()
|
| 23 |
+
for index in range(self.T):assert np.array_equal(restored[index],a[index],equal_nan=True)
|
| 24 |
+
self.checks.append({'test':'tensor_serialization_exact','file':path,'shape':list(a.shape),'valid_count':int(valid.sum())})
|
| 25 |
+
def video(self,name,path,iterator,mask=False,**kw):
|
| 26 |
+
w,h=self.m['camera']['image_size'];pix='gray16le' if mask else 'rgb24';dtype='<u2' if mask else 'uint8'
|
| 27 |
+
dst=self.p/path;dst.parent.mkdir(parents=True,exist_ok=True);hashes=[]
|
| 28 |
+
proc=subprocess.Popen([FF,'-v','error','-y','-f','rawvideo','-pixel_format',pix,'-video_size',f'{w}x{h}','-framerate','1','-i','pipe:0','-c:v','ffv1','-level','3','-g','1',str(dst)],stdin=subprocess.PIPE)
|
| 29 |
+
try:
|
| 30 |
+
for frame in iterator:
|
| 31 |
+
a=np.asarray(frame,dtype=dtype);assert a.shape==((h,w) if mask else (h,w,3));b=a.tobytes();hashes.append(hashlib.sha256(b).hexdigest());proc.stdin.write(b)
|
| 32 |
+
finally:proc.stdin.close()
|
| 33 |
+
assert proc.wait()==0 and len(hashes)==self.T
|
| 34 |
+
proc=subprocess.Popen([FF,'-v','error','-i',str(dst),'-f','rawvideo','-pix_fmt',pix,'pipe:1'],stdout=subprocess.PIPE)
|
| 35 |
+
nbytes=w*h*(2 if mask else 3)
|
| 36 |
+
for digest in hashes:
|
| 37 |
+
b=proc.stdout.read(nbytes);assert len(b)==nbytes and hashlib.sha256(b).hexdigest()==digest,'video roundtrip'
|
| 38 |
+
assert not proc.stdout.read(1);assert proc.wait()==0
|
| 39 |
+
self.checks.append({'test':'all_frames_pixel_exact_roundtrip','file':path,'frames':self.T})
|
| 40 |
+
self.add(name,path,'segment/uint16_labels/v1' if mask else 'rgb/uint8/v1',['T','height','width'] if mask else ['T','height','width','channel'],np.ones(self.T,bool),storage_fps=1,timebase_role='index_only',**kw)
|
| 41 |
+
def intrinsic(self,K):
|
| 42 |
+
self.m['camera'].update(model='pinhole',schema_id='camera/pinhole/v1')
|
| 43 |
+
self.array('intrinsic','camera/intrinsic.pt','camera/pinhole/v1',np.broadcast_to(K,(self.T,3,3)),np.ones(self.T,bool),['T','row','column'])
|
| 44 |
+
def finish(self):
|
| 45 |
+
lines(self.p/'camera/frames.jsonl',self.frames);save(self.p/'metainfo.json',self.m)
|
| 46 |
+
save(self.root/'doc'/f'{self.m["sequence_id"]}__{self.m["camera_id"]}.checks.json',{'checks':self.checks,'frames':self.T,'input':self.source})
|
| 47 |
+
print('Converted',self.m['dataset_id'],self.m['sequence_id'],self.m['camera_id'],self.T,flush=True)
|
| 48 |
+
|
| 49 |
+
def snapshot(dataset,scripts):
|
| 50 |
+
# Retained for old callers. The organized bundle must not be repopulated at runtime.
|
| 51 |
+
(ROOT/dataset/RELEASE/'script').mkdir(parents=True,exist_ok=True)
|
|
|
|
|
|
HOT3D/shared-v1.0/script/internal/apply_hot3d_qa.py
CHANGED
|
@@ -1,65 +1,65 @@
|
|
| 1 |
-
"""Apply native HOT3D manual QA to supervision validity, preserving raw diagnostics."""
|
| 2 |
-
from fresh_sequence_common import *
|
| 3 |
-
|
| 4 |
-
VIDEO_RUN='full-video-review-v2'
|
| 5 |
-
SEQ='P0015_179e1b84'
|
| 6 |
-
|
| 7 |
-
def csvrows(z,name):return list(csv.DictReader(io.StringIO(z.read(name).decode())))
|
| 8 |
-
|
| 9 |
-
def apply_qa(sequence=None,publish=True):
|
| 10 |
-
seq=sequence or SEQ
|
| 11 |
-
base=DATA_ROOT/'HOT3D';root=base/RELEASE;src=base/'raw/data/Aria'/seq
|
| 12 |
-
gtfile=next(src.glob('*ground_truth.zip'));qa_report={}
|
| 13 |
-
with zipfile.ZipFile(gtfile) as z:
|
| 14 |
-
masks=csvrows(z,'masks/mask_qa_pass.csv');hands=csvrows(z,'box2d_hands.csv');objects=csvrows(z,'box2d_objects.csv')
|
| 15 |
-
for meta in sorted((root/'data'/seq).glob('*/metainfo.json')):
|
| 16 |
-
p=meta.parent;m=load(meta);cam=m['camera_id'];T=m['num_frames'];frames=[json.loads(x) for x in (p/'camera/frames.jsonl').read_text().splitlines()]
|
| 17 |
-
cache=base/'tmp'/VIDEO_RUN/'diagnostic'/(cam if seq==SEQ else seq+'/'+cam)
|
| 18 |
-
if (cache/'snapshot.json').exists():assert Path(load(cache/'snapshot.json')['source_view']).resolve()==p.resolve()
|
| 19 |
-
if not (cache/'snapshot.json').exists():
|
| 20 |
-
cache.mkdir(parents=True,exist_ok=True)
|
| 21 |
-
for file in p.rglob('*.pt'):
|
| 22 |
-
target=cache/file.relative_to(p);target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(file,target)
|
| 23 |
-
save(cache/'metainfo.json',m);save(cache/'snapshot.json',{'purpose':'pre-QA native parameter diagnostics only; not shared usable labels','source_view':str(p),'frames':T})
|
| 24 |
-
lookup={int(r['timestamp[ns]']):r['mask']=='True' for r in masks if r['stream_id']==cam}
|
| 25 |
-
qa=np.array([lookup[f['timecode_ns']] for f in frames],bool)
|
| 26 |
-
source={'archive':gtfile.relative_to(base).as_posix(),'member':'masks/mask_qa_pass.csv','stream_id':cam,'time_index_ref':'camera/frames.jsonl:timecode_ns'}
|
| 27 |
-
policy={'semantics':'usable_annotation','formula':'source_annotation_present AND source_numerically_valid AND official_manual_qa_pass',
|
| 28 |
-
'qa_scope':'all visible hand/object poses in this camera frame; conservatively exclude all hand/object supervision if false',
|
| 29 |
-
'source_locator':source,'no_qa_source_rule':'use the component source-validity rules; do not invent QA'}
|
| 30 |
-
for key,c in m['components'].items():
|
| 31 |
-
# Camera calibration and RGB are not labels covered by this manual hand/object QA flag.
|
| 32 |
-
if key=='mano' or c['schema_id'] in ['object/rigid/v1','object/joint_state/v1','object_keypoints/camera/v1']:
|
| 33 |
-
values=torch.load(cache/c['data_ref'],weights_only=True).numpy();present=torch.load(cache/c['valid_ref'],weights_only=True).numpy()
|
| 34 |
-
valid=present & qa.reshape((T,)+(1,)*(present.ndim-1));values=values.copy();values[~valid]=np.nan
|
| 35 |
-
tensor(p/c['data_ref'],values);tensor(p/c['valid_ref'],valid);c['valid_policy']=policy
|
| 36 |
-
for attrname,a in c.get('attributes',{}).items():
|
| 37 |
-
if attrname!='visibility':continue
|
| 38 |
-
ishand=key=='mano';oid=c['source_locator'].get('object_uid');ids=[0,1] if ishand else [oid]
|
| 39 |
-
rows=hands if ishand else objects;identity='hand_index' if ishand else 'object_uid'
|
| 40 |
-
native={(int(r['timestamp[ns]']),str(r[identity])):float(r['visibility_ratio[%]']) for r in rows if r['stream_id']==cam and r['visibility_ratio[%]']!=''}
|
| 41 |
-
values=np.array([[native.get((f['timecode_ns'],str(k)),np.nan) for k in ids] for f in frames],np.float32)
|
| 42 |
-
if not ishand:values=values[:,0]
|
| 43 |
-
present=np.isfinite(values);assert ((values[present]>=0)&(values[present]<=1)).all()
|
| 44 |
-
# Correct the diagnostic copy as well: these values are fractions, despite the source header.
|
| 45 |
-
tensor(cache/a['data_ref'],values);tensor(cache/a['valid_ref'],present)
|
| 46 |
-
valid=present & qa.reshape((T,)+(1,)*(present.ndim-1));filtered=values.copy();filtered[~valid]=np.nan
|
| 47 |
-
tensor(p/a['data_ref'],filtered);tensor(p/a['valid_ref'],valid)
|
| 48 |
-
a['provenance']={'kind':'source','method':'native [0,1] ratio retained; official loader does not divide misleading [%] header by 100'}
|
| 49 |
-
a['valid_policy']={'semantics':'usable_visibility_annotation','formula':'source_ratio_present AND official_manual_qa_pass','source_locator':source}
|
| 50 |
-
a['source_locator']['match_method']='exact'
|
| 51 |
-
m['validity_revision']='usable-annotation-2026-09-20'
|
| 52 |
-
m['split']='train';m['split_scheme']='HOT3D_official_participant_split';m.pop('split_reason',None)
|
| 53 |
-
m['split_source_locator']={'url':'https://github.com/facebookresearch/hot3d/blob/146b34afef8c1a32adeef7e981c070109f225c87/README.md#testtrain-split','participant_id':seq.split('_')[0]}
|
| 54 |
-
assert seq.split('_')[0] not in {'P0004','P0005','P0006','P0008','P0016','P0020'}
|
| 55 |
-
save(meta,m)
|
| 56 |
-
qa_report[cam]={'frames':T,'qa_pass':qa.tolist(),'passed_count':int(qa.sum()),'source_locator':source,
|
| 57 |
-
'interpretation':'manual QA of visible hand/object poses; not RGB validity or individual error localization'}
|
| 58 |
-
print('QA_APPLIED',cam,'pass',int(qa.sum()),'fail',int((~qa).sum()),flush=True)
|
| 59 |
-
save(root/'doc/validation/source_qa.json' if publish else base/'tmp'/RUN/'qa'/f'{seq}.json',qa_report)
|
| 60 |
-
if publish:
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
return qa_report
|
| 64 |
-
|
| 65 |
-
if __name__=='__main__':apply_qa()
|
|
|
|
| 1 |
+
"""Apply native HOT3D manual QA to supervision validity, preserving raw diagnostics."""
|
| 2 |
+
from fresh_sequence_common import *
|
| 3 |
+
|
| 4 |
+
VIDEO_RUN='full-video-review-v2'
|
| 5 |
+
SEQ='P0015_179e1b84'
|
| 6 |
+
|
| 7 |
+
def csvrows(z,name):return list(csv.DictReader(io.StringIO(z.read(name).decode())))
|
| 8 |
+
|
| 9 |
+
def apply_qa(sequence=None,publish=True):
|
| 10 |
+
seq=sequence or SEQ
|
| 11 |
+
base=DATA_ROOT/'HOT3D';root=base/RELEASE;src=base/'raw/data/Aria'/seq
|
| 12 |
+
gtfile=next(src.glob('*ground_truth.zip'));qa_report={}
|
| 13 |
+
with zipfile.ZipFile(gtfile) as z:
|
| 14 |
+
masks=csvrows(z,'masks/mask_qa_pass.csv');hands=csvrows(z,'box2d_hands.csv');objects=csvrows(z,'box2d_objects.csv')
|
| 15 |
+
for meta in sorted((root/'data'/seq).glob('*/metainfo.json')):
|
| 16 |
+
p=meta.parent;m=load(meta);cam=m['camera_id'];T=m['num_frames'];frames=[json.loads(x) for x in (p/'camera/frames.jsonl').read_text().splitlines()]
|
| 17 |
+
cache=base/'tmp'/VIDEO_RUN/'diagnostic'/(cam if seq==SEQ else seq+'/'+cam)
|
| 18 |
+
if (cache/'snapshot.json').exists():assert Path(load(cache/'snapshot.json')['source_view']).resolve()==p.resolve()
|
| 19 |
+
if not (cache/'snapshot.json').exists():
|
| 20 |
+
cache.mkdir(parents=True,exist_ok=True)
|
| 21 |
+
for file in p.rglob('*.pt'):
|
| 22 |
+
target=cache/file.relative_to(p);target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(file,target)
|
| 23 |
+
save(cache/'metainfo.json',m);save(cache/'snapshot.json',{'purpose':'pre-QA native parameter diagnostics only; not shared usable labels','source_view':str(p),'frames':T})
|
| 24 |
+
lookup={int(r['timestamp[ns]']):r['mask']=='True' for r in masks if r['stream_id']==cam}
|
| 25 |
+
qa=np.array([lookup[f['timecode_ns']] for f in frames],bool)
|
| 26 |
+
source={'archive':gtfile.relative_to(base).as_posix(),'member':'masks/mask_qa_pass.csv','stream_id':cam,'time_index_ref':'camera/frames.jsonl:timecode_ns'}
|
| 27 |
+
policy={'semantics':'usable_annotation','formula':'source_annotation_present AND source_numerically_valid AND official_manual_qa_pass',
|
| 28 |
+
'qa_scope':'all visible hand/object poses in this camera frame; conservatively exclude all hand/object supervision if false',
|
| 29 |
+
'source_locator':source,'no_qa_source_rule':'use the component source-validity rules; do not invent QA'}
|
| 30 |
+
for key,c in m['components'].items():
|
| 31 |
+
# Camera calibration and RGB are not labels covered by this manual hand/object QA flag.
|
| 32 |
+
if key=='mano' or c['schema_id'] in ['object/rigid/v1','object/joint_state/v1','object_keypoints/camera/v1']:
|
| 33 |
+
values=torch.load(cache/c['data_ref'],weights_only=True).numpy();present=torch.load(cache/c['valid_ref'],weights_only=True).numpy()
|
| 34 |
+
valid=present & qa.reshape((T,)+(1,)*(present.ndim-1));values=values.copy();values[~valid]=np.nan
|
| 35 |
+
tensor(p/c['data_ref'],values);tensor(p/c['valid_ref'],valid);c['valid_policy']=policy
|
| 36 |
+
for attrname,a in c.get('attributes',{}).items():
|
| 37 |
+
if attrname!='visibility':continue
|
| 38 |
+
ishand=key=='mano';oid=c['source_locator'].get('object_uid');ids=[0,1] if ishand else [oid]
|
| 39 |
+
rows=hands if ishand else objects;identity='hand_index' if ishand else 'object_uid'
|
| 40 |
+
native={(int(r['timestamp[ns]']),str(r[identity])):float(r['visibility_ratio[%]']) for r in rows if r['stream_id']==cam and r['visibility_ratio[%]']!=''}
|
| 41 |
+
values=np.array([[native.get((f['timecode_ns'],str(k)),np.nan) for k in ids] for f in frames],np.float32)
|
| 42 |
+
if not ishand:values=values[:,0]
|
| 43 |
+
present=np.isfinite(values);assert ((values[present]>=0)&(values[present]<=1)).all()
|
| 44 |
+
# Correct the diagnostic copy as well: these values are fractions, despite the source header.
|
| 45 |
+
tensor(cache/a['data_ref'],values);tensor(cache/a['valid_ref'],present)
|
| 46 |
+
valid=present & qa.reshape((T,)+(1,)*(present.ndim-1));filtered=values.copy();filtered[~valid]=np.nan
|
| 47 |
+
tensor(p/a['data_ref'],filtered);tensor(p/a['valid_ref'],valid)
|
| 48 |
+
a['provenance']={'kind':'source','method':'native [0,1] ratio retained; official loader does not divide misleading [%] header by 100'}
|
| 49 |
+
a['valid_policy']={'semantics':'usable_visibility_annotation','formula':'source_ratio_present AND official_manual_qa_pass','source_locator':source}
|
| 50 |
+
a['source_locator']['match_method']='exact'
|
| 51 |
+
m['validity_revision']='usable-annotation-2026-09-20'
|
| 52 |
+
m['split']='train';m['split_scheme']='HOT3D_official_participant_split';m.pop('split_reason',None)
|
| 53 |
+
m['split_source_locator']={'url':'https://github.com/facebookresearch/hot3d/blob/146b34afef8c1a32adeef7e981c070109f225c87/README.md#testtrain-split','participant_id':seq.split('_')[0]}
|
| 54 |
+
assert seq.split('_')[0] not in {'P0004','P0005','P0006','P0008','P0016','P0020'}
|
| 55 |
+
save(meta,m)
|
| 56 |
+
qa_report[cam]={'frames':T,'qa_pass':qa.tolist(),'passed_count':int(qa.sum()),'source_locator':source,
|
| 57 |
+
'interpretation':'manual QA of visible hand/object poses; not RGB validity or individual error localization'}
|
| 58 |
+
print('QA_APPLIED',cam,'pass',int(qa.sum()),'fail',int((~qa).sum()),flush=True)
|
| 59 |
+
save(root/'doc/validation/source_qa.json' if publish else base/'tmp'/RUN/'qa'/f'{seq}.json',qa_report)
|
| 60 |
+
if publish:
|
| 61 |
+
# QA publication updates data/report artifacts only; the organized script bundle stays immutable.
|
| 62 |
+
pass
|
| 63 |
+
return qa_report
|
| 64 |
+
|
| 65 |
+
if __name__=='__main__':apply_qa()
|
HOT3D/shared-v1.0/script/internal/fresh_sequence_common.py
CHANGED
|
@@ -1,212 +1,209 @@
|
|
| 1 |
-
"""Helpers for the fresh ARCTIC/HOT3D whole-sequence v1.0 pilots.
|
| 2 |
-
|
| 3 |
-
Original archives are read only. Temporary extraction is outside raw.
|
| 4 |
-
Licensed MANO weights stay in the local model directory and are never published.
|
| 5 |
-
"""
|
| 6 |
-
from sequence_pilot_world import camera_mano, Mano
|
| 7 |
-
from pilot_build import *
|
| 8 |
-
from scipy.spatial.transform import Rotation
|
| 9 |
-
import hashlib
|
| 10 |
-
import re
|
| 11 |
-
import time
|
| 12 |
-
import trimesh
|
| 13 |
-
from concurrent.futures import ThreadPoolExecutor,wait,FIRST_COMPLETED
|
| 14 |
-
from contextlib import contextmanager
|
| 15 |
-
|
| 16 |
-
DATA_ROOT = Path('E:/hand-datasets')
|
| 17 |
-
RELEASE = 'shared-v1.0'
|
| 18 |
-
RUN = 'fresh-sequence-pilot-20260920'
|
| 19 |
-
VRS = WORK/'scripts/tools/vrs_env/Library/bin/vrs.exe'
|
| 20 |
-
MEDIA_POOL=None
|
| 21 |
-
MEDIA_PENDING=[]
|
| 22 |
-
MEDIA_WORKERS=1
|
| 23 |
-
MEDIA_POLICY='legacy_full_pixels'
|
| 24 |
-
OUTPUT_OVERRIDE=None
|
| 25 |
-
TMP_OVERRIDE=None
|
| 26 |
-
|
| 27 |
-
@contextmanager
|
| 28 |
-
def media_pipeline(workers=1,policy='jpeg-packets-all-rgb-sample16/v1'):
|
| 29 |
-
global MEDIA_POOL,MEDIA_PENDING,MEDIA_WORKERS,MEDIA_POLICY
|
| 30 |
-
assert MEDIA_POOL is None and not MEDIA_PENDING
|
| 31 |
-
MEDIA_WORKERS=workers;MEDIA_POLICY=policy
|
| 32 |
-
MEDIA_POOL=ThreadPoolExecutor(max_workers=workers)
|
| 33 |
-
try:
|
| 34 |
-
yield
|
| 35 |
-
for future in MEDIA_PENDING:future.result()
|
| 36 |
-
finally:
|
| 37 |
-
MEDIA_POOL.shutdown(wait=True,cancel_futures=True)
|
| 38 |
-
MEDIA_POOL=None;MEDIA_PENDING=[];MEDIA_POLICY='legacy_full_pixels'
|
| 39 |
-
|
| 40 |
-
def submit_media(view,members_factory):
|
| 41 |
-
global MEDIA_PENDING
|
| 42 |
-
def execute():
|
| 43 |
-
jpeg_video(view,members_factory());view.m['pilot_complete']=True;view.finish()
|
| 44 |
-
if MEDIA_POOL is None:execute();return
|
| 45 |
-
# Bound pending views and source/video spools, not only running FFmpeg tasks.
|
| 46 |
-
while len(MEDIA_PENDING)>=MEDIA_WORKERS:
|
| 47 |
-
finished,_=wait(MEDIA_PENDING,return_when=FIRST_COMPLETED)
|
| 48 |
-
for future in finished:future.result()
|
| 49 |
-
MEDIA_PENDING=[f for f in MEDIA_PENDING if f not in finished]
|
| 50 |
-
MEDIA_PENDING.append(MEDIA_POOL.submit(execute))
|
| 51 |
-
|
| 52 |
-
def digest(p):
|
| 53 |
-
h=hashlib.sha256()
|
| 54 |
-
with Path(p).open('rb') as f:
|
| 55 |
-
for b in iter(lambda:f.read(4*1024*1024),b''): h.update(b)
|
| 56 |
-
return h.hexdigest()
|
| 57 |
-
|
| 58 |
-
def native_npy_bytes(data):
|
| 59 |
-
f=io.BytesIO(data);version=np.lib.format.read_magic(f)
|
| 60 |
-
shape,order,dtype=np.lib.format._read_array_header(f,version)
|
| 61 |
-
if dtype.hasobject:return Restricted(f,encoding='latin1').load().item()
|
| 62 |
-
return np.frombuffer(f.read(),dtype=dtype).reshape(shape,order='F' if order else 'C').copy()
|
| 63 |
-
|
| 64 |
-
def command(args):
|
| 65 |
-
r=subprocess.run([str(x) for x in args],capture_output=True)
|
| 66 |
-
if r.returncode:raise RuntimeError(r.stderr.decode(errors='replace')[-3000:])
|
| 67 |
-
return r.stdout
|
| 68 |
-
|
| 69 |
-
def framehash(args,copy=False):
|
| 70 |
-
output=command([FF,'-v','error','-threads','2','-noautorotate',*args,'-map','0:v:0',
|
| 71 |
-
*(['-c:v','copy'] if copy else ['-pix_fmt','rgb24','-threads','2']),
|
| 72 |
-
'-f','framehash','-hash','sha256','-fps_mode','passthrough','pipe:1']).decode()
|
| 73 |
-
return [(int(r.split(',')[-2]),r.split(',')[-1].strip()) for r in output.splitlines() if r and not r.startswith('#')]
|
| 74 |
-
|
| 75 |
-
def jpeg_video(view, members):
|
| 76 |
-
"""members is a fresh iterator of (locator, JPEG bytes). Verify every packet/frame."""
|
| 77 |
-
if MEDIA_POLICY!='legacy_full_pixels':
|
| 78 |
-
from accelerated_media import write_video
|
| 79 |
-
return write_video(view,members)
|
| 80 |
-
temporary=view.tmp/f'{view.m["sequence_id"]}__{view.m["camera_id"]}.mjpeg'
|
| 81 |
-
temporary.parent.mkdir(parents=True,exist_ok=True)
|
| 82 |
-
hashes=[]
|
| 83 |
-
with temporary.open('wb') as out:
|
| 84 |
-
for locator,b in members:
|
| 85 |
-
assert b[:2]==b'\xff\xd8',locator
|
| 86 |
-
hashes.append((len(b),hashlib.sha256(b).hexdigest()));out.write(b)
|
| 87 |
-
assert len(hashes)==view.T
|
| 88 |
-
dst=view.p/'observation/rgb.mkv';dst.parent.mkdir(parents=True,exist_ok=True)
|
| 89 |
-
source=['-f','image2pipe','-framerate','1','-c:v','mjpeg','-i',str(temporary)]
|
| 90 |
-
command([FF,'-v','error','-y',*source,'-map','0:v:0','-c:v','copy',dst])
|
| 91 |
-
packet=framehash(['-i',str(dst)],True)
|
| 92 |
-
assert packet==hashes,'source JPEG packets changed in MKV'
|
| 93 |
-
before=framehash(source);after=framehash(['-i',str(dst)])
|
| 94 |
-
assert before==after and len(before)==view.T,'RGB decoding differs'
|
| 95 |
-
w,h=view.m['camera']['image_size'];assert all(n==w*h*3 for n,_ in after)
|
| 96 |
-
info=subprocess.run([FF,'-hide_banner','-i',str(dst)],capture_output=True).stderr.decode(errors='replace')
|
| 97 |
-
line=next(s.strip() for s in info.splitlines() if 'Video: mjpeg' in s)
|
| 98 |
-
pixel=re.search(r'Video: mjpeg[^,]*,\s*(\w+)',line).group(1)
|
| 99 |
-
version=command([FF,'-version']).decode().splitlines()[0]
|
| 100 |
-
view.component('rgb','observation/rgb.mkv','rgb/uint8/v1',['T','height','width','channel'],np.ones(view.T,bool),
|
| 101 |
-
source=view.source,method='Original JPEG packets copied from raw into MKV; no recompression or rotation',
|
| 102 |
-
storage={'profile':'mkv/mjpeg_copy/v1','codec':'mjpeg','pixel_format':pixel,'encoded_size':[w,h],
|
| 103 |
-
'source_lossy':True,'decoder':{'name':'ffmpeg','version':version,'output_pixel_format':'rgb24','autorotate':False,'source_color_declaration':'unknown','actual_stream_description':line},
|
| 104 |
-
'encoder_parameters':{'mode':'stream_copy','version':version}},storage_fps=1,timebase_role='index_only')
|
| 105 |
-
view.checks.append({'test':'all_source_JPEG_packets_and_RGB_pixels_exact','passed':True,'frames':view.T,
|
| 106 |
-
'packet_manifest_sha256':hashlib.sha256(json.dumps(hashes).encode()).hexdigest(),
|
| 107 |
-
'pixel_manifest_sha256':hashlib.sha256(json.dumps(after).encode()).hexdigest(),'output_bytes':dst.stat().st_size})
|
| 108 |
-
save(view.tmp/'media_checks'/f'{view.m["sequence_id"]}__{view.m["camera_id"]}.json',{'packets':hashes,'pixels':after})
|
| 109 |
-
# This precise file was created by this call within the current run's temporary directory.
|
| 110 |
-
assert temporary.resolve().is_relative_to(view.tmp.resolve());temporary.unlink()
|
| 111 |
-
|
| 112 |
-
class FreshView:
|
| 113 |
-
def __init__(self,dataset,seq,cam,ids,size,source):
|
| 114 |
-
self.root=(OUTPUT_OVERRIDE/dataset/RELEASE if OUTPUT_OVERRIDE else DATA_ROOT/dataset/RELEASE);self.p=self.root/'data'/seq/cam
|
| 115 |
-
self.tmp=(TMP_OVERRIDE/dataset/RUN if TMP_OVERRIDE else DATA_ROOT/dataset/'tmp'/RUN);self.p.mkdir(parents=True,exist_ok=True)
|
| 116 |
-
self.T=len(ids);self.source=source;self.checks=[]
|
| 117 |
-
self.m={'schema_version':'hand-warehouse/1.0','storage_revision':'lossless-video-2026-09-18',
|
| 118 |
-
'dataset_id':dataset,'release_id':RELEASE,'sequence_id':seq,'camera_id':cam,
|
| 119 |
-
'sample_type':'video','num_frames':self.T,'hand_slots':['left','right'],
|
| 120 |
-
'sampling':{'type':'dense','source_fps':None,'frames_ref':'camera/frames.jsonl','selection':'all released images in selected complete source sequence'},
|
| 121 |
-
'camera':{'model':'unknown','schema_id':None,'image_size':size},'split':'unknown','components':{},'pilot':True}
|
| 122 |
-
self.frames=[{'frame_index':i,'source_frame_id':str(fid),'timestamp_ns':None,'clock_domain':None,
|
| 123 |
-
'source_locator':dict(source,source_frame_id=str(fid))} for i,fid in enumerate(ids)]
|
| 124 |
-
def component(self,name,path,schema,axes,valid,source=None,method='source values retained',kind='format_conversion',**kw):
|
| 125 |
-
valid=np.asarray(valid,bool);vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix();tensor(self.p/vp,valid)
|
| 126 |
-
self.m['components'][name]={'available':True,'schema_id':schema,'data_ref':path,'axes':axes,
|
| 127 |
-
'valid_ref':vp,'valid_axes':axes[:valid.ndim],'provenance':{'kind':kind,'method':method},
|
| 128 |
-
'source_locator':source or self.source,**kw}
|
| 129 |
-
def array(self,name,path,schema,data,valid,axes,**kw):
|
| 130 |
-
a=np.asarray(data,np.float32).copy();valid=np.asarray(valid,bool)
|
| 131 |
-
assert a.shape[0]==self.T and a.shape[:valid.ndim]==valid.shape
|
| 132 |
-
assert np.isfinite(a[valid]).all(),name
|
| 133 |
-
a[~valid]=np.nan;tensor(self.p/path,a)
|
| 134 |
-
self.component(name,path,schema,axes,valid,**kw)
|
| 135 |
-
restored=torch.load(self.p/path,map_location='cpu',weights_only=True).numpy()
|
| 136 |
-
assert np.array_equal(a,restored,equal_nan=True)
|
| 137 |
-
self.checks.append({'test':'tensor_exact_roundtrip','file':path,'shape':list(a.shape),'valid_count':int(valid.sum()),'passed':True})
|
| 138 |
-
def attribute(self,parent,path,data,axes,source,meaning):
|
| 139 |
-
data=np.asarray(data,np.float32);valid=np.isfinite(data)
|
| 140 |
-
assert ((data[valid]>=0)&(data[valid]<=1)).all()
|
| 141 |
-
vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix();tensor(self.p/path,data);tensor(self.p/vp,valid)
|
| 142 |
-
self.m['components'][parent].setdefault('attributes',{})['visibility']={'data_ref':path,'valid_ref':vp,
|
| 143 |
-
'axes':axes,'valid_axes':axes,'dtype':'float32','visibility_type':'ratio','meaning':meaning,
|
| 144 |
-
'provenance':{'kind':'source','method':'native HOT3D visibility ratio retained in [0,1]; misleading [%] header is not a percentage scale'},'source_locator':source}
|
| 145 |
-
def mesh(self,oid,path,source):
|
| 146 |
-
self.component('object_'+oid+'_mesh',path,'mesh/obj/v1',['vertex','coordinate'],np.array(True),source=source,
|
| 147 |
-
method='Object vertices in metres; topology, material and texture dependencies retained',static=True,unit='m',coordinate_frame='object')
|
| 148 |
-
def finish(self):
|
| 149 |
-
lines(self.p/'camera/frames.jsonl',self.frames);save(self.p/'metainfo.json',self.m)
|
| 150 |
-
save(self.tmp/'checks'/f'{self.m["sequence_id"]}__{self.m["camera_id"]}.json',{'checks':self.checks,'frames':self.T,'input':self.source})
|
| 151 |
-
print('CONVERTED',self.m['dataset_id'],self.m['sequence_id'],self.m['camera_id'],self.T,flush=True)
|
| 152 |
-
|
| 153 |
-
def assert_se3(a):
|
| 154 |
-
a=np.asarray(a);assert a.shape[-2:]==(4,4)
|
| 155 |
-
# A component may exist while QA leaves no usable poses in this view.
|
| 156 |
-
if a.size==0:return
|
| 157 |
-
assert np.isfinite(a).all() and np.allclose(a[...,3,:],[0,0,0,1],atol=1e-6)
|
| 158 |
-
r=a[...,:3,:3];assert np.max(np.abs(r@np.swapaxes(r,-1,-2)-np.eye(3)))<2e-5
|
| 159 |
-
assert np.max(np.abs(np.linalg.det(r)-1))<2e-5
|
| 160 |
-
|
| 161 |
-
def setup(dataset,seq):
|
| 162 |
-
base=DATA_ROOT/dataset;out=base/RELEASE
|
| 163 |
-
for folder in ['doc','script','doc/validation']: (out/folder).mkdir(parents=True,exist_ok=True)
|
| 164 |
-
for f in ['CONTRACT.md','schema.json']:shutil.copyfile(WORK/'distribution/hand-warehouse-1.0'/f,out/'doc'/f)
|
| 165 |
-
save(out/'doc/validation/status.json',{'stage':'building_sequence_pilot','human_review':'pending','sequence_id':seq,'full_preprocessing_authorized':False,'upload_authorized':False})
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
if
|
| 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 |
-
else:
|
| 211 |
-
K,D=params;uv[good]=cv2.projectPoints(xyz[good],np.zeros(3),np.zeros(3),K,D)[0].reshape(-1,2)
|
| 212 |
-
return uv
|
|
|
|
| 1 |
+
"""Helpers for the fresh ARCTIC/HOT3D whole-sequence v1.0 pilots.
|
| 2 |
+
|
| 3 |
+
Original archives are read only. Temporary extraction is outside raw.
|
| 4 |
+
Licensed MANO weights stay in the local model directory and are never published.
|
| 5 |
+
"""
|
| 6 |
+
from sequence_pilot_world import camera_mano, Mano
|
| 7 |
+
from pilot_build import *
|
| 8 |
+
from scipy.spatial.transform import Rotation
|
| 9 |
+
import hashlib
|
| 10 |
+
import re
|
| 11 |
+
import time
|
| 12 |
+
import trimesh
|
| 13 |
+
from concurrent.futures import ThreadPoolExecutor,wait,FIRST_COMPLETED
|
| 14 |
+
from contextlib import contextmanager
|
| 15 |
+
|
| 16 |
+
DATA_ROOT = Path('E:/hand-datasets')
|
| 17 |
+
RELEASE = 'shared-v1.0'
|
| 18 |
+
RUN = 'fresh-sequence-pilot-20260920'
|
| 19 |
+
VRS = WORK/'scripts/tools/vrs_env/Library/bin/vrs.exe'
|
| 20 |
+
MEDIA_POOL=None
|
| 21 |
+
MEDIA_PENDING=[]
|
| 22 |
+
MEDIA_WORKERS=1
|
| 23 |
+
MEDIA_POLICY='legacy_full_pixels'
|
| 24 |
+
OUTPUT_OVERRIDE=None
|
| 25 |
+
TMP_OVERRIDE=None
|
| 26 |
+
|
| 27 |
+
@contextmanager
|
| 28 |
+
def media_pipeline(workers=1,policy='jpeg-packets-all-rgb-sample16/v1'):
|
| 29 |
+
global MEDIA_POOL,MEDIA_PENDING,MEDIA_WORKERS,MEDIA_POLICY
|
| 30 |
+
assert MEDIA_POOL is None and not MEDIA_PENDING
|
| 31 |
+
MEDIA_WORKERS=workers;MEDIA_POLICY=policy
|
| 32 |
+
MEDIA_POOL=ThreadPoolExecutor(max_workers=workers)
|
| 33 |
+
try:
|
| 34 |
+
yield
|
| 35 |
+
for future in MEDIA_PENDING:future.result()
|
| 36 |
+
finally:
|
| 37 |
+
MEDIA_POOL.shutdown(wait=True,cancel_futures=True)
|
| 38 |
+
MEDIA_POOL=None;MEDIA_PENDING=[];MEDIA_POLICY='legacy_full_pixels'
|
| 39 |
+
|
| 40 |
+
def submit_media(view,members_factory):
|
| 41 |
+
global MEDIA_PENDING
|
| 42 |
+
def execute():
|
| 43 |
+
jpeg_video(view,members_factory());view.m['pilot_complete']=True;view.finish()
|
| 44 |
+
if MEDIA_POOL is None:execute();return
|
| 45 |
+
# Bound pending views and source/video spools, not only running FFmpeg tasks.
|
| 46 |
+
while len(MEDIA_PENDING)>=MEDIA_WORKERS:
|
| 47 |
+
finished,_=wait(MEDIA_PENDING,return_when=FIRST_COMPLETED)
|
| 48 |
+
for future in finished:future.result()
|
| 49 |
+
MEDIA_PENDING=[f for f in MEDIA_PENDING if f not in finished]
|
| 50 |
+
MEDIA_PENDING.append(MEDIA_POOL.submit(execute))
|
| 51 |
+
|
| 52 |
+
def digest(p):
|
| 53 |
+
h=hashlib.sha256()
|
| 54 |
+
with Path(p).open('rb') as f:
|
| 55 |
+
for b in iter(lambda:f.read(4*1024*1024),b''): h.update(b)
|
| 56 |
+
return h.hexdigest()
|
| 57 |
+
|
| 58 |
+
def native_npy_bytes(data):
|
| 59 |
+
f=io.BytesIO(data);version=np.lib.format.read_magic(f)
|
| 60 |
+
shape,order,dtype=np.lib.format._read_array_header(f,version)
|
| 61 |
+
if dtype.hasobject:return Restricted(f,encoding='latin1').load().item()
|
| 62 |
+
return np.frombuffer(f.read(),dtype=dtype).reshape(shape,order='F' if order else 'C').copy()
|
| 63 |
+
|
| 64 |
+
def command(args):
|
| 65 |
+
r=subprocess.run([str(x) for x in args],capture_output=True)
|
| 66 |
+
if r.returncode:raise RuntimeError(r.stderr.decode(errors='replace')[-3000:])
|
| 67 |
+
return r.stdout
|
| 68 |
+
|
| 69 |
+
def framehash(args,copy=False):
|
| 70 |
+
output=command([FF,'-v','error','-threads','2','-noautorotate',*args,'-map','0:v:0',
|
| 71 |
+
*(['-c:v','copy'] if copy else ['-pix_fmt','rgb24','-threads','2']),
|
| 72 |
+
'-f','framehash','-hash','sha256','-fps_mode','passthrough','pipe:1']).decode()
|
| 73 |
+
return [(int(r.split(',')[-2]),r.split(',')[-1].strip()) for r in output.splitlines() if r and not r.startswith('#')]
|
| 74 |
+
|
| 75 |
+
def jpeg_video(view, members):
|
| 76 |
+
"""members is a fresh iterator of (locator, JPEG bytes). Verify every packet/frame."""
|
| 77 |
+
if MEDIA_POLICY!='legacy_full_pixels':
|
| 78 |
+
from accelerated_media import write_video
|
| 79 |
+
return write_video(view,members)
|
| 80 |
+
temporary=view.tmp/f'{view.m["sequence_id"]}__{view.m["camera_id"]}.mjpeg'
|
| 81 |
+
temporary.parent.mkdir(parents=True,exist_ok=True)
|
| 82 |
+
hashes=[]
|
| 83 |
+
with temporary.open('wb') as out:
|
| 84 |
+
for locator,b in members:
|
| 85 |
+
assert b[:2]==b'\xff\xd8',locator
|
| 86 |
+
hashes.append((len(b),hashlib.sha256(b).hexdigest()));out.write(b)
|
| 87 |
+
assert len(hashes)==view.T
|
| 88 |
+
dst=view.p/'observation/rgb.mkv';dst.parent.mkdir(parents=True,exist_ok=True)
|
| 89 |
+
source=['-f','image2pipe','-framerate','1','-c:v','mjpeg','-i',str(temporary)]
|
| 90 |
+
command([FF,'-v','error','-y',*source,'-map','0:v:0','-c:v','copy',dst])
|
| 91 |
+
packet=framehash(['-i',str(dst)],True)
|
| 92 |
+
assert packet==hashes,'source JPEG packets changed in MKV'
|
| 93 |
+
before=framehash(source);after=framehash(['-i',str(dst)])
|
| 94 |
+
assert before==after and len(before)==view.T,'RGB decoding differs'
|
| 95 |
+
w,h=view.m['camera']['image_size'];assert all(n==w*h*3 for n,_ in after)
|
| 96 |
+
info=subprocess.run([FF,'-hide_banner','-i',str(dst)],capture_output=True).stderr.decode(errors='replace')
|
| 97 |
+
line=next(s.strip() for s in info.splitlines() if 'Video: mjpeg' in s)
|
| 98 |
+
pixel=re.search(r'Video: mjpeg[^,]*,\s*(\w+)',line).group(1)
|
| 99 |
+
version=command([FF,'-version']).decode().splitlines()[0]
|
| 100 |
+
view.component('rgb','observation/rgb.mkv','rgb/uint8/v1',['T','height','width','channel'],np.ones(view.T,bool),
|
| 101 |
+
source=view.source,method='Original JPEG packets copied from raw into MKV; no recompression or rotation',
|
| 102 |
+
storage={'profile':'mkv/mjpeg_copy/v1','codec':'mjpeg','pixel_format':pixel,'encoded_size':[w,h],
|
| 103 |
+
'source_lossy':True,'decoder':{'name':'ffmpeg','version':version,'output_pixel_format':'rgb24','autorotate':False,'source_color_declaration':'unknown','actual_stream_description':line},
|
| 104 |
+
'encoder_parameters':{'mode':'stream_copy','version':version}},storage_fps=1,timebase_role='index_only')
|
| 105 |
+
view.checks.append({'test':'all_source_JPEG_packets_and_RGB_pixels_exact','passed':True,'frames':view.T,
|
| 106 |
+
'packet_manifest_sha256':hashlib.sha256(json.dumps(hashes).encode()).hexdigest(),
|
| 107 |
+
'pixel_manifest_sha256':hashlib.sha256(json.dumps(after).encode()).hexdigest(),'output_bytes':dst.stat().st_size})
|
| 108 |
+
save(view.tmp/'media_checks'/f'{view.m["sequence_id"]}__{view.m["camera_id"]}.json',{'packets':hashes,'pixels':after})
|
| 109 |
+
# This precise file was created by this call within the current run's temporary directory.
|
| 110 |
+
assert temporary.resolve().is_relative_to(view.tmp.resolve());temporary.unlink()
|
| 111 |
+
|
| 112 |
+
class FreshView:
|
| 113 |
+
def __init__(self,dataset,seq,cam,ids,size,source):
|
| 114 |
+
self.root=(OUTPUT_OVERRIDE/dataset/RELEASE if OUTPUT_OVERRIDE else DATA_ROOT/dataset/RELEASE);self.p=self.root/'data'/seq/cam
|
| 115 |
+
self.tmp=(TMP_OVERRIDE/dataset/RUN if TMP_OVERRIDE else DATA_ROOT/dataset/'tmp'/RUN);self.p.mkdir(parents=True,exist_ok=True)
|
| 116 |
+
self.T=len(ids);self.source=source;self.checks=[]
|
| 117 |
+
self.m={'schema_version':'hand-warehouse/1.0','storage_revision':'lossless-video-2026-09-18',
|
| 118 |
+
'dataset_id':dataset,'release_id':RELEASE,'sequence_id':seq,'camera_id':cam,
|
| 119 |
+
'sample_type':'video','num_frames':self.T,'hand_slots':['left','right'],
|
| 120 |
+
'sampling':{'type':'dense','source_fps':None,'frames_ref':'camera/frames.jsonl','selection':'all released images in selected complete source sequence'},
|
| 121 |
+
'camera':{'model':'unknown','schema_id':None,'image_size':size},'split':'unknown','components':{},'pilot':True}
|
| 122 |
+
self.frames=[{'frame_index':i,'source_frame_id':str(fid),'timestamp_ns':None,'clock_domain':None,
|
| 123 |
+
'source_locator':dict(source,source_frame_id=str(fid))} for i,fid in enumerate(ids)]
|
| 124 |
+
def component(self,name,path,schema,axes,valid,source=None,method='source values retained',kind='format_conversion',**kw):
|
| 125 |
+
valid=np.asarray(valid,bool);vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix();tensor(self.p/vp,valid)
|
| 126 |
+
self.m['components'][name]={'available':True,'schema_id':schema,'data_ref':path,'axes':axes,
|
| 127 |
+
'valid_ref':vp,'valid_axes':axes[:valid.ndim],'provenance':{'kind':kind,'method':method},
|
| 128 |
+
'source_locator':source or self.source,**kw}
|
| 129 |
+
def array(self,name,path,schema,data,valid,axes,**kw):
|
| 130 |
+
a=np.asarray(data,np.float32).copy();valid=np.asarray(valid,bool)
|
| 131 |
+
assert a.shape[0]==self.T and a.shape[:valid.ndim]==valid.shape
|
| 132 |
+
assert np.isfinite(a[valid]).all(),name
|
| 133 |
+
a[~valid]=np.nan;tensor(self.p/path,a)
|
| 134 |
+
self.component(name,path,schema,axes,valid,**kw)
|
| 135 |
+
restored=torch.load(self.p/path,map_location='cpu',weights_only=True).numpy()
|
| 136 |
+
assert np.array_equal(a,restored,equal_nan=True)
|
| 137 |
+
self.checks.append({'test':'tensor_exact_roundtrip','file':path,'shape':list(a.shape),'valid_count':int(valid.sum()),'passed':True})
|
| 138 |
+
def attribute(self,parent,path,data,axes,source,meaning):
|
| 139 |
+
data=np.asarray(data,np.float32);valid=np.isfinite(data)
|
| 140 |
+
assert ((data[valid]>=0)&(data[valid]<=1)).all()
|
| 141 |
+
vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix();tensor(self.p/path,data);tensor(self.p/vp,valid)
|
| 142 |
+
self.m['components'][parent].setdefault('attributes',{})['visibility']={'data_ref':path,'valid_ref':vp,
|
| 143 |
+
'axes':axes,'valid_axes':axes,'dtype':'float32','visibility_type':'ratio','meaning':meaning,
|
| 144 |
+
'provenance':{'kind':'source','method':'native HOT3D visibility ratio retained in [0,1]; misleading [%] header is not a percentage scale'},'source_locator':source}
|
| 145 |
+
def mesh(self,oid,path,source):
|
| 146 |
+
self.component('object_'+oid+'_mesh',path,'mesh/obj/v1',['vertex','coordinate'],np.array(True),source=source,
|
| 147 |
+
method='Object vertices in metres; topology, material and texture dependencies retained',static=True,unit='m',coordinate_frame='object')
|
| 148 |
+
def finish(self):
|
| 149 |
+
lines(self.p/'camera/frames.jsonl',self.frames);save(self.p/'metainfo.json',self.m)
|
| 150 |
+
save(self.tmp/'checks'/f'{self.m["sequence_id"]}__{self.m["camera_id"]}.json',{'checks':self.checks,'frames':self.T,'input':self.source})
|
| 151 |
+
print('CONVERTED',self.m['dataset_id'],self.m['sequence_id'],self.m['camera_id'],self.T,flush=True)
|
| 152 |
+
|
| 153 |
+
def assert_se3(a):
|
| 154 |
+
a=np.asarray(a);assert a.shape[-2:]==(4,4)
|
| 155 |
+
# A component may exist while QA leaves no usable poses in this view.
|
| 156 |
+
if a.size==0:return
|
| 157 |
+
assert np.isfinite(a).all() and np.allclose(a[...,3,:],[0,0,0,1],atol=1e-6)
|
| 158 |
+
r=a[...,:3,:3];assert np.max(np.abs(r@np.swapaxes(r,-1,-2)-np.eye(3)))<2e-5
|
| 159 |
+
assert np.max(np.abs(np.linalg.det(r)-1))<2e-5
|
| 160 |
+
|
| 161 |
+
def setup(dataset,seq):
|
| 162 |
+
base=DATA_ROOT/dataset;out=base/RELEASE
|
| 163 |
+
for folder in ['doc','script','doc/validation']: (out/folder).mkdir(parents=True,exist_ok=True)
|
| 164 |
+
for f in ['CONTRACT.md','schema.json']:shutil.copyfile(WORK/'distribution/hand-warehouse-1.0'/f,out/'doc'/f)
|
| 165 |
+
save(out/'doc/validation/status.json',{'stage':'building_sequence_pilot','human_review':'pending','sequence_id':seq,'full_preprocessing_authorized':False,'upload_authorized':False})
|
| 166 |
+
# The organized script bundle is already self-contained; runtime work must not repopulate its root.
|
| 167 |
+
(base/'tmp'/RUN).mkdir(parents=True,exist_ok=True)
|
| 168 |
+
|
| 169 |
+
def object_textured_assets(z,prefix,target):
|
| 170 |
+
target.mkdir(parents=True,exist_ok=True)
|
| 171 |
+
for name in z.namelist():
|
| 172 |
+
if not name.startswith(prefix) or name.endswith('/'):continue
|
| 173 |
+
rel=Path(name[len(prefix):]);dest=target/rel
|
| 174 |
+
assert dest.resolve().is_relative_to(target.resolve());dest.parent.mkdir(parents=True,exist_ok=True)
|
| 175 |
+
if dest.suffix.lower() in ('.obj','.mtl','.jpg','.jpeg','.png'):
|
| 176 |
+
b=z.read(name)
|
| 177 |
+
if dest.suffix=='.obj':
|
| 178 |
+
rows=b.decode().splitlines()
|
| 179 |
+
for i,row in enumerate(rows):
|
| 180 |
+
if row.startswith('v '):
|
| 181 |
+
v=row.split();v[1:4]=[format(float(x)/1000,'.17g') for x in v[1:4]];rows[i]=' '.join(v)
|
| 182 |
+
b=('\n'.join(rows)+'\n').encode()
|
| 183 |
+
dest.write_bytes(b)
|
| 184 |
+
repair_arctic_material_refs(target)
|
| 185 |
+
|
| 186 |
+
def repair_arctic_material_refs(target):
|
| 187 |
+
"""Repair a source filename mismatch only when material identifiers agree."""
|
| 188 |
+
material=target/'material.mtl'
|
| 189 |
+
if not material.exists():return
|
| 190 |
+
ids={x.split(maxsplit=1)[1] for x in material.read_text().splitlines() if x.startswith('newmtl ')}
|
| 191 |
+
for obj in target.glob('*.obj'):
|
| 192 |
+
text=obj.read_text();rows=text.splitlines();used={x.split(maxsplit=1)[1] for x in rows if x.startswith('usemtl ')}
|
| 193 |
+
if 'mtllib material_0.mtl' in rows and not (target/'material_0.mtl').exists():
|
| 194 |
+
assert used and used.issubset(ids),(obj,used,ids)
|
| 195 |
+
obj.write_text(text.replace('mtllib material_0.mtl','mtllib material.mtl'))
|
| 196 |
+
|
| 197 |
+
def project_points(xyz,camera,params):
|
| 198 |
+
xyz=np.asarray(xyz,float);uv=np.full((len(xyz),2),np.nan);good=np.isfinite(xyz).all(1)&(xyz[:,2]>1e-6)
|
| 199 |
+
if camera=='fisheye624':
|
| 200 |
+
p=np.asarray(params);xy=xyz[good,:2]/xyz[good,2,None];r=np.linalg.norm(xy,axis=1);th=np.arctan(r)
|
| 201 |
+
radial=th*(1+sum(p[3+i]*th**(2*i+2) for i in range(6)))
|
| 202 |
+
xy=xy*np.divide(radial,r,out=np.ones_like(r),where=r>1e-12)[:,None]
|
| 203 |
+
x,y=xy.T;rr=x*x+y*y
|
| 204 |
+
xd=x+(2*x*x+rr)*p[9]+2*x*y*p[10]+p[11]*rr+p[12]*rr*rr
|
| 205 |
+
yd=y+(2*y*y+rr)*p[10]+2*x*y*p[9]+p[13]*rr+p[14]*rr*rr
|
| 206 |
+
uv[good]=p[0]*np.stack([xd,yd],1)+p[1:3]
|
| 207 |
+
else:
|
| 208 |
+
K,D=params;uv[good]=cv2.projectPoints(xyz[good],np.zeros(3),np.zeros(3),K,D)[0].reshape(-1,2)
|
| 209 |
+
return uv
|
|
|
|
|
|
|
|
|
HOT3D/shared-v1.0/script/internal/pilot_build.py
CHANGED
|
@@ -1,209 +1,207 @@
|
|
| 1 |
-
"""Small, source-traceable dataset pilot. Originals are copied, never edited.
|
| 2 |
-
|
| 3 |
-
Run with Python + numpy + torch + Pillow + opencv and imageio-ffmpeg.
|
| 4 |
-
Optional runtime installed at tmp/pilot-runtime. Outputs: hand-datasets/.
|
| 5 |
-
"""
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
import argparse, codecs, collections, csv, io, json, pickle, shutil, subprocess, sys, zipfile
|
| 8 |
-
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tmp/pilot-runtime'))
|
| 9 |
-
import numpy as np
|
| 10 |
-
import torch
|
| 11 |
-
from PIL import Image, ImageDraw
|
| 12 |
-
import cv2
|
| 13 |
-
from pilot_fetch import ROOT, sha
|
| 14 |
-
|
| 15 |
-
WORK=ROOT.parent
|
| 16 |
-
OLD=WORK/'datasets'
|
| 17 |
-
sys.path.insert(0,str(WORK/'tmp/pilot-runtime'))
|
| 18 |
-
import imageio_ffmpeg
|
| 19 |
-
FF=imageio_ffmpeg.get_ffmpeg_exe()
|
| 20 |
-
N=16
|
| 21 |
-
|
| 22 |
-
def save(p,value):
|
| 23 |
-
p.parent.mkdir(parents=True,exist_ok=True)
|
| 24 |
-
p.write_text(json.dumps(value,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
|
| 25 |
-
def lines(p,rows):
|
| 26 |
-
p.parent.mkdir(parents=True,exist_ok=True)
|
| 27 |
-
p.write_text(''.join(json.dumps(x,ensure_ascii=False,allow_nan=False)+'\n' for x in rows),encoding='utf-8')
|
| 28 |
-
def tensor(p,a):
|
| 29 |
-
p.parent.mkdir(parents=True,exist_ok=True);torch.save(torch.as_tensor(np.asarray(a).copy()),p)
|
| 30 |
-
def load(p):return json.loads(p.read_text(encoding='utf-8'))
|
| 31 |
-
|
| 32 |
-
class Restricted(pickle.Unpickler):
|
| 33 |
-
def find_class(self,module,name):
|
| 34 |
-
allowed={('numpy.core.multiarray','_reconstruct'):np.core.multiarray._reconstruct,
|
| 35 |
-
('numpy._core.multiarray','_reconstruct'):np.core.multiarray._reconstruct,
|
| 36 |
-
('numpy','ndarray'):np.ndarray,('numpy','dtype'):np.dtype,
|
| 37 |
-
('numpy.core.numeric','_frombuffer'):np.core.numeric._frombuffer,
|
| 38 |
-
('numpy._core.numeric','_frombuffer'):np.core.numeric._frombuffer,
|
| 39 |
-
('_codecs','encode'):codecs.encode,
|
| 40 |
-
('collections','OrderedDict'):collections.OrderedDict,
|
| 41 |
-
('torch._utils','_rebuild_tensor_v2'):torch._utils._rebuild_tensor_v2,
|
| 42 |
-
('torch.storage','_load_from_bytes'):lambda b:torch.load(io.BytesIO(b),map_location='cpu',weights_only=True)}
|
| 43 |
-
if (module,name) not in allowed:raise pickle.UnpicklingError(f'Unsupported class: {module}.{name}')
|
| 44 |
-
return allowed[(module,name)]
|
| 45 |
-
def read_pickle(p):
|
| 46 |
-
with p.open('rb') as f:return Restricted(f,encoding='latin1').load()
|
| 47 |
-
|
| 48 |
-
class Build:
|
| 49 |
-
def __init__(self,name):
|
| 50 |
-
self.name=name;self.base=ROOT/name;self.out=self.base/'pilot-v0';self.refs=[];self.views=[];self.checks=[]
|
| 51 |
-
for p in ['raw/doc','raw/script','raw/data','pilot-v0/doc','pilot-v0/script','pilot-v0/data']:(self.base/p).mkdir(parents=True,exist_ok=True)
|
| 52 |
-
def copy(self,src):
|
| 53 |
-
rel=src.relative_to(OLD/self.name);dst=self.base/'raw/data/local_subset'/rel
|
| 54 |
-
dst.parent.mkdir(parents=True,exist_ok=True)
|
| 55 |
-
if not dst.exists():shutil.copyfile(src,dst)
|
| 56 |
-
source_hash=sha(src);assert sha(dst)==source_hash
|
| 57 |
-
self.refs.append({'source':str(src),'stored':str(dst.relative_to(self.base)), 'sha256':source_hash,'bytes':src.stat().st_size,'kind':'historical_extracted_file_copy','official_archive_verified':False})
|
| 58 |
-
return dst
|
| 59 |
-
def view(self,seq,cam,ids,**meta):
|
| 60 |
-
p=self.out/'data'/seq/cam;p.mkdir(parents=True,exist_ok=True)
|
| 61 |
-
m={'schema_version':'pilot-v0','dataset':self.name,'sequence_id':seq,'camera_id':cam,'num_frames':len(ids),'fps':None,'split':None,'view_type':None,'time_semantics':'unknown','missing_modalities':{},**meta}
|
| 62 |
-
self.views.append((p,m))
|
| 63 |
-
lines(p/'frames.jsonl',[{'frame_index':i,'source_frame_id':str(s),'timestamp_ns':None,'clock_domain':None} for i,s in enumerate(ids)])
|
| 64 |
-
return p,m
|
| 65 |
-
def video(self,p,arrays):
|
| 66 |
-
a=np.stack(arrays);h,w=a.shape[1:3]
|
| 67 |
-
pixel='rgb24' if a.ndim==4 else ('gray16le' if a.dtype==np.uint16 else 'gray')
|
| 68 |
-
if pixel=='gray16le':a=a.astype('<u2')
|
| 69 |
-
a=np.ascontiguousarray(a);p.parent.mkdir(parents=True,exist_ok=True)
|
| 70 |
-
command=[FF,'-hide_banner','-loglevel','error','-y','-f','rawvideo','-pixel_format',pixel,'-video_size',f'{w}x{h}','-framerate','1','-i','pipe:0','-an','-c:v','ffv1','-level','3','-g','1',str(p)]
|
| 71 |
-
subprocess.run(command,input=a.tobytes(),check=True,capture_output=True)
|
| 72 |
-
decoded=subprocess.run([FF,'-v','error','-i',str(p),'-f','rawvideo','-pix_fmt',pixel,'pipe:1'],check=True,capture_output=True).stdout
|
| 73 |
-
assert decoded==a.tobytes(),f'Lossless roundtrip failed: {p}'
|
| 74 |
-
self.checks.append({'file':str(p.relative_to(self.out)),'test':'decode_all_frames_pixel_exact','passed':True,'frames':len(a),'dtype':str(a.dtype),'shape':list(a.shape)})
|
| 75 |
-
return {'codec':'FFV1','pixel_format':pixel,'container_fps':1,'container_time_is_capture_time':False}
|
| 76 |
-
def finish(self,notes):
|
| 77 |
-
for p,m in self.views:save(p/'metainfo.json',m)
|
| 78 |
-
save(self.base/'raw/doc/local_subset_manifest.json',self.refs)
|
| 79 |
-
report={'dataset':self.name,'views':len(self.views),'observations':sum(m['num_frames'] for _,m in self.views),'checks':self.checks,'notes':notes,'status':'partial' if notes else 'passed'}
|
| 80 |
-
save(self.out/'doc/report.json',report)
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
(self.out/'
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
tensor(p/'camera/
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
rgb=
|
| 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 |
-
m['
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
b.
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
m['
|
| 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 |
-
f=
|
| 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 |
-
save(ROOT/name/'pilot-v0/doc/build_error.json',{'error':str(e)});raise
|
| 209 |
-
if __name__=='__main__':main()
|
|
|
|
| 1 |
+
"""Small, source-traceable dataset pilot. Originals are copied, never edited.
|
| 2 |
+
|
| 3 |
+
Run with Python + numpy + torch + Pillow + opencv and imageio-ffmpeg.
|
| 4 |
+
Optional runtime installed at tmp/pilot-runtime. Outputs: hand-datasets/.
|
| 5 |
+
"""
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import argparse, codecs, collections, csv, io, json, pickle, shutil, subprocess, sys, zipfile
|
| 8 |
+
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tmp/pilot-runtime'))
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
from PIL import Image, ImageDraw
|
| 12 |
+
import cv2
|
| 13 |
+
from pilot_fetch import ROOT, sha
|
| 14 |
+
|
| 15 |
+
WORK=ROOT.parent
|
| 16 |
+
OLD=WORK/'datasets'
|
| 17 |
+
sys.path.insert(0,str(WORK/'tmp/pilot-runtime'))
|
| 18 |
+
import imageio_ffmpeg
|
| 19 |
+
FF=imageio_ffmpeg.get_ffmpeg_exe()
|
| 20 |
+
N=16
|
| 21 |
+
|
| 22 |
+
def save(p,value):
|
| 23 |
+
p.parent.mkdir(parents=True,exist_ok=True)
|
| 24 |
+
p.write_text(json.dumps(value,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
|
| 25 |
+
def lines(p,rows):
|
| 26 |
+
p.parent.mkdir(parents=True,exist_ok=True)
|
| 27 |
+
p.write_text(''.join(json.dumps(x,ensure_ascii=False,allow_nan=False)+'\n' for x in rows),encoding='utf-8')
|
| 28 |
+
def tensor(p,a):
|
| 29 |
+
p.parent.mkdir(parents=True,exist_ok=True);torch.save(torch.as_tensor(np.asarray(a).copy()),p)
|
| 30 |
+
def load(p):return json.loads(p.read_text(encoding='utf-8'))
|
| 31 |
+
|
| 32 |
+
class Restricted(pickle.Unpickler):
|
| 33 |
+
def find_class(self,module,name):
|
| 34 |
+
allowed={('numpy.core.multiarray','_reconstruct'):np.core.multiarray._reconstruct,
|
| 35 |
+
('numpy._core.multiarray','_reconstruct'):np.core.multiarray._reconstruct,
|
| 36 |
+
('numpy','ndarray'):np.ndarray,('numpy','dtype'):np.dtype,
|
| 37 |
+
('numpy.core.numeric','_frombuffer'):np.core.numeric._frombuffer,
|
| 38 |
+
('numpy._core.numeric','_frombuffer'):np.core.numeric._frombuffer,
|
| 39 |
+
('_codecs','encode'):codecs.encode,
|
| 40 |
+
('collections','OrderedDict'):collections.OrderedDict,
|
| 41 |
+
('torch._utils','_rebuild_tensor_v2'):torch._utils._rebuild_tensor_v2,
|
| 42 |
+
('torch.storage','_load_from_bytes'):lambda b:torch.load(io.BytesIO(b),map_location='cpu',weights_only=True)}
|
| 43 |
+
if (module,name) not in allowed:raise pickle.UnpicklingError(f'Unsupported class: {module}.{name}')
|
| 44 |
+
return allowed[(module,name)]
|
| 45 |
+
def read_pickle(p):
|
| 46 |
+
with p.open('rb') as f:return Restricted(f,encoding='latin1').load()
|
| 47 |
+
|
| 48 |
+
class Build:
|
| 49 |
+
def __init__(self,name):
|
| 50 |
+
self.name=name;self.base=ROOT/name;self.out=self.base/'pilot-v0';self.refs=[];self.views=[];self.checks=[]
|
| 51 |
+
for p in ['raw/doc','raw/script','raw/data','pilot-v0/doc','pilot-v0/script','pilot-v0/data']:(self.base/p).mkdir(parents=True,exist_ok=True)
|
| 52 |
+
def copy(self,src):
|
| 53 |
+
rel=src.relative_to(OLD/self.name);dst=self.base/'raw/data/local_subset'/rel
|
| 54 |
+
dst.parent.mkdir(parents=True,exist_ok=True)
|
| 55 |
+
if not dst.exists():shutil.copyfile(src,dst)
|
| 56 |
+
source_hash=sha(src);assert sha(dst)==source_hash
|
| 57 |
+
self.refs.append({'source':str(src),'stored':str(dst.relative_to(self.base)), 'sha256':source_hash,'bytes':src.stat().st_size,'kind':'historical_extracted_file_copy','official_archive_verified':False})
|
| 58 |
+
return dst
|
| 59 |
+
def view(self,seq,cam,ids,**meta):
|
| 60 |
+
p=self.out/'data'/seq/cam;p.mkdir(parents=True,exist_ok=True)
|
| 61 |
+
m={'schema_version':'pilot-v0','dataset':self.name,'sequence_id':seq,'camera_id':cam,'num_frames':len(ids),'fps':None,'split':None,'view_type':None,'time_semantics':'unknown','missing_modalities':{},**meta}
|
| 62 |
+
self.views.append((p,m))
|
| 63 |
+
lines(p/'frames.jsonl',[{'frame_index':i,'source_frame_id':str(s),'timestamp_ns':None,'clock_domain':None} for i,s in enumerate(ids)])
|
| 64 |
+
return p,m
|
| 65 |
+
def video(self,p,arrays):
|
| 66 |
+
a=np.stack(arrays);h,w=a.shape[1:3]
|
| 67 |
+
pixel='rgb24' if a.ndim==4 else ('gray16le' if a.dtype==np.uint16 else 'gray')
|
| 68 |
+
if pixel=='gray16le':a=a.astype('<u2')
|
| 69 |
+
a=np.ascontiguousarray(a);p.parent.mkdir(parents=True,exist_ok=True)
|
| 70 |
+
command=[FF,'-hide_banner','-loglevel','error','-y','-f','rawvideo','-pixel_format',pixel,'-video_size',f'{w}x{h}','-framerate','1','-i','pipe:0','-an','-c:v','ffv1','-level','3','-g','1',str(p)]
|
| 71 |
+
subprocess.run(command,input=a.tobytes(),check=True,capture_output=True)
|
| 72 |
+
decoded=subprocess.run([FF,'-v','error','-i',str(p),'-f','rawvideo','-pix_fmt',pixel,'pipe:1'],check=True,capture_output=True).stdout
|
| 73 |
+
assert decoded==a.tobytes(),f'Lossless roundtrip failed: {p}'
|
| 74 |
+
self.checks.append({'file':str(p.relative_to(self.out)),'test':'decode_all_frames_pixel_exact','passed':True,'frames':len(a),'dtype':str(a.dtype),'shape':list(a.shape)})
|
| 75 |
+
return {'codec':'FFV1','pixel_format':pixel,'container_fps':1,'container_time_is_capture_time':False}
|
| 76 |
+
def finish(self,notes):
|
| 77 |
+
for p,m in self.views:save(p/'metainfo.json',m)
|
| 78 |
+
save(self.base/'raw/doc/local_subset_manifest.json',self.refs)
|
| 79 |
+
report={'dataset':self.name,'views':len(self.views),'observations':sum(m['num_frames'] for _,m in self.views),'checks':self.checks,'notes':notes,'status':'partial' if notes else 'passed'}
|
| 80 |
+
save(self.out/'doc/report.json',report)
|
| 81 |
+
# Script provenance is supplied by the organized bundle and validation manifests.
|
| 82 |
+
files=[{'path':str(p.relative_to(self.out)), 'bytes':p.stat().st_size,'sha256':sha(p)} for p in sorted((self.out/'data').rglob('*')) if p.is_file()]
|
| 83 |
+
save(self.out/'doc/output_manifest.json',files)
|
| 84 |
+
print(json.dumps(report,ensure_ascii=False),flush=True)
|
| 85 |
+
return report
|
| 86 |
+
|
| 87 |
+
def h2o():
|
| 88 |
+
b=Build('H2O');src=OLD/'H2O/subject4_ego/h1/0/cam4';ids=list(range(N))
|
| 89 |
+
p,m=b.view('subject4_h1_0','cam4',ids,split='test',view_type='ego',time_semantics='ordered_source_frames; acquisition FPS not yet verified')
|
| 90 |
+
for folder in ['rgb','depth','hand_pose','hand_pose_mano','cam_pose']:
|
| 91 |
+
for i in ids:b.copy(src/folder/f'{i:06d}.{ "png" if folder in ["rgb","depth"] else "txt"}')
|
| 92 |
+
intr=np.loadtxt(b.copy(src/'cam_intrinsics.txt'));fx,fy,cx,cy,w,h=intr
|
| 93 |
+
tensor(p/'camera/intrinsic.pt',np.array([[fx,0,cx],[0,fy,cy],[0,0,1]],np.float32))
|
| 94 |
+
ext=np.stack([np.loadtxt(src/'cam_pose'/f'{i:06d}.txt').reshape(4,4) for i in ids])
|
| 95 |
+
tensor(p/'camera/extrinsic.pt',np.linalg.inv(ext).astype(np.float32))
|
| 96 |
+
m['camera']={'model':'pinhole','width':int(w),'height':int(h),'extrinsic':'T_camera_from_world','source_extrinsic':'T_world_from_camera','unit':'m','distortion':'not supplied in selected intrinsics'}
|
| 97 |
+
a=np.stack([np.loadtxt(src/'hand_pose_mano'/f'{i:06d}.txt').reshape(2,62) for i in ids])
|
| 98 |
+
valid=a[:,:,0]==1;motion=np.concatenate([a[:,:,4:52],a[:,:,52:62],a[:,:,1:4]],axis=-1).astype(np.float32)
|
| 99 |
+
motion[~valid]=np.nan;tensor(p/'annotation/mano/motion.pt',motion);tensor(p/'annotation/mano/valid_flag.pt',valid)
|
| 100 |
+
m['mano']={'layout':['pose_axis_angle:48','betas:10','translation:3'],'shape':[N,2,61],'slots':['left','right'],'coordinate_frame':'camera','translation_unit':'m','flat_hand_mean':True,'model_version':'not supplied; MANO model not bundled','valid_flag':'source annotation flag, not visibility','geometry_validation':'not_tested; model unavailable'}
|
| 101 |
+
joints=np.stack([np.loadtxt(src/'hand_pose'/f'{i:06d}.txt').reshape(2,64) for i in ids]);tensor(p/'annotation/keypoints/xyz.pt',joints[:,:,1:].reshape(N,2,21,3).astype(np.float32));tensor(p/'annotation/keypoints/valid_flag.pt',joints[:,:,0]==1)
|
| 102 |
+
rgb=[np.asarray(Image.open(src/'rgb'/f'{i:06d}.png').convert('RGB')) for i in ids]
|
| 103 |
+
depth=[np.asarray(Image.open(src/'depth'/f'{i:06d}.png'),dtype=np.uint16) for i in ids]
|
| 104 |
+
m['rgb']=b.video(p/'observation/rgb.mkv',rgb);m['depth']={**b.video(p/'observation/depth.mkv',depth),'unit':'mm','scale_to_meters':0.001,'invalid_value':0,'rgb_registration':'not_tested'}
|
| 105 |
+
m['missing_modalities']={'object':'not present in selected historical subset','segmentation':'no native mask in selected subset'}
|
| 106 |
+
# Independent check: 3D keypoint projections must be finite where the source flags valid.
|
| 107 |
+
xyz=joints[:,:,1:].reshape(N,2,21,3);projection=xyz@np.array([[fx,0,cx],[0,fy,cy],[0,0,1]]).T
|
| 108 |
+
uv=projection[...,:2]/projection[...,2:];assert np.isfinite(uv[joints[:,:,0]==1]).all()
|
| 109 |
+
image=Image.fromarray(rgb[0]);draw=ImageDraw.Draw(image)
|
| 110 |
+
for side in range(2):
|
| 111 |
+
for u,v in uv[0,side]:draw.ellipse((u-3,v-3,u+3,v+3),fill=('red' if side==0 else 'cyan'))
|
| 112 |
+
image.save(b.out/'doc/keypoints_overlay.png')
|
| 113 |
+
return b.finish(['MANO geometry not rendered; model asset unavailable. RGB-depth registration not tested. No native segmentation or object input in subset.'])
|
| 114 |
+
|
| 115 |
+
def visor():
|
| 116 |
+
b=Build('VISOR');raw=b.base/'raw/data/GroundTruth-SparseAnnotations';jp=raw/'annotations/train/P01_03.json';zp=raw/'rgb_frames/train/P01/P01_03.zip'
|
| 117 |
+
source=load(jp);annotations=source['video_annotations'][:N]
|
| 118 |
+
ids=[x['image']['name'] for x in annotations];p,m=b.view('P01_03','ego',ids,split='train',view_type='ego',time_semantics='sparse_annotations; use source frame IDs; MKV timestamps are storage indices')
|
| 119 |
+
rgbs=[];masks=[];records=[]
|
| 120 |
+
with zipfile.ZipFile(zp) as z:
|
| 121 |
+
assert z.testzip() is None
|
| 122 |
+
for i,frame in enumerate(annotations):
|
| 123 |
+
rgb=np.asarray(Image.open(io.BytesIO(z.read(frame['image']['name']))).convert('RGB'));rgbs.append(rgb)
|
| 124 |
+
mask=np.zeros((1080,1920),np.uint16);entities=[]
|
| 125 |
+
for value,entity in enumerate(frame['annotations'],1):
|
| 126 |
+
# Same polygon rasterization primitive and integer conversion as official VISOR-VIS.
|
| 127 |
+
polygons=[np.asarray(poly,dtype=np.int32) for poly in entity['segments'] if len(poly)>=3]
|
| 128 |
+
if polygons:cv2.fillPoly(mask,polygons,int(value))
|
| 129 |
+
entities.append({'mask_value':value,'instance_id':entity['id'],'track_id':None,'source':{k:v for k,v in entity.items() if k!='segments'}})
|
| 130 |
+
if mask.shape!=rgb.shape[:2]:mask=cv2.resize(mask,(rgb.shape[1],rgb.shape[0]),interpolation=cv2.INTER_NEAREST)
|
| 131 |
+
masks.append(mask);records.append({'frame_index':i,'source_frame_id':frame['image']['name'],'subsequence':frame['image']['subsequence'],'annotation_valid':True,'instances':entities})
|
| 132 |
+
assert set(np.unique(mask)) <= {0,*[x['mask_value'] for x in entities]}
|
| 133 |
+
m['rgb']=b.video(p/'observation/rgb.mkv',rgbs);m['segmentation']={**b.video(p/'annotation/segmentation/mask.mkv',masks),'provenance':'native_sparse_polygon_rasterized','background_value':0,'background_semantics':'unlabeled/background; source is not globally exhaustive','ignore_value':None,'polygon_canvas':[1920,1080],'overlap_policy':'source annotation order; last polygon wins','track_id':'unknown; no heuristic tracking'}
|
| 134 |
+
lines(p/'annotation/segmentation/instances.jsonl',records)
|
| 135 |
+
m['missing_modalities']={'mano':'not supplied','depth':'not supplied','camera':'not supplied','object_pose_mesh':'not supplied'}
|
| 136 |
+
im=rgbs[2].copy();mask=masks[2];colors=np.array([[0,0,0],[240,70,70],[70,240,90],[70,100,240],[230,190,60],[150,80,200]],np.uint8)
|
| 137 |
+
used=mask>0;im[used]=(im[used]*0.55+colors[mask[used]%len(colors)]*0.45).astype(np.uint8)
|
| 138 |
+
Image.fromarray(im).save(b.out/'doc/segmentation_overlay.png')
|
| 139 |
+
b.checks.append({'test':'official_zip_crc_all_members','passed':True,'members':len(zipfile.ZipFile(zp).namelist())})
|
| 140 |
+
b.checks.append({'test':'all_mask_values_resolve_to_frame_instances','passed':True})
|
| 141 |
+
return b.finish([])
|
| 142 |
+
|
| 143 |
+
def rhd():
|
| 144 |
+
b=Build('RHD');src=OLD/'RHD/RHD_published_v2/evaluation';ann=read_pickle(b.copy(src/'anno_evaluation.pickle'))
|
| 145 |
+
for i in range(N):
|
| 146 |
+
p,m=b.view(f'evaluation_{i:05d}','camera',[i],split='evaluation',time_semantics='independent_image')
|
| 147 |
+
rgb=np.asarray(Image.open(b.copy(src/'color'/f'{i:05d}.png')).convert('RGB'))
|
| 148 |
+
depth=np.asarray(Image.open(b.copy(src/'depth'/f'{i:05d}.png')).convert('RGB'),dtype=np.uint16)
|
| 149 |
+
code=depth[:,:,0]*256+depth[:,:,1]
|
| 150 |
+
m['rgb']=b.video(p/'observation/rgb.mkv',[rgb]);m['depth']={**b.video(p/'observation/depth.mkv',[code]),'encoding':'source R*256+G','metric_unit':None,'metric_conversion_status':'not_tested; preserved integer code only'}
|
| 151 |
+
tensor(p/'camera/intrinsic.pt',ann[i]['K']);tensor(p/'annotation/keypoints/xyz.pt',ann[i]['xyz'].reshape(1,2,21,3));tensor(p/'annotation/keypoints/uv.pt',ann[i]['uv_vis'][:,:2].reshape(1,2,21,2));tensor(p/'annotation/keypoints/visible.pt',(ann[i]['uv_vis'][:,2]==1).reshape(1,2,21))
|
| 152 |
+
m['keypoints']={'unit':'m','layout':'source 42-joint order reshaped as 2x21','hand_order':['left','right'],'joint_order':'official RHD: wrist then thumb/index/middle/ring/pinky, fingers tip-to-palm','definition_reference':'raw/doc/dataset_README.txt','visibility':'per joint; invisible does not mean unannotated'}
|
| 153 |
+
m['missing_modalities']={'mano':'not supplied by source','segmentation':'omitted by historical downloader','extrinsic':'not supplied in selected annotations'}
|
| 154 |
+
return b.finish(['Depth metric conversion pending; segmentation absent from historical input.'])
|
| 155 |
+
|
| 156 |
+
def freihand():
|
| 157 |
+
b=Build('FreiHAND');src=OLD/'FreiHAND';K=load(b.copy(src/'training_K.json'));mano=load(b.copy(src/'training_mano.json'));scale=load(b.copy(src/'training_scale.json'))
|
| 158 |
+
for base in range(4):
|
| 159 |
+
for variant in range(4):
|
| 160 |
+
i=base+variant*32560;p,m=b.view(f'training_{base:08d}',f'variant_{variant}',[i],split='training',time_semantics='independent_image',base_sample_id=str(base),variant_id=variant)
|
| 161 |
+
m['camera_group_semantics']='image_variant_not_physical_camera';m['physical_camera_id']=None
|
| 162 |
+
rgb=np.asarray(Image.open(b.copy(src/'training/rgb'/f'{i:08d}.jpg')).convert('RGB'));m['rgb']=b.video(p/'observation/rgb.mkv',[rgb])
|
| 163 |
+
tensor(p/'camera/intrinsic.pt',np.asarray(K[base],np.float32));tensor(p/'annotation/mano/source_theta.pt',np.asarray(mano[base],np.float32));tensor(p/'annotation/mano/source_scale.pt',np.asarray(scale[base],np.float32))
|
| 164 |
+
m['mano']={'source_theta_layout':['pose48','shape10','uv_root2','scale1'],'motion_status':'not_generated','reason':'To recover MANO translation, official code subtracts posed joint 9 from backprojected root. Requires correct MANO model; last three source values are not translation.'}
|
| 165 |
+
m['missing_modalities']={'depth':'not supplied','segmentation':'not present in historical input','extrinsic':'not supplied','normalized_mano':'model dependency unresolved'}
|
| 166 |
+
return b.finish(['Preserved source MANO theta; no misleading motion.pt produced. Correct model needed for normalized translation.'])
|
| 167 |
+
|
| 168 |
+
def hoi4d():
|
| 169 |
+
b=Build('HOI4D');rel=Path('ZY20210800001/H1/C20/N18/S286/s01/T1');src=OLD/'HOI4D/Hand_pose/handpose_left_hand'/rel
|
| 170 |
+
files=sorted(src.glob('*.pickle'),key=lambda p:int(p.stem))[:N];ids=[x.stem for x in files]
|
| 171 |
+
p,m=b.view('H1_C20_N18_S286_s01_T1','ZY20210800001',ids,view_type='ego',time_semantics='annotation_frame_ids_only')
|
| 172 |
+
a=np.full((len(ids),2,61),np.nan,np.float32);v=np.zeros((len(ids),2),bool);uv=np.full((len(ids),2,21,2),np.nan,np.float32)
|
| 173 |
+
for i,frame in enumerate(ids):
|
| 174 |
+
for side,folder in enumerate(['handpose_left_hand','handpose_right_hand']):
|
| 175 |
+
f=OLD/'HOI4D/Hand_pose'/folder/rel/(frame+'.pickle')
|
| 176 |
+
if not f.exists():continue
|
| 177 |
+
x=read_pickle(b.copy(f));a[i,side]=np.concatenate([x['poseCoeff'].reshape(-1),x['beta'].reshape(-1),x['trans'].reshape(-1)]);v[i,side]=True;uv[i,side]=x['kps2D']
|
| 178 |
+
tensor(p/'annotation/mano/motion.pt',a);tensor(p/'annotation/mano/valid_flag.pt',v);tensor(p/'annotation/keypoints/uv.pt',uv)
|
| 179 |
+
tensor(p/'camera/intrinsic.pt',np.load(b.copy(OLD/'HOI4D/camera_params/ZY20210800001/intrin.npy'),allow_pickle=False))
|
| 180 |
+
m['mano']={'layout':['pose_axis_angle48','betas10','translation3'],'slots':['left','right'],'translation_unit':'m','coordinate_frame':'camera','flat_hand_mean':True,'valid_flag':'source file present and parsed; not visibility','geometry_validation':'not_tested'}
|
| 181 |
+
m['missing_modalities']={'rgb':'not downloaded','depth':'not downloaded','segmentation':'not downloaded','extrinsic':'not available in selected subset','object':'not available in selected subset'}
|
| 182 |
+
return b.finish(['Annotation-only mini; no matching RGB/depth/segmentation downloaded. MANO geometry not rendered.'])
|
| 183 |
+
|
| 184 |
+
def reinterhand():
|
| 185 |
+
b=Build('ReInterHand');src=next(p for p in sorted((OLD/'ReInterHand').glob('m--*')) if (p/'mano_fits/params').exists());files=sorted((src/'mano_fits/params').glob('*_left.json'))[:N];ids=[x.stem.rsplit('_',1)[0] for x in files]
|
| 186 |
+
# Capture-level poses have no established camera transform in current local subset.
|
| 187 |
+
p,m=b.view(src.name,'source_unresolved',ids,time_semantics='capture_annotations_only; not a camera observation')
|
| 188 |
+
rows=[]
|
| 189 |
+
for frame in ids:
|
| 190 |
+
row={'source_frame_id':frame,'hands':{}}
|
| 191 |
+
for side in ['left','right']:
|
| 192 |
+
f=src/'mano_fits/params'/f'{frame}_{side}.json'
|
| 193 |
+
if f.exists():row['hands'][side]=load(b.copy(f))
|
| 194 |
+
rows.append(row)
|
| 195 |
+
lines(p/'annotation/mano/source_parameters.jsonl',rows)
|
| 196 |
+
m['missing_modalities']={'rgb':'not extracted from incomplete archive set','camera':'not available','normalized_mano':'source-to-camera mapping unresolved'}
|
| 197 |
+
m['not_a_real_camera']=True
|
| 198 |
+
return b.finish(['Source-only annotation sample. source_unresolved is an explicit staging group, not an invented camera.'])
|
| 199 |
+
|
| 200 |
+
def main():
|
| 201 |
+
parser=argparse.ArgumentParser();parser.add_argument('--dataset',nargs='*',default=['VISOR','H2O','RHD','FreiHAND','HOI4D','ReInterHand']);args=parser.parse_args()
|
| 202 |
+
funcs={'VISOR':visor,'H2O':h2o,'RHD':rhd,'FreiHAND':freihand,'HOI4D':hoi4d,'ReInterHand':reinterhand}
|
| 203 |
+
for name in args.dataset:
|
| 204 |
+
try:funcs[name]()
|
| 205 |
+
except Exception as e:
|
| 206 |
+
save(ROOT/name/'pilot-v0/doc/build_error.json',{'error':str(e)});raise
|
| 207 |
+
if __name__=='__main__':main()
|
|
|
|
|
|
HOT3D/shared-v1.0/script/internal/preprocess_fresh_full.py
CHANGED
|
@@ -28,10 +28,10 @@ def atomic(p,value):
|
|
| 28 |
|
| 29 |
def temporary(ds):return DATA_ROOT/ds/'tmp'/JOB
|
| 30 |
|
| 31 |
-
PRODUCTION_SCRIPTS=
|
| 32 |
|
| 33 |
def code_manifest():
|
| 34 |
-
return [{'path':'script/'+f,'sha256':digest(
|
| 35 |
|
| 36 |
def verify_completed(ds,row,source):
|
| 37 |
root=DATA_ROOT/ds/RELEASE;record=temporary(ds)/'completed'/f'{row["sequence_id"]}.json';done=load(record)
|
|
@@ -80,9 +80,11 @@ def migrate_completed(ds):
|
|
| 80 |
|
| 81 |
def snapshot_scripts(ds):
|
| 82 |
root=DATA_ROOT/ds/RELEASE
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
| 86 |
|
| 87 |
def inputs(ds):
|
| 88 |
base=DATA_ROOT/ds
|
|
@@ -183,8 +185,7 @@ def approve():
|
|
| 183 |
docprod=doc/'full';docprod.mkdir(parents=True,exist_ok=True)
|
| 184 |
atomic(docprod/'plan.json',p['datasets'][ds])
|
| 185 |
(docprod/'README.md').write_text('# 全量预处理\n\n试点已获用户确认。逐序列转换、逐帧码流/像素和几何校验,完成后另建随机抽查报告。原始包保留,不自动上传。\n\n每个序列的正式自动检查在本目录sequences/;运行日志和进度只在数据集tmp。断点以输入官方摘要及全部输出文件摘要核验。\n\nHOT3D测试集未发布手物姿态真值:保留RGB、相机和物体资产,姿态及可见性缺省。ARCTIC仅保留已确认s09/laptop的曝光排除,其它序列不新增帧号屏蔽。\n',encoding='utf-8')
|
| 186 |
-
|
| 187 |
-
shutil.copyfile(WORK/'scripts'/f,root/'script'/f)
|
| 188 |
atomic(WORK/'tmp/dataset-work-state.json',state)
|
| 189 |
|
| 190 |
def official_arctic_check(row,views):
|
|
|
|
| 28 |
|
| 29 |
def temporary(ds):return DATA_ROOT/ds/'tmp'/JOB
|
| 30 |
|
| 31 |
+
PRODUCTION_SCRIPTS=sorted(p.name for p in SCRIPT.parent.glob('*.py'))
|
| 32 |
|
| 33 |
def code_manifest():
|
| 34 |
+
return [{'path':'script/internal/'+f,'sha256':digest(SCRIPT.parent/f)} for f in PRODUCTION_SCRIPTS]
|
| 35 |
|
| 36 |
def verify_completed(ds,row,source):
|
| 37 |
root=DATA_ROOT/ds/RELEASE;record=temporary(ds)/'completed'/f'{row["sequence_id"]}.json';done=load(record)
|
|
|
|
| 80 |
|
| 81 |
def snapshot_scripts(ds):
|
| 82 |
root=DATA_ROOT/ds/RELEASE
|
| 83 |
+
target=root/'script/internal';target.mkdir(parents=True,exist_ok=True)
|
| 84 |
+
for f in PRODUCTION_SCRIPTS:
|
| 85 |
+
src=SCRIPT.parent/f;dst=target/f
|
| 86 |
+
if src.resolve()!=dst.resolve():shutil.copyfile(src,dst)
|
| 87 |
+
atomic(root/'doc/validation/full/script-manifest.json',{'created_at':now(),'scope':'Current organized production implementation under script/internal; earlier manifests retain historical paths and hashes','files':code_manifest()})
|
| 88 |
|
| 89 |
def inputs(ds):
|
| 90 |
base=DATA_ROOT/ds
|
|
|
|
| 185 |
docprod=doc/'full';docprod.mkdir(parents=True,exist_ok=True)
|
| 186 |
atomic(docprod/'plan.json',p['datasets'][ds])
|
| 187 |
(docprod/'README.md').write_text('# 全量预处理\n\n试点已获用户确认。逐序列转换、逐帧码流/像素和几何校验,完成后另建随机抽查报告。原始包保留,不自动上传。\n\n每个序列的正式自动检查在本目录sequences/;运行日志和进度只在数据集tmp。断点以输入官方摘要及全部输出文件摘要核验。\n\nHOT3D测试集未发布手物姿态真值:保留RGB、相机和物体资产,姿态及可见性缺省。ARCTIC仅保留已确认s09/laptop的曝光排除,其它序列不新增帧号屏蔽。\n',encoding='utf-8')
|
| 188 |
+
snapshot_scripts(ds)
|
|
|
|
| 189 |
atomic(WORK/'tmp/dataset-work-state.json',state)
|
| 190 |
|
| 191 |
def official_arctic_check(row,views):
|
HOT3D/shared-v1.0/script/internal/render_full_sequence_review.py
CHANGED
|
@@ -1,256 +1,256 @@
|
|
| 1 |
-
"""Full-frame, all-camera diagnostic videos read from actual shared tensors/media.
|
| 2 |
-
|
| 3 |
-
Preview MP4 is explicitly display-only; warehouse MKV packets remain untouched.
|
| 4 |
-
"""
|
| 5 |
-
from fresh_sequence_common import *
|
| 6 |
-
from review_fresh_sequence_pilots import arr, validate_view, project_for_view
|
| 7 |
-
from datetime import datetime
|
| 8 |
-
import html
|
| 9 |
-
|
| 10 |
-
VIDEO_RUN='full-video-review-v2'
|
| 11 |
-
CELL=512
|
| 12 |
-
WIDTH=3*CELL
|
| 13 |
-
HEIGHT=800
|
| 14 |
-
COLORS=[(110,255,100),(255,80,210),(240,220,60),(90,180,255),(190,160,255),(255,120,140)]
|
| 15 |
-
|
| 16 |
-
def text(im,txt,xy,color=(235,235,235),size=.5):cv2.putText(im,txt,xy,cv2.FONT_HERSHEY_SIMPLEX,size,color,1,cv2.LINE_AA)
|
| 17 |
-
|
| 18 |
-
def fast_edges(im,uv,edges,color):
|
| 19 |
-
xy=uv[edges];good=np.isfinite(xy).all((1,2)) & (np.max(np.nan_to_num(np.abs(xy),nan=CELL*20),axis=(1,2))<CELL*12)
|
| 20 |
-
xy=xy[good];xy=xy[np.linalg.norm(xy[:,0]-xy[:,1],axis=1)<CELL*.7]
|
| 21 |
-
if len(xy):cv2.polylines(im,np.rint(xy).astype(np.int32),False,color,1,cv2.LINE_AA)
|
| 22 |
-
|
| 23 |
-
def dots(im,uv,color,radius=2):
|
| 24 |
-
good=np.isfinite(uv).all(1)&(uv[:,0]>=0)&(uv[:,0]<im.shape[1])&(uv[:,1]>=0)&(uv[:,1]<im.shape[0])
|
| 25 |
-
xy=np.rint(uv[good]).astype(int);xy[:,0]=np.clip(xy[:,0],0,im.shape[1]-1);xy[:,1]=np.clip(xy[:,1],0,im.shape[0]-1)
|
| 26 |
-
for d in range(max(1,radius)):
|
| 27 |
-
im[np.clip(xy[:,1]+d,0,im.shape[0]-1),xy[:,0]]=color
|
| 28 |
-
im[xy[:,1],np.clip(xy[:,0]+d,0,im.shape[1]-1)]=color
|
| 29 |
-
|
| 30 |
-
def model_vertices(motion,valid,side,fix):
|
| 31 |
-
model=Mano(['left','right'][side])
|
| 32 |
-
if side==0 and fix:
|
| 33 |
-
model.data['shapedirs'][:,0]*=-1
|
| 34 |
-
with torch.no_grad():model.layer.shapedirs[:,0]*=-1
|
| 35 |
-
verts=np.full((len(motion),778,3),np.nan,np.float32);joints=np.full((len(motion),16,3),np.nan,np.float32)
|
| 36 |
-
ids=np.flatnonzero(valid[:,side])
|
| 37 |
-
for start in range(0,len(ids),64):
|
| 38 |
-
ix=ids[start:start+64];a=motion[ix,side];verts[ix],_,joints[ix]=model.geometry(a[:,:48],a[:,48:58],a[:,58:])
|
| 39 |
-
faces=np.asarray(model.layer.faces);edges=np.unique(np.sort(np.concatenate([faces[:,[0,1]],faces[:,[1,2]],faces[:,[2,0]]]),axis=1),axis=0)
|
| 40 |
-
return verts,joints,edges
|
| 41 |
-
|
| 42 |
-
def encoder(path,fps,log,size=(WIDTH,HEIGHT)):
|
| 43 |
-
path.parent.mkdir(parents=True,exist_ok=True)
|
| 44 |
-
return subprocess.Popen([str(FF),'-v','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s',f'{size[0]}x{size[1]}','-r',str(fps),'-i','pipe:0',
|
| 45 |
-
'-an','-c:v','libx264','-preset','veryfast','-crf','19','-pix_fmt','yuv420p','-threads','2','-bf','0','-g','60','-movflags','+faststart',str(path)],stdin=subprocess.PIPE,stderr=log)
|
| 46 |
-
|
| 47 |
-
def read_exact(pipe,n):
|
| 48 |
-
chunks=[];count=0
|
| 49 |
-
while count<n:
|
| 50 |
-
b=pipe.read(n-count)
|
| 51 |
-
if not b:break
|
| 52 |
-
chunks.append(b);count+=len(b)
|
| 53 |
-
return b''.join(chunks)
|
| 54 |
-
|
| 55 |
-
def trajectory_plot(E,width=265,height=145):
|
| 56 |
-
good=np.isfinite(E).all((1,2));xyz=np.full((len(E),3),np.nan)
|
| 57 |
-
xyz[good]=-(np.swapaxes(E[good,:3,:3],1,2)@E[good,:3,3,None])[:,:,0]
|
| 58 |
-
base=np.full((height,width,3),24,np.uint8);xy=xyz[:,[0,2]];valid=np.isfinite(xy).all(1)
|
| 59 |
-
if not valid.any():return base,np.zeros((len(E),2),int),xyz
|
| 60 |
-
lo=np.nanmin(xy,0);hi=np.nanmax(xy,0);span=np.maximum(hi-lo,.05);scale=min((width-24)/span[0],(height-35)/span[1]);pix=(xy-lo)*scale+12
|
| 61 |
-
pix[:,1]=height-12-pix[:,1];pixels=np.nan_to_num(pix).astype(int)
|
| 62 |
-
for i in range(1,len(E)):
|
| 63 |
-
if valid[i-1] and valid[i]:cv2.line(base,tuple(pixels[i-1]),tuple(pixels[i]),(110,110,110),1)
|
| 64 |
-
text(base,'camera world trajectory X/Z (m)',(7,15),size=.38)
|
| 65 |
-
return base,pixels,xyz
|
| 66 |
-
|
| 67 |
-
def object_specs(p,source):
|
| 68 |
-
result=[]
|
| 69 |
-
for k,op in enumerate(sorted((p/'annotation/object').glob('*'))):
|
| 70 |
-
if not (op/'pose.pt').exists():continue
|
| 71 |
-
om=load(op/'metainfo.json');rel=op.relative_to(p);mesh=trimesh.load(p/om['mesh_ref'],process=False,force='mesh')
|
| 72 |
-
rawpose=arr(source/rel/'pose.pt');rawvalid=arr(source/rel/'pose_valid.pt');valid=arr(op/'pose_valid.pt')
|
| 73 |
-
spec={'id':om['object_id'],'name':om.get('category_name',om['object_id']),'color':COLORS[k%len(COLORS)],'P':rawpose,'rawvalid':rawvalid,'valid':valid,'op':op}
|
| 74 |
-
if 'vertex_part_ids_ref' in om:
|
| 75 |
-
xyz=np.array([[float(x) for x in r.split()[1:4]] for r in (p/om['mesh_ref']).read_text().splitlines() if r.startswith('v ')])
|
| 76 |
-
part=arr(p/om['vertex_part_ids_ref']);idx=np.arange(0,len(xyz),max(1,len(xyz)//4500))
|
| 77 |
-
spec.update(vertices=xyz[idx],parts=part[idx],top=arr(source/rel/'parts/top/pose.pt'),edges=None,
|
| 78 |
-
keypoints=arr(source/rel/'keypoints/xyz.pt'),joint=arr(source/rel/'joint_state.pt')[:,0])
|
| 79 |
-
else:
|
| 80 |
-
edges=np.asarray(mesh.edges_unique);edges=edges[::max(1,len(edges)//1100)]
|
| 81 |
-
unique,inv=np.unique(edges,return_inverse=True);spec.update(vertices=np.asarray(mesh.vertices)[unique],edges=inv.reshape(-1,2),parts=None)
|
| 82 |
-
spec['visibility']=arr(op/'visibility.pt') if (op/'visibility.pt').exists() else None
|
| 83 |
-
spec['raw_visibility']=arr(source/rel/'visibility.pt') if (source/rel/'visibility.pt').exists() else None
|
| 84 |
-
result.append(spec)
|
| 85 |
-
return result
|
| 86 |
-
|
| 87 |
-
def render_view(p,dataset,qa_data,doc=None,tmp=None,source=None,snapshot_indices=None):
|
| 88 |
-
m,frames,structural=validate_view(p);cam=m['camera_id'];T=m['num_frames'];root=DATA_ROOT/dataset/RELEASE
|
| 89 |
-
doc=doc or root/'doc/validation';tmp=tmp or DATA_ROOT/dataset/'tmp'/VIDEO_RUN;tmp.mkdir(parents=True,exist_ok=True)
|
| 90 |
-
if source is None:
|
| 91 |
-
source=p
|
| 92 |
-
for candidate in [DATA_ROOT/dataset/'tmp'/VIDEO_RUN/'diagnostic'/m['sequence_id']/cam,DATA_ROOT/dataset/'tmp'/VIDEO_RUN/'diagnostic'/cam]:
|
| 93 |
-
if (candidate/'snapshot.json').exists() and Path(load(candidate/'snapshot.json')['source_view']).resolve()==p.resolve():source=candidate;break
|
| 94 |
-
qa=np.array(qa_data[cam]['qa_pass'],bool) if dataset=='HOT3D' and qa_data and qa_data[cam].get('qa_pass') is not None else None
|
| 95 |
-
if 'mano' in m['components']:
|
| 96 |
-
motion=arr(source/'annotation/mano/motion.pt');present=arr(source/'annotation/mano/motion_valid.pt');valid=arr(p/'annotation/mano/motion_valid.pt')
|
| 97 |
-
else:motion=np.full((T,2,61),np.nan);present=np.zeros((T,2),bool);valid=present.copy()
|
| 98 |
-
visibility=arr(p/'annotation/mano/visibility.pt') if (p/'annotation/mano/visibility.pt').exists() else None
|
| 99 |
-
rawvis=arr(source/'annotation/mano/visibility.pt') if (source/'annotation/mano/visibility.pt').exists() else None
|
| 100 |
-
hands=[model_vertices(motion,present,s,m['components'].get('mano',{}).get('model_profile',{}).get('left_shapedirs_fix',False)) for s in range(2)]
|
| 101 |
-
objs=object_specs(p,source);K=arr(p/'camera/intrinsic.pt') if (p/'camera/intrinsic.pt').exists() else np.full((T,3,3),np.nan);D=arr(p/'camera/distortion.pt') if (p/'camera/distortion.pt').exists() else None;E=arr(p/'camera/extrinsic.pt') if (p/'camera/extrinsic.pt').exists() else np.full((T,4,4),np.nan)
|
| 102 |
-
W,H=m['camera']['image_size'];scale0=min(CELL/W,CELL/H);w=int(W*scale0)//2*2;h=int(H*scale0)//2*2;scale=np.array([w/W,h/H])
|
| 103 |
-
fps=m['sampling']['source_fps'] or 30;path=doc/'videos'/f'{cam}-full.mp4';logpath=tmp/f'render-{cam}.log';log=logpath.open('wb')
|
| 104 |
-
dec=subprocess.Popen([str(FF),'-v','error','-threads','2','-noautorotate','-i',str(p/'observation/rgb.mkv'),'-vf',f'scale={w}:{h}','-pix_fmt','rgb24','-fps_mode','passthrough','-f','rawvideo','pipe:1'],stdout=subprocess.PIPE,stderr=log)
|
| 105 |
-
enc=encoder(path,fps,log);traj,tp,world=trajectory_plot(E);rendered=0;exposure=[]
|
| 106 |
-
snapshots=sorted(set(snapshot_indices or [0,1,26,27,179,180,T//4,T//2,3*T//4,T-1]))
|
| 107 |
-
timeline=np.zeros((12,WIDTH,3),np.uint8)
|
| 108 |
-
for x in range(WIDTH):timeline[:,x]=(40,135,65) if qa is not None and qa[min(T-1,x*T//WIDTH)] else ((170,42,50) if qa is not None else (75,80,95))
|
| 109 |
-
for i in range(T):
|
| 110 |
-
b=read_exact(dec.stdout,w*h*3);assert len(b)==w*h*3,(cam,i,'decoder ended early')
|
| 111 |
-
original=np.frombuffer(b,np.uint8).reshape(h,w,3).copy();raw=original.copy();usable=original.copy()
|
| 112 |
-
gray=cv2.cvtColor(cv2.resize(original,(96,96)),cv2.COLOR_RGB2GRAY)
|
| 113 |
-
exposure.append({'frame_index':i,'p95_luma':float(np.percentile(gray,95)),'median_luma':float(np.median(gray))})
|
| 114 |
-
params=K[i] if m['camera']['model']=='fisheye624' else (K[i],D[i] if D is not None else None)
|
| 115 |
-
for side,(verts,joints,edges) in enumerate(hands):
|
| 116 |
-
if not present[i,side]:continue
|
| 117 |
-
uv=project_for_view(verts[i],m,params,scale);color=(0,235,255) if side==0 else (255,135,20)
|
| 118 |
-
fast_edges(raw,uv,edges,color)
|
| 119 |
-
if valid[i,side]:fast_edges(usable,uv,edges,color)
|
| 120 |
-
# White MANO joints are a diagnostic derivation, not a new keypoint component.
|
| 121 |
-
dots(raw,project_for_view(joints[i],m,params,scale),(255,255,255),2)
|
| 122 |
-
if valid[i,side]:dots(usable,project_for_view(joints[i],m,params,scale),(255,255,255),2)
|
| 123 |
-
for obj in objs:
|
| 124 |
-
if not obj['rawvalid'][i]:continue
|
| 125 |
-
P=obj['P'][i];xyz=obj['vertices']@P[:3,:3].T+P[:3,3]
|
| 126 |
-
if obj['parts'] is not None:
|
| 127 |
-
top=obj['top'][i];sel=obj['parts']==1;xyz[sel]=obj['vertices'][sel]@top[:3,:3].T+top[:3,3]
|
| 128 |
-
uv=project_for_view(xyz,m,params,scale)
|
| 129 |
-
for image,enabled in [(raw,True),(usable,obj['valid'][i])]:
|
| 130 |
-
if not enabled:continue
|
| 131 |
-
if obj['edges'] is not None:fast_edges(image,uv,obj['edges'],obj['color'])
|
| 132 |
-
else:
|
| 133 |
-
dots(image,uv[obj['parts']==0],(100,240,90));dots(image,uv[obj['parts']==1],(230,80,230))
|
| 134 |
-
dots(image,project_for_view(obj['keypoints'][i],m,params,scale),(255,255,255),3)
|
| 135 |
-
# Local object axes in metres make pose orientation visible.
|
| 136 |
-
axes=np.vstack([np.zeros(3),np.eye(3)*.045])@P[:3,:3].T+P[:3,3];auv=project_for_view(axes,m,params,scale)
|
| 137 |
-
for j,c in enumerate([(255,60,60),(60,255,60),(60,120,255)]):fast_edges(image,auv,np.array([[0,j+1]]),c)
|
| 138 |
-
canvas=np.full((HEIGHT,WIDTH,3),20,np.uint8)
|
| 139 |
-
for col,(im,label) in enumerate([(original,'SOURCE RGB'),(raw,'NATIVE LABEL DIAGNOSTIC'),(usable,'SHARED USABLE SUPERVISION')]):
|
| 140 |
-
canvas[40+(CELL-h)//2:40+(CELL-h)//2+h,col*CELL+(CELL-w)//2:col*CELL+(CELL-w)//2+w]=im
|
| 141 |
-
text(canvas,label,(col*CELL+12,25),size=.58)
|
| 142 |
-
status='NO OFFICIAL QA PROVIDED' if qa is None else ('OFFICIAL QA PASS' if qa[i] else 'OFFICIAL QA FAIL - NOT SUPERVISION')
|
| 143 |
-
if dataset=='ARCTIC' and i in m['components'].get('mano',{}).get('valid_policy',{}).get('local_excluded_frame_indices',[]):status='LOCAL REVIEW REJECT - NOT HAND SUPERVISION'
|
| 144 |
-
color=(235,195,65) if qa is None else ((80,240,110) if qa[i] else (255,90,90))
|
| 145 |
-
text(canvas,f'{dataset} {cam} index={i}/{T-1} source={frames[i]["source_frame_id"]} {status}',(12,578),color,.6)
|
| 146 |
-
text(canvas,f'MANO source L/R={int(present[i,0])}/{int(present[i,1])} shared valid L/R={int(valid[i,0])}/{int(valid[i,1])} (m/rad)',(12,603),size=.49)
|
| 147 |
-
def vals(a):return 'n/a' if a is None else ','.join('unknown' if not np.isfinite(x) else f'{100*x:.1f}%' for x in np.atleast_1d(a))
|
| 148 |
-
text(canvas,f'visibility native L/R: {vals(rawvis[i] if rawvis is not None else None)} usable: {vals(visibility[i] if visibility is not None else None)}',(12,626),size=.48)
|
| 149 |
-
text(canvas,f'camera={m["camera"]["model"]}; intrinsic '+np.array2string(K[i].ravel()[:5],precision=2),(12,649),size=.45)
|
| 150 |
-
text(canvas,'camera world position (m): '+np.array2string(world[i],precision=3),(12,672),size=.45)
|
| 151 |
-
clock=frames[i]['timestamp_ns'];text(canvas,f'timestamp_ns={clock} clock={frames[i]["clock_domain"]}',(12,695),size=.44)
|
| 152 |
-
text(canvas,f'preview FPS={fps}; '+('capture FPS unknown, playback only' if m['sampling']['source_fps'] is None else 'source capture time is stored separately'),(12,718),size=.44)
|
| 153 |
-
text(canvas,'cyan=left; orange=right; white=derived MANO joints / source object points',(12,741),size=.41)
|
| 154 |
-
text(canvas,'Projection shows hidden surfaces; it is NOT native segmentation.',(12,762),(180,180,180),.43)
|
| 155 |
-
for j,obj in enumerate(objs):
|
| 156 |
-
a=obj['raw_visibility'];v=obj['visibility'];s=f'{obj["name"]}: valid={int(obj["valid"][i])}'
|
| 157 |
-
if a is not None:s+=f' vis={vals(v[i])} (raw {vals(a[i])})'
|
| 158 |
-
if 'joint' in obj:s+=f' hinge={obj["joint"][i]:.3f}rad keypoints=32'
|
| 159 |
-
text(canvas,s,(660,603+j*24),obj['color'],.44)
|
| 160 |
-
tr=traj.copy()
|
| 161 |
-
if np.isfinite(world[i]).all():cv2.circle(tr,tuple(tp[i]),4,(255,220,70),-1)
|
| 162 |
-
canvas[610:755,WIDTH-277:WIDTH-12]=tr
|
| 163 |
-
canvas[-12:]=timeline;cursor=min(WIDTH-1,int(i*WIDTH/T));canvas[-12:,cursor:cursor+2]=255
|
| 164 |
-
enc.stdin.write(canvas.tobytes());rendered+=1
|
| 165 |
-
if i in snapshots:
|
| 166 |
-
snap=doc/'video_snapshots'/cam;snap.mkdir(parents=True,exist_ok=True);Image.fromarray(canvas).save(snap/f'{i:06d}.jpg',quality=92)
|
| 167 |
-
if i%200==0:print('VIDEO_FRAME',dataset,cam,i,T,flush=True)
|
| 168 |
-
assert not dec.stdout.read(1),'extra source frames';dec.stdout.close();assert dec.wait()==0
|
| 169 |
-
enc.stdin.close();assert enc.wait()==0;log.close();assert rendered==T
|
| 170 |
-
packets=framehash(['-i',str(path)],copy=True);assert len(packets)==T
|
| 171 |
-
result={'sequence_id':m['sequence_id'],'camera_id':cam,'frames':T,'rendered_frames':rendered,'video_ref':path.relative_to(doc).as_posix(),'video_sha256':digest(path),'preview_fps':fps,
|
| 172 |
-
'preview_is_training_data':False,'preview_encoding':'H264 CRF19, scaled, display only; shared original MKV unchanged',
|
| 173 |
-
'source_labels_from':'raw-derived diagnostic cache' if source!=p else 'shared unfiltered source-compatible labels',
|
| 174 |
-
'all_source_and_shared_valid_masks_used':True,'structure_checks':structural,'mano_valid_counts':valid.sum(0).tolist(),
|
| 175 |
-
'official_qa_pass_frames':int(qa.sum()) if qa is not None else None,'official_qa_fail_frames':int((~qa).sum()) if qa is not None else None,
|
| 176 |
-
'exposure_diagnostics':{'method':'scaled shared decoded RGB to 96x96 gray; p95<35 flags a candidate only, does not modify valid','suspect_dark_frame_indices':[x['frame_index'] for x in exposure if x['p95_luma']<35]}}
|
| 177 |
-
save(tmp/f'{cam}-exposure.json',exposure)
|
| 178 |
-
save(tmp/f'{cam}-video-result.json',result);print('VIDEO_COMPLETE',dataset,cam,T,flush=True)
|
| 179 |
-
return result
|
| 180 |
-
|
| 181 |
-
def asset_preview(op,out):
|
| 182 |
-
"""Textured point-splat turntable plus the source texture; diagnostic, not photoreal rendering."""
|
| 183 |
-
p=op.parents[2];m=load(op/'metainfo.json');meshpath=p/m['mesh_ref']
|
| 184 |
-
if (op/'assets/mesh_tex.obj').exists():meshpath=op/'assets/mesh_tex.obj'
|
| 185 |
-
mesh=trimesh.load(meshpath,process=False,force='mesh');xyz=np.asarray(mesh.vertices);idx=np.arange(0,len(xyz),max(1,len(xyz)//35000));xyz=xyz[idx]
|
| 186 |
-
texture=getattr(mesh.visual.material,'image',None) if hasattr(mesh.visual,'material') else None
|
| 187 |
-
texture_source=None
|
| 188 |
-
if meshpath.name=='mesh_tex.obj' and op.relative_to(DATA_ROOT).parts[0]=='ARCTIC':
|
| 189 |
-
# The loader can silently return a 2x2 default material. Resolve the
|
| 190 |
-
# official single-texture MTL explicitly instead of accepting that placeholder.
|
| 191 |
-
mtl=[r.split(maxsplit=1)[1] for r in meshpath.read_text().splitlines() if r.startswith('mtllib ')]
|
| 192 |
-
diffuse=[]
|
| 193 |
-
for name in mtl:
|
| 194 |
-
material=meshpath.parent/name
|
| 195 |
-
diffuse.extend(material.parent/r.split(maxsplit=1)[1] for r in material.read_text().splitlines() if r.startswith('map_Kd '))
|
| 196 |
-
diffuse=list(set(diffuse));assert len(diffuse)==1,(meshpath,diffuse)
|
| 197 |
-
assert diffuse[0].resolve().is_relative_to(meshpath.parent.resolve())
|
| 198 |
-
texture=Image.open(diffuse[0]).convert('RGB');assert min(texture.size)>2
|
| 199 |
-
texture_source={'file':diffuse[0].relative_to(p).as_posix(),'sha256':digest(diffuse[0]),'size':list(texture.size),'resolution_method':'explicit official MTL map_Kd; reject loader placeholder'}
|
| 200 |
-
if texture is not None and getattr(mesh.visual,'uv',None) is not None:
|
| 201 |
-
tex=np.asarray(texture.convert('RGB'));uv=np.asarray(mesh.visual.uv)[idx]
|
| 202 |
-
rgb=tex[np.clip(np.rint((1-uv[:,1])*(len(tex)-1)).astype(int),0,len(tex)-1),np.clip(np.rint(uv[:,0]*(tex.shape[1]-1)).astype(int),0,tex.shape[1]-1)]
|
| 203 |
-
else:rgb=np.broadcast_to([150,210,245],xyz.shape).astype(np.uint8)
|
| 204 |
-
extent=np.ptp(xyz,axis=0);xyz=xyz-(xyz.min(0)+xyz.max(0))/2;scale=300/max(np.linalg.norm(extent),.001)
|
| 205 |
-
logpath=DATA_ROOT/op.relative_to(DATA_ROOT).parts[0]/'tmp'/VIDEO_RUN/'assets.log'
|
| 206 |
-
logpath.parent.mkdir(parents=True,exist_ok=True)
|
| 207 |
-
out.parent.mkdir(parents=True,exist_ok=True)
|
| 208 |
-
with logpath.open('ab') as log:
|
| 209 |
-
enc=encoder(out,12,log,size=(800,480))
|
| 210 |
-
for i in range(72):
|
| 211 |
-
image=np.full((480,800,3),24,np.uint8);R=Rotation.from_euler('xy',[.35,i*2*np.pi/72]).as_matrix();v=xyz@R.T
|
| 212 |
-
order=np.argsort(v[:,2]);xy=np.rint(v[:,:2]*scale+[220,220]).astype(int)
|
| 213 |
-
good=(xy[:,0]>=0)&(xy[:,0]<430)&(xy[:,1]>=35)&(xy[:,1]<400);order=order[good[order]]
|
| 214 |
-
for dx,dy in [(0,0),(1,0),(0,1)]:image[np.clip(xy[order,1]+dy,0,479),np.clip(xy[order,0]+dx,0,429)]=rgb[order]
|
| 215 |
-
if texture is not None:
|
| 216 |
-
thumb=texture.convert('RGB');thumb.thumbnail((350,345));image[40:40+thumb.height,440:440+thumb.width]=np.asarray(thumb)
|
| 217 |
-
text(image,m.get('category_name',m['object_id']),(12,25),size=.65)
|
| 218 |
-
text(image,'TEXTURED 3D POINT PREVIEW',(12,420),size=.55);text(image,'SOURCE MATERIAL TEXTURE',(445,420),size=.5)
|
| 219 |
-
text(image,'OBJ extent (m): '+np.array2string(extent,precision=4),(12,450),size=.5);enc.stdin.write(image.tobytes())
|
| 220 |
-
enc.stdin.close();assert enc.wait()==0
|
| 221 |
-
assert len(framehash(['-i',str(out)],copy=True))==72
|
| 222 |
-
return {'object_id':m['object_id'],'video_ref':'assets/'+out.name,'frames':72,'texture_present':texture is not None,'texture_source':texture_source,'extent_m':extent.tolist(),'method':'diagnostic textured point turntable, not photoreal material rendering'}
|
| 223 |
-
|
| 224 |
-
def publish_review(dataset,results,assets):
|
| 225 |
-
root=DATA_ROOT/dataset/RELEASE;doc=root/'doc/validation'
|
| 226 |
-
scope=[('RGB','全部帧原图与逐帧码流/像素校验'),('相机内参/畸变','投影使用声明模型和全部参数;HUD显示相机模型'),('相机外参','全帧姿态、米制相机位置与世界XZ轨迹'),('MANO','逐帧网格线框、派生关节点、左右手valid'),('物体姿态/几何','逐帧轮廓、局部XYZ轴、物体ID'),('材质/纹理','每个物体的原纹理与完整旋转预览')]
|
| 227 |
-
scope+=([('部件/关节','底座/顶盖分别着色,逐帧关节角'),('物体关键点','源32个物体点逐帧叠加'),('visibility','原数据未提供,明确缺省')] if dataset=='ARCTIC' else [('visibility','原值0–1已修正,原生/可用比例同时显示'),('官方QA','完整红绿时间带;QA失败帧保留诊断、停用监督'),('部件/关节、独立物体关键点','本序列无该源模态,不虚构')])
|
| 228 |
-
scope+=[('深度/像素分割/接触','本次raw范围未提供,不以投影或帧筛选CSV冒充')]
|
| 229 |
-
table=''.join(f'<tr><td>{a}</td><td>{b}</td></tr>' for a,b in scope)
|
| 230 |
-
cards=''.join(f'<section><h2>Camera {r["camera_id"]} · {r["frames"]} 帧 · 有效MANO左右 {r["mano_valid_counts"]}</h2><video controls preload="metadata" src="{r["video_ref"]}"></video><p>全部{r["rendered_frames"]}帧已渲染,无码帧跳过。官方QA通过/未通过:{r["official_qa_pass_frames"]}/{r["official_qa_fail_frames"]}(null表示来源无此QA)。</p></section>' for r in results)
|
| 231 |
-
gallery=''.join(f'<section><h3>物体 {a["object_id"]}</h3><video controls loop preload="metadata" src="{a["video_ref"]}"></video><p>纹理点云旋转预览及原始材质图;此预览不证明完整PBR渲染等价。</p></section>' for a in assets)
|
| 232 |
-
known=('已修正转换器颠倒顶盖/底座编码的错误:原parts.json的0是顶盖、1是底座,共享层重新映射为0底座/1顶盖。9路相机前两帧均为源欠曝图,已排除对应几何监督;camera 6 index 270的手部偏移作为已知问题记录,按用户要求撤销单帧屏蔽,恢复原标注和valid。整套试点仍待验收。中栏显示源参数诊断,右栏按当前valid绘制。详见 <a href="ARCTIC_FINDINGS.md">问题与修复证据</a>、<a href="diagnosis/camera6-270-before-after.jpg">修复前后对照</a>
|
| 233 |
-
page=f'''<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{dataset} 完整视频审核 v2</title><style>body{{font:16px/1.7 system-ui;background:#edf1f7;color:#172136;max-width:1550px;margin:25px auto;padding:0 20px}}header,section{{background:white;padding:22px;border-radius:12px;margin-bottom:20px}}video{{width:100%;background:#151515}}h1{{margin:0}}.warn{{color:#a71d2b;font-weight:bold}}table{{border-collapse:collapse;width:100%}}td,th{{border:1px solid #ccd4df;padding:8px;text-align:left}}.assets{{display:grid;grid-template-columns:repeat(auto-fit,minmax(500px,1fr));gap:18px}}a{{color:#1567a3}}</style><header><h1>{dataset} · 完整序列审核 v2</h1><p class="warn">人工确认待完成。旧“抽帧投影通过”结论撤回,本页替代旧报告;尚未全量或发布。</p><p>视频三栏:原图 | 原始标注诊断 | 共享层有效监督。所有相机、所有帧都已渲染;青=左手,橙=右手,其他色=物体/部件,白点=MANO派生关节点或源物体关键点。投影不做遮挡剔除,也不是分割真值。</p><p>{known}</p><p>标注 valid=实际标注存在且数值合法,并通过适用官方QA及已明确登记的本地排除规则;可见性不代替valid,剩余帧不因此自动认定人工通过。诊断中被排除的参数不进入有效监督,raw保留。MP4经过缩放与展示编码,仅为doc预览,训练输入仍是无新增损失的shared MKV。</p><p><a href="REPORT.md">正式说明</a> · <a href="report.json">逐相机检查结果</a> · <a href="../RAW_TO_SHARED.md">字段映射</a> · <a href="../CONTRACT.md">更新后的valid定义</a></p><h2>逐模态检查覆盖</h2><table><tr><th>模态</th><th>检查/可视化方式</th></tr>{table}</table></header>{cards}<h2>物体资产检查</h2><div class="assets">{gallery}</div><script>document.querySelectorAll('video').forEach(v=>v.addEventListener('play',()=>document.querySelectorAll('video').forEach(o=>{{if(o!==v)o.pause()}})));</script></html>'''
|
| 234 |
-
(doc/'index.html').write_text(page,encoding='utf-8')
|
| 235 |
-
old=load(doc/'report.json');old.update(stage='full_video_review_awaiting_human',human_review='pending',review_revision='full-video-v2',
|
| 236 |
-
old_sample_projection_conclusion='withdrawn',full_video_views=results,asset_previews=assets,modality_coverage=[{'modality':a,'check':b} for a,b in scope],known_issues=known,
|
| 237 |
-
agent_visual_inspection={'status':'pending_new_full_video_review','not_equivalent_to_user_approval':True},created_at=datetime.now().astimezone().isoformat())
|
| 238 |
-
old.pop('views',None);old.pop('offline_artifact_check',None);save(doc/'report.json',old)
|
| 239 |
-
save(doc/'status.json',{'stage':'full_video_review_awaiting_human','human_review':'pending','full_preprocessing_authorized':False,'upload_authorized':False})
|
| 240 |
-
rows='\n'.join(f'| {r["camera_id"]} | {r["frames"]} | {r["rendered_frames"]} | {r["mano_valid_counts"]} | {r["official_qa_pass_frames"]} |' for r in results)
|
| 241 |
-
(doc/'REPORT.md').write_text(f'# {dataset} 完整序列审核 v2\n\n[离线完整视频](index.html) · [机器结果](report.json)\n\n人工确认待完成;旧抽帧投影通过结论撤回。{known}\n\n|相机|源帧数|渲染帧数|左右手有效标注帧数|官方QA通过帧数|\n|---|---:|---:|---|---:|\n{rows}\n\n## 逐模态覆盖\n\n'+''.join(f'- {a}:{b}。\n' for a,b in scope)+'\n完整视频表示每帧已渲染,并不等于每帧人工审核通过。被官方QA排除的源标注仅在诊断栏显示;不挪帧、不隐藏原始异常。所有有效性筛选、可见性与图像编码验收分开记录。源标注质量问题无法通过格式转换修好;通过valid屏蔽,并保留raw溯源。\n',encoding='utf-8')
|
| 242 |
-
for f in ['CONTRACT.md','schema.json']:shutil.copyfile(WORK/'distribution/hand-warehouse-1.0'/f,root/'doc'/f)
|
| 243 |
-
|
| 244 |
-
print('FULL_VIDEO_REVIEW_READY',dataset,flush=True)
|
| 245 |
-
|
| 246 |
-
if __name__=='__main__':
|
| 247 |
-
ap=argparse.ArgumentParser();ap.add_argument('dataset',choices=['HOT3D','ARCTIC']);a=ap.parse_args();torch.set_num_threads(3)
|
| 248 |
-
root=DATA_ROOT/a.dataset/RELEASE;qa=load(root/'doc/validation/source_qa.json') if a.dataset=='HOT3D' else None
|
| 249 |
-
# This entry point owns the original single-sequence report. Other review
|
| 250 |
-
# sequences have their own output directories in arctic_object_review.py.
|
| 251 |
-
sequence={'ARCTIC':'s09_laptop_use_03','HOT3D':'P0015_179e1b84'}[a.dataset]
|
| 252 |
-
views=sorted(p.parent for p in (root/'data'/sequence).glob('*/metainfo.json'));results=[]
|
| 253 |
-
for p in views:results.append(render_view(p,a.dataset,qa))
|
| 254 |
-
assets=[]
|
| 255 |
-
for op in sorted((views[0]/'annotation/object').iterdir()):assets.append(asset_preview(op,root/'doc/validation/assets'/f'{op.name}.mp4'))
|
| 256 |
-
publish_review(a.dataset,results,assets)
|
|
|
|
| 1 |
+
"""Full-frame, all-camera diagnostic videos read from actual shared tensors/media.
|
| 2 |
+
|
| 3 |
+
Preview MP4 is explicitly display-only; warehouse MKV packets remain untouched.
|
| 4 |
+
"""
|
| 5 |
+
from fresh_sequence_common import *
|
| 6 |
+
from review_fresh_sequence_pilots import arr, validate_view, project_for_view
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
import html
|
| 9 |
+
|
| 10 |
+
VIDEO_RUN='full-video-review-v2'
|
| 11 |
+
CELL=512
|
| 12 |
+
WIDTH=3*CELL
|
| 13 |
+
HEIGHT=800
|
| 14 |
+
COLORS=[(110,255,100),(255,80,210),(240,220,60),(90,180,255),(190,160,255),(255,120,140)]
|
| 15 |
+
|
| 16 |
+
def text(im,txt,xy,color=(235,235,235),size=.5):cv2.putText(im,txt,xy,cv2.FONT_HERSHEY_SIMPLEX,size,color,1,cv2.LINE_AA)
|
| 17 |
+
|
| 18 |
+
def fast_edges(im,uv,edges,color):
|
| 19 |
+
xy=uv[edges];good=np.isfinite(xy).all((1,2)) & (np.max(np.nan_to_num(np.abs(xy),nan=CELL*20),axis=(1,2))<CELL*12)
|
| 20 |
+
xy=xy[good];xy=xy[np.linalg.norm(xy[:,0]-xy[:,1],axis=1)<CELL*.7]
|
| 21 |
+
if len(xy):cv2.polylines(im,np.rint(xy).astype(np.int32),False,color,1,cv2.LINE_AA)
|
| 22 |
+
|
| 23 |
+
def dots(im,uv,color,radius=2):
|
| 24 |
+
good=np.isfinite(uv).all(1)&(uv[:,0]>=0)&(uv[:,0]<im.shape[1])&(uv[:,1]>=0)&(uv[:,1]<im.shape[0])
|
| 25 |
+
xy=np.rint(uv[good]).astype(int);xy[:,0]=np.clip(xy[:,0],0,im.shape[1]-1);xy[:,1]=np.clip(xy[:,1],0,im.shape[0]-1)
|
| 26 |
+
for d in range(max(1,radius)):
|
| 27 |
+
im[np.clip(xy[:,1]+d,0,im.shape[0]-1),xy[:,0]]=color
|
| 28 |
+
im[xy[:,1],np.clip(xy[:,0]+d,0,im.shape[1]-1)]=color
|
| 29 |
+
|
| 30 |
+
def model_vertices(motion,valid,side,fix):
|
| 31 |
+
model=Mano(['left','right'][side])
|
| 32 |
+
if side==0 and fix:
|
| 33 |
+
model.data['shapedirs'][:,0]*=-1
|
| 34 |
+
with torch.no_grad():model.layer.shapedirs[:,0]*=-1
|
| 35 |
+
verts=np.full((len(motion),778,3),np.nan,np.float32);joints=np.full((len(motion),16,3),np.nan,np.float32)
|
| 36 |
+
ids=np.flatnonzero(valid[:,side])
|
| 37 |
+
for start in range(0,len(ids),64):
|
| 38 |
+
ix=ids[start:start+64];a=motion[ix,side];verts[ix],_,joints[ix]=model.geometry(a[:,:48],a[:,48:58],a[:,58:])
|
| 39 |
+
faces=np.asarray(model.layer.faces);edges=np.unique(np.sort(np.concatenate([faces[:,[0,1]],faces[:,[1,2]],faces[:,[2,0]]]),axis=1),axis=0)
|
| 40 |
+
return verts,joints,edges
|
| 41 |
+
|
| 42 |
+
def encoder(path,fps,log,size=(WIDTH,HEIGHT)):
|
| 43 |
+
path.parent.mkdir(parents=True,exist_ok=True)
|
| 44 |
+
return subprocess.Popen([str(FF),'-v','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s',f'{size[0]}x{size[1]}','-r',str(fps),'-i','pipe:0',
|
| 45 |
+
'-an','-c:v','libx264','-preset','veryfast','-crf','19','-pix_fmt','yuv420p','-threads','2','-bf','0','-g','60','-movflags','+faststart',str(path)],stdin=subprocess.PIPE,stderr=log)
|
| 46 |
+
|
| 47 |
+
def read_exact(pipe,n):
|
| 48 |
+
chunks=[];count=0
|
| 49 |
+
while count<n:
|
| 50 |
+
b=pipe.read(n-count)
|
| 51 |
+
if not b:break
|
| 52 |
+
chunks.append(b);count+=len(b)
|
| 53 |
+
return b''.join(chunks)
|
| 54 |
+
|
| 55 |
+
def trajectory_plot(E,width=265,height=145):
|
| 56 |
+
good=np.isfinite(E).all((1,2));xyz=np.full((len(E),3),np.nan)
|
| 57 |
+
xyz[good]=-(np.swapaxes(E[good,:3,:3],1,2)@E[good,:3,3,None])[:,:,0]
|
| 58 |
+
base=np.full((height,width,3),24,np.uint8);xy=xyz[:,[0,2]];valid=np.isfinite(xy).all(1)
|
| 59 |
+
if not valid.any():return base,np.zeros((len(E),2),int),xyz
|
| 60 |
+
lo=np.nanmin(xy,0);hi=np.nanmax(xy,0);span=np.maximum(hi-lo,.05);scale=min((width-24)/span[0],(height-35)/span[1]);pix=(xy-lo)*scale+12
|
| 61 |
+
pix[:,1]=height-12-pix[:,1];pixels=np.nan_to_num(pix).astype(int)
|
| 62 |
+
for i in range(1,len(E)):
|
| 63 |
+
if valid[i-1] and valid[i]:cv2.line(base,tuple(pixels[i-1]),tuple(pixels[i]),(110,110,110),1)
|
| 64 |
+
text(base,'camera world trajectory X/Z (m)',(7,15),size=.38)
|
| 65 |
+
return base,pixels,xyz
|
| 66 |
+
|
| 67 |
+
def object_specs(p,source):
|
| 68 |
+
result=[]
|
| 69 |
+
for k,op in enumerate(sorted((p/'annotation/object').glob('*'))):
|
| 70 |
+
if not (op/'pose.pt').exists():continue
|
| 71 |
+
om=load(op/'metainfo.json');rel=op.relative_to(p);mesh=trimesh.load(p/om['mesh_ref'],process=False,force='mesh')
|
| 72 |
+
rawpose=arr(source/rel/'pose.pt');rawvalid=arr(source/rel/'pose_valid.pt');valid=arr(op/'pose_valid.pt')
|
| 73 |
+
spec={'id':om['object_id'],'name':om.get('category_name',om['object_id']),'color':COLORS[k%len(COLORS)],'P':rawpose,'rawvalid':rawvalid,'valid':valid,'op':op}
|
| 74 |
+
if 'vertex_part_ids_ref' in om:
|
| 75 |
+
xyz=np.array([[float(x) for x in r.split()[1:4]] for r in (p/om['mesh_ref']).read_text().splitlines() if r.startswith('v ')])
|
| 76 |
+
part=arr(p/om['vertex_part_ids_ref']);idx=np.arange(0,len(xyz),max(1,len(xyz)//4500))
|
| 77 |
+
spec.update(vertices=xyz[idx],parts=part[idx],top=arr(source/rel/'parts/top/pose.pt'),edges=None,
|
| 78 |
+
keypoints=arr(source/rel/'keypoints/xyz.pt'),joint=arr(source/rel/'joint_state.pt')[:,0])
|
| 79 |
+
else:
|
| 80 |
+
edges=np.asarray(mesh.edges_unique);edges=edges[::max(1,len(edges)//1100)]
|
| 81 |
+
unique,inv=np.unique(edges,return_inverse=True);spec.update(vertices=np.asarray(mesh.vertices)[unique],edges=inv.reshape(-1,2),parts=None)
|
| 82 |
+
spec['visibility']=arr(op/'visibility.pt') if (op/'visibility.pt').exists() else None
|
| 83 |
+
spec['raw_visibility']=arr(source/rel/'visibility.pt') if (source/rel/'visibility.pt').exists() else None
|
| 84 |
+
result.append(spec)
|
| 85 |
+
return result
|
| 86 |
+
|
| 87 |
+
def render_view(p,dataset,qa_data,doc=None,tmp=None,source=None,snapshot_indices=None):
|
| 88 |
+
m,frames,structural=validate_view(p);cam=m['camera_id'];T=m['num_frames'];root=DATA_ROOT/dataset/RELEASE
|
| 89 |
+
doc=doc or root/'doc/validation';tmp=tmp or DATA_ROOT/dataset/'tmp'/VIDEO_RUN;tmp.mkdir(parents=True,exist_ok=True)
|
| 90 |
+
if source is None:
|
| 91 |
+
source=p
|
| 92 |
+
for candidate in [DATA_ROOT/dataset/'tmp'/VIDEO_RUN/'diagnostic'/m['sequence_id']/cam,DATA_ROOT/dataset/'tmp'/VIDEO_RUN/'diagnostic'/cam]:
|
| 93 |
+
if (candidate/'snapshot.json').exists() and Path(load(candidate/'snapshot.json')['source_view']).resolve()==p.resolve():source=candidate;break
|
| 94 |
+
qa=np.array(qa_data[cam]['qa_pass'],bool) if dataset=='HOT3D' and qa_data and qa_data[cam].get('qa_pass') is not None else None
|
| 95 |
+
if 'mano' in m['components']:
|
| 96 |
+
motion=arr(source/'annotation/mano/motion.pt');present=arr(source/'annotation/mano/motion_valid.pt');valid=arr(p/'annotation/mano/motion_valid.pt')
|
| 97 |
+
else:motion=np.full((T,2,61),np.nan);present=np.zeros((T,2),bool);valid=present.copy()
|
| 98 |
+
visibility=arr(p/'annotation/mano/visibility.pt') if (p/'annotation/mano/visibility.pt').exists() else None
|
| 99 |
+
rawvis=arr(source/'annotation/mano/visibility.pt') if (source/'annotation/mano/visibility.pt').exists() else None
|
| 100 |
+
hands=[model_vertices(motion,present,s,m['components'].get('mano',{}).get('model_profile',{}).get('left_shapedirs_fix',False)) for s in range(2)]
|
| 101 |
+
objs=object_specs(p,source);K=arr(p/'camera/intrinsic.pt') if (p/'camera/intrinsic.pt').exists() else np.full((T,3,3),np.nan);D=arr(p/'camera/distortion.pt') if (p/'camera/distortion.pt').exists() else None;E=arr(p/'camera/extrinsic.pt') if (p/'camera/extrinsic.pt').exists() else np.full((T,4,4),np.nan)
|
| 102 |
+
W,H=m['camera']['image_size'];scale0=min(CELL/W,CELL/H);w=int(W*scale0)//2*2;h=int(H*scale0)//2*2;scale=np.array([w/W,h/H])
|
| 103 |
+
fps=m['sampling']['source_fps'] or 30;path=doc/'videos'/f'{cam}-full.mp4';logpath=tmp/f'render-{cam}.log';log=logpath.open('wb')
|
| 104 |
+
dec=subprocess.Popen([str(FF),'-v','error','-threads','2','-noautorotate','-i',str(p/'observation/rgb.mkv'),'-vf',f'scale={w}:{h}','-pix_fmt','rgb24','-fps_mode','passthrough','-f','rawvideo','pipe:1'],stdout=subprocess.PIPE,stderr=log)
|
| 105 |
+
enc=encoder(path,fps,log);traj,tp,world=trajectory_plot(E);rendered=0;exposure=[]
|
| 106 |
+
snapshots=sorted(set(snapshot_indices or [0,1,26,27,179,180,T//4,T//2,3*T//4,T-1]))
|
| 107 |
+
timeline=np.zeros((12,WIDTH,3),np.uint8)
|
| 108 |
+
for x in range(WIDTH):timeline[:,x]=(40,135,65) if qa is not None and qa[min(T-1,x*T//WIDTH)] else ((170,42,50) if qa is not None else (75,80,95))
|
| 109 |
+
for i in range(T):
|
| 110 |
+
b=read_exact(dec.stdout,w*h*3);assert len(b)==w*h*3,(cam,i,'decoder ended early')
|
| 111 |
+
original=np.frombuffer(b,np.uint8).reshape(h,w,3).copy();raw=original.copy();usable=original.copy()
|
| 112 |
+
gray=cv2.cvtColor(cv2.resize(original,(96,96)),cv2.COLOR_RGB2GRAY)
|
| 113 |
+
exposure.append({'frame_index':i,'p95_luma':float(np.percentile(gray,95)),'median_luma':float(np.median(gray))})
|
| 114 |
+
params=K[i] if m['camera']['model']=='fisheye624' else (K[i],D[i] if D is not None else None)
|
| 115 |
+
for side,(verts,joints,edges) in enumerate(hands):
|
| 116 |
+
if not present[i,side]:continue
|
| 117 |
+
uv=project_for_view(verts[i],m,params,scale);color=(0,235,255) if side==0 else (255,135,20)
|
| 118 |
+
fast_edges(raw,uv,edges,color)
|
| 119 |
+
if valid[i,side]:fast_edges(usable,uv,edges,color)
|
| 120 |
+
# White MANO joints are a diagnostic derivation, not a new keypoint component.
|
| 121 |
+
dots(raw,project_for_view(joints[i],m,params,scale),(255,255,255),2)
|
| 122 |
+
if valid[i,side]:dots(usable,project_for_view(joints[i],m,params,scale),(255,255,255),2)
|
| 123 |
+
for obj in objs:
|
| 124 |
+
if not obj['rawvalid'][i]:continue
|
| 125 |
+
P=obj['P'][i];xyz=obj['vertices']@P[:3,:3].T+P[:3,3]
|
| 126 |
+
if obj['parts'] is not None:
|
| 127 |
+
top=obj['top'][i];sel=obj['parts']==1;xyz[sel]=obj['vertices'][sel]@top[:3,:3].T+top[:3,3]
|
| 128 |
+
uv=project_for_view(xyz,m,params,scale)
|
| 129 |
+
for image,enabled in [(raw,True),(usable,obj['valid'][i])]:
|
| 130 |
+
if not enabled:continue
|
| 131 |
+
if obj['edges'] is not None:fast_edges(image,uv,obj['edges'],obj['color'])
|
| 132 |
+
else:
|
| 133 |
+
dots(image,uv[obj['parts']==0],(100,240,90));dots(image,uv[obj['parts']==1],(230,80,230))
|
| 134 |
+
dots(image,project_for_view(obj['keypoints'][i],m,params,scale),(255,255,255),3)
|
| 135 |
+
# Local object axes in metres make pose orientation visible.
|
| 136 |
+
axes=np.vstack([np.zeros(3),np.eye(3)*.045])@P[:3,:3].T+P[:3,3];auv=project_for_view(axes,m,params,scale)
|
| 137 |
+
for j,c in enumerate([(255,60,60),(60,255,60),(60,120,255)]):fast_edges(image,auv,np.array([[0,j+1]]),c)
|
| 138 |
+
canvas=np.full((HEIGHT,WIDTH,3),20,np.uint8)
|
| 139 |
+
for col,(im,label) in enumerate([(original,'SOURCE RGB'),(raw,'NATIVE LABEL DIAGNOSTIC'),(usable,'SHARED USABLE SUPERVISION')]):
|
| 140 |
+
canvas[40+(CELL-h)//2:40+(CELL-h)//2+h,col*CELL+(CELL-w)//2:col*CELL+(CELL-w)//2+w]=im
|
| 141 |
+
text(canvas,label,(col*CELL+12,25),size=.58)
|
| 142 |
+
status='NO OFFICIAL QA PROVIDED' if qa is None else ('OFFICIAL QA PASS' if qa[i] else 'OFFICIAL QA FAIL - NOT SUPERVISION')
|
| 143 |
+
if dataset=='ARCTIC' and i in m['components'].get('mano',{}).get('valid_policy',{}).get('local_excluded_frame_indices',[]):status='LOCAL REVIEW REJECT - NOT HAND SUPERVISION'
|
| 144 |
+
color=(235,195,65) if qa is None else ((80,240,110) if qa[i] else (255,90,90))
|
| 145 |
+
text(canvas,f'{dataset} {cam} index={i}/{T-1} source={frames[i]["source_frame_id"]} {status}',(12,578),color,.6)
|
| 146 |
+
text(canvas,f'MANO source L/R={int(present[i,0])}/{int(present[i,1])} shared valid L/R={int(valid[i,0])}/{int(valid[i,1])} (m/rad)',(12,603),size=.49)
|
| 147 |
+
def vals(a):return 'n/a' if a is None else ','.join('unknown' if not np.isfinite(x) else f'{100*x:.1f}%' for x in np.atleast_1d(a))
|
| 148 |
+
text(canvas,f'visibility native L/R: {vals(rawvis[i] if rawvis is not None else None)} usable: {vals(visibility[i] if visibility is not None else None)}',(12,626),size=.48)
|
| 149 |
+
text(canvas,f'camera={m["camera"]["model"]}; intrinsic '+np.array2string(K[i].ravel()[:5],precision=2),(12,649),size=.45)
|
| 150 |
+
text(canvas,'camera world position (m): '+np.array2string(world[i],precision=3),(12,672),size=.45)
|
| 151 |
+
clock=frames[i]['timestamp_ns'];text(canvas,f'timestamp_ns={clock} clock={frames[i]["clock_domain"]}',(12,695),size=.44)
|
| 152 |
+
text(canvas,f'preview FPS={fps}; '+('capture FPS unknown, playback only' if m['sampling']['source_fps'] is None else 'source capture time is stored separately'),(12,718),size=.44)
|
| 153 |
+
text(canvas,'cyan=left; orange=right; white=derived MANO joints / source object points',(12,741),size=.41)
|
| 154 |
+
text(canvas,'Projection shows hidden surfaces; it is NOT native segmentation.',(12,762),(180,180,180),.43)
|
| 155 |
+
for j,obj in enumerate(objs):
|
| 156 |
+
a=obj['raw_visibility'];v=obj['visibility'];s=f'{obj["name"]}: valid={int(obj["valid"][i])}'
|
| 157 |
+
if a is not None:s+=f' vis={vals(v[i])} (raw {vals(a[i])})'
|
| 158 |
+
if 'joint' in obj:s+=f' hinge={obj["joint"][i]:.3f}rad keypoints=32'
|
| 159 |
+
text(canvas,s,(660,603+j*24),obj['color'],.44)
|
| 160 |
+
tr=traj.copy()
|
| 161 |
+
if np.isfinite(world[i]).all():cv2.circle(tr,tuple(tp[i]),4,(255,220,70),-1)
|
| 162 |
+
canvas[610:755,WIDTH-277:WIDTH-12]=tr
|
| 163 |
+
canvas[-12:]=timeline;cursor=min(WIDTH-1,int(i*WIDTH/T));canvas[-12:,cursor:cursor+2]=255
|
| 164 |
+
enc.stdin.write(canvas.tobytes());rendered+=1
|
| 165 |
+
if i in snapshots:
|
| 166 |
+
snap=doc/'video_snapshots'/cam;snap.mkdir(parents=True,exist_ok=True);Image.fromarray(canvas).save(snap/f'{i:06d}.jpg',quality=92)
|
| 167 |
+
if i%200==0:print('VIDEO_FRAME',dataset,cam,i,T,flush=True)
|
| 168 |
+
assert not dec.stdout.read(1),'extra source frames';dec.stdout.close();assert dec.wait()==0
|
| 169 |
+
enc.stdin.close();assert enc.wait()==0;log.close();assert rendered==T
|
| 170 |
+
packets=framehash(['-i',str(path)],copy=True);assert len(packets)==T
|
| 171 |
+
result={'sequence_id':m['sequence_id'],'camera_id':cam,'frames':T,'rendered_frames':rendered,'video_ref':path.relative_to(doc).as_posix(),'video_sha256':digest(path),'preview_fps':fps,
|
| 172 |
+
'preview_is_training_data':False,'preview_encoding':'H264 CRF19, scaled, display only; shared original MKV unchanged',
|
| 173 |
+
'source_labels_from':'raw-derived diagnostic cache' if source!=p else 'shared unfiltered source-compatible labels',
|
| 174 |
+
'all_source_and_shared_valid_masks_used':True,'structure_checks':structural,'mano_valid_counts':valid.sum(0).tolist(),
|
| 175 |
+
'official_qa_pass_frames':int(qa.sum()) if qa is not None else None,'official_qa_fail_frames':int((~qa).sum()) if qa is not None else None,
|
| 176 |
+
'exposure_diagnostics':{'method':'scaled shared decoded RGB to 96x96 gray; p95<35 flags a candidate only, does not modify valid','suspect_dark_frame_indices':[x['frame_index'] for x in exposure if x['p95_luma']<35]}}
|
| 177 |
+
save(tmp/f'{cam}-exposure.json',exposure)
|
| 178 |
+
save(tmp/f'{cam}-video-result.json',result);print('VIDEO_COMPLETE',dataset,cam,T,flush=True)
|
| 179 |
+
return result
|
| 180 |
+
|
| 181 |
+
def asset_preview(op,out):
|
| 182 |
+
"""Textured point-splat turntable plus the source texture; diagnostic, not photoreal rendering."""
|
| 183 |
+
p=op.parents[2];m=load(op/'metainfo.json');meshpath=p/m['mesh_ref']
|
| 184 |
+
if (op/'assets/mesh_tex.obj').exists():meshpath=op/'assets/mesh_tex.obj'
|
| 185 |
+
mesh=trimesh.load(meshpath,process=False,force='mesh');xyz=np.asarray(mesh.vertices);idx=np.arange(0,len(xyz),max(1,len(xyz)//35000));xyz=xyz[idx]
|
| 186 |
+
texture=getattr(mesh.visual.material,'image',None) if hasattr(mesh.visual,'material') else None
|
| 187 |
+
texture_source=None
|
| 188 |
+
if meshpath.name=='mesh_tex.obj' and op.relative_to(DATA_ROOT).parts[0]=='ARCTIC':
|
| 189 |
+
# The loader can silently return a 2x2 default material. Resolve the
|
| 190 |
+
# official single-texture MTL explicitly instead of accepting that placeholder.
|
| 191 |
+
mtl=[r.split(maxsplit=1)[1] for r in meshpath.read_text().splitlines() if r.startswith('mtllib ')]
|
| 192 |
+
diffuse=[]
|
| 193 |
+
for name in mtl:
|
| 194 |
+
material=meshpath.parent/name
|
| 195 |
+
diffuse.extend(material.parent/r.split(maxsplit=1)[1] for r in material.read_text().splitlines() if r.startswith('map_Kd '))
|
| 196 |
+
diffuse=list(set(diffuse));assert len(diffuse)==1,(meshpath,diffuse)
|
| 197 |
+
assert diffuse[0].resolve().is_relative_to(meshpath.parent.resolve())
|
| 198 |
+
texture=Image.open(diffuse[0]).convert('RGB');assert min(texture.size)>2
|
| 199 |
+
texture_source={'file':diffuse[0].relative_to(p).as_posix(),'sha256':digest(diffuse[0]),'size':list(texture.size),'resolution_method':'explicit official MTL map_Kd; reject loader placeholder'}
|
| 200 |
+
if texture is not None and getattr(mesh.visual,'uv',None) is not None:
|
| 201 |
+
tex=np.asarray(texture.convert('RGB'));uv=np.asarray(mesh.visual.uv)[idx]
|
| 202 |
+
rgb=tex[np.clip(np.rint((1-uv[:,1])*(len(tex)-1)).astype(int),0,len(tex)-1),np.clip(np.rint(uv[:,0]*(tex.shape[1]-1)).astype(int),0,tex.shape[1]-1)]
|
| 203 |
+
else:rgb=np.broadcast_to([150,210,245],xyz.shape).astype(np.uint8)
|
| 204 |
+
extent=np.ptp(xyz,axis=0);xyz=xyz-(xyz.min(0)+xyz.max(0))/2;scale=300/max(np.linalg.norm(extent),.001)
|
| 205 |
+
logpath=DATA_ROOT/op.relative_to(DATA_ROOT).parts[0]/'tmp'/VIDEO_RUN/'assets.log'
|
| 206 |
+
logpath.parent.mkdir(parents=True,exist_ok=True)
|
| 207 |
+
out.parent.mkdir(parents=True,exist_ok=True)
|
| 208 |
+
with logpath.open('ab') as log:
|
| 209 |
+
enc=encoder(out,12,log,size=(800,480))
|
| 210 |
+
for i in range(72):
|
| 211 |
+
image=np.full((480,800,3),24,np.uint8);R=Rotation.from_euler('xy',[.35,i*2*np.pi/72]).as_matrix();v=xyz@R.T
|
| 212 |
+
order=np.argsort(v[:,2]);xy=np.rint(v[:,:2]*scale+[220,220]).astype(int)
|
| 213 |
+
good=(xy[:,0]>=0)&(xy[:,0]<430)&(xy[:,1]>=35)&(xy[:,1]<400);order=order[good[order]]
|
| 214 |
+
for dx,dy in [(0,0),(1,0),(0,1)]:image[np.clip(xy[order,1]+dy,0,479),np.clip(xy[order,0]+dx,0,429)]=rgb[order]
|
| 215 |
+
if texture is not None:
|
| 216 |
+
thumb=texture.convert('RGB');thumb.thumbnail((350,345));image[40:40+thumb.height,440:440+thumb.width]=np.asarray(thumb)
|
| 217 |
+
text(image,m.get('category_name',m['object_id']),(12,25),size=.65)
|
| 218 |
+
text(image,'TEXTURED 3D POINT PREVIEW',(12,420),size=.55);text(image,'SOURCE MATERIAL TEXTURE',(445,420),size=.5)
|
| 219 |
+
text(image,'OBJ extent (m): '+np.array2string(extent,precision=4),(12,450),size=.5);enc.stdin.write(image.tobytes())
|
| 220 |
+
enc.stdin.close();assert enc.wait()==0
|
| 221 |
+
assert len(framehash(['-i',str(out)],copy=True))==72
|
| 222 |
+
return {'object_id':m['object_id'],'video_ref':'assets/'+out.name,'frames':72,'texture_present':texture is not None,'texture_source':texture_source,'extent_m':extent.tolist(),'method':'diagnostic textured point turntable, not photoreal material rendering'}
|
| 223 |
+
|
| 224 |
+
def publish_review(dataset,results,assets):
|
| 225 |
+
root=DATA_ROOT/dataset/RELEASE;doc=root/'doc/validation'
|
| 226 |
+
scope=[('RGB','全部帧原图与逐帧码流/像素校验'),('相机内参/畸变','投影使用声明模型和全部参数;HUD显示相机模型'),('相机外参','全帧姿态、米制相机位置与世界XZ轨迹'),('MANO','逐帧网格线框、派生关节点、左右手valid'),('物体姿态/几何','逐帧轮廓、局部XYZ轴、物体ID'),('材质/纹理','每个物体的原纹理与完整旋转预览')]
|
| 227 |
+
scope+=([('部件/关节','底座/顶盖分别着色,逐帧关节角'),('物体关键点','源32个物体点逐帧叠加'),('visibility','原数据未提供,明确缺省')] if dataset=='ARCTIC' else [('visibility','原值0–1已修正,原生/可用比例同时显示'),('官方QA','完整红绿时间带;QA失败帧保留诊断、停用监督'),('部件/关节、独立物体关键点','本序列无该源模态,不虚构')])
|
| 228 |
+
scope+=[('深度/像素分割/接触','本次raw范围未提供,不以投影或帧筛选CSV冒充')]
|
| 229 |
+
table=''.join(f'<tr><td>{a}</td><td>{b}</td></tr>' for a,b in scope)
|
| 230 |
+
cards=''.join(f'<section><h2>Camera {r["camera_id"]} · {r["frames"]} 帧 · 有效MANO左右 {r["mano_valid_counts"]}</h2><video controls preload="metadata" src="{r["video_ref"]}"></video><p>全部{r["rendered_frames"]}帧已渲染,无码帧跳过。官方QA通过/未通过:{r["official_qa_pass_frames"]}/{r["official_qa_fail_frames"]}(null表示来源无此QA)。</p></section>' for r in results)
|
| 231 |
+
gallery=''.join(f'<section><h3>物体 {a["object_id"]}</h3><video controls loop preload="metadata" src="{a["video_ref"]}"></video><p>纹理点云旋转预览及原始材质图;此预览不证明完整PBR渲染等价。</p></section>' for a in assets)
|
| 232 |
+
known=('已修正转换器颠倒顶盖/底座编码的错误:原parts.json的0是顶盖、1是底座,共享层重新映射为0底座/1顶盖。9路相机前两帧均为源欠曝图,已排除对应几何监督;camera 6 index 270的手部偏移作为已知问题记录,按用户要求撤销单帧屏蔽,恢复原标注和valid。整套试点仍待验收。中栏显示源参数诊断,右栏按当前valid绘制。详见 <a href="ARCTIC_FINDINGS.md">问题与修复证据</a>、<a href="diagnosis/camera6-270-before-after.jpg">修复前后对照</a>。预览30fps仅用于播放,不代表真实采集帧率;没有源准确性QA。' if dataset=='ARCTIC' else '原始开头帧存在明显错位,官方QA为False;源头戴位姿开头27帧保持不变,帧号/时间/包顺序均未人为移动。中栏保留原始诊断投影,右栏只绘制当前valid监督。已修正visibility误除100。QA按相机整帧保守筛选,不能断言具体哪个实体错。')
|
| 233 |
+
page=f'''<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{dataset} 完整视频审核 v2</title><style>body{{font:16px/1.7 system-ui;background:#edf1f7;color:#172136;max-width:1550px;margin:25px auto;padding:0 20px}}header,section{{background:white;padding:22px;border-radius:12px;margin-bottom:20px}}video{{width:100%;background:#151515}}h1{{margin:0}}.warn{{color:#a71d2b;font-weight:bold}}table{{border-collapse:collapse;width:100%}}td,th{{border:1px solid #ccd4df;padding:8px;text-align:left}}.assets{{display:grid;grid-template-columns:repeat(auto-fit,minmax(500px,1fr));gap:18px}}a{{color:#1567a3}}</style><header><h1>{dataset} · 完整序列审核 v2</h1><p class="warn">人工确认待完成。旧“抽帧投影通过”结论撤回,本页替代旧报告;尚未全量或发布。</p><p>视频三栏:原图 | 原始标注诊断 | 共享层有效监督。所有相机、所有帧都已渲染;青=左手,橙=右手,其他色=物体/部件,白点=MANO派生关节点或源物体关键点。投影不做遮挡剔除,也不是分割真值。</p><p>{known}</p><p>标注 valid=实际标注存在且数值合法,并通过适用官方QA及已明确登记的本地排除规则;可见性不代替valid,剩余帧不因此自动认定人工通过。诊断中被排除的参数不进入有效监督,raw保留。MP4经过缩放与展示编码,仅为doc预览,训练输入仍是无新增损失的shared MKV。</p><p><a href="REPORT.md">正式说明</a> · <a href="report.json">逐相机检查结果</a> · <a href="../RAW_TO_SHARED.md">字段映射</a> · <a href="../CONTRACT.md">更新后的valid定义</a></p><h2>逐模态检查覆盖</h2><table><tr><th>模态</th><th>检查/可视化方式</th></tr>{table}</table></header>{cards}<h2>物体资产检查</h2><div class="assets">{gallery}</div><script>document.querySelectorAll('video').forEach(v=>v.addEventListener('play',()=>document.querySelectorAll('video').forEach(o=>{{if(o!==v)o.pause()}})));</script></html>'''
|
| 234 |
+
(doc/'index.html').write_text(page,encoding='utf-8')
|
| 235 |
+
old=load(doc/'report.json');old.update(stage='full_video_review_awaiting_human',human_review='pending',review_revision='full-video-v2',
|
| 236 |
+
old_sample_projection_conclusion='withdrawn',full_video_views=results,asset_previews=assets,modality_coverage=[{'modality':a,'check':b} for a,b in scope],known_issues=known,
|
| 237 |
+
agent_visual_inspection={'status':'pending_new_full_video_review','not_equivalent_to_user_approval':True},created_at=datetime.now().astimezone().isoformat())
|
| 238 |
+
old.pop('views',None);old.pop('offline_artifact_check',None);save(doc/'report.json',old)
|
| 239 |
+
save(doc/'status.json',{'stage':'full_video_review_awaiting_human','human_review':'pending','full_preprocessing_authorized':False,'upload_authorized':False})
|
| 240 |
+
rows='\n'.join(f'| {r["camera_id"]} | {r["frames"]} | {r["rendered_frames"]} | {r["mano_valid_counts"]} | {r["official_qa_pass_frames"]} |' for r in results)
|
| 241 |
+
(doc/'REPORT.md').write_text(f'# {dataset} 完整序列审核 v2\n\n[离线完整视频](index.html) · [机器结果](report.json)\n\n人工确认待完成;旧抽帧投影通过结论撤回。{known}\n\n|相机|源帧数|渲染帧数|左右手有效标注帧数|官方QA通过帧数|\n|---|---:|---:|---|---:|\n{rows}\n\n## 逐模态覆盖\n\n'+''.join(f'- {a}:{b}。\n' for a,b in scope)+'\n完整视频表示每帧已渲染,并不等于每帧人工审核通过。被官方QA排除的源标注仅在诊断栏显示;不挪帧、不隐藏原始异常。所有有效性筛选、可见性与图像编码验收分开记录。源标注质量问题无法通过格式转换修好;通过valid屏蔽,并保留raw溯源。\n',encoding='utf-8')
|
| 242 |
+
for f in ['CONTRACT.md','schema.json']:shutil.copyfile(WORK/'distribution/hand-warehouse-1.0'/f,root/'doc'/f)
|
| 243 |
+
# Keep the published script bundle immutable while regenerating review artifacts.
|
| 244 |
+
print('FULL_VIDEO_REVIEW_READY',dataset,flush=True)
|
| 245 |
+
|
| 246 |
+
if __name__=='__main__':
|
| 247 |
+
ap=argparse.ArgumentParser();ap.add_argument('dataset',choices=['HOT3D','ARCTIC']);a=ap.parse_args();torch.set_num_threads(3)
|
| 248 |
+
root=DATA_ROOT/a.dataset/RELEASE;qa=load(root/'doc/validation/source_qa.json') if a.dataset=='HOT3D' else None
|
| 249 |
+
# This entry point owns the original single-sequence report. Other review
|
| 250 |
+
# sequences have their own output directories in arctic_object_review.py.
|
| 251 |
+
sequence={'ARCTIC':'s09_laptop_use_03','HOT3D':'P0015_179e1b84'}[a.dataset]
|
| 252 |
+
views=sorted(p.parent for p in (root/'data'/sequence).glob('*/metainfo.json'));results=[]
|
| 253 |
+
for p in views:results.append(render_view(p,a.dataset,qa))
|
| 254 |
+
assets=[]
|
| 255 |
+
for op in sorted((views[0]/'annotation/object').iterdir()):assets.append(asset_preview(op,root/'doc/validation/assets'/f'{op.name}.mp4'))
|
| 256 |
+
publish_review(a.dataset,results,assets)
|
HOT3D/shared-v1.0/script/internal/review_fresh_sequence_pilots.py
CHANGED
|
@@ -1,225 +1,223 @@
|
|
| 1 |
-
"""Validate actual shared outputs and create portable, offline pilot reviews.
|
| 2 |
-
|
| 3 |
-
Run after convert_fresh_sequence_pilots.py. Never authorizes full processing.
|
| 4 |
-
"""
|
| 5 |
-
from fresh_sequence_common import *
|
| 6 |
-
import html
|
| 7 |
-
from datetime import datetime
|
| 8 |
-
|
| 9 |
-
def arr(p):
|
| 10 |
-
value=torch.load(p,map_location='cpu',weights_only=True)
|
| 11 |
-
assert isinstance(value,torch.Tensor) and value.device.type=='cpu'
|
| 12 |
-
return value.numpy()
|
| 13 |
-
|
| 14 |
-
def safe_ref(root,ref):
|
| 15 |
-
path=(root/ref).resolve()
|
| 16 |
-
assert path.is_relative_to(root.resolve()) and path.is_file(),ref
|
| 17 |
-
return path
|
| 18 |
-
|
| 19 |
-
def validate_view(p):
|
| 20 |
-
m=load(p/'metainfo.json');T=m['num_frames'];registry=load(WORK/'distribution/hand-warehouse-1.0/schema.json')
|
| 21 |
-
assert m['schema_version']==registry['schema_version'] and m['pilot_complete']
|
| 22 |
-
frames=[json.loads(line) for line in (p/'camera/frames.jsonl').read_text().splitlines()]
|
| 23 |
-
assert len(frames)==T and [f['frame_index'] for f in frames]==list(range(T))
|
| 24 |
-
assert len({f['source_frame_id'] for f in frames})==T
|
| 25 |
-
for frame in frames:
|
| 26 |
-
for match in frame.get('annotation_matches',{}).values():
|
| 27 |
-
if 'available' in match:match['source_record_present']=match.pop('available')
|
| 28 |
-
lines(p/'camera/frames.jsonl',frames)
|
| 29 |
-
summary=[]
|
| 30 |
-
for key,c in m['components'].items():
|
| 31 |
-
assert c['schema_id'] in registry['components'],(key,c['schema_id'])
|
| 32 |
-
assert c['available'] and c['source_locator'] and c['provenance']['kind'] in ['source','derived','format_conversion']
|
| 33 |
-
data=safe_ref(p,c['data_ref']);valid=arr(safe_ref(p,c['valid_ref']))
|
| 34 |
-
assert valid.dtype==bool and valid.ndim==len(c['valid_axes'])
|
| 35 |
-
if data.suffix=='.pt':
|
| 36 |
-
a=arr(data);assert a.dtype==np.float32 and a.shape[0]==T
|
| 37 |
-
assert a.shape[:valid.ndim]==valid.shape and len(c['axes'])==a.ndim
|
| 38 |
-
assert np.isfinite(a[valid]).all() and np.isnan(a[~valid]).all()
|
| 39 |
-
if c['schema_id'] in ['object/rigid/v1','transform/se3/v1']:assert_se3(a[valid])
|
| 40 |
-
if c['schema_id']=='mano/axis_angle61/v1':assert a.shape==(T,2,61)
|
| 41 |
-
elif data.suffix=='.mkv':
|
| 42 |
-
assert c['storage']['profile'] in registry['storage_profiles']
|
| 43 |
-
assert valid.shape==(T,) and valid.all()
|
| 44 |
-
for attr in c.get('attributes',{}).values():
|
| 45 |
-
a=arr(safe_ref(p,attr['data_ref']));b=arr(safe_ref(p,attr['valid_ref']))
|
| 46 |
-
assert b.dtype==bool and a.shape==b.shape
|
| 47 |
-
assert np.isfinite(a[b]).all() and ((a[b]>=0)&(a[b]<=1)).all() and np.isnan(a[~b]).all()
|
| 48 |
-
if 'distortion_ref' in c:
|
| 49 |
-
d=arr(safe_ref(p,c['distortion_ref']));assert d.shape==(T,8) and np.isfinite(d).all()
|
| 50 |
-
summary.append({'component':key,'schema':c['schema_id'],'valid':int(valid.sum()),'total':int(valid.size)})
|
| 51 |
-
for op in sorted((p/'annotation/object').glob('*')):
|
| 52 |
-
om=load(op/'metainfo.json');mesh=safe_ref(p,om['mesh_ref'])
|
| 53 |
-
if 'vertex_part_ids_ref' in om:
|
| 54 |
-
ids=arr(safe_ref(p,om['vertex_part_ids_ref']));assert ids.dtype==np.int64
|
| 55 |
-
assert len(ids)==sum(line.startswith('v ') for line in mesh.read_text().splitlines())
|
| 56 |
-
assert om['topology_id']=='sha256:'+digest(mesh)
|
| 57 |
-
if not (op/'pose.pt').exists():
|
| 58 |
-
assert m.get('omitted_components',{}).get('object_pose')
|
| 59 |
-
else:
|
| 60 |
-
root=arr(op/'pose.pt');top=arr(op/'parts/top/pose.pt');joint=arr(op/'joint_state.pt')[:,0]
|
| 61 |
-
ok=arr(op/'pose_valid.pt');H=np.broadcast_to(np.eye(4),(ok.sum(),4,4)).copy()
|
| 62 |
-
H[:,:3,:3]=Rotation.from_rotvec(np.c_[np.zeros((ok.sum(),2)),-joint[ok]]).as_matrix()
|
| 63 |
-
if ok.any():assert np.max(np.abs(root[ok]@H-top[ok]))<2e-6
|
| 64 |
-
for obj in (op/'assets').glob('*.obj'):
|
| 65 |
-
for row in obj.read_text().splitlines():
|
| 66 |
-
if row.startswith('mtllib '):
|
| 67 |
-
material=safe_ref(obj.parent,row.split(maxsplit=1)[1])
|
| 68 |
-
for r in material.read_text().splitlines():
|
| 69 |
-
if r.lower().startswith('map_kd '):safe_ref(material.parent,r.split(maxsplit=1)[1])
|
| 70 |
-
records=load(DATA_ROOT/m['dataset_id']/'tmp'/RUN/'checks'/f'{m["sequence_id"]}__{m["camera_id"]}.json')['checks']
|
| 71 |
-
assert records and all(x.get('passed',False) for x in records)
|
| 72 |
-
media=next(r for r in records if r['test'] in ['all_source_JPEG_packets_and_RGB_pixels_exact','all_source_JPEG_packets_exact']);assert media['frames']==T
|
| 73 |
-
if media['test']=='all_source_JPEG_packets_exact':
|
| 74 |
-
pixels=next(r for r in records if r['test']=='source_RGB_pixels_exact')
|
| 75 |
-
assert pixels['scope']=='deterministic_sample' and pixels['sampled_frames']==len(pixels['frame_indices']) and pixels['sampled_frames']==min(T,16)
|
| 76 |
-
assert pixels['decoded_from_container'] and pixels['frame_indices']==sorted(set(pixels['frame_indices']))
|
| 77 |
-
if 'mano' not in m['components']:
|
| 78 |
-
assert m.get('omitted_components',{}).get('mano')
|
| 79 |
-
assert not (p/'annotation/mano/motion.pt').exists()
|
| 80 |
-
return m,frames,{'camera_id':m['camera_id'],'frames':T,'components':summary,'conversion_checks':records,'structure_and_references':'passed','mano':'source modality absent, omitted'}
|
| 81 |
-
actual=arr(p/'annotation/mano/motion_valid.pt')
|
| 82 |
-
if m['dataset_id']=='HOT3D':
|
| 83 |
-
src=m['components']['mano']['source_locator']
|
| 84 |
-
with zipfile.ZipFile(DATA_ROOT/'HOT3D'/src['archive']) as z:
|
| 85 |
-
native={r['timestamp_ns']:r['hand_poses'] for r in map(json.loads,z.read(src['member']).splitlines())}
|
| 86 |
-
expected=np.array([[str(side) in native.get(f['annotation_matches']['mano']['source_timestamp_ns'],{}) for side in range(2)] for f in frames],bool)
|
| 87 |
-
else:expected=np.array([[f['source_annotation_index'] is not None]*2 for f in frames],bool)
|
| 88 |
-
if m['dataset_id']=='HOT3D' and m['components']['mano'].get('valid_policy'):
|
| 89 |
-
source=m['components']['mano']['valid_policy']['source_locator']
|
| 90 |
-
with zipfile.ZipFile(DATA_ROOT/'HOT3D'/source['archive']) as z:
|
| 91 |
-
lookup={int(r['timestamp[ns]']):r['mask']=='True' for r in csv.DictReader(io.StringIO(z.read(source['member']).decode())) if r['stream_id']==m['camera_id']}
|
| 92 |
-
qa=[lookup[f['timecode_ns']] for f in frames]
|
| 93 |
-
expected &= np.array(qa,bool)[:,None]
|
| 94 |
-
if m['dataset_id']=='ARCTIC':
|
| 95 |
-
rejected=m['components']['mano'].get('valid_policy',{}).get('local_excluded_frame_indices',[])
|
| 96 |
-
expected[rejected]=False
|
| 97 |
-
assert np.array_equal(expected,actual),'annotation validity disagrees with declared source and QA/local policy'
|
| 98 |
-
records.append({'test':'all_frame_source_annotation_and_QA_policy','passed':True,'left_right_valid_counts':actual.sum(0).tolist(),'frames_without_usable_hand':int((~actual.any(1)).sum())})
|
| 99 |
-
return m,frames,{'camera_id':m['camera_id'],'frames':T,'components':summary,'conversion_checks':records,'structure_and_references':'passed'}
|
| 100 |
-
|
| 101 |
-
def select_images(p,indices,dest):
|
| 102 |
-
dest.mkdir(parents=True,exist_ok=True)
|
| 103 |
-
selection='+'.join(f'eq(n,{i})' for i in indices)
|
| 104 |
-
command([FF,'-v','error','-y','-threads','2','-noautorotate','-i',p/'observation/rgb.mkv',
|
| 105 |
-
'-vf',f"select='{selection}',scale=900:900:force_original_aspect_ratio=decrease",'-fps_mode','vfr',dest/'decoded-%03d.png'])
|
| 106 |
-
output=sorted(dest.glob('decoded-*.png'));assert len(output)==len(indices)
|
| 107 |
-
return dict(zip(indices,output))
|
| 108 |
-
|
| 109 |
-
def project_for_view(points,m,params,scale):
|
| 110 |
-
uv=project_points(points,m['camera']['model'],params)
|
| 111 |
-
if m['camera']['model']=='fisheye624':
|
| 112 |
-
angle=np.arctan2(np.linalg.norm(points[:,:2],axis=1),points[:,2])
|
| 113 |
-
uv[angle>m['camera']['max_solid_angle']]=np.nan
|
| 114 |
-
return uv*scale
|
| 115 |
-
|
| 116 |
-
def draw_edges(canvas,uv,edges,color):
|
| 117 |
-
H,W=canvas.shape[:2]
|
| 118 |
-
for a,b in edges:
|
| 119 |
-
xy=uv[[a,b]]
|
| 120 |
-
if not np.isfinite(xy).all():continue
|
| 121 |
-
if np.max(np.abs(xy))>max(W,H)*20:continue
|
| 122 |
-
xy=np.rint(xy).astype(int)
|
| 123 |
-
if np.linalg.norm(xy[0]-xy[1])>max(W,H)*.35:continue
|
| 124 |
-
ok,start,end=cv2.clipLine((0,0,W,H),tuple(xy[0]),tuple(xy[1]))
|
| 125 |
-
if ok:cv2.line(canvas,start,end,color,1,cv2.LINE_AA)
|
| 126 |
-
|
| 127 |
-
def review_view(p,m,frames,dest):
|
| 128 |
-
T=m['num_frames'];indices=sorted(set([0,1,T//4,T//2,3*T//4,T-1]));imgs=select_images(p,indices,dest)
|
| 129 |
-
K=arr(p/'camera/intrinsic.pt');D=arr(p/'camera/distortion.pt') if (p/'camera/distortion.pt').exists() else None
|
| 130 |
-
motion=arr(p/'annotation/mano/motion.pt');valid=arr(p/'annotation/mano/motion_valid.pt');models=[Mano('left'),Mano('right')]
|
| 131 |
-
if m['components']['mano']['model_profile']['left_shapedirs_fix']:
|
| 132 |
-
models[0].data['shapedirs'][:,0]*=-1
|
| 133 |
-
with torch.no_grad():models[0].layer.shapedirs[:,0]*=-1
|
| 134 |
-
objects=[]
|
| 135 |
-
for op in sorted((p/'annotation/object').iterdir()):
|
| 136 |
-
om=load(op/'metainfo.json');mesh=trimesh.load(p/om['mesh_ref'],process=False,force='mesh')
|
| 137 |
-
if 'vertex_part_ids_ref' in om:
|
| 138 |
-
vertices=np.array([[float(x) for x in r.split()[1:4]] for r in (p/om['mesh_ref']).read_text().splitlines() if r.startswith('v ')])
|
| 139 |
-
# trimesh may split OBJ vertices along UV seams; render exact source-ordered vertices as points.
|
| 140 |
-
objects.append((op,om,vertices,None,arr(op/'pose.pt'),arr(op/'pose_valid.pt'),arr(p/om['vertex_part_ids_ref']),arr(op/'parts/top/pose.pt')))
|
| 141 |
-
else:
|
| 142 |
-
edges=np.asarray(mesh.edges_unique);edges=edges[::max(1,len(edges)//2500)]
|
| 143 |
-
objects.append((op,om,np.asarray(mesh.vertices),edges,arr(op/'pose.pt'),arr(op/'pose_valid.pt'),None,None))
|
| 144 |
-
records=[]
|
| 145 |
-
for i,source in imgs.items():
|
| 146 |
-
original=np.asarray(Image.open(source).convert('RGB'));overlay=original.copy()
|
| 147 |
-
scale=np.array([original.shape[1]/m['camera']['image_size'][0],original.shape[0]/m['camera']['image_size'][1]])
|
| 148 |
-
params=K[i] if m['camera']['model']=='fisheye624' else (K[i],D[i] if D is not None else None)
|
| 149 |
-
for side,model in enumerate(models):
|
| 150 |
-
if not valid[i,side]:continue
|
| 151 |
-
h=motion[i,side];vertices,_,_=model.geometry(h[:48],h[48:58],h[58:]);uv=project_for_view(vertices[0],m,params,scale)
|
| 152 |
-
faces=np.asarray(model.layer.faces);edges=np.concatenate([faces[:,[0,1]],faces[:,[1,2]],faces[:,[2,0]]]);draw_edges(overlay,uv,edges,(0,235,255) if side==0 else (255,135,20))
|
| 153 |
-
palette=[(110,255,100),(255,80,210),(240,220,60),(90,180,255),(190,160,255),(255,120,140)]
|
| 154 |
-
for c,(op,om,vertices,edges,P,ok,parts,top) in enumerate(objects):
|
| 155 |
-
if not ok[i]:continue
|
| 156 |
-
xyz=vertices@P[i,:3,:3].T+P[i,:3,3]
|
| 157 |
-
if parts is not None:xyz[parts==1]=vertices[parts==1]@top[i,:3,:3].T+top[i,:3,3]
|
| 158 |
-
uv=project_for_view(xyz,m,params,scale)
|
| 159 |
-
if edges is not None:draw_edges(overlay,uv,edges,palette[c%len(palette)])
|
| 160 |
-
else:
|
| 161 |
-
for xy in uv[::max(1,len(uv)//6000)]:
|
| 162 |
-
if np.isfinite(xy).all() and 0<=xy[0]<overlay.shape[1] and 0<=xy[1]<overlay.shape[0]:cv2.circle(overlay,tuple(np.rint(xy).astype(int)),1,palette[c%len(palette)],-1)
|
| 163 |
-
blended=cv2.addWeighted(overlay,.8,original,.2,0);output=dest/f'frame-{i:06d}-overlay.png';raw=dest/f'frame-{i:06d}-rgb.png'
|
| 164 |
-
Image.fromarray(blended).save(output);source.replace(raw)
|
| 165 |
-
records.append({'frame_index':i,'source_frame_id':frames[i]['source_frame_id'],'rgb':raw.name,'overlay':output.name,'mano_valid':valid[i].tolist()})
|
| 166 |
-
return records
|
| 167 |
-
|
| 168 |
-
def write_reports(dataset,views):
|
| 169 |
-
base=DATA_ROOT/dataset;root=base/RELEASE;doc=root/'doc';review=doc/'validation';reports=[];cards=[];thumbs=[]
|
| 170 |
-
rawpaths=set()
|
| 171 |
-
for p in views:
|
| 172 |
-
if dataset=='ARCTIC':
|
| 173 |
-
for assets in (p/'annotation/object').glob('*/assets'):repair_arctic_material_refs(assets)
|
| 174 |
-
m,frames,summary=validate_view(p);cam=m['camera_id'];samples=review_view(p,m,frames,review/'images'/cam)
|
| 175 |
-
summary['visual_samples']=samples;reports.append(summary)
|
| 176 |
-
# All actually consumed source files; camera/mano/object locators name source archives.
|
| 177 |
-
rawpaths.add(m['components']['rgb']['source_locator'].get('archive',m['components']['rgb']['source_locator'].get('file')))
|
| 178 |
-
for comp in m['components'].values():
|
| 179 |
-
src=comp['source_locator']
|
| 180 |
-
if 'archive' in src:rawpaths.add(src['archive'])
|
| 181 |
-
if dataset=='ARCTIC':rawpaths.add('raw/data/splits_json.zip')
|
| 182 |
-
for op in (p/'annotation/object').iterdir():
|
| 183 |
-
glb=load(op/'metainfo.json').get('original_glb_ref')
|
| 184 |
-
if glb:rawpaths.add(load(op/'metainfo.json')['original_glb_source_locator']['file'])
|
| 185 |
-
opts=''.join(f'<option value="{i}"'+(' selected' if s['frame_index']==m['num_frames']//2 else '')+f'>index {s["frame_index"]} · source {s["source_frame_id"]} · valid {s["mano_valid"]}</option>' for i,s in enumerate(samples))
|
| 186 |
-
samples_js=json.dumps([{k:(f'images/{cam}/'+s[k] if k in ('rgb','overlay') else s[k]) for k in s} for s in samples])
|
| 187 |
-
cards.append(f'<section class="card" data-samples=\'{html.escape(samples_js,quote=True)}\'><h2>Camera {cam} · {m["camera"]["model"]} · {m["num_frames"]} 帧</h2><select onchange="show(this.closest(\'.card\'))">{opts}</select><label><input type="checkbox" checked onchange="show(this.closest(\'.card\'))"> 显示投影</label><br><a class="zoom" target="_blank"><img alt="共享产物实际帧与投影"></a><p class="caption"></p></section>')
|
| 188 |
-
middle=samples[len(samples)//2];thumb=Image.open(review/'images'/cam/middle['overlay']).convert('RGB');thumb.thumbnail((400,320));tile=Image.new('RGB',(420,355),'#18202b');tile.paste(thumb,((420-thumb.width)//2,28));ImageDraw.Draw(tile).text((10,8),f'{dataset} camera {cam} / frame {middle["frame_index"]}',fill='white');thumbs.append(tile)
|
| 189 |
-
print('REVIEWED',dataset,cam,flush=True)
|
| 190 |
-
cols=3;grid=Image.new('RGB',(cols*420,((len(thumbs)+cols-1)//cols)*355),'#18202b')
|
| 191 |
-
for i,t in enumerate(thumbs):grid.paste(t,((i%cols)*420,(i//cols)*355))
|
| 192 |
-
grid.save(review/'overview.png')
|
| 193 |
-
source_manifest=[]
|
| 194 |
-
ledger=load(base/'raw/doc'/('archive_checksums.json' if dataset=='ARCTIC' else 'file_checksums.json'))
|
| 195 |
-
for rel in sorted(x for x in rawpaths if x):
|
| 196 |
-
file=base/rel;sha=digest(file);record=ledger[rel.removeprefix('raw/data/')]
|
| 197 |
-
assert record['sha256']==sha and record['size']==file.stat().st_size
|
| 198 |
-
assert record.get('official_sha256_match',record.get('official_digest_match')) is True
|
| 199 |
-
if file.suffix=='.zip':assert record['zip_crc']=='passed_all_members'
|
| 200 |
-
if dataset=='HOT3D':assert record['fresh_download_run']=='2026-09-18-aria-fresh'
|
| 201 |
-
source_manifest.append({'path':rel,'bytes':file.stat().st_size,'sha256':sha,'matches_verified_official_download':True,'zip_crc_at_download':record.get('zip_crc')})
|
| 202 |
-
save(doc/'pilot-source-manifest.json',source_manifest)
|
| 203 |
-
script_manifest=[]
|
| 204 |
-
for
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
'
|
| 209 |
-
'
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
if __name__=='__main__':
|
| 225 |
-
raise SystemExit('Static-sample review is retired. Use render_full_sequence_review.py DATASET and finalize_fresh_sequence_review.py; validate_view remains a reusable numeric helper.')
|
|
|
|
| 1 |
+
"""Validate actual shared outputs and create portable, offline pilot reviews.
|
| 2 |
+
|
| 3 |
+
Run after convert_fresh_sequence_pilots.py. Never authorizes full processing.
|
| 4 |
+
"""
|
| 5 |
+
from fresh_sequence_common import *
|
| 6 |
+
import html
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
|
| 9 |
+
def arr(p):
|
| 10 |
+
value=torch.load(p,map_location='cpu',weights_only=True)
|
| 11 |
+
assert isinstance(value,torch.Tensor) and value.device.type=='cpu'
|
| 12 |
+
return value.numpy()
|
| 13 |
+
|
| 14 |
+
def safe_ref(root,ref):
|
| 15 |
+
path=(root/ref).resolve()
|
| 16 |
+
assert path.is_relative_to(root.resolve()) and path.is_file(),ref
|
| 17 |
+
return path
|
| 18 |
+
|
| 19 |
+
def validate_view(p):
|
| 20 |
+
m=load(p/'metainfo.json');T=m['num_frames'];registry=load(WORK/'distribution/hand-warehouse-1.0/schema.json')
|
| 21 |
+
assert m['schema_version']==registry['schema_version'] and m['pilot_complete']
|
| 22 |
+
frames=[json.loads(line) for line in (p/'camera/frames.jsonl').read_text().splitlines()]
|
| 23 |
+
assert len(frames)==T and [f['frame_index'] for f in frames]==list(range(T))
|
| 24 |
+
assert len({f['source_frame_id'] for f in frames})==T
|
| 25 |
+
for frame in frames:
|
| 26 |
+
for match in frame.get('annotation_matches',{}).values():
|
| 27 |
+
if 'available' in match:match['source_record_present']=match.pop('available')
|
| 28 |
+
lines(p/'camera/frames.jsonl',frames)
|
| 29 |
+
summary=[]
|
| 30 |
+
for key,c in m['components'].items():
|
| 31 |
+
assert c['schema_id'] in registry['components'],(key,c['schema_id'])
|
| 32 |
+
assert c['available'] and c['source_locator'] and c['provenance']['kind'] in ['source','derived','format_conversion']
|
| 33 |
+
data=safe_ref(p,c['data_ref']);valid=arr(safe_ref(p,c['valid_ref']))
|
| 34 |
+
assert valid.dtype==bool and valid.ndim==len(c['valid_axes'])
|
| 35 |
+
if data.suffix=='.pt':
|
| 36 |
+
a=arr(data);assert a.dtype==np.float32 and a.shape[0]==T
|
| 37 |
+
assert a.shape[:valid.ndim]==valid.shape and len(c['axes'])==a.ndim
|
| 38 |
+
assert np.isfinite(a[valid]).all() and np.isnan(a[~valid]).all()
|
| 39 |
+
if c['schema_id'] in ['object/rigid/v1','transform/se3/v1']:assert_se3(a[valid])
|
| 40 |
+
if c['schema_id']=='mano/axis_angle61/v1':assert a.shape==(T,2,61)
|
| 41 |
+
elif data.suffix=='.mkv':
|
| 42 |
+
assert c['storage']['profile'] in registry['storage_profiles']
|
| 43 |
+
assert valid.shape==(T,) and valid.all()
|
| 44 |
+
for attr in c.get('attributes',{}).values():
|
| 45 |
+
a=arr(safe_ref(p,attr['data_ref']));b=arr(safe_ref(p,attr['valid_ref']))
|
| 46 |
+
assert b.dtype==bool and a.shape==b.shape
|
| 47 |
+
assert np.isfinite(a[b]).all() and ((a[b]>=0)&(a[b]<=1)).all() and np.isnan(a[~b]).all()
|
| 48 |
+
if 'distortion_ref' in c:
|
| 49 |
+
d=arr(safe_ref(p,c['distortion_ref']));assert d.shape==(T,8) and np.isfinite(d).all()
|
| 50 |
+
summary.append({'component':key,'schema':c['schema_id'],'valid':int(valid.sum()),'total':int(valid.size)})
|
| 51 |
+
for op in sorted((p/'annotation/object').glob('*')):
|
| 52 |
+
om=load(op/'metainfo.json');mesh=safe_ref(p,om['mesh_ref'])
|
| 53 |
+
if 'vertex_part_ids_ref' in om:
|
| 54 |
+
ids=arr(safe_ref(p,om['vertex_part_ids_ref']));assert ids.dtype==np.int64
|
| 55 |
+
assert len(ids)==sum(line.startswith('v ') for line in mesh.read_text().splitlines())
|
| 56 |
+
assert om['topology_id']=='sha256:'+digest(mesh)
|
| 57 |
+
if not (op/'pose.pt').exists():
|
| 58 |
+
assert m.get('omitted_components',{}).get('object_pose')
|
| 59 |
+
else:
|
| 60 |
+
root=arr(op/'pose.pt');top=arr(op/'parts/top/pose.pt');joint=arr(op/'joint_state.pt')[:,0]
|
| 61 |
+
ok=arr(op/'pose_valid.pt');H=np.broadcast_to(np.eye(4),(ok.sum(),4,4)).copy()
|
| 62 |
+
H[:,:3,:3]=Rotation.from_rotvec(np.c_[np.zeros((ok.sum(),2)),-joint[ok]]).as_matrix()
|
| 63 |
+
if ok.any():assert np.max(np.abs(root[ok]@H-top[ok]))<2e-6
|
| 64 |
+
for obj in (op/'assets').glob('*.obj'):
|
| 65 |
+
for row in obj.read_text().splitlines():
|
| 66 |
+
if row.startswith('mtllib '):
|
| 67 |
+
material=safe_ref(obj.parent,row.split(maxsplit=1)[1])
|
| 68 |
+
for r in material.read_text().splitlines():
|
| 69 |
+
if r.lower().startswith('map_kd '):safe_ref(material.parent,r.split(maxsplit=1)[1])
|
| 70 |
+
records=load(DATA_ROOT/m['dataset_id']/'tmp'/RUN/'checks'/f'{m["sequence_id"]}__{m["camera_id"]}.json')['checks']
|
| 71 |
+
assert records and all(x.get('passed',False) for x in records)
|
| 72 |
+
media=next(r for r in records if r['test'] in ['all_source_JPEG_packets_and_RGB_pixels_exact','all_source_JPEG_packets_exact']);assert media['frames']==T
|
| 73 |
+
if media['test']=='all_source_JPEG_packets_exact':
|
| 74 |
+
pixels=next(r for r in records if r['test']=='source_RGB_pixels_exact')
|
| 75 |
+
assert pixels['scope']=='deterministic_sample' and pixels['sampled_frames']==len(pixels['frame_indices']) and pixels['sampled_frames']==min(T,16)
|
| 76 |
+
assert pixels['decoded_from_container'] and pixels['frame_indices']==sorted(set(pixels['frame_indices']))
|
| 77 |
+
if 'mano' not in m['components']:
|
| 78 |
+
assert m.get('omitted_components',{}).get('mano')
|
| 79 |
+
assert not (p/'annotation/mano/motion.pt').exists()
|
| 80 |
+
return m,frames,{'camera_id':m['camera_id'],'frames':T,'components':summary,'conversion_checks':records,'structure_and_references':'passed','mano':'source modality absent, omitted'}
|
| 81 |
+
actual=arr(p/'annotation/mano/motion_valid.pt')
|
| 82 |
+
if m['dataset_id']=='HOT3D':
|
| 83 |
+
src=m['components']['mano']['source_locator']
|
| 84 |
+
with zipfile.ZipFile(DATA_ROOT/'HOT3D'/src['archive']) as z:
|
| 85 |
+
native={r['timestamp_ns']:r['hand_poses'] for r in map(json.loads,z.read(src['member']).splitlines())}
|
| 86 |
+
expected=np.array([[str(side) in native.get(f['annotation_matches']['mano']['source_timestamp_ns'],{}) for side in range(2)] for f in frames],bool)
|
| 87 |
+
else:expected=np.array([[f['source_annotation_index'] is not None]*2 for f in frames],bool)
|
| 88 |
+
if m['dataset_id']=='HOT3D' and m['components']['mano'].get('valid_policy'):
|
| 89 |
+
source=m['components']['mano']['valid_policy']['source_locator']
|
| 90 |
+
with zipfile.ZipFile(DATA_ROOT/'HOT3D'/source['archive']) as z:
|
| 91 |
+
lookup={int(r['timestamp[ns]']):r['mask']=='True' for r in csv.DictReader(io.StringIO(z.read(source['member']).decode())) if r['stream_id']==m['camera_id']}
|
| 92 |
+
qa=[lookup[f['timecode_ns']] for f in frames]
|
| 93 |
+
expected &= np.array(qa,bool)[:,None]
|
| 94 |
+
if m['dataset_id']=='ARCTIC':
|
| 95 |
+
rejected=m['components']['mano'].get('valid_policy',{}).get('local_excluded_frame_indices',[])
|
| 96 |
+
expected[rejected]=False
|
| 97 |
+
assert np.array_equal(expected,actual),'annotation validity disagrees with declared source and QA/local policy'
|
| 98 |
+
records.append({'test':'all_frame_source_annotation_and_QA_policy','passed':True,'left_right_valid_counts':actual.sum(0).tolist(),'frames_without_usable_hand':int((~actual.any(1)).sum())})
|
| 99 |
+
return m,frames,{'camera_id':m['camera_id'],'frames':T,'components':summary,'conversion_checks':records,'structure_and_references':'passed'}
|
| 100 |
+
|
| 101 |
+
def select_images(p,indices,dest):
|
| 102 |
+
dest.mkdir(parents=True,exist_ok=True)
|
| 103 |
+
selection='+'.join(f'eq(n,{i})' for i in indices)
|
| 104 |
+
command([FF,'-v','error','-y','-threads','2','-noautorotate','-i',p/'observation/rgb.mkv',
|
| 105 |
+
'-vf',f"select='{selection}',scale=900:900:force_original_aspect_ratio=decrease",'-fps_mode','vfr',dest/'decoded-%03d.png'])
|
| 106 |
+
output=sorted(dest.glob('decoded-*.png'));assert len(output)==len(indices)
|
| 107 |
+
return dict(zip(indices,output))
|
| 108 |
+
|
| 109 |
+
def project_for_view(points,m,params,scale):
|
| 110 |
+
uv=project_points(points,m['camera']['model'],params)
|
| 111 |
+
if m['camera']['model']=='fisheye624':
|
| 112 |
+
angle=np.arctan2(np.linalg.norm(points[:,:2],axis=1),points[:,2])
|
| 113 |
+
uv[angle>m['camera']['max_solid_angle']]=np.nan
|
| 114 |
+
return uv*scale
|
| 115 |
+
|
| 116 |
+
def draw_edges(canvas,uv,edges,color):
|
| 117 |
+
H,W=canvas.shape[:2]
|
| 118 |
+
for a,b in edges:
|
| 119 |
+
xy=uv[[a,b]]
|
| 120 |
+
if not np.isfinite(xy).all():continue
|
| 121 |
+
if np.max(np.abs(xy))>max(W,H)*20:continue
|
| 122 |
+
xy=np.rint(xy).astype(int)
|
| 123 |
+
if np.linalg.norm(xy[0]-xy[1])>max(W,H)*.35:continue
|
| 124 |
+
ok,start,end=cv2.clipLine((0,0,W,H),tuple(xy[0]),tuple(xy[1]))
|
| 125 |
+
if ok:cv2.line(canvas,start,end,color,1,cv2.LINE_AA)
|
| 126 |
+
|
| 127 |
+
def review_view(p,m,frames,dest):
|
| 128 |
+
T=m['num_frames'];indices=sorted(set([0,1,T//4,T//2,3*T//4,T-1]));imgs=select_images(p,indices,dest)
|
| 129 |
+
K=arr(p/'camera/intrinsic.pt');D=arr(p/'camera/distortion.pt') if (p/'camera/distortion.pt').exists() else None
|
| 130 |
+
motion=arr(p/'annotation/mano/motion.pt');valid=arr(p/'annotation/mano/motion_valid.pt');models=[Mano('left'),Mano('right')]
|
| 131 |
+
if m['components']['mano']['model_profile']['left_shapedirs_fix']:
|
| 132 |
+
models[0].data['shapedirs'][:,0]*=-1
|
| 133 |
+
with torch.no_grad():models[0].layer.shapedirs[:,0]*=-1
|
| 134 |
+
objects=[]
|
| 135 |
+
for op in sorted((p/'annotation/object').iterdir()):
|
| 136 |
+
om=load(op/'metainfo.json');mesh=trimesh.load(p/om['mesh_ref'],process=False,force='mesh')
|
| 137 |
+
if 'vertex_part_ids_ref' in om:
|
| 138 |
+
vertices=np.array([[float(x) for x in r.split()[1:4]] for r in (p/om['mesh_ref']).read_text().splitlines() if r.startswith('v ')])
|
| 139 |
+
# trimesh may split OBJ vertices along UV seams; render exact source-ordered vertices as points.
|
| 140 |
+
objects.append((op,om,vertices,None,arr(op/'pose.pt'),arr(op/'pose_valid.pt'),arr(p/om['vertex_part_ids_ref']),arr(op/'parts/top/pose.pt')))
|
| 141 |
+
else:
|
| 142 |
+
edges=np.asarray(mesh.edges_unique);edges=edges[::max(1,len(edges)//2500)]
|
| 143 |
+
objects.append((op,om,np.asarray(mesh.vertices),edges,arr(op/'pose.pt'),arr(op/'pose_valid.pt'),None,None))
|
| 144 |
+
records=[]
|
| 145 |
+
for i,source in imgs.items():
|
| 146 |
+
original=np.asarray(Image.open(source).convert('RGB'));overlay=original.copy()
|
| 147 |
+
scale=np.array([original.shape[1]/m['camera']['image_size'][0],original.shape[0]/m['camera']['image_size'][1]])
|
| 148 |
+
params=K[i] if m['camera']['model']=='fisheye624' else (K[i],D[i] if D is not None else None)
|
| 149 |
+
for side,model in enumerate(models):
|
| 150 |
+
if not valid[i,side]:continue
|
| 151 |
+
h=motion[i,side];vertices,_,_=model.geometry(h[:48],h[48:58],h[58:]);uv=project_for_view(vertices[0],m,params,scale)
|
| 152 |
+
faces=np.asarray(model.layer.faces);edges=np.concatenate([faces[:,[0,1]],faces[:,[1,2]],faces[:,[2,0]]]);draw_edges(overlay,uv,edges,(0,235,255) if side==0 else (255,135,20))
|
| 153 |
+
palette=[(110,255,100),(255,80,210),(240,220,60),(90,180,255),(190,160,255),(255,120,140)]
|
| 154 |
+
for c,(op,om,vertices,edges,P,ok,parts,top) in enumerate(objects):
|
| 155 |
+
if not ok[i]:continue
|
| 156 |
+
xyz=vertices@P[i,:3,:3].T+P[i,:3,3]
|
| 157 |
+
if parts is not None:xyz[parts==1]=vertices[parts==1]@top[i,:3,:3].T+top[i,:3,3]
|
| 158 |
+
uv=project_for_view(xyz,m,params,scale)
|
| 159 |
+
if edges is not None:draw_edges(overlay,uv,edges,palette[c%len(palette)])
|
| 160 |
+
else:
|
| 161 |
+
for xy in uv[::max(1,len(uv)//6000)]:
|
| 162 |
+
if np.isfinite(xy).all() and 0<=xy[0]<overlay.shape[1] and 0<=xy[1]<overlay.shape[0]:cv2.circle(overlay,tuple(np.rint(xy).astype(int)),1,palette[c%len(palette)],-1)
|
| 163 |
+
blended=cv2.addWeighted(overlay,.8,original,.2,0);output=dest/f'frame-{i:06d}-overlay.png';raw=dest/f'frame-{i:06d}-rgb.png'
|
| 164 |
+
Image.fromarray(blended).save(output);source.replace(raw)
|
| 165 |
+
records.append({'frame_index':i,'source_frame_id':frames[i]['source_frame_id'],'rgb':raw.name,'overlay':output.name,'mano_valid':valid[i].tolist()})
|
| 166 |
+
return records
|
| 167 |
+
|
| 168 |
+
def write_reports(dataset,views):
|
| 169 |
+
base=DATA_ROOT/dataset;root=base/RELEASE;doc=root/'doc';review=doc/'validation';reports=[];cards=[];thumbs=[]
|
| 170 |
+
rawpaths=set()
|
| 171 |
+
for p in views:
|
| 172 |
+
if dataset=='ARCTIC':
|
| 173 |
+
for assets in (p/'annotation/object').glob('*/assets'):repair_arctic_material_refs(assets)
|
| 174 |
+
m,frames,summary=validate_view(p);cam=m['camera_id'];samples=review_view(p,m,frames,review/'images'/cam)
|
| 175 |
+
summary['visual_samples']=samples;reports.append(summary)
|
| 176 |
+
# All actually consumed source files; camera/mano/object locators name source archives.
|
| 177 |
+
rawpaths.add(m['components']['rgb']['source_locator'].get('archive',m['components']['rgb']['source_locator'].get('file')))
|
| 178 |
+
for comp in m['components'].values():
|
| 179 |
+
src=comp['source_locator']
|
| 180 |
+
if 'archive' in src:rawpaths.add(src['archive'])
|
| 181 |
+
if dataset=='ARCTIC':rawpaths.add('raw/data/splits_json.zip')
|
| 182 |
+
for op in (p/'annotation/object').iterdir():
|
| 183 |
+
glb=load(op/'metainfo.json').get('original_glb_ref')
|
| 184 |
+
if glb:rawpaths.add(load(op/'metainfo.json')['original_glb_source_locator']['file'])
|
| 185 |
+
opts=''.join(f'<option value="{i}"'+(' selected' if s['frame_index']==m['num_frames']//2 else '')+f'>index {s["frame_index"]} · source {s["source_frame_id"]} · valid {s["mano_valid"]}</option>' for i,s in enumerate(samples))
|
| 186 |
+
samples_js=json.dumps([{k:(f'images/{cam}/'+s[k] if k in ('rgb','overlay') else s[k]) for k in s} for s in samples])
|
| 187 |
+
cards.append(f'<section class="card" data-samples=\'{html.escape(samples_js,quote=True)}\'><h2>Camera {cam} · {m["camera"]["model"]} · {m["num_frames"]} 帧</h2><select onchange="show(this.closest(\'.card\'))">{opts}</select><label><input type="checkbox" checked onchange="show(this.closest(\'.card\'))"> 显示投影</label><br><a class="zoom" target="_blank"><img alt="共享产物实际帧与投影"></a><p class="caption"></p></section>')
|
| 188 |
+
middle=samples[len(samples)//2];thumb=Image.open(review/'images'/cam/middle['overlay']).convert('RGB');thumb.thumbnail((400,320));tile=Image.new('RGB',(420,355),'#18202b');tile.paste(thumb,((420-thumb.width)//2,28));ImageDraw.Draw(tile).text((10,8),f'{dataset} camera {cam} / frame {middle["frame_index"]}',fill='white');thumbs.append(tile)
|
| 189 |
+
print('REVIEWED',dataset,cam,flush=True)
|
| 190 |
+
cols=3;grid=Image.new('RGB',(cols*420,((len(thumbs)+cols-1)//cols)*355),'#18202b')
|
| 191 |
+
for i,t in enumerate(thumbs):grid.paste(t,((i%cols)*420,(i//cols)*355))
|
| 192 |
+
grid.save(review/'overview.png')
|
| 193 |
+
source_manifest=[]
|
| 194 |
+
ledger=load(base/'raw/doc'/('archive_checksums.json' if dataset=='ARCTIC' else 'file_checksums.json'))
|
| 195 |
+
for rel in sorted(x for x in rawpaths if x):
|
| 196 |
+
file=base/rel;sha=digest(file);record=ledger[rel.removeprefix('raw/data/')]
|
| 197 |
+
assert record['sha256']==sha and record['size']==file.stat().st_size
|
| 198 |
+
assert record.get('official_sha256_match',record.get('official_digest_match')) is True
|
| 199 |
+
if file.suffix=='.zip':assert record['zip_crc']=='passed_all_members'
|
| 200 |
+
if dataset=='HOT3D':assert record['fresh_download_run']=='2026-09-18-aria-fresh'
|
| 201 |
+
source_manifest.append({'path':rel,'bytes':file.stat().st_size,'sha256':sha,'matches_verified_official_download':True,'zip_crc_at_download':record.get('zip_crc')})
|
| 202 |
+
save(doc/'pilot-source-manifest.json',source_manifest)
|
| 203 |
+
script_manifest=[]
|
| 204 |
+
for p in sorted((root/'script').rglob('*.py')):script_manifest.append({'path':p.relative_to(root).as_posix(),'sha256':digest(p)})
|
| 205 |
+
full={'dataset':dataset,'stage':'pilot_awaiting_human_review','human_review':'pending','full_preprocessing_authorized':False,'upload_authorized':False,
|
| 206 |
+
'scope':'One complete selected sequence, every released camera frame; not full-dataset acceptance','views':reports,
|
| 207 |
+
'sources_manifest':'../pilot-source-manifest.json','script_manifest':script_manifest,'preview_selection':'Deterministic boundary and quartile samples per camera; not random or full-dataset review',
|
| 208 |
+
'preview_rendering':'Derived MANO/object projections from shared tensors, not segmentation ground truth; no depth occlusion test, hidden surfaces may be drawn',
|
| 209 |
+
'created_at':datetime.now().astimezone().isoformat()}
|
| 210 |
+
save(review/'report.json',full);save(review/'status.json',{k:full[k] for k in ['dataset','stage','human_review','full_preprocessing_authorized','upload_authorized']})
|
| 211 |
+
notes=('首帧 RGB 存在,动捕标注无对应项,valid=false;已保留。相机 0 使用 rational8 畸变,外部八相机使用官方针孔投影。关节绕父坐标系 -Z 轴旋转,部件点/网格保持米制。' if dataset=='ARCTIC' else 'Aria 三路相机均保留;RGB 与两路灰度均由原 JPEG 直接封装。device time 经官方映射对齐 timecode;原始 visibility 按百分比转 [0,1],独立于标注 valid。三路按时间匹配,不假定相同行号自动同步。')
|
| 212 |
+
if dataset=='HOT3D':notes+=' 每相机双手各806帧有MANO、208帧原始手参数为空;画面中有手但无投影的末尾帧属于源标注缺失,已验证并保留为valid=false。'
|
| 213 |
+
if dataset=='ARCTIC':notes+=' 原始部件OBJ的材质文件名引用错误已在共享层修正为实际存在的material.mtl,材质标识与纹理不变。'
|
| 214 |
+
missing=('本次官方 raw 中无独立深度、像素分割、接触标签、实测手关键点数组。保留 MANO,供任务层按需生成关键点;未把预览投影写成新增标注。' if dataset=='ARCTIC' else '本范围无深度流或像素分割;masks/*.csv 是帧筛选条件,不能当作像素 mask。UmeTrack 与 MPS 替代估计保留在 raw;shared 选择 MANO 和官方 GT 相机。没有额外生成关键点或接触标签。')
|
| 215 |
+
text=f'''<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{dataset} 序列试点审核</title><style>body{{font:16px/1.65 system-ui;background:#f3f5f8;color:#18202b;max-width:1450px;margin:24px auto;padding:0 20px}}header,.card{{background:white;padding:22px;border-radius:14px;margin-bottom:18px}}.status{{color:#9a5800;font-weight:bold}}.grid{{display:grid;grid-template-columns:repeat(auto-fit,minmax(360px,1fr));gap:18px}}.card img{{max-width:100%;max-height:670px;margin-top:12px}}select{{max-width:100%;padding:8px}}a{{color:#1766ab}}label{{display:inline-block;margin:10px}}h1{{margin:0}}.caption{{font-size:14px}}</style><header><h1>{dataset} · 完整序列试点</h1><p class="status">自动校验已完成;人工审核待确认。尚未开始全量预处理或上传。</p><p>共 {len(views)} 路相机、{sum(r['frames'] for r in reports):,} 个相机帧。全部源 JPEG 码流、全部解码 RGB 帧已逐一比较一致;数值转换、有效性和引用检查通过。</p><p>{notes}</p><p>{missing}</p><p>下方是从 shared 实际产物读取的边界及四分位样本。青色=左手,橙色=右手,其余颜色=物体。投影仅用于几何核验,<b>不是源分割,也没有做遮挡剔除</b>。点击图像可放大;取消勾选可查看原图。</p><p><a href="REPORT.md">验收说明</a> · <a href="report.json">机器可读结果</a> · <a href="../RAW_TO_SHARED.md">raw → share 对照</a> · <a href="../CONTRACT.md">约定</a> · <a href="overview.png">全部相机总览</a></p></header><main class="grid">{''.join(cards)}</main><script>function show(card){{let s=JSON.parse(card.dataset.samples)[Number(card.querySelector('select').value)];let path=card.querySelector('input').checked?s.overlay:s.rgb;card.querySelector('img').src=path;card.querySelector('.zoom').href=path;card.querySelector('.caption').textContent='frame_index='+s.frame_index+' / 原帧 '+s.source_frame_id+' / 左右手 valid='+s.mano_valid;}}document.querySelectorAll('.card').forEach(show)</script></html>'''
|
| 216 |
+
(review/'index.html').write_text(text,encoding='utf-8')
|
| 217 |
+
rows='\n'.join(f'| {r["camera_id"]} | {r["frames"]} | '+', '.join(str(x['frame_index']) for x in r['visual_samples'])+' | 通过 |' for r in reports)
|
| 218 |
+
report=f'''# {dataset} 完整序列试点验收\n\n状态:**自动检查通过,人工确认待完成**。本报告不是全量验收或发布许可。\n\n[离线预览](index.html) · [机器结果](report.json) · [原始包摘要](../pilot-source-manifest.json)\n\n| 相机 | 全序列帧数 | 可视化帧索引 | 自动校验 |\n|---|---:|---|---|\n{rows}\n\n## 已验证\n\n- 完整所选序列的每一张源 JPEG 与 MKV 取回的压缩包 SHA256 相同;全部帧在同一 FFmpeg/noautorotate/rgb24 配置下解码字节相同,顺序和数量一致。不是有损重编码。\n- 全部有效 MANO 帧的相机坐标变换与直接变换几何一致;独立源模型配置抽样校验非平手均值/PCA 展开。张量 float32 保存读取一致,invalid 为 NaN,valid 为 bool。\n- SE(3) 正交性、单位与资产引用检查;ARCTIC 部件关节运动与源旋转公式逐帧对照,HOT3D 物体 OBJ 尺度、三角形及纹理像素往返一致。\n- 所有实际组件使用现有注册 schema;没有为缺省模态伪造值。\n\n## 帧对应和缺省范围\n\n{notes}\n\n{missing}\n\n## 人工核验边界\n\n每相机选序列起点、紧邻帧、四分位、中点、四分之三及终点,不是随机抽查。预览只用于核对几何对齐;投影线条/点不是分割真值,遮挡表面可能被画出。数值自洽不等于图像投影正确,请检查所有相机和多个时刻。此处一序列通过不能覆盖全数据集、其他物体或异常序列。全量处理后仍需独立随机抽查和用户发布确认。\n'''
|
| 219 |
+
(review/'REPORT.md').write_text(report,encoding='utf-8')
|
| 220 |
+
return full
|
| 221 |
+
|
| 222 |
+
if __name__=='__main__':
|
| 223 |
+
raise SystemExit('Static-sample review is retired. Use render_full_sequence_review.py DATASET and finalize_fresh_sequence_review.py; validate_view remains a reusable numeric helper.')
|
|
|
|
|
|
HOT3D/shared-v1.0/script/internal/sequence_pilot_common.py
CHANGED
|
@@ -1,53 +1,51 @@
|
|
| 1 |
-
"""Whole-selection conversion utilities. Never reads previous pilot outputs."""
|
| 2 |
-
from pilot_build import *
|
| 3 |
-
import hashlib
|
| 4 |
-
|
| 5 |
-
RELEASE='shared-sequence-v1.1'
|
| 6 |
-
|
| 7 |
-
class View:
|
| 8 |
-
def __init__(self,dataset,seq,cam,ids,size,source,kind='video',sampling='dense',split='unknown'):
|
| 9 |
-
self.root=ROOT/dataset/RELEASE;self.p=self.root/'data'/seq/cam
|
| 10 |
-
self.p.mkdir(parents=True,exist_ok=True);self.T=len(ids);self.source=source;self.checks=[]
|
| 11 |
-
self.m={'schema_version':'hand-warehouse/1.1','dataset_id':dataset,'release_id':RELEASE,'sequence_id':seq,'camera_id':cam,'sample_type':kind,'num_frames':self.T,'hand_slots':['left','right'],'sampling':{'type':'single' if kind=='image' else sampling,'source_fps':None,'frames_ref':'camera/frames.jsonl'},'camera':{'model':'unknown','schema_id':None,'image_size':size},'components':{},'split':split}
|
| 12 |
-
self.frames=[{'frame_index':i,'source_frame_id':str(fid),'timestamp_ns':None,'clock_domain':None,'source_locator':{**source,'source_frame_id':str(fid)}} for i,fid in enumerate(ids)]
|
| 13 |
-
def add(self,name,path,schema,axes,valid,method='source values retained',**kw):
|
| 14 |
-
vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix()
|
| 15 |
-
tensor(self.p/vp,valid)
|
| 16 |
-
self.m['components'][name]={'available':True,'schema_id':schema,'data_ref':path,'axes':axes,'valid_ref':vp,'valid_axes':axes[:valid.ndim],'provenance':{'kind':'format_conversion','method':method},'source_locator':self.source,**kw}
|
| 17 |
-
def array(self,name,path,schema,a,valid,axes,**kw):
|
| 18 |
-
a=np.asarray(a,np.float32).copy();valid=np.asarray(valid,bool)
|
| 19 |
-
assert a.shape[:valid.ndim]==valid.shape and a.shape[0]==self.T
|
| 20 |
-
assert np.isfinite(a[valid]).all(),name
|
| 21 |
-
a[~valid]=np.nan;tensor(self.p/path,a);self.add(name,path,schema,axes,valid,**kw)
|
| 22 |
-
restored=torch.load(self.p/path,map_location='cpu',weights_only=True).numpy()
|
| 23 |
-
for index in range(self.T):assert np.array_equal(restored[index],a[index],equal_nan=True)
|
| 24 |
-
self.checks.append({'test':'tensor_serialization_exact','file':path,'shape':list(a.shape),'valid_count':int(valid.sum())})
|
| 25 |
-
def video(self,name,path,iterator,mask=False,**kw):
|
| 26 |
-
w,h=self.m['camera']['image_size'];pix='gray16le' if mask else 'rgb24';dtype='<u2' if mask else 'uint8'
|
| 27 |
-
dst=self.p/path;dst.parent.mkdir(parents=True,exist_ok=True);hashes=[]
|
| 28 |
-
proc=subprocess.Popen([FF,'-v','error','-y','-f','rawvideo','-pixel_format',pix,'-video_size',f'{w}x{h}','-framerate','1','-i','pipe:0','-c:v','ffv1','-level','3','-g','1',str(dst)],stdin=subprocess.PIPE)
|
| 29 |
-
try:
|
| 30 |
-
for frame in iterator:
|
| 31 |
-
a=np.asarray(frame,dtype=dtype);assert a.shape==((h,w) if mask else (h,w,3));b=a.tobytes();hashes.append(hashlib.sha256(b).hexdigest());proc.stdin.write(b)
|
| 32 |
-
finally:proc.stdin.close()
|
| 33 |
-
assert proc.wait()==0 and len(hashes)==self.T
|
| 34 |
-
proc=subprocess.Popen([FF,'-v','error','-i',str(dst),'-f','rawvideo','-pix_fmt',pix,'pipe:1'],stdout=subprocess.PIPE)
|
| 35 |
-
nbytes=w*h*(2 if mask else 3)
|
| 36 |
-
for digest in hashes:
|
| 37 |
-
b=proc.stdout.read(nbytes);assert len(b)==nbytes and hashlib.sha256(b).hexdigest()==digest,'video roundtrip'
|
| 38 |
-
assert not proc.stdout.read(1);assert proc.wait()==0
|
| 39 |
-
self.checks.append({'test':'all_frames_pixel_exact_roundtrip','file':path,'frames':self.T})
|
| 40 |
-
self.add(name,path,'segment/uint16_labels/v1' if mask else 'rgb/uint8/v1',['T','height','width'] if mask else ['T','height','width','channel'],np.ones(self.T,bool),storage_fps=1,timebase_role='index_only',**kw)
|
| 41 |
-
def intrinsic(self,K):
|
| 42 |
-
self.m['camera'].update(model='pinhole',schema_id='camera/pinhole/v1')
|
| 43 |
-
self.array('intrinsic','camera/intrinsic.pt','camera/pinhole/v1',np.broadcast_to(K,(self.T,3,3)),np.ones(self.T,bool),['T','row','column'])
|
| 44 |
-
def finish(self):
|
| 45 |
-
lines(self.p/'camera/frames.jsonl',self.frames);save(self.p/'metainfo.json',self.m)
|
| 46 |
-
save(self.root/'doc'/f'{self.m["sequence_id"]}__{self.m["camera_id"]}.checks.json',{'checks':self.checks,'frames':self.T,'input':self.source})
|
| 47 |
-
print('Converted',self.m['dataset_id'],self.m['sequence_id'],self.m['camera_id'],self.T,flush=True)
|
| 48 |
-
|
| 49 |
-
def snapshot(dataset,scripts):
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
names.update(p.name for p in (WORK/'scripts').glob('sequence_pilot_*.py'))
|
| 53 |
-
for name in names:shutil.copyfile(WORK/'scripts'/name,out/name)
|
|
|
|
| 1 |
+
"""Whole-selection conversion utilities. Never reads previous pilot outputs."""
|
| 2 |
+
from pilot_build import *
|
| 3 |
+
import hashlib
|
| 4 |
+
|
| 5 |
+
RELEASE='shared-sequence-v1.1'
|
| 6 |
+
|
| 7 |
+
class View:
|
| 8 |
+
def __init__(self,dataset,seq,cam,ids,size,source,kind='video',sampling='dense',split='unknown'):
|
| 9 |
+
self.root=ROOT/dataset/RELEASE;self.p=self.root/'data'/seq/cam
|
| 10 |
+
self.p.mkdir(parents=True,exist_ok=True);self.T=len(ids);self.source=source;self.checks=[]
|
| 11 |
+
self.m={'schema_version':'hand-warehouse/1.1','dataset_id':dataset,'release_id':RELEASE,'sequence_id':seq,'camera_id':cam,'sample_type':kind,'num_frames':self.T,'hand_slots':['left','right'],'sampling':{'type':'single' if kind=='image' else sampling,'source_fps':None,'frames_ref':'camera/frames.jsonl'},'camera':{'model':'unknown','schema_id':None,'image_size':size},'components':{},'split':split}
|
| 12 |
+
self.frames=[{'frame_index':i,'source_frame_id':str(fid),'timestamp_ns':None,'clock_domain':None,'source_locator':{**source,'source_frame_id':str(fid)}} for i,fid in enumerate(ids)]
|
| 13 |
+
def add(self,name,path,schema,axes,valid,method='source values retained',**kw):
|
| 14 |
+
vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix()
|
| 15 |
+
tensor(self.p/vp,valid)
|
| 16 |
+
self.m['components'][name]={'available':True,'schema_id':schema,'data_ref':path,'axes':axes,'valid_ref':vp,'valid_axes':axes[:valid.ndim],'provenance':{'kind':'format_conversion','method':method},'source_locator':self.source,**kw}
|
| 17 |
+
def array(self,name,path,schema,a,valid,axes,**kw):
|
| 18 |
+
a=np.asarray(a,np.float32).copy();valid=np.asarray(valid,bool)
|
| 19 |
+
assert a.shape[:valid.ndim]==valid.shape and a.shape[0]==self.T
|
| 20 |
+
assert np.isfinite(a[valid]).all(),name
|
| 21 |
+
a[~valid]=np.nan;tensor(self.p/path,a);self.add(name,path,schema,axes,valid,**kw)
|
| 22 |
+
restored=torch.load(self.p/path,map_location='cpu',weights_only=True).numpy()
|
| 23 |
+
for index in range(self.T):assert np.array_equal(restored[index],a[index],equal_nan=True)
|
| 24 |
+
self.checks.append({'test':'tensor_serialization_exact','file':path,'shape':list(a.shape),'valid_count':int(valid.sum())})
|
| 25 |
+
def video(self,name,path,iterator,mask=False,**kw):
|
| 26 |
+
w,h=self.m['camera']['image_size'];pix='gray16le' if mask else 'rgb24';dtype='<u2' if mask else 'uint8'
|
| 27 |
+
dst=self.p/path;dst.parent.mkdir(parents=True,exist_ok=True);hashes=[]
|
| 28 |
+
proc=subprocess.Popen([FF,'-v','error','-y','-f','rawvideo','-pixel_format',pix,'-video_size',f'{w}x{h}','-framerate','1','-i','pipe:0','-c:v','ffv1','-level','3','-g','1',str(dst)],stdin=subprocess.PIPE)
|
| 29 |
+
try:
|
| 30 |
+
for frame in iterator:
|
| 31 |
+
a=np.asarray(frame,dtype=dtype);assert a.shape==((h,w) if mask else (h,w,3));b=a.tobytes();hashes.append(hashlib.sha256(b).hexdigest());proc.stdin.write(b)
|
| 32 |
+
finally:proc.stdin.close()
|
| 33 |
+
assert proc.wait()==0 and len(hashes)==self.T
|
| 34 |
+
proc=subprocess.Popen([FF,'-v','error','-i',str(dst),'-f','rawvideo','-pix_fmt',pix,'pipe:1'],stdout=subprocess.PIPE)
|
| 35 |
+
nbytes=w*h*(2 if mask else 3)
|
| 36 |
+
for digest in hashes:
|
| 37 |
+
b=proc.stdout.read(nbytes);assert len(b)==nbytes and hashlib.sha256(b).hexdigest()==digest,'video roundtrip'
|
| 38 |
+
assert not proc.stdout.read(1);assert proc.wait()==0
|
| 39 |
+
self.checks.append({'test':'all_frames_pixel_exact_roundtrip','file':path,'frames':self.T})
|
| 40 |
+
self.add(name,path,'segment/uint16_labels/v1' if mask else 'rgb/uint8/v1',['T','height','width'] if mask else ['T','height','width','channel'],np.ones(self.T,bool),storage_fps=1,timebase_role='index_only',**kw)
|
| 41 |
+
def intrinsic(self,K):
|
| 42 |
+
self.m['camera'].update(model='pinhole',schema_id='camera/pinhole/v1')
|
| 43 |
+
self.array('intrinsic','camera/intrinsic.pt','camera/pinhole/v1',np.broadcast_to(K,(self.T,3,3)),np.ones(self.T,bool),['T','row','column'])
|
| 44 |
+
def finish(self):
|
| 45 |
+
lines(self.p/'camera/frames.jsonl',self.frames);save(self.p/'metainfo.json',self.m)
|
| 46 |
+
save(self.root/'doc'/f'{self.m["sequence_id"]}__{self.m["camera_id"]}.checks.json',{'checks':self.checks,'frames':self.T,'input':self.source})
|
| 47 |
+
print('Converted',self.m['dataset_id'],self.m['sequence_id'],self.m['camera_id'],self.T,flush=True)
|
| 48 |
+
|
| 49 |
+
def snapshot(dataset,scripts):
|
| 50 |
+
# Retained for old callers. The organized bundle must not be repopulated at runtime.
|
| 51 |
+
(ROOT/dataset/RELEASE/'script').mkdir(parents=True,exist_ok=True)
|
|
|
|
|
|