-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvoice_translator.py
More file actions
491 lines (383 loc) · 15.7 KB
/
voice_translator.py
File metadata and controls
491 lines (383 loc) · 15.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
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
#!/usr/bin/env python3
"""
Voice to LaTeX Translation System
================================
This module provides real-time microphone input for mathematical speech-to-LaTeX translation.
It integrates speech recognition, natural language processing, and LaTeX generation.
Features:
- Real-time microphone recording
- Speech-to-text using Whisper
- Mathematical expression recognition
- LaTeX output generation
- Multiple translation backends (FST + Neural)
Usage:
from voice_translator import VoiceTranslator
translator = VoiceTranslator()
translator.start_listening()
"""
import pyaudio
import wave
import threading
import time
import os
import tempfile
from datetime import datetime
from typing import Optional, Callable, Dict, Any
import numpy as np
# Import our existing components
from steve import Steve
from interpreter import MathFST
class AudioRecorder:
"""Real-time audio recording from microphone"""
def __init__(self, sample_rate=16000, chunk_size=1024, channels=1):
self.sample_rate = sample_rate
self.chunk_size = chunk_size
self.channels = channels
self.audio_format = pyaudio.paInt16
self.pyaudio = pyaudio.PyAudio()
self.recording = False
self.frames = []
self.stream = None
def start_recording(self):
"""Start recording audio from microphone"""
if self.recording:
return
self.frames = []
self.recording = True
self.stream = self.pyaudio.open(
format=self.audio_format,
channels=self.channels,
rate=self.sample_rate,
input=True,
frames_per_buffer=self.chunk_size,
stream_callback=self._audio_callback
)
self.stream.start_stream()
print("🎤 Recording started...")
def stop_recording(self):
"""Stop recording and return audio data"""
if not self.recording:
return None
self.recording = False
if self.stream:
self.stream.stop_stream()
self.stream.close()
print("🛑 Recording stopped.")
if not self.frames:
return None
# Convert frames to numpy array
audio_data = b''.join(self.frames)
audio_array = np.frombuffer(audio_data, dtype=np.int16).astype(np.float32) / 32768.0
return audio_array
def _audio_callback(self, in_data, frame_count, time_info, status):
"""Callback for audio stream"""
if self.recording:
self.frames.append(in_data)
return (in_data, pyaudio.paContinue)
def save_audio(self, audio_data: np.ndarray, filename: str):
"""Save audio data to WAV file"""
# Convert back to int16
audio_int16 = (audio_data * 32768).astype(np.int16)
with wave.open(filename, 'wb') as wf:
wf.setnchannels(self.channels)
wf.setsampwidth(self.pyaudio.get_sample_size(self.audio_format))
wf.setframerate(self.sample_rate)
wf.writeframes(audio_int16.tobytes())
def cleanup(self):
"""Clean up audio resources"""
if self.stream:
self.stream.close()
self.pyaudio.terminate()
class VoiceTranslator:
"""Main voice-to-LaTeX translation system"""
def __init__(self,
sample_rate=16000,
temp_dir=None):
"""
Initialize the voice translator
Args:
sample_rate (int): Audio sample rate
temp_dir (str): Directory for temporary files
"""
self.sample_rate = sample_rate
self.temp_dir = temp_dir or tempfile.gettempdir()
# Initialize components
print("🚀 Initializing Voice Translator...")
# Audio recorder
self.recorder = AudioRecorder(sample_rate=sample_rate)
# Speech-to-text (Whisper)
print("📝 Loading speech recognition model...")
self.speech_recognizer = Steve()
# Math-to-LaTeX translator (FST-based)
print("🧮 Loading mathematical translator...")
self.fst_translator = MathFST()
# State management
self.is_listening = False
self.last_translation = None
self.translation_history = []
# Callbacks
self.on_speech_detected = None
self.on_translation_complete = None
self.on_error = None
print("✅ Voice Translator initialized successfully!")
def set_callbacks(self,
on_speech_detected: Optional[Callable[[str], None]] = None,
on_translation_complete: Optional[Callable[[str, str], None]] = None,
on_error: Optional[Callable[[str], None]] = None):
"""Set callback functions for events"""
self.on_speech_detected = on_speech_detected
self.on_translation_complete = on_translation_complete
self.on_error = on_error
def start_listening(self, duration=None):
"""
Start listening for voice input
Args:
duration (float): Recording duration in seconds (None = manual stop)
"""
if self.is_listening:
print("⚠️ Already listening...")
return
self.is_listening = True
print("🎤 Starting voice translation session...")
try:
if duration:
# Timed recording
self._record_for_duration(duration)
else:
# Manual recording (call stop_listening to end)
self.recorder.start_recording()
except Exception as e:
error_msg = f"Failed to start listening: {e}"
print(f"❌ {error_msg}")
if self.on_error:
self.on_error(error_msg)
self.is_listening = False
def stop_listening(self):
"""Stop listening and process the recorded audio"""
if not self.is_listening:
print("⚠️ Not currently listening...")
return None
print("🔄 Processing speech...")
try:
# Stop recording and get audio data
audio_data = self.recorder.stop_recording()
self.is_listening = False
if audio_data is None:
print("❌ No audio data recorded")
return None
# Process the audio
return self._process_audio(audio_data)
except Exception as e:
error_msg = f"Failed to process audio: {e}"
print(f"❌ {error_msg}")
if self.on_error:
self.on_error(error_msg)
self.is_listening = False
return None
def _record_for_duration(self, duration: float):
"""Record for a specific duration"""
self.recorder.start_recording()
def stop_after_duration():
time.sleep(duration)
if self.is_listening:
self.stop_listening()
threading.Thread(target=stop_after_duration, daemon=True).start()
def _process_audio(self, audio_data: np.ndarray) -> Optional[Dict[str, Any]]:
"""Process recorded audio and generate LaTeX translation"""
try:
# Save audio to temporary file
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
temp_audio_path = os.path.join(self.temp_dir, f"voice_input_{timestamp}.wav")
self.recorder.save_audio(audio_data, temp_audio_path)
# Speech-to-text
print("🗣️ Converting speech to text...")
text = self._speech_to_text(temp_audio_path)
if not text or not text.strip():
print("❌ No speech detected or transcription failed")
return None
print(f"📝 Detected speech: '{text}'")
# Trigger speech detected callback
if self.on_speech_detected:
self.on_speech_detected(text)
# Text-to-LaTeX translation
print("🧮 Translating to LaTeX...")
latex_result = self._text_to_latex(text)
if not latex_result:
print("❌ LaTeX translation failed")
return None
print(f"📐 LaTeX result: {latex_result}")
# Create result object
result = {
'timestamp': timestamp,
'speech_text': text,
'latex': latex_result,
'audio_file': temp_audio_path,
'method': 'fst'
}
# Store in history
self.translation_history.append(result)
self.last_translation = result
# Trigger translation complete callback
if self.on_translation_complete:
self.on_translation_complete(text, latex_result)
# Clean up temporary file
try:
os.remove(temp_audio_path)
except:
pass
return result
except Exception as e:
error_msg = f"Error processing audio: {e}"
print(f"❌ {error_msg}")
if self.on_error:
self.on_error(error_msg)
return None
def _speech_to_text(self, audio_path: str) -> str:
"""Convert speech to text using Whisper"""
try:
result = self.speech_recognizer.transcribe(audio_path)
return result.strip() if result else ""
except Exception as e:
print(f"❌ Speech recognition failed: {e}")
return ""
def _text_to_latex(self, text: str) -> str:
"""Convert mathematical text to LaTeX using FST"""
try:
latex = self.fst_translator.compile(text)
return latex.strip() if latex else ""
except Exception as e:
print(f"❌ LaTeX translation failed: {e}")
return ""
def translate_text_directly(self, text: str) -> Optional[Dict[str, Any]]:
"""Translate text directly without voice input"""
print(f"🔄 Direct translation: '{text}'")
try:
# Text-to-LaTeX translation
latex_result = self._text_to_latex(text)
if not latex_result:
print("❌ LaTeX translation failed")
return None
print(f"📐 LaTeX result: {latex_result}")
# Create result object
result = {
'timestamp': datetime.now().strftime("%Y%m%d_%H%M%S"),
'speech_text': text,
'latex': latex_result,
'audio_file': None,
'method': 'fst'
}
# Store in history
self.translation_history.append(result)
self.last_translation = result
# Trigger translation complete callback
if self.on_translation_complete:
self.on_translation_complete(text, latex_result)
return result
except Exception as e:
error_msg = f"Direct translation failed: {e}"
print(f"❌ {error_msg}")
if self.on_error:
self.on_error(error_msg)
return None
def get_translation_history(self) -> list:
"""Get history of all translations"""
return self.translation_history.copy()
def clear_history(self):
"""Clear translation history"""
self.translation_history.clear()
self.last_translation = None
def cleanup(self):
"""Clean up resources"""
self.recorder.cleanup()
def interactive_demo():
"""Interactive demonstration of the voice translator"""
print("🎙️ Voice to LaTeX Translation Demo")
print("=" * 50)
translator = VoiceTranslator()
def on_speech_detected(text):
print(f"🗣️ Heard: '{text}'")
def on_translation_complete(text, latex):
print(f"📝 Input: {text}")
print(f"📐 LaTeX: {latex}")
print("-" * 30)
def on_error(error):
print(f"❌ Error: {error}")
translator.set_callbacks(
on_speech_detected=on_speech_detected,
on_translation_complete=on_translation_complete,
on_error=on_error
)
print("\n🎤 Voice Translation Mode")
print("Commands:")
print(" - Press ENTER to start recording")
print(" - Press ENTER again to stop recording")
print(" - Type 'text:' followed by text for direct translation")
print(" - Type 'history' to see translation history")
print(" - Type 'quit' to exit")
print("-" * 40)
try:
while True:
user_input = input("\nPress ENTER to record (or type command): ").strip()
if user_input.lower() in ['quit', 'exit', 'q']:
break
elif user_input.lower() == 'history':
history = translator.get_translation_history()
if history:
print("\n📚 Translation History:")
for i, item in enumerate(history, 1):
print(f"{i}. {item['speech_text']} → {item['latex']}")
else:
print("📭 No translations yet")
elif user_input.startswith('text:'):
# Direct text translation
text = user_input[5:].strip()
if text:
translator.translate_text_directly(text)
elif user_input == '':
# Voice recording mode
if not translator.is_listening:
print("🎤 Recording... (press ENTER to stop)")
translator.start_listening()
input() # Wait for user to press ENTER
translator.stop_listening()
else:
translator.stop_listening()
else:
print("❓ Unknown command. Try 'quit', 'history', 'text:', or just ENTER to record.")
except KeyboardInterrupt:
print("\n👋 Interrupted by user")
finally:
translator.cleanup()
print("🧹 Cleaned up resources")
def quick_test():
"""Quick test of text translation functionality"""
print("🧪 Quick Test Mode")
print("=" * 30)
translator = VoiceTranslator() # FST-based translation
test_cases = [
"integral of x squared dx",
"derivative of sine x",
"x plus y equals z",
"square root of x",
"limit as x approaches zero",
"sum from i equals one to n",
"a over b",
]
print("Testing mathematical expressions:")
for i, test in enumerate(test_cases, 1):
print(f"\n{i}. Testing: '{test}'")
result = translator.translate_text_directly(test)
if result:
print(f" Result: {result['latex']}")
else:
print(" ❌ Failed")
translator.cleanup()
def main():
"""Main function"""
import sys
if len(sys.argv) > 1 and sys.argv[1] == 'test':
quick_test()
else:
interactive_demo()
if __name__ == "__main__":
main()