stt-cli 0.2.1

Speech to text Cli using Groq API and OpenAI API
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
# Instructions for Restructuring the Codebase into Library and CLI Components

To create better separation of concerns, we'll restructure the codebase into a library component for core functionality and a CLI application that uses this library. This approach improves maintainability, testability, and allows for potential future interfaces beyond the CLI.

## Proposed File Structure

```
audio-transcription/
├── Cargo.toml                 # Main workspace manifest
├── .gitignore
├── README.md
├── crates/
│   ├── audio-transcription/   # Core library crate
│   │   ├── Cargo.toml         # Library dependencies
│   │   └── src/
│   │       ├── lib.rs         # Main library exports
│   │       ├── audio/         # Audio processing components
│   │       │   ├── mod.rs
│   │       │   ├── buffer.rs  # AudioBuffer implementation
│   │       │   ├── device.rs  # Device management
│   │       │   └── stream.rs  # Audio stream handling
│   │       ├── hotkey/        # Hotkey handling
│   │       │   ├── mod.rs
│   │       │   └── service.rs # Hotkey service implementation
│   │       ├── state/         # State management
│   │       │   ├── mod.rs
│   │       │   └── recording.rs # Recording state implementation
│   │       ├── transcription/ # Transcription services
│   │       │   ├── mod.rs
│   │       │   └── providers/ # Provider implementations
│   │       │       ├── mod.rs
│   │       │       ├── openai.rs
│   │       │       ├── groq.rs
│   │       │       └── mock.rs
│   │       └── util/          # Utility functions
│   │           ├── mod.rs
│   │           └── tracing.rs # Tracing setup
│   └── audio-transcription-cli/ # CLI application crate
│       ├── Cargo.toml         # CLI-specific dependencies
│       └── src/
│           ├── main.rs        # CLI entry point
│           ├── cli/           # CLI-specific code
│           │   ├── mod.rs
│           │   ├── args.rs    # Command-line argument parsing
│           │   └── ui.rs      # User interface functions
│           └── tasks/         # Long-running tasks for CLI
│               ├── mod.rs
│               ├── device_monitor.rs
│               └── provider_manager.rs
└── examples/                  # Example usage scripts
    └── simple_transcription.rs
```

## Implementation Instructions

### 1. Set Up the Workspace Structure

First, create a workspace Cargo.toml:

```toml
[workspace]
members = [
    "crates/audio-transcription",
    "crates/audio-transcription-cli"
]
resolver = "2"
```

### 2. Create the Core Library Crate

Set up the library crate's Cargo.toml:

```toml
[package]
name = "audio-transcription"
version = "0.1.0"
edition = "2021"

[dependencies]
anyhow = "1.0"
async-trait = "0.1"
cpal = "0.15"
futures = "0.3"
hound = "3.5"
tokio = { version = "1", features = ["full"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing-appender = "0.2"
global-hotkey = "0.3"
```

### 3. Create the CLI Crate

Set up the CLI crate's Cargo.toml:

```toml
[package]
name = "audio-transcription-cli"
version = "0.1.0"
edition = "2021"

[dependencies]
audio-transcription = { path = "../audio-transcription" }
anyhow = "1.0"
clap = { version = "4.3", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
tracing = "0.1"
```

### 4. Implementation Steps

#### Step 1: Create Core Library Components

1. **Move Core Functionality to Library**:
   - Begin by extracting the `AudioBuffer`, `RecordingState`, and provider traits to the library.
   - Create a public API in lib.rs that exposes only what's needed by clients.

2. **Define Clean Interfaces**:
   - Design clear interfaces for audio recording, transcription, and hotkey management.
   - Use dependency injection to allow for flexible component configuration.

#### Step 2: Implement State Management

Create `state/recording.rs` with the `RecordingState` implementation:

```rust
// audio-transcription/src/state/recording.rs

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

/// Manages the recording active/inactive state
#[derive(Debug, Clone)]
pub struct RecordingState {
    active: Arc<AtomicBool>,
}

impl RecordingState {
    pub fn new(initially_active: bool) -> Self {
        Self {
            active: Arc<AtomicBool::new(initially_active)),
        }
    }
    
    pub fn is_active(&self) -> bool {
        self.active.load(Ordering::SeqCst)
    }
    
    pub fn set_active(&self, active: bool) {
        self.active.store(active, Ordering::SeqCst);
    }
    
    pub fn toggle(&self) -> bool {
        let previous = self.active.fetch_xor(true, Ordering::SeqCst);
        !previous
    }
}
```

