Pj12 commited on
Commit
709d0de
·
verified ·
1 Parent(s): d8b7aa1

Update extract_feature_print.py

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