-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathsafeVisionCLI.py
More file actions
1562 lines (1383 loc) · 61.2 KB
/
Copy pathsafeVisionCLI.py
File metadata and controls
1562 lines (1383 loc) · 61.2 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
"""
SafeVision CLI
A user-friendly command console for SafeVision settings, rule profiles, media
scanning, and launching image/video/API/GUI workflows.
"""
import argparse
import json
import os
import subprocess
import sys
from datetime import datetime
from pathlib import Path
try:
from colorama import Fore, Style, init as colorama_init
colorama_init()
COLORAMA_AVAILABLE = True
except ImportError:
COLORAMA_AVAILABLE = False
try:
from tqdm import tqdm
except ImportError:
tqdm = None
from safevision_utils import (
ALL_CENSOR_LABELS,
default_blur_rules,
ensure_blur_exception_rules,
load_blur_exception_rules,
parse_provider_list,
select_onnx_providers,
write_blur_exception_rules,
)
APP_DIR = Path(__file__).resolve().parent
SETTINGS_DIR = APP_DIR / "settings"
CONFIG_PATH = SETTINGS_DIR / "configs.json"
DEFAULT_RULE_PATH = APP_DIR / "BlurException.rule"
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff", ".webp"}
VIDEO_EXTENSIONS = {".mp4", ".avi", ".mov", ".mkv", ".wmv", ".m4v", ".webm"}
SCRIPT_TARGETS = {
"image": "main.py",
"video": "video.py",
"gui": "SafeVisionGUI.py",
"api": "safevision_api.py",
"web": "safevision_api.py",
"live": "live.py",
"streamer": "live_streamer.py",
"screen": "safeVisionScreenGuard.py",
}
COLORS = {
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"magenta": "\033[35m",
"cyan": "\033[36m",
"bold": "\033[1m",
"reset": "\033[0m",
}
def color(text, name=None):
if COLORAMA_AVAILABLE:
mapping = {
"red": Fore.RED,
"green": Fore.GREEN,
"yellow": Fore.YELLOW,
"blue": Fore.BLUE,
"magenta": Fore.MAGENTA,
"cyan": Fore.CYAN,
"bold": Style.BRIGHT,
}
return f"{mapping.get(name, '')}{text}{Style.RESET_ALL}"
if name in COLORS:
return f"{COLORS[name]}{text}{COLORS['reset']}"
return text
def print_header(title):
print(color(f"\n{title}", "bold"))
print(color("=" * len(title), "cyan"))
def print_ok(message):
print(color(f"[OK] {message}", "green"))
def print_warn(message):
print(color(f"[WARN] {message}", "yellow"))
def print_error(message):
print(color(f"[ERROR] {message}", "red"))
def default_profiles():
return {
"default": default_blur_rules(),
"strict": default_blur_rules(),
"faces_allowed": {
**default_blur_rules(),
"FACE_FEMALE": False,
"FACE_MALE": False,
},
"covered_allowed": {
**default_blur_rules(),
"FEMALE_GENITALIA_COVERED": False,
"BELLY_COVERED": False,
"FEET_COVERED": False,
"ARMPITS_COVERED": False,
"ANUS_COVERED": False,
"FEMALE_BREAST_COVERED": False,
"BUTTOCKS_COVERED": False,
},
}
def default_config():
return {
"version": 1,
"created_at": datetime.now().isoformat(timespec="seconds"),
"active_rule_profile": "default",
"paths": {
"input": "input",
"output": "output",
"video_output": "video_output",
"blur": "Blur",
"process": "Prosses",
"logs": "Logs",
"models": "Models",
},
"processing": {
"providers": "",
"detectors": "nude",
"object_model": "Models/safety_objects.onnx",
"object_labels": "Models/safety_objects.labels.json",
"object_threshold": 0.25,
"codec": "mp4v",
"mask_shape": "rectangle",
"mask_color": "0,0,0",
"blur_strength": 23,
"blur_sigma": 0.0,
"enhanced_blur": False,
"with_audio": False,
"delete_frames": True,
"rule": "0/0",
"full_blur_rule": "",
"save_report": False,
"report_formats": "json,csv",
"export_markers": "",
"marker_gap": 1.0,
},
"screen_guard": {
"monitor": 1,
"mode": "box",
"fps": 5.0,
"overlay_fps": 20.0,
"threshold": 0.35,
"hold_ms": 650,
"providers": "",
"rules": "BlurException.rule",
"capture_backend": "auto",
"smooth_overlay": True,
"smooth_iou": 0.45,
"smooth_alpha": 0.65,
"stable_score_alpha": 0.2,
"track_hold_ms": 1600,
"merge_nearby": True,
"merge_distance": 260,
"merge_overlap": 0.35,
"feedback_delta": 18.0,
"feedback_safe_capture": False,
"capture_hide_ms": 20,
"drop_stale_on_screen_change": True,
"stale_region_delta": 10.0,
"screen_change_delta": 28.0,
"exclude_overlay_capture": True,
"label_filter": "exposed",
"respect_rules": True,
"show_boxes": True,
"show_labels": False,
"show_status": False,
"block_enabled": False,
"blur_enabled": False,
"privacy_on_detection": False,
"blur_style": "gaussian",
"blur_strength": 45,
"mask_shape": "rectangle",
"block_color": "0,0,0",
"outline_color": "#ff3333",
"safe_outline_color": "#3388ff",
"rule_skipped_outline_color": "#aaaaaa",
"label_bg": "#111111",
"label_color": "white",
"line_width": 4,
"box_padding": 0,
"min_box_area": 0,
"click_through": True,
},
"rule_profiles": default_profiles(),
}
def deep_merge(base, incoming):
result = dict(base)
for key, value in incoming.items():
if isinstance(value, dict) and isinstance(result.get(key), dict):
result[key] = deep_merge(result[key], value)
else:
result[key] = value
return result
def load_config():
SETTINGS_DIR.mkdir(parents=True, exist_ok=True)
if CONFIG_PATH.exists():
with open(CONFIG_PATH, "r", encoding="utf-8") as config_file:
loaded = json.load(config_file)
config = deep_merge(default_config(), loaded)
else:
config = default_config()
save_config(config)
return config
def save_config(config):
SETTINGS_DIR.mkdir(parents=True, exist_ok=True)
with open(CONFIG_PATH, "w", encoding="utf-8") as config_file:
json.dump(config, config_file, indent=2)
def resolve_app_path(path_value):
path = Path(path_value)
if not path.is_absolute():
path = APP_DIR / path
return path
def script_path(name):
return APP_DIR / SCRIPT_TARGETS[name]
def script_exists(name):
return script_path(name).exists()
def python_command():
return sys.executable or "python"
def bool_text(value):
return color("true", "green") if value else color("false", "yellow")
def parse_bool(value):
return str(value).strip().lower() in {"1", "true", "yes", "on", "y"}
def set_nested(config, dotted_key, value):
target = config
parts = dotted_key.split(".")
for part in parts[:-1]:
if part not in target or not isinstance(target[part], dict):
target[part] = {}
target = target[part]
old_value = target.get(parts[-1])
if isinstance(old_value, bool):
value = parse_bool(value)
elif isinstance(old_value, int):
value = int(value)
elif isinstance(old_value, float):
value = float(value)
target[parts[-1]] = value
def get_nested(config, dotted_key):
target = config
for part in dotted_key.split("."):
if not isinstance(target, dict) or part not in target:
raise KeyError(dotted_key)
target = target[part]
return target
def rule_profile(config, name=None):
name = name or config.get("active_rule_profile", "default")
profiles = config.setdefault("rule_profiles", default_profiles())
if name not in profiles:
raise KeyError(f"Rule profile does not exist: {name}")
return name, profiles[name]
def normalize_rules(rules):
normalized = default_blur_rules()
for label, value in rules.items():
normalized[label] = bool(value)
return normalized
def activate_rule_profile(config, name):
name, rules = rule_profile(config, name)
rules = normalize_rules(rules)
config["rule_profiles"][name] = rules
config["active_rule_profile"] = name
write_blur_exception_rules(DEFAULT_RULE_PATH, rules=rules)
save_config(config)
print_ok(f"Activated rule profile '{name}' and wrote {DEFAULT_RULE_PATH.name}")
def run_subprocess(command, cwd=APP_DIR):
print(color("Command:", "cyan"), " ".join(str(part) for part in command))
return subprocess.call(command, cwd=str(cwd))
def clear_screen():
os.system("cls" if os.name == "nt" else "clear")
def pause(message="Press Enter to continue..."):
try:
input(color(f"\n{message}", "cyan"))
except EOFError:
pass
def prompt(message, default=None, required=False):
suffix = f" [{default}]" if default not in (None, "") else ""
while True:
try:
value = input(f"{message}{suffix}: ").strip()
except EOFError:
return default or ""
if value:
return value
if default is not None:
return default
if not required:
return ""
print_warn("A value is required.")
def prompt_bool(message, default=False):
default_text = "Y/n" if default else "y/N"
value = prompt(f"{message} ({default_text})", default="")
if not value:
return default
return parse_bool(value)
def selected_row(text):
return color(f"> {text}", "cyan")
def unselected_row(text):
return f" {text}"
def read_menu_key():
if os.name == "nt" and sys.stdin.isatty():
import msvcrt
key = msvcrt.getwch()
if key in ("\x00", "\xe0"):
arrow = msvcrt.getwch()
if arrow == "H":
return "up"
if arrow == "P":
return "down"
return ""
if key == "\r":
return "enter"
if key == "\x1b":
return "escape"
if key.isdigit():
return key
return key.lower()
return input(color("Select number: ", "cyan")).strip()
def menu_select(title, options, *, subtitle=None, allow_back=True):
"""
Show an interactive row selector.
options: list of (label, value) tuples.
"""
rows = list(options)
if allow_back:
rows.append(("Back", "__back__"))
index = 0
if not sys.stdin.isatty():
print_header(title)
for row_index, (label, _) in enumerate(rows, start=1):
print(f"{row_index}. {label}")
return rows[0][1] if rows else "__back__"
while True:
clear_screen()
print_header(title)
if subtitle:
print(subtitle)
print(color("Use Up/Down + Enter, or press a number.", "yellow"))
print()
for row_index, (label, _) in enumerate(rows, start=1):
text = f"{row_index}. {label}"
print(selected_row(text) if row_index - 1 == index else unselected_row(text))
key = read_menu_key()
if key == "up":
index = (index - 1) % len(rows)
elif key == "down":
index = (index + 1) % len(rows)
elif key == "enter":
return rows[index][1]
elif key == "escape":
return "__back__"
elif key.isdigit():
selected = int(key)
if 1 <= selected <= len(rows):
return rows[selected - 1][1]
def choose_from_values(title, values, default=None, allow_back=True):
options = [(str(value), value) for value in values]
if default is not None:
subtitle = f"Current: {default}"
else:
subtitle = None
return menu_select(title, options, subtitle=subtitle, allow_back=allow_back)
def media_files_for_menu(media_type="all"):
config = load_config()
input_folder = resolve_app_path(config["paths"]["input"])
return list(iter_media(input_folder, recursive=True, media_type=media_type))
def choose_media_file(media_type="all"):
files = media_files_for_menu(media_type)
options = []
for path in files[:100]:
try:
size_mb = path.stat().st_size / (1024 * 1024)
label = f"{path.relative_to(APP_DIR)} ({size_mb:.1f} MB)"
except ValueError:
label = str(path)
options.append((label, str(path)))
options.append(("Type a custom path", "__custom__"))
selected = menu_select("Select Media File", options, allow_back=True)
if selected == "__custom__":
return prompt("Input file path", required=True)
if selected == "__back__":
return None
return selected
def command_init(args):
config = load_config()
for relative in config["paths"].values():
resolve_app_path(relative).mkdir(parents=True, exist_ok=True)
activate_rule_profile(config, config.get("active_rule_profile", "default"))
print_ok(f"Settings ready at {CONFIG_PATH}")
def command_status(args):
config = load_config()
print_header("SafeVision Status")
print(f"App folder: {APP_DIR}")
print(f"Config: {CONFIG_PATH} ({'exists' if CONFIG_PATH.exists() else 'missing'})")
print(f"Rule file: {DEFAULT_RULE_PATH} ({'exists' if DEFAULT_RULE_PATH.exists() else 'missing'})")
print(f"Active rule profile: {config.get('active_rule_profile')}")
print_header("Scripts")
for name in ["image", "video", "gui", "api", "live", "streamer", "screen"]:
path = script_path(name)
print(f"{name:8} {bool_text(path.exists())} {path.name}")
print_header("Folders")
for key, value in config["paths"].items():
path = resolve_app_path(value)
print(f"{key:12} {bool_text(path.exists())} {path}")
print_header("ONNX Providers")
try:
selected = select_onnx_providers(parse_provider_list(config["processing"].get("providers", "")))
print(", ".join(selected))
except Exception as exc:
print_warn(f"Could not inspect ONNX Runtime providers: {exc}")
screen_guard = config.get("screen_guard", {})
print_header("Screen Guard")
for key in [
"mode",
"label_filter",
"respect_rules",
"capture_backend",
"smooth_overlay",
"smooth_iou",
"smooth_alpha",
"stable_score_alpha",
"track_hold_ms",
"merge_nearby",
"merge_distance",
"merge_overlap",
"feedback_delta",
"feedback_safe_capture",
"capture_hide_ms",
"drop_stale_on_screen_change",
"stale_region_delta",
"screen_change_delta",
"exclude_overlay_capture",
"show_boxes",
"show_labels",
"block_enabled",
"blur_enabled",
"privacy_on_detection",
"threshold",
]:
print(f"{key:22} {screen_guard.get(key)}")
def command_folders(args):
config = load_config()
print_header("SafeVision Folders")
for key, value in config["paths"].items():
path = resolve_app_path(value)
if args.create:
path.mkdir(parents=True, exist_ok=True)
size = ""
if path.exists():
file_count = sum(1 for item in path.rglob("*") if item.is_file()) if args.recursive else sum(1 for item in path.iterdir() if item.is_file())
size = f"files={file_count}"
print(f"{key:12} {bool_text(path.exists())} {path} {size}")
def iter_media(folder, recursive=False, media_type="all"):
folder = Path(folder)
pattern = "**/*" if recursive else "*"
for path in folder.glob(pattern):
if not path.is_file():
continue
suffix = path.suffix.lower()
is_image = suffix in IMAGE_EXTENSIONS
is_video = suffix in VIDEO_EXTENSIONS
if media_type == "image" and not is_image:
continue
if media_type == "video" and not is_video:
continue
if media_type == "all" and not (is_image or is_video):
continue
yield path
def command_scan(args):
config = load_config()
folder = Path(args.folder or resolve_app_path(config["paths"]["input"]))
if not folder.exists():
print_error(f"Folder does not exist: {folder}")
return 2
files = list(iter_media(folder, recursive=args.recursive, media_type=args.type))
print_header(f"Media Scan: {folder}")
iterator = tqdm(files, desc="Scanning", unit="file") if tqdm and args.progress else files
images = 0
videos = 0
for path in iterator:
suffix = path.suffix.lower()
if suffix in IMAGE_EXTENSIONS:
images += 1
kind = color("image", "green")
else:
videos += 1
kind = color("video", "magenta")
if not args.names_only:
size_mb = path.stat().st_size / (1024 * 1024)
print(f"{kind:14} {size_mb:8.2f} MB {path}")
else:
print(path)
print_ok(f"Found {images} images and {videos} videos")
def command_settings(args):
config = load_config()
if args.settings_action == "show":
print(json.dumps(config, indent=2))
elif args.settings_action == "get":
try:
print(get_nested(config, args.key))
except KeyError:
print_error(f"Unknown setting: {args.key}")
return 2
elif args.settings_action == "set":
set_nested(config, args.key, args.value)
save_config(config)
print_ok(f"Set {args.key} = {args.value}")
elif args.settings_action == "reset":
config = default_config()
save_config(config)
print_ok(f"Reset settings at {CONFIG_PATH}")
def command_rules(args):
config = load_config()
profiles = config.setdefault("rule_profiles", default_profiles())
if args.rules_action == "init":
ensure_blur_exception_rules(DEFAULT_RULE_PATH, labels=ALL_CENSOR_LABELS)
activate_rule_profile(config, config.get("active_rule_profile", "default"))
return
if args.rules_action == "list":
print_header("Rule Profiles")
active = config.get("active_rule_profile", "default")
for name in sorted(profiles):
marker = "*" if name == active else " "
normalized = normalize_rules(profiles[name])
enabled = sum(1 for value in normalized.values() if value)
disabled = len(ALL_CENSOR_LABELS) - enabled
print(f"{marker} {name:18} blur={enabled:2} skip={disabled:2}")
return
if args.rules_action == "show":
name, rules = rule_profile(config, args.profile)
rules = normalize_rules(rules)
print_header(f"Rule Profile: {name}")
for label in ALL_CENSOR_LABELS:
print(f"{label:30} {'blur' if rules.get(label, True) else 'skip'}")
return
if args.rules_action == "use":
activate_rule_profile(config, args.profile)
return
if args.rules_action == "create":
if args.profile in profiles and not args.force:
print_error(f"Profile already exists: {args.profile}. Use --force to overwrite.")
return 2
if args.from_file:
profiles[args.profile] = load_blur_exception_rules(args.from_file, labels=ALL_CENSOR_LABELS)
elif args.base:
_, base_rules = rule_profile(config, args.base)
profiles[args.profile] = dict(base_rules)
else:
profiles[args.profile] = default_blur_rules()
save_config(config)
print_ok(f"Created rule profile '{args.profile}'")
return
if args.rules_action == "set":
name, rules = rule_profile(config, args.profile)
if args.label not in ALL_CENSOR_LABELS:
print_error(f"Unknown label: {args.label}")
return 2
rules[args.label] = parse_bool(args.value)
profiles[name] = normalize_rules(rules)
save_config(config)
if name == config.get("active_rule_profile"):
write_blur_exception_rules(DEFAULT_RULE_PATH, rules=profiles[name])
print_ok(f"{name}: {args.label} = {'true' if rules[args.label] else 'false'}")
return
if args.rules_action == "delete":
if args.profile == "default":
print_error("The default profile cannot be deleted.")
return 2
if args.profile not in profiles:
print_error(f"Profile does not exist: {args.profile}")
return 2
del profiles[args.profile]
if config.get("active_rule_profile") == args.profile:
config["active_rule_profile"] = "default"
activate_rule_profile(config, "default")
save_config(config)
print_ok(f"Deleted rule profile '{args.profile}'")
return
if args.rules_action == "export":
name, rules = rule_profile(config, args.profile)
write_blur_exception_rules(args.output, rules=normalize_rules(rules))
print_ok(f"Exported '{name}' to {args.output}")
return
def append_common_processing_options(command, config, args):
processing = config["processing"]
providers = args.providers if getattr(args, "providers", None) is not None else processing.get("providers", "")
if providers:
command.extend(["--providers", providers])
detectors = getattr(args, "detectors", None)
if detectors is None:
detectors = processing.get("detectors", "nude")
if detectors:
command.extend(["--detectors", str(detectors)])
object_model = getattr(args, "object_model", None) or processing.get("object_model")
if object_model:
command.extend(["--object-model", str(object_model)])
object_labels = getattr(args, "object_labels", None) or processing.get("object_labels")
if object_labels:
command.extend(["--object-labels", str(object_labels)])
object_threshold = getattr(args, "object_threshold", None)
if object_threshold is None:
object_threshold = processing.get("object_threshold")
if object_threshold not in (None, ""):
command.extend(["--object-threshold", str(object_threshold)])
return command
def clean_extra_args(extra):
extra = list(extra or [])
if extra and extra[0] == "--":
return extra[1:]
return extra
def screen_guard_args_from_config(config):
settings = config.get("screen_guard", {})
args = []
value_options = [
("monitor", "--monitor"),
("mode", "--mode"),
("fps", "--fps"),
("overlay_fps", "--overlay-fps"),
("threshold", "--threshold"),
("hold_ms", "--hold-ms"),
("rules", "--rules"),
("capture_backend", "--capture-backend"),
("smooth_iou", "--smooth-iou"),
("smooth_alpha", "--smooth-alpha"),
("stable_score_alpha", "--stable-score-alpha"),
("track_hold_ms", "--track-hold-ms"),
("merge_distance", "--merge-distance"),
("merge_overlap", "--merge-overlap"),
("feedback_delta", "--feedback-delta"),
("capture_hide_ms", "--capture-hide-ms"),
("stale_region_delta", "--stale-region-delta"),
("screen_change_delta", "--screen-change-delta"),
("label_filter", "--label-filter"),
("blur_style", "--blur-style"),
("blur_strength", "--blur-strength"),
("mask_shape", "--mask-shape"),
("block_color", "--block-color"),
("outline_color", "--outline-color"),
("safe_outline_color", "--safe-outline-color"),
("rule_skipped_outline_color", "--rule-skipped-outline-color"),
("label_bg", "--label-bg"),
("label_color", "--label-color"),
("line_width", "--line-width"),
("box_padding", "--box-padding"),
("min_box_area", "--min-box-area"),
]
for key, flag in value_options:
value = settings.get(key)
if value not in (None, ""):
args.extend([flag, str(value)])
providers = settings.get("providers") or config.get("processing", {}).get("providers", "")
if providers:
args.extend(["--providers", str(providers)])
mode = settings.get("mode", "box")
mode_defaults = {
"show_boxes": mode in {"box", "both", "block"},
"block_enabled": mode in {"block", "both"},
"blur_enabled": mode == "blur",
"privacy_on_detection": mode == "privacy",
}
render_bool_options = [
("show_boxes", "--show-boxes", "--no-boxes"),
("block_enabled", "--block-enabled", "--no-block"),
("blur_enabled", "--blur", "--no-blur"),
("privacy_on_detection", "--privacy-on-detection", "--no-privacy"),
]
for key, enabled_flag, disabled_flag in render_bool_options:
if key in settings and bool(settings.get(key)) != mode_defaults[key]:
args.append(enabled_flag if settings.get(key) else disabled_flag)
if settings.get("respect_rules") is False:
args.append("--ignore-rules")
if settings.get("smooth_overlay") is False:
args.append("--no-smooth-overlay")
if settings.get("merge_nearby") is False:
args.append("--no-merge-nearby")
if settings.get("feedback_safe_capture"):
args.append("--feedback-safe-capture")
if settings.get("drop_stale_on_screen_change") is False:
args.append("--keep-stale-regions")
if settings.get("exclude_overlay_capture") is False:
args.append("--allow-overlay-capture")
if settings.get("show_labels"):
args.append("--show-labels")
if settings.get("click_through") is False:
args.append("--no-click-through")
if settings.get("show_status"):
args.append("--show-status")
return args
def command_process(args):
config = load_config()
activate_rule_profile(config, config.get("active_rule_profile", "default"))
input_path = Path(args.input)
if not input_path.exists():
print_error(f"Input does not exist: {input_path}")
return 2
suffix = input_path.suffix.lower()
if suffix in IMAGE_EXTENSIONS:
target = "image"
elif suffix in VIDEO_EXTENSIONS:
target = "video"
else:
print_error(f"Unsupported input type: {input_path.suffix}")
return 2
if not script_exists(target):
print_error(f"Required script is missing: {script_path(target)}")
return 2
if target == "image":
processing = config["processing"]
command = [python_command(), str(script_path("image")), "-i", str(input_path)]
if args.output:
command.extend(["-o", args.output])
if args.blur:
command.append("-b")
if args.full_blur_rule:
command.extend(["-fbr", args.full_blur_rule])
if getattr(args, "color", False):
command.append("--color")
mask_color = getattr(args, "mask_color", None) or processing.get("mask_color")
if mask_color:
command.extend(["--mask-color", mask_color])
mask_shape = getattr(args, "mask_shape", None) or processing.get("mask_shape")
if mask_shape:
command.extend(["--mask-shape", mask_shape])
blur_strength = getattr(args, "blur_strength", None)
if blur_strength is None:
blur_strength = processing.get("blur_strength")
if blur_strength:
command.extend(["--blur-strength", str(blur_strength)])
blur_sigma = getattr(args, "blur_sigma", None)
if blur_sigma is None:
blur_sigma = processing.get("blur_sigma")
if blur_sigma:
command.extend(["--blur-sigma", str(blur_sigma)])
append_common_processing_options(command, config, args)
else:
processing = config["processing"]
command = [python_command(), str(script_path("video")), "-i", str(input_path), "-t", "video"]
video_output = args.output_dir or processing.get("video_output") or config["paths"].get("video_output")
if video_output:
command.extend(["-vo", video_output])
if getattr(args, "analyze_only", False):
command.append("--analyze-only")
if args.boxes:
command.append("-b")
if args.blur:
command.append("--blur")
if args.with_audio or processing.get("with_audio"):
command.append("-a")
codec = args.codec or processing.get("codec")
if codec:
command.extend(["-c", codec])
if args.delete_frames or processing.get("delete_frames"):
command.append("-df")
if args.enhanced_blur or processing.get("enhanced_blur"):
command.append("--enhanced-blur")
if args.color:
command.append("--color")
mask_color = args.mask_color or processing.get("mask_color")
if mask_color:
command.extend(["--mask-color", mask_color])
mask_shape = args.mask_shape or processing.get("mask_shape")
if mask_shape:
command.extend(["--mask-shape", mask_shape])
blur_strength = getattr(args, "blur_strength", None)
if blur_strength is None:
blur_strength = processing.get("blur_strength")
if blur_strength:
command.extend(["--blur-strength", str(blur_strength)])
blur_sigma = getattr(args, "blur_sigma", None)
if blur_sigma is None:
blur_sigma = processing.get("blur_sigma")
if blur_sigma:
command.extend(["--blur-sigma", str(blur_sigma)])
rule = args.rule or processing.get("rule")
if rule and rule != "0/0":
command.extend(["-r", rule])
fbr = args.full_blur_rule or processing.get("full_blur_rule")
if fbr:
command.extend(["-fbr", fbr])
if getattr(args, "save_report", False) or processing.get("save_report"):
command.append("--save-report")
report_formats = getattr(args, "report_formats", None) or processing.get("report_formats")
if report_formats:
command.extend(["--report-formats", str(report_formats)])
export_markers = getattr(args, "export_markers", None)
if export_markers is None:
export_markers = processing.get("export_markers")
if export_markers:
command.extend(["--export-markers", str(export_markers)])
marker_gap = getattr(args, "marker_gap", None)
if marker_gap is None:
marker_gap = processing.get("marker_gap")
if marker_gap:
command.extend(["--marker-gap", str(marker_gap)])
if args.ffmpeg_path:
command.extend(["--ffmpeg-path", args.ffmpeg_path])
append_common_processing_options(command, config, args)
return run_subprocess(command)
def command_launch(args):
name = args.target
if not script_exists(name):
print_error(f"{name} script is missing: {script_path(name)}")
return 2
command = [python_command(), str(script_path(name))]
extra = clean_extra_args(args.extra)
if name == "screen":
config = load_config()
activate_rule_profile(config, config.get("active_rule_profile", "default"))
command.extend(screen_guard_args_from_config(config))
if extra:
command.extend(extra)
return run_subprocess(command)
def command_screen(args):
return command_launch(argparse.Namespace(target="screen", extra=args.extra))
def command_providers(args):
config = load_config()
requested = parse_provider_list(args.providers or config["processing"].get("providers", ""))
try:
providers = select_onnx_providers(requested)
print_header("Selected ONNX Providers")
for provider in providers:
print(provider)
except Exception as exc:
print_error(f"Could not inspect providers: {exc}")
return 2
def interactive_scan():
while True:
choice = menu_select(
"Scan Media",
[
("Scan all media in input folder", "all"),
("Scan images only", "image"),
("Scan videos only", "video"),
("Scan a custom folder", "custom"),
],
)
if choice == "__back__":
return
config = load_config()
folder = None
media_type = choice
if choice == "custom":
folder = prompt("Folder to scan", default=str(resolve_app_path(config["paths"]["input"])))
media_type = choose_from_values("Media Type", ["all", "image", "video"], default="all", allow_back=False)
recursive = prompt_bool("Scan recursively", default=True)
clear_screen()
command_scan(argparse.Namespace(folder=folder, recursive=recursive, type=media_type, names_only=False, progress=True))
pause()
def interactive_process():
selected = menu_select(
"Process Media",
[
("Choose from input folder", "choose"),
("Type custom image/video path", "custom"),
],
)
if selected == "__back__":
return
input_path = choose_media_file("all") if selected == "choose" else prompt("Input file path", required=True)
if not input_path: