add Tensorboard + meanMetrics for training, actor3 processing
This commit is contained in:
1 parent
33e5cb7584
commit
ad93886668
36 files changed
+351
-214
No files matched your search
Executable
+35
@@ -0,0 +1,35 @@
|
||||
from pathlib import Path
|
||||
import json
|
||||
import moviepy
|
||||
from moviepy.editor import VideoFileClip, AudioFileClip
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
# path_root = Path("/yrfs/lsen/DATA/Actor1")
|
||||
path_root = Path("/data1/yrfs/lsen/DATA/Actor1")
|
||||
|
||||
vpath_videos = sorted(path_root.glob("raw/*.MP4"), reverse=False)
|
||||
print(f"Have {len(vpath_videos)} dir files")
|
||||
|
||||
durations = 0
|
||||
# for each video
|
||||
for i, ipath_item in enumerate(vpath_videos):
|
||||
iname = ipath_item.stem
|
||||
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
|
||||
|
||||
# load video
|
||||
video = VideoFileClip(str(ipath_item))
|
||||
print(f"video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
|
||||
|
||||
# durations += video.duration
|
||||
# print(f"\t -> Total durations = ({durations / 60 } min) ({durations / 3600 } h))")
|
||||
# continue
|
||||
|
||||
if video.audio is None:
|
||||
print("\nERROR: audio info is None")
|
||||
continue
|
||||
|
||||
durations += video.duration
|
||||
print(f"\n\t -> Total durations = ({durations / 60 } min) ({durations / 3600 } h))")
|
||||
# cont
|
||||
@@ -30,7 +30,7 @@ def main(args):
|
||||
print(f"Have {len(v_dir_videos)} dir files")
|
||||
|
||||
# IDs = ["actor-2HD", "actor-3HD"]
|
||||
# IDs = ["clip_full"]
|
||||
# IDs = ["2-23min"]
|
||||
|
||||
# for each video
|
||||
for i, ipath_data in enumerate(v_dir_videos):
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
from torch.utils.data import Dataset, DataLoader
|
||||
|
||||
import torch
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
from pathlib2 import Path
|
||||
from face_alignment import FaceAlignment, LandmarksType
|
||||
from zmq import device
|
||||
|
||||
|
||||
class ImagesDataset(Dataset):
|
||||
def __init__(self, path_folder:Path):
|
||||
|
||||
self.path_folder = path_folder
|
||||
self.list_image = sorted(path_folder.glob("*.jpg"), reverse=False)
|
||||
print(f"Have {len(self.list_image)} images, like {self.list_image[:3]}")
|
||||
|
||||
|
||||
def __len__(self):
|
||||
return len(self.list_image)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
path_frame = self.list_image[idx]
|
||||
image = Image.open(str(path_frame)).convert('RGB') # (h, w, 3)
|
||||
image = np.asarray(image)
|
||||
return {"image_name": path_frame.stem, "image": image}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
path_data = Path("/mfs/lsen/DATA/Actor1/processing")
|
||||
vpath_videos = sorted(path_data.glob("*"))
|
||||
print(f"Have {len(vpath_videos)} dir files")
|
||||
|
||||
device = "cuda:5"
|
||||
model = FaceAlignment(LandmarksType._2D, device=device, face_detector='sfd')
|
||||
print(f"load FaceAlignment model in {device}")
|
||||
|
||||
IDs = ["2-23min"]
|
||||
# for each word
|
||||
for i, ipath_item in enumerate(vpath_videos):
|
||||
iname = ipath_item.stem
|
||||
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
|
||||
|
||||
if iname not in IDs: continue
|
||||
|
||||
ipath_infor = ipath_item.joinpath("video/info.json")
|
||||
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
|
||||
ipath_frame = ipath_item.joinpath("frames")
|
||||
ipath_ldmks.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
dataset = ImagesDataset(ipath_frame)
|
||||
dloader = DataLoader(dataset, batch_size=16, num_workers=8)
|
||||
|
||||
for k, ibatch in enumerate(dloader):
|
||||
ibatch_name = ibatch["image_name"]
|
||||
ibatch_data = ibatch["image"].to(device) # B x H x W x 3
|
||||
ibatch_data = ibatch_data.permute(0, 3, 1, 2) # B x H x W x 3
|
||||
# print(f"ibatch_data shape = {ibatch_data.shape}, path={ibatch_name[:3]}")
|
||||
if k%100 == 0:
|
||||
print(f"batching {k}/{len(dloader)} ... ")
|
||||
|
||||
pred = model.get_landmarks_from_batch(ibatch_data, return_landmark_score=False)
|
||||
# print(f"pred len = {len(pred)}, type= {type(pred)}, [0] shape={pred[0].shape}")
|
||||
|
||||
# save landmarks
|
||||
for jldmk, jname in zip(pred, ibatch_name):
|
||||
jpath_ldmk = ipath_ldmks.joinpath(jname + ".txt")
|
||||
np.savetxt(jpath_ldmk, jldmk, fmt=" %3d")
|
||||
|
||||
|
||||
|
||||
# break
|
||||
@@ -6,7 +6,7 @@ if __name__ == "__main__":
|
||||
|
||||
# fid = "Bringing-Our-Workplace-Policies-into-the-21st-Century"
|
||||
fid = "AA7A9571"
|
||||
path_root = Path("/yrfs/lsen/DATA/Actor2/processing")
|
||||
path_root = Path("/mfs/lsen/DATA/Actor2/processing")
|
||||
|
||||
path_data = path_root.joinpath(fid)
|
||||
|
||||
|
||||
@@ -16,7 +16,6 @@ from decalib.utils.config import cfg as deca_cfg
|
||||
|
||||
def main(args):
|
||||
|
||||
|
||||
# device = args.device
|
||||
device = "cuda:2"
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
from torch.utils.data import Dataset, DataLoader
|
||||
|
||||
import torch
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
from pathlib2 import Path
|
||||
from face_alignment import FaceAlignment, LandmarksType
|
||||
from zmq import device
|
||||
|
||||
|
||||
class ImagesDataset(Dataset):
|
||||
def __init__(self, path_folder:Path):
|
||||
|
||||
self.path_folder = path_folder
|
||||
self.list_image = sorted(path_folder.glob("*.jpg"), reverse=False)
|
||||
print(f"Have {len(self.list_image)} images, like {self.list_image[:3]}")
|
||||
|
||||
|
||||
def __len__(self):
|
||||
return len(self.list_image)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
path_frame = self.list_image[idx]
|
||||
image = Image.open(str(path_frame)).convert('RGB') # (h, w, 3)
|
||||
image = np.asarray(image)
|
||||
return {"image_name": path_frame.stem, "image": image}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
path_data = Path("/mfs/lsen/DATA/Actor2/processing")
|
||||
vpath_videos = sorted(path_data.glob("*"))
|
||||
print(f"Have {len(vpath_videos)} dir files")
|
||||
|
||||
device = "cuda:8"
|
||||
model = FaceAlignment(LandmarksType._2D, device=device, face_detector='sfd')
|
||||
print(f"load FaceAlignment model in {device}")
|
||||
|
||||
IDs = ["AA7A9568", "AA7A9577"]
|
||||
# for each word
|
||||
for i, ipath_item in enumerate(vpath_videos):
|
||||
iname = ipath_item.stem
|
||||
print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ")
|
||||
|
||||
if iname not in IDs: continue
|
||||
|
||||
ipath_infor = ipath_item.joinpath("video/info.json")
|
||||
ipath_ldmks = ipath_item.joinpath("landmarks_FAN")
|
||||
ipath_frame = ipath_item.joinpath("frames")
|
||||
ipath_ldmks.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
dataset = ImagesDataset(ipath_frame)
|
||||
dloader = DataLoader(dataset, batch_size=16, num_workers=8)
|
||||
|
||||
for k, ibatch in enumerate(dloader):
|
||||
ibatch_name = ibatch["image_name"]
|
||||
ibatch_data = ibatch["image"].to(device) # B x H x W x 3
|
||||
ibatch_data = ibatch_data.permute(0, 3, 1, 2) # B x H x W x 3
|
||||
# print(f"ibatch_data shape = {ibatch_data.shape}, path={ibatch_name[:3]}")
|
||||
if k%100 == 0:
|
||||
print(f"batching {k}/{len(dloader)} ... ")
|
||||
|
||||
pred = model.get_landmarks_from_batch(ibatch_data, return_landmark_score=False)
|
||||
# print(f"pred len = {len(pred)}, type= {type(pred)}, [0] shape={pred[0].shape}")
|
||||
|
||||
# save landmarks
|
||||
for jldmk, jname in zip(pred, ibatch_name):
|
||||
jpath_ldmk = ipath_ldmks.joinpath(jname + ".txt")
|
||||
np.savetxt(jpath_ldmk, jldmk, fmt=" %3d")
|
||||
|
||||
|
||||
|
||||
# break
|
||||
@@ -5,8 +5,10 @@ from pathlib import Path
|
||||
if __name__ == "__main__":
|
||||
|
||||
# fid = "Bringing-Our-Workplace-Policies-into-the-21st-Century"
|
||||
fid = "AA7A9571"
|
||||
path_root = Path("/yrfs/lsen/DATA/Actor2/processing")
|
||||
fid = "BU6A9965"
|
||||
path_root = Path("/mfs/lsen/DATA/Actor3/processing")
|
||||
path_save = Path("./data/Actor3/DECA_Actor3_mean.npy")
|
||||
path_save.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
path_data = path_root.joinpath(fid)
|
||||
|
||||
@@ -22,7 +24,8 @@ if __name__ == "__main__":
|
||||
feat_light = []
|
||||
feat_detail = []
|
||||
|
||||
for ipath_coeff in vpath_coeff:
|
||||
for i, ipath_coeff in enumerate(vpath_coeff):
|
||||
if i > 1000: break
|
||||
|
||||
data_coeff = np.load(ipath_coeff, allow_pickle=True).item()
|
||||
|
||||
@@ -70,48 +73,6 @@ if __name__ == "__main__":
|
||||
"shape": mean_shape, # (100, )
|
||||
}
|
||||
|
||||
path_save = "./data/Actor2/DECA_Actor2_mean.npy"
|
||||
np.save(path_save, mean_DECA)
|
||||
print("save to --> ", path_save)
|
||||
print(f"mean deca = \n {mean_DECA}")
|
||||
|
||||
|
||||
# Have 21499 frames
|
||||
# 'cam': array([ 9.8221273e+00, -9.2755520e-04, 2.8869644e-02], dtype=float32),
|
||||
|
||||
# 'pose': array([ 0.04063781, -0.00623041, -0.01067916,
|
||||
# 0.11206006, 0.00411261, 0.02320058], dtype=float32),
|
||||
|
||||
# 'exp': array([-0.6491158 , -0.0998203 , 0.10486019, 0.37043977, -0.29840025,
|
||||
# -0.41017675, 0.327057 , 0.04885808, -0.06325228, 0.4434316 ,
|
||||
# 0.05493879, 0.66853815, -0.10403663, 0.01440001, 0.25900015,
|
||||
# -0.46350944, -0.41076973, -0.10278799, -0.08775225, 0.51222765,
|
||||
# 0.10053314, -0.26408502, 0.11820181, -0.05676581, 0.02643572,
|
||||
# 0.16058844, -0.11792275, 0.12630136, -0.23953533, -0.10915831,
|
||||
# -0.16660552, 0.00958887, 0.2679962 , -0.26946628, 0.19901456,
|
||||
# -0.09804437, -0.03807065, -0.12970755, 0.01078465, 0.19384004,
|
||||
# -0.06548703, -0.03329738, 0.11319494, -0.02613433, 0.02363422,
|
||||
# 0.02380173, -0.11122038, 0.13734889, 0.1255798 , 0.13813666],
|
||||
# dtype=float32),
|
||||
|
||||
# 'shape': array([ 0.00951388, -0.22505675, -0.53953266, -0.4397285 , 0.37905172,
|
||||
# 0.11540896, -0.36891365, -0.218832 , -0.3684414 , 0.24644622,
|
||||
# 0.6223965 , -0.16298303, -0.35899413, -0.11834836, -0.04909257,
|
||||
# -0.13188031, 0.35037243, -0.10429271, 0.25443867, -0.18088193,
|
||||
# 0.16413063, 0.20566346, 0.0501059 , -0.19294368, -0.00809607,
|
||||
# -0.08120474, -0.07019995, 0.01174292, 0.33962983, 0.04500978,
|
||||
# -0.25193816, -0.2265279 , 0.14124256, 0.21158281, -0.09555811,
|
||||
# 0.14076404, 0.04877019, 0.03229018, -0.00235608, -0.08356833,
|
||||
# 0.09741616, 0.2644469 , 0.13229795, -0.14537199, -0.2314888 ,
|
||||
# -0.48501098, -0.13492987, -0.13772976, -0.18299519, -0.11046503,
|
||||
# 0.04127223, -0.4613573 , -0.06382176, 0.08914807, 0.08793663,
|
||||
# 0.11848436, 0.03956904, 0.04172374, -0.04793308, 0.30301905,
|
||||
# -0.06345342, 0.04190513, 0.13665007, -0.03253645, 0.08728135,
|
||||
# 0.06684338, 0.02282041, 0.00583193, -0.11710295, -0.06365721,
|
||||
# -0.00492529, -0.14196472, 0.03584495, -0.00815303, -0.00147824,
|
||||
# 0.2087406 , -0.11037645, -0.04405028, -0.129121 , 0.03147175,
|
||||
# -0.03467533, -0.00330734, 0.13060835, -0.02846657, 0.05666886,
|
||||
# -0.07806987, -0.17371002, 0.05375125, -0.04018219, 0.08453278,
|
||||
# -0.05303599, -0.11419729, -0.16071273, -0.00130347, -0.1172006 ,
|
||||
# -0.06073425, -0.03826162, -0.0587554 , -0.06399846, -0.14208533],
|
||||
# dtype=float32)}
|
||||
@@ -91,7 +91,6 @@ if __name__ == '__main__':
|
||||
nframes = len(list(video.iter_frames()))
|
||||
|
||||
|
||||
|
||||
# get audio
|
||||
audio_sub = video.audio
|
||||
if audio_sub is None:
|
||||
|
||||
@@ -18,14 +18,14 @@ def main(args):
|
||||
|
||||
|
||||
# device = args.device
|
||||
device = "cuda:2"
|
||||
device = "cuda:7"
|
||||
|
||||
# run DECA
|
||||
deca_cfg.model.use_tex = args.useTex
|
||||
deca = DECA(config = deca_cfg, device=device)
|
||||
|
||||
# path_data = Path("/yrfs/lsen/DATA/TestData/processing")
|
||||
path_data = Path("/yrfs/lsen/DATA/Actor2/processing")
|
||||
path_data = Path("/mfs/lsen/DATA/Actor3/processing")
|
||||
|
||||
v_dir_videos = sorted(path_data.glob("*"), reverse=False)
|
||||
print(f"Have {len(v_dir_videos)} dir files")
|
||||
@@ -75,10 +75,10 @@ def main(args):
|
||||
print(f"Have finised before, nkpt2d={nkpt2d} nframes = {nframes}")
|
||||
continue
|
||||
|
||||
|
||||
datatest = ObamaData(ipath_frame, iscrop=args.iscrop, face_detector=args.detector, device=device)
|
||||
dataloader = DataLoader(datatest, batch_size=128, shuffle=False, drop_last=False)
|
||||
|
||||
|
||||
for i, ibatch_data in enumerate(dataloader):
|
||||
batch_names = ibatch_data["names"]
|
||||
batch_image = ibatch_data["image"].to(device)
|
||||
|
||||
@@ -7,11 +7,10 @@ from pathlib import Path
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
path_data = Path("/yrfs/lsen/DATA/Actor2/processing")
|
||||
path_data = Path("/mfs/lsen/DATA/Actor3/processing")
|
||||
v_dir_videos = sorted(path_data.glob("*"))
|
||||
print(f"Have {len(v_dir_videos)} dir files")
|
||||
|
||||
|
||||
# for each video
|
||||
duration_frame, duration_coeff = 0, 0
|
||||
for ipath_data in v_dir_videos:
|
||||
@@ -51,11 +50,11 @@ if __name__ == "__main__":
|
||||
|
||||
if len(vframe_frame) != nframes:
|
||||
print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
|
||||
# continue
|
||||
continue
|
||||
|
||||
if len(vframe_coeff)+1 < nframes:
|
||||
print(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}")
|
||||
# continue
|
||||
continue
|
||||
|
||||
if ipath_save_exp.exists() and ipath_save_pos.exists():
|
||||
print(f"ipath_save_exp have already save > {ipath_save_exp}")
|
||||
|
||||
@@ -29,8 +29,8 @@ def landmark_resample_fps(y, source_fps = 30, target_fps=25):
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
path_data = Path("/yrfs/lsen/DATA/Actor2/processing")
|
||||
path_save = Path('data/Actor2/Actor2-raw-7h') # processing
|
||||
path_data = Path("/mfs/lsen/DATA/Actor3/processing")
|
||||
path_save = Path('data/Actor2/Actor3-raw-1h') # processing
|
||||
path_save.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
|
||||
@@ -40,17 +40,17 @@ if __name__ == "__main__":
|
||||
vids = set([ipath.stem for ipath in v_dir_videos])
|
||||
# print(f"vids total= {vids}")
|
||||
|
||||
vid_test = set(["AA7A9568", "AA7A9577"])
|
||||
# vid_valid = set(["AA7A9569", "AA7A9578"])
|
||||
vid_train = set(['AA7A9570', 'AA7A9571', 'AA7A9572', 'AA7A9573', 'AA7A9574', 'AA7A9575', 'AA7A9576', 'AA7A9579',
|
||||
'AA7A9580', 'AA7A9582', 'AA7A9583', 'AA7A9584', 'AA7A9585', 'AA7A9600', 'AA7A9601', 'AA7A9602',
|
||||
'AA7A9603', 'AA7A9604', 'AA7A9605', 'AA7A9606', 'AA7A9607', 'AA7A9608', 'AA7A9609', 'AA7A9610',
|
||||
'AA7A9611', 'AA7A9612', 'AA7A9613', 'AA7A9614', 'AA7A9615', 'AA7A9616', 'AA7A9617', 'AA7A9618',
|
||||
'AA7A9619', 'AA7A9620', 'AA7A9621', 'AA7A9622', 'AA7A9623', 'AA7A9625', 'AA7A9626', 'AA7A9627',
|
||||
'AA7A9628'])
|
||||
vid_test = set(["BU6A9965"])
|
||||
vid_valid = set(["BU6A9965"])
|
||||
# vid_train = set(['AA7A9570', 'AA7A9571', 'AA7A9572', 'AA7A9573', 'AA7A9574', 'AA7A9575', 'AA7A9576', 'AA7A9579',
|
||||
# 'AA7A9580', 'AA7A9582', 'AA7A9583', 'AA7A9584', 'AA7A9585', 'AA7A9600', 'AA7A9601', 'AA7A9602',
|
||||
# 'AA7A9603', 'AA7A9604', 'AA7A9605', 'AA7A9606', 'AA7A9607', 'AA7A9608', 'AA7A9609', 'AA7A9610',
|
||||
# 'AA7A9611', 'AA7A9612', 'AA7A9613', 'AA7A9614', 'AA7A9615', 'AA7A9616', 'AA7A9617', 'AA7A9618',
|
||||
# 'AA7A9619', 'AA7A9620', 'AA7A9621', 'AA7A9622', 'AA7A9623', 'AA7A9625', 'AA7A9626', 'AA7A9627',
|
||||
# 'AA7A9628'])
|
||||
|
||||
# vid_train = vids - vid_test - vid_valid
|
||||
vid_valid = vids - vid_test - vid_train
|
||||
vid_train = vids - vid_test - vid_valid
|
||||
# vid_valid = vids - vid_test - vid_train
|
||||
|
||||
# vids = set(["2021-P09", "2021-P14", "2021-P22"])
|
||||
# vid_test = set(["2021-P09" ])
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
* Copyright 2015 Alibaba Group Holding Limited
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
"""
|
||||
|
||||
from multiprocessing import Process, Pool
|
||||
import json
|
||||
import random
|
||||
import uuid
|
||||
import os
|
||||
import librosa
|
||||
|
||||
import ali_speech
|
||||
from ali_speech.callbacks import SpeechSynthesizerCallback
|
||||
from ali_speech.constant import TTSFormat
|
||||
from ali_speech.constant import TTSSampleRate
|
||||
from aliyunsdkcore.client import AcsClient
|
||||
from aliyunsdkcore.request import CommonRequest
|
||||
|
||||
class MyCallback(SpeechSynthesizerCallback):
|
||||
# 参数name用于指定保存音频的文件
|
||||
def __init__(self, name):
|
||||
self._name = name
|
||||
self._fout = open(name, 'wb')
|
||||
|
||||
def on_binary_data_received(self, raw):
|
||||
# print('MyCallback.on_binary_data_received: %s' % len(raw))
|
||||
self._fout.write(raw)
|
||||
|
||||
def on_completed(self, message):
|
||||
# print('MyCallback.OnRecognitionCompleted: %s' % message)
|
||||
self._fout.close()
|
||||
|
||||
def on_task_failed(self, message):
|
||||
print('MyCallback.OnRecognitionTaskFailed-task_id:%s, status_text:%s' % (message['header']['task_id'], message['header']['status_text']))
|
||||
self._fout.close()
|
||||
os.remove(self._name)
|
||||
|
||||
def on_channel_closed(self):
|
||||
# print('MyCallback.OnRecognitionChannelClosed')
|
||||
pass
|
||||
|
||||
def on_close(self, a, b, c):
|
||||
pass
|
||||
|
||||
|
||||
def process(client, appkey, token, text, audio_name, voice, volume, pitch, speed):
|
||||
voices = ["aixia", "stella"]
|
||||
#voices = ["maoxiaomei", "aifei", "yaqun", "qiaowei", "laotie", "laomei"]
|
||||
#voices = ["xiaoyun","xiaogang","ruoxi","siqi","sijia","sicheng","aiqi","aijia","aicheng","aida","ninger","ruilin","siyue","aiya","aixia","aimei","aiyu","aiyue","aijing","xiaomei","sijing","aishuo","guijie","stella","stanley","kenny","rosa","xiaoxian","maoxiaomei","aifei"]
|
||||
# voices = ['aikan']
|
||||
callback = MyCallback(audio_name)
|
||||
synthesizer = client.create_synthesizer(callback)
|
||||
synthesizer.set_appkey(appkey)
|
||||
synthesizer.set_token(token)
|
||||
synthesizer.set_voice(voices[voice])
|
||||
synthesizer.set_text(text)
|
||||
synthesizer.set_format(TTSFormat.WAV)
|
||||
synthesizer.set_sample_rate(TTSSampleRate.SAMPLE_RATE_16K)
|
||||
synthesizer.set_volume(volume)
|
||||
synthesizer.set_speech_rate(speed)
|
||||
synthesizer.set_pitch_rate(pitch)
|
||||
|
||||
try:
|
||||
ret = synthesizer.start()
|
||||
if ret < 0:
|
||||
return ret
|
||||
synthesizer.wait_completed()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
finally:
|
||||
synthesizer.close()
|
||||
|
||||
if os.path.exists(audio_name):
|
||||
duration = round(librosa.get_duration(filename=audio_name), 2)
|
||||
|
||||
return {'audio_filepath': audio_name, 'duration': duration, 'text': text}
|
||||
|
||||
return None
|
||||
|
||||
def process_multiprocess(number, repeat, texts, export_dir, json_file):
|
||||
client = ali_speech.NlsClient()
|
||||
# 设置输出日志信息的级别:DEBUG、INFO、WARNING、ERROR
|
||||
client.set_log_level('INFO')
|
||||
ali_client = AcsClient(
|
||||
"LTAIUkF55OIJw7Q8",
|
||||
"a2OxoUuAQ4gbT2FkqpfiPfXgpPp7dh",
|
||||
"cn-shanghai"
|
||||
)
|
||||
|
||||
# 创建request,并设置参数
|
||||
request = CommonRequest()
|
||||
request.set_method('POST')
|
||||
request.set_domain('nls-meta.cn-shanghai.aliyuncs.com')
|
||||
request.set_version('2019-02-28')
|
||||
request.set_action_name('CreateToken')
|
||||
response = ali_client.do_action_with_exception(request)
|
||||
response = json.loads(response)
|
||||
token = response["Token"]["Id"]
|
||||
|
||||
appkey = 'vxDWVWpU2V2nwPhK'
|
||||
|
||||
pool = Pool(processes=number)
|
||||
result = []
|
||||
for text in texts:
|
||||
for _ in range(repeat): # repeat syn time
|
||||
audio_name = os.path.join(export_dir, ''.join(str(uuid.uuid4()).split('-')) + ".wav")
|
||||
voice = random.randint(0, 5)
|
||||
#voice = 4
|
||||
volume = random.randint(25, 75)
|
||||
pitch = random.randint(-50, 50)
|
||||
speed = random.randint(-125, 166)
|
||||
result.append(pool.apply_async(process,(client, appkey, token, text, audio_name, voice, volume, pitch, speed)))
|
||||
|
||||
pool.close()
|
||||
pool.join()
|
||||
|
||||
with open(json_file, 'w') as f:
|
||||
for res in result:
|
||||
line = res.get()
|
||||
if line is not None:
|
||||
f.write(json.dumps(line, ensure_ascii=False)+'\n')
|
||||
|
||||
if __name__ == "__main__":
|
||||
texts = open('/mfs/dylan/tts/tts_text.txt').read().splitlines()
|
||||
export_dir = '/mfs/dylan/tts/wav_john/'
|
||||
json_file = '/mfs/dylan/tts/tts_data_john.json'
|
||||
process_num = 30
|
||||
repeat_num = 10
|
||||
|
||||
process_multiprocess(process_num, repeat_num, texts, export_dir, json_file)
|
||||
Reference in new issue
Block a user