appworld-tmp / reports /import_clean.py
hbiny's picture
Upload folder using huggingface_hub
27c779e verified
Raw History Blame Contribute Delete
11.7 kB
#!/usr/bin/env python3
"""Import clean originals without altering any existing perturbation audio."""
import collections
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import shutil
import sys
import wave
sys.dont_write_bytecode = True
ROOT=Path('/mnt/lynx1/datasets/Appworld-vox')
SOURCE=Path('/home/hbcho/agent/appworld/data/tasks_llm')
def load(p): return json.loads(p.read_text())
def sha(p):
h=hashlib.sha256()
with p.open('rb') as f:
for b in iter(lambda:f.read(1048576),b''):h.update(b)
return h.hexdigest()
def write(p,o):
p.parent.mkdir(parents=True,exist_ok=True)
tmp=p.with_name(p.name+'.tmp-clean')
tmp.write_text(json.dumps(o,ensure_ascii=False,indent=2)+'\n');tmp.chmod(0o644);tmp.replace(p)
def wav_info(p):
with wave.open(str(p),'rb') as w:
info={'sample_rate':w.getframerate(),'frames':w.getnframes(),'channels':w.getnchannels(),
'sample_width_bytes':w.getsampwidth()}
assert len(w.readframes(w.getnframes()))==info['frames']*info['channels']*info['sample_width_bytes']
info['duration_seconds']=info['frames']/info['sample_rate']
return info
rows=[json.loads(s) for s in (ROOT/'manifest.jsonl').read_text().splitlines()]
assert not any(r['type']=='clean' for r in rows), 'Clean already imported; do not overwrite'
for e in load(ROOT/'reports/file_inventory.json'):
assert sha(ROOT/e['path'])==e['sha256'], e['path']
original_rows=rows.copy()
plans=[]
for split,ids in load(ROOT/'splits.json').items():
for tid in ids:
sample=ROOT/split/tid
metas=list((SOURCE/tid/'audio_natural/clean').glob('*/*/metadata.json'))
assert len(metas)==1, (tid,len(metas))
m=load(metas[0]);wav=metas[0].parent/'speech.wav'
assert m['task_id']==tid and m['type']=='clean' and m['status']=='ok'
assert m['original_instruction']==load(sample/'specs.json')['instruction']
assert sha(wav)==m['wav_sha256']
assert not m['long_boundaries']
assert all(not u.get('timeline') and u.get('edited_events')==0 for u in m['utterance_reports'])
assert {r['speaker_id'] for r in rows if r['task_id']==tid}=={m['speaker_id']}, 'Speaker mismatch: '+tid
dependencies={}
for p,h in m['source_dependencies'].items():
p=Path(p);assert sha(p)==h
dependencies[p.name]={'original_path':str(p),'sha256':h,'document':load(p)}
assert not (sample/'audio/clean.wav').exists() and not (sample/'metadata/clean.json').exists()
plans.append((sample,wav,m,dependencies,wav_info(wav)))
print('PREFLIGHT_PASSED',len(plans),flush=True)
imported=[]
for sample,src,m,dependencies,info in plans:
wav=sample/'audio/clean.wav';mp=sample/'metadata/clean.json'
# Source bytes and dependencies were checked before any dataset mutation.
assert sha(src)==m['wav_sha256']
shutil.copy2(src,wav);wav.chmod(0o644)
assert sha(wav)==m['wav_sha256']
meta={'schema_version':'1.0','task_id':sample.name,'type':'clean','source_type':'clean',
'source_wav':str(src),'audio_info':info,'llm_selection':None,
'import_selection':{'method':'user_requested_clean_original','candidate_count':1,
'llm_semantic_status':'not_checked_by_this_import',
'same_speaker_as_existing_variants':True},
'source_metadata':m,'source_documents':dependencies,'inserted_pause_intervals':[],
'timing_notes':{'interval_coordinate_system':'final exported WAV; zero-based frames; end exclusive',
'clean_condition':'No generated fillers or inserted short/long pauses; natural speech may include natural pauses.',
'verification':'Source ASR and quality flags preserved; no new human listening or semantic judgment.'}}
write(mp,meta)
record={'task_id':sample.name,'family_id':sample.name.rsplit('_',1)[0],'split':sample.parent.name,
'type':'clean','source_type':'clean','variant_id':m['variant_id'],
'audio':str(wav.relative_to(ROOT)),'metadata':str(mp.relative_to(ROOT)),
'wav_sha256':m['wav_sha256'],'audio_info':info,'expected_control_intent':'execute','speaker_id':m['speaker_id']}
v=load(sample/'variants.json');v['available']['clean']=record;v.pop('clean',None)
write(sample/'variants.json',v)
rows.append(record);imported.append(record)
(ROOT/'manifest.jsonl').write_text(''.join(json.dumps(r,ensure_ascii=False)+'\n' for r in rows))
stats=load(ROOT/'statistics.json')
stats.update(wavs=len(rows),type_counts=dict(collections.Counter(r['type'] for r in rows)),
split_wav_counts=dict(collections.Counter(r['split'] for r in rows)),
speaker_id_counts=dict(collections.Counter(r['speaker_id'] for r in rows)),
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),
sample_rates_hz=sorted({r['audio_info']['sample_rate'] for r in rows}),
channels=sorted({r['audio_info']['channels'] for r in rows}),
sample_width_bytes=sorted({r['audio_info']['sample_width_bytes'] for r in rows}))
stats['complete_seven_type_samples']=stats['complete_six_type_samples']
write(ROOT/'statistics.json',stats)
validator=ROOT/'tools/validate_dataset.py'
text=validator.read_text().replace("TYPES = {'filler'", "PERTURBATION_TYPES = {'filler'",1)
text=text.replace('\ndef digest(path):',"\nTYPES = PERTURBATION_TYPES | {'clean'}\n\ndef digest(path):",1)
old=""" assert m['llm_selection']['is_default']
assert m['llm_selection']['audio_semantic']['status'] == 'equivalent'
"""
new=""" if r['type'] == 'clean':
assert m['llm_selection'] is None
assert m['import_selection']['method'] == 'user_requested_clean_original'
assert not m['inserted_pause_intervals'] and not m['source_metadata']['long_boundaries']
assert all(not u.get('timeline') and u.get('edited_events') == 0 for u in m['source_metadata']['utterance_reports'])
else:
assert m['llm_selection']['is_default']
assert m['llm_selection']['audio_semantic']['status'] == 'equivalent'
"""
assert old in text;text=text.replace(old,new)
text=text.replace("'complete_six_type_samples':sum(set(a)==TYPES for a in samples.values()),",
"'complete_six_type_samples':sum(PERTURBATION_TYPES <= set(a) for a in samples.values()),\n 'complete_seven_type_samples':sum(set(a)==TYPES for a in samples.values()),")
assert text!=validator.read_text();validator.write_text(text)
readme=ROOT/'README.md';text=readme.read_text()
text=text.replace('1,086 WAVs','1,275 WAVs').replace('317 WAVs','371 WAVs').replace('769 WAVs','904 WAVs')
text=text.replace('Clean audio is intentionally excluded.','Clean baseline audio is included for all 189 samples, using the same per-sample speaker as the existing variants.')
text=text.replace('1,086 independent tasks','1,275 independent tasks')
text=text.replace('| filler | 181 |','| clean | 189 | execute | Original normalized instruction with no generated fillers or inserted pauses. |\n| filler | 181 |',1)
text=text.replace('162 samples have all six types.','162 samples have all six perturbation types plus clean (seven conditions).')
text=text.replace('Up to six WAVs','Up to seven WAVs')
text=text.replace('one sample\'s task and database.',"one sample's task and database.")
text=text.replace('IDs with six available types (162 samples).','IDs with all six perturbation types (162 samples); these also have clean audio.')
text=text.replace('The first four types target task execution','Clean and the first four perturbation types target task execution')
text=text.replace('Selection follows the LLM default recommendation','For the six perturbation types, selection follows the LLM default recommendation')
text=text.replace('Human Yes/No reviews are preserved but do not drive this LLM selection.','Human Yes/No reviews are preserved but do not drive this LLM selection. Clean originals were subsequently imported at user request from `tasks_llm/<task_id>/audio_natural/clean/`; each has exactly one source candidate. Their generation ASR and quality flags are preserved, but this import did not add LLM semantic or human listening approval. Clean metadata uses `llm_selection: null` and records `import_selection` instead.')
text += '\nClean import: [reports/clean_import.json](reports/clean_import.json) lists all 189 sources, destination records and validation results. Earlier selection, lifecycle and documentation audit reports describe the initial six-type export; the clean import report records the current seven-condition validation. Existing perturbation WAVs, including previously identified semantic issues, were not replaced or reselected.\n'
readme.write_text(text)
fmt=ROOT/'docs/FORMAT.md';text=fmt.read_text()
text=text.replace('`filler`, `false-start`, `addition`, `revision`, `cancel`, `halt`.','`clean`, `filler`, `false-start`, `addition`, `revision`, `cancel`, `halt`.')
text=text.replace('`filler`, `false_start`, `addition`, `revision`, `cancellation`, `ambiguous_halt`.','`clean`, `filler`, `false_start`, `addition`, `revision`, `cancellation`, `ambiguous_halt`.')
text=text.replace('`execute` for the first four types','`execute` for clean and the first four perturbation types')
text=text.replace(' and a `clean` exclusion marker','')
text=text.replace('or silently create clean audio','or silently synthesize replacement audio')
text += '\n## Clean baseline addition\n\nAll 189 samples include clean audio from the later `audio_natural/clean` generation, with the same per-sample TTS speaker as the perturbation variants. No generated fillers or inserted silence edits are present; natural pauses can still occur. Clean `llm_selection` is null and `import_selection` identifies the user-requested singleton import and its verification scope. ASR/WER and generation quality flags are retained without inventing an LLM semantic pass. `reports/clean_import.json` records the current full export verification; older audit reports describe earlier export stages.\n'
fmt.write_text(text)
policy=load(ROOT/'reports/inventory_policy.json')
policy['excluded_paths'].append('reports/clean_import.json');write(ROOT/'reports/inventory_policy.json',policy)
shutil.copy2(__file__,ROOT/'reports/import_clean.py')
# Preserve readability of both imported and updated files.
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)
scope={'__name__':'clean_import_validator','__file__':str(validator)}
exec(compile(validator.read_text(),str(validator),'exec'),scope)
result=scope['validate'](ROOT)
assert all(sha(ROOT/r['audio'])==r['wav_sha256'] for r in original_rows)
report={'imported_at_utc':datetime.now(timezone.utc).isoformat(),'clean_wavs_added':len(imported),
'selection_method':'user_requested_clean_original; no new LLM approval',
'existing_perturbation_wavs_unchanged':True,'known_semantic_issues_not_modified':True,
'imports':imported,'validation':result}
write(ROOT/'reports/clean_import.json',report)
print(json.dumps({k:v for k,v in report.items() if k!='imports'},indent=2),flush=True)