livetalking/musereal.py

316 lines
13 KiB
Python
Raw Normal View History

2024-05-26 11:10:03 +08:00
import math
import torch
import numpy as np
2024-06-19 14:47:57 +08:00
# from .utils import *
2024-05-26 11:10:03 +08:00
import subprocess
import os
import time
import torch.nn.functional as F
import cv2
import glob
import pickle
import copy
import queue
from queue import Queue
from threading import Thread, Event
from io import BytesIO
2024-06-09 09:04:04 +08:00
import multiprocessing as mp
2024-05-26 11:10:03 +08:00
2024-06-19 14:47:57 +08:00
from musetalk.utils.utils import get_file_type, get_video_fps, datagen
# from musetalk.utils.preprocessing import get_landmark_and_bbox,read_imgs,coord_placeholder
from musetalk.utils.blending import get_image, get_image_prepare_material, get_image_blending
from musetalk.utils.utils import load_all_model, load_diffusion_model, load_audio_model
from ttsreal import EdgeTTS, VoitsTTS, XTTS
2024-05-26 11:10:03 +08:00
from museasr import MuseASR
import asyncio
from av import AudioFrame, VideoFrame
2024-06-09 09:04:04 +08:00
from tqdm import tqdm
2024-06-19 14:47:57 +08:00
2024-06-09 09:04:04 +08:00
def read_imgs(img_list):
frames = []
print('reading images...')
for img_path in tqdm(img_list):
frame = cv2.imread(img_path)
frames.append(frame)
return frames
2024-06-19 14:47:57 +08:00
2024-06-09 09:04:04 +08:00
def __mirror_index(size, index):
2024-06-19 14:47:57 +08:00
# size = len(self.coord_list_cycle)
2024-06-09 09:04:04 +08:00
turn = index // size
res = index % size
if turn % 2 == 0:
return res
else:
2024-06-19 14:47:57 +08:00
return size - res - 1
def inference(render_event, batch_size, latents_out_path, audio_feat_queue, audio_out_queue, res_frame_queue,
): # vae, unet, pe,timesteps
2024-06-09 09:04:04 +08:00
2024-06-10 13:10:21 +08:00
vae, unet, pe = load_diffusion_model()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
timesteps = torch.tensor([0], device=device)
pe = pe.half()
vae.vae = vae.vae.half()
unet.model = unet.model.half()
2024-06-19 14:47:57 +08:00
2024-06-10 13:10:21 +08:00
input_latent_list_cycle = torch.load(latents_out_path)
2024-06-09 09:04:04 +08:00
length = len(input_latent_list_cycle)
index = 0
2024-06-19 14:47:57 +08:00
count = 0
counttime = 0
2024-06-09 09:04:04 +08:00
print('start inference')
while True:
if render_event.is_set():
2024-06-19 14:47:57 +08:00
starttime = time.perf_counter()
2024-06-09 09:04:04 +08:00
try:
whisper_chunks = audio_feat_queue.get(block=True, timeout=1)
except queue.Empty:
continue
2024-06-19 14:47:57 +08:00
is_all_silence = True
2024-06-09 09:04:04 +08:00
audio_frames = []
2024-06-19 14:47:57 +08:00
for _ in range(batch_size * 2):
frame, type = audio_out_queue.get()
audio_frames.append((frame, type))
if type == 0:
is_all_silence = False
2024-06-09 09:04:04 +08:00
if is_all_silence:
for i in range(batch_size):
2024-06-19 14:47:57 +08:00
res_frame_queue.put((None, __mirror_index(length, index), audio_frames[i * 2:i * 2 + 2]))
2024-06-09 09:04:04 +08:00
index = index + 1
else:
# print('infer=======')
2024-06-19 14:47:57 +08:00
t = time.perf_counter()
2024-06-09 09:04:04 +08:00
whisper_batch = np.stack(whisper_chunks)
latent_batch = []
for i in range(batch_size):
2024-06-19 14:47:57 +08:00
idx = __mirror_index(length, index + i)
2024-06-09 09:04:04 +08:00
latent = input_latent_list_cycle[idx]
latent_batch.append(latent)
latent_batch = torch.cat(latent_batch, dim=0)
2024-06-19 14:47:57 +08:00
2024-06-09 09:04:04 +08:00
# for i, (whisper_batch,latent_batch) in enumerate(gen):
audio_feature_batch = torch.from_numpy(whisper_batch)
audio_feature_batch = audio_feature_batch.to(device=unet.device,
2024-06-19 14:47:57 +08:00
dtype=unet.model.dtype)
2024-06-09 09:04:04 +08:00
audio_feature_batch = pe(audio_feature_batch)
latent_batch = latent_batch.to(dtype=unet.model.dtype)
# print('prepare time:',time.perf_counter()-t)
# t=time.perf_counter()
2024-06-19 14:47:57 +08:00
pred_latents = unet.model(latent_batch,
timesteps,
encoder_hidden_states=audio_feature_batch).sample
2024-06-09 09:04:04 +08:00
# print('unet time:',time.perf_counter()-t)
# t=time.perf_counter()
recon = vae.decode_latents(pred_latents)
# print('vae time:',time.perf_counter()-t)
2024-06-19 14:47:57 +08:00
# print('diffusion len=',len(recon))
2024-06-09 09:04:04 +08:00
counttime += (time.perf_counter() - t)
count += batch_size
2024-06-19 14:47:57 +08:00
# _totalframe += 1
if count >= 100:
print(f"------actual avg infer fps:{count / counttime:.4f}")
count = 0
counttime = 0
for i, res_frame in enumerate(recon):
# self.__pushmedia(res_frame,loop,audio_track,video_track)
res_frame_queue.put((res_frame, __mirror_index(length, index), audio_frames[i * 2:i * 2 + 2]))
2024-06-09 09:04:04 +08:00
index = index + 1
2024-06-19 14:47:57 +08:00
# print('total batch time:',time.perf_counter()-starttime)
2024-06-09 09:04:04 +08:00
else:
time.sleep(1)
print('musereal inference processor stop')
2024-06-19 14:47:57 +08:00
2024-05-31 22:39:03 +08:00
@torch.no_grad()
2024-05-26 11:10:03 +08:00
class MuseReal:
def __init__(self, opt):
2024-06-19 14:47:57 +08:00
self.opt = opt # shared with the trainer's opt to support in-place modification of rendering parameters.
2024-05-26 11:10:03 +08:00
self.W = opt.W
self.H = opt.H
2024-06-19 14:47:57 +08:00
self.fps = opt.fps # 20 ms per frame
2024-05-26 11:10:03 +08:00
#### musetalk
self.avatar_id = opt.avatar_id
2024-06-19 14:47:57 +08:00
self.static_img = opt.static_img
self.video_path = '' # video_path
2024-05-26 11:10:03 +08:00
self.bbox_shift = opt.bbox_shift
self.avatar_path = f"./data/avatars/{self.avatar_id}"
2024-06-19 14:47:57 +08:00
self.full_imgs_path = f"{self.avatar_path}/full_imgs"
2024-05-26 11:10:03 +08:00
self.coords_path = f"{self.avatar_path}/coords.pkl"
2024-06-19 14:47:57 +08:00
self.latents_out_path = f"{self.avatar_path}/latents.pt"
2024-05-26 11:10:03 +08:00
self.video_out_path = f"{self.avatar_path}/vid_output/"
2024-06-19 14:47:57 +08:00
self.mask_out_path = f"{self.avatar_path}/mask"
self.mask_coords_path = f"{self.avatar_path}/mask_coords.pkl"
2024-05-26 11:10:03 +08:00
self.avatar_info_path = f"{self.avatar_path}/avator_info.json"
self.avatar_info = {
2024-06-19 14:47:57 +08:00
"avatar_id": self.avatar_id,
"video_path": self.video_path,
"bbox_shift": self.bbox_shift
2024-05-26 11:10:03 +08:00
}
self.batch_size = opt.batch_size
self.idx = 0
2024-06-19 14:47:57 +08:00
self.res_frame_queue = mp.Queue(self.batch_size * 2)
2024-05-26 11:10:03 +08:00
self.__loadmodels()
self.__loadavatar()
2024-06-19 14:47:57 +08:00
self.asr = MuseASR(opt, self.audio_processor)
2024-06-02 22:25:19 +08:00
if opt.tts == "edgetts":
2024-06-19 14:47:57 +08:00
self.tts = EdgeTTS(opt, self)
2024-06-02 22:25:19 +08:00
elif opt.tts == "gpt-sovits":
2024-06-19 14:47:57 +08:00
self.tts = VoitsTTS(opt, self)
2024-06-02 22:25:19 +08:00
elif opt.tts == "xtts":
2024-06-19 14:47:57 +08:00
self.tts = XTTS(opt, self)
# self.__warm_up()
2024-06-09 09:04:04 +08:00
self.render_event = mp.Event()
2024-06-19 14:47:57 +08:00
mp.Process(target=inference, args=(self.render_event, self.batch_size, self.latents_out_path,
self.asr.feat_queue, self.asr.output_queue, self.res_frame_queue,
)).start() # self.vae, self.unet, self.pe,self.timesteps
2024-05-26 11:10:03 +08:00
def __loadmodels(self):
# load model weights
2024-06-19 14:47:57 +08:00
self.audio_processor = load_audio_model()
2024-06-10 13:10:21 +08:00
# self.audio_processor, self.vae, self.unet, self.pe = load_all_model()
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# self.timesteps = torch.tensor([0], device=device)
# self.pe = self.pe.half()
# self.vae.vae = self.vae.vae.half()
# self.unet.model = self.unet.model.half()
2024-05-26 11:10:03 +08:00
def __loadavatar(self):
2024-06-19 14:47:57 +08:00
# self.input_latent_list_cycle = torch.load(self.latents_out_path)
2024-05-26 11:10:03 +08:00
with open(self.coords_path, 'rb') as f:
self.coord_list_cycle = pickle.load(f)
input_img_list = glob.glob(os.path.join(self.full_imgs_path, '*.[jpJP][pnPN]*[gG]'))
input_img_list = sorted(input_img_list, key=lambda x: int(os.path.splitext(os.path.basename(x))[0]))
self.frame_list_cycle = read_imgs(input_img_list)
with open(self.mask_coords_path, 'rb') as f:
self.mask_coords_list_cycle = pickle.load(f)
input_mask_list = glob.glob(os.path.join(self.mask_out_path, '*.[jpJP][pnPN]*[gG]'))
input_mask_list = sorted(input_mask_list, key=lambda x: int(os.path.splitext(os.path.basename(x))[0]))
self.mask_list_cycle = read_imgs(input_mask_list)
2024-06-19 14:47:57 +08:00
def put_msg_txt(self, msg):
2024-06-02 22:25:19 +08:00
self.tts.put_msg_txt(msg)
2024-06-19 14:47:57 +08:00
def put_audio_frame(self, audio_chunk): # 16khz 20ms pcm
2024-06-02 22:25:19 +08:00
self.asr.put_audio_frame(audio_chunk)
2024-05-26 11:10:03 +08:00
def __mirror_index(self, index):
size = len(self.coord_list_cycle)
turn = index // size
res = index % size
if turn % 2 == 0:
return res
else:
2024-06-19 14:47:57 +08:00
return size - res - 1
2024-06-02 22:25:19 +08:00
2024-06-19 14:47:57 +08:00
def __warm_up(self):
2024-06-02 22:25:19 +08:00
self.asr.run_step()
whisper_chunks = self.asr.get_next_feat()
whisper_batch = np.stack(whisper_chunks)
latent_batch = []
for i in range(self.batch_size):
2024-06-19 14:47:57 +08:00
idx = self.__mirror_index(self.idx + i)
2024-06-02 22:25:19 +08:00
latent = self.input_latent_list_cycle[idx]
latent_batch.append(latent)
latent_batch = torch.cat(latent_batch, dim=0)
print('infer=======')
# for i, (whisper_batch,latent_batch) in enumerate(gen):
audio_feature_batch = torch.from_numpy(whisper_batch)
audio_feature_batch = audio_feature_batch.to(device=self.unet.device,
2024-06-19 14:47:57 +08:00
dtype=self.unet.model.dtype)
2024-06-02 22:25:19 +08:00
audio_feature_batch = self.pe(audio_feature_batch)
latent_batch = latent_batch.to(dtype=self.unet.model.dtype)
2024-06-19 14:47:57 +08:00
pred_latents = self.unet.model(latent_batch,
self.timesteps,
encoder_hidden_states=audio_feature_batch).sample
2024-06-02 22:25:19 +08:00
recon = self.vae.decode_latents(pred_latents)
2024-05-26 11:10:03 +08:00
2024-06-19 14:47:57 +08:00
def process_frames(self, quit_event, loop=None, audio_track=None, video_track=None):
2024-05-26 11:10:03 +08:00
while not quit_event.is_set():
try:
2024-06-19 14:47:57 +08:00
res_frame, idx, audio_frames = self.res_frame_queue.get(block=True, timeout=1)
2024-05-26 11:10:03 +08:00
except queue.Empty:
continue
2024-06-19 14:47:57 +08:00
if audio_frames[0][1] == 1 and audio_frames[1][1] == 1: # 全为静音数据只需要取fullimg
if self.static_img:
combine_frame = self.frame_list_cycle[0]
else:
combine_frame = self.frame_list_cycle[idx]
2024-05-26 18:07:22 +08:00
else:
bbox = self.coord_list_cycle[idx]
ori_frame = copy.deepcopy(self.frame_list_cycle[idx])
x1, y1, x2, y2 = bbox
try:
2024-06-19 14:47:57 +08:00
res_frame = cv2.resize(res_frame.astype(np.uint8), (x2 - x1, y2 - y1))
2024-05-26 18:07:22 +08:00
except:
continue
mask = self.mask_list_cycle[idx]
mask_crop_box = self.mask_coords_list_cycle[idx]
2024-06-19 14:47:57 +08:00
# combine_frame = get_image(ori_frame,res_frame,bbox)
# t=time.perf_counter()
combine_frame = get_image_blending(ori_frame, res_frame, bbox, mask, mask_crop_box)
# print('blending time:',time.perf_counter()-t)
2024-05-26 11:10:03 +08:00
2024-06-19 14:47:57 +08:00
image = combine_frame # (outputs['image'] * 255).astype(np.uint8)
2024-05-26 11:10:03 +08:00
new_frame = VideoFrame.from_ndarray(image, format="bgr24")
2024-06-19 14:47:57 +08:00
asyncio.run_coroutine_threadsafe(video_track._queue.put(new_frame), loop)
2024-05-26 11:10:03 +08:00
2024-05-26 18:07:22 +08:00
for audio_frame in audio_frames:
2024-06-19 14:47:57 +08:00
frame, type = audio_frame
2024-05-26 11:10:03 +08:00
frame = (frame * 32767).astype(np.int16)
new_frame = AudioFrame(format='s16', layout='mono', samples=frame.shape[0])
new_frame.planes[0].update(frame.tobytes())
2024-06-19 14:47:57 +08:00
new_frame.sample_rate = 16000
2024-05-26 11:10:03 +08:00
# if audio_track._queue.qsize()>10:
# time.sleep(0.1)
2024-06-02 22:25:19 +08:00
asyncio.run_coroutine_threadsafe(audio_track._queue.put(new_frame), loop)
2024-06-19 14:47:57 +08:00
print('musereal process_frames thread stop')
def render(self, quit_event, loop=None, audio_track=None, video_track=None):
# if self.opt.asr:
2024-05-26 11:10:03 +08:00
# self.asr.warm_up()
2024-06-02 22:25:19 +08:00
self.tts.render(quit_event)
2024-06-19 14:47:57 +08:00
process_thread = Thread(target=self.process_frames, args=(quit_event, loop, audio_track, video_track))
2024-05-26 11:10:03 +08:00
process_thread.start()
2024-06-19 14:47:57 +08:00
self.render_event.set() # start infer process render
count = 0
totaltime = 0
_starttime = time.perf_counter()
# _totalframe=0
while not quit_event.is_set(): # todo
2024-05-26 11:10:03 +08:00
# update texture every frame
# audio stream thread...
t = time.perf_counter()
2024-06-09 09:04:04 +08:00
self.asr.run_step()
2024-06-19 14:47:57 +08:00
# self.test_step(loop,audio_track,video_track)
2024-06-09 09:04:04 +08:00
# totaltime += (time.perf_counter() - t)
# count += self.opt.batch_size
# if count>=100:
# print(f"------actual avg infer fps:{count/totaltime:.4f}")
# count=0
# totaltime=0
2024-06-19 14:47:57 +08:00
if video_track._queue.qsize() >= 2 * self.opt.batch_size:
print('sleep qsize=', video_track._queue.qsize())
time.sleep(0.04 * self.opt.batch_size * 1.5)
2024-05-26 11:10:03 +08:00
# delay = _starttime+_totalframe*0.04-time.perf_counter() #40ms
# if delay > 0:
# time.sleep(delay)
2024-06-19 14:47:57 +08:00
self.render_event.clear() # end infer process render
2024-06-02 22:25:19 +08:00
print('musereal thread stop')