Merge branch 'v2.0-beta-feature-branch' into improve-roi-rotation

This commit is contained in:
Prohurtz 2024-07-10 16:50:50 -05:00 committed by GitHub
commit 8d01217c8c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
65 changed files with 228851 additions and 1855 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

6
.coveragerc Normal file
View File

@ -0,0 +1,6 @@
[run]
omit=
tests/*
conftest.py
source =
EyeTrackApp

1034
EyeTrackApp/AHSF.py Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 618 B

After

Width:  |  Height:  |  Size: 408 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.4 KiB

After

Width:  |  Height:  |  Size: 570 B

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

View File

@ -1,21 +0,0 @@
import PySimpleGUI as sg
from config import EyeTrackConfig
from osc import EyeId
from settings.BaseSettings import BaseSettingsWidget
from settings.modules.AdvancedTrackingAlgoSettingsModule import (
AdvancedTrackingAlgoSettingsModule,
)
from settings.modules.BlinkAlgoModule import BlinkAlgoSettingsModule
from settings.modules.TrackingAlgorithmModule import TrackingAlgorithmModule
class AlgoSettingsWidget(BaseSettingsWidget):
def __init__(self, widget_id: EyeId, main_config: EyeTrackConfig):
settings_modules = [
TrackingAlgorithmModule,
BlinkAlgoSettingsModule,
AdvancedTrackingAlgoSettingsModule,
]
super().__init__(widget_id, main_config, settings_modules)

View File

@ -1,6 +1,36 @@
"""
------------------------------------------------------------------------------------------------------
,@@@@@@
@@@@@@@@@@@ @@@
@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@@ @@@@@@@@@@@@@@
@@@@@@@/ ,@@@@@@@@@@@@@
/@@@@@@@@@@@@@@@ @@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@
@@@@@@@@ @@@@@
,@@@ @@@@&
@@@@@@. @@@@
@@@ @@@@@@@@@/ @@@@@
,@@@. @@@@@@((@ @@@@(
//@@@ ,, @@@@ @@@@@
@@@( @@@@@@@
@@@ @ @@@@@@@@#
@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@(
Binary Intensity Based Blink by: Summer, Prohurtz
Algorithm App Implementations and tweaks By: Prohurtz
Copyright (c) 2023 EyeTrackVR <3
LICENSE: Summer Software Distribution License 1.0
------------------------------------------------------------------------------------------------------
"""
import numpy as np
def BLINK(self):
def BLINK(self):
if self.blink_clear == True:
self.max_ints = []
@ -10,14 +40,18 @@ def BLINK(self):
intensity = np.sum(self.current_image_gray_clean)
if self.calibration_frame_counter == 300:
self.filterlist = [] #clear filter
self.filterlist = [] # clear filter
if len(self.filterlist) < 300:
self.filterlist.append(intensity)
else:
self.filterlist.pop(0)
self.filterlist.append(intensity)
if intensity >= np.percentile(self.filterlist, 99) or intensity <= np.percentile(self.filterlist, 1) and len(self.max_ints) >= 1: # filter abnormally high values
try: # I don't want this here but I cant get python to stop crying when it's not
if (
intensity >= np.percentile(self.filterlist, 99)
or intensity <= np.percentile(self.filterlist, 1)
and len(self.max_ints) >= 1
): # filter abnormally high values
try: # I don't want this here but I cant get python to stop crying when it's not
intensity = min(self.max_ints)
except:
pass
@ -25,7 +59,7 @@ def BLINK(self):
self.frames = self.frames + 1
if intensity > self.max_int:
self.max_int = intensity
if self.frames > 300: #TODO: test this number more (make it a setting??)
if self.frames > 300: # TODO: test this number more (make it a setting??)
self.max_ints.append(self.max_int)
if intensity < self.min_int:
self.min_int = intensity
@ -34,9 +68,11 @@ def BLINK(self):
if intensity > min(self.max_ints):
blinkvalue = 0.0
else:
blinkvalue = 0.7
blinkvalue = 0.8
try:
return blinkvalue
except:
return 0.7
# print(self.blinkvalue, self.max_int, self.min_int, self.frames, intensity)
return 0.8
# print(self.blinkvalue, self.max_int, self.min_int, self.frames, intensity)

View File

@ -19,23 +19,15 @@
@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@(
BLOB By: Prohurtz#0001 (Main App Developer)
Algorithm App Implimentations By: Prohurtz#0001, qdot (Inital App Creator)
BLOB By: Prohurtz
Algorithm App Implimentations By: Prohurtz, qdot (Inital App Creator)
Copyright (c) 2023 EyeTrackVR <3
LICENSE: GNU GPLv3
------------------------------------------------------------------------------------------------------
"""
import cv2
import numpy as np
from enum import IntEnum
class EyeId(IntEnum):
RIGHT = 0
LEFT = 1
BOTH = 2
SETTINGS = 3
def BLOB(self):

View File

@ -0,0 +1,2 @@
cd Tools\
EyeTrackVR-Overlay.exe

View File

@ -1,3 +1,29 @@
"""
------------------------------------------------------------------------------------------------------
,@@@@@@
@@@@@@@@@@@ @@@
@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@@ @@@@@@@@@@@@@@
@@@@@@@/ ,@@@@@@@@@@@@@
/@@@@@@@@@@@@@@@ @@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@
@@@@@@@@ @@@@@
,@@@ @@@@&
@@@@@@. @@@@
@@@ @@@@@@@@@/ @@@@@
,@@@. @@@@@@((@ @@@@(
//@@@ ,, @@@@ @@@@@
@@@( @@@@@@@
@@@ @ @@@@@@@@#
@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@(
Copyright (c) 2023 EyeTrackVR <3
LICENSE: GNU GPLv3
------------------------------------------------------------------------------------------------------
"""
import cv2
import numpy as np
import queue
@ -5,10 +31,23 @@ import serial
import serial.tools.list_ports
import threading
import time
import platform
from colorama import Fore
from config import EyeTrackConfig
from config import EyeTrackCameraConfig
from enum import Enum
import psutil, os
import sys
process = psutil.Process(os.getpid()) # set process priority to low
try:
sys.getwindowsversion()
except AttributeError:
process.nice(10) # UNIX: 0 low 10 high
process.nice()
else:
process.nice(psutil.HIGH_PRIORITY_CLASS) # Windows
process.nice()
# See https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getpriorityclass#return-value for values
WAIT_TIME = 0.1
# Serial communication protocol:
@ -27,15 +66,24 @@ class CameraState(Enum):
DISCONNECTED = 2
def is_serial_capture_source(addr: str) -> bool:
"""
Returns True if the capture source address is a serial port.
"""
return (
addr.startswith("COM") or addr.startswith("/dev/cu") or addr.startswith("/dev/tty") # Windows # macOS # Linux
)
class Camera:
def __init__(
self,
config: EyeTrackConfig,
config: EyeTrackCameraConfig,
camera_index: int,
cancellation_event: "threading.Event",
capture_event: "threading.Event",
camera_status_outgoing: "queue.Queue[CameraState]",
camera_output_outgoing: "queue.Queue(maxsize=2)",
camera_output_outgoing: "queue.Queue(maxsize=20)",
):
self.camera_status = CameraState.CONNECTING
self.config = config
@ -79,13 +127,23 @@ class Camera:
while True:
if self.cancellation_event.is_set():
print(f"{Fore.CYAN}[INFO] Exiting Capture thread{Fore.RESET}")
# openCV won't switch to a new source if provided with one
# so, we have to manually release the camera on exit
addr = str(self.current_capture_source)
if is_serial_capture_source(addr):
self.serial_connection.close()
else:
self.cv2_camera.release()
return
should_push = True
# If things aren't open, retry until they are. Don't let read requests come in any earlier
# than this, otherwise we can deadlock ourselves.
if self.config.capture_source != None and self.config.capture_source != "":
if "COM" in str(self.current_capture_source):
self.current_capture_source = self.config.capture_source
addr = str(self.current_capture_source)
if is_serial_capture_source(addr):
if (
self.serial_connection is None
or self.camera_status == CameraState.DISCONNECTED
@ -122,10 +180,11 @@ class Camera:
# Assuming we can access our capture source, wait for another thread to request a capture.
# Cycle every so often to see if our cancellation token has fired. This basically uses a
# python event as a context-less, resettable one-shot channel.
if should_push and not self.capture_event.wait(timeout=0.02):
if should_push and not self.capture_event.wait(timeout=0.001):
continue
if self.config.capture_source != None:
if "COM" in str(self.current_capture_source):
addr = str(self.current_capture_source)
if is_serial_capture_source(addr):
self.get_serial_camera_picture(should_push)
else:
self.get_cv2_camera_picture(should_push)
@ -165,7 +224,7 @@ class Camera:
self.fl.pop(0)
self.fl.append(self.fps)
self.fps = sum(self.fl) / len(self.fl)
# self.bps = image.nbytes
# self.bps = image.nbytes
if should_push:
self.push_image_to_queue(image, frame_number, self.fps)
except:
@ -204,20 +263,14 @@ class Camera:
jpeg = self.get_next_jpeg_frame()
if jpeg:
# Create jpeg frame from byte string
image = cv2.imdecode(
np.fromstring(jpeg, dtype=np.uint8), cv2.IMREAD_UNCHANGED
)
image = cv2.imdecode(np.fromstring(jpeg, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
if image is None:
print(
f"{Fore.YELLOW}[WARN] Frame drop. Corrupted JPEG.{Fore.RESET}"
)
print(f"{Fore.YELLOW}[WARN] Frame drop. Corrupted JPEG.{Fore.RESET}")
return
# Discard the serial buffer. This is due to the fact that it
# may build up some outdated frames. A bit of a workaround here tbh.
if conn.in_waiting >= 32768:
print(
f"{Fore.CYAN}[INFO] Discarding the serial buffer ({conn.in_waiting} bytes){Fore.RESET}"
)
print(f"{Fore.CYAN}[INFO] Discarding the serial buffer ({conn.in_waiting} bytes){Fore.RESET}")
conn.reset_input_buffer()
self.buffer = b""
# Calculate the fps.
@ -260,15 +313,14 @@ class Camera:
if not any(p for p in com_ports if port in p):
return
try:
conn = serial.Serial(
baudrate=3000000, port=port, xonxoff=False, dsrdtr=False, rtscts=False
)
rate = 115200 if sys.platform == "darwin" else 3000000 # Higher baud rate not working on macOS
conn = serial.Serial(baudrate=rate, port=port, xonxoff=False, dsrdtr=False, rtscts=False)
# Set explicit buffer size for serial.
conn.set_buffer_size(rx_size=32768, tx_size=32768)
if sys.platform == "win32":
buffer_size = 32768
conn.set_buffer_size(rx_size=buffer_size, tx_size=buffer_size)
print(
f"{Fore.CYAN}[INFO] ETVR Serial Tracker device connected on {port}{Fore.RESET}"
)
print(f"{Fore.CYAN}[INFO] ETVR Serial Tracker device connected on {port}{Fore.RESET}")
self.serial_connection = conn
self.camera_status = CameraState.CONNECTED
except Exception:

2
EyeTrackApp/center.bat Normal file
View File

@ -0,0 +1,2 @@
cd Tools\
ETVR_SteamVR_Calibration_Overlay.exe center

View File

@ -1,4 +1,4 @@
'''
"""
------------------------------------------------------------------------------------------------------
,@@@@@@
@ -23,8 +23,9 @@ DADDY By: PallasNeko Optimization
Algorithm App Implementations By: PallasNeko, Prohurtz
Copyright (c) 2023 EyeTrackVR <3
LICENSE: GNU GPLv3
------------------------------------------------------------------------------------------------------
'''
"""
import sys
from typing import Tuple
import math
@ -35,6 +36,7 @@ import onnxruntime
from one_euro_filter import OneEuroFilter
from utils.misc_utils import FastMedian, resource_path
import os
os.environ["OMP_NUM_THREADS"] = "1"
# DADDY
# Please change the name of this script and the name of the method if you have something better.
@ -43,15 +45,16 @@ input_size = 192 # Do not change this number.
heatmap_size = 48 # Do not change this number.
kernel_size = 7
if platform.system() == "Darwin":
model_file = "EyeTrackApp/Models/daddy230210.onnx" # The model file name will be changed when performance stabilises. # funny MacOS files issues :P
model_file = "Models/daddy230210.onnx" # The model file name will be changed when performance stabilises. # funny MacOS files issues :P
else:
model_file = "Models/daddy230210.onnx" # The model file name will be changed when performance stabilises.
# SHA256 for model version verification
# daddy230210.onnx = 59e59aa2a21024884200dd3acbd5e6a2e8d7209c46555fbdc727d4fe3adb68d3
imshow_enable = False
save_video = False
save_filepath = 'output.mp4'
save_filepath = "output.mp4"
def get_max_preds(batch_heatmaps):
@ -62,18 +65,18 @@ def get_max_preds(batch_heatmaps):
heatmaps_reshaped = batch_heatmaps.reshape((batch_size, num_joints, -1))
idx = np.argmax(heatmaps_reshaped, 2)
maxvals = np.amax(heatmaps_reshaped, 2)
maxvals = maxvals.reshape((batch_size, num_joints, 1))
idx = idx.reshape((batch_size, num_joints, 1))
preds = np.tile(idx, (1, 1, 2)).astype(np.float32)
preds[:, :, 0] = (preds[:, :, 0]) % width
preds[:, :, 1] = np.floor((preds[:, :, 1]) / width)
pred_mask = np.tile(np.greater(maxvals, 0.0), (1, 1, 2))
pred_mask = pred_mask.astype(np.float32)
preds *= pred_mask
return preds, maxvals
@ -88,12 +91,11 @@ def taylor(hm, coord):
dx = 0.5 * (hm[py][px + 1] - hm[py][px - 1])
dy = 0.5 * (hm[py + 1][px] - hm[py - 1][px])
dxx = 0.25 * (hm[py][px + 2] - 2 * hm[py][px] + hm[py][px - 2])
dxy = 0.25 * (hm[py + 1][px + 1] - hm[py - 1][px + 1] - hm[py + 1][px - 1] \
+ hm[py - 1][px - 1])
dxy = 0.25 * (hm[py + 1][px + 1] - hm[py - 1][px + 1] - hm[py + 1][px - 1] + hm[py - 1][px - 1])
dyy = 0.25 * (hm[py + 2 * 1][px] - 2 * hm[py][px] + hm[py - 2 * 1][px])
derivative = np.matrix([[dx], [dy]])
hessian = np.matrix([[dxx, dxy], [dxy, dyy]])
if dxx * dyy - dxy ** 2 != 0:
if dxx * dyy - dxy**2 != 0:
hessianinv = hessian.I
offset = -hessianinv * derivative
offset = np.squeeze(np.array(offset.T), axis=0)
@ -112,9 +114,9 @@ def gaussian_blur(hm, kernel):
for j in range(num_joints):
origin_max = np.max(hm[i, j])
dr = np.zeros((height + 2 * border, width + 2 * border))
dr[border: -border, border: -border] = hm[i, j].copy()
dr[border:-border, border:-border] = hm[i, j].copy()
dr = cv2.GaussianBlur(dr, (kernel, kernel), 0)
hm[i, j] = dr[border: -border, border: -border].copy()
hm[i, j] = dr[border:-border, border:-border].copy()
hm[i, j] *= origin_max / np.max(hm[i, j])
return hm
@ -122,7 +124,7 @@ def gaussian_blur(hm, kernel):
def get_final_preds(hm, realsize):
# base:https://github.com/ilovepose/DarkPose
coords, maxvals = get_max_preds(hm)
# post-processing
hm = gaussian_blur(hm, kernel_size)
hm = np.maximum(hm, 1e-10)
@ -130,22 +132,22 @@ def get_final_preds(hm, realsize):
for n in range(coords.shape[0]):
for p in range(coords.shape[1]):
coords[n, p] = taylor(hm[n][p], coords[n][p])
preds = coords.copy()
preds = (preds / heatmap_size) * realsize # input_size
# Transform back
# for i in range(coords.shape[0]):
# preds[i] = transform_preds(
# coords[i], center[i], scale[i], [heatmap_width, heatmap_height]
# )
return preds, maxvals
def resize_with_pad(image: np.array,
new_shape: Tuple[int, int],
padding_color: Tuple[int] = (255, 255, 255)) -> np.array:
def resize_with_pad(
image: np.array, new_shape: Tuple[int, int], padding_color: Tuple[int] = (255, 255, 255)
) -> np.array:
"""
https://gist.github.com/IdeaKing/11cf5e146d23c5bb219ba3508cca89ec
Maintains aspect ratio and resizes with padding.
@ -177,29 +179,32 @@ class BEER(object):
self.p03_med = FastMedian(k=256)
self.prev_ear = 0.5
# todo https://peerj.com/articles/cs-943/
def ear(self, pred):
p15 = np.linalg.norm(pred[1]-pred[5])
p24 = np.linalg.norm(pred[2]-pred[4])
p03 = np.linalg.norm(pred[0]-pred[3])
self.p03_med+p03
if p03 > self.p03_med.median()*1.5:
p15 = np.linalg.norm(pred[1] - pred[5])
p24 = np.linalg.norm(pred[2] - pred[4])
p03 = np.linalg.norm(pred[0] - pred[3])
self.p03_med + p03
if p03 > self.p03_med.median() * 1.5:
return self.prev_ear
ear = (p15+p24)/(2*self.p03_med.median())
ear = (p15 + p24) / (2 * self.p03_med.median())
self.ear_minmax(ear)
norm_ear = self.ear_norm(ear)
self.prev_ear = norm_ear.copy()
return norm_ear
def ear_minmax(self,ear):
def ear_minmax(self, ear):
if ear < self.ear_min:
self.ear_min = ear.copy()
if ear > self.ear_max:
self.ear_max = ear.copy()
def ear_norm(self,ear):
return (ear-self.ear_min)/(self.ear_max-self.ear_min) # todo:It is better to add very small values to avoid zero division.
def ear_norm(self, ear):
return (ear - self.ear_min) / (
self.ear_max - self.ear_min
) # todo:It is better to add very small values to avoid zero division.
#
# loopnum = 0
@ -214,35 +219,33 @@ class DADDY_cls(object):
options.intra_op_num_threads = 1 # This number should be changed accordingly
options.execution_mode = onnxruntime.ExecutionMode.ORT_SEQUENTIAL
options.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
ort_session = onnxruntime.InferenceSession(resource_path(model_file), sess_options=options, providers=["CPUExecutionProvider"])
ort_session.set_providers(['CPUExecutionProvider']) # only cpu mode
ort_session = onnxruntime.InferenceSession(
resource_path(model_file), sess_options=options, providers=["CPUExecutionProvider"]
)
ort_session.set_providers(["CPUExecutionProvider"]) # only cpu mode
self.ort_session = ort_session
self.input_name = ort_session.get_inputs()[0].name
self.output_name = ort_session.get_outputs()[0].name
min_cutoff = 0.0004
beta = 0.9
input_point = np.zeros((11, 2)) # np.array([1, 1])
self.one_euro_filter = OneEuroFilter(
input_point,
min_cutoff=min_cutoff,
beta=beta
)
self.one_euro_filter = OneEuroFilter(input_point, min_cutoff=min_cutoff, beta=beta)
# self.ear_oef = OneEuroFilter(
# np.zeros(1),
# min_cutoff=min_cutoff,
# beta=beta
# ) # memo: Parameters need tuning
self.beer = BEER()
# filepath = 'test.mp4'
# codec = cv2.VideoWriter_fourcc(*"mp4v")
# video = cv2.VideoWriter(filepath, codec, 60.0, (200, 150), 0) # (60, 60)) # (150, 200))
# self.video = video
def open_video(self, video_path):
# Temporary implementation to run
cap = cv2.VideoCapture(video_path)
@ -250,7 +253,7 @@ class DADDY_cls(object):
raise IOError("Error opening video stream or file")
self.cap = cap
return True
def read_frame(self):
# Temporary implementation to run
if not self.cap.isOpened():
@ -262,26 +265,28 @@ class DADDY_cls(object):
self.current_image_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
return True
return False
def single_run(self):
# Temporary implementation to run
# todo: If it's the left hand eye, flip the image left to right.
gray_frame = self.current_image_gray.copy()
# frame_resize=resize_with_pad(gray_frame,(input_size,input_size))
# or
frame_resize = cv2.resize(gray_frame, (input_size, input_size))
imgs = np.divide(frame_resize[np.newaxis, np.newaxis], 255, dtype=np.float32) # input/255.0
pred_heatmap = self.ort_session.run(None, {self.input_name: imgs})[0] # .reshape((-1, 2))
# if imshow_enable:
# heatmap = pred_heatmap.reshape((-1, heatmap_size, heatmap_size))
# for i in range(heatmap.shape[0]):
# cv2.imshow("heatmap_{}".format(i + 1), heatmap[i])
pred, max_val = get_final_preds(pred_heatmap, (self.current_image_gray.shape[1], self.current_image_gray.shape[0]))
pred, max_val = get_final_preds(
pred_heatmap, (self.current_image_gray.shape[1], self.current_image_gray.shape[0])
)
pred = pred.reshape((-1, 2))
# or
# pred, max_val = get_final_preds(pred_heatmap, input_size)
@ -294,7 +299,7 @@ class DADDY_cls(object):
pred = self.one_euro_filter(pred)
kps = pred.astype(np.int32)
# eyecenter = kps[:6].mean(axis=0).astype(int)
ear = self.beer.ear(pred)
# ear=self.ear_oef(ear[np.newaxis])#memo: Parameters need tuning
@ -315,7 +320,6 @@ class DADDY_cls(object):
# cv2.putText(self.current_image_gray, str(i), (kps[i, 0] - 10, kps[i, 1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)
# cv2.putText(self.current_image_gray, "EAR: "+str(ear), (self.current_image_gray.shape[1]//10, self.current_image_gray.shape[0]//10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (255,0,0), 1)
# global loopnum
# if loopnum < 1350*2:
# # self.video.write(cv2.resize(gray_frame.copy(), (200, 150), None))
@ -326,19 +330,19 @@ class DADDY_cls(object):
# sys.exit()
# if w_video:
# video.release()
# kps[i, :] = (x, y)
# i == [0:6] = Inner and outer corners of eyes and eyelids
# i == [6] = pupil
# i == [7:] = iris
return pupil_center_x, pupil_center_y, ear
class External_Run_DADDY(object):
def __init__(self):
self.algo = DADDY_cls()
def run(self, current_image_gray):
self.algo.current_image_gray = current_image_gray
pupil_x, pupil_y, ear = self.algo.single_run()
@ -349,4 +353,4 @@ if __name__ == "__main__":
daddy = DADDY_cls()
daddy.open_video(video_path)
while daddy.read_frame():
_ = daddy.single_run()
_ = daddy.single_run()

View File

@ -23,6 +23,7 @@ Ellipse Based Pupil Dilation By: Prohurtz, PallasNeko (Optimization)
Algorithm App Implementations By: Prohurtz
Copyright (c) 2023 EyeTrackVR <3
LICENSE: GNU GPLv3
------------------------------------------------------------------------------------------------------
"""
import numpy
@ -30,30 +31,10 @@ import numpy as np
import time
import os
import cv2
from enums import EyeLR
from eye import EyeId
from one_euro_filter import OneEuroFilter
from utils.img_utils import safe_crop
from enum import IntEnum
import psutil
import sys
process = psutil.Process(os.getpid()) # set process priority to low
try: # medium chance this does absolutely nothing but eh
sys.getwindowsversion()
except AttributeError:
process.nice(0) # UNIX: 0 low 10 high
process.nice()
else:
process.nice(psutil.BELOW_NORMAL_PRIORITY_CLASS) # Windows
process.nice()
class EyeId(IntEnum):
RIGHT = 0
LEFT = 1
BOTH = 2
SETTINGS = 3
os.environ["OMP_NUM_THREADS"] = "1"
# Note.
# OpenCV on Windows will generate an error if the file path contains non-ASCII characters when using cv2.imread(), cv2.imwrite(), etc.
@ -359,9 +340,10 @@ class EllipseBasedPupilDilation:
minp = float(self.maxval)
try:
eyedilation = (pupil_area - maxp) / (
minp - maxp
) # for whatever reason when input and maxp are too close it outputs high
if not np.isfinite(pupil_area) or not np.isfinite(maxp) or not np.isfinite(minp) or (minp - maxp) == 0:
eyedilation = 0.5
else:
eyedilation = (pupil_area - maxp) / (minp - maxp)
except:
eyedilation = 0.5
eyedilation = 1 - eyedilation
@ -381,7 +363,7 @@ class EllipseBasedPupilDilation:
eyedilation = 0.0
if changed and (
(time.time() - self.lct) > 5
(time.time() - self.lct) > 15
): # save every 5 seconds if something changed to save disk usage
self.save()
self.lct = time.time()

View File

@ -1,13 +1,49 @@
"""
------------------------------------------------------------------------------------------------------
,@@@@@@
@@@@@@@@@@@ @@@
@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@@ @@@@@@@@@@@@@@
@@@@@@@/ ,@@@@@@@@@@@@@
/@@@@@@@@@@@@@@@ @@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@
@@@@@@@@ @@@@@
,@@@ @@@@&
@@@@@@. @@@@
@@@ @@@@@@@@@/ @@@@@
,@@@. @@@@@@((@ @@@@(
//@@@ ,, @@@@ @@@@@
@@@( @@@@@@@
@@@ @ @@@@@@@@#
@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@(
Copyright (c) 2023 EyeTrackVR <3
LICENSE: GNU GPLv3
------------------------------------------------------------------------------------------------------
"""
from __future__ import annotations
import types
from collections import namedtuple
from typing import Any, ClassVar, Dict, List, Optional, TYPE_CHECKING, Tuple, Type, TypeVar, Iterator, Mapping
from typing import (
Any,
ClassVar,
Dict,
List,
TYPE_CHECKING,
Tuple,
Type,
TypeVar,
Iterator,
Mapping,
)
__all__ = (
'Enum',
# 'EyeId',
'EyeLR',
"Enum",
"EyeLR",
)
if TYPE_CHECKING:
@ -17,9 +53,9 @@ if TYPE_CHECKING:
def _create_value_cls(name: str, comparable: bool):
# All the type ignores here are due to the type checker being unable to recognise
# Runtime type creation without exploding.
cls = namedtuple('_EnumValue_' + name, 'name value')
cls.__repr__ = lambda self: f'<{name}.{self.name}: {self.value!r}>' # type: ignore
cls.__str__ = lambda self: f'{name}.{self.name}' # type: ignore
cls = namedtuple("_EnumValue_" + name, "name value")
cls.__repr__ = lambda self: f"<{name}.{self.name}: {self.value!r}>" # type: ignore
cls.__str__ = lambda self: f"{name}.{self.name}" # type: ignore
if comparable:
cls.__le__ = lambda self, other: isinstance(other, self.__class__) and self.value <= other.value # type: ignore
cls.__ge__ = lambda self, other: isinstance(other, self.__class__) and self.value >= other.value # type: ignore
@ -29,7 +65,9 @@ def _create_value_cls(name: str, comparable: bool):
def _is_descriptor(obj):
return hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__')
return (
hasattr(obj, "__get__") or hasattr(obj, "__set__") or hasattr(obj, "__delete__")
)
class EnumMeta(type):
@ -39,7 +77,14 @@ class EnumMeta(type):
_enum_member_map_: ClassVar[Dict[str, Any]]
_enum_value_map_: ClassVar[Dict[Any, Any]]
def __new__(cls, name: str, bases: Tuple[type, ...], attrs: Dict[str, Any], *, comparable: bool = False) -> Self:
def __new__(
cls,
name: str,
bases: Tuple[type, ...],
attrs: Dict[str, Any],
*,
comparable: bool = False,
):
value_mapping = {}
member_mapping = {}
member_names = []
@ -47,7 +92,7 @@ class EnumMeta(type):
value_cls = _create_value_cls(name, comparable)
for key, value in list(attrs.items()):
is_descriptor = _is_descriptor(value)
if key[0] == '_' and not is_descriptor:
if key[0] == "_" and not is_descriptor:
continue
# Special case classmethod to just pass through
@ -69,10 +114,10 @@ class EnumMeta(type):
member_mapping[key] = new_value
attrs[key] = new_value
attrs['_enum_value_map_'] = value_mapping
attrs['_enum_member_map_'] = member_mapping
attrs['_enum_member_names_'] = member_names
attrs['_enum_value_cls_'] = value_cls
attrs["_enum_value_map_"] = value_mapping
attrs["_enum_member_map_"] = member_mapping
attrs["_enum_member_names_"] = member_names
attrs["_enum_value_cls_"] = value_cls
actual_cls = super().__new__(cls, name, bases, attrs)
value_cls._actual_enum_cls_ = actual_cls # type: ignore # Runtime attribute isn't understood
return actual_cls
@ -81,13 +126,15 @@ class EnumMeta(type):
return (cls._enum_member_map_[name] for name in cls._enum_member_names_)
def __reversed__(cls) -> Iterator[Any]:
return (cls._enum_member_map_[name] for name in reversed(cls._enum_member_names_))
return (
cls._enum_member_map_[name] for name in reversed(cls._enum_member_names_)
)
def __len__(cls) -> int:
return len(cls._enum_member_names_)
def __repr__(cls) -> str:
return f'<enum {cls.__name__}>'
return f"<enum {cls.__name__}>"
@property
def __members__(cls) -> Mapping[str, Any]:
@ -103,10 +150,10 @@ class EnumMeta(type):
return cls._enum_member_map_[key]
def __setattr__(cls, name: str, value: Any) -> None:
raise TypeError('Enums are immutable.')
raise TypeError("Enums are immutable.")
def __delattr__(cls, attr: str) -> None:
raise TypeError('Enums are immutable')
raise TypeError("Enums are immutable")
def __instancecheck__(self, instance: Any) -> bool:
# isinstance(x, Y)
@ -118,8 +165,9 @@ class EnumMeta(type):
if TYPE_CHECKING:
from enum import Enum
from enum import Enum, IntEnum
else:
class Enum(metaclass=EnumMeta):
@classmethod
def try_value(cls, value):
@ -128,11 +176,13 @@ else:
except (KeyError, TypeError):
return value
E = TypeVar('E', bound='Enum')
E = TypeVar("E", bound="Enum")
def create_unknown_value(cls: Type[E], val: Any) -> E:
value_cls = cls._enum_value_cls_ # type: ignore # This is narrowed below
name = f'unknown_{val}'
name = f"unknown_{val}"
return value_cls(name=name, value=val)
@ -145,26 +195,12 @@ def try_enum(cls: Type[E], val: Any) -> E:
return cls._enum_value_map_[val] # type: ignore # All errors are caught below
except (KeyError, TypeError, AttributeError):
return create_unknown_value(cls, val)
# The line above is based on the code in the following url
# https://github.com/Rapptz/discord.py/blob/f7e97954950ffb0e34238d70813454caa6f1a3ae/discord/enums.py
# class EyeId(Enum):
# # https://docs.python.org/3.9/library/enum.html#functional-api
# # > The reason for defaulting to 1 as the starting number and not 0 is that 0 is False in a boolean sense, but enum members all evaluate to True.
# RIGHT = 1
# LEFT = 2
# BOTH = 3
# SETTINGS = 4
#
# def __str__(self) -> str:
# return self.name
#
# def __int__(self) -> int:
# return self.value
class EyeLR(Enum):
LEFT = 1
RIGHT = 2
@ -173,4 +209,4 @@ class EyeLR(Enum):
return self.name
def __int__(self) -> int:
return self.value
return self.value

View File

@ -1,3 +1,29 @@
"""
------------------------------------------------------------------------------------------------------
,@@@@@@
@@@@@@@@@@@ @@@
@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@@ @@@@@@@@@@@@@@
@@@@@@@/ ,@@@@@@@@@@@@@
/@@@@@@@@@@@@@@@ @@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@
@@@@@@@@ @@@@@
,@@@ @@@@&
@@@@@@. @@@@
@@@ @@@@@@@@@/ @@@@@
,@@@. @@@@@@((@ @@@@(
//@@@ ,, @@@@ @@@@@
@@@( @@@@@@@
@@@ @ @@@@@@@@#
@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@(
Copyright (c) 2023 EyeTrackVR <3
LICENSE: GNU GPLv3
------------------------------------------------------------------------------------------------------
"""
from dataclasses import dataclass
from enum import Enum, IntEnum
@ -8,6 +34,7 @@ class EyeId(IntEnum):
BOTH = 2
SETTINGS = 3
ALGOSETTINGS = 4
VRCFTMODULESETTINGS = 5
class EyeInfoOrigin(Enum):

View File

@ -1,3 +1,29 @@
"""
------------------------------------------------------------------------------------------------------
,@@@@@@
@@@@@@@@@@@ @@@
@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@@ @@@@@@@@@@@@@@
@@@@@@@/ ,@@@@@@@@@@@@@
/@@@@@@@@@@@@@@@ @@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@
@@@@@@@@ @@@@@
,@@@ @@@@&
@@@@@@. @@@@
@@@ @@@@@@@@@/ @@@@@
,@@@. @@@@@@((@ @@@@(
//@@@ ,, @@@@ @@@@@
@@@( @@@@@@@
@@@ @ @@@@@@@@#
@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@(
Copyright (c) 2023 EyeTrackVR <3
LICENSE: GNU GPLv3
------------------------------------------------------------------------------------------------------
"""
import os
import PySimpleGUI as sg
import queue
@ -6,9 +32,11 @@ import threading
from camera_widget import CameraWidget
from config import EyeTrackConfig
from eye import EyeId
from osc import VRChatOSCReceiver, VRChatOSC
from general_settings_widget import SettingsWidget
from algo_settings_widget import AlgoSettingsWidget
from settings.VRCFTModuleSettings import VRCFTSettingsWidget
from settings.general_settings_widget import SettingsWidget
from settings.algo_settings_widget import AlgoSettingsWidget
from osc.osc import OSCManager
from osc.OSCMessage import OSCMessage
from utils.misc_utils import is_nt, resource_path
if is_nt:
@ -23,14 +51,16 @@ RIGHT_EYE_NAME = "-RIGHTEYEWIDGET-"
LEFT_EYE_NAME = "-LEFTEYEWIDGET-"
SETTINGS_NAME = "-SETTINGSWIDGET-"
ALGO_SETTINGS_NAME = "-ALGOSETTINGSWIDGET-"
VRCFT_MODULE_SETTINGS_NAME = "-VRCFTSETTINGSWIDGET-"
LEFT_EYE_RADIO_NAME = "-LEFTEYERADIO-"
RIGHT_EYE_RADIO_NAME = "-RIGHTEYERADIO-"
BOTH_EYE_RADIO_NAME = "-BOTHEYERADIO-"
SETTINGS_RADIO_NAME = "-SETTINGSRADIO-"
ALGO_SETTINGS_RADIO_NAME = "-ALGOSETTINGSRADIO-"
VRCFT_MODULE_SETTINGS_RADIO_NAME = "-VRCFTSETTINGSRADIO-"
page_url = "https://github.com/RedHawk989/EyeTrackVR/releases/latest"
appversion = "EyeTrackApp 0.2.0 BETA 8"
appversion = "EyeTrackApp 0.2.0 BETA 11"
def main():
@ -39,50 +69,43 @@ def main():
config.save()
cancellation_event = threading.Event()
ROSC = False
# Check to see if we can connect to our video source first. If not, bring up camera finding
# dialog.
if config.settings.gui_update_check:
response = requests.get(
"https://api.github.com/repos/RedHawk989/EyeTrackVR/releases/latest"
)
latestversion = response.json()["name"]
if (
appversion == latestversion
): # If what we scraped and hardcoded versions are same, assume we are up to date.
print(f"\033[92m[INFO] App is the latest version! [{latestversion}]\033[0m")
else:
print(
f"\033[93m[INFO] You have app version [{appversion}] installed. Please update to [{latestversion}] for the newest features.\033[0m"
)
try:
if is_nt:
cwd = os.getcwd()
# icon = cwd + "\Images\logo.ico"
icon = resource_path("Images/logo.ico")
toast = Notification(
app_id="EyeTrackApp",
title="New Update Available!",
msg=f"Please update to {latestversion}",
icon=r"{}".format(icon),
)
toast.add_actions(
label="Download Page",
launch="https://github.com/RedHawk989/EyeTrackVR/releases/latest",
)
toast.show()
except Exception as e:
print("[INFO] Toast notifications not supported")
try:
if config.settings.gui_update_check:
response = requests.get("https://api.github.com/repos/EyeTrackVR/EyeTrackVR/releases/latest")
latestversion = response.json()["name"]
if (
appversion == latestversion
): # If what we scraped and hardcoded versions are same, assume we are up to date.
print(f"\033[92m[INFO] App is the latest version! [{latestversion}]\033[0m")
else:
print(
f"\033[93m[INFO] You have app version [{appversion}] installed. Please update to [{latestversion}] for the newest features.\033[0m"
)
try:
if is_nt:
cwd = os.getcwd()
# icon = cwd + "\Images\logo.ico"
icon = resource_path("Images/logo.ico")
toast = Notification(
app_id="EyeTrackApp",
title="New Update Available!",
msg=f"Please update to {latestversion}",
icon=r"{}".format(icon),
)
toast.add_actions(
label="Download Page",
launch="https://github.com/RedHawk989/EyeTrackVR/releases/latest",
)
toast.show()
except Exception as e:
print("[INFO] Toast notifications not supported")
except:
print("\033[91m[INFO] Could not check for updates. Please try again later.\033[0m")
# Check to see if we have an ROI. If not, bring up ROI finder GUI.
# Spawn worker threads
osc_queue: queue.Queue[tuple[bool, int, int]] = queue.Queue()
osc = VRChatOSC(cancellation_event, osc_queue, config)
osc_thread = threading.Thread(target=osc.run)
# start worker threads
osc_thread.start()
osc_queue: queue.Queue[OSCMessage] = queue.Queue()
eyes = [
CameraWidget(EyeId.RIGHT, config, osc_queue),
@ -92,8 +115,34 @@ def main():
settings = [
SettingsWidget(EyeId.SETTINGS, config),
AlgoSettingsWidget(EyeId.ALGOSETTINGS, config),
VRCFTSettingsWidget(EyeId.VRCFTMODULESETTINGS, config, osc_queue),
]
osc_manager = OSCManager(
osc_message_in_queue=osc_queue,
config=config,
)
config.register_listener_callback(osc_manager.update)
config.register_listener_callback(eyes[0].on_config_update)
config.register_listener_callback(eyes[1].on_config_update)
osc_manager.register_listeners(
config.settings.gui_osc_recenter_address,
[
eyes[0].recenter_eyes,
eyes[1].recenter_eyes,
],
)
osc_manager.register_listeners(
config.settings.gui_osc_recalibrate_address,
[
eyes[0].recalibrate_eyes,
eyes[1].recalibrate_eyes,
],
)
osc_manager.start()
layout = [
[
sg.Radio(
@ -131,6 +180,13 @@ def main():
default=(config.eye_display_id == EyeId.ALGOSETTINGS),
key=ALGO_SETTINGS_RADIO_NAME,
),
sg.Radio(
"VRCFT Module Settings",
"EYESELECTRADIO",
background_color="#292929",
default=(config.eye_display_id == EyeId.VRCFTMODULESETTINGS),
key=VRCFT_MODULE_SETTINGS_RADIO_NAME,
),
],
[
sg.Column(
@ -161,6 +217,13 @@ def main():
visible=(config.eye_display_id in [EyeId.ALGOSETTINGS]),
background_color="#424042",
),
sg.Column(
settings[2].get_layout(),
vertical_alignment="top",
key=VRCFT_MODULE_SETTINGS_NAME,
visible=(config.eye_display_id in [EyeId.VRCFTMODULESETTINGS]),
background_color="#424042",
),
],
]
@ -172,15 +235,10 @@ def main():
settings[0].start()
if config.eye_display_id in [EyeId.ALGOSETTINGS]:
settings[1].start()
# self.main_config.eye_display_id
if config.eye_display_id in [EyeId.VRCFTMODULESETTINGS]:
settings[2].start()
# the eye's needs to be running before it is passed to the OSC
if config.settings.gui_ROSC:
osc_receiver = VRChatOSCReceiver(cancellation_event, config, eyes)
osc_receiver_thread = threading.Thread(target=osc_receiver.run)
osc_receiver_thread.start()
ROSC = True
# Create the window
window = sg.Window(
f"{appversion}",
@ -192,23 +250,16 @@ def main():
# GUI Render loop
while True:
# First off, check for any events from the GUI
event, values = window.read(timeout=1)
event, values = window.read(timeout=1) # this higher timeout saves some cpu usage
# If we're in either mode and someone hits q, quit immediately
if event == "Exit" or event == sg.WIN_CLOSED:
for eye in eyes:
eye.stop()
cancellation_event.set()
# shut down worker threads
osc_thread.join()
# TODO: find a way to have this function run on join maybe??
# threading.Event() wont work because pythonosc spawns its own thread.
# only way i can see to get around this is an ugly while loop that only checks if a threading event is triggered
# and then call the pythonosc shutdown function
if ROSC:
osc_receiver.shutdown()
osc_receiver_thread.join()
osc_manager.shutdown()
print("\033[94m[INFO] Exiting EyeTrackApp\033[0m")
os._exit(0) # I do not like this, but for now this fixes app hang on close
return
if values[RIGHT_EYE_RADIO_NAME] and config.eye_display_id != EyeId.RIGHT:
@ -216,9 +267,11 @@ def main():
eyes[1].stop()
settings[0].stop()
settings[1].stop()
settings[2].stop()
window[RIGHT_EYE_NAME].update(visible=True)
window[LEFT_EYE_NAME].update(visible=False)
window[SETTINGS_NAME].update(visible=False)
window[VRCFT_MODULE_SETTINGS_NAME].update(visible=False)
window[ALGO_SETTINGS_NAME].update(visible=False)
config.eye_display_id = EyeId.RIGHT
config.settings.tracker_single_eye = 2
@ -227,11 +280,13 @@ def main():
elif values[LEFT_EYE_RADIO_NAME] and config.eye_display_id != EyeId.LEFT:
settings[0].stop()
settings[1].stop()
settings[2].stop()
eyes[0].stop()
eyes[1].start()
window[RIGHT_EYE_NAME].update(visible=False)
window[LEFT_EYE_NAME].update(visible=True)
window[SETTINGS_NAME].update(visible=False)
window[VRCFT_MODULE_SETTINGS_NAME].update(visible=False)
window[ALGO_SETTINGS_NAME].update(visible=False)
config.eye_display_id = EyeId.LEFT
config.settings.tracker_single_eye = 1
@ -240,11 +295,13 @@ def main():
elif values[BOTH_EYE_RADIO_NAME] and config.eye_display_id != EyeId.BOTH:
settings[0].stop()
settings[1].stop()
settings[2].stop()
eyes[1].start()
eyes[0].start()
window[LEFT_EYE_NAME].update(visible=True)
window[RIGHT_EYE_NAME].update(visible=True)
window[SETTINGS_NAME].update(visible=False)
window[VRCFT_MODULE_SETTINGS_NAME].update(visible=False)
window[ALGO_SETTINGS_NAME].update(visible=False)
config.eye_display_id = EyeId.BOTH
config.settings.tracker_single_eye = 0
@ -255,28 +312,43 @@ def main():
eyes[1].stop()
settings[1].stop()
settings[0].start()
settings[2].stop()
window[RIGHT_EYE_NAME].update(visible=False)
window[LEFT_EYE_NAME].update(visible=False)
window[SETTINGS_NAME].update(visible=True)
window[VRCFT_MODULE_SETTINGS_NAME].update(visible=False)
window[ALGO_SETTINGS_NAME].update(visible=False)
config.eye_display_id = EyeId.SETTINGS
config.save()
elif (
values[ALGO_SETTINGS_RADIO_NAME]
and config.eye_display_id != EyeId.ALGOSETTINGS
):
elif values[ALGO_SETTINGS_RADIO_NAME] and config.eye_display_id != EyeId.ALGOSETTINGS:
eyes[0].stop()
eyes[1].stop()
settings[0].stop()
settings[1].start()
settings[2].stop()
window[RIGHT_EYE_NAME].update(visible=False)
window[LEFT_EYE_NAME].update(visible=False)
window[SETTINGS_NAME].update(visible=False)
window[VRCFT_MODULE_SETTINGS_NAME].update(visible=False)
window[ALGO_SETTINGS_NAME].update(visible=True)
config.eye_display_id = EyeId.ALGOSETTINGS
config.save()
elif values[VRCFT_MODULE_SETTINGS_RADIO_NAME] and config.eye_display_id != EyeId.VRCFTMODULESETTINGS:
eyes[0].stop()
eyes[1].stop()
settings[0].stop()
settings[1].stop()
settings[2].start()
window[RIGHT_EYE_NAME].update(visible=False)
window[LEFT_EYE_NAME].update(visible=False)
window[SETTINGS_NAME].update(visible=False)
window[VRCFT_MODULE_SETTINGS_NAME].update(visible=True)
window[ALGO_SETTINGS_NAME].update(visible=False)
config.eye_display_id = EyeId.VRCFTMODULESETTINGS
config.save()
else:
# Otherwise, render all
for eye in eyes:

View File

@ -11,7 +11,7 @@ a = Analysis(
pathex=[],
binaries=[],
datas=resources,
hiddenimports=['cv2', 'numpy', 'PySimpleGui'],
hiddenimports=['cv2', 'numpy', 'PySimpleGui', 'pkg_resources.extern'],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
@ -44,4 +44,4 @@ exe = EXE(
codesign_identity=None,
entitlements_file=None,
icon="Images/logo.ico",
)
)

View File

@ -1,18 +0,0 @@
from config import EyeTrackConfig
from osc import EyeId
from settings.BaseSettings import BaseSettingsWidget
from settings.modules.GeneralSettingsModule import GeneralSettingsModule
from settings.modules.OneEuroSettingsModule import OneEuroSettingsModule
from settings.modules.OSCSettingsModule import OSCSettingsModule
class SettingsWidget(BaseSettingsWidget):
def __init__(self, widget_id: EyeId, main_config: EyeTrackConfig):
settings_modules = [
GeneralSettingsModule,
OneEuroSettingsModule,
OSCSettingsModule,
]
super().__init__(widget_id, main_config, settings_modules)

View File

@ -1,11 +1,38 @@
"""
------------------------------------------------------------------------------------------------------
,@@@@@@
@@@@@@@@@@@ @@@
@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@@ @@@@@@@@@@@@@@
@@@@@@@/ ,@@@@@@@@@@@@@
/@@@@@@@@@@@@@@@ @@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@
@@@@@@@@ @@@@@
,@@@ @@@@&
@@@@@@. @@@@
@@@ @@@@@@@@@/ @@@@@
,@@@. @@@@@@((@ @@@@(
//@@@ ,, @@@@ @@@@@
@@@( @@@@@@@
@@@ @ @@@@@@@@#
@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@(
Haar Surround Feature: Summer, PallasNeko (Optimization)
Algorithm App Implementations and tweaks By: Prohurtz
Copyright (c) 2023 EyeTrackVR <3
LICENSE: Summer Software Distribution License 1.0
------------------------------------------------------------------------------------------------------
"""
import timeit
from functools import lru_cache
import cv2
import numpy as np
from utils.misc_utils import clamp
from utils.img_utils import safe_crop
from enum import IntEnum
import psutil
import sys
import os
@ -20,16 +47,9 @@ else:
process.nice(psutil.BELOW_NORMAL_PRIORITY_CLASS) # Windows
process.nice()
class EyeId(IntEnum):
RIGHT = 0
LEFT = 1
BOTH = 2
SETTINGS = 3
# from line_profiler_pycharm import profile
video_path = "ezgif.com-gif-maker.avi"
imshow_enable = False
calc_print_enable = False
@ -122,10 +142,7 @@ class HaarSurroundFeature:
def get_kernel(self):
# Defined here, but not yet used?
# Create a kernel filled with the value of self.val_out
kernel = (
np.ones(shape=(2 * self.r_out - 1, 2 * self.r_out - 1), dtype=np.float64)
* self.val_out
)
kernel = np.ones(shape=(2 * self.r_out - 1, 2 * self.r_out - 1), dtype=np.float64) * self.val_out
# Set the values of the inner area of the kernel using array slicing
start = self.r_out - self.r_in
@ -144,9 +161,7 @@ def to_gray(frame):
@lru_cache(maxsize=lru_maxsize_vvs)
def get_frameint_empty_array(frame_shape, pad, x_step, y_step, r_in, r_out):
frame_int_dtype = np.intc
frame_pad = np.empty(
(frame_shape[0] + (pad * 2), frame_shape[1] + (pad * 2)), dtype=np.uint8
)
frame_pad = np.empty((frame_shape[0] + (pad * 2), frame_shape[1] + (pad * 2)), dtype=np.uint8)
row, col = frame_pad.shape
@ -183,9 +198,7 @@ def get_frameint_empty_array(frame_shape, pad, x_step, y_step, r_in, r_out):
out_p01 = np.empty(len_syx, dtype=frame_int_dtype)
out_p10 = np.empty(len_syx, dtype=frame_int_dtype)
response_list = np.empty(len_syx, dtype=np.float64) # or np.int32
frame_conv = np.zeros(
shape=(row - 2 * pad, col - 2 * pad), dtype=np.uint8
) # or np.float64
frame_conv = np.zeros(shape=(row - 2 * pad, col - 2 * pad), dtype=np.uint8) # or np.float64
frame_conv_stride = frame_conv[::y_step, ::x_step]
return (
@ -332,21 +345,14 @@ class AutoRadiusCalc(object):
self.adj_comp_flag = False
return self.radius_cand_list[self.radius_middle_index]
else:
if (
self.left_index <= self.right_index
and self.left_index != self.radius_middle_index
):
if (self.left_item[1] + self.response_list[-1][1]) < (
self.right_item[1] + self.response_list[-1][1]
):
if self.left_index <= self.right_index and self.left_index != self.radius_middle_index:
if (self.left_item[1] + self.response_list[-1][1]) < (self.right_item[1] + self.response_list[-1][1]):
self.right_item = self.response_list[-1]
self.right_index = self.radius_middle_index - 1
self.radius_middle_index = (self.left_index + self.right_index) // 2
self.adj_comp_flag = False
return self.radius_cand_list[self.radius_middle_index]
if (self.left_item[1] + self.response_list[-1][1]) > (
self.right_item[1] + self.response_list[-1][1]
):
if (self.left_item[1] + self.response_list[-1][1]) > (self.right_item[1] + self.response_list[-1][1]):
self.left_item = self.response_list[-1]
self.left_index = self.radius_middle_index + 1
self.radius_middle_index = (self.left_index + self.right_index) // 2
@ -380,21 +386,11 @@ class AutoRadiusCalc(object):
self.adj_comp_flag = True
return default_radius
elif sort_res[0] == auto_radius_range[0]:
self.radius_cand_list = [
i
for i in range(
auto_radius_range[0], default_radius, auto_radius_step
)
][1:]
self.radius_cand_list = [i for i in range(auto_radius_range[0], default_radius, auto_radius_step)][1:]
self.adj_comp_flag = False
return self.radius_cand_list.pop()
else:
self.radius_cand_list = [
i
for i in range(
default_radius, auto_radius_range[1], auto_radius_step
)
][1:]
self.radius_cand_list = [i for i in range(default_radius, auto_radius_range[1], auto_radius_step)][1:]
self.adj_comp_flag = False
return self.radius_cand_list.pop()
else:
@ -468,9 +464,7 @@ class CenterCorrection(object):
self.frame_mask = None
self.frame_bin = None
self.frame_final = None
self.morph_kernel = cv2.getStructuringElement(
cv2.MORPH_RECT, (kernel_size, kernel_size)
)
self.morph_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_size, kernel_size))
self.morph_kernel2 = np.ones((3, 3))
self.hist_index = np.arange(256)
self.hist = np.empty((256, 1))
@ -507,20 +501,14 @@ class CenterCorrection(object):
)
# bottleneck
self.frame_bin = cv2.threshold(gray_frame, frame_thr, 1, cv2.THRESH_BINARY_INV)[
1
]
self.frame_bin = cv2.threshold(gray_frame, frame_thr, 1, cv2.THRESH_BINARY_INV)[1]
cropped_x, cropped_y, cropped_w, cropped_h = cv2.boundingRect(self.frame_bin)
self.frame_final = cv2.bitwise_and(self.frame_bin, self.frame_mask)
# bottleneck
self.frame_final = cv2.morphologyEx(
self.frame_final, cv2.MORPH_CLOSE, self.morph_kernel
)
self.frame_final = cv2.morphologyEx(
self.frame_final, cv2.MORPH_OPEN, self.morph_kernel
)
self.frame_final = cv2.morphologyEx(self.frame_final, cv2.MORPH_CLOSE, self.morph_kernel)
self.frame_final = cv2.morphologyEx(self.frame_final, cv2.MORPH_OPEN, self.morph_kernel)
if (cropped_h, cropped_w) == self.frame_shape:
# Not detected.
@ -539,9 +527,7 @@ class CenterCorrection(object):
else:
base_x, base_y = center_x, center_y
contours, _ = cv2.findContours(
self.frame_final, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE
)
contours, _ = cv2.findContours(self.frame_final, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
contours_box = [cv2.boundingRect(cnt) for cnt in contours]
contours_dist = np.array(
[
@ -551,9 +537,7 @@ class CenterCorrection(object):
)
if len(contours_box):
cropped_x2, cropped_y2, cropped_w2, cropped_h2 = contours_box[
contours_dist.argmin()
]
cropped_x2, cropped_y2, cropped_w2, cropped_h2 = contours_box[contours_dist.argmin()]
x = cropped_x2 + cropped_w2 // 2
y = cropped_y2 + cropped_h2 // 2
else:
@ -659,9 +643,7 @@ class HSF_cls(object):
self.cvparam.radius = self.auto_radius_calc.get_radius()
if self.auto_radius_calc.adj_comp_flag:
self.now_modeo = (
self.cv_modeo[2] if not skip_blink_detect else self.cv_modeo[3]
)
self.now_modeo = self.cv_modeo[2] if not skip_blink_detect else self.cv_modeo[3]
radius, pad, step, hsf = self.cvparam.get_rpsh()
@ -694,13 +676,9 @@ class HSF_cls(object):
response_list,
frame_conv,
frame_conv_stride,
) = get_frameint_empty_array(
gray_frame.shape, pad, step[0], step[1], hsf.r_in, hsf.r_out
)
) = get_frameint_empty_array(gray_frame.shape, pad, step[0], step[1], hsf.r_in, hsf.r_out)
# BORDER_CONSTANT is faster than BORDER_REPLICATE There seems to be almost no negative impact when BORDER_CONSTANT is used.
cv2.copyMakeBorder(
gray_frame, pad, pad, pad, pad, cv2.BORDER_CONSTANT, dst=frame_pad
)
cv2.copyMakeBorder(gray_frame, pad, pad, pad, pad, cv2.BORDER_CONSTANT, dst=frame_pad)
cv2.integral(frame_pad, sum=frame_int, sdepth=cv2.CV_32S)
self.timedict["int_img"].append(timeit.default_timer() - int_start_time)
@ -756,18 +734,10 @@ class HSF_cls(object):
if self.blink_detector.response_len() < blink_init_frames:
self.blink_detector.add_response(cv2.mean(cropped_image)[0])
upper_x = center_x + max(
20, radius
) # self.center_correct.center_q1_radius
lower_x = center_x - max(
20, radius
) # self.center_correct.center_q1_radius
upper_y = center_y + max(
20, radius
) # self.center_correct.center_q1_radius
lower_y = center_y - max(
20, radius
) # self.center_correct.center_q1_radius
upper_x = center_x + max(20, radius) # self.center_correct.center_q1_radius
lower_x = center_x - max(20, radius) # self.center_correct.center_q1_radius
upper_y = center_y + max(20, radius) # self.center_correct.center_q1_radius
lower_y = center_y - max(20, radius) # self.center_correct.center_q1_radius
self.center_q1.add_response(
cv2.mean(
@ -802,19 +772,13 @@ class HSF_cls(object):
else:
# pass
if not self.center_correct.setup_comp:
self.center_correct.init_array(
gray_frame.shape, self.center_q1.quartile_1, radius
)
self.center_correct.init_array(gray_frame.shape, self.center_q1.quartile_1, radius)
elif self.center_correct.frame_shape != gray_frame.shape:
"""The resolution should have changed and the statistics should have changed, so essentially the statistics
need to be reworked, but implementation will be postponed as viability is the highest priority."""
self.center_correct.init_array(
gray_frame.shape, self.center_q1.quartile_1, radius
)
self.center_correct.init_array(gray_frame.shape, self.center_q1.quartile_1, radius)
center_x, center_y = self.center_correct.correction(
gray_frame, center_x, center_y
)
center_x, center_y = self.center_correct.correction(gray_frame, center_x, center_y)
# Define the center point and radius
center_xy = (center_x, center_y)
upper_x = center_x + radius
@ -822,9 +786,7 @@ class HSF_cls(object):
upper_y = center_y + radius
lower_y = center_y - radius
# Crop the image using the calculated bounds
cropped_image = safe_crop(
gray_frame, lower_x, lower_y, upper_x, upper_y
)
cropped_image = safe_crop(gray_frame, lower_x, lower_y, upper_x, upper_y)
# cropbox = [clamp(val, 0, gray_frame.shape[i]) for i, val in
# zip([1, 0, 1, 0], [lower_x, lower_y, upper_x, upper_y])] # debug code
@ -845,10 +807,7 @@ class HSF_cls(object):
# print('Pixel position:', center_xy)
if imshow_enable:
if (
self.now_modeo != self.cv_modeo[0]
and self.now_modeo != self.cv_modeo[1]
):
if self.now_modeo != self.cv_modeo[0] and self.now_modeo != self.cv_modeo[1]:
if 0 in cropped_image.shape:
# If shape contains 0, it is not detected well.
pass

View File

@ -23,16 +23,15 @@ Intensity Based Openess By: Prohurtz, PallasNeko (Optimization)
Algorithm App Implementations By: Prohurtz
Copyright (c) 2023 EyeTrackVR <3
LICENSE: GNU GPLv3
------------------------------------------------------------------------------------------------------
"""
import numpy as np
import time
import os
import cv2
from enums import EyeLR
from eye import EyeId
from one_euro_filter import OneEuroFilter
from utils.img_utils import safe_crop
from enum import IntEnum
import psutil
import sys
@ -47,13 +46,6 @@ else:
process.nice()
class EyeId(IntEnum):
RIGHT = 0
LEFT = 1
BOTH = 2
SETTINGS = 3
# higher intensity means more closed/ more white/less pupil
# Hm I need an acronym for this, any ideas?
@ -258,9 +250,7 @@ class IntensityBasedOpeness:
# The same can be done with cv2.integral, but since there is only one area of the rectangle for which we want to know the total value, there is no advantage in terms of computational complexity.
intensity = frame_crop.sum() + 1
# cv2.imshow('e', frame)
# if cv2.waitKey(10) == 27:
# exit()
if len(self.filterlist) < filterSamples:
self.filterlist.append(intensity)
else:
@ -269,7 +259,7 @@ class IntensityBasedOpeness:
try:
if intensity >= np.percentile(
self.filterlist, 98
self.filterlist, 99
): # filter abnormally high values
# print('filter, assume blink')
intensity = self.maxval
@ -386,16 +376,13 @@ class IntensityBasedOpeness:
eyeopen = 0.0
if changed and (
(time.time() - self.lct) > 5
(time.time() - self.lct) > 11
): # save every 5 seconds if something changed to save disk usage
self.save()
self.lct = time.time()
self.prev_val = eyeopen
try:
noisy_point = np.array(
[float(eyeopen), float(eyeopen)]
) # fliter our values with a One Euro Filter
point_hat = self.one_euro_filter(noisy_point)
eyeopenx = point_hat[0]
eyeopeny = point_hat[1]
@ -404,7 +391,7 @@ class IntensityBasedOpeness:
except:
pass
eyevec = abs(self.prev_val - eyeopen)
# eyevec = abs(self.prev_val - eyeopen)
# print(eyevec)
# if eyevec > 0.4:
# print("BLINK LCOK")

View File

@ -23,10 +23,12 @@ LEAP by: Prohurtz
Algorithm App Implementation By: Prohurtz
Copyright (c) 2023 EyeTrackVR <3
LICENSE: GNU GPLv3
------------------------------------------------------------------------------------------------------
"""
# LEAP = Lightweight Eyelid And Pupil
import os
os.environ["OMP_NUM_THREADS"] = "1"
import onnxruntime
import numpy as np
@ -39,9 +41,11 @@ from one_euro_filter import OneEuroFilter
import psutil, os
import sys
from utils.misc_utils import resource_path
import platform
from pathlib import Path
frames = 0
models = Path("Models")
def run_model(input_queue, output_queue, session):
@ -50,24 +54,21 @@ def run_model(input_queue, output_queue, session):
if frame is None:
break
# to_tensor = transforms.ToTensor()
# img_tensor = to_tensor(frame)
# img_tensor.unsqueeze_(0)
# img_np = img_tensor.numpy()
img_np = np.array(frame)
# Normalize the pixel values to [0, 1] and convert the data type to float32
img_np = img_np.astype(np.float32) / 255.0
gray_img = 0.299 * img_np[:, :, 0] + 0.587 * img_np[:, :, 1] + 0.114 * img_np[:, :, 2]
# Transpose the dimensions from (height, width, channels) to (channels, height, width)
img_np = np.transpose(img_np, (2, 0, 1))
# Add a batch dimension
img_np = np.expand_dims(img_np, axis=0)
# Add the channel and batch dimensions
gray_img = np.expand_dims(gray_img, axis=0) # Add channel dimension
img_np = np.expand_dims(gray_img, axis=0) # Add batch dimension
# img_np = np.transpose(img_np, (2, 0, 1))
# img_np = np.expand_dims(img_np, axis=0)
ort_inputs = {session.get_inputs()[0].name: img_np}
pre_landmark = session.run(None, ort_inputs)
pre_landmark = pre_landmark[1]
pre_landmark = np.reshape(pre_landmark, (7, 2))
# pre_landmark = pre_landmark[1]
# pre_landmark = np.reshape(pre_landmark, (12, 2))
pre_landmark = np.reshape(pre_landmark, (-1, 2))
output_queue.put((frame, pre_landmark))
@ -75,22 +76,22 @@ class LEAP_C(object):
def __init__(self):
onnxruntime.disable_telemetry_events()
# Config variables
self.num_threads = 3 # Number of python threads to use (using ~1 more than needed to achieve wanted fps yields lower cpu usage)
self.num_threads = 1 # Number of python threads to use (using ~1 more than needed to achieve wanted fps yields lower cpu usage)
self.queue_max_size = 1 # Optimize for best CPU usage, Memory, and Latency. A maxsize is needed to not create a potential memory leak.
if platform.system() == "Darwin":
self.model_path = resource_path(
"EyeTrackApp/Models/mommy072623.onnx"
) # funny MacOS files issues :P
else:
self.model_path = resource_path("Models/mommy072623.onnx")
self.interval = 1 # FPS print update rate
self.low_priority = True # set process priority to low (may cause issues when unfocusing? reported by one, not reproducable)
self.model_path = resource_path(models / 'LEAP071024_E16.onnx')
self.low_priority = (
False # set process priority to low (may cause issues when unfocusing? reported by one, not reproducable)
)
self.low_priority = (
True # set process priority to low (may cause issues when unfocusing? reported by one, not reproducable)
)
self.print_fps = False
# Init variables
self.frames = 0
self.queues = []
self.threads = []
self.model_output = np.zeros((7, 2))
self.model_output = np.zeros((12, 2))
self.output_queue = Queue(maxsize=self.queue_max_size)
self.start_time = time.time()
@ -99,44 +100,50 @@ class LEAP_C(object):
self.queues.append(self.queue)
opts = onnxruntime.SessionOptions()
opts.inter_op_num_threads = 1
opts.intra_op_num_threads = 1
opts.graph_optimization_level = (
onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
)
opts.inter_op_num_threads = 4
opts.intra_op_num_threads = 1 # big perf hit
opts.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
opts.optimized_model_filepath = ""
if self.low_priority:
process = psutil.Process(os.getpid()) # set process priority to low
try:
sys.getwindowsversion()
except AttributeError:
process.nice(0) # UNIX: 0 low 10 high
process.nice()
else:
process.nice(psutil.BELOW_NORMAL_PRIORITY_CLASS) # Windows
process.nice()
process = psutil.Process(os.getpid()) # set process priority to low
try:
sys.getwindowsversion()
except AttributeError:
process.nice(0) # UNIX: 0 low 10 high
process.nice()
else:
process.nice(psutil.BELOW_NORMAL_PRIORITY_CLASS) # Windows
process.nice()
except:
pass
# See https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getpriorityclass#return-value for values
else:
pass
# process = psutil.Process(os.getpid()) # set process priority to low
# try:
# sys.getwindowsversion()
# except AttributeError:
# process.nice(10) # UNIX: 0 low 10 high
# else:
# process.nice(psutil.HIGH_PRIORITY_CLASS) # Windows
# See https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getpriorityclass#return-value for values
min_cutoff = 0.1
beta = 15.0
# print(np.random.rand(22, 2))
# noisy_point = np.array([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1])
self.one_euro_filter = OneEuroFilter(
np.random.rand(7, 2), min_cutoff=min_cutoff, beta=beta
)
# self.one_euro_filter_open = OneEuroFilter(
# np.random.rand(1, 2), min_cutoff=0.01, beta=0.04
# )
self.one_euro_filter = OneEuroFilter(np.random.rand(12, 2), min_cutoff=min_cutoff, beta=beta)
self.one_euro_filter_float = OneEuroFilter(np.random.rand(1, 2), min_cutoff=5, beta=0.007)
self.dmax = 0
self.dmin = 0
self.openlist = []
self.x = 0
self.y = 0
self.maxlist = []
self.ort_session1 = onnxruntime.InferenceSession(self.model_path, opts, providers=["CPUExecutionProvider"])
self.ort_session1 = onnxruntime.InferenceSession(
self.model_path, opts, providers=["CPUExecutionProvider"]
)
# ort_session1 = onnxruntime.InferenceSession("C:/Users/beaul/PycharmProjects/EyeTrackVR/EyeTrackApp/Models/mommy062023.onnx", opts, providers=['DmlExecutionProvider'])
threads = []
for i in range(self.num_threads):
thread = threading.Thread(
@ -148,11 +155,7 @@ class LEAP_C(object):
thread.start()
def to_numpy(self, tensor):
return (
tensor.detach().cpu().numpy()
if tensor.requires_grad
else tensor.cpu().numpy()
)
return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()
def run_onnx_model(self, queues, session, frame):
for i in range(len(queues)):
@ -162,106 +165,118 @@ class LEAP_C(object):
def leap_run(self):
img = self.current_image_gray.copy()
img = self.current_image_gray_clean.copy()
img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
# img = imutils.rotate(img, angle=320)
img_height, img_width = img.shape[:2] # Move outside the loop
frame = cv2.resize(img, (112, 112))
imgvis = self.current_image_gray.copy()
self.run_onnx_model(self.queues, self.ort_session1, frame)
if not self.output_queue.empty():
frame, pre_landmark = self.output_queue.get()
pre_landmark = self.one_euro_filter(pre_landmark)
# frame = cv2.resize(frame, (112, 112))
# pre_landmark = np.reshape(pre_landmark, (-1, 2))
# pre_landmark = self.one_euro_filter(pre_landmark)
for point in pre_landmark:
x, y = point
cv2.circle(
img, (int(x * img_width), int(y * img_height)), 2, (0, 0, 50), -1
)
cv2.circle(
img,
tuple(int(x * img_width) for x in pre_landmark[2]),
1,
(255, 255, 0),
-1,
)
# cv2.circle(img, tuple(int(x*112) for x in pre_landmark[2]), 1, (255, 255, 0), -1)
cv2.circle(
img,
tuple(int(x * img_width) for x in pre_landmark[4]),
1,
(255, 255, 255),
-1,
)
# cv2.circle(img, tuple(int(x * 112) for x in pre_landmark[4]), 1, (255, 255, 255), -1)
# print(pre_landmark)
# x, y = (point*112).astype(int)
x, y = point # Assuming point is a tuple (x, y)
# Scale the coordinates to image width and height
x = int(x * img_width)
y = int(y * img_height)
# x, y = int(x), int(y) # Ensure x and y are integers
cv2.circle(imgvis, (int(x), int(y)), 2, (255, 255, 0), -1)
x1, y1 = pre_landmark[0]
x2, y2 = pre_landmark[6]
euclidean_dist_width = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
x1, y1 = pre_landmark[1]
x2, y2 = pre_landmark[3]
x3, y3 = pre_landmark[4]
x4, y4 = pre_landmark[2]
euclidean_dist_open = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
# d = area / euclidean_dist_width
# print(area)
eyesize_dist = math.dist(pre_landmark[0], pre_landmark[6])
distance = math.dist(pre_landmark[1], pre_landmark[3])
# d = distance / eyesize_dist
d1 = math.dist(pre_landmark[1], pre_landmark[3])
# a more fancy method could be used taking into acount the relative size of the landmarks so that weirdness can be acounted for better
d2 = math.dist(pre_landmark[2], pre_landmark[4])
d = (d1 + d2) / 2
# by averaging both sets we can get less error? i think part of why 1 eye was better than the other is because we only considered one offset points.
# considering both should smooth things out between eyes
d = math.dist(pre_landmark[1], pre_landmark[3])
# d2 = math.dist(pre_landmark[2], pre_landmark[4])
# d = d + d2
try:
if d >= np.percentile(
self.openlist, 80 # do not go above 85, but this value can be tuned
): # an aditional approach could be using the place where on average it is most stable, denoting what distance is the most stable "open"
self.maxlist.append(d)
if len(self.maxlist) > 2000: # i feel that this is very cpu intensive. think of a better method
self.maxlist.pop(0)
# this should be the average most open value, the average of top 2000 values in rolling calibration
# with this we can use it as the "openstate" (0.7, for expanded squeeze)
# weighted values to shift slightly to max value
normal_open = ((sum(self.maxlist) / len(self.maxlist)) * 0.90 + max(self.openlist) * 0.10) / (
0.95 + 0.15
)
except:
normal_open = 0.8
if len(self.openlist) < 5000: # TODO expose as setting?
self.openlist.append(d)
else:
# if d >= np.percentile(self.openlist, 99) or d <= np.percentile(
# self.openlist, 1
# ):
# pass
# else:
self.openlist.pop(0)
self.openlist.append(d)
try:
per = (d - max(self.openlist)) / (
per = (d - normal_open) / (min(self.openlist) - normal_open)
oldper = (d - max(self.openlist)) / (
min(self.openlist) - max(self.openlist)
)
) # TODO: remove when testing is done
per = 1 - per
per = per - 0.2 # allow for eye widen? might require a more legit math way but this makes sense.
per = min(per, 1.0) # clamp to 1.0 max
per = max(per, 0.0) # clamp to 1.0 min
# print("new: ", per, "vs old: ", oldper)
except:
per = 0.7
per = 0.8
pass
# print(d, per)
x = pre_landmark[6][0]
y = pre_landmark[6][1]
frame = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# per = d - 0.1
self.last_lid = per
# pera = np.array([per, per])
# self.one_euro_filter_open(pera)
calib_array = np.array([per, per]).reshape(1, 2)
per = self.one_euro_filter_float(calib_array)
per = per[0][0]
# print(per)
if per <= 0.2: # TODO: EXPOSE AS SETTING
per == 0.0
# print(per)
return frame, float(x), float(y), per
# this should be tuned, i could make this auto calib based on min from a list of per values.
frame = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
return frame, 0, 0, 0
return imgvis, float(x), float(y), per
imgvis = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
return imgvis, 0, 0, 0
class External_Run_LEAP(object):
def __init__(self):
self.algo = LEAP_C()
def run(self, current_image_gray):
def run(self, current_image_gray, current_image_gray_clean):
self.algo.current_image_gray = current_image_gray
self.algo.current_image_gray_clean = current_image_gray_clean
img, x, y, per = self.algo.leap_run()
return img, x, y, per
return img, x, y, per

View File

@ -1,3 +1,6 @@
# https://github.com/jaantollander/OneEuroFilter
# LICENSE: MIT
import numpy as np
from time import time

View File

@ -1,491 +0,0 @@
from pythonosc import udp_client
from pythonosc import osc_server
from pythonosc import dispatcher
from config import EyeTrackConfig
from utils.misc_utils import PlaySound, SND_FILENAME, SND_ASYNC
import queue
import threading
from enum import IntEnum
import time
import numpy as np
class EyeId(IntEnum):
RIGHT = 0
LEFT = 1
BOTH = 2
SETTINGS = 3
ALGOSETTINGS = 4
def eyelid_transformer(self, eye_blink):
if self.config.osc_invert_eye_close:
return float(1 - eye_blink)
else:
return float(eye_blink)
se = False
falloff = False
def output_osc(eye_x, eye_y, eye_blink, last_blink, pupil_dilation, avg_velocity, self):
# print(pupil_dilation)
global se, falloff
# self.config.gui_osc_vrcft_v2
# self.config.gui_osc_vrcft_v1
# self.config.gui_vrc_native
if self.config.gui_osc_vrcft_v1:
if self.main_config.eye_display_id in [
EyeId.RIGHT,
EyeId.LEFT,
]: # we are in single eye mode
se = True
self.client.send_message(self.config.osc_left_eye_x_address, eye_x)
self.client.send_message(self.config.osc_right_eye_x_address, eye_x)
self.client.send_message(self.config.osc_eyes_y_address, eye_y)
self.config.osc_left_eye_close_address
self.client.send_message(
self.config.osc_right_eye_close_address,
eyelid_transformer(self, eye_blink),
)
self.client.send_message(
self.config.osc_left_eye_close_address,
eyelid_transformer(self, eye_blink),
)
else:
se = False
if self.eye_id in [EyeId.LEFT] and not se: # left eye, send data to left
self.l_eye_x = eye_x
self.l_eye_blink = eye_blink
self.l_eye_velocity = avg_velocity
if self.l_eye_blink == 0.0:
if (
last_blink > 0.15
): # when binary blink is on, blinks may be too fast for OSC so we repeat them.
for i in range(4):
self.client.send_message(
self.config.osc_left_eye_close_address,
eyelid_transformer(self, self.l_eye_blink),
)
last_blink = time.time() - last_blink
self.l_eye_x = self.r_eye_x
self.client.send_message(self.config.osc_left_eye_x_address, self.l_eye_x)
self.left_y = eye_y
self.client.send_message(
self.config.osc_left_eye_close_address,
eyelid_transformer(self, self.l_eye_blink),
)
elif self.eye_id in [EyeId.RIGHT] and not se: # Right eye, send data to right
self.r_eye_x = eye_x
self.r_eye_blink = eye_blink
self.l_eye_velocity = avg_velocity
if self.r_eye_blink == 0.0:
if (
last_blink > 0.15
): # when binary blink is on, blinks may be too fast for OSC so we repeat them.
# print("REPEATING R BLINK")
for i in range(4):
self.client.send_message(
self.config.osc_right_eye_close_address,
eyelid_transformer(self, self.r_eye_blink),
)
last_blink = time.time() - last_blink
if self.config.gui_outer_side_falloff:
if (
self.l_eye_blink == 0.0
): # if both eyes closed and DEF is enables, blink
self.client.send_message(
self.config.osc_left_eye_close_address,
eyelid_transformer(self, self.r_eye_blink),
)
self.client.send_message(
self.config.osc_right_eye_close_address,
eyelid_transformer(self, self.r_eye_blink),
)
self.r_eye_x = self.l_eye_x
self.client.send_message(self.config.osc_right_eye_x_address, eye_x)
self.right_y = eye_y
self.client.send_message(
self.config.osc_right_eye_close_address,
eyelid_transformer(self, self.r_eye_blink),
)
if (
self.main_config.eye_display_id in [EyeId.BOTH]
and self.right_y != 621
and self.left_y != 621
):
y = (self.right_y + self.left_y) / 2
self.client.send_message(self.config.osc_eyes_y_address, y)
if self.config.gui_osc_vrcft_v2:
if self.main_config.eye_display_id in [
EyeId.RIGHT,
EyeId.LEFT,
]: # we are in single eye mode
se = True
self.client.send_message("/avatar/parameters/v2/EyeX", eye_x)
self.client.send_message("/avatar/parameters/v2/EyeLeftX", eye_x)
self.client.send_message("/avatar/parameters/v2/EyeRightX", eye_x)
self.client.send_message("/avatar/parameters/v2/EyeLeftY", eye_y)
self.client.send_message("/avatar/parameters/v2/EyeRightY", eye_y)
self.client.send_message(
"/avatar/parameters/v2/EyeLid",
eyelid_transformer(self, eye_blink),
)
else:
se = False
if self.eye_id in [EyeId.LEFT] and not se: # left eye, send data to left
self.l_eye_x = eye_x
self.l_eye_blink = eye_blink
self.r_eye_velocity = avg_velocity
if self.l_eye_blink == 0.0:
if (
last_blink > 0.15
): # when binary blink is on, blinks may be too fast for OSC so we repeat them.
for i in range(4):
self.client.send_message(
"/avatar/parameters/v2/EyeLidLeft",
eyelid_transformer(self, self.l_eye_blink),
)
last_blink = time.time() - last_blink
if self.config.gui_outer_side_falloff:
if (
self.r_eye_blink == 0.0
): # if both eyes closed and DEF is enables, blink
self.client.send_message(
"/avatar/parameters/v2/EyeLidLeft",
eyelid_transformer(self, self.l_eye_blink),
)
self.client.send_message(
"/avatar/parameters/v2/EyeLidRight",
eyelid_transformer(self, self.l_eye_blink),
)
self.l_eye_x = self.r_eye_x
self.client.send_message("/avatar/parameters/v2/EyeLeftX", self.l_eye_x)
self.left_y = eye_y
if self.left_y != 621:
self.client.send_message(
"/avatar/parameters/FT/v2/EyeLeftY", self.left_y
)
self.client.send_message(
"/avatar/parameters/FT/v2/EyeLidLeft",
eyelid_transformer(self, self.l_eye_blink),
)
elif self.eye_id in [EyeId.RIGHT] and not se: # Right eye, send data to right
self.r_eye_x = eye_x
self.r_eye_blink = eye_blink
self.r_eye_velocity = avg_velocity
if self.r_eye_blink == 0.0:
if (
last_blink > 0.15
): # when binary blink is on, blinks may be too fast for OSC so we repeat them.
# print("REPEATING R BLINK")
for i in range(4):
self.client.send_message(
"/avatar/parameters/v2/EyeLidRight",
eyelid_transformer(self, self.r_eye_blink),
)
last_blink = time.time() - last_blink
if self.config.gui_outer_side_falloff:
if (
self.l_eye_blink == 0.0
): # if both eyes closed and DEF is enables, blink
self.client.send_message(
"/avatar/parameters/v2/EyeLidLeft",
eyelid_transformer(self, self.r_eye_blink),
)
self.client.send_message(
"/avatar/parameters/v2/EyeLidRight",
eyelid_transformer(self, self.r_eye_blink),
)
self.r_eye_x = self.l_eye_x
self.client.send_message("/avatar/parameters/v2/EyeRightX", self.r_eye_x)
self.right_y = eye_y
if self.right_y != 621:
self.client.send_message(
"/avatar/parameters/v2/EyeRightY", self.right_y
)
self.client.send_message(
"/avatar/parameters/v2/EyeLidRight",
eyelid_transformer(self, self.r_eye_blink),
)
if (
self.main_config.eye_display_id in [EyeId.BOTH]
and self.right_y != 621
and self.left_y != 621
):
y = (self.right_y + self.left_y) / 2
self.client.send_message("/avatar/parameters/v2/EyeY", y)
if self.config.gui_vrc_native: # VRC NATIVE
if self.main_config.eye_display_id in [
EyeId.RIGHT,
EyeId.LEFT,
]: # we are in single eye mode
se = True
if eye_blink == 0.0:
if (
last_blink > 0.2
): # when binary blink is on, blinks may be too fast for OSC so we repeat them.
for i in range(5):
self.client.send_message(
"/tracking/eye/EyesClosedAmount", float(1 - eye_blink)
)
eye_blink += 0.02 # TODO finish tuning value
last_blink = time.time() - last_blink
else:
self.client.send_message(
"/tracking/eye/EyesClosedAmount", float(1 - eye_blink)
)
self.client.send_message(
"/tracking/eye/LeftRightVec",
[float(eye_x), float(eye_y), 1.0, float(eye_x), float(eye_y), 1.0],
) # vrc native ET
else:
se = False
if self.eye_id in [EyeId.LEFT] and not se: # left eye, send data to left
self.l_eye_x = eye_x
self.l_eye_blink = eye_blink
self.left_y = eye_y
self.l_eye_velocity = avg_velocity
self.client.send_message(
self.config.osc_left_eye_close_address,
eyelid_transformer(self, eye_blink),
)
if self.l_eye_blink == 0.0:
if (
last_blink > 0.2
): # when binary blink is on, blinks may be too fast for OSC so we repeat them.
for i in range(5):
self.client.send_message(
"/tracking/eye/EyesClosedAmount", float(1 - eye_blink)
)
last_blink = time.time() - last_blink
if self.config.gui_outer_side_falloff:
if (
self.r_eye_blink == 0.0
): # if both eyes closed and DEF is enables, blink
self.client.send_message(
"/tracking/eye/EyesClosedAmount", float(1 - eye_blink)
)
self.l_eye_x = self.r_eye_x
elif self.eye_id in [EyeId.RIGHT] and not se: # Right eye, send data to right
self.r_eye_x = eye_x
self.r_eye_blink = eye_blink
self.right_y = eye_y
self.r_eye_velocity = avg_velocity
self.client.send_message(
self.config.osc_right_eye_close_address,
eyelid_transformer(self, eye_blink),
)
if self.r_eye_blink == 0.0:
if (
last_blink > 0.2
): # when binary blink is on, blinks may be too fast for OSC so we repeat them.
for i in range(5):
self.client.send_message(
"/tracking/eye/EyesClosedAmount", float(1 - eye_blink)
)
last_blink = time.time() - last_blink
if self.config.gui_outer_side_falloff:
if (
self.l_eye_blink == 0.0
): # if both eyes closed and DEF is enables, blink
self.client.send_message(
"/tracking/eye/EyesClosedAmount", float(0)
)
self.r_eye_x = self.l_eye_x
if (
self.main_config.eye_display_id in [EyeId.BOTH]
and self.r_eye_blink != 621
and self.r_eye_blink != 621
):
if self.r_eye_blink == 0.0 or self.l_eye_blink == 0.0:
if (
last_blink > 0.2
): # when binary blink is on, blinks may be too fast for OSC so we repeat them.
for i in range(5):
self.client.send_message(
"/tracking/eye/EyesClosedAmount", float(1)
)
last_blink = time.time() - last_blink
eye_blink = (self.r_eye_blink + self.l_eye_blink) / 2
self.client.send_message(
"/tracking/eye/EyesClosedAmount", float(1 - eye_blink)
)
if (
self.main_config.eye_display_id in [EyeId.BOTH]
and self.right_y != 621
and self.left_y != 621
):
eye_y = (self.right_y + self.left_y) / 2
if not se:
# vrc native ET (z values may need tweaking, they act like a scalar)
self.client.send_message(
"/tracking/eye/LeftRightVec",
[
float(self.l_eye_x),
float(self.left_y),
1.0,
float(self.r_eye_x),
float(self.right_y),
1.0,
],
)
class VRChatOSC:
# Use a tuple of blink (true, blinking, false, not), x, y for now.
def __init__(
self,
cancellation_event: threading.Event,
msg_queue: queue.Queue[tuple[bool, int, int]],
main_config: EyeTrackConfig,
):
self.main_config = main_config
self.config = main_config.settings
self.client = udp_client.SimpleUDPClient(
self.config.gui_osc_address, int(self.config.gui_osc_port)
) # use OSC port and address that was set in the config
self.cancellation_event = cancellation_event
self.msg_queue = msg_queue
self.eye_id = EyeId.RIGHT
self.left_y = 621
self.right_y = 621
self.r_eye_x = 0
self.l_eye_x = 0
self.r_eye_blink = 0.7
self.l_eye_blink = 0.7
self.l_eye_velocity = 0
self.r_eye_velocity = 1
def run(self):
start = time.time()
last_blink = time.time()
while True:
if self.cancellation_event.is_set():
print("\033[94m[INFO] Exiting OSC Queue\033[0m")
return
try:
(self.eye_id, eye_info) = self.msg_queue.get(block=True, timeout=0.1)
except:
continue
output_osc(
eye_info.x,
eye_info.y,
eye_info.blink,
last_blink,
eye_info.pupil_dilation,
eye_info.avg_velocity,
self,
)
class VRChatOSCReceiver:
def __init__(
self, cancellation_event: threading.Event, main_config: EyeTrackConfig, eyes: []
):
self.config = main_config.settings
self.cancellation_event = cancellation_event
self.dispatcher = dispatcher.Dispatcher()
self.eyes = eyes # we cant import CameraWidget so any type it is
try:
self.server = osc_server.OSCUDPServer(
(self.config.gui_osc_address, int(self.config.gui_osc_receiver_port)),
self.dispatcher,
)
except:
print(
f"\033[91m[ERROR] OSC Receive port: {self.config.gui_osc_receiver_port} occupied.\033[0m"
)
def shutdown(self):
print("\033[94m[INFO] Exiting OSC Receiver\033[0m")
try:
self.server.shutdown()
except:
pass
def recenter_eyes(self, address, osc_value):
if type(osc_value) != bool:
return # just incase we get anything other than bool
if osc_value:
for eye in self.eyes:
eye.settings.gui_recenter_eyes = True
def recalibrate_eyes(self, address, osc_value):
if type(osc_value) != bool:
return # just incase we get anything other than bool
if osc_value:
for eye in self.eyes:
eye.ransac.ibo.clear_filter()
eye.ransac.calibration_frame_counter = self.config.calibration_samples
PlaySound("Audio/start.wav", SND_FILENAME | SND_ASYNC)
def run(self):
# bind what function to run when specified OSC message is received
try:
self.dispatcher.map(
self.config.gui_osc_recalibrate_address, self.recalibrate_eyes
)
self.dispatcher.map(
self.config.gui_osc_recenter_address, self.recenter_eyes
)
# start the server
print(
"\033[92m[INFO] VRChatOSCReceiver serving on {}\033[0m".format(
self.server.server_address
)
)
self.server.serve_forever()
except:
print(
f"\033[91m[ERROR] OSC Receive port: {self.config.gui_osc_receiver_port} occupied.\033[0m"
)

View File

@ -0,0 +1,13 @@
import dataclasses
from enum import IntEnum
class OSCMessageType(IntEnum):
EYE_INFO = 1
VRCFT_MODULE_INFO = 2
@dataclasses.dataclass
class OSCMessage:
type: OSCMessageType
data: any

View File

@ -0,0 +1,17 @@
from pythonosc.udp_client import SimpleUDPClient
from osc.OSCMessage import OSCMessage
class VRCFTModuleSender:
set_command_pattern = "/command/{}/{}/"
def send(self, osc_message: OSCMessage, client: SimpleUDPClient):
command = osc_message.data.get("command", None)
field_to_send = osc_message.data.get("field", None)
value_to_send = osc_message.data.get("value", None)
if not command or not all([field_to_send, value_to_send is not None]):
print("[ERROR] Misconfiguration in received OSC message for the VRCFT Module")
return
client.send_message(self.set_command_pattern.format(command, field_to_send), value_to_send)

View File

@ -0,0 +1,350 @@
from pythonosc.udp_client import SimpleUDPClient
from eye import EyeId
from osc.OSCMessage import OSCMessage
from config import EyeTrackConfig, EyeTrackSettingsConfig
from enum import IntEnum
import time
def _eyelid_transformer(config, eye_blink):
if config.osc_invert_eye_close:
return float(1 - eye_blink)
else:
return float(eye_blink)
class OutputType(IntEnum):
V1_PARAMS = 1
V2_PARAMS = 2
NATIVE_PARAMS = 3
class VRChatOSCSender:
def __init__(self):
self.is_single_eye = False
self.falloff_enabled = False
self.left_y = 621
self.right_y = 621
self.r_eye_x = 0
self.l_eye_x = 0
self.r_eye_blink = 0.7
self.l_eye_blink = 0.7
self.l_eye_velocity = 0
self.r_eye_velocity = 1
self.left_last_blink = time.time()
self.right_last_blink = time.time()
self.r_dilation = 0
self.l_dilation = 0
def output_osc_info(
self,
osc_message: OSCMessage,
client: SimpleUDPClient,
main_config: EyeTrackConfig,
config: EyeTrackSettingsConfig,
):
eye_id, eye_info = osc_message.data
self.is_single_eye = self.get_is_single_eye(main_config.eye_display_id)
output_method = None
if config.gui_vrc_native:
output_method = self.output_native
if config.gui_osc_vrcft_v1:
output_method = self.output_v1_params
if config.gui_osc_vrcft_v2:
output_method = self.output_v2_params
if output_method:
output_method(
main_config=main_config,
config=config,
client=client,
eye_x=eye_info.x,
eye_y=eye_info.y,
eye_blink=eye_info.blink,
avg_velocity=eye_info.avg_velocity,
eye_id=eye_id,
pupil_dilation=eye_info.pupil_dilation,
)
@staticmethod
def get_is_single_eye(eye_display_id):
return eye_display_id in [EyeId.RIGHT, EyeId.LEFT]
def update_eye_state(self, eye_id, eye_x, eye_y, eye_blink, avg_velocity, pupil_dilation):
if eye_id == EyeId.LEFT:
self.l_eye_x = eye_x
self.l_eye_blink = eye_blink
self.left_y = eye_y
self.l_eye_velocity = avg_velocity
if eye_id == EyeId.RIGHT:
self.r_eye_x = eye_x
self.r_eye_blink = eye_blink
self.right_y = eye_y
self.r_eye_velocity = avg_velocity
def output_native(self, main_config, config, client, eye_x, eye_y, eye_blink, avg_velocity, eye_id, pupil_dilation):
default_eye_blink_params = {
"eye_id": eye_id,
"client": client,
"config": config,
}
self.update_eye_state(
eye_id=eye_id,
eye_x=eye_x,
eye_y=eye_y,
eye_blink=eye_blink,
avg_velocity=avg_velocity,
pupil_dilation=pupil_dilation,
)
if self.is_single_eye:
self.output_osc_native_blink(
**default_eye_blink_params,
)
client.send_message(
"/tracking/eye/LeftRightVec",
[float(eye_x), float(eye_y), 1.0, float(eye_x), float(eye_y), 1.0],
)
if eye_id in [EyeId.LEFT, EyeId.RIGHT, EyeId.BOTH] and not self.is_single_eye:
self.output_osc_native_blink(**default_eye_blink_params, single_eye_mode=False)
if not self.is_single_eye:
# vrc native ET (z values may need tweaking, they act like a scalar)
client.send_message(
"/tracking/eye/LeftRightVec",
[
float(self.l_eye_x),
float(self.left_y),
1.0,
float(self.r_eye_x),
float(self.right_y),
1.0,
],
)
def output_v1_params(
self,
main_config,
config,
client,
eye_x,
eye_y,
eye_blink,
avg_velocity,
eye_id,
pupil_dilation,
):
default_eye_blink_params = {
"eye_id": eye_id,
"client": client,
"config": config,
"left_eye_blink_address": config.osc_left_eye_close_address,
"right_eye_blink_address": config.osc_right_eye_close_address,
}
self.update_eye_state(
eye_id=eye_id,
eye_x=eye_x,
eye_y=eye_y,
eye_blink=eye_blink,
avg_velocity=avg_velocity,
pupil_dilation=pupil_dilation,
)
if self.is_single_eye:
client.send_message(config.osc_left_eye_x_address, eye_x)
client.send_message(config.osc_right_eye_x_address, eye_x)
client.send_message(config.osc_eyes_y_address, eye_y)
client.send_message(config.osc_eyes_pupil_dilation_address, pupil_dilation)
self.output_vrcft_blink_data(**default_eye_blink_params)
if eye_id in [EyeId.LEFT, EyeId.RIGHT] and not self.is_single_eye:
self.output_vrcft_blink_data(**default_eye_blink_params, single_eye_mode=False)
if eye_id == EyeId.LEFT:
client.send_message(config.osc_left_eye_x_address, self.l_eye_x)
self.left_y = eye_y
self.l_dilation = pupil_dilation
client.send_message(
config.osc_left_eye_close_address,
_eyelid_transformer(config, self.l_eye_blink),
)
if eye_id == EyeId.RIGHT:
client.send_message(config.osc_right_eye_x_address, self.r_eye_x)
self.right_y = eye_y
self.r_dilation = pupil_dilation
client.send_message(
config.osc_right_eye_close_address,
_eyelid_transformer(config, self.r_eye_blink),
)
if main_config.eye_display_id == EyeId.BOTH and self.right_y != 621 and self.left_y != 621:
y = (self.right_y + self.left_y) / 2
client.send_message(config.osc_eyes_y_address, y)
avg_dilation = (self.r_dilation + self.l_dilation) / 2 # i am unsure of this tbh.
client.send_message(config.osc_eyes_pupil_dilation_address, avg_dilation) # single param for both eyes.
def output_v2_params(
self,
main_config,
config,
client,
eye_x,
eye_y,
eye_blink,
avg_velocity,
eye_id,
pupil_dilation,
):
default_eye_blink_params = {
"eye_id": eye_id,
"client": client,
"config": config,
}
self.update_eye_state(
eye_id=eye_id,
eye_x=eye_x,
eye_y=eye_y,
eye_blink=eye_blink,
avg_velocity=avg_velocity,
pupil_dilation=pupil_dilation,
)
if self.is_single_eye:
client.send_message("/avatar/parameters/v2/EyeX", eye_x)
client.send_message("/avatar/parameters/v2/EyeY", eye_y)
client.send_message("/avatar/parameters/v2/PupilDilation", pupil_dilation)
self.output_vrcft_blink_data(
**default_eye_blink_params,
left_eye_blink_address="/avatar/parameters/v2/EyeLid",
right_eye_blink_address="/avatar/parameters/v2/EyeLid",
)
if eye_id in [EyeId.LEFT, EyeId.RIGHT] and not self.is_single_eye:
self.output_vrcft_blink_data(
**default_eye_blink_params,
left_eye_blink_address="/avatar/parameters/v2/EyeLidLeft",
right_eye_blink_address="/avatar/parameters/v2/EyeLidRight",
single_eye_mode=False,
)
if eye_id == EyeId.LEFT:
self.l_dilation = pupil_dilation
client.send_message("/avatar/parameters/v2/EyeLeftX", self.l_eye_x)
if self.left_y != 621:
client.send_message("/avatar/parameters/v2/EyeLeftY", eye_y)
client.send_message(
"/avatar/parameters/v2/EyeLidLeft",
_eyelid_transformer(config, self.l_eye_blink),
)
if eye_id == EyeId.RIGHT:
self.r_dilation = pupil_dilation
client.send_message("/avatar/parameters/v2/EyeRightX", self.r_eye_x)
if eye_y != 621:
client.send_message("/avatar/parameters/v2/EyeRightY", eye_y)
client.send_message(
"/avatar/parameters/v2/EyeLidRight",
_eyelid_transformer(config, self.r_eye_blink),
)
avg_pupil_dilation = (self.l_dilation + self.r_dilation) / 2
client.send_message("/avatar/parameters/v2/PupilDilation", avg_pupil_dilation)
def output_vrcft_blink_data(
self,
eye_id: EyeId,
client: SimpleUDPClient,
config,
left_eye_blink_address,
right_eye_blink_address,
single_eye_mode=True,
):
active_eye_blink = self.r_eye_blink if eye_id == EyeId.RIGHT else self.l_eye_blink
falloff_blink = self.r_eye_blink if eye_id == EyeId.LEFT else self.l_eye_blink
blink_address = right_eye_blink_address if eye_id == EyeId.RIGHT else left_eye_blink_address
side_name = "left" if eye_id == EyeId.RIGHT else "right"
last_side_blink = getattr(self, f"{side_name}_last_blink")
if single_eye_mode:
# in case of v1 params, we have to send the same data do each eye separately.
# so in case of v2 params, we will be generating one unnecessary call more
client.send_message(left_eye_blink_address, _eyelid_transformer(config, active_eye_blink))
client.send_message(right_eye_blink_address, _eyelid_transformer(config, active_eye_blink))
elif eye_id in [EyeId.RIGHT, EyeId.LEFT] and not single_eye_mode:
if active_eye_blink == 0.0:
if last_side_blink > 0.20:
for _ in range(5):
client.send_message(blink_address, _eyelid_transformer(config, active_eye_blink))
setattr(self, f"{side_name}_last_blink", time.time() - last_side_blink)
if config.gui_outer_side_falloff:
if falloff_blink == 0.0:
client.send_message(left_eye_blink_address, _eyelid_transformer(config, self.l_eye_blink))
client.send_message(right_eye_blink_address, _eyelid_transformer(config, self.r_eye_blink))
client.send_message(blink_address, _eyelid_transformer(config, active_eye_blink))
def output_osc_native_blink(
self,
eye_id: EyeId,
client,
config,
single_eye_mode=True,
):
blink_address = "/tracking/eye/EyesClosedAmount"
active_eye_blink = self.r_eye_blink if eye_id == EyeId.RIGHT else self.l_eye_blink
falloff_blink = self.r_eye_blink if eye_id == EyeId.LEFT else self.l_eye_blink
side_name = "left" if eye_id == EyeId.RIGHT else "right"
last_side_blink = getattr(self, f"{side_name}_last_blink")
def send_native_binary_blink(address: str, blink_value):
if last_side_blink > 0.2:
for _ in range(5):
client.send_message(address, float(1 - blink_value))
setattr(self, f"{side_name}_last_blink", time.time() - last_side_blink)
if single_eye_mode:
if active_eye_blink == 0.0:
send_native_binary_blink(blink_address, active_eye_blink)
else:
client.send_message(blink_address, float(1 - active_eye_blink))
if eye_id in [EyeId.RIGHT, EyeId.LEFT] and not single_eye_mode:
# in dual eye mode we need to average the blink to prevent flickering.
# VRC also **currently** doesn't support separate eyelids, so it's fine
if self.r_eye_blink or self.l_eye_blink:
averaged_eye_blink = (self.r_eye_blink + self.l_eye_blink) / 2
else:
averaged_eye_blink = 0
client.send_message(
blink_address,
_eyelid_transformer(config, 1 - averaged_eye_blink),
)
if averaged_eye_blink == 0.0:
send_native_binary_blink(blink_address, averaged_eye_blink)
if config.gui_outer_side_falloff:
if falloff_blink == 0.0:
client.send_message(blink_address, float(1 - averaged_eye_blink))
if eye_id == EyeId.BOTH and self.r_eye_blink != 621 and self.r_eye_blink != 621:
if self.r_eye_blink == 0.0 or self.l_eye_blink == 0.0:
send_native_binary_blink(blink_address, active_eye_blink)
# this has a nasty habit of permanent-squint FIXME
averaged_eye_blink = (self.r_eye_blink + self.l_eye_blink) / 2
client.send_message(blink_address, float(1 - averaged_eye_blink))

View File

214
EyeTrackApp/osc/osc.py Normal file
View File

@ -0,0 +1,214 @@
"""
------------------------------------------------------------------------------------------------------
,@@@@@@
@@@@@@@@@@@ @@@
@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@@ @@@@@@@@@@@@@@
@@@@@@@/ ,@@@@@@@@@@@@@
/@@@@@@@@@@@@@@@ @@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@
@@@@@@@@ @@@@@
,@@@ @@@@&
@@@@@@. @@@@
@@@ @@@@@@@@@/ @@@@@
,@@@. @@@@@@((@ @@@@(
//@@@ ,, @@@@ @@@@@
@@@( @@@@@@@
@@@ @ @@@@@@@@#
@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@(
Copyright (c) 2023 EyeTrackVR <3
LICENSE: GNU GPLv3
------------------------------------------------------------------------------------------------------
"""
from time import sleep
from typing import Dict, Optional, Iterable, Callable
from pythonosc import udp_client
from pythonosc import osc_server
from pythonosc import dispatcher
from config import EyeTrackConfig
from osc.OSCMessage import OSCMessage, OSCMessageType
from osc.VRCFTModuleMessenger import VRCFTModuleSender
from osc.VRChatOSCSender import VRChatOSCSender
import queue
import threading
class OSCManager:
def __init__(
self,
osc_message_in_queue: queue.Queue[OSCMessage],
config: EyeTrackConfig,
):
self.sender_cancellation_event = threading.Event()
self.receiver_cancellation_event = threading.Event()
self.listeners = {}
self.osc_message_in_queue = osc_message_in_queue
self.config = config
self.settings = config.settings
self.osc_sender: Optional[OSCSender] = None
self.osc_receiver = None
self.osc_sender_thread: Optional[threading.Thread] = None
self.osc_receiver_thread: Optional[threading.Thread] = None
def start(self):
self.setup_sender()
self.setup_receiver()
def setup_sender(self):
print(f"\033[92m[INFO] Setting up OSC sender\033[0m")
self.sender_cancellation_event.clear()
self.osc_sender = OSCSender(self.sender_cancellation_event, self.osc_message_in_queue, self.config)
self.osc_sender_thread = threading.Thread(target=self.osc_sender.run)
self.osc_sender_thread.start()
def setup_receiver(self):
if self.settings.gui_ROSC:
self.receiver_cancellation_event.clear()
print(f"\033[92m[INFO] Setting up OSC receiver\033[0m")
self.osc_receiver = OSCReceiver(self.receiver_cancellation_event, self.config, self.listeners)
self.osc_receiver_thread = threading.Thread(target=self.osc_receiver.run)
self.osc_receiver_thread.start()
def register_listeners(self, osc_address: str, callbacks: Iterable[Callable]):
if not self.listeners.get(osc_address):
self.listeners[osc_address] = []
self.listeners[osc_address].extend(callbacks)
def update(self, data: dict):
keys = set(data.keys())
sender_trigger_keys = {
"gui_osc_port",
"gui_VRCFTModulePort",
"gui_VRCFTModuleIPAddress",
"gui_use_module",
}
if sender_trigger_keys.intersection(keys):
self.stop_sender()
self.setup_sender()
receiver_trigger_keys = {
"gui_ROSC",
"gui_osc_receiver_port",
}
if receiver_trigger_keys.intersection(keys):
self.stop_receiver()
self.setup_receiver()
def shutdown(self):
self.stop_sender()
self.stop_receiver()
def stop_sender(self):
self.sender_cancellation_event.set()
self.osc_sender_thread.join()
def stop_receiver(self):
if self.osc_receiver_thread:
self.receiver_cancellation_event.set()
self.osc_receiver_thread.join()
class OSCSender:
def __init__(
self,
cancellation_event: threading.Event,
msg_queue: queue.Queue[OSCMessage],
main_config: EyeTrackConfig,
):
self.cancellation_event = cancellation_event
self.msg_queue = msg_queue
self.main_config = main_config
self.config = main_config.settings
self.vrc_sender = VRChatOSCSender()
self.module_sender = VRCFTModuleSender()
self.vrc_client = None
self.vrcft_client = None
def run(self):
self.vrc_client = udp_client.SimpleUDPClient(self.config.gui_osc_address, int(self.config.gui_osc_port))
self.vrcft_client = udp_client.SimpleUDPClient(
self.config.gui_VRCFTModuleIPAddress,
int(self.config.gui_VRCFTModulePort),
)
vrc_osc_output_client = self.vrc_client
if self.config.gui_use_module:
vrc_osc_output_client = self.vrcft_client
while not self.cancellation_event.is_set():
try:
osc_message: OSCMessage = self.msg_queue.get(block=True, timeout=0.1)
match osc_message.type:
case OSCMessageType.EYE_INFO:
self.vrc_sender.output_osc_info(
osc_message=osc_message,
client=vrc_osc_output_client,
main_config=self.main_config,
config=self.config,
)
case OSCMessageType.VRCFT_MODULE_INFO:
self.module_sender.send(osc_message=osc_message, client=self.vrcft_client)
case _:
raise Exception("Encountered message without a handler %s", osc_message.type)
except queue.Empty:
continue
class OSCReceiver:
def __init__(
self,
cancellation_event: threading.Event,
main_config: EyeTrackConfig,
listeners: Dict[str, Callable[[OSCMessage], None]],
):
self.config = main_config.settings
self.cancellation_event = cancellation_event
self.dispatcher = dispatcher.Dispatcher()
self.listeners = listeners
self.server_thread = None
try:
# this thing sucks ass god fucking damn it.
# like, there is no way of shutting it down UNLESS you run it in a thread
# which is kinda dumb, but oh well.
# Also, it doesn't shutdown properly. It's STILL connected to the port
self.server = osc_server.OSCUDPServer(
(self.config.gui_osc_address, int(self.config.gui_osc_receiver_port)),
self.dispatcher,
)
except Exception: # noqa
print(f"\033[91m[ERROR] OSC Receive port: {self.config.gui_osc_receiver_port} occupied.\033[0m")
def shutdown(self):
print("\033[94m[INFO] Exiting OSC Receiver\033[0m")
try:
self.server.shutdown()
self.server_thread.join()
except Exception: # noqa
pass
def handle_osc_message(self, address, value):
for listener in self.listeners.get(address, []):
listener(OSCMessage(type=OSCMessageType.EYE_INFO, data=value))
def run(self):
try:
self.dispatcher.set_default_handler(self.handle_osc_message)
print("\033[92m[INFO] OSC Listening on {}\033[0m".format(self.server.server_address))
self.server_thread = threading.Thread(target=self.server.serve_forever)
self.server_thread.start()
while not self.cancellation_event.is_set():
sleep(10)
self.shutdown()
except Exception: # noqa:
print(f"\033[91m[ERROR] OSC Receive port: {self.config.gui_osc_receiver_port} occupied.\033[0m")

View File

@ -1,3 +1,29 @@
"""
------------------------------------------------------------------------------------------------------
,@@@@@@
@@@@@@@@@@@ @@@
@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@@ @@@@@@@@@@@@@@
@@@@@@@/ ,@@@@@@@@@@@@@
/@@@@@@@@@@@@@@@ @@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@
@@@@@@@@ @@@@@
,@@@ @@@@&
@@@@@@. @@@@
@@@ @@@@@@@@@/ @@@@@
,@@@. @@@@@@((@ @@@@(
//@@@ ,, @@@@ @@@@@
@@@( @@@@@@@
@@@ @ @@@@@@@@#
@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@(
Copyright (c) 2023 EyeTrackVR <3
LICENSE: GNU GPLv3
------------------------------------------------------------------------------------------------------
"""
import numpy as np
import time
from enum import IntEnum
@ -5,9 +31,11 @@ from utils.misc_utils import PlaySound, SND_FILENAME, SND_ASYNC, resource_path
from utils.eye_falloff import velocity_falloff
import socket
import struct
import threading
import os
import subprocess
import math
from utils.calibration_3d import receive_calibration_data, converge_3d
class TimeoutError(RuntimeError):
pass
@ -19,9 +47,7 @@ class AsyncCall(object):
self.Callback = callback
def __call__(self, *args, **kwargs):
self.Thread = threading.Thread(
target=self.run, name=self.Callable.__name__, args=args, kwargs=kwargs
)
self.Thread = threading.Thread(target=self.run, name=self.Callable.__name__, args=args, kwargs=kwargs)
self.Thread.start()
return self
@ -77,31 +103,77 @@ class var:
right_y = 0.0
l_eye_velocity = 0.0
r_eye_velocity = 0.0
overlay_active = False
falloff_latch = False
single_eye = True
left_enb = 0
right_enb = 0
eye_wait = 10
left_calib = False
right_calib = False
completed_3d_calib = 0
@Async
def center_overlay_calibrate(self):
try:
os.startfile(
"Tools/ETVR_SteamVR_Calibration_Overlay.exe -center"
) # i cant remember if this need the - for argument...
# try:
if var.overlay_active != True:
dirname = os.getcwd()
overlay_path = os.path.join(dirname, "center.bat")
os.startfile(overlay_path)
var.overlay_active = True
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ("localhost", 2112)
sock.bind(server_address)
data, address = sock.recvfrom(4096)
received_int = struct.unpack("!l", data)[0]
message = received_int
self.settings.gui_recenter_eyes = False
print(message) # TODO: remove print after testing
self.calibration_frame_counter = 0
var.overlay_active = False
# except:
# print("[WARN] Calibration overlay error. Make sure SteamVR is Running.")
# self.settings.gui_recenter_eyes = False
# var.overlay_active = False
@Async
def overlay_calibrate_3d(self):
try:
if var.overlay_active != True:
dirname = os.getcwd()
overlay_path = os.path.join(dirname, "calibrate.bat")
os.startfile(overlay_path)
var.overlay_active = True
while var.overlay_active:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ("localhost", 2112)
sock.bind(server_address)
data, address = sock.recvfrom(4096)
received_int = struct.unpack("!l", data)[0]
message = received_int
self.settings.gui_recenter_eyes = False
self.settings.grab_3d_point = True
print(message)
if message == 9:
var.overlay_active = False
except:
print("[WARN] Calibration overlay error. Make sure SteamVR is Running.")
self.settings.gui_recenter_eyes = False
return self.settings.gui_recenter_eyes
var.overlay_active = False
class cal:
def cal_osc(self, cx, cy):
def cal_osc(self, cx, cy, angle):
#print(self.eye_id)
if cx == None or cy == None:
return 0, 0
if cx == 0:
@ -112,6 +184,51 @@ class cal:
flipx = self.settings.gui_flip_x_axis_right
else:
flipx = self.settings.gui_flip_x_axis_left
if self.calibration_3d_frame_counter == -621: #or self.settings.gui_3d_calibration:
self.calibration_3d_frame_counter = self.calibration_3d_frame_counter - 1
overlay_calibrate_3d(self)
self.config.calibration_points_3d = []
# print(self.eye_id, cx, cy)
# self.settings.gui_3d_calibration = False
if self.settings.grab_3d_point:
# Check if both calibrations are done
if var.left_calib and var.right_calib:
self.settings.grab_3d_point = False
var.left_calib = False
var.right_calib = False
print('end', len(self.config.calibration_points_3d), self.config.calibration_points_3d)
else:
# Check if it's the left eye and left calibration is not done yet
if self.eye_id == EyeId.LEFT and not var.left_calib:
var.left_calib = True
self.config.calibration_points_3d.append((cx, cy, 1))
# Check if it's the right eye and right calibration is not done yet
elif self.eye_id == EyeId.RIGHT and not var.right_calib:
var.right_calib = True
self.config.calibration_points_3d.append((cx, cy, 0))
if self.eye_id == EyeId.LEFT and len(self.config.calibration_points_3d) == 9 and var.left_calib == False:
var.left_calib = True
receive_calibration_data(self.config.calibration_points_3d, self.eye_id)
print('SENT LEFT EYE POINTS')
var.completed_3d_calib += 1
if self.eye_id == EyeId.RIGHT and len(self.config.calibration_points_3d) == 9 and var.right_calib == False:
var.right_calib = True
receive_calibration_data(self.config.calibration_points_3d, self.eye_id)
print('SENT RIGHT EYE POINTS')
var.completed_3d_calib += 1
# print(len(self.config.calibration_points), self.eye_id)
if var.completed_3d_calib >= 2:
converge_3d()
# pass
if self.calibration_frame_counter == 0:
self.calibration_frame_counter = None
@ -140,15 +257,15 @@ class cal:
self.calibration_frame_counter -= 1
if self.settings.gui_recenter_eyes == True:
self.config.calib_XOFF = cx
self.config.calib_YOFF = cy
if self.ts == 0:
center_overlay_calibrate(self) # TODO, only call on windows machines?
self.settings.gui_recenter_eyes = False
PlaySound(
resource_path("Audio/completed.wav"), SND_FILENAME | SND_ASYNC
)
PlaySound(resource_path("Audio/completed.wav"), SND_FILENAME | SND_ASYNC)
else:
self.ts = self.ts - 1
@ -181,9 +298,7 @@ class cal:
yu = float((cy - self.config.calib_YOFF) / calib_diff_y_MIN)
yd = float((cy - self.config.calib_YOFF) / calib_diff_y_MAX)
if (
self.settings.gui_flip_y_axis
): # check config on flipped values settings and apply accordingly
if self.settings.gui_flip_y_axis: # check config on flipped values settings and apply accordingly
if yd >= 0:
out_y = max(0.0, min(1.0, yd))
if yu > 0:
@ -206,16 +321,12 @@ class cal:
out_x = -abs(max(0.0, min(1.0, xl)))
if self.settings.gui_outer_side_falloff:
run_time = time.time()
out_x_mult = out_x * 100
out_y_mult = out_y * 100
velocity = abs(
np.sqrt(
abs(
np.square(out_x_mult - var.past_x)
- np.square(out_y_mult - var.past_y)
)
)
np.sqrt(abs(np.square(out_x_mult - var.past_x) - np.square(out_y_mult - var.past_y)))
/ ((var.start_time - run_time) * 10)
)
if len(var.velocity_rolling_list) < 15:
@ -223,24 +334,21 @@ class cal:
else:
var.velocity_rolling_list.pop(0)
var.velocity_rolling_list.append(float(velocity))
var.average_velocity = sum(var.velocity_rolling_list) / len(
var.velocity_rolling_list
)
var.average_velocity = sum(var.velocity_rolling_list) / len(var.velocity_rolling_list)
var.past_x = out_x_mult
var.past_y = out_y_mult
out_x, out_y = velocity_falloff(self, var, out_x, out_y)
try:
noisy_point = np.array(
[float(out_x), float(out_y)]
) # fliter our values with a One Euro Filter
noisy_point = np.array([float(out_x), float(out_y)]) # fliter our values with a One Euro Filter
point_hat = self.one_euro_filter(noisy_point)
out_x = point_hat[0]
out_y = point_hat[1]
except:
pass
out_x, out_y = velocity_falloff(self, var, out_x, out_y)
return out_x, out_y, var.average_velocity
else:
if self.printcal:

View File

@ -23,11 +23,12 @@ RANSAC 3D By: Summer#2406 (Main Algorithm Engineer), Pupil Labs (pye3d), PallasN
Algorithm App Implementations By: Prohurtz, qdot (Initial App Creator)
Copyright (c) 2023 EyeTrackVR <3
LICENSE: Summer Software Distribution License 1.0
------------------------------------------------------------------------------------------------------
"""
import cv2
import numpy as np
from enum import IntEnum
from eye import EyeId
from utils.img_utils import safe_crop
from utils.misc_utils import clamp
import os
@ -45,13 +46,6 @@ else:
process.nice()
class EyeId(IntEnum):
RIGHT = 0
LEFT = 1
BOTH = 2
SETTINGS = 3
def ellipse_model(data, y, f):
"""
There is no need to make this process a function, since making the process a function will slow it down a little by calling it.
@ -117,13 +111,9 @@ def fit_rotated_ellipse_ransac(
# These two lines are one of the bottlenecks
datamod_rng_5x5 = np.matmul(datamod_rng_swap_trans, datamod_rng_swap)
datamod_rng_p5smp = np.matmul(
np.linalg.inv(datamod_rng_5x5), datamod_rng_swap_trans
)
datamod_rng_p5smp = np.matmul(np.linalg.inv(datamod_rng_5x5), datamod_rng_swap_trans)
datamod_rng_p = np.matmul(
datamod_rng_p5smp, datamod_rng6[:, :, np.newaxis]
).reshape((-1, 5))
datamod_rng_p = np.matmul(datamod_rng_p5smp, datamod_rng6[:, :, np.newaxis]).reshape((-1, 5))
# I don't think it looks beautiful.
ellipse_y_arr = np.asarray(
@ -137,9 +127,7 @@ def fit_rotated_ellipse_ransac(
dtype=ret_dtype,
)
ellipse_data_arr = ellipse_model(
datamod_slim, ellipse_y_arr, np.asarray(datamod_rng_p[:, 4])
).transpose((1, 0))
ellipse_data_arr = ellipse_model(datamod_slim, ellipse_y_arr, np.asarray(datamod_rng_p[:, 4])).transpose((1, 0))
ellipse_data_abs = np.abs(ellipse_data_arr)
ellipse_data_index = np.argmax(np.sum(ellipse_data_abs < offset, axis=1), axis=0)
effective_data_arr = ellipse_data_arr[ellipse_data_index]
@ -218,7 +206,8 @@ cct = 300
def RANSAC3D(self, hsrac_en):
f = False
ranf = False
blink = 0.7
blink = 0.8
angle = 0
if hsrac_en:
(
@ -246,7 +235,6 @@ def RANSAC3D(self, hsrac_en):
else:
frame = self.current_image_gray_clean
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
rng = np.random.default_rng()
@ -267,7 +255,12 @@ def RANSAC3D(self, hsrac_en):
# Crop first to reduce the amount of data to process.
# frame = frame[0:len(frame) - 5, :]
# To reduce the processing data, blur.
frame_gray = cv2.GaussianBlur(frame, (5, 5), 0)
if frame is None:
print("[WARN] Frame is empty")
self.failed = self.failed + 1 # we have failed, move onto next algo
return 0, 0, 0, frame, blink, 0, 0
else:
frame_gray = cv2.GaussianBlur(frame, (5, 5), 0)
# this will need to be adjusted everytime hardware is changed (brightness of IR, Camera postion, etc)m
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(frame_gray)
@ -296,6 +289,7 @@ def RANSAC3D(self, hsrac_en):
contours, _ = cv2.findContours(th_frame, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
hull = []
# print(contours)
# This way is faster than contours[i]
# But maybe this one is faster. hull = [cv2.convexHull(cnt, False) for cnt in contours]
for cnt in contours:
@ -329,9 +323,7 @@ def RANSAC3D(self, hsrac_en):
pass
self.current_image_gray = frame
cv2.circle(
self.current_image_gray, min_loc, 2, (0, 0, 255), -1
) # the point of the darkest area in the image
cv2.circle(self.current_image_gray, min_loc, 2, (0, 0, 255), -1) # the point of the darkest area in the image
# However eyes are annoyingly three dimensional, so we need to take this ellipse and turn it
# into a curve patch on the surface of a sphere (the eye itself). If it's not a sphere, see your
@ -346,6 +338,7 @@ def RANSAC3D(self, hsrac_en):
result_2d["center"] = (cx, cy)
result_2d["axes"] = (w, h)
result_2d["angle"] = theta * 180.0 / np.pi
angle = result_2d["angle"]
result_2d_final["ellipse"] = result_2d
result_2d_final["diameter"] = w
result_2d_final["location"] = (cx, cy)
@ -354,9 +347,7 @@ def RANSAC3D(self, hsrac_en):
# Black magic happens here, but after this we have our reprojected pupil/eye, and all we had
# to do was sell our soul to satan and/or C++.
result_3d = self.detector_3d.update_and_detect(
result_2d_final, self.current_image_gray
)
result_3d = self.detector_3d.update_and_detect(result_2d_final, self.current_image_gray)
# Now we have our pupil
ellipse_3d = result_3d["ellipse"]
@ -366,7 +357,7 @@ def RANSAC3D(self, hsrac_en):
# Record our pupil center
exm = ellipse_3d["center"][0]
eym = ellipse_3d["center"][1]
# print(result_2d["angle"])
d = result_3d["diameter_3d"]
self.cc_radius = int(float(self.lkg_projected_sphere["axes"][0]))
self.xc = int(float(self.lkg_projected_sphere["center"][0]))
@ -384,9 +375,7 @@ def RANSAC3D(self, hsrac_en):
cy = self.rawy
else:
# print(int(cx), int(clamp(cx + ransac_lower_x, 0, csx)), ransac_lower_x, csx, "y", int(cy), int(clamp(cy + ransac_lower_y, 0, csy)), ransac_lower_y, csy)
cx = int(
clamp(cx + ransac_lower_x, 0, csx)
) # dunno why this is being weird
cx = int(clamp(cx + ransac_lower_x, 0, csx)) # dunno why this is being weird
cy = int(clamp(cy + ransac_lower_y, 0, csy))
# print(contours)
@ -427,6 +416,7 @@ def RANSAC3D(self, hsrac_en):
with open("RANSAC_BLINK_RIGHT.cfg", "w") as file:
for item in self.blink_list:
file.write(str(item) + "\n")
# print("SAVE")
# self.blink_list.pop(0)
@ -439,9 +429,7 @@ def RANSAC3D(self, hsrac_en):
blink = 0.0
try:
cv2.drawContours(
self.current_image_gray, contours, -1, (255, 0, 0), 1
) # TODO: fix visualizations with HSRAC
cv2.drawContours(self.current_image_gray, contours, -1, (255, 0, 0), 1) # TODO: fix visualizations with HSRAC
cv2.circle(self.current_image_gray, (int(cx), int(cy)), 2, (0, 0, 255), -1)
except:
pass
@ -474,12 +462,12 @@ def RANSAC3D(self, hsrac_en):
)
# draw line from center of eyeball to center of pupil
# cv2.line(
# self.current_image_gray,
# tuple(int(v) for v in self.lkg_projected_sphere["center"]),
# tuple(int(v) for v in ellipse_3d["center"]),
# (0, 255, 0), # color (BGR): red
# )
cv2.line(
self.current_image_gray,
tuple(int(v) for v in self.lkg_projected_sphere["center"]),
tuple(int(v) for v in ellipse_3d["center"]),
(0, 255, 0), # color (BGR): red
)
except:
pass
@ -489,7 +477,7 @@ def RANSAC3D(self, hsrac_en):
thresh = cv2.resize(thresh, (x, y))
try:
self.failed = 0 # we have succeded, continue with this
return cx, cy, thresh, blink, w, h
return cx, cy, angle, thresh, blink, w, h
except:
self.failed = self.failed + 1 # we have failed, move onto next algo
return 0, 0, thresh, blink, 0, 0
return 0, 0, 0, thresh, blink, 0, 0

View File

@ -1,9 +0,0 @@
python-osc == 1.8.0
opencv-python == 4.6.0.66
numpy == 1.23.5
pye3d == 0.3.1
pysimplegui == 4.60.4
pydantic == 1.10.2
winotify == 1.1.0
onnxruntime == 1.13.1
serial == 0.0.97

View File

@ -6,7 +6,7 @@ from colorama import Fore
from config import EyeTrackConfig, EyeTrackSettingsConfig
from threading import Event
from osc import EyeId # TODO this is bad, fix this
from eye import EyeId
class BaseSettingsWidget:
@ -25,9 +25,7 @@ class BaseSettingsWidget:
self.main_config = main_config
self.config = main_config.settings
self.initialized_modules = self._initialize_modules(
settings_modules=settings_modules, widget_id=widget_id
)
self.initialized_modules = self._initialize_modules(settings_modules=settings_modules, widget_id=widget_id)
self.general_settings_layout = []
for module in self.initialized_modules:
@ -41,8 +39,16 @@ class BaseSettingsWidget:
background_color="#424042",
),
],
[sg.Text("", background_color="#424042"), ],
[sg.Button("Reset settings to default", key=self.reset_button_key, button_color="#c40e23")],
[
sg.Text("", background_color="#424042"),
],
[
sg.Button(
"Reset settings to default",
key=self.reset_button_key,
button_color="#c40e23",
)
],
]
self.cancellation_event = (

View File

@ -0,0 +1,34 @@
from queue import Queue
from config import EyeTrackConfig
from eye import EyeId
from osc.OSCMessage import OSCMessage, OSCMessageType
from settings.BaseSettings import BaseSettingsWidget
from settings.modules.VRCFTSettingsModule import VRCFTSettingsModule
class VRCFTSettingsWidget(BaseSettingsWidget):
def __init__(self, widget_id: EyeId, main_config: EyeTrackConfig, osc_queue_in: Queue[OSCMessage]):
self.osc_queue = osc_queue_in
settings_modules = [
VRCFTSettingsModule,
]
super().__init__(widget_id, main_config, settings_modules)
def _update_and_save_config(self, validated_data: dict):
self.main_config.update(validated_data, save=True)
for field, value in validated_data.items():
self.osc_queue.put(
OSCMessage(
type=OSCMessageType.VRCFT_MODULE_INFO,
data={
"command": "set",
"field": field,
"value": value,
},
)
)
self.is_saving = False

View File

@ -0,0 +1,45 @@
"""
------------------------------------------------------------------------------------------------------
,@@@@@@
@@@@@@@@@@@ @@@
@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@@ @@@@@@@@@@@@@@
@@@@@@@/ ,@@@@@@@@@@@@@
/@@@@@@@@@@@@@@@ @@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@
@@@@@@@@ @@@@@
,@@@ @@@@&
@@@@@@. @@@@
@@@ @@@@@@@@@/ @@@@@
,@@@. @@@@@@((@ @@@@(
//@@@ ,, @@@@ @@@@@
@@@( @@@@@@@
@@@ @ @@@@@@@@#
@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@(
Copyright (c) 2023 EyeTrackVR <3
LICENSE: GNU GPLv3
------------------------------------------------------------------------------------------------------
"""
from config import EyeTrackConfig
from eye import EyeId
from settings.BaseSettings import BaseSettingsWidget
from settings.modules.AdvancedTrackingAlgoSettingsModule import (
AdvancedTrackingAlgoSettingsModule,
)
from settings.modules.BlinkAlgoModule import BlinkAlgoSettingsModule
from settings.modules.TrackingAlgorithmModule import TrackingAlgorithmModule
class AlgoSettingsWidget(BaseSettingsWidget):
def __init__(self, widget_id: EyeId, main_config: EyeTrackConfig):
settings_modules = [
TrackingAlgorithmModule,
BlinkAlgoSettingsModule,
AdvancedTrackingAlgoSettingsModule,
]
super().__init__(widget_id, main_config, settings_modules)

View File

@ -0,0 +1,43 @@
"""
------------------------------------------------------------------------------------------------------
,@@@@@@
@@@@@@@@@@@ @@@
@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@@ @@@@@@@@@@@@@@
@@@@@@@/ ,@@@@@@@@@@@@@
/@@@@@@@@@@@@@@@ @@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@
@@@@@@@@ @@@@@
,@@@ @@@@&
@@@@@@. @@@@
@@@ @@@@@@@@@/ @@@@@
,@@@. @@@@@@((@ @@@@(
//@@@ ,, @@@@ @@@@@
@@@( @@@@@@@
@@@ @ @@@@@@@@#
@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@(
Copyright (c) 2023 EyeTrackVR <3
LICENSE: GNU GPLv3
------------------------------------------------------------------------------------------------------
"""
from config import EyeTrackConfig
from eye import EyeId
from settings.BaseSettings import BaseSettingsWidget
from settings.modules.GeneralSettingsModule import GeneralSettingsModule
from settings.modules.OneEuroSettingsModule import OneEuroSettingsModule
from settings.modules.OSCSettingsModule import OSCSettingsModule
class SettingsWidget(BaseSettingsWidget):
def __init__(self, widget_id: EyeId, main_config: EyeTrackConfig):
settings_modules = [
GeneralSettingsModule,
OneEuroSettingsModule,
OSCSettingsModule,
]
super().__init__(widget_id, main_config, settings_modules)

View File

@ -1,11 +1,34 @@
def check_is_float_convertible(v: str):
"""Check if value provided can be converted to a float or double.
import ipaddress
PySimpleGUI does not support floats or doubles in UI, so we have to make sure
that what the user typed in is correct
def check_is_float_convertible(v: str):
"""
Check if value provided can be converted to a float or double.
PySimpleGUI does not support floats or doubles in UI, so we have to make sure
that what the user typed in is correct
"""
try:
float(v)
return v
except ValueError:
raise ValueError("Please provide a proper number")
def try_convert_to_float(v: str):
"""
Check if value provided can be converted to a float and return converted result
Basically what `check_is_float_convertible` does but returns a float
"""
try:
return float(check_is_float_convertible(v))
except ValueError:
raise
def check_is_ip_address(v: str):
try:
ipaddress.IPv4Address(v)
return v
except ValueError:
raise ValueError("Please provide a valid IP Address")

View File

@ -15,6 +15,7 @@ class OSCValidationModel(BaseValidationModel):
gui_vrc_native: bool
gui_osc_vrcft_v1: bool
gui_osc_vrcft_v2: bool
gui_use_module: bool
@model_validator(mode="after")
def check_osc_vrcft_versions(self):
@ -42,12 +43,22 @@ class OSCSettingsModule(BaseSettingsModule):
self.gui_vrc_native = f"-VRCNATIVE{widget_id}-"
self.gui_osc_vrcft_v1 = f"-OSCVRCFTV1{widget_id}-"
self.gui_osc_vrcft_v2 = f"-OSCVRCFTV2{widget_id}-"
self.gui_use_module = f"-OSCUSEMODULE{widget_id}-"
def get_layout(self):
return [
[
sg.Text("OSC Settings:", background_color="#242224"),
],
[
sg.Checkbox(
"Use ETVR VRCFT Module",
default=self.config.gui_use_module,
key=self.gui_use_module,
background_color="#424042",
tooltip="Toggle output to VRCFT Module or just regular OSC port",
),
],
[
sg.Checkbox(
"VRC Native Eyetracking",

View File

@ -9,13 +9,17 @@ class TrackingAlgorithmValidationModel(BaseValidationModel):
gui_DADDY: bool
gui_HSF: bool
gui_HSRAC: bool
gui_AHSF: bool
gui_LEAP: bool
gui_RANSAC3D: bool
gui_AHSFRAC: bool
gui_legacy_ransac: bool
gui_BLOBP: int
gui_DADDYP: int
gui_AHSFRACP: int
gui_HSFP: int
gui_AHSFP: int
gui_HSRACP: int
gui_LEAPP: int
gui_RANSAC3DP: int
@ -23,12 +27,14 @@ class TrackingAlgorithmValidationModel(BaseValidationModel):
@model_validator(mode="after")
def check_algorith_order(self):
algos_list = [
self.gui_AHSFP,
self.gui_BLOBP,
self.gui_DADDYP,
self.gui_HSFP,
self.gui_HSRACP,
self.gui_LEAPP,
self.gui_RANSAC3DP,
self.gui_AHSFRACP,
]
algos_set = set(algos_list)
if len(algos_set) != len(algos_list):
@ -39,13 +45,15 @@ class TrackingAlgorithmValidationModel(BaseValidationModel):
class TrackingAlgorithmModule(BaseSettingsModule):
def __init__(self, config, widget_id, **kwargs):
super().__init__(config=config, widget_id=widget_id, **kwargs)
self.algo_count = ["1", "2", "3", "4", "5", "6"]
self.algo_count = ["1", "2", "3", "4", "5", "6", "7", "8"]
self.validation_model = TrackingAlgorithmValidationModel
self.gui_BLOB = f"-BLOBFALLBACK{widget_id}-"
self.gui_DADDY = f"-DADDY{widget_id}-"
self.gui_HSF = f"-HSF{widget_id}-"
self.gui_HSRAC = f"-HSRAC{widget_id}-"
self.gui_LEAP = f"-LEAP{widget_id}-"
self.gui_AHSF = f"-AHSF{widget_id}-"
self.gui_AHSFRAC = f"-gui_AHSFRAC{widget_id}-"
self.gui_RANSAC3D = f"-RANSAC3D{widget_id}-"
self.gui_legacy_ransac = f"-LEGACYRANSACTHRESH{widget_id}-"
@ -54,7 +62,9 @@ class TrackingAlgorithmModule(BaseSettingsModule):
self.gui_HSFP = f"-HSFP{widget_id}-"
self.gui_HSRACP = f"-HSRACP{widget_id}-"
self.gui_LEAPP = f"-LEAPP{widget_id}-"
self.gui_AHSFP = f"-AHSFP{widget_id}-"
self.gui_RANSAC3DP = f"-RANSAC3DP{widget_id}-"
self.gui_AHSFRACP = f"-gui_AHSFRACP{widget_id}-"
# TODO custom validation, make a set of values, count if there's less than overall, if yeah we have a problem
def get_layout(self):
@ -65,6 +75,44 @@ class TrackingAlgorithmModule(BaseSettingsModule):
background_color="#242224",
)
],
[
sg.Checkbox(
"",
default=self.config.gui_AHSFRAC,
key=self.gui_AHSFRAC,
background_color="#424042",
tooltip="Flagship hybrid algo",
),
sg.Combo(
self.algo_count,
default_value=self.config.gui_AHSFRACP,
key=self.gui_AHSFRACP,
background_color="#424042",
text_color="white",
button_arrow_color="black",
button_background_color="#6f4ca1",
tooltip="Select the priority of eyetracking algorithms.",
),
sg.Text("ASHSFRAC", background_color="#424042"),
sg.Checkbox(
"",
default=self.config.gui_AHSF,
key=self.gui_AHSF,
background_color="#424042",
tooltip="Newer version of HSF",
),
sg.Combo(
self.algo_count,
default_value=self.config.gui_AHSFP,
key=self.gui_AHSFP,
background_color="#424042",
text_color="white",
button_arrow_color="black",
button_background_color="#6f4ca1",
tooltip="Select the priority of eyetracking algorithms.",
),
sg.Text("ASHSF", background_color="#424042"),
],
[
sg.Checkbox(
"",

View File

@ -0,0 +1,225 @@
from typing import Iterable
import PySimpleGUI as sg
from pydantic import AfterValidator
from typing_extensions import Annotated
from settings.modules.BaseModule import BaseSettingsModule, BaseValidationModel
from settings.modules.CommonFieldValidators import check_is_ip_address, try_convert_to_float
class VRCFTSettingsModuleValidationModel(BaseValidationModel):
gui_VRCFTModulePort: int
gui_VRCFTModuleIPAddress: Annotated[str, AfterValidator(check_is_ip_address)]
gui_ShouldEmulateEyeWiden: bool
gui_ShouldEmulateEyeSquint: bool
gui_ShouldEmulateEyebrows: bool
gui_WidenThresholdV1_min: float
gui_WidenThresholdV1_max: float
gui_WidenThresholdV2_min: float
gui_WidenThresholdV2_max: float
gui_SqueezeThresholdV1_min: float
gui_SqueezeThresholdV1_max: float
gui_SqueezeThresholdV2_min: float
gui_SqueezeThresholdV2_max: float
gui_EyebrowThresholdRising: float
gui_EyebrowThresholdLowering: float
# this is a hack. I don't like it, but that's what I gotta do to make both, Pydantic and PySimpleGUI happy
gui_OutputMultiplier: Annotated[float, AfterValidator(try_convert_to_float)]
class VRCFTSettingsModule(BaseSettingsModule):
def __init__(self, config, widget_id, **kwargs):
super().__init__(config=config, widget_id=widget_id, **kwargs)
self.validation_model = VRCFTSettingsModuleValidationModel
self.gui_VRCFTModulePort = f"-VRCFTSETTINGSPORTNUMBER{widget_id}"
self.gui_VRCFTModuleIPAddress = f"-VRCFTSETTINGSIPNUMBER{widget_id}"
self.gui_ShouldEmulateEyeWiden = f"-VRCFTSETTINGSEMULATEWIDEN{widget_id}"
self.gui_ShouldEmulateEyeSquint = f"-VRCFTSETTINGSEMULATEEYEWIDEN{widget_id}"
self.gui_ShouldEmulateEyebrows = f"-VRCFTSETTINGSEMULATEEYEBROWS{widget_id}"
self.gui_WidenThresholdV1_min = f"-VRCFTSETTINGSWIDENTHRESHOLDV1MIN{widget_id}"
self.gui_WidenThresholdV1_max = f"-VRCFTSETTINGSWIDENTHRESHOLDV1MAX{widget_id}"
self.gui_WidenThresholdV2_min = f"-VRCFTSETTINGSWIDENTHRESHOLDV2MIN{widget_id}"
self.gui_WidenThresholdV2_max = f"-VRCFTSETTINGSWIDENTHRESHOLDV2MAX{widget_id}"
self.gui_SqueezeThresholdV1_min = f"-VRCFTSETTINGSSQUEEZETHRESHOLDV1MIN{widget_id}"
self.gui_SqueezeThresholdV1_max = f"-VRCFTSETTINGSSQUEEZETHRESHOLDV1MAX{widget_id}"
self.gui_SqueezeThresholdV2_min = f"-VRCFTSETTINGSSQUEEZETHRESHOLDV2MIN{widget_id}"
self.gui_SqueezeThresholdV2_max = f"-VRCFTSETTINGSSQUEEZETHRESHOLDV2MAX{widget_id}"
self.gui_EyebrowThresholdRising = f"-VRCFTSETTINGSEYEBROWTHRESHOLDRISING{widget_id}"
self.gui_EyebrowThresholdLowering = f"-VRCFTSETTINGSEYEBROWTHRESHOLDLOWERING{widget_id}"
self.gui_OutputMultiplier = f"-VRCFTSETTINGSOUTPUTMULTIPLIER{widget_id}"
def get_layout(self) -> Iterable:
return [
[
sg.Text("Emulation selection:", background_color="#242224"),
],
[
sg.Checkbox(
"Emulate Eye Widen",
default=self.config.gui_ShouldEmulateEyeWiden,
key=self.gui_ShouldEmulateEyeWiden,
background_color="#424042",
),
sg.Checkbox(
"Emulate Eye Squint",
default=self.config.gui_ShouldEmulateEyeSquint,
key=self.gui_ShouldEmulateEyeSquint,
background_color="#424042",
),
sg.Checkbox(
"Emulate Eyebrows",
default=self.config.gui_ShouldEmulateEyebrows,
key=self.gui_ShouldEmulateEyebrows,
background_color="#424042",
),
],
[
sg.Text("General Module Settings:", background_color="#242224"),
],
[
sg.Text("VRCFT Module listening IP", background_color="#242224"),
sg.InputText(
self.config.gui_VRCFTModuleIPAddress,
key=self.gui_VRCFTModuleIPAddress,
size=(0, 10),
tooltip="Ip on which the module should listen.",
),
sg.Text("port", background_color="#242224"),
sg.InputText(
self.config.gui_VRCFTModulePort,
key=self.gui_VRCFTModulePort,
size=(0, 10),
tooltip="UDP port on which the module should listen.",
),
],
[
sg.Text("VRCFT Module output multiplier", background_color="#242224"),
sg.InputText(
self.config.gui_OutputMultiplier,
key=self.gui_OutputMultiplier,
size=(0, 10),
tooltip="Output multiplier adjusts the output by the given amount",
),
],
[
sg.Text("Eye Widen thresholds:", background_color="#424042"),
],
[
sg.Text("V1 Min:", background_color="#424042"),
sg.Slider(
range=(0, 1),
resolution=0.01,
default_value=self.config.gui_WidenThresholdV1_min,
orientation="h",
key=self.gui_WidenThresholdV1_min,
background_color="#424042",
tooltip="Controls the point at which the emulation should start for v1 params, reacts to openness",
),
sg.Text("V1 Max:", background_color="#424042"),
sg.Slider(
range=(0, 2),
resolution=0.01,
default_value=self.config.gui_WidenThresholdV1_max,
orientation="h",
key=self.gui_WidenThresholdV1_max,
background_color="#424042",
tooltip="Controls the maximum range of widen emulation",
),
],
[
sg.Text("V2 Min:", background_color="#424042"),
sg.Slider(
range=(0, 2),
resolution=0.01,
default_value=self.config.gui_WidenThresholdV2_min,
orientation="h",
key=self.gui_WidenThresholdV2_min,
background_color="#424042",
tooltip="Controls the point at which the emulation should start for v2 params, reacts to openness",
),
sg.Text("V2 Max:", background_color="#424042"),
sg.Slider(
range=(0, 2),
resolution=0.01,
default_value=self.config.gui_WidenThresholdV2_max,
orientation="h",
key=self.gui_WidenThresholdV2_max,
background_color="#424042",
tooltip="Controls the maximum range of widen emulation",
),
],
[
sg.Text("Eye Squeeze thresholds:", background_color="#424042"),
],
[
sg.Text("V1 Min:", background_color="#424042"),
sg.Slider(
range=(0, 1),
resolution=0.01,
default_value=self.config.gui_SqueezeThresholdV1_min,
orientation="h",
key=self.gui_SqueezeThresholdV1_min,
background_color="#424042",
tooltip="Controls the point at which the emulation should start for v1 params, reacts to openness",
),
sg.Text("V1 Max:", background_color="#424042"),
sg.Slider(
range=(0, 2),
resolution=0.01,
default_value=self.config.gui_SqueezeThresholdV1_max,
orientation="h",
key=self.gui_SqueezeThresholdV1_max,
background_color="#424042",
tooltip="Controls the maximum range of squeeze emulation",
),
],
[
sg.Text("V2 Min:", background_color="#424042"),
sg.Slider(
range=(0, 1),
resolution=0.01,
default_value=self.config.gui_SqueezeThresholdV2_min,
orientation="h",
key=self.gui_SqueezeThresholdV2_min,
background_color="#424042",
tooltip="Controls the point at which the emulation should start for v2 params, reacts to openness",
),
sg.Text("V2 Max:", background_color="#424042"),
sg.Slider(
range=(-2, 0),
resolution=0.01,
default_value=self.config.gui_SqueezeThresholdV2_max,
orientation="h",
key=self.gui_SqueezeThresholdV2_max,
background_color="#424042",
tooltip="Controls the maximum range of squeeze emulation",
),
],
[
sg.Text("Eyebrow emulation Thresholds:", background_color="#424042"),
],
[
sg.Text("Rising:", background_color="#424042"),
sg.Slider(
range=(0, 1),
resolution=0.01,
default_value=self.config.gui_EyebrowThresholdRising,
orientation="h",
key=self.gui_EyebrowThresholdRising,
background_color="#424042",
tooltip="Controls the point at which the emulation should start, reacts to openness",
),
sg.Text("Lowering:", background_color="#424042"),
sg.Slider(
range=(0, 2),
resolution=0.01,
default_value=self.config.gui_EyebrowThresholdLowering,
orientation="h",
key=self.gui_EyebrowThresholdLowering,
background_color="#424042",
tooltip="Controls the maximum range of eyebrows emulation",
),
],
]

View File

@ -0,0 +1,130 @@
# calibration_module.py
import numpy as np
class CalibrationProcessor:
def __init__(self):
self.left_eye_data = None
self.right_eye_data = None
self.P_left = None
self.P_right = None
self.gt_3d = np.array([
(0.8, 0.8, 1), (0, 0.8, 1), (-0.8, 0.8, 1), (0.8, 0, 1), (0, 0, 1),
(-0.8, 0, 1), (0.8, -0.8, 1), (0, -0.8, 1), (-0.8, -0.8, 1)
])
def estimate_projection_matrix(self, eye_data, gt_3d):
# Ensure the input data is a numpy array
eye_data = np.array(eye_data)
gt_3d = np.array(gt_3d)
# Append ones for homogeneous coordinates
gt_3d_h = np.hstack((gt_3d, np.ones((gt_3d.shape[0], 1))))
eye_data_h = np.hstack((eye_data, np.ones((eye_data.shape[0], 1))))
# Debug: Print the shapes of the matrices
print("Shape of gt_3d_h:", gt_3d_h.shape)
print("Shape of eye_data_h:", eye_data_h.shape)
# Solve for the projection matrix using least squares
P, _, _, _ = np.linalg.lstsq(gt_3d_h, eye_data_h, rcond=None)
return P
def receive_calibration_data(self, eye_id, data):
if eye_id == 1:
self.left_eye_data = data
elif eye_id == 0:
self.right_eye_data = data
# print('receive',len(self.left_eye_data), self.left_eye_data, self.right_eye_data, data, eye_id)
# Check if both sets of data have been received
if self.left_eye_data is not None and self.right_eye_data is not None:
if len(self.left_eye_data) == 8 and len(self.right_eye_data) == 8:
self.process_calibration_data()
def process_calibration_data(self):
# Ensure both data are present
if self.left_eye_data is None or self.right_eye_data is None:
raise ValueError("Calibration data for both eyes must be provided")
print("Processing calibration data for both eyes...")
print(f"Left Eye Data: {self.left_eye_data}")
print(f"Right Eye Data: {self.right_eye_data}")
self.left_eye_data = np.array(self.left_eye_data)
self.right_eye_data = np.array(self.right_eye_data)
if len(self.left_eye_data) != len(self.gt_3d):
raise ValueError(
f"Number of left eye points ({len(self.left_eye_data)}) does not match number of 3D points ({len(self.gt_3d)}).")
if len(self.right_eye_data) != len(self.gt_3d):
raise ValueError(
f"Number of right eye points ({len(self.right_eye_data)}) does not match number of 3D points ({len(self.gt_3d)}).")
# After processing, reset the data
# self.left_eye_data = None
# self.right_eye_data = None
# Function to compute the 3D gaze direction from 2D points
def compute_gaze_direction(self, P, point_2d):
print(P, point_2d)
# Convert 2D point to homogeneous coordinates
point_2d_h = np.append(point_2d, 1)
# Solve for 3D direction (Ax = b, where A is the projection matrix and b is the 2D point)
direction, _, _, _ = np.linalg.lstsq(P[:, :-1], point_2d_h, rcond=None)
direction /= np.linalg.norm(direction)
return direction
# Compute the convergence point given 2D points for both eyes
def compute_convergence_point(self, left_point_2d, right_point_2d, P_left, P_right, IPD):
left_eye_pos = np.array([-IPD / 2, 0, 0])
right_eye_pos = np.array([IPD / 2, 0, 0])
gaze_left = self.compute_gaze_direction(P_left, left_point_2d)
gaze_right = self.compute_gaze_direction(P_right, right_point_2d)
# Parameterize the gaze directions as lines
def line_parametric_form(point, direction, t):
return point + t * direction
# Find the closest point between two lines
t_values = np.linspace(-10, 10, 1000)
min_distance = float('inf')
best_point = None
for t1 in t_values:
for t2 in t_values:
point1 = line_parametric_form(left_eye_pos, gaze_left, t1)
point2 = line_parametric_form(right_eye_pos, gaze_right, t2)
distance = np.linalg.norm(point1 - point2)
if distance < min_distance:
min_distance = distance
best_point = (point1 + point2) / 2
return best_point
def set_P(self):
self.P_left = self.estimate_projection_matrix(self.left_eye_data, self.gt_3d)
self.P_right = self.estimate_projection_matrix(self.right_eye_data, self.gt_3d)
# Global instance of CalibrationProcessor
calibration_processor = CalibrationProcessor()
def receive_calibration_data(data, eye_id):
global calibration_processor
calibration_processor.receive_calibration_data(eye_id, data)
def converge_3d():
IPD = 0.058
left_point_2d = (120, 100)
right_point_2d = (118, 65)
# estimate_projection_matrix
calibration_processor.set_P()
convergence_point = calibration_processor.compute_convergence_point(left_point_2d, right_point_2d, calibration_processor.P_left, calibration_processor.P_right, IPD)
print(f"Convergence Point: {convergence_point}")

View File

@ -1,85 +1,45 @@
import numpy as np
from enum import IntEnum
class EyeId(IntEnum):
RIGHT = 0
LEFT = 1
BOTH = 2
SETTINGS = 3
from eye import EyeId
def velocity_falloff(self, var, out_x, out_y):
falloff = False
if self.eye_id in [EyeId.LEFT]:
var.l_eye_velocity = var.average_velocity
if self.settings.gui_outer_side_falloff:
dist = abs(
np.sqrt(
abs(np.square(out_x - var.r_eye_x) - np.square(out_y - var.right_y))
)
)
# print(dist) # TODO remove once testing is done
if dist > self.settings.gui_eye_dominant_diff_thresh:
falloff = True
if (
not self.settings.gui_left_eye_dominant
and not self.settings.gui_right_eye_dominant
):
if var.l_eye_velocity < var.r_eye_velocity:
var.r_eye_x = out_x
var.right_y = out_y
else:
eye_x = var.l_eye_x
eye_y = var.left_y
elif self.settings.gui_left_eye_dominant:
var.r_eye_x = out_x
var.right_y = out_y
falloff = False
else:
var.l_eye_x = out_x
var.left_y = out_y
falloff = False
if (
self.settings.gui_right_eye_dominant
or self.settings.gui_left_eye_dominant
or self.settings.gui_outer_side_falloff
):
# Calculate the distance between the two eyes
dist = np.sqrt(np.square(var.l_eye_x - var.r_eye_x) + np.square(var.left_y - var.right_y))
if self.eye_id == EyeId.LEFT:
var.l_eye_x = out_x
var.left_y = out_y
if self.eye_id == EyeId.RIGHT:
var.r_eye_velocity = var.average_velocity
if self.settings.gui_outer_side_falloff:
dist = abs(
np.sqrt(
abs(np.square(var.l_eye_x - out_x) - np.square(var.left_y - out_y))
)
)
# print(dist, "r") # TODO remove once testing is done
if dist > self.settings.gui_eye_dominant_diff_thresh:
falloff = True
if (
not self.settings.gui_left_eye_dominant
and not self.settings.gui_right_eye_dominant
):
if var.l_eye_velocity < var.r_eye_velocity:
var.r_eye_x = out_x
var.right_y = out_y
else:
var.l_eye_x = out_x
var.left_y = out_y # need to make sure we send these values... might re think the whole file
elif self.settings.gui_right_eye_dominant:
var.l_eye_x = out_x
var.left_y = out_y
falloff = False
if self.eye_id == EyeId.RIGHT:
var.r_eye_x = out_x
var.right_y = out_y
# Check if the distance is greater than the threshold
if dist > self.settings.gui_eye_dominant_diff_thresh:
if self.settings.gui_right_eye_dominant:
out_x, out_y = var.r_eye_x, var.right_y
elif self.settings.gui_left_eye_dominant:
out_x, out_y = var.l_eye_x, var.left_y
else:
falloff = False
var.r_eye_x = out_x
var.right_y = out_y
if self.eye_id == EyeId.LEFT and falloff:
out_x = var.r_eye_x
out_y = var.right_y
if self.eye_id == EyeId.RIGHT and falloff:
out_x = var.l_eye_x
out_y = (
var.left_y
) # needs to not be in this file lol... well if we want proper visualization..
# If the distance is too large, identify the eye with the lower velocity
if var.l_eye_velocity < var.r_eye_velocity:
# Mirror the position of the eye with lower velocity to the other eye
out_x, out_y = var.r_eye_x, var.right_y
else:
# Mirror the position of the eye with lower velocity to the other eye
out_x, out_y = var.l_eye_x, var.left_y
else:
# If the distance is within the threshold, do not mirror the eyes
pass
else:
pass
return out_x, out_y

View File

@ -2,14 +2,20 @@ import cv2
import numpy as np
def safe_crop(img, x, y, x2, y2, keepsize=False):
# The order of the arguments can be reconsidered.
img_h, img_w = img.shape[:2]
outimg = img[max(0, y) : min(img_h, y2), max(0, x) : min(img_w, x2)].copy()
reqsize_x, reqsize_y = abs(x2 - x), abs(y2 - y)
if keepsize and outimg.shape[:2] != (reqsize_y, reqsize_x):
# If the size is different from the expected size (smaller by the amount that is out of range)
outimg = cv2.resize(outimg, (reqsize_x, reqsize_y))
return outimg
try:
# The order of the arguments can be reconsidered.
img_h, img_w = img.shape[:2]
outimg = img[max(0, y) : min(img_h, y2), max(0, x) : min(img_w, x2)].copy()
reqsize_x, reqsize_y = abs(x2 - x), abs(y2 - y)
if keepsize and outimg.shape[:2] != (reqsize_y, reqsize_x):
# If the size is different from the expected size (smaller by the amount that is out of range)
outimg = cv2.resize(outimg, (reqsize_x, reqsize_y))
return outimg
except cv2.error as e:
if '!ssize.empty()' in str(e):
print("Image is None or has zero dimensions. Skipping resizing.")
else:
raise
def circle_crop(img, xc, yc, radius, cct):

View File

@ -2,17 +2,26 @@ import os
import typing
import sys
from pathlib import Path
from typing import Union
is_nt = True if os.name == "nt" else False
def PlaySound(*args, **kwargs): pass
def PlaySound(*args, **kwargs):
pass
SND_FILENAME = SND_ASYNC = 1
if is_nt:
import winsound
PlaySound = winsound.PlaySound
SND_FILENAME = winsound.SND_FILENAME
SND_ASYNC = winsound.SND_ASYNC
def clamp(x, low, high):
return max(low, min(x, high))
@ -39,7 +48,7 @@ class FastMedian:
self.more, self.__median = None, None
if inits is not None:
[self + x for x in inits]
# When full, push the median of current values to next list, then reset.
def __add__(self, x):
self.__median = None
@ -49,23 +58,25 @@ class FastMedian:
self.more + self.__medianPrim(self.all)
# It's going to be slower because of the re-allocation.
self.all = [] # reset
# If there is a next list, ask its median. Else, work it out locally.
def median(self):
return self.more.median() if self.more else self.__medianPrim(self.all)
# Only recompute median if we do not know it already.
def __medianPrim(self, all):
if self.__median is None:
self.__median = lst_median(all, ordered=False)
return self.__median
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
def resource_path(relative_path: Union[str, Path]) -> str:
"""
Get absolute path to resource, works for dev and for PyInstaller
"""
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
base_path = Path(sys._MEIPASS)
except AttributeError:
base_path = os.path.abspath(".")
base_path = Path(".")
return os.path.join(base_path, relative_path)
return str(base_path / relative_path)

687
LICENSE
View File

@ -1,21 +1,674 @@
MIT License
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (c) 2018 Alireza Keshavarzi
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Preamble
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

63
LICENSE-SUMMER Normal file
View File

@ -0,0 +1,63 @@
Summer Software Distribution License 1.0
Copyright 2024, Sameer Suri
0. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall refer to the copyright owner or entity authorized by the copyright owner that is granting the License.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
1. Grant of Copyright License.
Subject to the terms and conditions of this License, the Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual license to use, reproduce, and distribute the original work of the Licensor in Source or Object form.
2. Grant of Patent License.
Subject to the terms and conditions of this License, the Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual license under Licensors applicable patent claims, to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work.
3. Redistribution.
You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, provided that You meet the following conditions:
The original Work and any Derivative Works are licensed under this same License.
You must give any other recipients of the Work or Derivative Works a copy of this License.
4. Contribution.
Any contributions made by You to the Work will automatically be licensed under the same terms as this License, without any additional terms or conditions.
5. Relicensing.
The Licensor reserves the right to relicense the Work under a different license at any time wSithout seeking consent from any contributors or licensees.
6. Modification of License Terms.
Notwithstanding the provisions of Section 7 ("Relicensing"), a Licensee may propose modifications to the terms of this License or a request for a different license to apply to the Work, provided the following conditions are met:
Written Consent: The Licensee must obtain the written consent of the Licensor for the proposed license modification or change. Such consent must be explicit, specifying the new terms or license to be applied, and signed by the Licensor.
Notification to Other Licensees: If the Work has been distributed to other licensees, the Licensee proposing the change must take reasonable steps to notify other affected parties of the proposed licensing change. This may involve public announcement, direct communication with known recipients of the Work, or other reasonable methods to ensure wide awareness of the proposed change.
Agreement Recording: A record of the consent and agreement between the Licensor and Licensee regarding the license modification or change must be maintained. This record should include the original terms, the proposed modifications, and the explicit consent of the Licensor. For transparency and legal clarity, it is recommended to attach this record to any distributions of the Work subject to the modified license terms.
Compliance with Original License Terms: Until the modification or change of the license is formally agreed upon by the Licensor, the Licensee must continue to comply with all terms of the original License as specified in this document.
7. Disclaimer of Warranty.
The Work is provided under this License on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
8. Limitation of Liability.
In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if the Licensor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability.
While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other contributor or the Licensor, and only if You agree to indemnify, defend, and hold each contributor harmless for any liability incurred by, or claims asserted against, such contributor by reason of your accepting any such warranty or additional liability.
10. Termination.
This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. Provisions which, by their nature, should remain in effect beyond the termination of this License shall survive.

View File

@ -64,9 +64,8 @@ Please join our Discord for updates and any questions.
## Licenses
[![GitHub license](https://img.shields.io/github/license/RedHawk989/EyeTrackVR?style=plastic)](https://github.com/RedHawk989/EyeTrackVR/blob/master/LICENSE)
***Most software is licensed under GNU GPLv3, with most tracking algorithims under Summer Software Distribution License 1.0. Each file has its license noted in the beginning of the file for clarity.
***All software is under the [MIT License](http://opensource.org/licenses/MIT).
All documentation, including the [Wiki](https://github.com/RedHawk989/EyeTrackVR/wiki), is under the Creative Commons CC-BY-SA-4.0 license***.
<!-- <div align="center">

125
conftest.py Normal file
View File

@ -0,0 +1,125 @@
import pytest
from config import (
EyeTrackConfig,
EyeTrackCameraConfig,
EyeTrackSettingsConfig,
)
@pytest.fixture()
def eyetrack_settings_config():
return EyeTrackSettingsConfig(
gui_flip_x_axis_left=False,
gui_flip_x_axis_right=False,
gui_flip_y_axis=False,
gui_RANSAC3D=False,
gui_HSF=False,
gui_BLOB=False,
gui_BLINK=False,
gui_HSRAC=False,
gui_AHSFRAC=False,
gui_AHSF=False,
gui_DADDY=False,
gui_LEAP=True,
gui_HSF_radius=15,
gui_HSF_radius_left=10,
gui_HSF_radius_right=10,
gui_min_cutoff="0.0004",
gui_speed_coefficient="0.9",
gui_osc_address="127.0.0.1",
gui_osc_port=8889,
gui_osc_receiver_port=9001,
gui_osc_recenter_address="/avatar/parameters/etvr_recenter",
gui_osc_recalibrate_address="/avatar/parameters/etvr_recalibrate",
gui_blob_maxsize=25.0,
gui_blob_minsize=10.0,
gui_recenter_eyes=False,
tracker_single_eye=2,
gui_threshold=65,
gui_AHSFRACP=1,
gui_AHSFP=2,
gui_HSRACP=3,
gui_HSFP=4,
gui_DADDYP=5,
gui_RANSAC3DP=6,
gui_BLOBP=7,
gui_LEAPP=8,
gui_IBO=True,
gui_skip_autoradius=False,
gui_thresh_add=11,
gui_update_check=False,
gui_ROSC=False,
gui_circular_crop_right=False,
gui_circular_crop_left=False,
ibo_filter_samples=400,
ibo_average_output_samples=0,
ibo_fully_close_eye_threshold=0.3,
calibration_samples=600,
osc_right_eye_close_address="/avatar/parameters/RightEyeLidExpandedSqueeze",
osc_left_eye_close_address="/avatar/parameters/LeftEyeLidExpandedSqueeze",
osc_left_eye_x_address="/avatar/parameters/LeftEyeX",
osc_right_eye_x_address="/avatar/parameters/RightEyeX",
osc_eyes_y_address="/avatar/parameters/EyesY",
osc_invert_eye_close=False,
gui_RANSACBLINK=False,
gui_right_eye_dominant=False,
gui_left_eye_dominant=False,
gui_outer_side_falloff=False,
gui_eye_dominant_diff_thresh=0.3,
gui_legacy_ransac=False,
gui_legacy_ransac_thresh_right=80,
gui_legacy_ransac_thresh_left=80,
gui_LEAP_lid=False,
gui_osc_vrcft_v1=False,
gui_osc_vrcft_v2=False,
gui_vrc_native=False,
gui_pupil_dilation=True,
)
@pytest.fixture()
def eyetrack_camera_config():
return EyeTrackCameraConfig(
rotation_angle=250,
roi_window_x=67,
roi_window_y=27,
roi_window_w=96,
roi_window_h=117,
focal_length=30,
capture_source="http://192.168.0.31/",
calib_XMAX=122.5,
calib_XMIN=38.0,
calib_YMAX=118.0,
calib_YMIN=6.0,
calib_XOFF=40.0,
calib_YOFF=63.0,
calibration_points=[],
)
@pytest.fixture()
def main_config(eyetrack_camera_config, eyetrack_settings_config):
return EyeTrackConfig(
right_eye=eyetrack_camera_config,
left_eye=eyetrack_camera_config,
settings=eyetrack_settings_config,
eye_display_id=0,
)
@pytest.fixture()
def main_config_v1_params(main_config):
main_config.settings.gui_osc_vrcft_v1 = True
return main_config
@pytest.fixture()
def main_config_v2_params(main_config):
main_config.settings.gui_osc_vrcft_v2 = True
return main_config
@pytest.fixture()
def main_config_native_params(main_config):
main_config.settings.gui_vrc_native = True
return main_config

1207
poetry.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -3,18 +3,19 @@ name = "EyeTrackVR"
version = "0.2"
description = "Opensource, affordable VR eye tracker for VRChat"
authors = ["RedHawk989"]
license = "MIT"
license = "GNU GPL V3"
repository = "https://github.com/EyeTrackVR/EyeTrackVR"
[tool.poetry.dependencies]
python = "~3.10.0"
python = "~3.11.0"
python-osc = "^1.8.0"
requests = "^2.28.1"
opencv-python = "^4.6.0.66"
numpy = "~1.23.5"
pye3d = "^0.3.1.post1"
pysimplegui = "^4.60.4"
pye3d = "^0.3.2"
pysimplegui-4-foss = "^4.6.4.1"
pydantic = "^2.4.2"
scikit-image = "*"
pyserial = "^3.5"
winotify = [
{ version = "^1.1.0", platform = 'win32' }
@ -22,6 +23,9 @@ winotify = [
onnxruntime = "^1.13.1"
colorama = "^0.4.6"
taskipy = "^1.10.4"
pytest = "^8.0.0"
pytest-cov = "^4.1.0"
[tool.poetry.group.dev.dependencies]
black = "^22.10.0"
pyinstaller = "^5.6.2"
@ -30,6 +34,16 @@ flake8 = "^5.0.4"
[tool.taskipy.tasks]
dev = "python eyetrackapp.py"
[tool.black]
line-length = 120
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
[tool.pytest.ini_options]
addopts = "-ra -q"
pythonpath = "."
python_files = [
"test_*.py"
]

View File

@ -2,7 +2,7 @@
; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!
#define MyAppName "EyeTrackVR"
#define MyAppVersion "0.2 BETA 5"
#define MyAppVersion "0.2 BETA 10"
#define MyAppPublisher "EyeTrackVR"
#define MyAppURL "https://redhawk989.github.io/EyeTrackVR/"
#define MyAppExeName "eyetrackapp.exe"
@ -20,11 +20,11 @@ AppSupportURL={#MyAppURL}
AppUpdatesURL={#MyAppURL}
DefaultDirName={autopf}\{#MyAppName}
DisableProgramGroupPage=yes
OutputDir=C:\Users\beaul\OneDrive\Desktop\Output\
OutputDir=C:\Users\Prohurtz\Desktop\Output\
; Uncomment the following line to run in non administrative install mode (install for current user only.)
;PrivilegesRequired=lowest
OutputBaseFilename=EyeTrackVR-Setup
SetupIconFile=C:\Users\beaul\PycharmProjects\EyeTrackVR\EyeTrackApp\Images\logo.ico
SetupIconFile=C:\Users\Prohurtz\PycharmProjects\EyeTrackVR\EyeTrackApp\Images\logo.ico
Compression=lzma/ultra64
SolidCompression=yes
@ -37,8 +37,8 @@ Name: "english"; MessagesFile: "compiler:Default.isl"
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}";
[Files]
Source: "C:\Users\beaul\PycharmProjects\EyeTrackVR\EyeTrackApp\dist\EyeTrackApp\{#MyAppExeName}"; DestDir: "{app}"; Flags: ignoreversion
Source: "C:\Users\beaul\PycharmProjects\EyeTrackVR\EyeTrackApp\dist\EyeTrackApp\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
Source: "C:\Users\Prohurtz\PycharmProjects\EyeTrackVR\EyeTrackApp\dist\{#MyAppExeName}"; DestDir: "{app}"; Flags: ignoreversion
Source: "C:\Users\Prohurtz\PycharmProjects\EyeTrackVR\EyeTrackApp\dist\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
; NOTE: Don't use "Flags: ignoreversion" on any shared system files
[Dirs]

20
tests/__init__.py Normal file
View File

@ -0,0 +1,20 @@
import dataclasses
@dataclasses.dataclass
class EyeInfoMock:
x: int
y: int
blink: float
pupil_dilation: float
avg_velocity: float
class SimpleUDPClientMock:
def __init__(self, osc_address, port):
self.osc_address = osc_address
self.port = port
self.messages = []
def send_message(self, address, value):
self.messages.append((address, value))

View File

@ -0,0 +1,269 @@
from queue import Queue
from time import sleep
from unittest import mock
import pytest
from osc.osc import OSCManager, OSCMessage
from osc.OSCMessage import OSCMessageType
from tests import EyeInfoMock, SimpleUDPClientMock
@pytest.mark.parametrize(
"messages,expected_outcome",
[
(
[
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
0,
EyeInfoMock(
x=0,
y=0,
blink=1,
pupil_dilation=0,
avg_velocity=0,
),
),
),
],
[
("/tracking/eye/EyesClosedAmount", 0.0),
("/tracking/eye/LeftRightVec", [0.0, 0.0, 1.0, 0.0, 0.0, 1.0]),
],
),
(
[
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
1,
EyeInfoMock(
x=0,
y=0,
blink=1,
pupil_dilation=0,
avg_velocity=0,
),
),
),
],
[
("/tracking/eye/EyesClosedAmount", 0.0),
("/tracking/eye/LeftRightVec", [0.0, 0.0, 1.0, 0.0, 0.0, 1.0]),
],
),
],
)
def test_send_command_native_params_single_eye(main_config_native_params, messages, expected_outcome):
with mock.patch("EyeTrackApp.osc.osc.udp_client.SimpleUDPClient", SimpleUDPClientMock):
msg_queue = Queue()
client = OSCManager(
config=main_config_native_params,
osc_message_in_queue=msg_queue,
)
client.start()
for message in messages:
sleep(0.01)
msg_queue.put(message)
client.shutdown()
assert msg_queue.empty()
assert client.osc_sender.client.messages == expected_outcome
@pytest.mark.parametrize(
"eye_data,expected_outcome",
[
(
[
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
0,
EyeInfoMock(
x=0,
y=0,
blink=1,
pupil_dilation=1,
avg_velocity=0,
),
),
),
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
1,
EyeInfoMock(
x=10,
y=5,
blink=0.5,
pupil_dilation=1,
avg_velocity=0,
),
),
),
],
[
("/tracking/eye/EyesClosedAmount", 0.0),
("/tracking/eye/EyesClosedAmount", 0.0),
# we're expecting 621 as left_y here because that's the default value
# before the first state update with real data, but that's ok
# we're gonna be like 10 messages deep before anyone starts playing
# and if they already are, they won't be able to notice
("/tracking/eye/LeftRightVec", [0.0, 621.0, 1.0, 0.0, 0.0, 1.0]),
("/tracking/eye/EyesClosedAmount", 0.5),
("/tracking/eye/EyesClosedAmount", 0.5),
("/tracking/eye/LeftRightVec", [0.0, 5.0, 1.0, 0.0, 0.0, 1.0]),
],
),
# binary blink
(
[
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
0,
EyeInfoMock(
x=0,
y=0,
blink=0,
pupil_dilation=1,
avg_velocity=0,
),
),
),
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
1,
EyeInfoMock(
x=10,
y=5,
blink=0,
pupil_dilation=1,
avg_velocity=0,
),
),
),
],
[
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/LeftRightVec", [0.0, 621.0, 1.0, 0.0, 0.0, 1.0]),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/LeftRightVec", [0.0, 5.0, 1.0, 0.0, 0.0, 1.0]),
],
),
],
)
def test_send_command_native_params_dual_eye(main_config_native_params, eye_data, expected_outcome):
main_config_native_params.eye_display_id = 2
with mock.patch("EyeTrackApp.osc.osc.udp_client.SimpleUDPClient", SimpleUDPClientMock):
msg_queue = Queue()
client = OSCManager(
config=main_config_native_params,
osc_message_in_queue=msg_queue,
)
client.start()
for message in eye_data:
sleep(0.01)
msg_queue.put(message)
client.shutdown()
assert msg_queue.empty()
assert client.osc_sender.client.messages == expected_outcome
@pytest.mark.parametrize(
"eye_data,expected_outcome",
[
(
[
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
0,
EyeInfoMock(
x=0,
y=0,
blink=0,
pupil_dilation=1,
avg_velocity=0,
),
),
),
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
1,
EyeInfoMock(
x=10,
y=5,
blink=0,
pupil_dilation=1,
avg_velocity=0,
),
),
),
],
[
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/LeftRightVec", [0.0, 621.0, 1.0, 0.0, 0.0, 1.0]),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/EyesClosedAmount", 1.0),
("/tracking/eye/LeftRightVec", [0.0, 5.0, 1.0, 0.0, 0.0, 1.0]),
],
),
],
)
def test_send_command_native_params_eye_outer_side_falloff(main_config_native_params, eye_data, expected_outcome):
main_config_native_params.eye_display_id = 2
main_config_native_params.settings.gui_outer_side_falloff = True
with mock.patch("EyeTrackApp.osc.osc.udp_client.SimpleUDPClient", SimpleUDPClientMock):
msg_queue = Queue()
client = OSCManager(
config=main_config_native_params,
osc_message_in_queue=msg_queue,
)
client.start()
for message in eye_data:
msg_queue.put(message)
sleep(1)
client.shutdown()
assert msg_queue.empty()
assert client.osc_sender.client.messages == expected_outcome

274
tests/test_osc_v1_params.py Normal file
View File

@ -0,0 +1,274 @@
from queue import Queue
from time import sleep
from unittest import mock
import pytest
from osc.osc import OSCManager, OSCMessage
from osc.OSCMessage import OSCMessageType
from tests import EyeInfoMock, SimpleUDPClientMock
@pytest.mark.parametrize(
"messages,expected_outcome",
[
(
[
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
0,
EyeInfoMock(
x=0,
y=0,
blink=1,
pupil_dilation=0,
avg_velocity=0,
),
),
),
],
[
("/avatar/parameters/LeftEyeX", 0),
("/avatar/parameters/RightEyeX", 0),
("/avatar/parameters/EyesY", 0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 1.0),
("/avatar/parameters/RightEyeLidExpandedSqueeze", 1.0),
],
),
(
[
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
1,
EyeInfoMock(
x=0,
y=0,
blink=1,
pupil_dilation=0,
avg_velocity=0,
),
),
),
],
[
("/avatar/parameters/LeftEyeX", 0),
("/avatar/parameters/RightEyeX", 0),
("/avatar/parameters/EyesY", 0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 1.0),
("/avatar/parameters/RightEyeLidExpandedSqueeze", 1.0),
],
),
],
)
def test_send_command_v1_params_single_eye(main_config_v1_params, messages, expected_outcome):
with mock.patch("EyeTrackApp.osc.osc.udp_client.SimpleUDPClient", SimpleUDPClientMock):
msg_queue = Queue()
client = OSCManager(
config=main_config_v1_params,
osc_message_in_queue=msg_queue,
)
client.start()
for message in messages:
sleep(0.01)
msg_queue.put(message)
client.shutdown()
assert msg_queue.empty()
assert client.osc_sender.client.messages == expected_outcome
@pytest.mark.parametrize(
"eye_data,expected_outcome",
[
(
[
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
0,
EyeInfoMock(
x=0,
y=0,
blink=1,
pupil_dilation=1,
avg_velocity=0,
),
),
),
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
1,
EyeInfoMock(
x=10,
y=5,
blink=0.5,
pupil_dilation=1,
avg_velocity=0,
),
),
),
],
[
("/avatar/parameters/RightEyeLidExpandedSqueeze", 1.0),
("/avatar/parameters/RightEyeX", 0),
("/avatar/parameters/RightEyeLidExpandedSqueeze", 1.0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 0.5),
("/avatar/parameters/LeftEyeX", 0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 0.5),
("/avatar/parameters/EyesY", 2.5),
],
),
# binary blink
(
[
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
0,
EyeInfoMock(
x=0,
y=0,
blink=0,
pupil_dilation=1,
avg_velocity=0,
),
),
),
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
1,
EyeInfoMock(
x=10,
y=5,
blink=0,
pupil_dilation=1,
avg_velocity=0,
),
),
),
],
[
("/avatar/parameters/RightEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/RightEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/RightEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/RightEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/RightEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/RightEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/RightEyeX", 0),
("/avatar/parameters/RightEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/LeftEyeX", 0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/EyesY", 2.5),
],
),
],
)
def test_send_command_v1_params_dual_eye(main_config_v1_params, eye_data, expected_outcome):
main_config_v1_params.eye_display_id = 2
with mock.patch("EyeTrackApp.osc.osc.udp_client.SimpleUDPClient", SimpleUDPClientMock):
msg_queue = Queue()
client = OSCManager(
config=main_config_v1_params,
osc_message_in_queue=msg_queue,
)
client.start()
for message in eye_data:
sleep(0.01)
msg_queue.put(message)
client.shutdown()
assert msg_queue.empty()
assert client.osc_sender.client.messages == expected_outcome
@pytest.mark.parametrize(
"eye_data,expected_outcome",
[
(
[
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
0,
EyeInfoMock(
x=0,
y=0,
blink=0,
pupil_dilation=1,
avg_velocity=0,
),
),
),
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
1,
EyeInfoMock(
x=10,
y=5,
blink=0,
pupil_dilation=1,
avg_velocity=0,
),
),
),
],
[
("/avatar/parameters/RightEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/RightEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/RightEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/RightEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/RightEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/RightEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/RightEyeX", 0),
("/avatar/parameters/RightEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/RightEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/LeftEyeX", 0),
("/avatar/parameters/LeftEyeLidExpandedSqueeze", 0.0),
("/avatar/parameters/EyesY", 2.5),
],
),
],
)
def test_send_command_v1_params_eye_outer_side_falloff(main_config_v1_params, eye_data, expected_outcome):
main_config_v1_params.eye_display_id = 2
main_config_v1_params.settings.gui_outer_side_falloff = True
with mock.patch("EyeTrackApp.osc.osc.udp_client.SimpleUDPClient", SimpleUDPClientMock):
msg_queue = Queue()
client = OSCManager(
config=main_config_v1_params,
osc_message_in_queue=msg_queue,
)
client.start()
for message in eye_data:
msg_queue.put(message)
sleep(1)
client.shutdown()
assert msg_queue.empty()
assert client.osc_sender.client.messages == expected_outcome

275
tests/test_osc_v2_params.py Normal file
View File

@ -0,0 +1,275 @@
from queue import Queue
from time import sleep
from unittest import mock
import pytest
from osc.osc import OSCManager, OSCMessage
from osc.OSCMessage import OSCMessageType
from tests import EyeInfoMock, SimpleUDPClientMock
@pytest.mark.parametrize(
"messages,expected_outcome",
[
(
[
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
0,
EyeInfoMock(
x=0,
y=0,
blink=1,
pupil_dilation=0,
avg_velocity=0,
),
),
),
],
[
("/avatar/parameters/v2/EyeX", 0),
("/avatar/parameters/v2/EyeY", 0),
("/avatar/parameters/v2/EyeLid", 1.0),
("/avatar/parameters/v2/EyeLid", 1.0),
],
),
(
[
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
1,
EyeInfoMock(
x=0,
y=0,
blink=1,
pupil_dilation=0,
avg_velocity=0,
),
),
),
],
[
("/avatar/parameters/v2/EyeX", 0),
("/avatar/parameters/v2/EyeY", 0),
("/avatar/parameters/v2/EyeLid", 1.0),
("/avatar/parameters/v2/EyeLid", 1.0),
],
),
],
)
def test_send_command_v2_params_single_eye(main_config_v2_params, messages, expected_outcome):
with mock.patch("EyeTrackApp.osc.osc.udp_client.SimpleUDPClient", SimpleUDPClientMock):
msg_queue = Queue()
client = OSCManager(
config=main_config_v2_params,
osc_message_in_queue=msg_queue,
)
client.start()
for message in messages:
sleep(0.01)
msg_queue.put(message)
client.shutdown()
assert msg_queue.empty()
assert client.osc_sender.client.messages == expected_outcome
@pytest.mark.parametrize(
"eye_data,expected_outcome",
[
(
[
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
0,
EyeInfoMock(
x=0,
y=0,
blink=1,
pupil_dilation=1,
avg_velocity=0,
),
),
),
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
1,
EyeInfoMock(
x=10,
y=5,
blink=0.5,
pupil_dilation=1,
avg_velocity=0,
),
),
),
],
[
("/avatar/parameters/v2/EyeLidRight", 1.0),
("/avatar/parameters/v2/EyeRightX", 0),
("/avatar/parameters/v2/EyeRightY", 0),
("/avatar/parameters/v2/EyeLidRight", 1.0),
("/avatar/parameters/v2/EyeLidLeft", 0.5),
("/avatar/parameters/v2/EyeLeftX", 10),
("/avatar/parameters/v2/EyeLeftY", 5),
("/avatar/parameters/v2/EyeLidLeft", 0.5),
],
),
# binary blink
(
[
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
0,
EyeInfoMock(
x=0,
y=0,
blink=0,
pupil_dilation=1,
avg_velocity=0,
),
),
),
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
1,
EyeInfoMock(
x=10,
y=5,
blink=0,
pupil_dilation=1,
avg_velocity=0,
),
),
),
],
[
("/avatar/parameters/v2/EyeLidRight", 0.0),
("/avatar/parameters/v2/EyeLidRight", 0.0),
("/avatar/parameters/v2/EyeLidRight", 0.0),
("/avatar/parameters/v2/EyeLidRight", 0.0),
("/avatar/parameters/v2/EyeLidRight", 0.0),
("/avatar/parameters/v2/EyeLidRight", 0.0),
("/avatar/parameters/v2/EyeRightX", 0),
("/avatar/parameters/v2/EyeRightY", 0),
("/avatar/parameters/v2/EyeLidRight", 0.0),
("/avatar/parameters/v2/EyeLidLeft", 0.0),
("/avatar/parameters/v2/EyeLidLeft", 0.0),
("/avatar/parameters/v2/EyeLidLeft", 0.0),
("/avatar/parameters/v2/EyeLidLeft", 0.0),
("/avatar/parameters/v2/EyeLidLeft", 0.0),
("/avatar/parameters/v2/EyeLidLeft", 0.0),
("/avatar/parameters/v2/EyeLeftX", 10),
("/avatar/parameters/v2/EyeLeftY", 5),
("/avatar/parameters/v2/EyeLidLeft", 0.0),
],
),
],
)
def test_send_command_v2_params_dual_eye(main_config_v2_params, eye_data, expected_outcome):
main_config_v2_params.eye_display_id = 2
with mock.patch("EyeTrackApp.osc.osc.udp_client.SimpleUDPClient", SimpleUDPClientMock):
msg_queue = Queue()
client = OSCManager(
config=main_config_v2_params,
osc_message_in_queue=msg_queue,
)
client.start()
for message in eye_data:
sleep(0.01)
msg_queue.put(message)
client.shutdown()
assert msg_queue.empty()
assert client.osc_sender.client.messages == expected_outcome
@pytest.mark.parametrize(
"eye_data,expected_outcome",
[
(
[
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
0,
EyeInfoMock(
x=0,
y=0,
blink=0,
pupil_dilation=1,
avg_velocity=0,
),
),
),
OSCMessage(
type=OSCMessageType.EYE_INFO,
data=(
1,
EyeInfoMock(
x=10,
y=5,
blink=0,
pupil_dilation=1,
avg_velocity=0,
),
),
),
],
[
("/avatar/parameters/v2/EyeLidRight", 0.0),
("/avatar/parameters/v2/EyeLidRight", 0.0),
("/avatar/parameters/v2/EyeLidRight", 0.0),
("/avatar/parameters/v2/EyeLidRight", 0.0),
("/avatar/parameters/v2/EyeLidRight", 0.0),
("/avatar/parameters/v2/EyeLidRight", 0.0),
("/avatar/parameters/v2/EyeRightX", 0),
("/avatar/parameters/v2/EyeRightY", 0),
("/avatar/parameters/v2/EyeLidRight", 0.0),
("/avatar/parameters/v2/EyeLidLeft", 0.0),
("/avatar/parameters/v2/EyeLidLeft", 0.0),
("/avatar/parameters/v2/EyeLidLeft", 0.0),
("/avatar/parameters/v2/EyeLidLeft", 0.0),
("/avatar/parameters/v2/EyeLidLeft", 0.0),
("/avatar/parameters/v2/EyeLidLeft", 0.0),
("/avatar/parameters/v2/EyeLidRight", 0.0),
("/avatar/parameters/v2/EyeLidLeft", 0.0),
("/avatar/parameters/v2/EyeLeftX", 10),
("/avatar/parameters/v2/EyeLeftY", 5),
("/avatar/parameters/v2/EyeLidLeft", 0.0),
],
),
],
)
def test_send_command_v2_params_eye_outer_side_falloff(main_config_v2_params, eye_data, expected_outcome):
main_config_v2_params.eye_display_id = 2
main_config_v2_params.settings.gui_outer_side_falloff = True
with mock.patch("EyeTrackApp.osc.osc.udp_client.SimpleUDPClient", SimpleUDPClientMock):
msg_queue = Queue()
client = OSCManager(
config=main_config_v2_params,
osc_message_in_queue=msg_queue,
)
client.start()
for message in eye_data:
msg_queue.put(message)
sleep(1)
client.shutdown()
assert msg_queue.empty()
assert client.osc_sender.client.messages == expected_outcome