This commit is contained in:
Summer committed 2025-05-02 13:57:40 -07:00
1 parent 51ffed98b1
commit b2bad824a6
7 files changed
+110 -73

No files matched your search

+2
View File
@@ -79,6 +79,8 @@
"algorithm.minFrequencyCutoffTooltip": "",
"algorithm.speedCoefficient": "Speed Coefficient",
"algorithm.speedCoefficientTooltip": "",
"algorithm.clearCalibration": "Clear Calibration",
"algorithm.clearCalibrationTooltip": "Reset all calibration values to their defaults",
"camera.selectEntireFrame": "Select Entire Frame",
"camera.selectEntireFrameTooltip": "Automatically set ROI",
"camera.rotation": "Rotation",
+2
View File
@@ -151,6 +151,8 @@
"calibration.maxLeftValue": "Max Left Value",
"calibration.minRightValue": "Min Right Value",
"calibration.maxRightValue": "Max Right Value",
"algorithm.clearCalibration": "Clear Calibration",
"algorithm.clearCalibrationTooltip": "Reset all calibration values to their defaults",
"general.theme": "Theme",
"general.theme.system": "System",
"general.theme.light": "Light",
+15
View File
@@ -24,6 +24,7 @@ class AlgoSettingsWidget:
self.gui_gpu_index = f"GPUINDEX{widget_id}"
self.calib_deadzone = f"CALIBDEADZONE{widget_id}"
self.main_config = main_config
self.main_config.settings.widget_id = widget_id
self.config = main_config.settings
self.osc_queue = osc_queue
self.runtime_list = ("Default (ONNX)", "ONNX")
@@ -153,6 +154,14 @@ class AlgoSettingsWidget:
background_color=bg_color_highlight,
),
],
[
sg.Button(
lang._instance.get_string("algorithm.clearCalibration"),
key=f"-CLEARCALIBRATION{widget_id}-",
button_color=("white", "#d9534f"),
tooltip=lang._instance.get_string("algorithm.clearCalibrationTooltip"),
),
],
]
self.cancellation_event = (
@@ -200,6 +209,12 @@ class AlgoSettingsWidget:
window[self.gui_inference_threads].update(value)
values[self.gui_inference_threads] = value
# --- Begin patch: handle clear calibration button ---
if event == f"-CLEARCALIBRATION{self.main_config.settings.widget_id}-":
if hasattr(self.main_config.settings, "calibration_filter") and hasattr(self.main_config.settings.calibration_filter, "clear_calibration"):
self.main_config.settings.calibration_filter.clear_calibration()
sg.popup(lang._instance.get_string("algorithm.calibrationCleared"), title="Calibration Reset")
# --- End patch ---
elif event == self.gui_gpu_index:
value = values[self.gui_gpu_index]
if not is_valid_int_input(value):
+2 -2
View File
@@ -377,13 +377,13 @@ async def main_loop(window, config, cams, settings, thread_manager):
config.cam_display_id = Tab.SETTINGS
config.save()
elif (
elif (
values[UIConstants.ALGO_SETTINGS_RADIO_NAME]
and config.cam_display_id != Tab.ALGOSETTINGS
):
cams[0].stop()
settings[0].stop()
settings[2].stop()
settings[2].stop()
settings[1].start()
window[UIConstants.CAM_NAME].update(visible=False)
window[UIConstants.SETTINGS_NAME].update(visible=False)
+1 -1
View File
@@ -11,7 +11,7 @@ from enum import Enum
import serial.tools.list_ports
from lang_manager import LocaleStringManager as lang
from colorama import Fore
from config import BabbleConfig, BabbleSettingsConfig
from config import BabbleConfig, BabbleSettingsConfig, BabbleCameraConfig
from PIL import Image
from io import BytesIO
from utils.misc_utils import get_camera_index_by_name, list_camera_names, os_type
+2 -1
View File
@@ -5,7 +5,7 @@ import shutil
from utils.misc_utils import ensurePath
from tab import Tab
from pydantic import BaseModel
from typing import Union
from typing import Union, Optional
from lang_manager import LocaleStringManager as lang
CONFIG_FILE_NAME: str = "babble_settings.json"
@@ -25,6 +25,7 @@ class BabbleCameraConfig(BaseModel):
class BabbleSettingsConfig(BaseModel):
widget_id: Optional[int] = None
gui_min_cutoff: str = "3"
gui_speed_coefficient: str = "0.9"
gui_osc_address: str = "127.0.0.1"
+86 -69
View File
@@ -6,16 +6,19 @@ import os
from lang_manager import LocaleStringManager as lang
import numpy as np
from math import log
from enum import IntEnum
from utils.misc_utils import playSound
import os
from lang_manager import LocaleStringManager as lang
class CamId(IntEnum):
CAM = 0
SETTINGS = 1
class BlendShapeCalibrator:
"""
Continuous calibrator for blend shape model outputs.
Tracks independent minimum and maximum values for each blend shape to robustly calibrate and normalize outputs.
Implements time-weighted adaptation and separate strategies for neutral and active expressions.
"""
def __init__(self, num_blendshapes, alpha=0.1, beta=0.1, threshold_multiplier=2.0):
self.num_blendshapes = num_blendshapes
self.alpha = alpha
@@ -29,74 +32,95 @@ class BlendShapeCalibrator:
self.threshold = np.zeros(num_blendshapes)
self.confidence = np.ones(num_blendshapes)
self.sample_count = 0
# Time-weighted adaptation parameters
self.adaptation_rate = 1.0 # Starts aggressive, decreases over time
self.min_adaptation_rate = 0.1 # Minimum adaptation rate
self.adaptation_decay = 0.9999 # Decay factor for adaptation rate
# Hysteresis parameters to prevent oscillation
self.hysteresis_threshold = 0.05 # Minimum change required to update min/max
self.sample_counts = np.zeros(num_blendshapes, dtype=int)
self.calibrated_flags = np.zeros(num_blendshapes, dtype=bool)
self.warmup_frames = 300 # 5 seconds at 60 FPS
self.adaptation_rate = 1.0
self.min_adaptation_rate = 0.01
self.adaptation_decay = 0.99998 # Slower decay for long sessions
self.hysteresis_threshold = 0.05
self.decay_counters = np.zeros(num_blendshapes, dtype=int)
self.decay_threshold = 54000 # 10 minutes at 90 FPS (conservatively long)
self.decay_levels = np.zeros(num_blendshapes)
def update(self, input_array):
input_array = np.asarray(input_array)
if input_array.shape[0] != self.num_blendshapes:
raise ValueError(f"Expected input of length {self.num_blendshapes}, got {input_array.shape[0]}")
# Update adaptation rate - decreases over time for stability
if self.sample_count > 0:
self.adaptation_rate = max(self.min_adaptation_rate,
self.adaptation_rate * self.adaptation_decay)
self.adaptation_rate = max(self.min_adaptation_rate, self.adaptation_rate * self.adaptation_decay)
if not self.initialized:
self.min = input_array.astype(float).copy()
self.max = input_array.astype(float).copy()
self.mean = input_array.astype(float).copy()
self.variance = np.zeros(self.num_blendshapes)
self.initialized = True
# Identify neutral and active expressions
if self.sample_count < self.warmup_frames:
self.min = np.minimum(self.min, input_array)
self.max = np.maximum(self.max, input_array)
self.mean = self.alpha * input_array + (1 - self.alpha) * self.mean
self.sample_count += 1
return self.min, self.max, np.ones(self.num_blendshapes), self.calibrated_flags
neutral_threshold = 0.15
neutral_mask = np.abs(input_array) < neutral_threshold
active_mask = ~neutral_mask
is_neutral_pose = np.sum(neutral_mask) >= int(0.8 * self.num_blendshapes)
# Apply hysteresis to prevent oscillation
min_diff = self.min - input_array
max_diff = input_array - self.max
# Update strategy for neutral expressions - establish baseline
if is_neutral_pose:
# Only update min values that exceed hysteresis threshold
update_min_mask = (min_diff > self.hysteresis_threshold) & neutral_mask
if np.any(update_min_mask):
self.min[update_min_mask] = self.adaptation_rate * input_array[update_min_mask] + \
(1 - self.adaptation_rate) * self.min[update_min_mask]
# Update mean for neutral expressions
self.mean[neutral_mask] = self.alpha * input_array[neutral_mask] + \
(1 - self.alpha) * self.mean[neutral_mask]
# Update strategy for active expressions - capture true ranges
if np.any(active_mask):
# Only update max values that exceed hysteresis threshold
update_max_mask = (max_diff > self.hysteresis_threshold) & active_mask
if np.any(update_max_mask):
self.max[update_max_mask] = self.adaptation_rate * input_array[update_max_mask] + \
(1 - self.adaptation_rate) * self.max[update_max_mask]
# Calculate confidence based on distance from mean
self.min[update_min_mask] = self.adaptation_rate * input_array[update_min_mask] + (1 - self.adaptation_rate) * self.min[update_min_mask]
self.mean[neutral_mask] = self.alpha * input_array[neutral_mask] + (1 - self.alpha) * self.mean[neutral_mask]
update_max_mask = (max_diff > self.hysteresis_threshold) & active_mask
# Modify adaptation rate if shape decayed a lot
per_shape_adaptation = np.full(self.num_blendshapes, self.adaptation_rate)
high_decay_mask = self.decay_levels > 0.1 # Threshold for high decay
per_shape_adaptation[high_decay_mask] = 0.5 # More aggressive update
self.max[update_max_mask] = per_shape_adaptation[update_max_mask] * input_array[update_max_mask] + \
(1 - per_shape_adaptation[update_max_mask]) * self.max[update_max_mask]
below_max_mask = input_array < self.max * 0.9
self.decay_counters[below_max_mask] += 1
decay_mask = self.decay_counters > self.decay_threshold
self.decay_levels[decay_mask] += 0.01 # track how much it's been decayed
self.max[decay_mask] *= 0.999 # Very slow decay
self.decay_counters[~below_max_mask] = 0
self.decay_levels[~below_max_mask] *= 0.95 # Slowly fade decay level back down
swap_mask = self.min > self.max
avg = (self.min[swap_mask] + self.max[swap_mask]) / 2
self.min[swap_mask] = avg
self.max[swap_mask] = avg
diff = input_array - self.mean
std = np.sqrt(self.variance)
self.threshold = self.multiplier * std
epsilon = 1e-6
denom = self.threshold + epsilon
confidence = np.exp(-np.abs(diff) / denom)
# Update variance for tracking
self.variance = self.beta * (diff ** 2) + (1 - self.beta) * self.variance
self.confidence = confidence
std = np.sqrt(self.variance) + 1e-6
self.threshold = self.multiplier * std
self.confidence = np.exp(-np.abs(diff) / self.threshold)
self.sample_count += 1
return self.min, self.max, self.confidence
self.sample_counts += 1
for i in range(self.num_blendshapes):
if not self.calibrated_flags[i]:
if (self.max[i] - self.min[i] > 1e-3 and
self.sample_counts[i] >= 300 and # ~5s at 60FPS
self.variance[i] > 1e-4):
self.calibrated_flags[i] = True
return self.min, self.max, self.confidence, self.calibrated_flags
class cal:
def __init__(self, settings=None):
@@ -107,39 +131,32 @@ class cal:
self.confidence = None
self.continuous_enabled = getattr(settings, 'continuous_calibration', True) if settings else True
def clear_calibration(self):
self.calibrator = None
self.calibrated_array = None
self.raw_array = None
self.confidence = None
def cal_osc(self, array):
"""Calibrate input array using adaptive calibration algorithm.
The improved algorithm features:
- Time-weighted adaptation (more aggressive initially, stabilizes over time)
- Separate strategies for neutral and active expressions
- Hysteresis to prevent oscillation between states
Args:
array: Input blendshape values to calibrate
Returns:
Calibrated array with values normalized to [0,1] range
"""
self.raw_array = array
if self.calibrator is None or (self.calibrator.num_blendshapes != len(array)):
self.calibrator = BlendShapeCalibrator(num_blendshapes=len(array))
if self.settings and hasattr(self.settings, 'continuous_calibration'):
self.continuous_enabled = self.settings.continuous_calibration
if self.continuous_enabled:
min_vals, max_vals, confidence = self.calibrator.update(array)
# Normalize using running min and max
min_vals, max_vals, confidence, calibrated_flags = self.calibrator.update(array)
denom = (max_vals - min_vals)
denom[denom == 0] = 1e-6 # Prevent division by zero
calibrated = (array - min_vals) / denom
denom[denom == 0] = 1e-6
calibrated = np.zeros_like(array)
for i in range(len(array)):
if calibrated_flags[i]:
calibrated[i] = (array[i] - min_vals[i]) / denom[i]
self.calibrated_array = np.clip(calibrated, 0, 1)
self.confidence = confidence
# --- Begin patch: propagate calibration to config and widget ---
if hasattr(self.settings, 'calib_array'):
self.settings.calib_array = np.array2string(np.vstack((min_vals, max_vals)), separator=",")
if hasattr(self.settings, 'main_config') and hasattr(self.settings.main_config, 'save'):
self.settings.main_config.save()
# --- End patch ---
return self.calibrated_array
else:
self.calibrated_array = np.clip(array, 0, 1)