human/human/audio_inference_handler.py

179 lines
6.9 KiB
Python
Raw Normal View History

#encoding = utf8
2024-10-17 15:26:21 +00:00
import logging
import os
import queue
import time
from threading import Event, Thread
2024-12-04 16:47:17 +00:00
import cv2
import numpy as np
import torch
2024-11-06 12:31:23 +00:00
from eventbus import EventBus
2024-10-17 15:26:21 +00:00
from human_handler import AudioHandler
2024-10-29 10:09:26 +00:00
from utils import load_model, mirror_index, get_device, SyncQueue
2024-12-06 00:27:18 +00:00
from .huaman_status import HumanStatus
2024-10-17 15:26:21 +00:00
logger = logging.getLogger(__name__)
current_file_path = os.path.dirname(os.path.abspath(__file__))
class AudioInferenceHandler(AudioHandler):
def __init__(self, context, handler):
super().__init__(context, handler)
2024-11-06 12:31:23 +00:00
EventBus().register('stop', self._on_stop)
2024-11-01 12:38:57 +00:00
self._mal_queue = SyncQueue(1, "AudioInferenceHandler_Mel")
self._audio_queue = SyncQueue(context.batch_size * 2, "AudioInferenceHandler_Audio")
2024-10-16 11:04:12 +00:00
2024-11-06 12:31:23 +00:00
self._is_running = True
self._exit_event = Event()
2024-11-01 12:38:57 +00:00
self._run_thread = Thread(target=self.__on_run, name="AudioInferenceHandlerThread")
self._exit_event.set()
self._run_thread.start()
2024-11-06 12:31:23 +00:00
2024-10-17 15:26:21 +00:00
logger.info("AudioInferenceHandler init")
2024-11-06 12:31:23 +00:00
def __del__(self):
EventBus().unregister('stop', self._on_stop)
def _on_stop(self, *args, **kwargs):
self.stop()
2024-10-16 11:04:12 +00:00
def on_handle(self, stream, type_):
2024-11-06 12:31:23 +00:00
if not self._is_running:
return
2024-10-16 11:04:12 +00:00
if type_ == 1:
2024-10-17 00:25:53 +00:00
self._mal_queue.put(stream)
2024-10-16 11:04:12 +00:00
elif type_ == 0:
self._audio_queue.put(stream)
2024-11-01 12:38:57 +00:00
# print('AudioInferenceHandler on_handle', type_, self._audio_queue.size())
2024-10-25 00:23:55 +00:00
def on_message(self, message):
super().on_message(message)
def __on_run(self):
2024-11-20 16:30:15 +00:00
# wav2lip_path = os.path.join(current_file_path, '..', 'checkpoints', 'wav2lip.pth')
wav2lip_path = os.path.join(current_file_path, '..', 'checkpoints', 'weights', 'wav2lip',
'ema_checkpoint_step000300000.pth')
2024-10-17 15:26:21 +00:00
logger.info(f'AudioInferenceHandler init, path:{wav2lip_path}')
model = load_model(wav2lip_path)
logger.info("Model loaded")
2024-10-17 00:25:53 +00:00
face_list_cycle = self._context.face_list_cycle
length = len(face_list_cycle)
index = 0
count = 0
count_time = 0
2024-10-17 15:26:21 +00:00
logger.info('start inference')
2024-12-04 16:47:17 +00:00
silence_length = 133
2024-12-06 00:27:18 +00:00
human_status = HumanStatus(length, silence_length)
device = get_device()
2024-10-17 15:26:21 +00:00
logger.info(f'use device:{device}')
2024-11-06 12:31:23 +00:00
while self._is_running:
if self._exit_event.is_set():
start_time = time.perf_counter()
2024-10-17 00:25:53 +00:00
batch_size = self._context.batch_size
try:
2024-11-07 12:43:46 +00:00
mel_batch = self._mal_queue.get(timeout=0.02)
2024-11-07 23:27:00 +00:00
# print('AudioInferenceHandler mel_batch:', len(mel_batch), 'size:', self._mal_queue.size())
except queue.Empty:
continue
2024-11-01 12:38:57 +00:00
# print('origin mel_batch:', len(mel_batch))
is_all_silence = True
audio_frames = []
2024-11-13 11:29:40 +00:00
current_text = ''
for _ in range(batch_size * 2):
2024-10-16 11:04:12 +00:00
frame, type_ = self._audio_queue.get()
2024-11-01 12:38:57 +00:00
# print('AudioInferenceHandler type_', type_)
2024-11-13 11:29:40 +00:00
current_text = frame[1]
audio_frames.append((frame, type_))
if type_ == 0:
is_all_silence = False
2024-11-06 12:31:23 +00:00
if not self._is_running:
2024-11-07 00:26:03 +00:00
print('AudioInferenceHandler not running')
break
2024-11-06 12:31:23 +00:00
if is_all_silence:
for i in range(batch_size):
2024-11-07 00:26:03 +00:00
if not self._is_running:
break
2024-12-08 17:20:48 +00:00
self.on_next_handle((None, mirror_index(length, index),
# self.on_next_handle((None, human_status.get_index(),
2024-12-04 16:47:17 +00:00
audio_frames[i * 2:i * 2 + 2]), 0)
2024-12-08 17:20:48 +00:00
index = index + 1
else:
2024-12-06 00:27:18 +00:00
human_status.start_talking()
2024-11-13 11:29:40 +00:00
logger.info(f'infer======= {current_text}')
2024-12-05 16:16:41 +00:00
# human_status.try_to_talk()
t = time.perf_counter()
img_batch = []
2024-12-06 00:27:18 +00:00
index_list = []
2024-10-31 13:38:35 +00:00
# for i in range(batch_size):
for i in range(len(mel_batch)):
2024-12-08 17:20:48 +00:00
idx = mirror_index(length, index + i)
# idx = human_status.get_index()
# index_list.append(idx)
face = face_list_cycle[idx]
img_batch.append(face)
2024-11-01 12:38:57 +00:00
# print('orign img_batch:', len(img_batch), 'origin mel_batch:', len(mel_batch))
img_batch = np.asarray(img_batch)
mel_batch = np.asarray(mel_batch)
img_masked = img_batch.copy()
img_masked[:, face.shape[0] // 2:] = 0
2024-10-17 00:25:53 +00:00
img_batch = np.concatenate((img_masked, img_batch), axis=3) / 255.
mel_batch = np.reshape(mel_batch,
[len(mel_batch), mel_batch.shape[1], mel_batch.shape[2], 1])
img_batch = torch.FloatTensor(np.transpose(img_batch, (0, 3, 1, 2))).to(device)
mel_batch = torch.FloatTensor(np.transpose(mel_batch, (0, 3, 1, 2))).to(device)
2024-11-20 16:30:15 +00:00
# print('img_batch:', img_batch.shape, 'mel_batch:', mel_batch.shape)
with torch.no_grad():
pred = model(mel_batch, img_batch)
pred = pred.cpu().numpy().transpose(0, 2, 3, 1) * 255.
count_time += (time.perf_counter() - t)
count += batch_size
if count >= 100:
2024-10-17 15:26:21 +00:00
logger.info(f"------actual avg infer fps:{count / count_time:.4f}")
count = 0
count_time = 0
for i, res_frame in enumerate(pred):
2024-11-07 00:26:03 +00:00
if not self._is_running:
break
2024-10-16 11:04:12 +00:00
self.on_next_handle(
2024-12-08 17:20:48 +00:00
(res_frame, mirror_index(length, index), audio_frames[i * 2:i * 2 + 2]),
# (res_frame, index_list[i], audio_frames[i * 2:i * 2 + 2]),
2024-10-16 11:04:12 +00:00
0)
2024-12-08 17:20:48 +00:00
index = index + 1
2024-12-06 00:27:18 +00:00
2024-10-17 15:26:21 +00:00
logger.info(f'total batch time: {time.perf_counter() - start_time}')
else:
time.sleep(1)
break
2024-10-17 15:26:21 +00:00
logger.info('AudioInferenceHandler inference processor stop')
def stop(self):
2024-11-06 12:31:23 +00:00
logger.info('AudioInferenceHandler stop')
self._is_running = False
2024-10-17 15:26:21 +00:00
self._exit_event.clear()
2024-11-07 00:26:03 +00:00
if self._run_thread.is_alive():
2024-11-07 12:43:46 +00:00
logger.info('AudioInferenceHandler stop join')
2024-11-07 00:26:03 +00:00
self._run_thread.join()
2024-11-07 12:43:46 +00:00
logger.info('AudioInferenceHandler stop exit')
2024-10-19 19:28:49 +00:00
def pause_talk(self):
2024-11-04 13:44:51 +00:00
print('AudioInferenceHandler pause_talk', self._audio_queue.size(), self._mal_queue.size())
2024-10-31 13:38:35 +00:00
self._audio_queue.clear()
2024-11-04 13:44:51 +00:00
self._mal_queue.clear()