|
|
|
# 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
|
|
|
|
|
|
|
|
import torch
|
|
|
|
import numpy
|
|
|
|
import resampy
|
|
|
|
|
|
|
|
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,
|
|
|
|
checkpoint_path: str = None,
|
|
|
|
framework: str = 'pytorch'):
|
|
|
|
super().__init__(framework=framework)
|
|
|
|
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
if params is None:
|
|
|
|
self.params = default_params
|
|
|
|
else:
|
|
|
|
self.params = params
|
|
|
|
|
|
|
|
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...')
|
|
|
|
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)
|
|
|
|
|
|
|
|
log.info('Loading weights...')
|
|
|
|
if checkpoint_path is None:
|
|
|
|
path = str(Path(__file__).parent)
|
|
|
|
checkpoint_path = os.path.join(path, 'saved_model', 'pfann_fma_m.pt')
|
|
|
|
state_dict = torch.load(checkpoint_path, map_location=self.device)
|
|
|
|
self.model.load_state_dict(state_dict)
|
|
|
|
self.model.eval()
|
|
|
|
log.info('Model is loaded.')
|
|
|
|
|
|
|
|
def __call__(self, data: List[AudioFrame]) -> numpy.ndarray:
|
|
|
|
audio_tensors = self.preprocess(data).to(self.device)
|
|
|
|
features = self.model(audio_tensors)
|
|
|
|
return features.detach().cpu().numpy()
|
|
|
|
|
|
|
|
def preprocess(self, frames: List[AudioFrame]):
|
|
|
|
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)
|
|
|
|
audio = audio[None, :]
|
|
|
|
|
|
|
|
audio = self.int2float(audio)
|
|
|
|
|
|
|
|
if sr != self.params['sample_rate']:
|
|
|
|
audio = resampy.resample(audio, sr, self.params['sample_rate'])
|
|
|
|
|
|
|
|
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
|
|
|
|
else:
|
|
|
|
log.warning('Converting float dtype from %s to %s.', wav.dtype, dtype)
|
|
|
|
return wav.astype(dtype)
|