#### Step 3: Implement Audio Components

Create the `audio/buffer.rs` file:

```rust
// audio-transcription/src/audio/buffer.rs

use crate::state::recording::RecordingState;
use std::sync::{Arc, Mutex};

pub const SAMPLE_RATE: u32 = 16000;
pub const CHANNELS: u16 = 1;
pub const CHUNK_DURATION_MS: u64 = 5000;
pub const CHUNK_SIZE: usize = (SAMPLE_RATE as usize * CHANNELS as usize) * (CHUNK_DURATION_MS as usize) / 1000;

#[derive(Debug)]
pub struct AudioBuffer {
    samples: Vec<f32>,
    recording_state: RecordingState,
}

impl AudioBuffer {
    pub fn new(recording_state: RecordingState) -> Self {
        Self {
            samples: Vec::with_capacity(CHUNK_SIZE * 2),
            recording_state,
        }
    }
    
    pub fn add_samples(&mut self, samples: &[f32]) {
        if self.recording_state.is_active() {
            self.samples.extend_from_slice(samples);
        }
    }
    
    pub fn samples_len(&self) -> usize {
        self.samples.len()
    }
    
    pub fn drain_samples(&mut self, count: usize) -> Vec<f32> {
        let count = std::cmp::min(count, self.samples.len());
        self.samples.drain(..count).collect()
    }
    
    pub fn clear(&mut self) {
        self.samples.clear();
    }
}

pub type SharedAudioBuffer = Arc<Mutex<AudioBuffer>>;

pub fn create_shared_buffer(recording_state: RecordingState) -> SharedAudioBuffer {
    Arc::new(Mutex::new(AudioBuffer::new(recording_state)))
}
```

#### Step 4: Implement the Transcription Provider System

Create the provider trait in `transcription/providers/mod.rs`:

```rust
// audio-transcription/src/transcription/providers/mod.rs

use anyhow::Result;
use async_trait::async_trait;

pub mod openai;
pub mod groq;
pub mod mock;

#[async_trait]
pub trait TranscriptionProvider {
    fn name(&self) -> &'static str;
    async fn transcribe(&self, audio_data: &[u8]) -> Result<String>;
}

pub fn create_provider(provider_name: &str) -> Box<dyn TranscriptionProvider + Send + Sync> {
    match provider_name.to_lowercase().as_str() {
        "openai" => Box::new(openai::OpenAIProvider::new()),
        "groq" => Box::new(groq::GroqProvider::new()),
        "mock" => Box::new(mock::MockProvider::new()),
        _ => Box::new(openai::OpenAIProvider::new()),
    }
}
```

#### Step 5: Create the Hotkey Service

Implement `hotkey/service.rs`:

```rust
// audio-transcription/src/hotkey/service.rs

use crate::state::recording::RecordingState;
use anyhow::Result;
use global_hotkey::{GlobalHotKeyManager, HotKeyState, hotkey::HotKey};
use std::str::FromStr;
use tokio::sync::mpsc;
use tracing::{info, error};

pub struct HotkeyService {
    manager: GlobalHotKeyManager,
    recording_state: RecordingState,
}

impl HotkeyService {
    pub fn new(recording_state: RecordingState) -> Result<Self> {
        let manager = GlobalHotKeyManager::new()?;
        Ok(Self { manager, recording_state })
    }
    
    pub fn register_hotkey(&self, hotkey_str: &str) -> Result<()> {
        let hotkey = HotKey::from_str(hotkey_str)?;
        self.manager.register(hotkey)?;
        Ok(())
    }
    
    pub async fn run(&self, mut rx: mpsc::Receiver<HotKeyState>) {
        while let Some(state) = rx.recv().await {
            if state.state() {
                let is_now_active = self.recording_state.toggle();
                info!("Recording {}", if is_now_active { "started" } else { "paused" });
            }
        }
    }
}
```

#### Step 6: Implement Audio Stream Manager

Create `audio/stream.rs`:

