xref: /aosp_15_r20/external/libopus/dnn/torch/lpcnet/utils/data.py (revision a58d3d2adb790c104798cd88c8a3aff4fa8b82cc)
1"""
2/* Copyright (c) 2023 Amazon
3   Written by Jan Buethe */
4/*
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions
7   are met:
8
9   - Redistributions of source code must retain the above copyright
10   notice, this list of conditions and the following disclaimer.
11
12   - Redistributions in binary form must reproduce the above copyright
13   notice, this list of conditions and the following disclaimer in the
14   documentation and/or other materials provided with the distribution.
15
16   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
20   OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27*/
28"""
29
30import os
31
32import torch
33import numpy as np
34
35def load_features(feature_file, version=2):
36    if version == 2:
37        layout = {
38            'cepstrum': [0,18],
39            'periods': [18, 19],
40            'pitch_corr': [19, 20],
41            'lpc': [20, 36]
42            }
43        frame_length = 36
44
45    elif version == 1:
46        layout = {
47            'cepstrum': [0,18],
48            'periods': [36, 37],
49            'pitch_corr': [37, 38],
50            'lpc': [39, 55],
51            }
52        frame_length = 55
53    else:
54        raise ValueError(f'unknown feature version: {version}')
55
56
57    raw_features = torch.from_numpy(np.fromfile(feature_file, dtype='float32'))
58    raw_features = raw_features.reshape((-1, frame_length))
59
60    features = torch.cat(
61        [
62            raw_features[:, layout['cepstrum'][0]   : layout['cepstrum'][1]],
63            raw_features[:, layout['pitch_corr'][0] : layout['pitch_corr'][1]]
64        ],
65        dim=1
66    )
67
68    lpcs = raw_features[:, layout['lpc'][0]   : layout['lpc'][1]]
69    periods = (0.1 + 50 * raw_features[:, layout['periods'][0] : layout['periods'][1]] + 100).long()
70
71    return {'features' : features, 'periods' : periods, 'lpcs' : lpcs}
72
73
74
75def create_new_data(signal_path, reference_data_path, new_data_path, offset=320, preemph_factor=0.85):
76    ref_data = np.memmap(reference_data_path, dtype=np.int16)
77    signal = np.memmap(signal_path, dtype=np.int16)
78
79    signal_preemph_path = os.path.splitext(signal_path)[0] + '_preemph.raw'
80    signal_preemph = np.memmap(signal_preemph_path, dtype=np.int16, mode='write', shape=signal.shape)
81
82
83    assert len(signal) % 160 == 0
84    num_frames = len(signal) // 160
85    mem = np.zeros(1)
86    for fr in range(len(signal)//160):
87        signal_preemph[fr * 160 : (fr + 1) * 160] = np.convolve(np.concatenate((mem, signal[fr * 160 : (fr + 1) * 160])), [1, -preemph_factor], mode='valid')
88        mem = signal[(fr + 1) * 160 - 1 : (fr + 1) * 160]
89
90    new_data = np.memmap(new_data_path, dtype=np.int16, mode='write', shape=ref_data.shape)
91
92    new_data[:] = 0
93    N = len(signal) - offset
94    new_data[1 : 2*N + 1: 2] = signal_preemph[offset:]
95    new_data[2 : 2*N + 2: 2] = signal_preemph[offset:]
96
97
98def parse_warpq_scores(output_file):
99    """ extracts warpq scores from output file """
100
101    with open(output_file, "r") as f:
102        lines = f.readlines()
103
104    scores = [float(line.split("WARP-Q score:")[-1]) for line in lines if line.startswith("WARP-Q score:")]
105
106    return scores
107
108
109def parse_stats_file(file):
110
111    with open(file, "r") as f:
112        lines = f.readlines()
113
114    mean     = float(lines[0].split(":")[-1])
115    bt_mean  = float(lines[1].split(":")[-1])
116    top_mean = float(lines[2].split(":")[-1])
117
118    return mean, bt_mean, top_mean
119
120def collect_test_stats(test_folder):
121    """ collects statistics for all discovered metrics from test folder """
122
123    metrics = {'pesq', 'warpq', 'pitch_error', 'voicing_error'}
124
125    results = dict()
126
127    content = os.listdir(test_folder)
128
129    stats_files = [file for file in content if file.startswith('stats_')]
130
131    for file in stats_files:
132        metric = file[len("stats_") : -len(".txt")]
133
134        if metric not in metrics:
135            print(f"warning: unknown metric {metric}")
136
137        mean, bt_mean, top_mean = parse_stats_file(os.path.join(test_folder, file))
138
139        results[metric] = [mean, bt_mean, top_mean]
140
141    return results
142