Download tests/test_live_multimodal_overlay.py from Tinghong-Ye22/code-HFD: direct link, hf CLI and curl.
- Browser
- Download file 7.92 kB
-
https://huggingface.co/Tinghong-Ye22/code-HFD/resolve/main/tests/test_live_multimodal_overlay.py
- Command line
-
hf download hf://Tinghong-Ye22/code-HFD/tests/test_live_multimodal_overlay.py
-
curl -L -o test_live_multimodal_overlay.py https://huggingface.co/Tinghong-Ye22/code-HFD/resolve/main/tests/test_live_multimodal_overlay.py
7.92 kB
| from copy import deepcopy | |
| import json | |
| from types import SimpleNamespace | |
| import numpy as np | |
| import pytest | |
| import torch | |
| from psi.data.seed.live_multimodal_overlay import (LiveMultimodalOverlayDataset, | |
| attach_live_packets, available_intervals, continuous_audio, interaction_task, visual_features) | |
| def test_safe_question_gain_preserves_base_and_limits_both_polarities(): | |
| from psi.data.seed.live_multimodal_overlay import safe_question_gain | |
| base = np.array([.99, -.99, 0.], np.float32) | |
| original = base.copy() | |
| clip = np.array([.2, -.2, .1], np.float32) | |
| gain = safe_question_gain(base, clip, .9) | |
| assert 0 < gain < .05 | |
| assert np.abs(base + clip * gain).max() < 1. | |
| np.testing.assert_array_equal(base, original) | |
| assert safe_question_gain(np.zeros(3), clip, .9) == .9 | |
| assert safe_question_gain(np.array([-1.]), np.array([-.2]), .9) == 0 | |
| with pytest.raises(ValueError, match='Non-finite'): | |
| safe_question_gain(np.array([float('nan')]), np.ones(1), 1.) | |
| def test_saturated_audio_falls_back_without_false_qa(tmp_path): | |
| ds = dataset(tmp_path) | |
| for step in ds.raw_dataset[0]['steps']: | |
| if 'audio_waveform' in step: | |
| step['audio_waveform'][:] = -1. | |
| result = ds.compose(ds.raw_dataset[0], forced_mode='qa') | |
| assert result['multimodal_overlay']['mode'] == 'visual-only' | |
| assert result['multimodal_overlay']['question_gain'] == 0 | |
| assert np.all(continuous_audio(result) == -1.) | |
| def source(): | |
| steps = [] | |
| audio = np.linspace(-.002, .002, 25 * 6400 + 3200, dtype=np.float32) | |
| for index in range(500): | |
| step = dict(step_index=index, semantic_window_index=index // 20, | |
| update_semantic_cache=index % 20 == 0, control_label=2 if index < 50 else 0 if index < 150 else 1, | |
| states=np.zeros((1, 36), np.float32), actions=np.ones((30,36), np.float32), | |
| future_progress=np.full((30,5), index, np.float32)) | |
| if index % 20 == 0: | |
| step['audio_waveform'] = audio[index // 20 * 6400:index // 20 * 6400 + 9600] | |
| steps.append(step) | |
| return dict(source_id='test', steps=steps, interaction_mode='turn-taking', session_voice_name='female_01_en', | |
| microphone_speech_intervals=[dict(start_seconds=1.2, end_seconds=3.)]) | |
| def test_audio_only_deployment_packet_matches_training(): | |
| from psi.data.seed.live_multimodal_overlay import live_audio_packet | |
| sample = source() | |
| sample["multimodal_overlay"] = dict(mode="audio-only") | |
| for step in sample["steps"]: | |
| if step["update_semantic_cache"]: | |
| step["stream_input_features"] = torch.ones(2, 3) * step["semantic_window_index"] | |
| step["stream_feature_attention_mask"] = torch.ones(3, dtype=torch.long) | |
| attach_live_packets(sample) | |
| for i, actual in enumerate(sample["swa_packets"]): | |
| step = sample["steps"][i * 20] | |
| expected = live_audio_packet(step["stream_input_features"], step["stream_feature_attention_mask"], i) | |
| assert expected.keys() == actual.keys() | |
| for key in actual: | |
| if isinstance(actual[key], torch.Tensor): | |
| torch.testing.assert_close(actual[key], expected[key], rtol=0, atol=0) | |
| else: | |
| assert actual[key] == expected[key] | |
| def dataset(tmp_path, split='train'): | |
| import wave | |
| wav = tmp_path/'q.wav' | |
| with wave.open(str(wav), 'wb') as handle: | |
| handle.setparams((1, 2, 16000, 0, 'NONE', 'not compressed')) | |
| handle.writeframes(np.rint(32768 * .05 * np.sin(np.arange(16000) * .1)).astype('<i2').tobytes()) | |
| visual = tmp_path/'v.pt' | |
| torch.save({str(n): torch.ones(((n + 1)//2 * 64, 4)) for n in (3,4,5)}, visual) | |
| path = tmp_path/'assets.json' | |
| path.write_text(json.dumps(dict(format='hfd_overlay_assets_v1', assets=[dict( | |
| asset_id='one', split=split, question='Is the sky blue?', answer='yes', voice='female_01_en', | |
| question_audio_path=str(wav), visual_features_path=str(visual), image_path='image.jpg', image_sha256='abc') ]))) | |
| return LiveMultimodalOverlayDataset([source()], [path], split) | |
| def test_all_five_task_labels(task, subtype, expected): | |
| assert interaction_task(dict(interaction_mode=task, disfluency_subtype=subtype)) == expected | |
| def test_overlay_preserves_motion_labels_progress_and_exact_audio_overlap(tmp_path): | |
| ds = dataset(tmp_path) | |
| original = source() | |
| result = ds.compose(original, 'qa') | |
| relation = result['multimodal_overlay'] | |
| assert relation['mode'] == 'qa' and 4. <= relation['question_start'] < relation['question_end'] <= 9.2 | |
| for before, after in zip(original['steps'], result['steps']): | |
| for key in ('states','actions','future_progress','control_label'): | |
| np.testing.assert_array_equal(before[key], after[key]) | |
| audio = continuous_audio(result) | |
| old = continuous_audio(original) | |
| a, b = round(relation['question_start'] * 16000), round(relation['question_end'] * 16000) | |
| assert np.max(np.abs(audio[:a] - old[:a])) <= 1/32768 | |
| assert np.max(np.abs(audio[b:] - old[b:])) <= 1/32768 | |
| assert np.max(np.abs(audio[a:b] - old[a:b])) > .01 | |
| assert 'yes' not in str([s.get('audio_text','') for s in result['steps']]) | |
| repeat = ds.compose(original, 'qa') | |
| assert repeat['multimodal_overlay'] == relation | |
| def test_question_never_overlaps_other_microphone_events(tmp_path): | |
| ds = dataset(tmp_path) | |
| raw = source() | |
| raw['microphone_speech_intervals'].append(dict(start_seconds=4.0, end_seconds=8.0)) | |
| intervals = available_intervals(raw) | |
| assert intervals == [(8.4,9.2)] | |
| result = ds.compose(raw, 'qa') | |
| assert result['multimodal_overlay']['mode'] == 'audio-only' | |
| with pytest.raises(ValueError, match='Missing exact microphone'): | |
| del raw['microphone_speech_intervals'] | |
| ds.compose(raw, 'qa') | |
| def test_voice_and_split_guard(tmp_path): | |
| ds = dataset(tmp_path) | |
| raw = source(); raw['session_voice_name'] = 'male_02_zh' | |
| with pytest.raises(ValueError, match='matching session voice'): | |
| ds.compose(raw, 'qa') | |
| assert ds.compose(raw, 'audio-only')['multimodal_overlay']['mode'] == 'audio-only' | |
| with pytest.raises(ValueError, match='No approved'): | |
| LiveMultimodalOverlayDataset([raw], [tmp_path/'assets.json'], 'val') | |
| def test_rejects_corrupt_camera_features(tmp_path): | |
| path=tmp_path/'bad_visual.pt' | |
| torch.save({str(n):torch.full(((n+1)//2*64,4),float('nan')) for n in (3,4,5)},path) | |
| with pytest.raises(ValueError,match='nonfinite'):visual_features(path) | |
| def test_live_features_match_actual_windows_and_causal_targets(tmp_path, mode): | |
| ds = dataset(tmp_path) | |
| out = ds.compose(source(), mode) | |
| for step in out['steps']: | |
| if step['update_semantic_cache']: | |
| step['stream_input_features'] = np.ones((128,63), np.float32) * step['semantic_window_index'] | |
| step['stream_feature_attention_mask'] = np.ones(63, np.int64) | |
| attach_live_packets(out) | |
| assert len(out['swa_packets']) == 25 | |
| for i, packet in enumerate(out['swa_packets']): | |
| assert packet['input_features'].mean() == i | |
| assert packet['first_window'] == (i == 0) | |
| assert (packet['visual_features'] is None) == (mode == 'audio-only') | |
| if packet['reply_label']: | |
| assert packet['available_seconds'] >= out['multimodal_overlay']['question_end'] | |
| assert packet['answer_target'] == 'yes' | |
| else: | |
| assert packet['answer_target'] == '' | |
| assert sum(p['reply_label'] for p in out['swa_packets']) == (3 if mode == 'qa' else 0) | |