```rust
// audio-transcription/src/audio/stream.rs

use crate::audio::buffer::{SharedAudioBuffer, CHUNK_SIZE, SAMPLE_RATE, CHANNELS};
use anyhow::{Context, Result};
use cpal::{
    traits::{DeviceTrait, StreamTrait},
    Device, Stream, StreamConfig,
};
use futures::channel::mpsc::Sender as FuturesSender;
use tracing::{error, trace};

pub fn setup_audio_stream(
    device: &Device,
    sender: FuturesSender<Vec<f32>>,
    buffer: SharedAudioBuffer,
) -> Result<Stream> {
    // Find appropriate format
    let supported_configs = device.supported_input_configs()?;
    let config = supported_configs
        .filter(|c| c.channels() == CHANNELS && c.sample_format() == cpal::SampleFormat::F32)
        .filter_map(|c| {
            if c.min_sample_rate() <= cpal::SampleRate(SAMPLE_RATE) && 
               c.max_sample_rate() >= cpal::SampleRate(SAMPLE_RATE) {
                Some(c.with_sample_rate(cpal::SampleRate(SAMPLE_RATE)))
            } else {
                None
            }
        })
        .next()
        .or_else(|| device.default_input_config().ok())
        .context("No suitable audio configuration found")?;
    
    let mut chunk_samples: Vec<f32> = Vec::with_capacity(CHUNK_SIZE * 2);
    let mut sender = sender;
    
    let stream = device.build_input_stream(
        &config.config(),
        move |data: &[f32], _: &cpal::InputCallbackInfo| {
            let mut buffer_guard = match buffer.lock() {
                Ok(guard) => guard,
                Err(poisoned) => {
                    error!("Audio buffer mutex poisoned! Recovering.");
                    poisoned.into_inner()
                }
            };
            
            buffer_guard.add_samples(data);
            drop(buffer_guard);
            
            chunk_samples.extend_from_slice(data);
            
            while chunk_samples.len() >= CHUNK_SIZE {
                let samples_to_send: Vec<f32> = chunk_samples.drain(..CHUNK_SIZE).collect();
                if let Err(e) = futures::executor::block_on(sender.send(samples_to_send)) {
                    error!("Audio CB: Failed send chunk: {}", e);
                } else {
                    trace!("Audio CB: Sent chunk");
                }
            }
        },
        |err| error!("Audio stream error: {}", err),
        None,
    )?;
    
    Ok(stream)
}
```

#### Step 7: Create Device Management

Create `audio/device.rs`:

```rust
// audio-transcription/src/audio/device.rs

use anyhow::{Context, Result};
use cpal::{
    traits::{DeviceTrait, HostTrait},
    Device, Host,
};
use std::collections::HashSet;

pub fn list_audio_devices(host: &Host) -> Result<Vec<(usize, String)>> {
    let devices = host.input_devices()?;
    
    let mut device_list = Vec::new();
    for (idx, device) in devices.enumerate() {
        if let Ok(name) = device.name() {
            device_list.push((idx, name));
        }
    }
    
    Ok(device_list)
}

pub fn find_device_by_name(host: &Host, name: &str) -> Result<Device> {
    host.input_devices()?
        .find(|d| d.name().map(|n| n == name).unwrap_or(false))
        .ok_or_else(|| anyhow::anyhow!("Device '{}' not found", name))
}

pub fn get_known_devices(host: &Host) -> Result<HashSet<String>> {
    let devices = host.input_devices()?;
    let mut known_devices = HashSet::new();
    
    for device in devices {
        if let Ok(name) = device.name() {
            known_devices.insert(name);
        }
    }
    
    Ok(known_devices)
}
```

#### Step 8: Set Up the Library API in lib.rs

Create the main library exports:

```rust
// audio-transcription/src/lib.rs

pub mod audio;
pub mod hotkey;
pub mod state;
pub mod transcription;
pub mod util;

// Re-export key components for easier use
pub use audio::buffer::{AudioBuffer, SharedAudioBuffer, create_shared_buffer};
pub use audio::device::{list_audio_devices, find_device_by_name};
pub use audio::stream::setup_audio_stream;
pub use state::recording::RecordingState;
pub use transcription::providers::{TranscriptionProvider, create_provider};
pub use hotkey::service::HotkeyService;

// Export constants
pub use audio::buffer::{SAMPLE_RATE, CHANNELS, CHUNK_SIZE, CHUNK_DURATION_MS};
```

