-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvoice_command.py
99 lines (86 loc) · 2.64 KB
/
voice_command.py
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
import speech_recognition as sr
import subprocess
import json
def r(file_path):
try:
with open(file_path, 'r') as f:
content = f.read().strip()
return content
except Exception as e:
print(f"Error reading from file: {e}")
return None
def x(file_path):
try:
with open(file_path, 'r') as f:
phrases = f.read().strip().split('\n')
return phrases
except Exception as e:
print(f"Error reading phrases from file: {e}")
return []
def log_command(command, log_file='command_log.txt'):
try:
with open(log_file, 'a') as f:
f.write(f"{command}\n")
except Exception as e:
print(f"Error logging command: {e}")
def e(command):
try:
subprocess.run(command, shell=True, check=True)
print("Executed.")
log_command(command)
except subprocess.CalledProcessError as e:
print(f"Command error: {e}")
def load_config(file_path):
try:
with open(file_path, 'r') as f:
config = json.load(f)
return config
except Exception as e:
print(f"Error loading configuration: {e}")
return {}
def show_command_log(log_file='command_log.txt'):
try:
with open(log_file, 'r') as f:
commands = f.readlines()
if commands:
print("Command History:")
for command in commands:
print(command.strip())
else:
print("No commands in history.")
except Exception as e:
print(f"Error reading command log: {e}")
def lfc():
config = load_config('config.json')
rzn = sr.Recognizer()
m = sr.Microphone()
phrases_file = config.get('phrases_file', 'commands.txt')
command_file = config.get('command_file', 'command.config')
language = config.get('language', 'en-US')
phrases = x(phrases_file)
if not phrases:
print("No phrases.")
return
with m as s:
print("Noise adjustment...")
rzn.adjust_for_ambient_noise(s)
print("Listening...")
audio = rzn.listen(s)
try:
text = rzn.recognize_google(audio, language=language)
print(f"Recognized: {text}")
if any(phrase.lower() in text.lower() for phrase in phrases):
command = r(command_file)
if command:
e(command)
else:
print("No command.")
else:
print("Command not supported.")
except sr.UnknownValueError:
print("Not understood.")
except sr.RequestError as e:
print(f"Service error: {e}")
show_command_log()
if __name__ == "__main__":
lfc()