File size: 15,668 Bytes
c74e524
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
"""Build Stage 1 training examples with strict causal context.

One example per assistant turn. The context event stream contains only what a live
system could legally have consumed by `context_cutoff` (the target turn onset plus
one 80 ms tick):

  * user words that the streaming ASR had already committed
  * Mimi prosody pooled only over frames available at that commit tick
  * pauses and backchannels that had already ended
  * tool results whose result_ready_at <= cutoff and that are not stale

The target is the assistant's public spoken text for that turn, plus a native tool
call when the corpus dispatched one during that turn. No hidden reasoning, no
future text, no unplayed assistant audio.
"""
from __future__ import annotations

import argparse
import json
import math
import re
from collections import Counter
from pathlib import Path

ROOT = Path('/workspace/chroma_duplex_demo')
ANN = ROOT / 'annotations/duplex_5k'
ALIGN = ANN / 'alignment_tracks'
STREAM = ANN / 'streaming_asr'
EVENTS = ANN / 'events'
MIMI = ROOT / 'dataset_features/mimi_user'
DATA = ROOT / 'datasets/duplex_5k_extracted'
OUT = ROOT / 'stage1/examples'
FRAME_RATE = 12.5
TICK = 0.08

TOOLS = [
    {"type": "function", "function": {
        "name": "get_weather",
        "description": "Get the weather for a city on a specific date.",
        "parameters": {"type": "object",
                       "properties": {"city": {"type": "string"}, "date": {"type": "string"}},
                       "required": ["city", "date"]}}},
    {"type": "function", "function": {
        "name": "search_local_docs",
        "description": "Search the local product documentation for a policy or fact.",
        "parameters": {"type": "object",
                       "properties": {"query": {"type": "string"}},
                       "required": ["query"]}}},
    {"type": "function", "function": {
        "name": "calculate",
        "description": "Calculate a simple arithmetic expression.",
        "parameters": {"type": "object",
                       "properties": {"expression": {"type": "string"}},
                       "required": ["expression"]}}},
]


def frames(seg, t0, t1):
    if seg is None:
        return None
    t0 = max(float(t0), float(seg['start']))
    t1 = min(float(t1), float(seg['end']))
    if t1 <= t0:
        return None
    # Only frames fully contained in [t0, t1]: a Mimi frame ending after
    # `available_at` would not yet exist at runtime.
    f0 = int(math.floor(seg['frame_start'] + (t0 - seg['start']) * FRAME_RATE))
    f1 = int(math.floor(seg['frame_start'] + (t1 - seg['start']) * FRAME_RATE))
    f0 = max(f0, seg['frame_start'])
    f1 = min(f1, seg['frame_end'])
    if f1 <= f0:
        return None
    return [f0, f1]


def ev_time(e):
    if e['t'] == 'user_word':
        return float(e['available_at'])
    if e['t'] in ('user_event', 'pause'):
        return float(e['end'])
    if e['t'] == 'user_turn_end':
        return float(e['at'])
    if e['t'] == 'assistant':
        return float(e.get('start', 0.0))
    if e['t'] == 'tool_result':
        return float(e['available_at'])
    return 0.0


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--ids', nargs='*')
    ap.add_argument('--limit', type=int, default=0)
    ap.add_argument('--out', default=str(OUT))
    ap.add_argument('--require-prosody', action='store_true')
    args = ap.parse_args()

    rows = [json.loads(l) for l in (ANN / 'manifest.jsonl').read_text().splitlines() if l.strip()]
    if args.ids:
        wanted = set(args.ids)
        rows = [r for r in rows if r['id'] in wanted]
    if args.limit:
        rows = rows[:args.limit]
    print('ROWS', len(rows), flush=True)

    out_root = Path(args.out)
    out_root.mkdir(parents=True, exist_ok=True)
    files = {s: open(out_root / f'{s}.jsonl', 'w', encoding='utf-8')
             for s in ('train', 'val', 'test')}
    stats = Counter()

    for r in rows:
        sid, cohort, split = r['id'], r['cohort'], r['split']
        ann = json.loads((ANN / cohort / f'{sid}.json').read_text())
        ev_p = EVENTS / cohort / f'{sid}.json'
        st_p = STREAM / cohort / f'{sid}.json'
        al_p = ALIGN / cohort / f'{sid}.json'
        if not (ev_p.exists() and st_p.exists() and al_p.exists()):
            stats['skipped_missing_annotation'] += 1
            continue
        ev = json.loads(ev_p.read_text())
        st = json.loads(st_p.read_text())
        al = json.loads(al_p.read_text())
        mp = MIMI / cohort / f'{sid}.npy'
        meta = MIMI / cohort / f'{sid}.json'
        if args.require_prosody and (not mp.exists() or not meta.exists()):
            stats['skipped_no_prosody'] += 1
            continue
        mseg = json.loads(meta.read_text())['segments'] if meta.exists() else []
        seg_by_turn = {}
        for s in mseg:
            seg_by_turn.setdefault((s.get('turn_index'), s.get('kind')), s)
        # Turn audio paths are unique; prefer a path key when available.
        seg_by_path = {str(s.get('path')): s for s in mseg}

        turns = ann['turns']
        st_by_pos = {}
        al_by_pos = {}
        for t in st['turns']:
            st_by_pos[(t.get('turn_index'), t.get('kind'))] = t
        for t in al['turns']:
            al_by_pos[str(t.get('audio'))] = t
        stream_bytes = str(mp) if mp.exists() else None
        assistant_positions = [i for i, t in enumerate(turns) if t['role'] == 'agent']
        # Attach every tool call to the single assistant turn that dispatched it
        # (normally the pre_tool turn of its turn_index), so calls are never
        # duplicated across the pre_tool/final speech pair.
        call_by_pos = {}
        for led in ev.get('tool_ledger') or []:
            d = float(led.get('dispatch_at') or 0.0)
            cands = [i for i in assistant_positions if float(turns[i]['end']) <= d + 0.05]
            pos = max(cands, key=lambda i: float(turns[i]['end'])) if cands else (
                assistant_positions[0] if assistant_positions else None)
            if pos is not None:
                call_by_pos.setdefault(pos, []).append(led)

        sys_text, tools_enabled = '', False
        try:
            tj = json.loads((DATA / cohort / sid / 'text.json').read_text()) or {}
            sys_text = tj.get('system') or ''
            tools_enabled = bool(tj.get('tools_enabled'))
        except Exception:
            pass
        tools_enabled = tools_enabled or bool(ev.get('tool_ledger'))

        for target_i in assistant_positions:
            target = turns[target_i]
            cutoff = float(target['start']) + TICK
            events = []
            last_user = None
            # Prior user speech and boundaries.
            for i, t in enumerate(turns):
                if i >= target_i:
                    break
                if t['role'] != 'user':
                    continue
                last_user = t
                seg = seg_by_path.get(str(t.get('path'))) or seg_by_turn.get(
                    (t.get('turn_index'), t.get('kind')))
                stream_t = st_by_pos.get((t.get('turn_index'), t.get('kind')))
                align_t = al_by_pos.get(str(t.get('path')))
                words = (stream_t or {}).get('words') or []
                committed = [w for w in words if w.get('asr_committed')
                             and float(w['available_at']) <= cutoff]
                for w in committed:
                    pf = frames(seg, float(w['word_time']) - 0.08,
                                min(float(w['word_end']) + 0.16, float(w['available_at'])))
                    events.append({'t': 'user_word', 'text': w['word'],
                                   'available_at': float(w['available_at']),
                                   'word_time': float(w['word_time']),
                                   'word_end': float(w['word_end']),
                                   'turn': t.get('turn_index'), 'kind': t.get('kind'),
                                   'align_source': w.get('source'),
                                   'pf': pf})
                    stats['ctx_words'] += 1
                    if pf is None:
                        stats['word_no_prosody'] += 1
                # Backchannel / very short feedback with no committed text carries
                # its prosody as an event.
                if not committed and float(t['end']) <= cutoff:
                    pf = frames(seg, t['start'], min(float(t['end']), cutoff))
                    if pf:
                        events.append({'t': 'user_event',
                                       'event': 'backchannel' if t.get('kind') == 'backchannel' else 'uncommitted_speech',
                                       'start': float(t['start']), 'end': float(t['end']),
                                       'dur_s': round(float(t['end']) - float(t['start']), 3),
                                       'turn': t.get('turn_index'), 'kind': t.get('kind'),
                                       'pf': pf})
                        stats['ctx_prosody_only'] += 1
                if stream_t and float(stream_t.get('endpoint_at') or 1e9) <= cutoff:
                    events.append({'t': 'user_turn_end',
                                   'at': float(stream_t['endpoint_at']),
                                   'turn': t.get('turn_index'), 'kind': t.get('kind')})
            # Intra-user pauses that had ended before the cutoff.
            for p in ev.get('pauses') or []:
                if p.get('role') != 'user' or float(p['end']) > cutoff:
                    continue
                turn = next((t for t in turns if t.get('turn_index') == p.get('turn_index')
                             and t['role'] == 'user'), None)
                seg = seg_by_path.get(str(turn.get('path'))) if turn else None
                pf = frames(seg, p['start'], min(float(p['end']), cutoff))
                if pf:
                    events.append({'t': 'pause', 'start': float(p['start']),
                                   'end': float(p['end']), 'dur_s': round(float(p['gap']), 3),
                                   'turn': p.get('turn_index'), 'pf': pf})
                    stats['ctx_pauses'] += 1
            # Prior assistant turns and tool calls/results.
            excluded_stale = []
            reused_stale = []
            target_text = str(target.get('text', ''))
            for i, t in enumerate(turns):
                if i >= target_i:
                    break
                if t['role'] != 'agent':
                    continue
                calls = [c for c in (call_by_pos.get(i) or [])
                         if float(c['dispatch_at']) <= cutoff]
                events.append({'t': 'assistant', 'text': t.get('text', ''),
                               'turn': t.get('turn_index'), 'kind': t.get('kind'),
                               'start': float(t['start']), 'end': float(t['end']),
                               'tool_calls': [{k: c[k] for k in
                                               ('call_id', 'name', 'arguments', 'dispatch_at')}
                                              for c in calls]})
                for c in calls:
                    if c.get('result_ready_at') is None or float(c['result_ready_at']) > cutoff:
                        continue
                    is_stale = any(x.get('stale_call_id') == c['call_id']
                                   and float(x.get('end') or 0) <= cutoff
                                   for x in ev.get('stale_results') or [])
                    if is_stale:
                        # A stale result is never treated as current. It may only
                        # enter context when the target itself reuses its values
                        # (e.g. "summarize both results"), and stays flagged.
                        reused = any(isinstance(v, str) and len(v) > 3
                                     and k not in ('date', 'time', 'when')
                                     and re.search(r'\b' + re.escape(v.lower()) + r'\b',
                                                   target_text.lower())
                                     for k, v in (c.get('arguments') or {}).items())
                        if not reused:
                            excluded_stale.append(c)
                            stats['ctx_stale_excluded'] += 1
                            continue
                        reused_stale.append(c)
                        stats['ctx_stale_reused'] += 1
                    events.append({'t': 'tool_result', 'call_id': c['call_id'],
                                   'name': c['name'], 'payload': c.get('result'),
                                   'available_at': float(c['result_ready_at']),
                                   'stale': bool(is_stale),
                                   'reused_in_target': bool(is_stale)})
                    stats['ctx_tool_results'] += 1
            # Target.
            target_calls = [c for c in (call_by_pos.get(target_i) or []) if c.get('name')]
            events.sort(key=ev_time)
            stale_refs = []
            for c in excluded_stale:
                for v in (c.get('arguments') or {}).values():
                    if isinstance(v, str) and len(v) > 2 and v.lower() in target_text.lower():
                        stale_refs.append({'call_id': c['call_id'], 'value': v})
            ex = {
                'example_id': f'{sid}:{target_i}',
                'session': sid, 'cohort': cohort, 'split': split,
                'family': r.get('family') or ann.get('family'),
                'target': {'turn_index': target.get('turn_index'), 'kind': target.get('kind'),
                           'start': float(target['start']), 'end': float(target['end']),
                           'text': target.get('text', ''),
                           'tool_calls': [{k: c[k] for k in ('call_id', 'name', 'arguments')}
                                          for c in target_calls]},
                'context_cutoff': round(cutoff, 4),
                'stale_conflict': bool(stale_refs),
                'stale_refs': stale_refs,
                'stale_reused': [c['call_id'] for c in reused_stale],
                'system': sys_text,
                'tools': TOOLS if tools_enabled else [],
                'events': events,
                'prosody': ({'file': stream_bytes, 'frame_rate': FRAME_RATE, 'dim': 512}
                            if stream_bytes else None),
                'user_last': ({'turn_index': last_user.get('turn_index'),
                               'start': float(last_user['start']),
                               'end': float(last_user['end']),
                               'text': last_user.get('text', ''),
                               'kind': last_user.get('kind')} if last_user else None),
                'session_meta': {'duration': ann['duration'],
                                 'cohort': cohort, 'split': split},
            }
            files[split].write(json.dumps(ex, ensure_ascii=False) + '\n')
            stats[f'examples_{split}'] += 1
            stats['examples'] += 1
        if stats['examples'] and stats['examples'] % 1000 < 5:
            print(json.dumps(dict(stats)), flush=True)

    for f in files.values():
        f.close()
    report = {'sessions': len(rows), 'examples': stats['examples'],
              'by_split': {k: stats[f'examples_{k}'] for k in ('train', 'val', 'test')},
              'stats': dict(stats), 'out': str(out_root)}
    (out_root / 'report.json').write_text(json.dumps(report, indent=1) + '\n')
    print(json.dumps(report, indent=1), flush=True)


if __name__ == '__main__':
    main()