-
-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathsimple_recorder.py
More file actions
2554 lines (2150 loc) · 95.7 KB
/
simple_recorder.py
File metadata and controls
2554 lines (2150 loc) · 95.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
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
"""
Simple Audio Recorder & Transcriber for Electron App
Backend script that handles:
1. Recording system/microphone audio
2. Transcribing with Whisper
3. Summarizing with Ollama
4. Saving everything locally
Usage (called by Electron):
python simple_recorder.py start "Meeting Name"
python simple_recorder.py stop
python simple_recorder.py process recording.wav --name "Session"
python simple_recorder.py status
"""
import click
import asyncio
import logging
import json
import re
import sys
import time
from datetime import datetime
from pathlib import Path
from typing import Optional
# Import modules with graceful fallback for missing dependencies
try:
from src.audio_recorder import AudioRecorder
except ImportError:
AudioRecorder = None
try:
from src.transcriber import WhisperTranscriber
except ImportError:
WhisperTranscriber = None
try:
from src.summarizer import OllamaSummarizer
except ImportError:
OllamaSummarizer = None
# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class SimpleRecorder:
"""Simple audio recorder and transcriber."""
def __init__(self):
# Only initialize if dependencies are available
self.audio_recorder = AudioRecorder() if AudioRecorder else None
# Only initialize transcriber/summarizer when needed to save memory
self.transcriber = None
self.summarizer = None
# Directories - centralised via get_data_dirs()
from src.config import get_data_dirs
dirs = get_data_dirs()
self.recordings_dir = dirs["recordings"]
self.transcripts_dir = dirs["transcripts"]
self.output_dir = dirs["output"]
# State file
self.state_file = Path("recorder_state.json")
# Global AudioRecorder instance to maintain state across CLI calls
self.persistent_recorder = None
def get_state(self) -> dict:
"""Get current recorder state."""
if self.state_file.exists():
try:
with open(self.state_file, 'r') as f:
return json.load(f)
except:
pass
return {"recording": False, "current_file": None, "session_name": None}
def save_state(self, state: dict):
"""Save recorder state."""
with open(self.state_file, 'w') as f:
json.dump(state, f, indent=2)
def _resolve_output_language(self, configured_language: str, detected_language: Optional[str] = None) -> str:
"""Resolve which language should be used for summary/title/query output."""
from src.config import get_config
if configured_language != "auto":
return configured_language
if detected_language:
return detected_language
return "en"
@staticmethod
def _load_user_notes(session_name: str, output_dir) -> Optional[str]:
"""Load user notes file saved by Electron during recording."""
safe_name = re.sub(r'[^a-zA-Z0-9_-]', '_', session_name)
for candidate in [
Path(output_dir) / f"{safe_name}_notes.txt",
Path(output_dir) / f"{session_name}_notes.txt",
]:
if candidate.exists():
try:
text = candidate.read_text(encoding='utf-8').strip()
if text:
logger.info(f"Loaded user notes ({len(text)} chars)")
return text
except Exception:
pass
break
return None
@staticmethod
def _parse_streamed_markdown(md_text: str) -> dict:
"""Parse streamed markdown summary into structured fields."""
summary_parts = []
participants = []
discussion_areas = []
key_points = []
action_items = []
current_section = None
current_topic_title = None
current_topic_lines = []
for line in md_text.split('\n'):
stripped = line.strip()
if stripped.startswith('## Summary'):
current_section = 'summary'
elif stripped.startswith('## Participants'):
current_section = 'participants'
elif stripped.startswith('## Key Topics'):
current_section = 'topics'
elif stripped.startswith('## Key Points'):
current_section = 'keypoints'
elif stripped.startswith('## Action Items'):
current_section = 'actions'
elif stripped.startswith('### ') and current_section == 'topics':
if current_topic_title:
discussion_areas.append({"title": current_topic_title, "analysis": '\n'.join(current_topic_lines).strip()})
current_topic_title = stripped[4:]
current_topic_lines = []
elif current_section == 'summary' and stripped:
summary_parts.append(stripped)
elif current_section == 'participants' and stripped:
participants.extend([p.strip() for p in stripped.split(',') if p.strip()])
elif current_section == 'topics' and current_topic_title:
current_topic_lines.append(stripped)
elif current_section == 'keypoints' and stripped.startswith('- '):
key_points.append(stripped[2:])
elif current_section == 'actions' and stripped.startswith('- '):
action_items.append(stripped[2:].replace('[ ] ', '').replace('[x] ', ''))
if current_topic_title:
discussion_areas.append({"title": current_topic_title, "analysis": '\n'.join(current_topic_lines).strip()})
return {
"summary": ' '.join(summary_parts),
"participants": participants,
"discussion_areas": discussion_areas,
"key_points": key_points,
"action_items": action_items,
}
def start_recording(self, session_name: str = "Recording") -> str:
"""Start recording audio."""
state = self.get_state()
if state.get("recording"):
raise Exception(f"Already recording: {state.get('current_file', 'unknown file')}")
# Create filename
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
safe_name = "".join(c for c in session_name if c.isalnum() or c in (' ', '-', '_')).strip()
filename = f"{timestamp}_{safe_name}.wav"
recording_path = self.recordings_dir / filename
print(f"🎤 Starting recording: {session_name}")
print(f"📁 File: {recording_path}")
# Start recording
self.audio_recorder.start_recording()
# Update state
new_state = {
"recording": True,
"current_file": str(recording_path),
"session_name": session_name,
"start_time": datetime.now().isoformat()
}
self.save_state(new_state)
return str(recording_path)
def stop_recording(self) -> Optional[str]:
"""Stop current recording."""
state = self.get_state()
if not state.get("recording"):
print("⚠️ No active recording to stop")
return None
print("🔴 Stopping recording")
# Stop recording
self.audio_recorder.stop_recording()
# Wait a moment for recording to fully stop
import time
time.sleep(0.5)
# Get the planned file path from state
recording_path = state.get("current_file")
if not recording_path:
print("⚠️ No recording file path found in state")
# Try to create a default path
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
recording_path = str(self.recordings_dir / f"{timestamp}_recording.wav")
# Save the recording to the planned file
from pathlib import Path
if self.audio_recorder.save_recording(Path(recording_path)):
print(f"✅ Recording saved: {recording_path}")
else:
print("❌ Failed to save recording")
recording_path = None
# Update state (always clear recording state)
new_state = {
"recording": False,
"current_file": None,
"session_name": None,
"stop_time": datetime.now().isoformat()
}
if recording_path:
new_state["last_recording"] = recording_path
self.save_state(new_state)
return recording_path
async def transcribe_audio(self, audio_file: str, session_name: str = "Recording") -> dict:
"""Transcribe audio file."""
audio_path = Path(audio_file)
if not audio_path.exists():
raise FileNotFoundError(f"Audio file not found: {audio_file}")
print(f"📝 Transcribing: {audio_path.name}")
# Initialize transcriber only when needed
if self.transcriber is None:
self.transcriber = WhisperTranscriber()
# Get configured language
from src.config import get_config
config = get_config()
configured_language = config.get_language()
# Transcribe with diarisation support (stereo → [You]/[Others])
transcript_result = self.transcriber.transcribe_diarised(audio_path, language=configured_language)
# Handle different return types
duration_seconds = None
detected_language = None
if isinstance(transcript_result, dict):
transcript_text = transcript_result.get("text") or ""
duration_seconds = transcript_result.get("duration_seconds")
detected_language = transcript_result.get("detected_language")
elif hasattr(transcript_result, 'text'):
transcript_text = transcript_result.text
elif isinstance(transcript_result, str):
transcript_text = transcript_result
else:
transcript_text = str(transcript_result)
# Extract diarisation fields
is_diarised = False
diarised_text = None
if isinstance(transcript_result, dict):
is_diarised = transcript_result.get("is_diarised", False)
diarised_text = transcript_result.get("diarised_text")
output_language = self._resolve_output_language(configured_language, detected_language)
detected_language_name = config.get_language_name(detected_language) if detected_language else "Unknown"
# Save transcript (use diarised text if available for the saved file)
transcript_path = self.transcripts_dir / f"{audio_path.stem}_transcript.txt"
saved_transcript = diarised_text if diarised_text else transcript_text
transcript_content = f"""Session: {session_name}
File: {audio_path.name}
Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
Language setting: {config.get_language_name(configured_language)}
Detected language: {detected_language_name}
Summary output language: {config.get_language_name(output_language)}
{'='*60}
{saved_transcript}
"""
with open(transcript_path, 'w') as f:
f.write(transcript_content)
print(f"📄 Transcript saved: {transcript_path}")
return {
"audio_file": str(audio_path),
"transcript_file": str(transcript_path),
"transcript_text": transcript_text,
"session_name": session_name,
"duration_seconds": duration_seconds,
"configured_language": configured_language,
"detected_language": detected_language,
"is_diarised": is_diarised,
"diarised_text": diarised_text,
"output_language": output_language,
}
async def summarize_transcript(
self,
transcript_text: str,
session_name: str = "Recording",
duration_minutes: int = 10,
language: Optional[str] = None,
notes_text: Optional[str] = None
) -> dict:
"""Summarize transcript text."""
print("🧠 Generating summary...")
# Initialize summarizer only when needed
if self.summarizer is None:
self.summarizer = OllamaSummarizer()
# Create summary prompt
prompt = f"""
Please analyze and summarize this audio transcript from a recording session.
Session: {session_name}
Please provide:
1. Brief overview of the content
2. Key points discussed
3. Important decisions or conclusions
4. Action items (if any)
5. Notable quotes or insights
Transcript:
{transcript_text}
"""
# Resolve output language
from src.config import get_config
if language is None:
configured_language = get_config().get_language()
language = self._resolve_output_language(configured_language)
# Generate summary (using correct method name and parameters)
summary_result = self.summarizer.summarize_transcript(transcript_text, duration_minutes, language=language, notes=notes_text)
if summary_result is None:
return {
"summary": "Failed to generate summary",
"participants": [],
"discussion_areas": [],
"key_points": [],
"action_items": []
}
# Defensive extraction from summary_result
try:
return {
"summary": getattr(summary_result, 'overview', '') or '',
"participants": getattr(summary_result, 'participants', []) or [],
"discussion_areas": [
{
"title": getattr(area, 'title', ''),
"analysis": getattr(area, 'analysis', '')
} for area in getattr(summary_result, 'discussion_areas', [])
],
"key_points": [getattr(decision, 'decision', '') for decision in getattr(summary_result, 'key_points', [])],
"action_items": [getattr(action, 'description', '') for action in getattr(summary_result, 'next_steps', [])]
}
except Exception as e:
print(f"⚠️ Error extracting summary data: {e}")
return {
"summary": "Summary extraction failed",
"participants": [],
"discussion_areas": [],
"key_points": [],
"action_items": []
}
async def process_recording(self, audio_file: str, session_name: str = "Recording", notes_text: Optional[str] = None) -> dict:
"""Complete processing: transcribe + summarize."""
print(f"🔄 Processing recording: {audio_file}")
# If no audio file provided, use the last recording
if not audio_file:
state = self.get_state()
audio_file = state.get("last_recording")
if not audio_file:
raise Exception("No audio file specified and no recent recording found")
# Ensure we have a proper path
audio_file = str(audio_file) # Convert to string if it's a Path object
audio_path = Path(audio_file)
# Step 1: Transcribe (also returns duration from the converted WAV)
transcript_data = await self.transcribe_audio(audio_file, session_name)
# Determine duration: use transcriber's value (works for all formats)
duration_seconds = transcript_data.get("duration_seconds")
if duration_seconds is not None:
if duration_seconds < 60:
duration_minutes = 0
print(f"📏 Audio duration: {duration_seconds:.1f} seconds ({int(duration_seconds)}s)")
else:
duration_minutes = int(duration_seconds / 60)
print(f"📏 Audio duration: {duration_seconds:.1f} seconds ({duration_minutes}m)")
else:
duration_minutes = 0
print("⚠️ Could not determine audio duration")
# Step 2: Summarize — prefer diarised text so LLM sees speaker labels
text_for_summary = transcript_data.get("diarised_text") or transcript_data["transcript_text"]
summary_data = await self.summarize_transcript(
text_for_summary,
session_name,
duration_minutes,
language=transcript_data.get("output_language"),
notes_text=notes_text
)
# Step 2b: Auto-generate title for auto-named meetings
if re.match(r'^(Meeting|Note)-[A-Z0-9]{6}$', session_name):
try:
language = transcript_data.get("output_language")
generated_title = self.summarizer.generate_title(
summary_data.get("summary", ""),
transcript_data["transcript_text"],
language=language
)
if generated_title:
print(f"Auto-generated title: {generated_title}")
session_name = generated_title
except Exception as e:
print(f"Title generation skipped: {e}")
# Step 3: Save complete summary
summary_path = self.output_dir / f"{audio_path.stem}_summary.json"
complete_data = {
"session_info": {
"name": session_name,
"audio_file": str(audio_path),
"transcript_file": transcript_data["transcript_file"],
"summary_file": str(summary_path),
"processed_at": datetime.now().isoformat(),
"duration_seconds": int(duration_seconds) if duration_seconds is not None else None,
"duration_minutes": duration_minutes,
"configured_language": transcript_data.get("configured_language"),
"detected_language": transcript_data.get("detected_language"),
"output_language": transcript_data.get("output_language"),
},
"summary": summary_data.get("summary", "") or "",
"participants": summary_data.get("participants", []) or [],
"discussion_areas": summary_data.get("discussion_areas", []) or [],
"key_points": summary_data.get("key_points", []) or [],
"action_items": summary_data.get("action_items", []) or [],
"transcript": transcript_data["transcript_text"],
"is_diarised": transcript_data.get("is_diarised", False),
"diarised_text": transcript_data.get("diarised_text"),
"user_notes": notes_text,
}
with open(summary_path, 'w') as f:
json.dump(complete_data, f, indent=2)
print(f"✅ Complete processing saved: {summary_path}")
# Clean up WAV file after successful processing
try:
audio_path.unlink()
print(f"🗑️ Cleaned up audio file: {audio_path}")
except Exception as e:
print(f"⚠️ Could not delete audio file: {e}")
# Clear any recording state after successful processing
state_file = Path("recorder_state.json")
if state_file.exists():
try:
state_file.unlink()
print(f"🧹 Cleared recording state")
except Exception as e:
print(f"⚠️ Could not clear state: {e}")
print(f"📋 Processing complete - meeting available in list")
return complete_data
async def process_recording_streaming(self, audio_file: str, session_name: str = "Recording", notes_text: Optional[str] = None) -> dict:
"""Process recording with streaming summary output via CHUNK: protocol."""
import base64
print(f"🔄 Processing recording: {audio_file}")
if not audio_file:
state = self.get_state()
audio_file = state.get("last_recording")
if not audio_file:
raise Exception("No audio file specified and no recent recording found")
audio_path = Path(audio_file)
if not audio_path.exists():
raise Exception(f"Audio file not found: {audio_file}")
# Step 1: Transcribe
transcript_data = await self.transcribe_audio(audio_file, session_name)
transcript_text = transcript_data.get("transcript_text", "")
diarised_text = transcript_data.get("diarised_text")
text_for_summary = diarised_text or transcript_text
duration_seconds = transcript_data.get("duration_seconds")
duration_minutes = int(duration_seconds / 60) if duration_seconds else 0
if duration_seconds:
print(f"📏 Audio duration: {duration_seconds} seconds ({int(duration_seconds)}s)")
print(f"TRANSCRIPTION_COMPLETE:{len(transcript_text)}", flush=True)
# Step 2: Streaming summary
if self.summarizer is None:
self.summarizer = OllamaSummarizer()
from src.config import get_config
config = get_config()
configured_language = config.get_language()
output_language = self._resolve_output_language(
configured_language, transcript_data.get("detected_language")
)
print("🧠 Generating summary...", flush=True)
streamed_chunks = []
for chunk in self.summarizer.summarize_transcript_streaming(
text_for_summary, duration_minutes, output_language, notes_text
):
encoded = base64.b64encode(chunk.encode('utf-8')).decode('ascii')
sys.stdout.write(f"CHUNK:{encoded}\n")
sys.stdout.flush()
streamed_chunks.append(chunk)
streamed_md = ''.join(streamed_chunks)
print("STREAM_COMPLETE", flush=True)
# Step 3: Generate title
if re.match(r'^(Meeting|Note)-[A-Z0-9]{6}$', session_name):
try:
generated_title = self.summarizer.generate_title(
streamed_md, transcript_text, language=output_language
)
if generated_title:
session_name = generated_title
print(f"TITLE:{session_name}", flush=True)
print(f"Auto-generated title: {session_name}")
except Exception as e:
logger.warning(f"Title generation failed: {e}")
# Step 4: Parse streamed markdown into structured JSON
parsed = self._parse_streamed_markdown(streamed_md)
# Step 5: Save as .md (primary format for new meetings)
summary_path = self.output_dir / f"{audio_path.stem}_summary.md"
processed_at = datetime.now().isoformat()
md_lines = ['---']
md_meta = {
'title': session_name,
'date': processed_at,
'duration_seconds': int(duration_seconds) if duration_seconds else None,
'language': output_language,
'is_diarised': transcript_data.get('is_diarised', False),
}
for k, v in md_meta.items():
if v is None:
md_lines.append(f'{k}: null')
elif isinstance(v, bool):
md_lines.append(f'{k}: {"true" if v else "false"}')
elif isinstance(v, int):
md_lines.append(f'{k}: {v}')
else:
escaped = str(v).replace('\\', '\\\\').replace('"', '\\"')
md_lines.append(f'{k}: "{escaped}"')
md_lines.append('---')
md_lines.append('')
md_lines.append(streamed_md)
md_lines.append('')
md_lines.append('## Transcript')
md_lines.append('')
md_lines.append(diarised_text or transcript_text)
if notes_text:
md_lines.append('')
md_lines.append('## User Notes')
md_lines.append('')
md_lines.append(notes_text)
summary_path.write_text('\n'.join(md_lines), encoding='utf-8')
# Clean up
try:
audio_path.unlink()
print(f"🗑️ Cleaned up audio file: {audio_path}")
except Exception:
pass
state_file = Path("recorder_state.json")
if state_file.exists():
try:
state_file.unlink()
except Exception:
pass
print(f"✅ Complete processing saved: {summary_path}")
print(f"SAVED:{summary_path}", flush=True)
return {
"session_info": {
"name": session_name,
"transcript_file": str(transcript_data.get("transcript_file", "")),
"summary_file": str(summary_path),
}
}
# CLI Commands for Electron
@click.group()
def cli():
"""Simple Audio Recorder & Transcriber Backend"""
pass
@cli.command()
@click.argument('session_name', default='Recording')
def start(session_name):
"""Start recording audio (stop with Ctrl+C to auto-process)"""
import signal
import time
recorder = SimpleRecorder()
recording_path = None
recording_started = False
processing_started = False
def signal_handler(signum, frame):
"""Handle SIGTERM/SIGINT gracefully by stopping recording and processing"""
nonlocal processing_started
# Different handling for different signals
signal_name = "SIGINT" if signum == 2 else f"SIGTERM" if signum == 15 else f"Signal {signum}"
print(f"\n🛑 Received {signal_name} - stopping recording and processing...")
# Prevent double processing if multiple signals received
if processing_started:
print("⚠️ Processing already started - please wait for completion...")
if signum == 15: # SIGTERM - ignore it during processing
print("🔄 Ignoring SIGTERM during transcription/summarization")
return
sys.exit(0)
if recording_started and recorder:
processing_started = True
try:
final_path = recorder.stop_recording()
if final_path:
print(f"✅ Recording saved: {final_path}")
# Check file size
from pathlib import Path
file_size = Path(final_path).stat().st_size
print(f"📏 File size: {file_size / 1024:.1f} KB")
if file_size >= 1000: # At least 1KB of audio data
print("🔄 Starting transcription and summarization pipeline...")
# Process recording with proper async handling
try:
import asyncio
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
_notes_text = recorder._load_user_notes(session_name, recorder.output_dir)
print("📝 Starting transcription...")
result = loop.run_until_complete(recorder.process_recording_streaming(final_path, session_name, notes_text=_notes_text))
print("✅ Complete processing finished!", flush=True)
print(f"📄 Transcript: {result['session_info']['transcript_file']}")
print(f"📋 Summary: {result['session_info']['summary_file']}")
print(f"📊 Meeting: {result['session_info']['name']}")
except Exception as e:
print(f"❌ Processing pipeline failed: {e}", flush=True)
import traceback
traceback.print_exc()
else:
print("⚠️ Recording too short - skipping processing")
else:
print("❌ No recording data to save")
except Exception as e:
print(f"❌ Error during signal handling: {e}")
import traceback
traceback.print_exc()
print("🏁 Recording session ended")
sys.exit(0)
# Register signal handlers for graceful shutdown
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
try:
recording_path = recorder.start_recording(session_name)
recording_started = True
print(f"🎤 Recording '{session_name}' - Press Ctrl+C to stop and process")
print(f"📁 File: {recording_path}")
print("📢 Speak now...")
# Wait indefinitely until interrupted
while True:
time.sleep(1)
except Exception as e:
print(f"ERROR: {e}")
sys.exit(1)
@cli.command()
def stop():
"""Stop current recording and trigger processing"""
import subprocess
import signal
import os
import time
# First check if there's a recording process running
try:
# Find running start processes
result = subprocess.run(
['pgrep', '-f', 'simple_recorder.py start'],
capture_output=True,
text=True
)
if result.returncode == 0 and result.stdout.strip():
pids = result.stdout.strip().split('\n')
print(f"🔍 Found {len(pids)} recording process(es)")
for pid in pids:
if pid.strip():
try:
pid_int = int(pid.strip())
print(f"🛑 Sending SIGINT to recording process (PID: {pid_int})")
os.kill(pid_int, signal.SIGINT)
print(f"✅ Stop signal sent to process {pid_int}")
print(f"🔄 Recording will stop and processing will begin automatically")
print(f"💡 Processing may take a few minutes - check output files when complete")
except (ValueError, ProcessLookupError) as e:
print(f"⚠️ Could not signal process {pid}: {e}")
print("✅ Stop signal sent - recording will be processed automatically")
else:
# Fallback to old method if no start process found
print("🔍 No start process found, checking recording state...")
recorder = SimpleRecorder()
state = recorder.get_state()
if state.get("recording"):
print("⚠️ Recording state shows active but no process found")
print("🔧 Clearing stuck state...")
recorder.save_state({
"recording": False,
"current_file": None,
"session_name": None
})
print("✅ State cleared")
else:
print("ℹ️ No active recording found")
except Exception as e:
print(f"ERROR: {e}")
sys.exit(1)
@cli.command()
@click.argument('audio_file', default='')
@click.option('--name', '-n', default='Recording', help='Session name for the recording')
@click.option('--notes', default=None, help='Path to user notes file')
def process(audio_file, name, notes):
"""Process audio file: transcribe + summarize"""
async def run_process():
recorder = SimpleRecorder()
# Read user notes if provided
notes_text = None
if notes:
try:
notes_text = Path(notes).read_text(encoding='utf-8').strip()
if notes_text:
logger.info(f"Loaded user notes ({len(notes_text)} chars)")
except Exception as e:
logger.warning(f"Failed to read notes file: {e}")
try:
result = await recorder.process_recording(audio_file, name, notes_text=notes_text)
print("SUCCESS: Processing complete!")
print(f"Transcript: {result['session_info']['transcript_file']}")
print(f"Summary: {result['session_info']['summary_file']}")
except Exception as e:
print(f"ERROR: {e}")
sys.exit(1)
asyncio.run(run_process())
@cli.command(name='process-streaming')
@click.argument('audio_file', default='')
@click.option('--name', '-n', default='Recording', help='Session name')
@click.option('--notes', default=None, help='Path to user notes file')
def process_streaming(audio_file, name, notes):
"""Process audio with streaming summary output.
Transcribes audio, then streams the summary as CHUNK: prefixed lines
to stdout for Electron to relay to the renderer in real time.
"""
import sys
async def run():
recorder = SimpleRecorder()
# Read user notes
notes_text = None
if notes:
try:
notes_text = Path(notes).read_text(encoding='utf-8').strip()
if notes_text:
logger.info(f"Loaded user notes ({len(notes_text)} chars)")
except Exception as e:
logger.warning(f"Failed to read notes file: {e}")
# Step 1: Transcribe
transcript_data = await recorder.transcribe_audio(audio_file, name)
transcript_text = transcript_data.get("transcript_text", "")
diarised_text = transcript_data.get("diarised_text")
text_for_summary = diarised_text or transcript_text
duration_seconds = transcript_data.get("duration_seconds")
duration_minutes = int(duration_seconds / 60) if duration_seconds else 0
print(f"TRANSCRIPTION_COMPLETE:{len(transcript_text)}", flush=True)
# Step 2: Stream summary
if recorder.summarizer is None:
recorder.summarizer = OllamaSummarizer()
from src.config import get_config
config = get_config()
configured_language = config.get_language()
output_language = recorder._resolve_output_language(
configured_language, transcript_data.get("detected_language")
)
import base64
streamed_chunks = []
for chunk in recorder.summarizer.summarize_transcript_streaming(
text_for_summary, duration_minutes, output_language, notes_text
):
encoded = base64.b64encode(chunk.encode('utf-8')).decode('ascii')
sys.stdout.write(f"CHUNK:{encoded}\n")
sys.stdout.flush()
streamed_chunks.append(chunk)
streamed_md = ''.join(streamed_chunks)
print("STREAM_COMPLETE", flush=True)
# Step 3: Generate title
session_name = name
if re.match(r'^(Meeting|Note)-[A-Z0-9]{6}$', name):
try:
generated_title = recorder.summarizer.generate_title(
streamed_md, transcript_text, language=output_language
)
if generated_title:
session_name = generated_title
print(f"TITLE:{session_name}", flush=True)
except Exception as e:
logger.warning(f"Title generation failed: {e}")
# Step 4: Save as .md
audio_path = Path(audio_file)
summary_path = recorder.output_dir / f"{audio_path.stem}_summary.md"
# Parse the streamed markdown for title generation
parsed = SimpleRecorder._parse_streamed_markdown(streamed_md)
# Save as .md only (primary format for new meetings)
summary_path = summary_path.with_suffix('.md')
processed_at = datetime.now().isoformat()
md_lines = ['---']
md_meta = {
'title': session_name,
'date': processed_at,
'duration_seconds': int(duration_seconds) if duration_seconds else None,
'language': output_language,
'is_diarised': transcript_data.get('is_diarised', False),
}
for k, v in md_meta.items():
if v is None:
md_lines.append(f'{k}: null')
elif isinstance(v, bool):
md_lines.append(f'{k}: {"true" if v else "false"}')
elif isinstance(v, int):
md_lines.append(f'{k}: {v}')
else:
escaped = str(v).replace('\\', '\\\\').replace('"', '\\"')
md_lines.append(f'{k}: "{escaped}"')
md_lines.append('---')
md_lines.append('')
md_lines.append(streamed_md)
md_lines.append('')
md_lines.append('## Transcript')
md_lines.append('')
md_lines.append(diarised_text or transcript_text)
if notes_text:
md_lines.append('')
md_lines.append('## User Notes')
md_lines.append('')
md_lines.append(notes_text)
summary_path.write_text('\n'.join(md_lines), encoding='utf-8')
# Clean up audio
try:
audio_path.unlink()
except Exception:
pass
print(f"SAVED:{summary_path}", flush=True)
asyncio.run(run())
@cli.command()
def status():
"""Show recorder status"""
recorder = SimpleRecorder()
state = recorder.get_state()
print("🎙️ Steno Recorder Status")
print("=" * 25)
if state.get("recording"):
print("STATUS: RECORDING")
print(f"Session: {state.get('session_name')}")
print(f"File: {state.get('current_file')}")
print(f"Started: {state.get('start_time')}")
else:
print("STATUS: READY")
# Show recent recordings
recordings = list(recorder.recordings_dir.glob("*.wav"))
if recordings:
recent = sorted(recordings, key=lambda x: x.stat().st_mtime, reverse=True)[:3]
print(f"\nRecent recordings ({len(recordings)} total):")
for recording in recent:
size_mb = recording.stat().st_size / (1024 * 1024)
print(f" • {recording.name} ({size_mb:.1f}MB)")
@cli.command()
@click.argument('duration', type=int, default=10)
@click.argument('session_name', default='Recording')
def record(duration, session_name):
"""Record audio for specified duration and process it"""
import signal
import sys
print(f"🎤 Recording {duration} seconds of audio for '{session_name}'...")
recorder = SimpleRecorder()
recording_path = None
recording_started = False
is_paused = False
def pause_handler(signum, frame):
"""Handle SIGUSR1 to pause recording"""
nonlocal is_paused