qgyd2021 commited on
Commit
be75db4
1 Parent(s): 3244151
data/early_media_examples_wav.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:66ac7e2aa7f8fe0b001038f3041b9e8d03a27f30d99c27dab2efe82c93fc6c0f
3
+ size 27919350
examples/channel_dual_to_single.py CHANGED
@@ -15,7 +15,7 @@ def get_args():
15
 
16
  parser.add_argument(
17
  "--wav_dir",
18
- default=(project_path / "data/early_media/60/wav").as_posix(),
19
  type=str
20
  )
21
 
@@ -43,6 +43,8 @@ def main():
43
  continue
44
 
45
  # print(signal.shape)
 
 
46
  signal = signal[:, 0]
47
  # print(signal.shape)
48
 
 
15
 
16
  parser.add_argument(
17
  "--wav_dir",
18
+ default=(project_path / "data/early_media/63/wav").as_posix(),
19
  type=str
20
  )
21
 
 
43
  continue
44
 
45
  # print(signal.shape)
46
+ if signal.ndim != 2:
47
+ continue
48
  signal = signal[:, 0]
49
  # print(signal.shape)
50
 
examples/early_media_and_voicemail/step_1_early_media_and_voicemail.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import argparse
4
+ import os
5
+ from pathlib import Path
6
+ import sys
7
+ import tempfile
8
+ import zipfile
9
+
10
+ pwd = os.path.abspath(os.path.dirname(__file__))
11
+ sys.path.append(os.path.join(pwd, "../../"))
12
+
13
+ import numpy as np
14
+ import pandas as pd
15
+ from scipy.io import wavfile
16
+ import torch
17
+ from tqdm import tqdm
18
+
19
+ from project_settings import project_path
20
+ from toolbox.torch.utils.data.vocabulary import Vocabulary
21
+
22
+
23
+ area_code = 886
24
+
25
+
26
+ def get_args():
27
+ parser = argparse.ArgumentParser()
28
+ parser.add_argument(
29
+ "--voicemail_model_file",
30
+ # default="D:/Users/tianx/VoiceProxyProjects/VoicemailDetection/trained_models/cnn_voicemail_ms_my_20240122.zip",
31
+ # default="D:/Users/tianx/VoiceProxyProjects/VoicemailDetection/trained_models/cnn_voicemail_th_th_20221107.zip",
32
+ default="D:/Users/tianx/VoiceProxyProjects/VoicemailDetection/trained_models/cnn_voicemail_zh_tw_20230814.zip",
33
+ # default=(project_path / "trained_models").as_posix(),
34
+ type=str
35
+ )
36
+ parser.add_argument(
37
+ "--calling_wav_dir",
38
+ default=(project_path / "data/calling/{area_code}/wav".format(area_code=area_code)).as_posix(),
39
+ type=str
40
+ )
41
+ parser.add_argument(
42
+ "--early_media_wav_dir",
43
+ default=(project_path / "data/early_media/{area_code}/wav".format(area_code=area_code)).as_posix(),
44
+ type=str
45
+ )
46
+ parser.add_argument("--output_file", default="result.xlsx", type=str)
47
+
48
+ args = parser.parse_args()
49
+ return args
50
+
51
+
52
+ class VoicemailDetection(object):
53
+ def __init__(self, model_file: str):
54
+ self.model_file = model_file
55
+
56
+ self.model = None
57
+ self.vocabulary = None
58
+ self.load_models()
59
+
60
+ def load_models(self):
61
+ model_file = Path(self.model_file)
62
+ model_name = model_file.stem
63
+
64
+ with zipfile.ZipFile(model_file.as_posix(), "r") as f_zip:
65
+ out_root = Path(tempfile.gettempdir()) / "cnn_voicemail"
66
+ out_root.mkdir(parents=True, exist_ok=True)
67
+ f_zip.extractall(path=out_root)
68
+
69
+ tgt_path = out_root / model_name
70
+ pth_path = tgt_path / "cnn_voicemail.pth"
71
+ vocab_path = tgt_path / "vocabulary"
72
+
73
+ with open(pth_path.as_posix(), "rb") as f:
74
+ model = torch.jit.load(f, map_location="cpu")
75
+ vocabulary = Vocabulary.from_files(vocab_path.as_posix())
76
+ self.model = model
77
+ self.vocabulary = vocabulary
78
+
79
+ def infer(self, inputs: np.ndarray):
80
+ # infer
81
+ inputs = inputs / (1 << 15)
82
+ inputs = torch.tensor(inputs, dtype=torch.float32)
83
+ inputs = torch.unsqueeze(inputs, dim=0)
84
+
85
+ outputs = self.model(inputs)
86
+
87
+ probs = outputs["probs"]
88
+ argmax = torch.argmax(probs, dim=-1)
89
+ probs = probs.tolist()[0]
90
+ argmax = argmax.tolist()[0]
91
+
92
+ label = self.vocabulary.get_token_from_index(argmax, namespace="labels")
93
+ prob = round(probs[argmax], 4)
94
+ return label, prob
95
+
96
+
97
+ def main():
98
+ args = get_args()
99
+
100
+ voicemail_detection = VoicemailDetection(model_file=args.voicemail_model_file)
101
+
102
+ calling_wav_dir = Path(args.calling_wav_dir)
103
+ early_media_wav_dir = Path(args.early_media_wav_dir)
104
+
105
+ result = list()
106
+ for filename in tqdm(calling_wav_dir.glob("**/*.wav")):
107
+ filename = Path(filename)
108
+ call_id = filename.stem.split("_")[-1]
109
+
110
+ # early media
111
+ early_media_filename = None
112
+ for fn in early_media_wav_dir.glob("*/*.wav"):
113
+ basename = fn.stem
114
+
115
+ if str(basename).__contains__(call_id):
116
+ early_media_filename = fn
117
+ break
118
+ if early_media_filename is None:
119
+ continue
120
+ early_media_label = early_media_filename.parts[-2]
121
+
122
+ # read early media signal
123
+ sample_rate, signal = wavfile.read(early_media_filename)
124
+ if sample_rate != 8000:
125
+ raise AssertionError
126
+ if len(signal) < 1.0 * sample_rate:
127
+ continue
128
+ early_media_duration = len(signal) / sample_rate
129
+
130
+ # read calling signal
131
+ sample_rate, signal = wavfile.read(filename)
132
+ if sample_rate != 8000:
133
+ raise AssertionError
134
+ if len(signal) < 1.0 * sample_rate:
135
+ continue
136
+ signal = signal[:, 0]
137
+ calling_duration = len(signal) / sample_rate
138
+
139
+ # voicemail
140
+ calling_label = "non_voicemail"
141
+ last_prob = 0
142
+ for i in range(4):
143
+ begin = i * sample_rate * 2
144
+ end = begin + sample_rate * 2
145
+ if end > len(signal):
146
+ break
147
+ sub_signal = signal[begin:end]
148
+
149
+ label, prob = voicemail_detection.infer(sub_signal)
150
+ if label == "non_voicemail":
151
+ prob = 1.0 - prob
152
+
153
+ if prob > 0.5:
154
+ calling_label = "voicemail"
155
+ break
156
+ if (prob + last_prob) / 2 > 0.5:
157
+ calling_label = "voicemail"
158
+ break
159
+
160
+ if early_media_label in ("voicemail",):
161
+ calling_label = early_media_label
162
+
163
+ # print(early_media_label)
164
+ # print(early_media_duration)
165
+ # print(calling_label)
166
+ # print(calling_duration)
167
+ result.append({
168
+ "call_id": call_id,
169
+ "early_media_filename": early_media_filename.as_posix(),
170
+ "early_media_label": early_media_label,
171
+ "early_media_duration": early_media_duration,
172
+ "calling_filename": filename.as_posix(),
173
+ "calling_label": calling_label,
174
+ "calling_duration": calling_duration,
175
+ })
176
+ result = pd.DataFrame(result)
177
+ result.to_excel(args.output_file, index=False, encoding="utf-8")
178
+ return
179
+
180
+
181
+ if __name__ == '__main__':
182
+ main()
examples/early_media_and_voicemail/step_2_analysis_features.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import argparse
4
+ from collections import Counter
5
+
6
+ import pandas as pd
7
+
8
+
9
+ def get_args():
10
+ parser = argparse.ArgumentParser()
11
+
12
+ parser.add_argument("--excel_file", default="result.xlsx", type=str)
13
+
14
+ args = parser.parse_args()
15
+ return args
16
+
17
+
18
+ def main():
19
+ args = get_args()
20
+
21
+ df = pd.read_excel(args.excel_file)
22
+
23
+ # count
24
+ labels = df["calling_label"].tolist()
25
+ counter = Counter(labels)
26
+ msg = "语音信箱和非语音信箱的数量: \n"
27
+ msg += "label\tcount\n"
28
+ for l, c in counter.most_common():
29
+ row = "{}\t{}\n".format(l, c)
30
+ msg += row
31
+ print(msg)
32
+
33
+ # voicemail labels
34
+ labels = df[df["calling_label"] == "voicemail"]["early_media_label"].tolist()
35
+ voicemail_labels_counter = Counter(labels)
36
+
37
+ msg = "语音信箱的早媒体标签特征: \n"
38
+ msg += "label\tcount\n"
39
+ for l, c in voicemail_labels_counter.most_common():
40
+ row = "{}\t{}\n".format(l, c)
41
+ msg += row
42
+ print(msg)
43
+
44
+ auc = list()
45
+ voicemail_total = len(df[df["calling_label"] == "voicemail"])
46
+ non_voicemail_total = len(df[df["calling_label"] == "non_voicemail"])
47
+ for t in range(60):
48
+ sub_df = df[df["early_media_duration"] > t]
49
+ voicemail_count = len(sub_df[sub_df["calling_label"] == "voicemail"])
50
+ non_voicemail_count = len(sub_df[sub_df["calling_label"] == "non_voicemail"])
51
+ tpr = voicemail_count / voicemail_total
52
+ fpr = non_voicemail_count / non_voicemail_total
53
+ rate = tpr / (fpr + 1e-5)
54
+ auc.append((t, round(tpr, 4), round(fpr, 4), round(rate, 4)))
55
+
56
+ msg = "语音信箱和响铃时长的AUC: \n"
57
+ msg += "t\ttpr\tfpr\trate\n"
58
+ for t, tpr, fpr, rate in auc:
59
+ row = "{}\t{}\t{}\t{}\n".format(t, tpr, fpr, rate)
60
+ msg += row
61
+
62
+ print(msg)
63
+ return
64
+
65
+
66
+ if __name__ == '__main__':
67
+ main()
examples/make_templates/step_1_wav_classification.py CHANGED
@@ -24,7 +24,7 @@ from toolbox.cv2.misc import show_image
24
  from toolbox.python_speech_features.misc import wave2spectrum_image
