appworld-tmp / reports /update_two_samples.py
hbiny's picture
Upload folder using huggingface_hub
27c779e verified
Raw History Blame Contribute Delete
7.2 kB
#!/usr/bin/env python3
import collections
from datetime import datetime, timezone
import json
from pathlib import Path
import shutil
import sys
sys.dont_write_bytecode=True
from rebuild_appworld_vox import sha, wave_info, NAMES, read, write
ROOT=Path('/mnt/lynx1/datasets/Appworld-vox')
SRC=Path('/home/hbcho/agent/appworld/data/tasks_llm')
TIDS={'5a83b05_2','9871968_3'}
PLAN=Path('/home/hbcho/agent/dataset_rebuild/update_two_selection.json')
rows=[json.loads(s) for s in (ROOT/'manifest.jsonl').read_text().splitlines()]
old={(r['task_id'],r['type']):r for r in rows}
choices=read(PLAN);tasks={tid:next(ROOT.glob('*/'+tid)) for tid in TIDS}
for e in read(ROOT/'reports/file_inventory.json'):
assert sha(ROOT/e['path'])==e['sha256'],e['path']
updates=[]
for group in choices:
assert group['task_id'] in TIDS
assert len(group['selected'])==1,(group['task_id'],group['kind'],'no eligible LLM default')
s=group['selected'][0]
updates.append((group['task_id'],NAMES[group['kind']],Path(s['audio']['path']),s))
for tid in sorted(TIDS):
metas=list((SRC/tid/'audio_natural/clean').glob('*/*/metadata.json'))
assert len(metas)==1
updates.append((tid,'clean',metas[0].parent/'speech.wav',None))
assert len(updates)==14
prepared=[]
for tid,kind,wav,selection in updates:
m=read(wav.parent/'metadata.json');prev=old[(tid,kind)]
assert m['status']=='ok' and m['task_id']==tid and m['speaker_id']==prev['speaker_id']
assert m['original_instruction']==read(tasks[tid]/'specs.json')['instruction']==read(SRC/tid/'annotation.json')['instruction']
assert sha(wav)==m['wav_sha256']
if selection: assert selection['audio']['wav_sha256']==m['wav_sha256']
docs={}
for path,digest in m['source_dependencies'].items():
assert sha(path)==digest,path
docs[Path(path).name]={'original_path':path,'sha256':digest,'document':read(path)}
info=wave_info(wav);sr=info['sample_rate'];intervals=[]
for i,u in enumerate(m.get('utterance_reports',[])):
base=0 if i==0 else m['long_boundaries'][i-1]['end_frame']
for event in u.get('timeline',[]):
if 'output_insert_start_frame' not in event:continue
start=base+event['output_insert_start_frame'];end=base+event['output_insert_end_frame']
assert 0<=start<end<=info['frames']
intervals.append({'utterance_index':i,'event_id':event.get('event_id'),
'kind':'inserted_short_pause','filler':event.get('filler'),'source_before':event.get('source_before'),
'start_frame':start,'end_frame':end,'start_seconds':start/sr,'end_seconds':end/sr})
for b in m['long_boundaries']:
intervals.append({**b,'start_seconds':b['start_frame']/sr,'end_seconds':b['end_frame']/sr})
meta=read(ROOT/prev['metadata'])
meta.update(source_wav=str(wav),audio_info=info,source_metadata=m,source_documents=docs,
llm_selection=selection,inserted_pause_intervals=intervals)
if kind=='clean':
assert not intervals and all(u.get('edited_events')==0 for u in m['utterance_reports'])
meta['import_selection']={'method':'user_requested_clean_original','candidate_count':1,
'llm_semantic_status':'not_checked_by_this_update','same_speaker_as_existing_variants':True}
record={**prev,'variant_id':m['variant_id'],'wav_sha256':m['wav_sha256'],'audio_info':info}
prepared.append((wav,record,meta))
print('PREFLIGHT_PASSED',len(prepared),flush=True)
changes=[]
for source,record,meta in prepared:
before=old[(record['task_id'],record['type'])]
dest=ROOT/record['audio'];tmp=dest.with_suffix('.wav.updating')
shutil.copy2(source,tmp);tmp.chmod(0o644);assert sha(tmp)==record['wav_sha256'];tmp.replace(dest)
write(ROOT/record['metadata'],meta)
changes.append({'task_id':record['task_id'],'type':record['type'],'previous_variant_id':before['variant_id'],
'variant_id':record['variant_id'],'previous_sha256':before['wav_sha256'],'wav_sha256':record['wav_sha256'],
'source_wav':str(source),'changed':before['wav_sha256']!=record['wav_sha256'],
'spoken_utterances':meta['source_metadata']['spoken_utterances']})
replacements={(r['task_id'],r['type']):r for _,r,_ in prepared}
rows=[replacements.get((r['task_id'],r['type']),r) for r in rows]
for tid,sample in tasks.items():
shutil.copy2(SRC/tid/'annotation.json',sample/'annotation.json');(sample/'annotation.json').chmod(0o644)
v=read(sample/'variants.json')
v['available']={r['type']:r for r in rows if r['task_id']==tid}
write(sample/'variants.json',v)
(ROOT/'manifest.jsonl').write_text(''.join(json.dumps(r,ensure_ascii=False)+'\n' for r in rows))
stats=read(ROOT/'statistics.json')
stats.update(total_audio_seconds=sum(r['audio_info']['duration_seconds'] for r in rows),
minimum_audio_seconds=min(r['audio_info']['duration_seconds'] for r in rows),
maximum_audio_seconds=max(r['audio_info']['duration_seconds'] for r in rows))
write(ROOT/'statistics.json',stats)
report_rel='reports/sample_update_20261019.json'
doc=ROOT/'README.md';text=doc.read_text().replace('the clean import report records the current seven-condition validation.',
'the latest sample-update report records the current seven-condition validation.')
text+='\nSample audio refresh (2026-10-19): `5a83b05_2` and `9871968_3` were updated from the regenerated source outputs, including clean. The six perturbation types use the latest eligible annotation-review LLM defaults; clean uses the regenerated original. Annotation normalization, metadata, pause intervals and manifest hashes were refreshed. See [reports/sample_update_20261019.json](reports/sample_update_20261019.json) for before/after hashes, actual utterances and current validation. Earlier snapshot/import reports are historical.\n'
doc.write_text(text)
policy=read(ROOT/'reports/inventory_policy.json')
if report_rel not in policy['excluded_paths']:policy['excluded_paths'].append(report_rel)
write(ROOT/'reports/inventory_policy.json',policy)
write(ROOT/'reports/sample_update_selection_20261019.json',choices)
shutil.copy2(__file__,ROOT/'reports/update_two_samples.py')
for p in ROOT.rglob('*'):
if p.is_file():p.chmod(p.stat().st_mode|0o444)
inventory=[{'path':str(p.relative_to(ROOT)),'sha256':sha(p),'bytes':p.stat().st_size}
for p in sorted(ROOT.rglob('*')) if p.is_file() and str(p.relative_to(ROOT)) not in policy['excluded_paths']]
write(ROOT/'reports/file_inventory.json',inventory)
validator=ROOT/'tools/validate_dataset.py';scope={'__name__':'update_validator','__file__':str(validator)}
exec(compile(validator.read_text(),str(validator),'exec'),scope)
validation=scope['validate'](ROOT)
assert all(sha(ROOT/r['audio'])==r['wav_sha256'] for key,r in old.items() if key[0] not in TIDS)
report={'updated_at_utc':datetime.now(timezone.utc).isoformat(),'updated_samples':sorted(TIDS),
'wav_changes':changes,'other_samples_unchanged':True,'validation':validation}
write(ROOT/report_rel,report);(ROOT/report_rel).chmod(0o644)
print(json.dumps({'updated_wavs':sum(c['changed'] for c in changes),'changes':changes,'validation':validation},ensure_ascii=False,indent=2),flush=True)