cleanup, rename things

This commit is contained in:
Prohurtz committed 2023-06-04 08:01:23 -07:00
1 parent b7109f2dab
commit 4fb705048e
13 files changed
+91 -1629

No files matched your search

-325
View File
@@ -1,325 +0,0 @@
import os
import json
os.environ["OMP_NUM_THREADS"] = "1"
import onnxruntime as ort
import time
import PySimpleGUI as sg
import cv2
import numpy as np
from pythonosc import udp_client
from torchvision.transforms.functional import to_grayscale
import PIL.Image as Image
from torchvision import transforms
from threading import Thread
from one_euro_filter import OneEuroFilter
class WebcamVideoStream:
def __init__(self, src=0):
# initialize the video camera stream and read the first frame
# from the stream
self.stream = cv2.VideoCapture(src)
(self.grabbed, self.frame) = self.stream.read()
# initialize the variable used to indicate if the thread should
# be stopped
self.stopped = False
def start(self):
# start the thread to read frames from the video stream
Thread(target=self.update, args=()).start()
return self
def update(self):
# keep looping infinitely until the thread is stopped
while True:
# if the thread indicator variable is set, stop the thread
if self.stopped:
return
# otherwise, read the next frame from the stream
(self.grabbed, self.frame) = self.stream.read()
def read(self):
# return the frame most recently read
return self.frame
def stop(self):
# indicate that the thread should be stopped
self.stopped = True
class Calibration(object):
def __init__(self, filename):
self.CALIBRATION_FILE = filename
self._load_calibration(self.CALIBRATION_FILE)
def update_calib(self, filename):
if self._last_update != os.stat(self.CALIBRATION_FILE).st_mtime:
print("Change detected, reloading calibration file")
self._load_calibration(filename)
return True
return False
def _load_calibration(self, filename):
with open(filename) as user_file: # Open and load the file into a dict
self.calib = json.load(user_file)
self._last_update = os.fstat(user_file.fileno()).st_mtime
self.jsonminmax = [
[self.calib["cheekPuffLeft"]["min"],self.calib["cheekPuffLeft"]["max"]], # CheekPuff
[self.calib["cheekPuffRight"]["min"],self.calib["cheekPuffRight"]["max"]], # CheekPuff
[self.calib["cheekSuckLeft"]["min"],self.calib["cheekSuckLeft"]["max"]], # CheekPuff
[self.calib["cheekSuckRight"]["min"],self.calib["cheekSuckRight"]["max"]], # CheekPuff
[self.calib["jawOpen"]["min"],self.calib["jawOpen"]["max"]], # jawOpen
[self.calib["jawForward"]["min"],self.calib["jawForward"]["max"]], # jawForward
[self.calib["jawLeft"]["min"],self.calib["jawLeft"]["max"]], # jawLeft
[self.calib["jawRight"]["min"],self.calib["jawRight"]["max"]], # jawRight
[self.calib["noseSneerLeft"]["min"],self.calib["noseSneerLeft"]["max"]], # noseSneerLeft
[self.calib["noseSneerRight"]["min"],self.calib["noseSneerRight"]["max"]], # noseSneerRight
[self.calib["mouthFunnel"]["min"],self.calib["mouthFunnel"]["max"]], # mouthFunnel
[self.calib["mouthPucker"]["min"],self.calib["mouthPucker"]["max"]], # mouthPucker
[self.calib["mouthLeft"]["min"],self.calib["mouthLeft"]["max"]], # mouthLeft
[self.calib["mouthRight"]["min"],self.calib["mouthRight"]["max"]], # mouthRight
[self.calib["mouthRollUpper"]["min"],self.calib["mouthRollUpper"]["max"]], # mouthRollUpper
[self.calib["mouthRollLower"]["min"],self.calib["mouthRollLower"]["max"]], # mouthRollLower
[self.calib["mouthShrugUpper"]["min"],self.calib["mouthShrugUpper"]["max"]], # mouthShrugUpper
[self.calib["mouthShrugLower"]["min"],self.calib["mouthShrugLower"]["max"]], # mouthShrugLower
[self.calib["mouthClose"]["min"],self.calib["mouthClose"]["max"]], # mouthClose
[self.calib["mouthSmileLeft"]["min"],self.calib["mouthSmileLeft"]["max"]], # mouthSmileLeft
[self.calib["mouthSmileRight"]["min"],self.calib["mouthSmileRight"]["max"]], # mouthSmileRight
[self.calib["mouthFrownLeft"]["min"],self.calib["mouthFrownLeft"]["max"]], # mouthFrownLeft
[self.calib["mouthSmileRight"]["min"],self.calib["mouthSmileRight"]["max"]], # mouthFrownRight
[self.calib["mouthDimpleLeft"]["min"],self.calib["mouthDimpleLeft"]["max"]], # mouthDimpleLeft
[self.calib["mouthDimpleRight"]["min"],self.calib["mouthDimpleRight"]["max"]], # mouthDimpleRight
[self.calib["mouthUpperUpLeft"]["min"],self.calib["mouthUpperUpLeft"]["max"]], # mouthUpperUpLeft
[self.calib["mouthUpperUpRight"]["min"],self.calib["mouthUpperUpRight"]["max"]], # mouthUpperUpRight
[self.calib["mouthLowerDownLeft"]["min"],self.calib["mouthLowerDownLeft"]["max"]], # mouthLowerDownLeft
[self.calib["mouthLowerDownRight"]["min"],self.calib["mouthLowerDownRight"]["max"]], # mouthLowerDownRight
[self.calib["mouthPressLeft"]["min"],self.calib["mouthPressLeft"]["max"]], # mouthPressLeft
[self.calib["mouthPressRight"]["min"],self.calib["mouthPressRight"]["max"]], # mouthPressRight
[self.calib["mouthStretchLeft"]["min"],self.calib["mouthStretchLeft"]["max"]], # mouthStretchLeft
[self.calib["mouthStretchRight"]["min"],self.calib["mouthStretchRight"]["max"]], # mouthStretchRight
[self.calib["tongueOut"]["min"],self.calib["tongueOut"]["max"]], # tongueOut
[self.calib["tongueUp"]["min"],self.calib["tongueUp"]["max"]], # tongueOut
[self.calib["tongueDown"]["min"],self.calib["tongueDown"]["max"]], # tongueOut
[self.calib["tongueLeft"]["min"],self.calib["tongueLeft"]["max"]], # tongueOut
[self.calib["tongueRight"]["min"],self.calib["tongueRight"]["max"]], # tongueOut
[self.calib["tongueRoll"]["min"],self.calib["tongueRoll"]["max"]], # tongueOut
[self.calib["tongueBendDown"]["min"],self.calib["tongueBendDown"]["max"]], # tongueOut
[self.calib["tongueCurlUp"]["min"],self.calib["tongueCurlUp"]["max"]], # tongueOut
[self.calib["tongueSquish"]["min"],self.calib["tongueSquish"]["max"]], # tongueOut
[self.calib["tongueFlat"]["min"],self.calib["tongueFlat"]["max"]], # tongueOut
[self.calib["tongueTwistLeft"]["min"],self.calib["tongueTwistLeft"]["max"]], # tongueOut
[self.calib["tongueTwistRight"]["min"],self.calib["tongueTwistRight"]["max"]], # tongueOut
]
return self.jsonminmax
def makeminmaxarray(amount):
stored_values = []
for i in range(amount):
stored_values.append([0,0])
return stored_values
def minmax(stored_values, value, passthrough = False): # Set passthrough to true if you don't want to set the stored values wtih the function
if passthrough == False: # Sets and updates the min and max value
if stored_values[0] == 0 and stored_values[1] == 0:
stored_values[0] = value
stored_values[1] = value
array = (0, max(min(value, 1), 0), 1)
else: # if value is greater than the max or less than the min, set it.
if value < stored_values[0]: stored_values[0] = value
if value > stored_values[1]: stored_values[1] = value
array = (stored_values[0], max(min(value, 1), 0), stored_values[1])
else:
array = stored_values # Formats the min max value without changing the values
array = (stored_values[0], max(min(value, 1), 0), stored_values[1])
return array
def normalize_value(array):
normalized_value = ((array[1] - array[0]) / (array[2] - array[0]))
return normalized_value
"""
Demo program that allows a user to type in a webcam url or number and displays it using OpenCV
"""
# ---------------- Create Form ----------------
sg.theme('DarkAmber') # Add a touch of color
# All the stuff inside your window.
layout = [
[sg.Image(key = '-IMAGE-')],
[sg.Text('Enter Webcam URL or Number (Defualts to 0)'), sg.Input(key = '-URL-', size = (30, 1))],
[sg.Text('Enter Onnx model name (Defualts to EFV2300K45E100P2.onnx)'), sg.Input(key = '-MODEL-', size = (30, 1))],
[sg.Text('OSC Location Address'), sg.Input(key = '-LOC-', size = (30, 1))],
[sg.Text('Output Mutiplier (defualts to 1. Please use 100 if you are using the unity demo.)'), sg.Input(key = '-MULT-', size = (30, 1))],
[sg.Text('Enter OSC IP (Defualts to 127.0.0.1)'), sg.Input(key = '-OSC-', size = (30, 1))],
[sg.Text('Enter OSC Port (Defualts to 8888)'), sg.Input(key = '-PORT-', size = (30, 1))],
[sg.Text('Enter Calibration file name (Defaults to calib.json)'), sg.Input(key = '-JSON_FILE-', size = (30, 1))],
[sg.Text('Press Ok to start the webcam')],
[sg.Checkbox('Flip 180', key = '-FLIP180-')],
[sg.Checkbox('Flip 90 Left', key = '-FLIP90-')],
[sg.Checkbox('Flip 90 Right', key = '-FLIP90R-')],
[sg.Checkbox('No Calibration', key = '-CAL-')],
[sg.Checkbox('Use GPU (DirectML)', key = '-GPU-')],
[sg.Button('Start'), sg.Button('Stop'), sg.Button('Draw ROI')],
]
# Create the Window
window = sg.Window('Project BabbleV1.0.3', layout, location = (800, 400))
event, values = window.read(timeout = 20)
calibjson = values['-MODEL-']
if calibjson == '':
calibjson = 'calib.json'
calibration = Calibration(calibjson)
# ---------------- Event Loop ----------------
while True:
event, values = window.read(timeout = 20)
OSCip= values['-OSC-'] #VR Chat OSC ip
if OSCip == '':
OSCip="127.0.0.1"
OSCport= values['-PORT-'] #VR Chat OSC port
if OSCport == '':
OSCport = 8888
else:
OSCport = int(OSCport)
multi = values['-MULT-']
if multi == '':
multi = 1
else:
multi = int(multi)
client = udp_client.SimpleUDPClient(OSCip, OSCport)
model = values['-MODEL-']
if model == '':
model = 'EFV2300K45E100P2.onnx'
if calibjson == '':
calibjson = 'calib.json'
usegpu = values['-GPU-']
calibration.update_calib(calibjson) # Checks and updates values of the json file
stored_values = calibration.jsonminmax
flip180 = values['-FLIP180-']
flip90 = values['-FLIP90-']
flip90r = values['-FLIP90R-']
location = values['-LOC-']
ROI = None
if event == sg.WIN_CLOSED or event == 'Stop':
break
if event == 'Start':
opts = ort.SessionOptions()
opts.intra_op_num_threads = 1
opts.inter_op_num_threads = 1
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_EXTENDED
if not usegpu:
sess = ort.InferenceSession(model, opts, providers=['CPUExecutionProvider'])
if usegpu:
sess = ort.InferenceSession(model, opts, providers=['DmlExecutionProvider'])
input_name = sess.get_inputs()[0].name
output_name = sess.get_outputs()[0].name
url = values['-URL-']
if url == '':
url = 0
elif url in '0123456789':
url = int(url)
steamer = WebcamVideoStream(url).start()
min_cutoff = 15.5004
beta = 0.62
noisy_point = np.array([45])
filter = OneEuroFilter(
noisy_point,
min_cutoff=min_cutoff,
beta=beta
)
while True:
frame = steamer.read()
if event == 'Draw ROI':
ROI = cv2.selectROI(frame)
cv2.destroyWindow("ROI selector")
cv2.waitKey(1)
if ROI != None:
frame = frame[int(ROI[1]):int(ROI[1]+ROI[3]), int(ROI[0]):int(ROI[0]+ROI[2])]
if flip180:
frame = cv2.flip(frame, 0)
if flip90:
frame = cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE)
if flip90r:
frame = cv2.rotate(frame, cv2.ROTATE_90_COUNTERCLOCKWISE)
frame2 = frame
#frame = cv2.flip(frame, 1)
calibration.update_calib(calibjson) # Checks and updates values of the json file
stored_values = calibration.jsonminmax
frame = cv2.resize(frame, (256, 256))
#make it pil
frame = Image.fromarray(frame)
#make it grayscale
frame = to_grayscale(frame)
#make it a tensor
frame = transforms.ToTensor()(frame)
#make it a batch
frame = frame.unsqueeze(0)
#make it a numpy array
frame = frame.numpy()
#print te amout of outputs that are zero
out = sess.run([output_name], {input_name: frame})
end = time.time()
output = out[0]
output = output[0]
output = filter(output)
if values['-CAL-'] == False:
array = []
for i in range(len(output)):
yeah = minmax(stored_values[i], output[i], True) # Enabled passthrough to allow changes to happen with calib json
value = normalize_value(yeah)
array.append(value)
else:
array = output
for i in range(len(output)): # Clip values between 0 - 1
output[i] = max(min(output[i], 1), 0)
client.send_message(location + "/cheekPuffLeft", array[0] * multi)
client.send_message(location + "/cheekPuffRight", array[1] * multi)
client.send_message(location + "/cheekSuckLeft", array[2] * multi)
client.send_message(location + "/cheekSuckRight", array[3] * multi)
client.send_message(location + "/jawOpen", array[4] * multi)
client.send_message(location + "/jawForward", array[5] * multi)
client.send_message(location + "/jawLeft", array[6] * multi)
client.send_message(location + "/jawRight", array[7] * multi)
client.send_message(location + "/noseSneerLeft", array[8] * multi)
client.send_message(location + "/noseSneerRight", array[9] * multi)
client.send_message(location + "/mouthFunnel", array[10] * multi)
client.send_message(location + "/mouthPucker", array[11] * multi)
client.send_message(location + "/mouthLeft", array[12] * multi)
client.send_message(location + "/mouthRight", array[13] * multi)
client.send_message(location + "/mouthRollUpper", array[14] * multi)
client.send_message(location + "/mouthRollLower", array[15] * multi)
client.send_message(location + "/mouthShrugUpper", array[16] * multi)
client.send_message(location + "/mouthShrugLower", array[17] * multi)
client.send_message(location + "/mouthClose", output[18] * multi)
client.send_message(location + "/mouthSmileLeft", array[19] * multi)
client.send_message(location + "/mouthSmileRight", array[20] * multi)
client.send_message(location + "/mouthFrownLeft", array[21] * multi)
client.send_message(location + "/mouthFrownRight", array[22] * multi)
client.send_message(location + "/mouthDimpleLeft", array[23] * multi)
client.send_message(location + "/mouthDimpleRight", array[24] * multi)
client.send_message(location + "/mouthUpperUpLeft", array[25] * multi)
client.send_message(location + "/mouthUpperUpRight", array[26] * multi)
client.send_message(location + "/mouthLowerDownLeft", array[27] * multi)
client.send_message(location + "/mouthLowerDownRight", array[28] * multi)
client.send_message(location + "/mouthPressLeft", array[29] * multi)
client.send_message(location + "/mouthPressRight", array[30] * multi)
client.send_message(location + "/mouthStretchLeft", array[31] * multi)
client.send_message(location + "/mouthStretchRight", array[32] * multi)
client.send_message(location + "/tongueOut", array[33] * multi)
client.send_message(location + "/tongueUp", array[34] * multi)
client.send_message(location + "/tongueDown", array[35] * multi)
client.send_message(location + "/tongueLeft", array[36] * multi)
client.send_message(location + "/tongueRight", array[37] * multi)
client.send_message(location + "/tongueRoll", array[38] * multi)
client.send_message(location + "/tongueBendDown", array[39] * multi)
client.send_message(location + "/tongueCurlUp", array[40] * multi)
client.send_message(location + "/tongueSquish", array[41] * multi)
client.send_message(location + "/tongueFlat", array[42] * multi)
client.send_message(location + "/tongueTwistLeft", array[43] * multi)
client.send_message(location + "/tongueTwistRight", array[44] * multi)
frame2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
imgbytes = cv2.imencode('.png', frame2)[1].tobytes() # ditto
window['-IMAGE-'].update(data=imgbytes)
event, values = window.read(timeout = 20)
if event == sg.WIN_CLOSED or event == 'Stop':
break
steamer.stop()
window.close()
File diff suppressed because it is too large. Load diff
+10 -56
View File
@@ -15,7 +15,7 @@ from utils.misc_utils import PlaySound, SND_FILENAME, SND_ASYNC
import importlib
from osc import Tab
from osc_calibrate_filter import *
from eye import CamInfo, EyeInfoOrigin
from tab import CamInfo, CamInfoOrigin
from babble_model_loader import *
import os
os.environ["OMP_NUM_THREADS"] = "1"
@@ -36,7 +36,7 @@ async def delayed_setting_change(setting, value):
class EyeProcessor:
class BabbleProcessor:
def __init__(
self,
config: "BabbleCameraConfig",
@@ -46,25 +46,19 @@ class EyeProcessor:
capture_event: "threading.Event",
capture_queue_incoming: "queue.Queue",
image_queue_outgoing: "queue.Queue",
eye_id,
cam_id,
):
self.main_config = BabbleSettingsConfig
self.config = config
self.settings = settings
self.eye_id = eye_id
self.cam_id = cam_id
self.config_class = fullconfig
# Cross-thread communication management
self.capture_queue_incoming = capture_queue_incoming
self.image_queue_outgoing = image_queue_outgoing
self.cancellation_event = cancellation_event
self.capture_event = capture_event
self.eye_id = eye_id
# Cross algo state
self.lkg_projected_sphere = None
self.xc = 20
self.yc = 20
self.cc_radius = 40
self.cam_id = cam_id
# Image state
self.previous_image = None
@@ -72,42 +66,15 @@ class EyeProcessor:
self.current_image_gray = None
self.current_frame_number = None
self.current_fps = None
self.threshold_image = None
self.thresh = None
# Calibration Values
self.xoff = 1
self.yoff = 1
# Keep large in order to recenter correctly
self.calibration_frame_counter = None
self.eyeoffx = 1
self.xmax = -69420
self.xmin = 69420
self.ymax = -69420
self.ymin = 69420
self.blink_clear = False
self.cct = 200
self.calibration_frame_counter = None
self.cccs = False
self.ts = 10
self.previous_rotation = self.config.rotation_angle
self.roi_include_set = {"rotation_angle", "roi_window_x", "roi_window_y"}
self.out_y = 0.0
self.out_x = 0.0
self.rawx = 0.0
self.rawy = 0.0
self.eyeopen = 0.7
#blink
self.max_ints = []
self.max_int = 0
self.min_int = 4000000000000
self.frames = 0
self.prev_x = None
self.prev_y = None
self.bd_blink = False
self.current_algo = EyeInfoOrigin.MODEL
self.current_algo = CamInfoOrigin.MODEL
self.model = self.settings.gui_model_file
self.use_gpu = self.settings.gui_use_gpu
self.output = []
@@ -141,7 +108,7 @@ class EyeProcessor:
beta=beta
)
def output_images_and_update(self, threshold_image, output_information: CamInfo):
def output_images_and_update(self, output_information: CamInfo):
try:
image_stack = np.concatenate(
(
@@ -216,22 +183,9 @@ class EyeProcessor:
pass
def UPDATE(self):
self.output_images_and_update(self.thresh, CamInfo(self.current_algo, self.out_x, self.out_y, 0, self.eyeopen))
def run(self):
# Run the following somewhere
# self.daddy = External_Run_DADDY()
f = True
while True:
# f = True
# Check to make sure we haven't been requested to close
if self.cancellation_event.is_set():
print("\033[94m[INFO] Exiting Tracking thread\033[0m")
@@ -277,5 +231,5 @@ class EyeProcessor:
#else:
# pass
#print(self.output)
self.output_images_and_update(self.thresh, CamInfo(self.current_algo, self.output))
self.output_images_and_update(CamInfo(self.current_algo, self.output))
+41 -47
View File
@@ -1,5 +1,4 @@
import os
import os
import PySimpleGUI as sg
import queue
import requests
@@ -7,7 +6,7 @@ import threading
from babble_model_loader import *
from camera_widget import CameraWidget
from config import BabbleConfig
from eye import CamInfo, Tab
from tab import CamInfo, Tab
from osc import VRChatOSCReceiver, VRChatOSC
from general_settings_widget import SettingsWidget
from algo_settings_widget import AlgoSettingsWidget
@@ -22,15 +21,11 @@ os.system('color') # init ANSI color
# https://github.com/opencv/opencv/issues/17687
os.environ["OPENCV_VIDEOIO_MSMF_ENABLE_HW_TRANSFORMS"] = "0"
WINDOW_NAME = "EyeTrackApp"
RIGHT_EYE_NAME = "-RIGHTEYEWIDGET-"
LEFT_EYE_NAME = "-LEFTEYEWIDGET-"
WINDOW_NAME = "Babble sApp"
CAM_NAME = "-CAMWIDGET-"
SETTINGS_NAME = "-SETTINGSWIDGET-"
ALGO_SETTINGS_NAME = "-ALGOSETTINGSWIDGET-"
LEFT_EYE_RADIO_NAME = "-LEFTEYERADIO-"
RIGHT_EYE_RADIO_NAME = "-RIGHTEYERADIO-"
BOTH_EYE_RADIO_NAME = "-BOTHEYERADIO-"
CAM_RADIO_NAME = "-CAMRADIO-"
SETTINGS_RADIO_NAME = "-SETTINGSRADIO-"
ALGO_SETTINGS_RADIO_NAME = "-ALGOSETTINGSRADIO-"
@@ -90,7 +85,7 @@ def main():
# start worker threads
osc_thread.start()
eyes = [
cams = [
CameraWidget(Tab.CAM, config, osc_queue),
]
@@ -103,63 +98,62 @@ def main():
[
sg.Radio(
"Cam",
"EYESELECTRADIO",
"TABSELECTRADIO",
background_color="#292929",
default=(config.eye_display_id == Tab.CAM),
key=RIGHT_EYE_RADIO_NAME,
default=(config.cam_display_id == Tab.CAM),
key=CAM_RADIO_NAME,
),
sg.Radio(
"Settings",
"EYESELECTRADIO",
"TABSELECTRADIO",
background_color="#292929",
default=(config.eye_display_id == Tab.SETTINGS),
default=(config.cam_display_id == Tab.SETTINGS),
key=SETTINGS_RADIO_NAME,
),
sg.Radio(
"Algo Settings",
"EYESELECTRADIO",
"TABSELECTRADIO",
background_color="#292929",
default=(config.eye_display_id == Tab.ALGOSETTINGS),
default=(config.cam_display_id == Tab.ALGOSETTINGS),
key=ALGO_SETTINGS_RADIO_NAME,
),
],
[
sg.Column(
eyes[0].widget_layout,
cams[0].widget_layout,
vertical_alignment="top",
key=RIGHT_EYE_NAME,
visible=(config.eye_display_id in [Tab.CAM]),
key=CAM_NAME,
visible=(config.cam_display_id in [Tab.CAM]),
background_color="#424042",
),
sg.Column(
settings[0].widget_layout,
vertical_alignment="top",
key=SETTINGS_NAME,
visible=(config.eye_display_id in [Tab.SETTINGS]),
visible=(config.cam_display_id in [Tab.SETTINGS]),
background_color="#424042",
),
sg.Column(
settings[1].widget_layout,
vertical_alignment="top",
key=ALGO_SETTINGS_NAME,
visible=(config.eye_display_id in [Tab.ALGOSETTINGS]),
visible=(config.cam_display_id in [Tab.ALGOSETTINGS]),
background_color="#424042",
),
],
]
if config.eye_display_id in [Tab.CAM]:
eyes[0].start()
if config.eye_display_id in [Tab.SETTINGS]:
if config.cam_display_id in [Tab.CAM]:
cams[0].start()
if config.cam_display_id in [Tab.SETTINGS]:
settings[0].start()
if config.eye_display_id in [Tab.ALGOSETTINGS]:
if config.cam_display_id in [Tab.ALGOSETTINGS]:
settings[1].start()
# self.main_config.eye_display_id
# the eye's needs to be running before it is passed to the OSC
# the cam 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 = VRChatOSCReceiver(cancellation_event, config, cams)
osc_receiver_thread = threading.Thread(target=osc_receiver.run)
osc_receiver_thread.start()
ROSC = True
@@ -176,8 +170,8 @@ def main():
# 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()
for cam in cams: #yes we only have one cam page but im just gonna leave this incase
cam.stop()
cancellation_event.set()
# shut down worker threads
osc_thread.join()
@@ -188,46 +182,46 @@ def main():
if ROSC:
osc_receiver.shutdown()
osc_receiver_thread.join()
print("\033[94m[INFO] Exiting EyeTrackApp\033[0m")
print("\033[94m[INFO] Exiting BabbleApp\033[0m")
return
if values[RIGHT_EYE_RADIO_NAME] and config.eye_display_id != Tab.CAM:
eyes[0].start()
if values[CAM_RADIO_NAME] and config.cam_display_id != Tab.CAM:
cams[0].start()
settings[0].stop()
settings[1].stop()
window[RIGHT_EYE_NAME].update(visible=True)
window[CAM_NAME].update(visible=True)
window[SETTINGS_NAME].update(visible=False)
window[ALGO_SETTINGS_NAME].update(visible=False)
config.eye_display_id = Tab.CAM
config.cam_display_id = Tab.CAM
config.save()
elif values[SETTINGS_RADIO_NAME] and config.eye_display_id != Tab.SETTINGS:
eyes[0].stop()
elif values[SETTINGS_RADIO_NAME] and config.cam_display_id != Tab.SETTINGS:
cams[0].stop()
settings[1].stop()
settings[0].start()
window[RIGHT_EYE_NAME].update(visible=False)
window[CAM_NAME].update(visible=False)
window[SETTINGS_NAME].update(visible=True)
window[ALGO_SETTINGS_NAME].update(visible=False)
config.eye_display_id = Tab.SETTINGS
config.cam_display_id = Tab.SETTINGS
config.save()
elif values[ALGO_SETTINGS_RADIO_NAME] and config.eye_display_id != Tab.ALGOSETTINGS:
eyes[0].stop()
elif values[ALGO_SETTINGS_RADIO_NAME] and config.cam_display_id != Tab.ALGOSETTINGS:
cams[0].stop()
settings[0].stop()
settings[1].start()
window[RIGHT_EYE_NAME].update(visible=False)
window[CAM_NAME].update(visible=False)
window[SETTINGS_NAME].update(visible=False)
window[ALGO_SETTINGS_NAME].update(visible=True)
config.eye_display_id = Tab.ALGOSETTINGS
config.cam_display_id = Tab.ALGOSETTINGS
config.save()
# Otherwise, render all
for eye in eyes:
if eye.started():
eye.render(window, event, values)
for cam in cams:
if cam.started():
cam.render(window, event, values)
for setting in settings:
if setting.started():
setting.render(window, event, values)
+11 -12
View File
@@ -3,7 +3,7 @@ from config import BabbleConfig
from config import BabbleSettingsConfig
from collections import deque
from threading import Event, Thread
from babble_processor import EyeProcessor, EyeInfoOrigin
from babble_processor import BabbleProcessor, CamInfoOrigin
from enum import Enum
from queue import Queue, Empty
from camera import Camera, CameraState
@@ -30,7 +30,6 @@ class CameraWidget:
self.gui_output_graph = f"-OUTPUTGRAPH{widget_id}-"
self.gui_restart_calibration = f"-RESTARTCALIBRATION{widget_id}-"
self.gui_stop_calibration = f"-STOPCALIBRATION{widget_id}-"
self.gui_recenter_eyes = f"-RECENTEREYES{widget_id}-"
self.gui_mode_readout = f"-APPMODE{widget_id}-"
self.gui_roi_message = f"-ROIMESSAGE{widget_id}-"
self.gui_vertical_flip = f"-VERTICALFLIP{widget_id}-"
@@ -38,11 +37,11 @@ class CameraWidget:
self.use_calibration = f"-USECALIBRATION{widget_id}-"
self.osc_queue = osc_queue
self.main_config = main_config
self.eye_id = widget_id
self.cam_id = widget_id
self.settings_config = main_config.settings
self.config = main_config.cam
self.settings = main_config.settings
if self.eye_id == Tab.CAM:
if self.cam_id == Tab.CAM:
self.config = main_config.cam
else:
raise RuntimeError("\033[91m[WARN] Improper tab value!\033[0m")
@@ -56,7 +55,7 @@ class CameraWidget:
self.image_queue = Queue()
self.ransac = EyeProcessor(
self.ransac = BabbleProcessor(
self.config,
self.settings_config,
self.main_config,
@@ -64,7 +63,7 @@ class CameraWidget:
self.capture_event,
self.capture_queue,
self.image_queue,
self.eye_id,
self.cam_id,
)
self.camera_status_queue = Queue()
@@ -152,8 +151,8 @@ class CameraWidget:
sg.Button("Save and Restart Tracking", key=self.gui_save_tracking_button, button_color='#539e8a'),
],
[
sg.Button("Tracking Mode", key=self.gui_tracking_button, button_color='#539e8a', tooltip = "Go here to track your eye.",),
sg.Button("Cropping Mode", key=self.gui_roi_button, button_color='#539e8a', tooltip = "Go here to crop out your eye.",),
sg.Button("Tracking Mode", key=self.gui_tracking_button, button_color='#539e8a', tooltip = "Go here to track your mouth.",),
sg.Button("Cropping Mode", key=self.gui_roi_button, button_color='#539e8a', tooltip = "Go here to crop out your mouth.",),
],
[
sg.Column(self.tracking_layout, key=self.gui_tracking_layout, background_color='#424042'),
@@ -301,7 +300,7 @@ class CameraWidget:
elif self.camera.camera_status == CameraState.DISCONNECTED:
window[self.gui_mode_readout].update("Camera Reconnecting...")
elif needs_roi_set:
window[self.gui_mode_readout].update("Awaiting Eye Crop")
window[self.gui_mode_readout].update("Awaiting Mouth Crop")
elif self.ransac.calibration_frame_counter != None:
window[self.gui_mode_readout].update("Calibration")
else:
@@ -335,13 +334,13 @@ class CameraWidget:
return
try:
window[self.gui_roi_message].update(visible=False)
(maybe_image, eye_info) = self.image_queue.get(block=False)
(maybe_image, cam_info) = self.image_queue.get(block=False)
imgbytes = cv2.imencode(".ppm", maybe_image)[1].tobytes()
window[self.gui_tracking_image].update(data=imgbytes)
# Relay information to OSC
if eye_info.info_type != EyeInfoOrigin.FAILURE:
self.osc_queue.put((self.eye_id, eye_info))
if cam_info.info_type != CamInfoOrigin.FAILURE:
self.osc_queue.put((self.cam_id, cam_info))
except Empty:
pass
+2 -2
View File
@@ -2,7 +2,7 @@ import json
import os.path
import shutil
from eye import Tab
from tab import Tab
from pydantic import BaseModel
from typing import Union
@@ -41,7 +41,7 @@ class BabbleConfig(BaseModel):
version: int = 1
cam: BabbleCameraConfig = BabbleCameraConfig()
settings: BabbleSettingsConfig = BabbleSettingsConfig()
eye_display_id: Tab = Tab.CAM
cam_display_id: Tab = Tab.CAM
@staticmethod
def load():
+2 -28
View File
@@ -6,8 +6,7 @@ from typing import Any, ClassVar, Dict, List, Optional, TYPE_CHECKING, Tuple, Ty
__all__ = (
'Enum',
# 'EyeId',
'EyeLR',
'CamLR',
)
if TYPE_CHECKING:
@@ -148,29 +147,4 @@ def try_enum(cls: Type[E], val: Any) -> E:
# 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
def __str__(self) -> str:
return self.name
def __int__(self) -> int:
return self.value
# https://github.com/Rapptz/discord.py/blob/f7e97954950ffb0e34238d70813454caa6f1a3ae/discord/enums.py
+9 -16
View File
@@ -72,7 +72,7 @@ class VRChatOSC:
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 = Tab.CAM
self.cam = Tab.CAM
def run(self):
start = time.time()
@@ -82,19 +82,19 @@ class VRChatOSC:
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)
(self.cam_id, cam_info) = self.msg_queue.get(block=True, timeout=0.1)
except:
continue
output_osc(eye_info.output, self)
output_osc(cam_info.output, self)
class VRChatOSCReceiver:
def __init__(self, cancellation_event: threading.Event, main_config: BabbleConfig, eyes: []):
def __init__(self, cancellation_event: threading.Event, main_config: BabbleConfig, cams: []):
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
self.cams = cams # 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:
@@ -107,25 +107,18 @@ class VRChatOSCReceiver:
except:
pass
def recenter_eyes(self, address, osc_value):
def recalibrate_mouth(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.calibration_frame_counter = 300
for cam in self.cams:
cam.ransac.calibration_frame_counter = 300
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)
self.dispatcher.map(self.config.gui_osc_recalibrate_address, self.recalibrate_cams)
# start the server
print("\033[92m[INFO] VRChatOSCReceiver serving on {}\033[0m".format(self.server.server_address))
self.server.serve_forever()
+1 -1
View File
@@ -3,7 +3,7 @@ import numpy as np
from enum import IntEnum
from utils.misc_utils import PlaySound, SND_FILENAME, SND_ASYNC
class EyeId(IntEnum):
class CamId(IntEnum):
RIGHT = 0
LEFT = 1
BOTH = 2
+2 -2
View File
@@ -7,12 +7,12 @@ class Tab(IntEnum):
ALGOSETTINGS = 2
class EyeInfoOrigin(Enum):
class CamInfoOrigin(Enum):
MODEL = 1
FAILURE = 2
@dataclass
class CamInfo:
info_type: EyeInfoOrigin
info_type: CamInfoOrigin
output: str
+1 -1
View File
@@ -1,7 +1,7 @@
[tool.poetry]
name = "Project Babble"
version = "0.2"
description = "Opensource, affordable VR eye tracker for VRChat"
description = "Affordable and Fully Opensource Mouth Tracker for VR"
authors = ["SummerSigh", "RedHawk989"]
license = "MIT"
repository = "https://github.com/SummerSigh/ProjectBabble"
+1 -1
View File
@@ -1,7 +1,7 @@
:: Example script to auto build app and make an installer
:: File paths will all need to be updated to your setup
cd C:\Users\Prohurtz\PycharmProjects\Babble_app\BabbleApp
pyinstaller eyetrackapp.spec --noconfirm
pyinstaller babbleapp.spec --noconfirm
cd C:\Users\Prohurtz\OneDrive\Desktop
cd C:\Program Files (x86)\Inno Setup 6
ISCC C:\Users\Prohurtz\OneDrive\Desktop\installer.iss
+11 -11
View File
@@ -1,16 +1,16 @@
; Script generated by the Inno Setup Script Wizard.
; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!
#define MyAppName "EyeTrackVR"
#define MyAppVersion "0.2 BETA 5"
#define MyAppPublisher "EyeTrackVR"
#define MyAppURL "https://redhawk989.github.io/EyeTrackVR/"
#define MyAppExeName "eyetrackapp.exe"
#define MyAppName "Project Babble"
#define MyAppVersion "0.2 BETA"
#define MyAppPublisher "Project Babble Team"
#define MyAppURL "https://github.com/SummerSigh/ProjectBabble/tree/main"
#define MyAppExeName "Babble_App.exe"
[Setup]
; NOTE: The value of AppId uniquely identifies this application. Do not use the same AppId value in installers for other applications.
; (To generate a new GUID, click Tools | Generate GUID inside the IDE.)
AppId={{60B32C3C-819B-4685-AF40-49AB93539405}
AppId={{}
AppName={#MyAppName}
AppVersion={#MyAppVersion}
;AppVerName={#MyAppName} {#MyAppVersion}
@@ -20,11 +20,11 @@ AppSupportURL={#MyAppURL}
AppUpdatesURL={#MyAppURL}
DefaultDirName={autopf}\{#MyAppName}
DisableProgramGroupPage=yes
OutputDir=C:\Users\beaul\OneDrive\Desktop\Output\
OutputDir=C:\Users\Prohurtz\OneDrive\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
OutputBaseFilename=Project_Babble-Setup
SetupIconFile=C:\Users\Prohurtz\PycharmProjects\ProjectBabble\BabbleApp\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\ProjectBabble\BabbleApp\dist\BabbleApp\{#MyAppExeName}"; DestDir: "{app}"; Flags: ignoreversion
Source: "C:\Users\Prohurtz\PycharmProjects\ProjectBabble\BabbleApp\dist\BabbleApp\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
; NOTE: Don't use "Flags: ignoreversion" on any shared system files
[Dirs]