-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2865 lines (2406 loc) · 98.5 KB
/
app.py
File metadata and controls
2865 lines (2406 loc) · 98.5 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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
ChatGPT Voice Mode Transcript Recorder
Main Flask Application
"""
import csv
import io
import json
import queue
import socket
import sqlite3
import threading
import time
from datetime import datetime
from typing import Any
from flask import Flask, Response, jsonify, render_template, request
# Import our custom modules
from src.audio_capture import AudioCapture
from src.llm_processor import LLMProcessor
from src.whisper_stream_processor import WhisperStreamProcessor
app = Flask(__name__)
app.config["SECRET_KEY"] = "your-secret-key-here"
# SSE streaming queue
stream_queue: queue.Queue[dict[str, Any]] = queue.Queue(
maxsize=1000
) # Prevent memory issues
# Global state
recording_state = {"is_recording": False, "session_id": None, "start_time": None}
# Auto-processing state
auto_processing_state = {
"enabled": True,
"interval_minutes": 2,
"timer": None,
"last_processing_time": None,
}
audio_capture = None
transcript_processor = None
mic_whisper_processor = None
system_whisper_processor = None
llm_processor = None
# Track sessions waiting for summary generation after stop recording
sessions_waiting_for_summary = set()
def on_whisper_transcript(event_data):
"""Callback for whisper streaming processor events"""
try:
if event_data["type"] == "raw_transcript":
# Save raw transcript to database
transcript_data = event_data["data"]
save_raw_transcript(transcript_data)
# Send via SSE
stream_queue.put(
{
"type": "raw_transcript",
"data": transcript_data,
"accumulated_count": event_data["accumulated_count"],
},
block=False,
)
elif event_data["type"] == "error":
# Send error via SSE
stream_queue.put(
{
"type": "whisper_error",
"message": event_data["message"],
"session_id": event_data["session_id"],
},
block=False,
)
except queue.Full:
print("⚠️ Stream queue full, dropping whisper event")
except Exception as e:
print(f"❌ Error in whisper callback: {e}")
def on_llm_result(event_data):
"""Callback for LLM processor events"""
try:
if event_data["type"] == "llm_processing_start":
# Send processing start via SSE
stream_queue.put(
{
"type": "llm_processing_start",
"job_id": event_data["job_id"],
"session_id": event_data["session_id"],
"transcript_count": event_data["transcript_count"],
},
block=False,
)
elif event_data["type"] == "llm_processing_complete":
# Save processed transcript to database
result = event_data["result"]
if result.get("status") == "success":
save_processed_transcript(result)
# Send completion via SSE
stream_queue.put(
{
"type": "llm_processing_complete",
"job_id": event_data["job_id"],
"result": result,
},
block=False,
)
# Check if this session is waiting for summary generation
session_id = event_data.get("session_id")
if session_id and session_id in sessions_waiting_for_summary:
print(
f"📝 LLM processing complete for session {session_id}, checking if ready for summary..."
)
check_and_generate_summary_if_ready(session_id)
elif event_data["type"] == "llm_processing_error":
# Send error via SSE
stream_queue.put(
{
"type": "llm_processing_error",
"job_id": event_data["job_id"],
"error": event_data["error"],
},
block=False,
)
except queue.Full:
print("⚠️ Stream queue full, dropping LLM event")
except Exception as e:
print(f"❌ Error in LLM callback: {e}")
def start_auto_processing_timer():
"""Start the auto-processing timer if enabled"""
global auto_processing_state
if not auto_processing_state["enabled"] or not recording_state["is_recording"]:
return
# Cancel existing timer if any
stop_auto_processing_timer()
interval_seconds = auto_processing_state["interval_minutes"] * 60
auto_processing_state["timer"] = threading.Timer(
interval_seconds, auto_process_transcripts
)
auto_processing_state["timer"].daemon = True
auto_processing_state["timer"].start()
print(
f"🤖 Auto-processing timer started: {auto_processing_state['interval_minutes']} minutes"
)
def stop_auto_processing_timer():
"""Stop the auto-processing timer"""
global auto_processing_state
if auto_processing_state["timer"]:
auto_processing_state["timer"].cancel()
auto_processing_state["timer"] = None
print("🤖 Auto-processing timer stopped")
def auto_process_transcripts():
"""Automatically process accumulated transcripts"""
global \
mic_whisper_processor, \
system_whisper_processor, \
llm_processor, \
auto_processing_state
try:
if not recording_state["is_recording"] or not auto_processing_state["enabled"]:
return
# Check if we have accumulated transcripts
accumulated_transcripts = []
if mic_whisper_processor:
accumulated_transcripts.extend(
mic_whisper_processor.get_accumulated_transcripts()
)
if system_whisper_processor:
accumulated_transcripts.extend(
system_whisper_processor.get_accumulated_transcripts()
)
if len(accumulated_transcripts) == 0:
print("🤖 Auto-processing: No transcripts to process")
# Restart timer for next interval
start_auto_processing_timer()
return
print(
f"🤖 Auto-processing: Processing {len(accumulated_transcripts)} transcripts"
)
# Sort transcripts by timestamp
accumulated_transcripts.sort(key=lambda x: x.get("timestamp", ""))
# Process with LLM asynchronously
session_id = recording_state["session_id"]
job_id = llm_processor.process_transcripts_async(
accumulated_transcripts, session_id
)
# Clear accumulated transcripts after sending to LLM
mic_whisper_processor.clear_accumulated_transcripts()
if system_whisper_processor:
system_whisper_processor.clear_accumulated_transcripts()
# Update last processing time
auto_processing_state["last_processing_time"] = datetime.now().isoformat()
# Send auto-processing notification via SSE
try:
stream_queue.put(
{
"type": "auto_processing_triggered",
"job_id": job_id,
"transcript_count": len(accumulated_transcripts),
"interval_minutes": auto_processing_state["interval_minutes"],
"timestamp": auto_processing_state["last_processing_time"],
},
block=False,
)
except queue.Full:
print("⚠️ Stream queue full, dropping auto-processing notification")
# Restart timer for next interval
start_auto_processing_timer()
except Exception as e:
print(f"❌ Error in auto-processing: {e}")
# Restart timer even on error
start_auto_processing_timer()
@app.route("/")
def index():
"""Main transcript display page"""
return render_template("index.html")
@app.route("/stream")
def stream():
"""Server-Sent Events endpoint for real-time updates"""
def event_stream():
heartbeat_counter = 0
while True:
try:
# Get data from queue (blocks until available)
data = stream_queue.get(timeout=1)
yield f"data: {json.dumps(data)}\n\n"
except queue.Empty:
# Send heartbeat with periodic state validation
heartbeat_counter += 1
heartbeat_data = {
"type": "heartbeat",
"timestamp": datetime.now().isoformat(),
}
# Include state validation every 10 heartbeats (every ~10 seconds)
if heartbeat_counter % 10 == 0:
heartbeat_data["state_sync"] = {
"is_recording": recording_state["is_recording"],
"session_id": recording_state["session_id"],
"start_time": recording_state["start_time"],
}
print(
f"🔄 Sending state sync heartbeat: {heartbeat_data['state_sync']}"
)
yield f"data: {json.dumps(heartbeat_data)}\n\n"
except Exception as e:
print(f"SSE stream error: {e}")
break
return Response(
event_stream(),
mimetype="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Access-Control-Allow-Origin": "*",
},
)
@app.route("/api/status")
def get_status():
"""Get current recording status with detailed information"""
global mic_whisper_processor, system_whisper_processor, audio_capture, llm_processor
# Get processor states
mic_active = False
system_active = False
mic_count = 0
system_count = 0
if mic_whisper_processor:
mic_active = (
mic_whisper_processor.is_streaming
if hasattr(mic_whisper_processor, "is_streaming")
else False
)
try:
mic_transcripts = mic_whisper_processor.get_accumulated_transcripts()
mic_count = len(mic_transcripts) if mic_transcripts else 0
except Exception:
mic_count = 0
if system_whisper_processor:
system_active = (
system_whisper_processor.is_streaming
if hasattr(system_whisper_processor, "is_streaming")
else False
)
try:
system_transcripts = system_whisper_processor.get_accumulated_transcripts()
system_count = len(system_transcripts) if system_transcripts else 0
except Exception:
system_count = 0
# Get audio capture state
audio_capture_active = False
if audio_capture:
audio_capture_active = (
audio_capture.is_recording
if hasattr(audio_capture, "is_recording")
else False
)
# Get LLM processor state
llm_state = {
"available": llm_processor is not None,
"is_processing": False,
"queue_length": 0,
"total_processed": 0,
"failed_requests": 0,
}
if llm_processor:
llm_state.update(
{
"is_processing": llm_processor.is_processing,
"queue_length": len(llm_processor.processing_queue),
"total_processed": llm_processor.total_processed,
"failed_requests": llm_processor.failed_requests,
}
)
# Get processed transcript count for current session
processed_count = 0
if recording_state["session_id"]:
try:
session_transcripts = get_session_transcripts(
recording_state["session_id"], "processed"
)
processed_count = len(session_transcripts.get("processed", []))
except Exception:
processed_count = 0
return jsonify(
{
"is_recording": recording_state["is_recording"],
"session_id": recording_state["session_id"],
"start_time": recording_state["start_time"],
"processors": {
"microphone_active": mic_active,
"system_active": system_active,
"accumulated_transcripts": {
"microphone": mic_count,
"system": system_count,
"total": mic_count + system_count,
},
},
"llm_processor": llm_state,
"processed_transcripts": {"session_count": processed_count},
"audio_capture_active": audio_capture_active,
"server_timestamp": datetime.now().isoformat(),
}
)
@app.route("/api/start", methods=["POST"])
def start_recording():
"""Start recording and transcription with whisper.cpp streaming"""
global \
mic_whisper_processor, \
system_whisper_processor, \
llm_processor, \
audio_capture, \
recording_state
try:
if recording_state["is_recording"]:
return jsonify({"error": "Already recording"}), 400
# Get device selections from request
device_data = request.get_json() or {}
requested_mic_device = device_data.get("mic_device_id")
requested_system_device_raw = device_data.get("system_device_id")
print(f"🔍 Raw request data: {device_data}")
print(
f"🔍 Raw system device: {requested_system_device_raw} (type: {type(requested_system_device_raw)})"
)
# Handle output device selection (format: "output_X")
requested_system_device = None
is_output_device = False
user_explicitly_disabled_system_audio = False
if requested_system_device_raw is not None:
if isinstance(
requested_system_device_raw, str
) and requested_system_device_raw.startswith("output_"):
requested_system_device = int(
requested_system_device_raw.replace("output_", "")
)
is_output_device = True
print(
f"🎛️ Output device selected for system audio: {requested_system_device}"
)
else:
requested_system_device = requested_system_device_raw
print(
f"🎛️ Input device selected for system audio: {requested_system_device}"
)
else:
# When system_device_id is not in the request, it means user selected "No system audio capture"
user_explicitly_disabled_system_audio = True
print(
"🔍 User explicitly disabled system audio capture (no system_device_id in request)"
)
print(
f"🎛️ Device selection request - Mic: {requested_mic_device}, System: {requested_system_device} ({'output' if is_output_device else 'input'})"
)
# Initialize SDL device mapper
from src.sdl_device_mapper import SDLDeviceMapper
device_mapper = SDLDeviceMapper()
device_info = device_mapper.get_device_info()
print(
f"🔧 SDL Device Mapping: {device_info['sdl_device_count']} SDL devices, {device_info['mapped_devices']} mapped to PyAudio"
)
# Initialize audio capture for volume monitoring
audio_capture = AudioCapture()
audio_capture.callback = on_audio_chunk
# Try to find and set audio devices using SDL device mapping
try:
# Get PyAudio devices for audio level monitoring
input_devices, output_devices = audio_capture.list_devices()
print(
f"🎧 Found {len(input_devices)} PyAudio input devices, {len(output_devices)} output devices"
)
# Debug: Show SDL devices available for whisper.cpp
print("📋 Available SDL devices for whisper.cpp:")
for device in device_info["devices"]:
print(
f" SDL Device {device['sdl_id']}: {device['display_name']} (PyAudio: {device['pyaudio_id']})"
)
# Frontend now sends SDL device IDs, convert to PyAudio IDs for monitoring
mic_sdl_id = requested_mic_device # SDL device ID from frontend
system_sdl_id = requested_system_device # SDL device ID from frontend
# Get corresponding PyAudio IDs for audio level monitoring
mic_pyaudio_id = (
device_mapper.get_pyaudio_device_id(mic_sdl_id)
if mic_sdl_id is not None
else None
)
system_pyaudio_id = (
device_mapper.get_pyaudio_device_id(system_sdl_id)
if system_sdl_id is not None
else None
)
print(
f"🎛️ Device mapping - Mic SDL:{mic_sdl_id}→PyAudio:{mic_pyaudio_id}, System SDL:{system_sdl_id}→PyAudio:{system_pyaudio_id}"
)
# Validate SDL devices exist
available_sdl_ids = [device["sdl_id"] for device in device_info["devices"]]
if mic_sdl_id is not None and mic_sdl_id not in available_sdl_ids:
print(
f"⚠️ Requested microphone SDL device {mic_sdl_id} not found, auto-detecting..."
)
mic_sdl_id = None
mic_pyaudio_id = None
# Handle system audio device validation (now using SDL IDs)
if system_sdl_id is not None and system_sdl_id not in available_sdl_ids:
print(
f"⚠️ Requested system audio SDL device {system_sdl_id} not found, auto-detecting..."
)
system_sdl_id = None
system_pyaudio_id = None
# Auto-detect SDL devices if not specified or invalid
if mic_sdl_id is None:
# Look for microphone in SDL devices
for device in device_info["devices"]:
device_name_lower = device["display_name"].lower()
if "airpods" in device_name_lower or (
"microphone" in device_name_lower
and "blackhole" not in device_name_lower
):
mic_sdl_id = device["sdl_id"]
mic_pyaudio_id = device["pyaudio_id"]
print(
f"🎤 Auto-detected microphone: {device['display_name']} (SDL: {mic_sdl_id}, PyAudio: {mic_pyaudio_id})"
)
break
if system_sdl_id is None and not user_explicitly_disabled_system_audio:
# Look for system audio device in SDL devices (only if user didn't explicitly disable)
for device in device_info["devices"]:
device_name_lower = device["display_name"].lower()
if (
"blackhole" in device_name_lower
or "loopback" in device_name_lower
or "soundflower" in device_name_lower
):
system_sdl_id = device["sdl_id"]
system_pyaudio_id = device["pyaudio_id"]
print(
f"🔊 Auto-detected system audio: {device['display_name']} (SDL: {system_sdl_id}, PyAudio: {system_pyaudio_id})"
)
break
# Print final device selection
if mic_sdl_id is not None:
mic_name = next(
(
device["display_name"]
for device in device_info["devices"]
if device["sdl_id"] == mic_sdl_id
),
"Unknown",
)
print(
f"✅ Using microphone: {mic_name} (SDL: {mic_sdl_id}, PyAudio: {mic_pyaudio_id})"
)
else:
print("⚠️ No microphone device available")
if system_sdl_id is not None:
sys_name = next(
(
device["display_name"]
for device in device_info["devices"]
if device["sdl_id"] == system_sdl_id
),
"Unknown",
)
print(
f"✅ Using system audio: {sys_name} (SDL: {system_sdl_id}, PyAudio: {system_pyaudio_id})"
)
else:
print("⚠️ No system audio device available")
print(" To enable system audio capture:")
print(" 1. Install BlackHole: brew install blackhole-2ch")
print(" 2. Route audio through BlackHole using Multi-Output Device")
# Set PyAudio devices for audio level monitoring
audio_capture.set_devices(
mic_device_id=mic_pyaudio_id, system_device_id=system_pyaudio_id
)
print(
f"🎚️ Audio devices configured - Mic PyAudio: {mic_pyaudio_id}, System PyAudio: {system_pyaudio_id}"
)
except Exception as e:
print(f"⚠️ Error setting up audio devices: {e}")
# Initialize processors with SDL device IDs for whisper.cpp
mic_whisper_processor = WhisperStreamProcessor(
callback=on_whisper_transcript,
audio_source="microphone",
audio_device_id=mic_sdl_id, # Use SDL device ID for whisper.cpp
vad_config=vad_settings, # Pass VAD configuration
)
# System audio processor (if system device is available and user didn't explicitly disable)
system_whisper_processor = None
if system_sdl_id is not None and not user_explicitly_disabled_system_audio:
system_whisper_processor = WhisperStreamProcessor(
callback=on_whisper_transcript,
audio_source="system",
audio_device_id=system_sdl_id, # Use SDL device ID for whisper.cpp
vad_config=vad_settings, # Pass VAD configuration
)
print("🔊 System audio transcription enabled")
elif user_explicitly_disabled_system_audio:
print("🔇 System audio transcription disabled (user choice)")
else:
print("⚠️ System audio transcription disabled (no system audio device)")
llm_processor = LLMProcessor(callback=on_llm_result)
# Start recording
session_id = f"session_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
start_time = datetime.now()
recording_state.update(
{
"is_recording": True,
"session_id": session_id,
"start_time": start_time.isoformat(),
}
)
# Create session record in database
create_session_record(session_id, start_time.isoformat())
# Send recording started message via SSE
try:
stream_queue.put(
{
"type": "recording_started",
"session_id": session_id,
"timestamp": datetime.now().isoformat(),
"message": "🎯 Whisper.cpp streaming started! Ready for transcription.",
"processor_type": "whisper_stream",
},
block=False,
)
except queue.Full:
print("⚠️ Stream queue full, dropping message")
# Start whisper.cpp streaming for microphone
mic_success = mic_whisper_processor.start_streaming(session_id)
# Start whisper.cpp streaming for system audio (if available)
system_success = True
if system_whisper_processor:
print(
f"🔧 Attempting to start system audio transcription with SDL device {system_sdl_id}"
)
system_success = system_whisper_processor.start_streaming(session_id)
if system_success:
print("🔊 System audio transcription started successfully")
else:
print("⚠️ System audio transcription failed to start")
if not mic_success:
recording_state["is_recording"] = False
return jsonify(
{
"error": "Failed to start whisper.cpp streaming for microphone",
"message": "Check that whisper.cpp binary and model are available",
}
), 500
# Report status
active_sources = ["microphone"]
if system_success and system_whisper_processor:
active_sources.append("system")
print(f"✅ Active transcription sources: {', '.join(active_sources)}")
# Start audio capture for volume monitoring (separate from whisper.cpp)
try:
audio_capture.start_recording(session_id, callback=on_audio_chunk)
print("🎚️ Audio level monitoring started")
except Exception as e:
print(f"⚠️ Audio level monitoring failed: {e}")
# Don't fail the whole recording if audio monitoring fails
# Start auto-processing timer if enabled
if auto_processing_state["enabled"]:
start_auto_processing_timer()
return jsonify(
{
"success": True,
"session_id": session_id,
"message": "Whisper.cpp streaming started with audio monitoring",
"processor_type": "whisper_stream",
}
)
except Exception as e:
recording_state["is_recording"] = False
return jsonify({"error": str(e)}), 500
@app.route("/api/stop", methods=["POST"])
def stop_recording():
"""Stop whisper.cpp streaming and transcription"""
global \
mic_whisper_processor, \
system_whisper_processor, \
audio_capture, \
recording_state
try:
if not recording_state["is_recording"]:
return jsonify({"error": "Not currently recording"}), 400
session_id = recording_state["session_id"]
# Stop whisper streaming for both sources
stats = {}
if mic_whisper_processor:
mic_stats = mic_whisper_processor.stop_streaming()
stats["microphone"] = mic_stats
if system_whisper_processor:
system_stats = system_whisper_processor.stop_streaming()
stats["system"] = system_stats
print("🔊 System audio transcription stopped")
# Stop audio capture
if audio_capture:
try:
audio_capture.stop_recording()
print("🎚️ Audio level monitoring stopped")
except Exception as e:
print(f"⚠️ Error stopping audio capture: {e}")
# Stop auto-processing timer
stop_auto_processing_timer()
# Process any remaining raw transcripts before stopping
print("📝 Processing any remaining raw transcripts before stopping...")
try:
process_remaining_transcripts_before_stop(session_id)
except Exception as e:
print(f"⚠️ Error processing remaining transcripts: {e}")
# Update state
recording_state.update(
{"is_recording": False, "session_id": None, "start_time": None}
)
# Send recording stopped message via SSE
try:
stream_queue.put(
{
"type": "recording_stopped",
"session_id": session_id,
"timestamp": datetime.now().isoformat(),
"message": "🛑 Whisper.cpp streaming stopped.",
"stats": stats,
},
block=False,
)
except queue.Full:
print("⚠️ Stream queue full, dropping message")
# Update session with end time and duration
end_time = datetime.now()
start_time_str = recording_state.get("start_time")
if start_time_str:
try:
start_time = datetime.fromisoformat(start_time_str)
duration_seconds = int((end_time - start_time).total_seconds())
update_session_end_time(
session_id, end_time.isoformat(), duration_seconds
)
print(
f"📊 Session {session_id} ended. Duration: {duration_seconds} seconds"
)
except Exception as e:
print(f"⚠️ Error calculating session duration: {e}")
update_session_end_time(session_id, end_time.isoformat(), None)
# Calculate and save session quality metrics
calculate_and_save_session_metrics(session_id)
# Mark session as waiting for summary generation after LLM processing completes
print(
"📝 Marking session for summary generation after LLM processing completes..."
)
sessions_waiting_for_summary.add(session_id)
# Check if summary can be generated immediately (if no LLM processing is pending)
check_and_generate_summary_if_ready(session_id)
return jsonify(
{
"success": True,
"message": "Whisper.cpp streaming and audio monitoring stopped",
"session_id": session_id,
"stats": stats,
}
)
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/pause", methods=["POST"])
def pause_recording():
"""Pause whisper.cpp streaming and transcription"""
global mic_whisper_processor, system_whisper_processor, recording_state
try:
if not recording_state["is_recording"]:
return jsonify({"error": "Not currently recording"}), 400
# Pause both whisper processors
results = {}
if mic_whisper_processor:
mic_result = mic_whisper_processor.pause_streaming()
results["microphone"] = mic_result
if system_whisper_processor:
system_result = system_whisper_processor.pause_streaming()
results["system"] = system_result
# Check if any pause operation failed
failed_operations = [
k for k, v in results.items() if not v.get("success", False)
]
if failed_operations:
error_messages = [
f"{k}: {results[k].get('error', 'Unknown error')}"
for k in failed_operations
]
return jsonify(
{
"error": f"Failed to pause: {', '.join(error_messages)}",
"results": results,
}
), 500
# Send pause message via SSE
try:
stream_queue.put(
{
"type": "recording_paused",
"session_id": recording_state["session_id"],
"timestamp": datetime.now().isoformat(),
"message": "⏸️ Recording paused",
},
block=False,
)
except queue.Full:
print("⚠️ Stream queue full, dropping pause message")
return jsonify(
{"success": True, "message": "Recording paused", "results": results}
)
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/resume", methods=["POST"])
def resume_recording():
"""Resume whisper.cpp streaming and transcription"""
global mic_whisper_processor, system_whisper_processor, recording_state
try:
if not recording_state["is_recording"]:
return jsonify({"error": "Not currently recording"}), 400
# Resume both whisper processors
results = {}
if mic_whisper_processor:
mic_result = mic_whisper_processor.resume_streaming()
results["microphone"] = mic_result
if system_whisper_processor:
system_result = system_whisper_processor.resume_streaming()
results["system"] = system_result
# Check if any resume operation failed
failed_operations = [
k for k, v in results.items() if not v.get("success", False)
]
if failed_operations:
error_messages = [
f"{k}: {results[k].get('error', 'Unknown error')}"
for k in failed_operations
]
return jsonify(
{
"error": f"Failed to resume: {', '.join(error_messages)}",
"results": results,
}
), 500
# Send resume message via SSE
try:
stream_queue.put(
{
"type": "recording_resumed",
"session_id": recording_state["session_id"],
"timestamp": datetime.now().isoformat(),
"message": "▶️ Recording resumed",
},
block=False,
)
except queue.Full:
print("⚠️ Stream queue full, dropping resume message")
return jsonify(
{"success": True, "message": "Recording resumed", "results": results}
)
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/status", methods=["GET"])
def get_recording_status():
"""Get current recording and pause status"""
global mic_whisper_processor, system_whisper_processor, recording_state
try:
status = {
"is_recording": recording_state["is_recording"],
"session_id": recording_state.get("session_id"),
"start_time": recording_state.get("start_time"),
}
# Add pause status if recording
if recording_state["is_recording"]:
mic_status = (
mic_whisper_processor.get_streaming_status()
if mic_whisper_processor
else {}
)
system_status = (
system_whisper_processor.get_streaming_status()
if system_whisper_processor
else {}
)
status.update(
{
"microphone": mic_status,
"system": system_status,
"is_paused": mic_status.get("is_paused", False)
or system_status.get("is_paused", False),
}
)
return jsonify(status)
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/api/sessions")
def get_sessions():
"""Get list of recording sessions with transcript counts"""
try:
# Get query parameters
bookmarked_filter = request.args.get("bookmarked")
conn = sqlite3.connect("transcripts.db")
cursor = conn.cursor()
# Get all sessions from raw_transcripts (for backward compatibility)
cursor.execute(
"""
SELECT
session_id,
COUNT(*) as raw_transcript_count,
MIN(timestamp) as transcript_start_time,
MAX(timestamp) as transcript_end_time,
COUNT(DISTINCT audio_source) as audio_sources
FROM raw_transcripts
GROUP BY session_id
"""
)
transcript_sessions = {row[0]: row for row in cursor.fetchall()}
# Get session records from sessions table (preferred source)
cursor.execute(
"""