# 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 logging import warnings import os from pathlib import Path from typing import List, Union import torch import torchaudio import numpy import onnxruntime from towhee.operator.base import NNOperator from towhee import register from towhee.types.audio_frame import AudioFrame from towhee.models.nnfp import NNFp from towhee.models.utils.audio_preprocess import preprocess_wav, MelSpec from .configs import default_params warnings.filterwarnings('ignore') log = logging.getLogger() @register(output_schema=['vecs']) class NNFingerprint(NNOperator): """ Audio embedding operator using Neural Network Fingerprint """ def __init__(self, params: dict = None, model_path: str = None, framework: str = 'pytorch', device: str = None ): super().__init__(framework=framework) if device is None: device = 'cuda' if torch.cuda.is_available() else 'cpu' self.device = device if params is None: self.params = default_params else: self.params = params log.info('Loading model...') if model_path is None: path = str(Path(__file__).parent) model_path = os.path.join(path, 'saved_model', 'nnfp_fma.pt') if model_path.endswith('.onnx'): log.warning('Using onnx.') self.model = onnxruntime.InferenceSession( model_path, providers=['CPUExecutionProvider'] if self.device == 'cpu' else ['CUDAExecutionProvider'] ) else: try: state_dict = torch.jit.load(model_path, map_location=self.device) except Exception: state_dict = torch.load(model_path, map_location=self.device) if isinstance(state_dict, torch.nn.Module): self.model = state_dict else: dim = self.params['dim'] h = self.params['h'] u = self.params['u'] f_bin = self.params['n_mels'] n_seg = int(self.params['segment_size'] * self.params['sample_rate']) t = (n_seg + self.params['hop_length'] - 1) // self.params['hop_length'] log.info('Creating model with parameters...') self.model = NNFp( dim=dim, h=h, u=u, in_f=f_bin, in_t=t, fuller=self.params['fuller'], activation=self.params['activation'] ).to(self.device) self.model.load_state_dict(state_dict) self.model.eval() log.info('Model is loaded.') def __call__(self, data: Union[str, List[AudioFrame]]) -> numpy.ndarray: audio_tensors = self.preprocess(data) if audio_tensors.device != self.device: audio_tensors = audio_tensors.to(self.device) # print(audio_tensors.shape) if isinstance(self.model, onnxruntime.InferenceSession): audio_numpy = audio_tensors.detach().cpu().numpy() if audio_tensors.requires_grad \ else audio_tensors.cpu().numpy() ort_inputs = {self.model.get_inputs()[0].name: audio_numpy} outs = self.model.run(None, ort_inputs)[0] else: features = self.model(audio_tensors) outs = features.detach().cpu().numpy() return outs def preprocess(self, frames: Union[str, List[AudioFrame]]): if isinstance(frames, str): audio, sr = torchaudio.load(frames) else: sr = frames[0].sample_rate layout = frames[0].layout if layout == 'stereo': frames = [frame.reshape(-1, 2) for frame in frames] audio = numpy.vstack(frames).transpose() else: audio = numpy.hstack(frames) if len(audio.shape) == 1: audio = audio[None, :] audio = self.int2float(audio, dtype='float32') audio = torch.from_numpy(audio) assert len(audio.shape) == 2 if sr != self.params['sample_rate']: resampler = torchaudio.transforms.Resample(sr, self.params['sample_rate'], dtype=audio.dtype) audio = resampler(audio) wav = preprocess_wav(audio, segment_size=int(self.params['sample_rate'] * self.params['segment_size']), hop_size=int(self.params['sample_rate'] * self.params['hop_size']), frame_shift_mul=self.params['frame_shift_mul']).to(self.device) wav = wav.to(torch.float32) mel = MelSpec(sample_rate=self.params['sample_rate'], window_length=self.params['window_length'], hop_length=self.params['hop_length'], f_min=self.params['f_min'], f_max=self.params['f_max'], n_mels=self.params['n_mels'], naf_mode=self.params['naf_mode'], mel_log=self.params['mel_log'], spec_norm=self.params['spec_norm']).to(self.device) wav = mel(wav) return wav @staticmethod def int2float(wav: numpy.ndarray, dtype: str = 'float64'): """ Convert audio imgs from int to float. The input dtype must be integers. The output dtype is controlled by the parameter `dtype`, defaults to 'float64'. The code is inspired by https://github.com/mgeier/python-audio/blob/master/audio-files/utility.py """ dtype = numpy.dtype(dtype) assert dtype.kind == 'f' if wav.dtype.kind in 'iu': # ii = numpy.iinfo(wav.dtype) # abs_max = 2 ** (ii.bits - 1) # offset = ii.min + abs_max # return (wav.astype(dtype) - offset) / abs_max if wav.dtype != 'int16': wav = (wav >> 16).astype(numpy.int16) assert wav.dtype == 'int16' wav = (wav / 32768.0).astype(dtype) return wav else: log.warning('Converting float dtype from %s to %s.', wav.dtype, dtype) return wav.astype(dtype) def save_model(self, format: str = 'pytorch', path: str = 'default'): if path == 'default': path = str(Path(__file__).parent) path = os.path.join(path, 'saved', format) os.makedirs(path, exist_ok=True) name = 'nnfp' path = os.path.join(path, name) dummy_input = torch.rand( (1,) + (self.params['n_mels'], self.params['u']) ).to(self.device) if format == 'pytorch': path = path + '.pt' torch.save(self.model, path) elif format == 'torchscript': path = path + '.pt' try: try: jit_model = torch.jit.script(self.model) except Exception: log.warning( 'Failed to directly export as torchscript.' 'Using dummy input in shape of %s now.', dummy_input.shape) jit_model = torch.jit.trace(self.model, dummy_input, strict=False) torch.jit.save(jit_model, path) except Exception as e: log.error('Fail to save as torchscript: %s.', e) raise RuntimeError(f'Fail to save as torchscript: {e}.') elif format == 'onnx': path = path + '.onnx' try: torch.onnx.export(self.model, dummy_input, path, input_names=['input'], output_names=['output'], opset_version=12, do_constant_folding=True, dynamic_axes={'input': {0: 'batch_size'}, 'output': {0: 'batch_size'} } ) except Exception as e: log.error(f'Fail to save as onnx: {e}.') raise RuntimeError(f'Fail to save as onnx: {e}.') # todo: elif format == 'tensorrt': else: log.error(f'Unsupported format "{format}".') def input_schema(self): return [(AudioFrame, (1024,))] def output_schema(self): return [(numpy.ndarray, (-1, self.params['dim']))]