Optimize this as best as you can import time
import numpy as np

from xlib.mp import csw as lib_csw
from xlib.python import all_is_not_None
from xlib.image import ImageProcessor
from .BackendBase import (BackendHost, BackendSignal, BackendWeakHeap,
                          BackendWorker, BackendDB, BackendConnection,
                          BackendWorkerState)

class FaceBeautifier(BackendHost):
    def __init__(self, weak_heap=False, reemit_frame_signal=None,
                       bc_in=None, bc_out=None, backend_db=None):
        self._weak_heap = weak_heap
        self._bc_out = bc_out
        super().__init__(backend_db=backend_db,
                        sheet_cls=Sheet,
                        worker_cls=FaceBeautifierWorker,
                        worker_state_cls=WorkerState,
                        worker_start_args=[weak_heap, reemit_frame_signal, bc_in, bc_out])

    def get_control_sheet(self) -> 'Sheet.Host': return super().get_control_sheet()
    def get_weak_heap(self) -> BackendWeakHeap: return self._weak_heap
    def get_bc_out(self) -> BackendConnection: return self._bc_out

class Sheet:
    class Host(lib_csw.Sheet.Host):
        def __init__(self):
            super().__init__()
            self.beauty_level = lib_csw.Number.Host()
            self.face_slim_level = lib_csw.Number.Host()
            self.chin_slim_level = lib_csw.Number.Host()
            self.forehead_level = lib_csw.Number.Host()  # 额高调整
            self.hairline_level = lib_csw.Number.Host()  # 发际线调整
            self.face_length_level = lib_csw.Number.Host()  # 脸长调整

    class Worker(lib_csw.Sheet.Worker):
        def __init__(self):
            super().__init__()
            self.beauty_level = lib_csw.Number.Client()
            self.face_slim_level = lib_csw.Number.Client()
            self.chin_slim_level = lib_csw.Number.Client()
            self.forehead_level = lib_csw.Number.Client()
            self.hairline_level = lib_csw.Number.Client()
            self.face_length_level = lib_csw.Number.Client()

class WorkerState(BackendWorkerState):
    def __init__(self):
        super().__init__()
        self.device = None
        self.beauty_level = 50
        self.face_slim_level = 50
        self.chin_slim_level = 50
        self.forehead_level = 50
        self.hairline_level = 50
        self.face_length_level = 50