#### Step 9: Implement CLI Argument Parsing

Create `audio-transcription-cli/src/cli/args.rs`:

```rust
// audio-transcription-cli/src/cli/args.rs

use clap::{Parser, ValueEnum};
use std::path::PathBuf;

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum TranscriptionMode {
    AlwaysOn,
    Hotkey,
}

#[derive(Parser, Debug, Clone)]
#[command(author, version, about = "Audio transcription tool")]
pub struct CliArgs {
    /// Audio device name to use
    #[arg(short, long)]
    pub device: Option<String>,
    
    /// Transcription activation mode
    #[arg(short, long, value_enum, default_value = "always-on")]
    pub mode: TranscriptionMode,
    
    /// Hotkey for toggling recording (when in hotkey mode)
    #[arg(short = 'k', long, default_value = "ctrl+space")]
    pub hotkey: String,
    
    /// Directory to store data
    #[arg(long, default_value = "data_dir")]
    pub data_dir: PathBuf,
    
    /// Enable debug mode
    #[arg(short, long)]
    pub debug: bool,
}
```

#### Step 10: Implement the Main CLI Application

Finally, implement `audio-transcription-cli/src/main.rs`:

```rust
// audio-transcription-cli/src/main.rs

mod cli;
mod tasks;

use cli::args::{CliArgs, TranscriptionMode};
use tasks::{device_monitor, provider_manager};

use anyhow::{Context, Result};
use audio_transcription::{
    create_provider, create_shared_buffer, find_device_by_name, list_audio_devices,
    setup_audio_stream, RecordingState, HotkeyService,
};
use clap::Parser;
use std::io::{self, Write};
use std::sync::Arc;
use tokio::sync::Mutex;
use tracing::{info, error};

#[tokio::main]
async fn main() -> Result<()> {
    // Parse command line args
    let args = CliArgs::parse();
    
    // Set up tracing
    audio_transcription::util::tracing::initialize(&args.data_dir, args.debug)?;
    
    info!("Starting audio transcription application");
    
    // Initialize CPAL host
    let host = cpal::default_host();
    
    // Get device - either from args or interactive selection
    let device = if let Some(name) = &args.device {
        info!("Using device from arguments: {}", name);
        find_device_by_name(&host, name)?
    } else {
        // Show available devices
        let devices = list_audio_devices(&host)?;
        if devices.is_empty() {
            return Err(anyhow::anyhow!("No audio input devices found"));
        }
        
        println!("Available audio devices:");
        for (idx, name) in &devices {
            println!("  {}: {}", idx + 1, name);
        }
        
        // Prompt for selection
        print!("Select device [1-{}] (Enter for default): ", devices.len());
        io::stdout().flush()?;
        
        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        
        if input.trim().is_empty() {
            host.default_input_device()
                .context("No default device available")?
        } else {
            let idx = input.trim().parse::<usize>()
                .context("Invalid selection")?;
            
            if idx < 1 || idx > devices.len() {
                return Err(anyhow::anyhow!("Selection out of range"));
            }
            
            let device_name = &devices[idx - 1].1;
            find_device_by_name(&host, device_name)?
        }
    };
    
    let device_name = device.name()?;
    info!("Selected device: {}", device_name);
    
    // Initialize recording state based on mode
    let initially_active = matches!(args.mode, TranscriptionMode::AlwaysOn);
    let recording_state = RecordingState::new(initially_active);
    
    // Set up rest of the application
    // - Create shared buffer
    // - Set up audio streaming
    // - Initialize transcription provider
    // - Start monitoring tasks
    // - Handle hotkeys if needed
    
    // Main application loop and shutdown handling
    // (Details omitted for brevity)
    
    Ok(())
}
```

### 5. Migration Strategy

1. **Incremental Migration**:
   - Start by creating the new directory structure and moving small, self-contained components first.
   - Continue to use existing code until each component is fully migrated.

2. **Testing During Migration**:
   - Create simple test applications that use the library components as you migrate them.
   - Verify functionality before proceeding to the next component.

3. **Documentation**:
   - Add documentation comments to all public interfaces.
   - Create examples to demonstrate how to use the library.

This structured approach creates clear separation between the core audio transcription functionality and the CLI interface, making the code more maintainable and reusable.