Pj12 commited on
Commit
f20b851
·
verified ·
1 Parent(s): 16bb1fb

Upload extract_feature_print.py

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