-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclap_start.py
More file actions
161 lines (134 loc) · 5.38 KB
/
Copy pathclap_start.py
File metadata and controls
161 lines (134 loc) · 5.38 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
import sounddevice as sd
import numpy as np
import subprocess
import time
import os
import sys
import json
def get_base_path():
"""Get the absolute path to the directory where the script or exe is located."""
if getattr(sys, 'frozen', False):
# If running as an EXE (PyInstaller)
return os.path.dirname(sys.executable)
else:
# If running as a .py script
return os.path.dirname(os.path.abspath(__file__))
def load_config():
"""Load configuration from local_config.json, or config.json if not found."""
base_path = get_base_path()
local_path = os.path.join(base_path, "local_config.json")
old_path = os.path.join(base_path, "config.json")
# Priority: local_config.json -> config.json -> default_config
config_path = local_path if os.path.exists(local_path) else old_path
# Default settings in case file is missing or broken
default_config = {
"browser_urls": [],
"vscode_projects": [],
"terminal_projects": [],
"explorer_folders": [],
"custom_commands": [],
"settings": {
"threshold": 0.015,
"max_gap_s": 0.8,
"cooldown_s": 5.0
}
}
if not os.path.exists(config_path):
print(f"⚠️ Config file not found at {config_path}. Using defaults.")
return default_config
try:
with open(config_path, 'r') as f:
return json.load(f)
except Exception as e:
print(f"❌ Error loading config: {e}. Using defaults.")
return default_config
# Load configuration
config = load_config()
settings = config.get("settings", {})
THRESHOLD = settings.get("threshold", 0.015)
MAX_GAP_S = settings.get("max_gap_s", 0.8)
COOLDOWN_S = settings.get("cooldown_s", 5.0)
SAMPLE_RATE = 44100
BLOCK_SIZE = 512
last_clap_time = 0.0
first_clap_received = False
last_activation_time = 0.0
should_exit = False
def activate_workspace():
"""Process config.json and launch all configured apps/folders/URLs."""
global last_activation_time, should_exit
print("\n👏 DOUBLE CLAP DETECTED — Launching workspace!")
try:
# 1. Launch Browser URLs
for url in config.get("browser_urls", []):
print(f" 🌐 Opening: {url}")
subprocess.Popen(["cmd", "/c", "start", "", url], shell=True)
time.sleep(0.1)
# 2. Launch VS Code Projects
for project in config.get("vscode_projects", []):
print(f" 💻 Opening VS Code: {project}")
subprocess.Popen(["cmd", "/c", "code", "--new-window", project], shell=True)
time.sleep(0.1)
# 3. Launch Windows Terminal
for path in config.get("terminal_projects", []):
print(f" 📟 Opening Terminal: {path}")
subprocess.Popen(["cmd", "/c", "start", "wt", "-d", path], shell=True)
time.sleep(0.1)
# 4. Launch Explorer Folders
for folder in config.get("explorer_folders", []):
print(f" 📁 Opening Folder: {folder}")
subprocess.Popen(["explorer", folder])
time.sleep(0.1)
# 5. Run Custom Commands (like Git Bash)
for cmd in config.get("custom_commands", []):
print(f" ⚙️ Running Command: {cmd}")
subprocess.Popen(["cmd", "/c", "start", "", "cmd", "/c", cmd], shell=True)
time.sleep(0.1)
last_activation_time = time.time()
print("✅ Workspace launch complete!")
print("👋 Task finished. ClapStart is now exiting to save resources.\n")
should_exit = True
except Exception as e:
print(f"❌ Error during activation: {e}")
def audio_callback(indata, frames, t, status):
"""Real-time audio processing callback."""
global last_clap_time, first_clap_received, last_activation_time
if time.time() - last_activation_time < COOLDOWN_S:
return
# Calculate Root Mean Square (RMS) to measure volume level
rms = np.sqrt(np.mean(indata**2))
# DEBUG: Uncomment the line below to see your volume levels in the console
print(f"Volume: {rms:.4f}", end="\r")
if rms > THRESHOLD:
now = time.time()
if (now - last_clap_time) > 0.15:
if first_clap_received and (now - last_clap_time) < MAX_GAP_S:
activate_workspace()
first_clap_received = False
else:
last_clap_time = now
first_clap_received = True
print("☝️ First clap detected... waiting for second...")
last_clap_time = now
elif first_clap_received and (time.time() - last_clap_time) > MAX_GAP_S:
first_clap_received = False
if __name__ == "__main__":
print("🎙️ ClapStart is listening... Double clap to start your workspace!")
print(f" Config loaded from: {get_base_path()}")
print(f" Sensitivity: {THRESHOLD} | Max Gap: {MAX_GAP_S}s | Cooldown: {COOLDOWN_S}s")
print(" Press Ctrl+C to exit\n")
try:
with sd.InputStream(
callback=audio_callback,
samplerate=SAMPLE_RATE,
channels=1,
blocksize=BLOCK_SIZE
):
while not should_exit:
time.sleep(0.5)
if should_exit:
sys.exit(0)
except KeyboardInterrupt:
print("\nExiting ClapStart...")
except Exception as e:
print(f"Stream error: {e}")