human/ui/ipc_render.py
2024-12-05 00:47:17 +08:00

73 lines
2.1 KiB
Python

#encoding = utf8
import os
import logging
import time
from queue import Queue
from human import HumanContext
from ipc import IPCUtil
from utils import render_image
logger = logging.getLogger(__name__)
current_file_path = os.path.dirname(os.path.abspath(__file__))
class IpcRender:
def __init__(self):
self._human_context = None
self._queue = None
self._exit = False
self._ipc = None
def _send_image(self, identifier, image):
height, width, channels = image.shape
width_bytes = width.to_bytes(4, byteorder='little')
height_bytes = height.to_bytes(4, byteorder='little')
bit_depth_bytes = channels.to_bytes(4, byteorder='little')
img_bytes = image.tobytes()
data = identifier + width_bytes + height_bytes + bit_depth_bytes + img_bytes
self._ipc.send_binary(data, len(data))
def _on_reader_callback(self, data_str, size):
data_str = data_str.decode('utf-8')
print(f'on_reader_callback: {data_str}, size:{size}')
if 'quit' == data_str:
self._exit = True
elif 'heartbeat' == data_str:
pass
def run(self):
self._queue = Queue()
self._human_context = HumanContext()
self._human_context.build()
self._ipc = IPCUtil('human_product', 'human_render')
self._ipc.set_reader_callback(self._on_reader_callback)
logger.info(f'ipc listen:{self._ipc.listen()}')
render = self._human_context.render_handler
render.set_image_render(self)
while not self._exit:
if not self._queue.empty():
while self._queue.qsize() > 5:
self._queue.get()
print('render queue is slower')
image = self._queue.get()
image = render_image(self._human_context, image)
self._send_image(b'\x01', image)
else:
time.sleep(0.02)
logger.info('ipc render exit')
def stop(self):
if self._human_context is not None:
self._human_context.stop()
def on_render(self, image):
self._queue.put(image)