-
Notifications
You must be signed in to change notification settings - Fork 984
/
Copy pathscreenpipe-server.rs
1679 lines (1536 loc) · 64.5 KB
/
screenpipe-server.rs
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
use clap::Parser;
#[allow(unused_imports)]
use colored::Colorize;
use dirs::home_dir;
use reqwest::Client;
use futures::pin_mut;
use port_check::is_local_ipv4_port_free;
use screenpipe_audio::{
audio_manager::AudioManagerBuilder,
core::device::{
default_input_device, default_output_device, list_audio_devices, parse_audio_device,
},
};
use screenpipe_core::find_ffmpeg_path;
use screenpipe_db::{
create_migration_worker, DatabaseManager, MigrationCommand, MigrationConfig, MigrationStatus,
};
use screenpipe_server::{
cli::{
AudioCommand, Cli, CliAudioTranscriptionEngine, CliOcrEngine, Command, MigrationSubCommand,
OutputFormat, PipeCommand, VisionCommand, McpCommand,
},
handle_index_command,
pipe_manager::PipeInfo,
start_continuous_recording, watch_pid, PipeManager, ResourceMonitor, SCServer,
};
use screenpipe_vision::monitor::list_monitors;
#[cfg(target_os = "macos")]
use screenpipe_vision::run_ui;
use serde_json::{json, Value};
use std::{
env, fs, io::Write, net::SocketAddr, ops::Deref, path::PathBuf, sync::Arc, time::Duration,
net::{IpAddr, Ipv4Addr},
};
use tokio::{runtime::Runtime, signal, sync::broadcast};
use tracing::{debug, error, info, warn};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_appender::rolling::{RollingFileAppender, Rotation};
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{fmt, EnvFilter};
use tracing_subscriber::{prelude::__tracing_subscriber_SubscriberExt, Layer};
use serde::Deserialize;
use std::path::Path;
use reqwest::header::{HeaderMap, HeaderValue, USER_AGENT};
const DISPLAY: &str = r"
_
__________________ ___ ____ ____ (_____ ___
/ ___/ ___/ ___/ _ \/ _ \/ __ \ / __ \/ / __ \/ _ \
(__ / /__/ / / __/ __/ / / / / /_/ / / /_/ / __/
/____/\___/_/ \___/\___/_/ /_/ / .___/_/ .___/\___/
/_/ /_/
";
// Add the struct definition with proper derive attributes
#[derive(Deserialize, Debug)]
struct GitHubContent {
name: String,
path: String,
download_url: Option<String>,
#[serde(rename = "type")]
content_type: String,
}
fn get_base_dir(custom_path: &Option<String>) -> anyhow::Result<PathBuf> {
let default_path = home_dir()
.ok_or_else(|| anyhow::anyhow!("failed to get home directory"))?
.join(".screenpipe");
let base_dir = custom_path
.as_ref()
.map(PathBuf::from)
.unwrap_or(default_path);
let data_dir = base_dir.join("data");
fs::create_dir_all(&data_dir)?;
Ok(base_dir)
}
fn setup_logging(local_data_dir: &PathBuf, cli: &Cli) -> anyhow::Result<WorkerGuard> {
let file_appender = RollingFileAppender::builder()
.rotation(Rotation::DAILY)
.filename_prefix("screenpipe")
.filename_suffix("log")
.max_log_files(5)
.build(local_data_dir)?;
let (file_writer, guard) = tracing_appender::non_blocking(file_appender);
let make_env_filter = || {
let filter = EnvFilter::from_default_env()
.add_directive("tokio=debug".parse().unwrap())
.add_directive("runtime=debug".parse().unwrap())
.add_directive("info".parse().unwrap())
.add_directive("tokenizers=error".parse().unwrap())
.add_directive("rusty_tesseract=error".parse().unwrap())
.add_directive("symphonia=error".parse().unwrap())
.add_directive("hf_hub=error".parse().unwrap())
.add_directive("whisper_rs=error".parse().unwrap());
#[cfg(target_os = "windows")]
let filter = filter
.add_directive("xcap::platform::impl_window=off".parse().unwrap())
.add_directive("xcap::platform::impl_monitor=off".parse().unwrap())
.add_directive("xcap::platform::utils=off".parse().unwrap());
let filter = env::var("SCREENPIPE_LOG")
.unwrap_or_default()
.split(',')
.filter(|s| !s.is_empty())
.fold(filter, |filter, module_directive| {
match module_directive.parse() {
Ok(directive) => filter.add_directive(directive),
Err(e) => {
eprintln!(
"warning: invalid log directive '{}': {}",
module_directive, e
);
filter
}
}
});
if cli.debug {
filter.add_directive("screenpipe=debug".parse().unwrap())
} else {
filter
}
};
let timer =
tracing_subscriber::fmt::time::ChronoLocal::new("%Y-%m-%dT%H:%M:%S%.6fZ".to_string());
let tracing_registry = tracing_subscriber::registry()
.with(
fmt::layer()
.with_writer(std::io::stdout)
.with_timer(timer.clone())
.with_filter(make_env_filter()),
)
.with(
fmt::layer()
.with_writer(file_writer)
.with_timer(timer)
.with_filter(make_env_filter()),
);
#[cfg(feature = "debug-console")]
let tracing_registry = tracing_registry.with(
console_subscriber::spawn().with_filter(
EnvFilter::from_default_env()
.add_directive("tokio=trace".parse().unwrap())
.add_directive("runtime=trace".parse().unwrap()),
),
);
// Build the final registry with conditional Sentry layer
if !cli.disable_telemetry {
tracing_registry
.with(sentry::integrations::tracing::layer())
.init();
} else {
tracing_registry.init();
};
Ok(guard)
}
#[tokio::main]
#[tracing::instrument]
async fn main() -> anyhow::Result<()> {
debug!("starting screenpipe server");
let cli = Cli::parse();
// Initialize Sentry only if telemetry is enabled
let _sentry_guard = if !cli.disable_telemetry {
let sentry_release_name_append = env::var("SENTRY_RELEASE_NAME_APPEND").unwrap_or_default();
let release_name = format!(
"{}{}",
sentry::release_name!().unwrap_or_default(),
sentry_release_name_append
);
Some(sentry::init((
"https://cf682877173997afc8463e5ca2fbe3c7@o4507617161314304.ingest.us.sentry.io/4507617170161664",
sentry::ClientOptions {
release: Some(release_name.into()),
traces_sample_rate: 0.1,
..Default::default()
}
)))
} else {
None
};
let local_data_dir = get_base_dir(&cli.data_dir)?;
let local_data_dir_clone = local_data_dir.clone();
// Only set up logging if we're not running a pipe command with JSON output
let should_log = match &cli.command {
Some(Command::Pipe { subcommand }) => {
matches!(
subcommand,
PipeCommand::List {
output: OutputFormat::Text,
..
} | PipeCommand::Install {
output: OutputFormat::Text,
..
} | PipeCommand::Info {
output: OutputFormat::Text,
..
} | PipeCommand::Enable { .. }
| PipeCommand::Disable { .. }
| PipeCommand::Update { .. }
| PipeCommand::Purge { .. }
| PipeCommand::Delete { .. }
)
}
Some(Command::Add {
output: OutputFormat::Text,
..
}) => true,
Some(Command::Migrate {
output: OutputFormat::Text,
..
}) => true,
_ => true,
};
// Store the guard in a variable that lives for the entire main function
let _log_guard = if should_log {
Some(setup_logging(&local_data_dir, &cli)?)
} else {
None
};
let pipe_manager = Arc::new(PipeManager::new(local_data_dir_clone.clone()));
if let Some(ref command) = cli.command {
match command {
Command::Audio { subcommand } => match subcommand {
AudioCommand::List { output } => {
let default_input = default_input_device().unwrap();
let default_output = default_output_device().await.unwrap();
let devices = list_audio_devices().await?;
match output {
OutputFormat::Json => println!(
"{}",
serde_json::to_string_pretty(&json!({
"data": devices.iter().map(|d| {
json!({
"name": d.to_string(),
"is_default": d.name == default_input.name || d.name == default_output.name
})
}).collect::<Vec<_>>(),
"success": true
}))?
),
OutputFormat::Text => {
println!("available audio devices:");
for device in devices.iter() {
println!(" {}", device);
}
#[cfg(target_os = "macos")]
println!("note: on macos, output devices are your displays");
}
}
return Ok(());
}
},
Command::Vision { subcommand } => match subcommand {
VisionCommand::List { output } => {
let monitors = list_monitors().await;
match output {
OutputFormat::Json => println!(
"{}",
serde_json::to_string_pretty(&json!({
"data": monitors.iter().map(|m| {
json!({
"id": m.id(),
"name": m.name(),
"width": m.width(),
"height": m.height(),
"is_default": m.is_primary(),
})
}).collect::<Vec<_>>(),
"success": true
}))?
),
OutputFormat::Text => {
println!("available monitors:");
for monitor in monitors.iter() {
println!(" {}. {:?}", monitor.id(), monitor.name());
}
}
}
return Ok(());
}
},
Command::Completions { shell } => {
cli.handle_completions(*shell)?;
return Ok(());
}
Command::Pipe { subcommand } => {
handle_pipe_command(subcommand, &pipe_manager).await?;
return Ok(());
}
Command::Migrate {
migration_name,
data_dir,
subcommand,
output,
batch_size,
batch_delay_ms,
continue_on_error,
} => {
// Initialize the database
let local_data_dir = get_base_dir(data_dir)?;
let db = Arc::new(
DatabaseManager::new(&format!(
"{}/db.sqlite",
local_data_dir.to_string_lossy()
))
.await
.map_err(|e| {
error!("failed to initialize database: {:?}", e);
e
})?,
);
// Create a migration worker config
let config = MigrationConfig::new(*batch_size, *batch_delay_ms, *continue_on_error);
// Start the migration worker
let (cmd_tx, mut status_rx, worker_handle) =
create_migration_worker(db, Some(config));
// Process the specified subcommand or default to status
let cmd = match subcommand {
Some(MigrationSubCommand::Start) => MigrationCommand::Start,
Some(MigrationSubCommand::Pause) => MigrationCommand::Pause,
Some(MigrationSubCommand::Stop) => MigrationCommand::Stop,
Some(MigrationSubCommand::Status) | None => MigrationCommand::Status,
};
// Send the command to the worker
if let Err(e) = cmd_tx.send(cmd.clone()).await {
error!("failed to send command to migration worker: {}", e);
return Err(anyhow::anyhow!(
"Failed to send command to migration worker"
));
}
// If the command is start, we need to track the progress
if matches!(cmd, MigrationCommand::Start) {
// Send the start command and wait for the worker to acknowledge
if let Some(response) = status_rx.recv().await {
match output {
OutputFormat::Json => {
println!("{}", serde_json::to_string_pretty(&response.status)?);
}
OutputFormat::Text => {
info!("Started migration: {}", migration_name);
match response.status {
MigrationStatus::Running {
total_records,
processed_records,
} => {
info!(
"Processing records: {}/{} ({:.2}%)",
processed_records,
total_records,
if total_records > 0 {
(processed_records as f64 / total_records as f64)
* 100.0
} else {
0.0
}
);
}
_ => {
info!("Migration status: {:?}", response.status);
}
}
}
}
}
// Keep checking status periodically until migration completes, fails, or is stopped
let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(5));
loop {
interval.tick().await;
// Send status command
if let Err(e) = cmd_tx.send(MigrationCommand::Status).await {
error!("failed to send status command: {}", e);
break;
}
// Wait for response
if let Some(response) = status_rx.recv().await {
match output {
OutputFormat::Json => {
println!("{}", serde_json::to_string_pretty(&response.status)?);
}
OutputFormat::Text => match &response.status {
MigrationStatus::Running {
total_records,
processed_records,
} => {
info!(
"Processing records: {}/{} ({:.2}%)",
processed_records,
total_records,
if *total_records > 0 {
(*processed_records as f64 / *total_records as f64)
* 100.0
} else {
0.0
}
);
}
MigrationStatus::Completed {
total_records,
duration_secs,
} => {
info!(
"Migration completed: {} records processed in {} seconds",
total_records, duration_secs
);
break;
}
MigrationStatus::Paused {
total_records,
processed_records,
} => {
info!(
"Migration paused: {}/{} ({:.2}%)",
processed_records,
total_records,
if *total_records > 0 {
(*processed_records as f64 / *total_records as f64)
* 100.0
} else {
0.0
}
);
}
MigrationStatus::Failed {
total_records,
processed_records,
error,
} => {
error!(
"Migration failed: {}/{} records processed. Error: {}",
processed_records, total_records, error
);
break;
}
_ => {
info!("Migration status: {:?}", response.status);
}
},
}
} else {
break;
}
}
} else {
// For non-start commands, just get the status once
if let Some(response) = status_rx.recv().await {
match output {
OutputFormat::Json => {
println!("{}", serde_json::to_string_pretty(&response.status)?);
}
OutputFormat::Text => {
info!("Migration status: {:?}", response.status);
}
}
}
}
// If we explicitly stopped, wait for the worker to finish
if matches!(cmd, MigrationCommand::Stop) {
if let Err(e) = worker_handle.await {
error!("error waiting for worker to finish: {}", e);
}
}
return Ok(());
}
Command::Add {
path,
output,
data_dir,
pattern,
ocr_engine,
metadata_override,
copy_videos,
debug,
use_embedding,
} => {
let local_data_dir = get_base_dir(data_dir)?;
// Update logging filter if debug is enabled
if *debug {
tracing::subscriber::set_global_default(
tracing_subscriber::registry()
.with(
EnvFilter::from_default_env()
.add_directive("screenpipe=debug".parse().unwrap()),
)
.with(fmt::layer().with_writer(std::io::stdout)),
)
.ok();
debug!("debug logging enabled");
}
let db = Arc::new(
DatabaseManager::new(&format!(
"{}/db.sqlite",
local_data_dir.to_string_lossy()
))
.await
.map_err(|e| {
error!("failed to initialize database: {:?}", e);
e
})?,
);
handle_index_command(
local_data_dir,
path.to_string(),
pattern.clone(),
db,
output.clone(),
ocr_engine.clone(),
metadata_override.clone(),
*copy_videos,
*use_embedding,
)
.await?;
return Ok(());
}
Command::Mcp { subcommand } => {
handle_mcp_command(subcommand, &local_data_dir_clone).await?;
return Ok(());
}
}
}
// Replace the current conditional check with:
let ffmpeg_path = find_ffmpeg_path();
if ffmpeg_path.is_none() {
// Try one more time, which might trigger the installation
let ffmpeg_path = find_ffmpeg_path();
if ffmpeg_path.is_none() {
eprintln!("ffmpeg not found and installation failed. please install ffmpeg manually.");
std::process::exit(1);
}
}
if !is_local_ipv4_port_free(cli.port) {
error!(
"you're likely already running screenpipe instance in a different environment, e.g. terminal/ide, close it and restart or use different port"
);
return Err(anyhow::anyhow!("port already in use"));
}
let all_monitors = list_monitors().await;
let mut audio_devices = Vec::new();
let mut realtime_audio_devices = Vec::new();
if !cli.disable_audio {
if cli.audio_device.is_empty() {
// Use default devices
if let Ok(input_device) = default_input_device() {
audio_devices.push(input_device.to_string());
}
if let Ok(output_device) = default_output_device().await {
audio_devices.push(output_device.to_string());
}
} else {
// Use specified devices
for d in &cli.audio_device {
let device = parse_audio_device(d).expect("failed to parse audio device");
audio_devices.push(device.to_string());
}
}
if audio_devices.is_empty() {
warn!("no audio devices available.");
}
if cli.enable_realtime_audio_transcription {
if cli.realtime_audio_device.is_empty() {
// Use default devices
if let Ok(input_device) = default_input_device() {
realtime_audio_devices.push(Arc::new(input_device.clone()));
}
if let Ok(output_device) = default_output_device().await {
realtime_audio_devices.push(Arc::new(output_device.clone()));
}
} else {
for d in &cli.realtime_audio_device {
let device = parse_audio_device(d).expect("failed to parse audio device");
realtime_audio_devices.push(Arc::new(device.clone()));
}
}
if realtime_audio_devices.is_empty() {
eprintln!("no realtime audio devices available. realtime audio transcription will be disabled.");
}
}
}
let audio_devices_clone = audio_devices.clone();
let resource_monitor = ResourceMonitor::new(!cli.disable_telemetry);
resource_monitor.start_monitoring(Duration::from_secs(30), Some(Duration::from_secs(60)));
let db = Arc::new(
DatabaseManager::new(&format!("{}/db.sqlite", local_data_dir.to_string_lossy()))
.await
.map_err(|e| {
eprintln!("failed to initialize database: {:?}", e);
e
})?,
);
let db_server = db.clone();
let warning_ocr_engine_clone = cli.ocr_engine.clone();
let warning_audio_transcription_engine_clone = cli.audio_transcription_engine.clone();
let monitor_ids = if cli.monitor_id.is_empty() {
all_monitors.iter().map(|m| m.id()).collect::<Vec<_>>()
} else {
cli.monitor_id.clone()
};
let languages = cli.unique_languages().unwrap();
let languages_clone = languages.clone();
let ocr_engine_clone = cli.ocr_engine.clone();
let vad_engine = cli.vad_engine.clone();
let vad_engine_clone = vad_engine.clone();
let vad_sensitivity_clone = cli.vad_sensitivity.clone();
let (shutdown_tx, _) = broadcast::channel::<()>(1);
let vision_runtime = Runtime::new().unwrap();
let pipes_runtime = Runtime::new().unwrap();
let vision_handle = vision_runtime.handle().clone();
let pipes_handle = pipes_runtime.handle().clone();
let db_clone = Arc::clone(&db);
let output_path_clone = Arc::new(local_data_dir.join("data").to_string_lossy().into_owned());
let shutdown_tx_clone = shutdown_tx.clone();
let monitor_ids_clone = monitor_ids.clone();
let ignored_windows_clone = cli.ignored_windows.clone();
let included_windows_clone = cli.included_windows.clone();
let realtime_audio_devices_clone = realtime_audio_devices.clone();
let fps = if cli.fps.is_finite() && cli.fps > 0.0 {
cli.fps
} else {
eprintln!("invalid fps value: {}. using default of 1.0", cli.fps);
1.0
};
let audio_chunk_duration = Duration::from_secs(cli.audio_chunk_duration);
let mut audio_manager_builder = AudioManagerBuilder::new()
.audio_chunk_duration(audio_chunk_duration)
.vad_engine(vad_engine.into())
.vad_sensitivity(cli.vad_sensitivity.into())
.languages(languages.clone())
.transcription_engine(cli.audio_transcription_engine.into())
.realtime(cli.enable_realtime_audio_transcription)
.enabled_devices(audio_devices)
.deepgram_api_key(cli.deepgram_api_key.clone())
.output_path(PathBuf::from(output_path_clone.clone().to_string()));
let audio_manager = match audio_manager_builder.build(db.clone()).await {
Ok(manager) => Arc::new(manager),
Err(e) => {
error!("{e}");
return Ok(());
}
};
let handle = {
let runtime = &tokio::runtime::Handle::current();
runtime.spawn(async move {
loop {
let mut shutdown_rx = shutdown_tx_clone.subscribe();
let recording_future = start_continuous_recording(
db_clone.clone(),
output_path_clone.clone(),
fps,
Duration::from_secs(cli.video_chunk_duration),
Arc::new(cli.ocr_engine.clone().into()),
monitor_ids_clone.clone(),
cli.use_pii_removal,
cli.disable_vision,
&vision_handle,
&cli.ignored_windows,
&cli.included_windows,
languages_clone.clone(),
cli.capture_unfocused_windows,
cli.enable_realtime_audio_transcription,
);
let result = tokio::select! {
result = recording_future => result,
_ = shutdown_rx.recv() => {
info!("received shutdown signal for recording");
break;
}
};
if let Err(e) = result {
error!("continuous recording error: {:?}", e);
}
}
})
};
let local_data_dir_clone_2 = local_data_dir_clone.clone();
#[cfg(feature = "llm")]
debug!("LLM initializing");
#[cfg(feature = "llm")]
let _llm = {
match cli.enable_llm {
true => Some(screenpipe_core::LLM::new(
screenpipe_core::ModelName::Llama,
)?),
false => None,
}
};
#[cfg(feature = "llm")]
debug!("LLM initialized");
let server = SCServer::new(
db_server,
SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), cli.port),
local_data_dir_clone_2,
pipe_manager.clone(),
cli.disable_vision,
cli.disable_audio,
cli.enable_ui_monitoring,
audio_manager.clone(),
);
// print screenpipe in gradient
println!("\n\n{}", DISPLAY.truecolor(147, 112, 219).bold());
println!(
"\n{}",
"build ai apps that have the full context"
.bright_yellow()
.italic()
);
println!(
"{}\n\n",
"open source | runs locally | developer friendly".bright_green()
);
println!("┌────────────────────────┬────────────────────────────────────┐");
println!("│ setting │ value │");
println!("├────────────────────────┼────────────────────────────────────┤");
println!("│ fps │ {:<34} │", cli.fps);
println!(
"│ audio chunk duration │ {:<34} │",
format!("{} seconds", cli.audio_chunk_duration)
);
println!(
"│ video chunk duration │ {:<34} │",
format!("{} seconds", cli.video_chunk_duration)
);
println!("│ port │ {:<34} │", cli.port);
println!(
"│ realtime audio enabled │ {:<34} │",
cli.enable_realtime_audio_transcription
);
println!("│ audio disabled │ {:<34} │", cli.disable_audio);
println!("│ vision disabled │ {:<34} │", cli.disable_vision);
println!(
"│ audio engine │ {:<34} │",
format!("{:?}", warning_audio_transcription_engine_clone)
);
println!(
"│ ocr engine │ {:<34} │",
format!("{:?}", ocr_engine_clone)
);
println!(
"│ vad engine │ {:<34} │",
format!("{:?}", vad_engine_clone)
);
println!(
"│ vad sensitivity │ {:<34} │",
format!("{:?}", vad_sensitivity_clone)
);
println!(
"│ data directory │ {:<34} │",
local_data_dir_clone.display()
);
println!("│ debug mode │ {:<34} │", cli.debug);
println!(
"│ telemetry │ {:<34} │",
!cli.disable_telemetry
);
println!("│ local llm │ {:<34} │", cli.enable_llm);
println!("│ use pii removal │ {:<34} │", cli.use_pii_removal);
println!(
"│ ignored windows │ {:<34} │",
format_cell(&format!("{:?}", &ignored_windows_clone), VALUE_WIDTH)
);
println!(
"│ included windows │ {:<34} │",
format_cell(&format!("{:?}", &included_windows_clone), VALUE_WIDTH)
);
println!(
"│ ui monitoring │ {:<34} │",
cli.enable_ui_monitoring
);
println!(
"│ frame cache │ {:<34} │",
cli.enable_frame_cache
);
println!(
"│ capture unfocused wins │ {:<34} │",
cli.capture_unfocused_windows
);
println!(
"│ auto-destruct pid │ {:<34} │",
cli.auto_destruct_pid.unwrap_or(0)
);
// For security reasons, you might want to mask the API key if displayed
println!(
"│ deepgram key │ {:<34} │",
if cli.deepgram_api_key.is_some() {
"set (masked)"
} else {
"not set"
}
);
const VALUE_WIDTH: usize = 34;
// Function to truncate and pad strings
fn format_cell(s: &str, width: usize) -> String {
if s.len() > width {
let mut max_pos = 0;
for (i, c) in s.char_indices() {
if i + c.len_utf8() > width - 3 {
break;
}
max_pos = i + c.len_utf8();
}
format!("{}...", &s[..max_pos])
} else {
format!("{:<width$}", s, width = width)
}
}
// Add languages section
println!("├────────────────────────┼────────────────────────────────────┤");
println!("│ languages │ │");
const MAX_ITEMS_TO_DISPLAY: usize = 5;
if cli.language.is_empty() {
println!("│ {:<22} │ {:<34} │", "", "all languages");
} else {
let total_languages = cli.language.len();
for (_, language) in languages.iter().enumerate().take(MAX_ITEMS_TO_DISPLAY) {
let language_str = format!("id: {}", language);
let formatted_language = format_cell(&language_str, VALUE_WIDTH);
println!("│ {:<22} │ {:<34} │", "", formatted_language);
}
if total_languages > MAX_ITEMS_TO_DISPLAY {
println!(
"│ {:<22} │ {:<34} │",
"",
format!("... and {} more", total_languages - MAX_ITEMS_TO_DISPLAY)
);
}
}
// Add monitors section
println!("├────────────────────────┼────────────────────────────────────┤");
println!("│ monitors │ │");
if cli.disable_vision {
println!("│ {:<22} │ {:<34} │", "", "vision disabled");
} else if monitor_ids.is_empty() {
println!("│ {:<22} │ {:<34} │", "", "no monitors available");
} else {
let total_monitors = monitor_ids.len();
for (_, monitor) in monitor_ids.iter().enumerate().take(MAX_ITEMS_TO_DISPLAY) {
let monitor_str = format!("id: {}", monitor);
let formatted_monitor = format_cell(&monitor_str, VALUE_WIDTH);
println!("│ {:<22} │ {:<34} │", "", formatted_monitor);
}
if total_monitors > MAX_ITEMS_TO_DISPLAY {
println!(
"│ {:<22} │ {:<34} │",
"",
format!("... and {} more", total_monitors - MAX_ITEMS_TO_DISPLAY)
);
}
}
// Audio devices section
println!("├────────────────────────┼────────────────────────────────────┤");
println!("│ audio devices │ │");
if cli.disable_audio {
println!("│ {:<22} │ {:<34} │", "", "disabled");
} else if audio_devices_clone.is_empty() {
println!("│ {:<22} │ {:<34} │", "", "no devices available");
} else {
let total_devices = audio_devices_clone.len();
for (_, device) in audio_devices_clone
.iter()
.enumerate()
.take(MAX_ITEMS_TO_DISPLAY)
{
let device_str = device.deref().to_string();
let formatted_device = format_cell(&device_str, VALUE_WIDTH);
println!("│ {:<22} │ {:<34} │", "", formatted_device);
}
if total_devices > MAX_ITEMS_TO_DISPLAY {
println!(
"│ {:<22} │ {:<34} │",
"",
format!("... and {} more", total_devices - MAX_ITEMS_TO_DISPLAY)
);
}
}
// Realtime Audio devices section
println!("├────────────────────────┼────────────────────────────────────┤");
println!("│ realtime audio devices │ │");
if cli.disable_audio || !cli.enable_realtime_audio_transcription {
println!("│ {:<22} │ {:<34} │", "", "disabled");
} else if realtime_audio_devices_clone.is_empty() {
println!("│ {:<22} │ {:<34} │", "", "no devices available");
} else {
let total_devices = realtime_audio_devices_clone.len();
for (_, device) in realtime_audio_devices_clone
.iter()
.enumerate()
.take(MAX_ITEMS_TO_DISPLAY)
{
let device_str = device.deref().to_string();
let formatted_device = format_cell(&device_str, VALUE_WIDTH);
println!("│ {:<22} │ {:<34} │", "", formatted_device);
}
if total_devices > MAX_ITEMS_TO_DISPLAY {
println!(
"│ {:<22} │ {:<34} │",
"",
format!("... and {} more", total_devices - MAX_ITEMS_TO_DISPLAY)
);
}
}
// Pipes section
println!("├────────────────────────┼────────────────────────────────────┤");
println!("│ pipes │ │");
let pipes = pipe_manager.list_pipes().await;
if pipes.is_empty() {
println!("│ {:<22} │ {:<34} │", "", "no pipes available");
} else {
let total_pipes = pipes.len();
for (_, pipe) in pipes.iter().enumerate().take(MAX_ITEMS_TO_DISPLAY) {
let pipe_str = format!(
"({}) {}",
if pipe.enabled { "enabled" } else { "disabled" },
pipe.id,
);
let formatted_pipe = format_cell(&pipe_str, VALUE_WIDTH);
println!("│ {:<22} │ {:<34} │", "", formatted_pipe);
}
if total_pipes > MAX_ITEMS_TO_DISPLAY {
println!(
"│ {:<22} │ {:<34} │",
"",
format!("... and {} more", total_pipes - MAX_ITEMS_TO_DISPLAY)
);
}
}
println!("└────────────────────────┴────────────────────────────────────┘");