Ricecake123 commited on
Commit
7fe2fda
1 Parent(s): 9fbdbfa

Upload extract_feature_print.py

Browse files
Files changed (1) hide show
  1. extract_feature_print.py +117 -0
extract_feature_print.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, sys, traceback
2
+
3
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
4
+ os.environ["PYTORCH_MPS_HIGH_WATERMARK_RATIO"] = "0.0"
5
+
6
+ device=sys.argv[1]
7
+ n_part = int(sys.argv[2])
8
+ i_part = int(sys.argv[3])
9
+ if len(sys.argv) == 6:
10
+ exp_dir = sys.argv[4]
11
+ version = sys.argv[5]
12
+ else:
13
+ i_gpu = sys.argv[4]
14
+ exp_dir = sys.argv[5]
15
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(i_gpu)
16
+ version = sys.argv[6]
17
+ import torch
18
+ import torch.nn.functional as F
19
+ import soundfile as sf
20
+ import numpy as np
21
+ from fairseq import checkpoint_utils
22
+
23
+ f = open("%s/extract_f0_feature.log" % exp_dir, "a+")
24
+
25
+
26
+ def printt(strr):
27
+ print(strr)
28
+ f.write("%s\n" % strr)
29
+ f.flush()
30
+
31
+
32
+ printt(sys.argv)
33
+ model_path = "hubert_base.pt"
34
+
35
+ printt(exp_dir)
36
+ wavPath = "%s/1_16k_wavs" % exp_dir
37
+ outPath = (
38
+ "%s/3_feature256" % exp_dir if version == "v1" else "%s/3_feature768" % exp_dir
39
+ )
40
+ os.makedirs(outPath, exist_ok=True)
41
+
42
+
43
+ # wave must be 16k, hop_size=320
44
+ def readwave(wav_path, normalize=False):
45
+ wav, sr = sf.read(wav_path)
46
+ assert sr == 16000
47
+ feats = torch.from_numpy(wav).float()
48
+ if feats.dim() == 2: # double channels
49
+ feats = feats.mean(-1)
50
+ assert feats.dim() == 1, feats.dim()
51
+ if normalize:
52
+ with torch.no_grad():
53
+ feats = F.layer_norm(feats, feats.shape)
54
+ feats = feats.view(1, -1)
55
+ return feats
56
+
57
+
58
+ # HuBERT model
59
+ printt("load model(s) from {}".format(model_path))
60
+ # if hubert model is exist
61
+ if os.access(model_path, os.F_OK) == False:
62
+ printt(
63
+ "Error: Extracting is shut down because %s does not exist, you may download it from https://huggingface.co/lj1995/VoiceConversionWebUI/tree/main"
64
+ % model_path
65
+ )
66
+ exit(0)
67
+ models, saved_cfg, task = checkpoint_utils.load_model_ensemble_and_task(
68
+ [model_path],
69
+ suffix="",
70
+ )
71
+ model = models[0]
72
+ model = model.to(device)
73
+ printt("move model to %s" % device)
74
+ if device not in ["mps", "cpu"]:
75
+ model = model.half()
76
+ model.eval()
77
+
78
+ todo = sorted(list(os.listdir(wavPath)))[i_part::n_part]
79
+ n = max(1, len(todo) // 10) # 最多打印十条
80
+ if len(todo) == 0:
81
+ printt("no-feature-todo")
82
+ else:
83
+ printt("all-feature-%s" % len(todo))
84
+ for idx, file in enumerate(todo):
85
+ try:
86
+ if file.endswith(".wav"):
87
+ wav_path = "%s/%s" % (wavPath, file)
88
+ out_path = "%s/%s" % (outPath, file.replace("wav", "npy"))
89
+
90
+ if os.path.exists(out_path):
91
+ continue
92
+
93
+ feats = readwave(wav_path, normalize=saved_cfg.task.normalize)
94
+ padding_mask = torch.BoolTensor(feats.shape).fill_(False)
95
+ inputs = {
96
+ "source": feats.half().to(device)
97
+ if device not in ["mps", "cpu"]
98
+ else feats.to(device),
99
+ "padding_mask": padding_mask.to(device),
100
+ "output_layer": 9 if version == "v1" else 12, # layer 9
101
+ }
102
+ with torch.no_grad():
103
+ logits = model.extract_features(**inputs)
104
+ feats = (
105
+ model.final_proj(logits[0]) if version == "v1" else logits[0]
106
+ )
107
+
108
+ feats = feats.squeeze(0).float().cpu().numpy()
109
+ if np.isnan(feats).sum() == 0:
110
+ np.save(out_path, feats, allow_pickle=False)
111
+ else:
112
+ printt("%s-contains nan" % file)
113
+ if idx % n == 0:
114
+ printt("now-%s,all-%s,%s,%s" % (len(todo), idx, file, feats.shape))
115
+ except:
116
+ printt(traceback.format_exc())
117
+ printt("all-feature-done")