Pj12 commited on
Commit
c607b9c
·
verified ·
1 Parent(s): 8f9fb5e

Update extract_feature_print.py

Browse files
Files changed (1) hide show
  1. extract_feature_print.py +123 -122
extract_feature_print.py CHANGED
@@ -1,122 +1,123 @@
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")
 
 
1
+ import os, sys, traceback
2
+ import feature_extraction_method
3
+
4
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
5
+ os.environ["PYTORCH_MPS_HIGH_WATERMARK_RATIO"] = "0.0"
6
+
7
+ # device=sys.argv[1]
8
+ n_part = int(sys.argv[2])
9
+ i_part = int(sys.argv[3])
10
+ if len(sys.argv) == 6:
11
+ exp_dir = sys.argv[4]
12
+ version = sys.argv[5]
13
+ else:
14
+ i_gpu = sys.argv[4]
15
+ exp_dir = sys.argv[5]
16
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(i_gpu)
17
+ version = sys.argv[6]
18
+ import torch
19
+ import torch.nn.functional as F
20
+ import soundfile as sf
21
+ import numpy as np
22
+ from fairseq import checkpoint_utils
23
+
24
+ device = "cpu"
25
+ if torch.cuda.is_available():
26
+ device = "cuda"
27
+ elif torch.backends.mps.is_available():
28
+ device = "mps"
29
+
30
+ f = open("%s/extract_f0_feature.log" % exp_dir, "a+")
31
+
32
+
33
+ def printt(strr):
34
+ print(strr)
35
+ f.write("%s\n" % strr)
36
+ f.flush()
37
+
38
+
39
+ printt(sys.argv)
40
+ model_path = feature_extraction_method
41
+
42
+ printt(exp_dir)
43
+ wavPath = "%s/1_16k_wavs" % exp_dir
44
+ outPath = (
45
+ "%s/3_feature256" % exp_dir if version == "v1" else "%s/3_feature768" % exp_dir
46
+ )
47
+ os.makedirs(outPath, exist_ok=True)
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")