# Copyright 2021 Zilliz. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import logging from pathlib import Path from typing import Union import torchaudio import torch import numpy from towhee.operator import NNOperator from towhee import register sys.path.append(str(Path(__file__).parent)) from clmr_checkpoint import load_encoder_checkpoint from sample_cnn import SampleCNN log = logging.getLogger() @register(output_schema=['vecs']) class ClmrMagnatagatune(NNOperator): """ Pretrained clmr """ def __init__(self, framework="pytorch") -> None: super().__init__(framework=framework) self.device = "cuda" if torch.cuda.is_available() else "cpu" weight_path = os.path.join(str(Path(__file__).parent), 'clmr_checkpoint_10000.pt') state_dict = load_encoder_checkpoint(weight_path, 1) encoder = SampleCNN(strides=[3, 3, 3, 3, 3, 3, 3, 3, 3], supervised=False, out_dim=1) encoder.load_state_dict(state_dict) new_encoder = torch.nn.Sequential(*(list(encoder.children())[:-1])) x = list(new_encoder[0][:10].children()) y = torch.nn.Sequential(*list(new_encoder[0][10].children())[:-1]) x.append(y) self.model = torch.nn.Sequential(*x) self.model.eval() self.model.to(self.device) def __call__(self, audio: Union[str, numpy.ndarray], sample_rate: int = None) -> numpy.ndarray: _sr = 22050 audio_length = 59049 if isinstance(audio, str): source = os.path.abspath(audio) audio, sr = torchaudio.load(source) elif isinstance(audio, numpy.ndarray): sr = sample_rate audio = torch.tensor(audio).to(torch.float32) if sr != _sr: transform = torchaudio.transforms.Resample(orig_freq=sr, new_freq=_sr) audio = transform(audio) with torch.no_grad(): batch = torch.split(audio, audio_length, dim=1) batch = torch.cat(batch[:-1]) batch = batch.unsqueeze(dim=1) batch = batch.to(self.device) features = numpy.squeeze(self.model(batch)) embeddings = features.to("cpu") return embeddings.detach().numpy() # if __name__ == "__main__": # encoder = ClmrMagnatagatune() # # # audio_path = "/audio/path/or/link" # # vec = encoder(audio_path) # # audio_data = numpy.zeros((2, 441344)) # sample_rate = 44100 # vec = encoder(audio_data, sample_rate) # # print(vec.shape)