25
 
26
 
27
- area_code = 60
28
 
29
 
30
  def get_args():
 
24
  from toolbox.python_speech_features.misc import wave2spectrum_image
25
 
26
 
27
+ area_code = 63
28
 
29
 
30
  def get_args():
examples/make_templates/step_2_wav_split.py CHANGED
@@ -18,14 +18,14 @@ from tqdm import tqdm
18
  from project_settings import project_path
19
 
20
 
21
- area_code = 60
22
 
23
 
24
  def get_args():
25
  parser = argparse.ArgumentParser()
26
  parser.add_argument(
27
  "--filename",
28
- default=(project_path / "data/early_media/60/wav/voice/early_vm_e4543473-eab8-4240-8e9c-d5249a1137b5.wav").as_posix(),
29
  type=str
30
  )
31
  parser.add_argument(
 
18
  from project_settings import project_path
19
 
20
 
21
+ area_code = 66
22
 
23
 
24
  def get_args():
25
  parser = argparse.ArgumentParser()
26
  parser.add_argument(
27
  "--filename",
28
+ default=(project_path / "data/early_media/66/wav/voice/early_vm_0ef2743d-341a-4859-960f-520ed3abda07.wav").as_posix(),
29
  type=str
30
  )
31
  parser.add_argument(
examples/make_templates/step_3_move_by_template.py CHANGED
@@ -3,6 +3,7 @@
3
  import argparse
4
  from collections import defaultdict
5
  from glob import glob
 
6
  import os
7
  from pathlib import Path
8
  import shutil
@@ -18,7 +19,7 @@ from project_settings import project_path
18
  from toolbox.python_speech_features.misc import wave2spectrum_image
19
 
20
 
21
- area_code = 60
22
 
23
 
24
  def get_args():
@@ -170,6 +171,10 @@ def main():
170
  templates_dir = Path(args.templates_dir)
171
  wav_dir = Path(args.wav_dir)
172
 
 
 
 
 
173
  def wave_to_spectrum(wave: np.ndarray):
174
  spectrum = wave2spectrum_image(wave=wave, sample_rate=8000)
175
  spectrum = np.array(spectrum, dtype=np.float32)
@@ -197,15 +202,25 @@ def main():
197
  if len(matches) == 0:
198
  continue
199
 
200
- labels = [match['label'] for match in matches]
 
 
 
 
 
 
 
 
 
201
  labels_ = [label for label in labels if label not in ("music",)]
202
 
203
  if len(set(labels_)) > 1:
204
  print("超过两个模板类别被匹配,请检测是否匹配正确。")
205
  print(filename)
206
- # for match in matches:
207
- # print(match)
208
- continue
 
209
 
210
  if len(labels_) == 0:
211
  label = "music"
 
3
  import argparse
4
  from collections import defaultdict
5
  from glob import glob
6
+ import json
7
  import os
8
  from pathlib import Path
9
  import shutil
 
19
  from toolbox.python_speech_features.misc import wave2spectrum_image
20
 
21
 
22
+ area_code = 63
23
 
24
 
25
  def get_args():
 
171
  templates_dir = Path(args.templates_dir)
172
  wav_dir = Path(args.wav_dir)
173
 
174
+ config_json_file = templates_dir / "config.json"
175
+ with open(config_json_file.as_posix(), "r", encoding="utf-8") as f:
176
+ config_json = json.load(f)
177
+
178
  def wave_to_spectrum(wave: np.ndarray):
179
  spectrum = wave2spectrum_image(wave=wave, sample_rate=8000)
180
  spectrum = np.array(spectrum, dtype=np.float32)
 
202
  if len(matches) == 0:
203
  continue
204
 
205
+ matches_ = list()
206
+ for match in matches:
207
+ label = match["label"]
208
+ matches_.append({
209
+ **match,
210
+ "weight": config_json[label]["weight"]
211
+ })
212
+ matches_ = list(sorted(matches_, key=lambda x: x["weight"], reverse=True))
213
+
214
+ labels = [match["label"] for match in matches_]
215
  labels_ = [label for label in labels if label not in ("music",)]
216
 
217
  if len(set(labels_)) > 1:
218
  print("超过两个模板类别被匹配,请检测是否匹配正确。")
219
  print(filename)
220
+ for match in matches_:
221
+ print(match)
222
+ # continue
223
+ labels_ = labels_[:1]
224
 
225
  if len(labels_) == 0:
226
  label = "music"
examples/media_to_resample_dual_channel.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import argparse
4
+ import os
5
+ from pathlib import Path
6
+
7
+ import librosa
8
+ import numpy as np
9
+ from scipy.io import wavfile
10
+ from tqdm import tqdm
11
+
12
+ from project_settings import project_path
13
+
14
+
15
+ def get_args():
16
+ parser = argparse.ArgumentParser()
17
+
18
+ parser.add_argument(
19
+ "--wav_dir",
20
+ # default=(project_path / "data/early_media/60/wav").as_posix(),
21
+ default=(project_path / "data/calling/60/wav").as_posix(),
22
+ type=str
23
+ )
24
+ parser.add_argument("--to_sample_rate", default=16000, type=int)
25
+ parser.add_argument(
26
+ "--output_dir",
27
+ # default="./early_media",
28
+ default="./calling",
29
+ type=str
30
+ )
31
+ args = parser.parse_args()
32
+ return args
33
+
34
+
35
+ def main():
36
+ args = get_args()
37
+
38
+ wav_dir = Path(args.wav_dir)
39
+ output_dir = Path(args.output_dir)
40
+
41
+ max_value = (2 << 15)
42
+
43
+ for filename in tqdm(wav_dir.glob("**/*.wav")):
44
+ filename = Path(filename)
45
+
46
+ signal, sample_rate = librosa.load(filename.as_posix(), sr=args.to_sample_rate)
47
+ signal = np.array(signal * max_value, dtype=np.int16)
48
+
49
+ if signal.ndim != 2:
50
+ signal2 = np.zeros(shape=signal.shape, dtype=np.int16)
51
+ signal = np.stack([signal, signal2], axis=-1)
52
+
53
+ to_filename = output_dir / filename.relative_to(wav_dir)
54
+ to_filename.parent.mkdir(parents=True, exist_ok=True)
55
+ wavfile.write(to_filename.as_posix(), rate=args.to_sample_rate, data=signal)
56
+ return
57
+
58
+
59
+ if __name__ == '__main__':
60
+ main()
requirements.txt CHANGED
@@ -16,3 +16,4 @@ gunicorn==20.1.0
16
  pandas==1.1.5
17
  xlrd==1.2.0
18
  openpyxl==3.0.9
 
 
16
  pandas==1.1.5
17
  xlrd==1.2.0
18
  openpyxl==3.0.9
19
+ librosa==0.10.1