File size: 9,990 Bytes
7e7a152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
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
178
179
"""Auditable auxiliary temporal alignment; original search policy data unchanged.

Auxiliary clips are newly mixed dry recordings with neutral duplicated channels,
NOT rerendered binaural scenes. They teach sound semantics/time, not localization.
Candidate crops are privileged auxiliary inputs only, never policy observations.
"""
import collections
import hashlib
import json
import random
from pathlib import Path


def read(path):
    return [json.loads(line) for line in Path(path).open() if line.strip()]


def sha(path):
    h = hashlib.sha256()
    with Path(path).open('rb') as f:
        for block in iter(lambda: f.read(8 * 1024 * 1024), b''):
            h.update(block)
    return h.hexdigest()


def atomic(path, value):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix('.tmp')
    tmp.write_text(json.dumps(value, indent=2))
    tmp.replace(path)


def active_segment(path):
    import numpy as np
    import soundfile as sf
    from scipy.signal import resample_poly
    import math
    wave, sr = sf.read(path, dtype='float32', always_2d=True)
    assert np.isfinite(wave).all()
    mono = wave.mean(axis=1)
    g = math.gcd(sr, 32000)
    mono = resample_poly(mono, 32000 // g, sr // g).astype('float32')
    hop = 6400
    rms = np.array([np.sqrt(np.mean(mono[i:i+hop] ** 2)) for i in range(0, len(mono)-hop+1, hop)])
    threshold = max(1e-5, float(rms.max()) * 10 ** (-32 / 20)) if len(rms) else 1
    candidates = [i for i in range(max(0, len(rms)-19)) if (rms[i:i+20] > threshold).all()]
    if not candidates:
        raise ValueError('no continuous four-second audible-energy window')
    start = max(candidates, key=lambda i: float(rms[i:i+20].min()))
    x = mono[start*hop:start*hop+128000].copy()
    x *= .12 / max(float(np.sqrt(np.mean(x*x))), 1e-8)
    return x, dict(source_sha256=sha(path), crop_start_s=start*.2,
                   energy_hop_s=.2, relative_threshold_db=-32,
                   minimum_bin_rms=float(rms[start:start+20].min()),
                   audit='automatic energy continuity, not human perceptual certification')


def build(cfg):
    import numpy as np
    import soundfile as sf
    root = Path(cfg['output_root'])/'data'
    root.mkdir(parents=True, exist_ok=True)
    original = Path(cfg['policy_data'])
    source_audit = json.loads((original/'audit.json').read_text())
    assert source_audit['train_validation_test_scene_clip_disjoint']
    proofs, identities, cache = {}, {}, {}
    for split in ['train', 'validation']:
        episodes = read(original/f'{split}_episodes.jsonl')
        assert sha(original/f'{split}_episodes.jsonl') == source_audit['splits'][split]['episodes_sha256']
        assert sha(original/f'{split}.jsonl') == source_audit['splits'][split]['sha256']
        unique = {e['clip_id']: e for e in episodes if e['task'] != 'HOS'}
        identities[split] = {k: {e[k] for e in episodes} for k in ['scene', 'clip_id']}
        rows, rejected, accepted, assets = [], collections.Counter(), [], set()
        for clip, ep in sorted(unique.items()):
            cs = ep['label']['candidates']
            if len(cs) != 2 or cs[0]['noun'] == cs[1]['noun']:
                rejected['ambiguous_same_class'] += 1
                continue
            segments, checks = [], []
            try:
                for c in cs:
                    path = c['dry_audio']
                    if path not in cache:
                        try:
                            cache[path] = active_segment(path)
                        except (OSError, ValueError, AssertionError) as error:
                            cache[path] = str(error)
                    if isinstance(cache[path], str):
                        raise ValueError(cache[path])
                    x, proof = cache[path]
                    segments.append(x)
                    checks.append(proof)
            except (OSError, ValueError, AssertionError):
                rejected['missing_or_noncontinuous_dry_audio'] += 1
                continue
            for order in [0, 1]:
                for longer in [0, 1]:
                    lengths = [4 if i == longer else 2 for i in range(2)]
                    starts = [0., 0.]
                    starts[order] = 1.
                    starts[1-order] = 1. + lengths[order] + 1.
                    mixed = np.zeros(320000, dtype='float32')
                    for i in range(2):
                        part = segments[i][:lengths[i]*32000].copy()
                        fade = np.linspace(0, 1, 640, dtype='float32')
                        part[:640] *= fade
                        part[-640:] *= fade[::-1]
                        mixed[int(starts[i]*32000):int((starts[i]+lengths[i])*32000)] += part
                    mixed *= min(1., .95 / max(float(abs(mixed).max()), 1e-8))
                    wav = root/'audio'/split/f'{clip}_o{order}_l{longer}.wav'
                    wav.parent.mkdir(parents=True, exist_ok=True)
                    sf.write(wav, np.stack([mixed, mixed], axis=1), 32000, subtype='PCM_16')
                    # Verify emitted audio, not just scheduled metadata.
                    actual, sr = sf.read(wav, always_2d=True)
                    energy = np.sqrt(np.mean(actual.reshape(50, 6400, 2)**2, axis=(1, 2)))
                    for i in range(2):
                        bins = energy[int(starts[i]*5):int((starts[i]+lengths[i])*5)]
                        assert (bins > 1e-5).all()
                    active = {b for i in range(2) for b in range(int(starts[i]*5), int((starts[i]+lengths[i])*5))}
                    assert all(energy[b] < 1e-7 for b in range(50) if b not in active)
                    wave_hash = sha(wav)
                    for query, target in [('first', order), ('last', 1-order), ('longer', longer), ('shorter', 1-longer)]:
                        rows.append(dict(id=f'{clip}:o{order}:l{longer}:{query}', clip_id=clip, scene=ep['scene'], split=split,
                            audio_path=str(wav), audio_sha256=wave_hash, panorama=ep['panorama'],
                            candidates=[dict(noun=c['noun'], center=c['center']) for c in cs],
                            query=query, target_index=target, starts=starts, durations=lengths,
                            provenance='constructed dry temporal counterfactual; neutral duplicated stereo; no spatial label'))
            accepted.append(dict(clip_id=clip, source_checks=checks))
            assets.update(c['dry_audio'] for c in cs)
            atomic(root/'build_status.json', dict(split=split, accepted=len(accepted), examined=len(accepted)+sum(rejected.values()), total=len(unique)))
        assert len(accepted) >= (cfg['minimum_alignment_clips'] if split == 'train' else 16), 'Insufficient automatically checked auxiliary audio'
        path = root/f'aux_{split}.jsonl'
        path.write_text(''.join(json.dumps(row)+'\n' for row in rows))
        atomic(root/f'{split}_waveform_audit.json', dict(accepted=accepted,rejected=dict(rejected),human_review=False))
        proofs[split] = dict(rows=len(rows), clips=len(accepted), sha256=sha(path), assets=sorted(assets),rejected=dict(rejected))
    for k in ['scene', 'clip_id']:
        assert not identities['train'][k] & identities['validation'][k]
    atomic(root/'audit.json', dict(phase='complete', auxiliary=proofs,
        train_validation_scene_clip_disjoint=True, policy_audit_sha256=sha(original/'audit.json'),
        shared_dry_assets=len(set(proofs['train']['assets']) & set(proofs['validation']['assets'])),
        caveats=['Auxiliary time windows checked using emitted waveform energy, not human labels.',
                 'Auxiliary neutral stereo does not teach binaural localization.',
                 'Search-policy recordings retain original stereo and existing silver labels.',
                 'Asset/pretraining overlap is not eliminated; scene/clip split is enforced.']))


def auxiliary_batch(row, proc, seed, mode='binding'):
    import torch
    import soundfile as sf
    from training.hvs_audio_fourtask.data import load_image
    from omini.data.staqa_preprocessing import prepare_staqa_waveform
    permutation = [0, 1]
    random.Random(seed).shuffle(permutation)
    question = {'first':'started first', 'last':'started later', 'longer':'lasted longer', 'shorter':'lasted for less time'}[row['query']]
    content, images = [], []
    if mode == 'binding':
        for j, i in enumerate(permutation):
            content += [dict(type='text',text=f'Candidate {"AB"[j]}:'),dict(type='image')]
            images.append(load_image(dict(panorama=row['panorama'], pose=row['candidates'][i]['center'])))
        target = 'AB'[permutation.index(row['target_index'])]
        request = f'Which pictured object made the sound that {question}? Answer only A or B.'
    else:
        target = row['candidates'][row['target_index']]['noun']
        request = f'Name the sound-producing object whose sound {question}. Answer with the object name only.'
    content += [dict(type='text',text='<|audio_start|>'+'<|audio_pad|>'*41+'<|audio_end|>'),dict(type='text',text=request)]
    messages = [dict(role='system',content='Identify objects from audible events. Use the complete recording to compare their timing.'),dict(role='user',content=content)]
    text = proc.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    batch = dict(proc(text=[text], images=images or None, return_tensors='pt'))
    n = batch['input_ids'].shape[1]
    target_ids = torch.tensor([proc.tokenizer.encode(target+'<|im_end|>',add_special_tokens=False)])
    batch['input_ids'] = torch.cat([batch['input_ids'],target_ids],1)
    batch['attention_mask'] = torch.ones_like(batch['input_ids'])
    batch['labels'] = batch['input_ids'].clone()
    batch['labels'][:,:n] = -100
    wave,sr = sf.read(row['audio_path'],dtype='float32',always_2d=True)
    batch['audio'] = prepare_staqa_waveform(wave,sr).unsqueeze(0)
    return batch,n,target