| |
| import sys |
| import os |
| sys.path.append(os.path.dirname(os.path.abspath(__file__))) |
|
|
| from model import CLAPEncoder |
| import torch |
| import torchaudio |
|
|
| def main(): |
| |
| model = CLAPEncoder() |
| model.load_pretrained() |
| model.eval() |
| |
| |
| audio_path = "/home/karan/sda_link/GitHub/EMMA2/EMMA2_contextual/experiments/emma2_txt_cond_128_2targets/single_source_extraction/test_outputs/000/gt.wav" |
| |
| |
| texts = ["car horn", "baby crying", "child speaking", "gunshot", "car horn on the left", "car horn on the right", "car horn in front", "car horn in front-left", "car horn in front-right"] |
| |
| |
| waveform, sr = torchaudio.load(audio_path) |
| if sr != 16000: |
| resampler = torchaudio.transforms.Resample(orig_freq=sr, new_freq=16000) |
| waveform = resampler(waveform) |
| |
| |
| if waveform.shape[0] == 1: |
| waveform = waveform.repeat(2, 1) |
| elif waveform.shape[0] > 2: |
| waveform = waveform[:2, :] |
| |
| |
| audio = waveform.unsqueeze(0) |
| |
| |
| with torch.no_grad(): |
| audio_embedding = model.embed_audio(audio) |
| |
| |
| print("Similarity scores:") |
| for text in texts: |
| with torch.no_grad(): |
| text_embedding = model.embed_text([text]) |
| |
| |
| audio_norm = torch.nn.functional.normalize(audio_embedding, dim=-1) |
| text_norm = torch.nn.functional.normalize(text_embedding, dim=-1) |
| similarity = torch.cosine_similarity(audio_norm, text_norm, dim=-1).item() |
| |
| print(f"'{text}': {similarity:.6f}") |
|
|
| if __name__ == "__main__": |
| main() |