-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
296 lines (235 loc) · 7.7 KB
/
Copy pathapp.py
File metadata and controls
296 lines (235 loc) · 7.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import webview
import threading
import serial
import numpy as np
import time
from collections import deque
import keyboard
import json
import os
import csv
from dotenv import load_dotenv
import os
load_dotenv(dotenv_path=".config")
# Optional ML imports
try:
import joblib
import pandas as pd
except:
joblib = None
# ===============================
# CONFIG
# ===============================
SERIAL_PORT = os.getenv("SERIAL_PORT", "COM3")
BAUD_RATE = int(os.getenv("BAUD_RATE", 115200))
MODEL_PATH = os.getenv("MODEL_PATH", "emg_modelv0.2.pkl")
FORCE_MODE = os.getenv("FORCE_MODE", "auto")
BUFFER_SIZE = int(os.getenv("BUFFER_SIZE", 64))
COOLDOWN_TIME = float(os.getenv("COOLDOWN_TIME", 0.5))
# ML config
WINDOW = int(os.getenv("WINDOW", 1))
BASELINE_SAMPLES = int(os.getenv("BASELINE_SAMPLES", 300))
DEV1 = int(os.getenv("DEV1", 5))
DEV2 = int(os.getenv("DEV2", 40))
# Recording
recording_enabled = False
csv_filename = os.getenv("CSV_FILENAME", "data.csv")
SAVE_INTERVAL = int(os.getenv("SAVE_INTERVAL", 5))
last_save_time = time.time()
running=False
timestampCSV, emg1, emg2, labels = [], [], [], []
last_trigger_time = 0
action_keys = {
"action1": "space",
"action2": "left",
"action3": "right"
}
# Buffers
buffer1 = deque([0]*BUFFER_SIZE, maxlen=BUFFER_SIZE)
buffer2 = deque([0]*BUFFER_SIZE, maxlen=BUFFER_SIZE)
window_buffer = deque(maxlen=WINDOW)
baseline_buffer = deque(maxlen=BASELINE_SAMPLES)
baseline_mean = [0, 0]
baseline_ready = False
model = None
MODE = "non-ml"
if FORCE_MODE == "ml":
MODE = "ml"
elif FORCE_MODE == "non-ml":
MODE = "non-ml"
else: # auto
if joblib and os.path.exists(MODEL_PATH):
try:
model = joblib.load(MODEL_PATH)
MODE = "ml"
except Exception as e:
print("⚠️ Model load failed:", e)
MODE = "non-ml"
print(f"""
=== CONFIG ===
PORT: {SERIAL_PORT}
BAUD: {BAUD_RATE}
MODE: {FORCE_MODE}
MODEL: {MODEL_PATH}
=============
""")
# ===============================
# HELPERS
# ===============================
def save_to_csv():
global timestampCSV, emg1, emg2, labels
if not timestampCSV:
return
file_exists = os.path.exists(csv_filename)
with open(csv_filename, "a", newline="") as f:
writer = csv.writer(f)
if not file_exists:
writer.writerow(["timestamp", "emg1", "emg2", "label"])
for i in range(len(timestampCSV)):
writer.writerow([timestampCSV[i], emg1[i], emg2[i], labels[i]])
timestampCSV.clear()
emg1.clear()
emg2.clear()
labels.clear()
# ===============================
# ML FUNCTIONS
# ===============================
def extract_features(window):
env1, env2 = window[-1]
return pd.DataFrame([[env1, env2]], columns=['emg1', 'emg2'])
def is_deviation(env1, env2):
global baseline_ready, baseline_mean
if not baseline_ready:
baseline_buffer.append((env1, env2))
if len(baseline_buffer) == BASELINE_SAMPLES:
baseline_mean[0] = np.mean([x[0] for x in baseline_buffer])
baseline_mean[1] = np.mean([x[1] for x in baseline_buffer])
baseline_ready = True
return False
return (abs(env1 - baseline_mean[0]) > DEV1 or
abs(env2 - baseline_mean[1]) > DEV2)
# ===============================
# MAIN LOOP (UNIFIED)
# ===============================
def process_emg_data():
global running, ser, last_trigger_time, last_save_time
while running:
try:
line = ser.readline().decode('utf-8', errors='ignore')
except:
continue
parts = line.strip().replace(',', '\t').split('\t')
if len(parts) < 2:
continue
try:
env1, env2 = int(parts[0]), int(parts[1])
except:
continue
current_time = time.time()
output = "0"
# ===============================
# 🔥 ML MODE
# ===============================
if MODE == "ml" and model:
window_buffer.append((env1, env2))
if is_deviation(env1, env2) and len(window_buffer) == WINDOW:
try:
features = extract_features(window_buffer)
pred = str(model.predict(features)[0])
output = pred
key = action_keys.get(f"action{pred}")
if key and current_time - last_trigger_time > COOLDOWN_TIME:
last_trigger_time = current_time
keyboard.press_and_release(key)
except:
pass
# ===============================
# 🔥 NON-ML MODE
# ===============================
else:
if env1 > 10 and env2 < 100:
if current_time - last_trigger_time > COOLDOWN_TIME:
last_trigger_time = current_time
keyboard.press_and_release(action_keys["action1"])
output = "1"
elif env2 > 100:
if env1 > 10:
if current_time - last_trigger_time > COOLDOWN_TIME:
last_trigger_time = current_time
keyboard.press_and_release(action_keys["action3"])
output = "3"
elif env2 > 150:
if current_time - last_trigger_time > COOLDOWN_TIME:
last_trigger_time = current_time
keyboard.press_and_release(action_keys["action2"])
output = "2"
# ===============================
# 📊 RECORDING
# ===============================
if recording_enabled:
timestampCSV.append(current_time)
emg1.append(env1)
emg2.append(env2)
labels.append(output)
if time.time() - last_save_time > SAVE_INTERVAL:
save_to_csv()
last_save_time = time.time()
# ===============================
# 🖥️ CLEAN DEBUG LINE
# ===============================
print(f"\r{env1:4d}, {env2:4d} -> {output} [{MODE}]", end="", flush=True)
# ===============================
# API
# ===============================
class API:
def __init__(self):
self.thread = None
def toggle_recording(self, enable, filename):
global recording_enabled, csv_filename
recording_enabled = enable
if filename:
csv_filename = filename
return f"Recording {'ON' if enable else 'OFF'}"
def start_emg(self, k1, k2, k3):
global running, ser, action_keys, baseline_ready
action_keys["action1"] = k1
action_keys["action2"] = k2
action_keys["action3"] = k3
baseline_ready = False
if not running:
try:
ser = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=0)
except Exception as e:
return str(e)
running = True
self.thread = threading.Thread(target=process_emg_data, daemon=True)
self.thread.start()
return f"Started in {MODE} mode 🚀"
return "Already running"
def stop_emg(self):
global running, ser
running = False
if ser:
ser.close()
ser = None
save_to_csv()
print("\nStopped.")
return "Stopped"
# ===============================
# LOAD UI
# ===============================
with open("templates/index.html", "r") as f:
html_content = f.read()
# ===============================
# MAIN
# ===============================
if __name__ == "__main__":
api = API()
webview.create_window(
"EMG Gesture Control",
html=html_content,
js_api=api,
width=900,
height=650
)
webview.start()