class FaceBeautifierWorker(BackendWorker):
    def get_state(self) -> WorkerState: return super().get_state()
    def get_control_sheet(self) -> 'Sheet.Worker': return super().get_control_sheet()

    def on_start(self, weak_heap, reemit_frame_signal, bc_in, bc_out):
        self.weak_heap = weak_heap
        self.reemit_frame_signal = reemit_frame_signal
        self.bc_in = bc_in
        self.bc_out = bc_out
        self.pending_bcd = None

        # 获取 state 和 control sheet
        state, cs = self.get_state(), self.get_control_sheet()

        # 设置所有参数的回调
        cs.beauty_level.call_on_number(self.on_beauty_level)
        cs.face_slim_level.call_on_number(self.on_face_slim_level)
        cs.chin_slim_level.call_on_number(self.on_chin_slim_level)
        # 新参数的回调
        cs.forehead_level.call_on_number(self.on_forehead_level)
        cs.hairline_level.call_on_number(self.on_hairline_level)
        cs.face_length_level.call_on_number(self.on_face_length_level)

        return True

    def on_beauty_level(self, value):
        state = self.get_state()
        state.beauty_level = value

    def on_face_slim_level(self, value):
        state = self.get_state()
        state.face_slim_level = value

    def on_chin_slim_level(self, value):
        state = self.get_state()
        state.chin_slim_level = value

    # 新参数的回调函数
    def on_forehead_level(self, value):
        state = self.get_state()
        state.forehead_level = value

    def on_hairline_level(self, value):
        state = self.get_state()
        state.hairline_level = value

    def on_hip_level(self, value):
        state = self.get_state()
        state.hip_level = value

    def on_face_length_level(self, value):
        state = self.get_state()
        state.face_length_level = value

    def on_tick(self):
            state, cs = self.get_state(), self.get_control_sheet()

            if self.pending_bcd is None:
                self.start_profile_timing()

                bcd = self.bc_in.read(timeout=0.005)
                if bcd is not None:
                    bcd.assign_weak_heap(self.weak_heap)
                    
                    faces = bcd.get_face_swap_info_list()
                    if faces is not None:
                        for face in faces:
                            image = bcd.get_image(face.image_name)
                            if image is not None:
                                # 添加新的参数
                                beauty_image = self._apply_beautify(image,
                                                                state.beauty_level,
                                                                state.face_slim_level,
                                                                state.chin_slim_level,
                                                                state.forehead_level,
                                                                state.hairline_level,
                                                                state.face_length_level)
                                bcd.set_image(face.image_name, beauty_image)

                    self.stop_profile_timing()
                    self.pending_bcd = bcd

            if self.pending_bcd is not None:
                if self.bc_out.is_full_read(1):
                    self.bc_out.write(self.pending_bcd)
                    self.pending_bcd = None
                else:
                    time.sleep(0.001)

            return True

    def _apply_beautify(self, image, beauty_level, face_slim_level, chin_slim_level, 
                       forehead_level, hairline_level, face_length_level):
        """应用美颜效果"""
        try:
            import cv2
            import numpy as np
            import cupy as cp

            # 計算縮放比例
            orig_h, orig_w = image.shape[:2]
            scale_factor = min(1.0, 640 / max(orig_w, orig_h))
            
            if scale_factor < 1.0:
                # 降低分辨率進行處理
                process_size = (int(orig_w * scale_factor), int(orig_h * scale_factor))
                small_image = cv2.resize(image, process_size, interpolation=cv2.INTER_LINEAR)
            else:
                small_image = image

            height, width = small_image.shape[:2]
            gpu_image = cp.asarray(small_image, dtype=cp.uint8)

            # 只在真正需要時進行美白操作
            if beauty_level > 5:  # 添加閾值，避免小幅度變化
                # LAB 轉換和調整
                bgr_image = cp.asnumpy(gpu_image).astype(np.uint8)
                lab = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2LAB)
                l, a, b = cv2.split(lab)
                
                # 使用 LUT 加速亮度調整
                lut = np.clip(np.arange(0, 256) + beauty_level * 0.6, 0, 255).astype(np.uint8)
                l = cv2.LUT(l, lut)
                
                lab = cv2.merge([l, a, b])
                bgr_image = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)

                # 優化磨皮算法，使用小核的高斯模糊
                if beauty_level > 0:
                    kernel_size = min(9, max(3, int(beauty_level/10) * 2 + 1))
                    blur = cv2.GaussianBlur(bgr_image, (kernel_size, kernel_size), 0)
                    result = cv2.addWeighted(bgr_image, 0.7, blur, 0.3, 0)
                    gpu_image = cp.asarray(result)

            # 創建網格（重用網格以減少內存分配）
            if not hasattr(self, '_grid_cache') or self._grid_cache[0] != (height, width):
                y_indices, x_indices = cp.mgrid[0:height, 0:width].astype(cp.float32)
                self._grid_cache = ((height, width), y_indices, x_indices)
            else:
                _, y_indices, x_indices = self._grid_cache

            # 只在需要時進行變形
            need_transform = any(abs(x - 50) > 3 for x in [face_slim_level, chin_slim_level, 
                                                          forehead_level, hairline_level, 
                                                          face_length_level])

            if need_transform:
                map_x = x_indices.copy()
                map_y = y_indices.copy()

                # 合併所有變形操作
                if abs(face_slim_level - 50) > 3:
                    center_x = width // 2
                    x_dist = cp.abs(x_indices - center_x)
                    mask = x_dist < width//4
                    map_x[mask] += ((face_slim_level-50)/50 * 10 * 
                                  cp.sin(x_dist[mask]/30))

                if abs(chin_slim_level - 50) > 3 or abs(face_length_level - 50) > 3:
                    # 組合下巴和臉長的變形
                    adjust_y = cp.zeros_like(y_indices)
                    
                    if abs(chin_slim_level - 50) > 3:
                        chin_y = int(height * 0.7)
                        mask = (y_indices >= chin_y) & (cp.abs(x_indices - width//2) < width//3)
                        adjust_y[mask] += ((chin_slim_level-50)/50 * 5 * 
                                         cp.sin(cp.abs(x_indices[mask] - width//2)/40))

                    if abs(face_length_level - 50) > 3:
                        center_y = height // 2
                        y_dist = cp.abs(y_indices - center_y)
                        adjust_y += ((face_length_level-50)/50 * 20 * 
                                    y_dist / (height/2))

                    map_y += adjust_y

                # 合併額頭和發際線的變形
                if abs(forehead_level - 50) > 3 or abs(hairline_level - 50) > 3:
                    forehead_mask = y_indices < (height * 0.2)
                    if abs(forehead_level - 50) > 3:
                        map_y[forehead_mask] += ((forehead_level-50)/50 * 10 * 
                                               cp.sin(y_indices[forehead_mask]/height * cp.pi))

                    if abs(hairline_level - 50) > 3:
                        hairline_y = int(height * 0.15)
                        hairline_mask = y_indices < hairline_y
                        map_y[hairline_mask] += ((hairline_level-50)/50 * 15 * 
                                               (hairline_y - y_indices[hairline_mask]) / hairline_y)

                # 使用 remap
                map_x_cpu = cp.asnumpy(map_x).astype(np.float32)
                map_y_cpu = cp.asnumpy(map_y).astype(np.float32)
                result = cv2.remap(cp.asnumpy(gpu_image), map_x_cpu, map_y_cpu, 
                                 cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
            else:
                result = cp.asnumpy(gpu_image)

            # 如果之前有縮放，現在需要放大回原始尺寸
            if scale_factor < 1.0:
                result = cv2.resize(result, (orig_w, orig_h), interpolation=cv2.INTER_LINEAR)

            return result

        except Exception as e:
            print(f"Error in _apply_beautify: {str(e)}")
            return image