-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtempCodeRunnerFile.py
More file actions
425 lines (376 loc) · 17.8 KB
/
Copy pathtempCodeRunnerFile.py
File metadata and controls
425 lines (376 loc) · 17.8 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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import speech_recognition as sr
import win32com.client
import time
import sys
import os
import argparse
import tkinter as tk
from tkinter import filedialog
def select_ppt_file():
root = tk.Tk()
root.withdraw() # Hide the main window
file_path = filedialog.askopenfilename(
title="Select PowerPoint Presentation",
filetypes=[("PowerPoint files", "*.ppt;*.pptx")]
)
return file_path if file_path else None
def setup_recognizer():
recognizer = sr.Recognizer()
# Enhanced noise handling and voice detection settings
recognizer.energy_threshold = 2500 # Lower threshold for better sensitivity
recognizer.dynamic_energy_threshold = True
recognizer.dynamic_energy_adjustment_damping = 0.2 # More responsive adaptation
recognizer.dynamic_energy_adjustment_ratio = 1.2 # Better signal-to-noise ratio
recognizer.pause_threshold = 0.6 # Faster command detection
recognizer.phrase_threshold = 0.2 # More sensitive phrase detection
recognizer.non_speaking_duration = 0.4 # Quicker response to silence
return recognizer
def listen_for_command(recognizer):
with sr.Microphone() as source:
print("\n🎤 Initializing voice recognition...")
print("Adjusting for background noise...")
try:
# Enhanced initial noise adjustment
recognizer.adjust_for_ambient_noise(source, duration=2)
except Exception as e:
print(f"Warning: Could not adjust for ambient noise: {e}")
print("Continuing with default settings...")
print("\n✨ Voice recognition ready!")
print("Continuously listening for commands...")
print("\n💡 Available commands:")
print(" - 'Next' or 'Forward' to advance")
print(" - 'Back' or 'Previous' to go back")
print(" - 'End', 'Stop', or 'Exit' to close")
noise_adjust_interval = 20 # More frequent noise adjustments
retry_count = 0
last_noise_adjust = time.time()
max_consecutive_errors = 5 # Maximum consecutive errors before resetting
consecutive_errors = 0
while True:
try:
# Enhanced periodic noise adjustment
current_time = time.time()
if retry_count >= noise_adjust_interval or (current_time - last_noise_adjust) > 180: # 3 minutes
print("\n⚠️ Readjusting for ambient noise...")
try:
recognizer.adjust_for_ambient_noise(source, duration=1.5)
print("✨ Ready! Continuously listening...")
except Exception as e:
print(f"Warning: Noise adjustment failed: {e}")
retry_count = 0
last_noise_adjust = current_time
# Enhanced audio capture with timeout
try:
audio = recognizer.listen(
source,
timeout=10, # Timeout after 10 seconds of silence
phrase_time_limit=5 # Allow longer commands
)
except sr.WaitTimeoutError:
print("\n⏳ No speech detected, continuing...", end='\r')
continue
try:
command = recognizer.recognize_google(
audio,
language='en-US',
show_all=False
).lower().strip()
if command:
# Reset error counters on successful recognition
consecutive_errors = 0
retry_count = 0
print(f"\n✅ Recognized command: {command}")
return command
else:
print("\n❌ Empty command detected. Please speak clearly.")
retry_count += 1
continue
except sr.UnknownValueError:
print("\n❓ Could not understand audio, please try again", end='\r')
retry_count += 1
consecutive_errors += 1
if consecutive_errors >= max_consecutive_errors:
print("\n⚠️ Multiple recognition failures. Resetting voice recognition...")
recognizer.adjust_for_ambient_noise(source, duration=2)
consecutive_errors = 0
continue
except sr.RequestError as e:
print(f"\n⚠️ Network error: {e}")
print("Retrying after brief pause...")
time.sleep(2) # Longer pause for network issues
continue
except KeyboardInterrupt:
print("\n🛑 Voice control stopped.")
return "end"
except Exception as e:
print(f"\n⚠️ Unexpected error: {str(e)}")
print("Attempting to recover...")
consecutive_errors += 1
if consecutive_errors >= max_consecutive_errors:
print("Too many errors. Resetting voice recognition...")
try:
recognizer.adjust_for_ambient_noise(source, duration=2)
consecutive_errors = 0
except:
pass
time.sleep(1) # Longer pause for recovery
continue
def parse_move_count(command):
words = command.split()
count = 1
# Count occurrences of movement-related words and handle jump commands
movement_words = ['forward', 'back', 'next', 'previous', 'jump']
for i, word in enumerate(words):
if word in movement_words:
# Check for jump command with number
if word == 'jump' and i + 1 < len(words):
try:
jump_count = int(words[i + 1])
return jump_count
except ValueError:
pass
count += 1
return count - 1
def cleanup_powerpoint(presentation, powerpoint):
max_retries = 3
retry_delay = 2
for attempt in range(max_retries):
try:
if presentation:
try:
# Save any changes if needed
if hasattr(presentation, 'Saved') and not presentation.Saved:
presentation.Save()
# Exit slideshow if active
if hasattr(presentation, 'SlideShowWindow') and presentation.SlideShowWindow:
presentation.SlideShowWindow.View.Exit()
time.sleep(1)
# Close presentation properly
presentation.Close()
# Explicitly release COM object
import pythoncom
pythoncom.CoInitialize()
presentation._oleobj_.Release()
pythoncom.CoUninitialize()
presentation = None
except Exception as e:
print(f"Warning: Error while closing presentation (attempt {attempt + 1}): {str(e)}")
if powerpoint:
try:
# Ensure PowerPoint is responsive
_ = powerpoint.Version
powerpoint.DisplayAlerts = False
powerpoint.Quit()
# Explicitly release COM object
powerpoint._oleobj_.Release()
powerpoint = None
time.sleep(1)
break # Success - exit retry loop
except Exception as e:
print(f"Warning: Error while closing PowerPoint (attempt {attempt + 1}): {str(e)}")
if attempt == max_retries - 1:
# Last resort: force close PowerPoint
try:
import win32gui
import win32con
def close_powerpoint(hwnd, _):
if 'PowerPoint' in win32gui.GetWindowText(hwnd):
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
win32gui.EnumWindows(close_powerpoint, None)
time.sleep(1)
except Exception as force_close_error:
print(f"Warning: Force close failed: {str(force_close_error)}")
try:
os.system('taskkill /f /im POWERPNT.EXE')
time.sleep(1)
except:
print("Warning: Failed to terminate PowerPoint process")
if attempt < max_retries - 1:
time.sleep(retry_delay)
except Exception as e:
print(f"Warning: General cleanup error (attempt {attempt + 1}): {str(e)}")
if attempt < max_retries - 1:
time.sleep(retry_delay)
# Final verification and cleanup
try:
# Release COM objects explicitly
if presentation:
del presentation
if powerpoint:
del powerpoint
# Check if any PowerPoint instance is still running
try:
win32com.client.GetActiveObject("PowerPoint.Application")
print("Warning: PowerPoint instance might still be running")
# Force cleanup through COM
pythoncom.CoInitialize()
pythoncom.CoUninitialize()
except pythoncom.com_error:
print("PowerPoint closed successfully")
except Exception as e:
print("PowerPoint closed successfully")
except Exception as e:
print(f"Note: Final cleanup completed with status: {str(e)}")
pass
def control_presentation(ppt_path):
if not os.path.exists(ppt_path):
print(f"Error: PowerPoint file not found: {ppt_path}")
return
if not ppt_path.lower().endswith(('.ppt', '.pptx')):
print("Error: File must be a PowerPoint presentation (.ppt or .pptx)")
return
powerpoint = None
presentation = None
max_retries = 5 # Reduced retries for faster failure detection
retry_delay = 3 # Increased delay for better stability
last_error = None
# First, try to clean up any existing PowerPoint instances
try:
existing_powerpoint = win32com.client.GetActiveObject("PowerPoint.Application")
if existing_powerpoint:
try:
existing_powerpoint.DisplayAlerts = False
existing_powerpoint.Quit()
time.sleep(1) # Give PowerPoint more time to close properly
except:
# If normal quit fails, try force closing
try:
os.system('taskkill /f /im POWERPNT.EXE')
time.sleep(1) # Wait for process to be killed
except:
pass
except:
pass # No existing PowerPoint instance found
# Kill any remaining PowerPoint processes
try:
os.system('taskkill /f /im POWERPNT.EXE')
time.sleep(1) # Wait for process to be killed
except:
pass
for attempt in range(max_retries):
try:
# Create a new PowerPoint instance with explicit COM settings
powerpoint = win32com.client.DispatchEx("PowerPoint.Application")
powerpoint.Visible = 1 # Use integer instead of boolean
powerpoint.DisplayAlerts = 0 # Suppress alerts
# Wait for PowerPoint to be fully initialized
time.sleep(1)
# Verify PowerPoint is responsive with proper error handling
try:
version = powerpoint.Version # Test responsiveness
print(f"PowerPoint Version: {version}")
except Exception as e:
raise Exception(f"PowerPoint not responding: {str(e)}")
# Open the presentation with full path and proper error handling
abs_path = os.path.abspath(ppt_path)
presentation = powerpoint.Presentations.Open(abs_path)
# Ensure presentation is loaded and validate its properties
time.sleep(1)
if not presentation or not hasattr(presentation, 'Slides') or presentation.Slides.Count < 1:
raise Exception("Failed to load presentation properly")
# Start slideshow with proper validation
if not presentation.SlideShowSettings:
raise Exception("SlideShowSettings not available")
presentation.SlideShowSettings.Run()
# Verify slideshow is running
if powerpoint.SlideShowWindows.Count < 1:
raise Exception("Failed to start slideshow")
print("PowerPoint initialized successfully")
break # Successfully initialized PowerPoint
except Exception as e:
if powerpoint:
try:
powerpoint.Quit()
except:
pass
powerpoint = None
presentation = None
if attempt < max_retries - 1:
print(f"Attempt {attempt + 1} failed: {str(e)}")
print(f"Retrying in {retry_delay} seconds...")
time.sleep(retry_delay)
else:
print(f"Error: Failed to initialize PowerPoint after {max_retries} attempts: {str(e)}")
return
try:
recognizer = setup_recognizer()
print("\nVoice commands available:")
print("- 'Next' or 'Forward' to advance slides")
print("- 'Back' or 'Previous' to go back")
print("- 'End', 'Stop', or 'Exit' to close the presentation\n")
while True:
command = listen_for_command(recognizer)
if command:
try:
# Comprehensive slideshow state validation
if not powerpoint or not presentation:
raise Exception("PowerPoint or Presentation object lost")
try:
_ = powerpoint.Version # Verify PowerPoint is still responsive
except:
raise Exception("Lost connection to PowerPoint")
if not powerpoint.SlideShowWindows.Count:
print("Slideshow is not active. Restarting presentation...")
# Ensure presentation is still valid before restarting
if hasattr(presentation, 'SlideShowSettings'):
presentation.SlideShowSettings.Run()
time.sleep(1) # Wait for slideshow to initialize
if not powerpoint.SlideShowWindows.Count:
raise Exception("Failed to restart slideshow")
else:
raise Exception("Invalid presentation state")
continue
# Get slideshow window with proper error handling
slideshow = powerpoint.SlideShowWindows(1).View
if not slideshow:
raise Exception("Cannot access slideshow view")
if "end" in command or "stop" in command or "exit" in command or "quit" in command:
print("Ending presentation...")
break
elif "forward" in command or "next" in command:
moves = parse_move_count(command)
# Handle jump command
if "jump" in command:
print(f"Jumping forward {moves} slides...")
for _ in range(moves):
slideshow.Next()
time.sleep(0.1) # Small delay between moves
elif "back" in command or "previous" in command:
moves = parse_move_count(command)
# Handle jump command
if "jump" in command:
print(f"Jumping backward {moves} slides...")
for _ in range(moves):
slideshow.Previous()
time.sleep(0.1) # Small delay between moves
except Exception as e:
print(f"Error during slide navigation: {str(e)}")
break # Exit on error to prevent infinite loop
except Exception as e:
print(f"Error: An unexpected error occurred: {str(e)}")
finally:
cleanup_powerpoint(presentation, powerpoint)
def main():
parser = argparse.ArgumentParser(description='Voice-controlled PowerPoint presentation handler')
parser.add_argument('presentation_path', nargs='?', help='Path to the PowerPoint file')
try:
args = parser.parse_args()
if args.presentation_path:
ppt_path = os.path.abspath(args.presentation_path)
else:
print("Please select a PowerPoint file...")
ppt_path = select_ppt_file()
if not ppt_path:
print("No file selected. Exiting...")
return
print(f"Opening presentation: {ppt_path}")
control_presentation(ppt_path)
except Exception as e:
print(f"Error: {str(e)}")
print('\nUsage:')
print('1. Run without arguments to open file browser:')
print(' python voice_ppt_handler.py')
print('2. Or specify the file path directly:')
print(' python voice_ppt_handler.py "path/to/presentation.pptx"')
if __name__ == "__main__":
main()