-
-
Notifications
You must be signed in to change notification settings - Fork 221
Expand file tree
/
Copy pathhelper_api.py
More file actions
1400 lines (1193 loc) · 52 KB
/
helper_api.py
File metadata and controls
1400 lines (1193 loc) · 52 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
from __future__ import annotations
import configparser
import json
import os
import platform
import secrets
import subprocess
import sys
import tempfile
import threading
import time
import zipfile
from pathlib import Path
from typing import Any
import requests
from fastapi import FastAPI, File, Form, HTTPException, Request, Response, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
from pydantic import BaseModel, Field
from helper_modules.common import DEVICE_OPTIONS, list_last_checkpoints, list_models, list_pt_models
from logic.buttons import Buttons
PROJECT_DIR = Path(__file__).resolve().parent
CONFIG_PATH = PROJECT_DIR / "config.ini"
VERSION_PATH = PROJECT_DIR / "version"
MODELS_DIR = PROJECT_DIR / "models"
UI_DIST_DIR = PROJECT_DIR / "helper_ui" / "dist"
CUDA_FILE_NAME = "cuda_12.8.0_571.96_windows.exe"
CUDA_URL = f"https://developer.download.nvidia.com/compute/cuda/12.8.0/local_installers/{CUDA_FILE_NAME}"
IS_WINDOWS = platform.system() == "Windows"
CONFIG_LOCK = threading.RLock()
STREAM_STATUS_PREFIX = "__SUNONE_HELPER_STREAM_STATUS__"
HELPER_TOKEN_COOKIE = "sunone_helper_token"
HELPER_TOKEN_HEADER = "x-sunone-helper-token"
HELPER_API_TOKEN = os.environ.get("SUNONE_HELPER_TOKEN") or secrets.token_urlsafe(32)
ALLOWED_ORIGINS = ["http://127.0.0.1:8501", "http://localhost:8501"]
SYSTEM_META_CACHE_PATH = PROJECT_DIR / ".helper_system_meta_cache.json"
SYSTEM_META_CACHE_TTL_SECONDS = 3600
SYSTEM_META_CACHE_LOCK = threading.RLock()
SYSTEM_STATUS_CACHE: dict[str, Any] | None = None
SYSTEM_STATUS_CACHE_EXPIRES_AT = 0.0
FIELD_MAP: dict[str, tuple[str, str, str, Any]] = {
"detection_window_width": ("Detection window", "detection_window_width", "int", 320),
"detection_window_height": ("Detection window", "detection_window_height", "int", 320),
"circle_capture": ("Detection window", "circle_capture", "bool", False),
"capture_fps": ("Capture Methods", "capture_fps", "int", 60),
"bettercam_monitor_id": ("Capture Methods", "bettercam_monitor_id", "int", 0),
"bettercam_gpu_id": ("Capture Methods", "bettercam_gpu_id", "int", 0),
"obs_camera_id": ("Capture Methods", "obs_camera_id", "str", "auto"),
"body_y_offset": ("Aim", "body_y_offset", "float", 0.1),
"hideout_targets": ("Aim", "hideout_targets", "bool", True),
"disable_headshot": ("Aim", "disable_headshot", "bool", False),
"disable_prediction": ("Aim", "disable_prediction", "bool", False),
"prediction_interval": ("Aim", "prediction_interval", "float", 0.3),
"hotkey_exit": ("Hotkeys", "hotkey_exit", "str", "F2"),
"hotkey_pause": ("Hotkeys", "hotkey_pause", "str", "F3"),
"hotkey_reload_config": ("Hotkeys", "hotkey_reload_config", "str", "F4"),
"mouse_dpi": ("Mouse", "mouse_dpi", "int", 800),
"mouse_sensitivity": ("Mouse", "mouse_sensitivity", "float", 2.0),
"mouse_fov_width": ("Mouse", "mouse_fov_width", "int", 40),
"mouse_fov_height": ("Mouse", "mouse_fov_height", "int", 40),
"mouse_min_speed_multiplier": ("Mouse", "mouse_min_speed_multiplier", "float", 1.0),
"mouse_max_speed_multiplier": ("Mouse", "mouse_max_speed_multiplier", "float", 1.5),
"mouse_lock_target": ("Mouse", "mouse_lock_target", "bool", False),
"mouse_auto_aim": ("Mouse", "mouse_auto_aim", "bool", False),
"mouse_ghub": ("Mouse", "mouse_ghub", "bool", False),
"mouse_rzr": ("Mouse", "mouse_rzr", "bool", False),
"auto_shoot": ("Shooting", "auto_shoot", "bool", False),
"triggerbot": ("Shooting", "triggerbot", "bool", False),
"force_click": ("Shooting", "force_click", "bool", False),
"bscope_multiplier": ("Shooting", "bscope_multiplier", "float", 1.0),
"arduino_move": ("Arduino", "arduino_move", "bool", False),
"arduino_shoot": ("Arduino", "arduino_shoot", "bool", False),
"arduino_port": ("Arduino", "arduino_port", "str", "COM3"),
"arduino_baudrate": ("Arduino", "arduino_baudrate", "int", 115200),
"arduino_16_bit_mouse": ("Arduino", "arduino_16_bit_mouse", "bool", False),
"ai_model_name": ("AI", "ai_model_name", "str", "sunxds_0.8.0.pt"),
"ai_model_image_size": ("AI", "ai_model_image_size", "int", 640),
"ai_conf": ("AI", "ai_conf", "float", 0.1),
"ai_device": ("AI", "ai_device", "str", "0"),
"ai_enable_amd": ("AI", "ai_enable_amd", "bool", False),
"disable_tracker": ("AI", "disable_tracker", "bool", False),
"show_overlay": ("overlay", "show_overlay", "bool", False),
"overlay_show_borders": ("overlay", "overlay_show_borders", "bool", True),
"overlay_show_boxes": ("overlay", "overlay_show_boxes", "bool", False),
"overlay_show_target_line": ("overlay", "overlay_show_target_line", "bool", False),
"overlay_show_target_prediction_line": ("overlay", "overlay_show_target_prediction_line", "bool", False),
"overlay_show_labels": ("overlay", "overlay_show_labels", "bool", False),
"overlay_show_conf": ("overlay", "overlay_show_conf", "bool", False),
"show_window": ("Debug window", "show_window", "bool", False),
"show_detection_speed": ("Debug window", "show_detection_speed", "bool", False),
"show_window_fps": ("Debug window", "show_window_fps", "bool", False),
"show_boxes": ("Debug window", "show_boxes", "bool", True),
"show_labels": ("Debug window", "show_labels", "bool", False),
"show_conf": ("Debug window", "show_conf", "bool", True),
"show_target_line": ("Debug window", "show_target_line", "bool", False),
"show_target_prediction_line": ("Debug window", "show_target_prediction_line", "bool", False),
"show_bscope_box": ("Debug window", "show_bscope_box", "bool", False),
"show_history_points": ("Debug window", "show_history_points", "bool", False),
"debug_window_always_on_top": ("Debug window", "debug_window_always_on_top", "bool", True),
"spawn_window_pos_x": ("Debug window", "spawn_window_pos_x", "int", 100),
"spawn_window_pos_y": ("Debug window", "spawn_window_pos_y", "int", 100),
"debug_window_scale_percent": ("Debug window", "debug_window_scale_percent", "int", 100),
"debug_window_screenshot_key": ("Debug window", "debug_window_screenshot_key", "str", "F12"),
}
class ConfigUpdateRequest(BaseModel):
config: dict[str, Any] = Field(default_factory=dict)
class ConfigFieldUpdateRequest(BaseModel):
key: str
value: Any = None
class ExportRequest(BaseModel):
model_name: str
image_size: int = 640
precision: str = "half"
data_yaml_path: str = "logic/game.yaml"
add_nms: bool = True
class TrainRequest(BaseModel):
selected_model_path: str
resume: bool = False
data_yaml: str = "logic/game.yaml"
epochs: int = 80
img_size: int = 640
use_cache: bool = False
augment: bool = True
augment_degrees: int = 5
augment_flipud: float = 0.2
train_device: str | int = "0"
batch_size: int | float = -1
profile: bool = False
disable_wandb: bool = True
def _parser() -> configparser.ConfigParser:
parser = configparser.ConfigParser()
with CONFIG_LOCK:
parser.read(CONFIG_PATH, encoding="utf-8")
return parser
def _as_bool(value: Any) -> bool:
if isinstance(value, bool):
return value
return str(value).strip().lower() in {"1", "true", "yes", "on"}
def _parse_version(lines: list[str]) -> dict[str, str | int]:
result: dict[str, str | int] = {"app_version": 0, "config_version": 0}
for line in lines:
if "=" not in line:
continue
key, value = line.strip().split("=", 1)
if key == "app":
result["app_version"] = value
elif key == "config":
result["config_version"] = value
return result
def _offline_version() -> dict[str, str | int]:
if not VERSION_PATH.exists():
return {"app_version": 0, "config_version": 0}
return _parse_version(VERSION_PATH.read_text(encoding="utf-8").splitlines())
def _online_version() -> dict[str, str | int]:
try:
response = requests.get("https://raw.githubusercontent.com/SunOner/sunone_aimbot/main/version", timeout=30)
response.raise_for_status()
return _parse_version(response.text.splitlines())
except requests.RequestException:
return {"app_version": 0, "config_version": 0}
def _find_cuda_paths(version: str = "12.8") -> list[str]:
path_parts = os.environ.get("PATH", "").split(os.pathsep)
return [item for item in path_parts if "cuda" in item.lower() and version in item]
def _python_probe(script: str, timeout: int = 30) -> dict[str, Any]:
try:
result = subprocess.run(
[sys.executable, "-c", script],
cwd=PROJECT_DIR,
capture_output=True,
text=True,
timeout=timeout,
)
except (OSError, subprocess.TimeoutExpired) as exc:
return {"available": False, "error": str(exc)}
if result.returncode != 0:
return {"available": False, "error": (result.stderr or result.stdout).strip()}
output_lines = [line for line in result.stdout.splitlines() if line.strip()]
if not output_lines:
return {"available": False, "error": "Probe returned no output."}
try:
return json.loads(output_lines[-1])
except json.JSONDecodeError:
return {"available": False, "error": result.stdout.strip()}
def _torch_info() -> dict[str, Any]:
info = _python_probe(
"import json\n"
"import sys\n"
"try:\n"
" import torch\n"
" devices = []\n"
" if torch.cuda.is_available():\n"
" devices = [torch.cuda.get_device_name(index) for index in range(torch.cuda.device_count())]\n"
" print(json.dumps({\n"
" 'available': True,\n"
" 'cuda': bool(torch.cuda.is_available()),\n"
" 'version': str(torch.__version__),\n"
" 'torch_cuda': str(getattr(torch.version, 'cuda', '') or ''),\n"
" 'device_count': int(torch.cuda.device_count()),\n"
" 'devices': devices,\n"
" 'executable': sys.executable,\n"
" 'torch_file': getattr(torch, '__file__', ''),\n"
" }))\n"
"except ModuleNotFoundError as exc:\n"
" print(json.dumps({'available': False, 'cuda': False, 'error': str(exc), 'executable': sys.executable}))\n"
"except Exception as exc:\n"
" print(json.dumps({'available': False, 'cuda': False, 'error': str(exc), 'executable': sys.executable}))\n"
)
if not info.get("available"):
return {
"available": False,
"cuda": False,
"version": None,
"torch_cuda": None,
"device_count": 0,
"devices": [],
"executable": info.get("executable") or sys.executable,
"torch_file": None,
"error": info.get("error"),
}
return {
"available": True,
"cuda": bool(info.get("cuda")),
"version": str(info.get("version") or ""),
"torch_cuda": str(info.get("torch_cuda") or ""),
"device_count": int(info.get("device_count") or 0),
"devices": info.get("devices") if isinstance(info.get("devices"), list) else [],
"executable": str(info.get("executable") or sys.executable),
"torch_file": str(info.get("torch_file") or ""),
"error": info.get("error"),
}
def _torch_gpu_support() -> bool | None:
info = _torch_info()
if not info.get("available"):
return None
return bool(info.get("cuda"))
def _tensorrt_info() -> dict[str, Any]:
info = _python_probe(
"import json\n"
"try:\n"
" import tensorrt\n"
" print(json.dumps({'available': True, 'version': str(tensorrt.__version__)}))\n"
"except ModuleNotFoundError:\n"
" print(json.dumps({'available': False, 'version': None}))\n"
)
if not info.get("available"):
return {"available": False, "version": None}
return {"available": True, "version": str(info.get("version"))}
def _ultralytics_version() -> str | None:
info = _python_probe(
"import json\n"
"try:\n"
" import ultralytics\n"
" print(json.dumps({'available': True, 'version': str(ultralytics.__version__)}))\n"
"except ModuleNotFoundError:\n"
" print(json.dumps({'available': False, 'version': None}))\n"
)
if not info.get("available"):
return None
return str(info.get("version"))
def _read_value(parser: configparser.ConfigParser, section: str, option: str, value_type: str, default: Any) -> Any:
if value_type == "bool":
return parser.getboolean(section, option, fallback=default)
if value_type == "int":
return parser.getint(section, option, fallback=default)
if value_type == "float":
return parser.getfloat(section, option, fallback=default)
return parser.get(section, option, fallback=default)
def _coerce_value(value: Any, value_type: str) -> Any:
if value_type == "bool":
return _as_bool(value)
if value_type == "int":
return int(value)
if value_type == "float":
return float(value)
return str(value)
def _set_value(parser: configparser.ConfigParser, section: str, option: str, value: Any) -> None:
if not parser.has_section(section):
parser.add_section(section)
if isinstance(value, bool):
parser.set(section, option, "True" if value else "False")
else:
parser.set(section, option, str(value))
def _write_config(parser: configparser.ConfigParser) -> None:
temp_path: Path | None = None
with CONFIG_LOCK:
try:
with tempfile.NamedTemporaryFile(
delete=False,
dir=PROJECT_DIR,
encoding="utf-8",
mode="w",
suffix=".ini",
) as file:
parser.write(file)
temp_path = Path(file.name)
os.replace(temp_path, CONFIG_PATH)
finally:
if temp_path and temp_path.exists():
try:
temp_path.unlink()
except OSError:
pass
def _config_file_version() -> dict[str, int]:
try:
stat = CONFIG_PATH.stat()
except FileNotFoundError:
return {"mtime_ns": 0, "size": 0}
return {"mtime_ns": stat.st_mtime_ns, "size": stat.st_size}
def _set_capture_method(parser: configparser.ConfigParser, value: Any) -> None:
capture = str(value).lower()
if capture not in {"bettercam", "obs", "mss"}:
raise ValueError(f"Unknown capture method: {value}")
_set_value(parser, "Capture Methods", "bettercam_capture", capture == "bettercam")
_set_value(parser, "Capture Methods", "obs_capture", capture == "obs")
_set_value(parser, "Capture Methods", "mss_capture", capture == "mss")
def _set_hotkey_targeting(parser: configparser.ConfigParser, value: Any) -> None:
if isinstance(value, list):
_set_value(parser, "Hotkeys", "hotkey_targeting", ",".join(str(item) for item in value))
else:
_set_value(parser, "Hotkeys", "hotkey_targeting", str(value))
def _snapshot_config() -> dict[str, Any]:
parser = _parser()
config: dict[str, Any] = {}
for key, (section, option, value_type, default) in FIELD_MAP.items():
config[key] = _read_value(parser, section, option, value_type, default)
if parser.getboolean("Capture Methods", "obs_capture", fallback=False):
config["capture_method"] = "obs"
elif parser.getboolean("Capture Methods", "mss_capture", fallback=True):
config["capture_method"] = "mss"
else:
config["capture_method"] = "bettercam"
raw_targeting = parser.get("Hotkeys", "hotkey_targeting", fallback="")
config["hotkey_targeting"] = [item.strip() for item in raw_targeting.split(",") if item.strip()]
return config
def _save_config(values: dict[str, Any]) -> None:
with CONFIG_LOCK:
parser = _parser()
for key, (section, option, value_type, _) in FIELD_MAP.items():
if key in values:
_set_value(parser, section, option, _coerce_value(values[key], value_type))
if "capture_method" in values:
_set_capture_method(parser, values["capture_method"])
if "hotkey_targeting" in values:
_set_hotkey_targeting(parser, values["hotkey_targeting"])
_write_config(parser)
def _save_config_field(key: str, value: Any) -> None:
with CONFIG_LOCK:
parser = _parser()
if key == "capture_method":
_set_capture_method(parser, value)
elif key == "hotkey_targeting":
_set_hotkey_targeting(parser, value)
elif key in FIELD_MAP:
section, option, value_type, _ = FIELD_MAP[key]
_set_value(parser, section, option, _coerce_value(value, value_type))
else:
raise KeyError(key)
_write_config(parser)
def _run_command(command: list[str]) -> tuple[bool, str]:
result = subprocess.run(command, cwd=PROJECT_DIR, capture_output=True, text=True)
output = "\n".join([result.stdout.strip(), result.stderr.strip()]).strip()
return result.returncode == 0, output
def _format_command(command: list[str]) -> str:
return " ".join(f'"{part}"' if " " in part else part for part in command)
def _stream_status(ok: bool, message: str, **extra: Any) -> str:
payload = json.dumps({"ok": ok, "message": message, **extra}, separators=(",", ":"))
return f"\n{STREAM_STATUS_PREFIX}{payload}\n"
def _split_stream_result(raw_output: str) -> tuple[str, dict[str, Any] | None]:
marker_index = raw_output.rfind(STREAM_STATUS_PREFIX)
if marker_index < 0:
return raw_output, None
output = raw_output[:marker_index].strip()
status_line = raw_output[marker_index + len(STREAM_STATUS_PREFIX) :].strip().splitlines()[0]
try:
status = json.loads(status_line)
except json.JSONDecodeError:
status = None
return output, status if isinstance(status, dict) else None
def _stream_commands(commands: list[list[str]], success_message: str, failure_message: str):
env = os.environ.copy()
env["PYTHONUNBUFFERED"] = "1"
env["PYTHONIOENCODING"] = "utf-8"
for command in commands:
yield f"$ {_format_command(command)}\n"
try:
process = subprocess.Popen(
command,
cwd=PROJECT_DIR,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
bufsize=1,
)
except OSError as exc:
yield f"Failed to start command: {exc}\n"
yield _stream_status(False, failure_message)
return
if process.stdout is not None:
for line in process.stdout:
yield line
returncode = process.wait()
if returncode != 0:
yield f"\nCommand exited with code {returncode}.\n"
yield _stream_status(False, failure_message)
return
yield "\n"
yield _stream_status(True, success_message)
def _stream_python_script(
script: str,
success_message: str,
failure_message: str,
*,
env_overrides: dict[str, str] | None = None,
cleanup_paths: list[Path] | None = None,
):
cleanup_paths = cleanup_paths or []
temp_path: Path | None = None
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=".py", dir=PROJECT_DIR, encoding="utf-8", mode="w") as temp_script:
temp_script.write(script)
temp_path = Path(temp_script.name)
command = [sys.executable, str(temp_path)]
yield f"$ {_format_command(command)}\n"
env = os.environ.copy()
env["PYTHONUNBUFFERED"] = "1"
env["PYTHONIOENCODING"] = "utf-8"
if env_overrides:
env.update(env_overrides)
try:
process = subprocess.Popen(
command,
cwd=PROJECT_DIR,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
bufsize=1,
)
except OSError as exc:
yield f"Failed to start process: {exc}\n"
yield _stream_status(False, failure_message)
return
if process.stdout is not None:
for line in process.stdout:
yield line
returncode = process.wait()
if returncode != 0:
yield f"\nProcess exited with code {returncode}.\n"
yield _stream_status(False, failure_message)
return
yield _stream_status(True, success_message)
finally:
if temp_path and temp_path.exists():
try:
temp_path.unlink()
except OSError:
pass
for cleanup_path in cleanup_paths:
try:
cleanup_path.unlink()
except FileNotFoundError:
pass
except OSError:
pass
def _stream_download_cuda():
if not IS_WINDOWS:
yield "CUDA installer download is only automated on Windows. Install NVIDIA drivers/CUDA with your Ubuntu package manager or NVIDIA's Linux installer.\n"
yield _stream_status(False, "CUDA download helper is Windows-only.")
return
destination = PROJECT_DIR / CUDA_FILE_NAME
bytes_downloaded = 0
last_report = 0.0
try:
yield f"Downloading {CUDA_FILE_NAME}...\n"
with requests.get(CUDA_URL, stream=True, timeout=60) as response:
response.raise_for_status()
total_bytes = int(response.headers.get("content-length", 0) or 0)
with destination.open("wb") as file:
for chunk in response.iter_content(chunk_size=1024 * 1024):
if not chunk:
continue
file.write(chunk)
bytes_downloaded += len(chunk)
now = time.monotonic()
if now - last_report >= 0.8:
last_report = now
if total_bytes:
percent = bytes_downloaded * 100 / total_bytes
yield f"Downloaded {bytes_downloaded / 1024 / 1024:.1f} MB / {total_bytes / 1024 / 1024:.1f} MB ({percent:.1f}%)\n"
else:
yield f"Downloaded {bytes_downloaded / 1024 / 1024:.1f} MB\n"
yield f"Downloaded to {destination}\n"
try:
subprocess.Popen([str(destination)], cwd=PROJECT_DIR)
except OSError as exc:
yield f"CUDA downloaded but failed to launch: {exc}\n"
yield _cuda_manual_launch_hint(destination)
yield _stream_status(False, "CUDA downloaded, but the installer requires manual launch.")
return
_invalidate_system_meta_cache()
yield _stream_status(True, "CUDA installer downloaded and launched.")
except (requests.RequestException, OSError) as exc:
yield f"Download failed: {exc}\n"
yield _stream_status(False, "CUDA download failed.")
def _format_torch_info(info: dict[str, Any]) -> str:
devices = ", ".join(str(device) for device in info.get("devices") or []) or "none"
lines = [
f"Python executable: {info.get('executable') or sys.executable}",
f"Torch installed: {bool(info.get('available'))}",
f"Torch version: {info.get('version') or 'not installed'}",
f"Torch CUDA build: {info.get('torch_cuda') or 'none'}",
f"torch.cuda.is_available(): {bool(info.get('cuda'))}",
f"CUDA device count: {info.get('device_count') or 0}",
f"CUDA devices: {devices}",
]
if info.get("torch_file"):
lines.append(f"Torch file: {info['torch_file']}")
if info.get("error"):
lines.append(f"Probe error: {info['error']}")
return "\n".join(lines)
def _ensure_torch_cuda_for_aimbot() -> None:
config = _snapshot_config()
if str(config.get("ai_device", "")).strip().lower().startswith("cpu") or bool(config.get("ai_enable_amd")):
return
info = _torch_info()
if info.get("cuda") is True:
return
raise HTTPException(
status_code=400,
detail={
"message": "PyTorch CUDA is not available for the selected AI device.",
"output": (
"Aimbot is configured to use GPU, but PyTorch does not see CUDA in this Python environment.\n"
f"{_format_torch_info(info)}\n\n"
"Use Reinstall Torch in Helper, or run:\n"
"pip uninstall torch torchvision torchaudio -y\n"
"pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128"
),
},
)
def _cuda_manual_launch_hint(destination: Path) -> str:
return (
"Manual launch required:\n"
f"1. Run this installer as Administrator: {destination}\n"
f'2. Or run in PowerShell: Start-Process -FilePath "{destination}" -Verb RunAs\n'
)
def _torch_reinstall_commands() -> list[list[str]]:
return [
[sys.executable, "-m", "pip", "uninstall", "torch", "torchvision", "torchaudio", "-y"],
[sys.executable, "-m", "pip", "install", "torch", "torchvision", "torchaudio", "--index-url", "https://download.pytorch.org/whl/cu128"],
]
def _tensorrt_reinstall_commands() -> list[list[str]]:
return [
[sys.executable, "-m", "pip", "uninstall", "tensorrt", "tensorrt-bindings", "tensorrt-cu12", "tensorrt-cu12_bindings", "tensorrt-cu12_libs", "tensorrt-libs", "-y"],
[sys.executable, "-m", "pip", "install", "tensorrt"],
]
def _download_file(url: str, destination: Path) -> tuple[bool, str]:
try:
with requests.get(url, stream=True, timeout=60) as response:
response.raise_for_status()
with destination.open("wb") as file:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
file.write(chunk)
return True, "Downloaded"
except (requests.RequestException, OSError) as exc:
return False, str(exc)
def _reinstall_aimbot() -> tuple[bool, str]:
archive = PROJECT_DIR / "main.zip"
extract_dir = PROJECT_DIR / "temp_extract"
repo_root = extract_dir / "sunone_aimbot-main"
ok, message = _download_file(
"https://github.com/SunOner/sunone_aimbot/archive/refs/heads/main.zip",
archive,
)
if not ok:
return False, message
try:
with zipfile.ZipFile(archive, "r") as zip_ref:
zip_ref.extractall(extract_dir)
except Exception as exc:
return False, f"Unpack failed: {exc}"
online_cfg = int(_online_version().get("config_version", 0) or 0)
offline_cfg = int(_offline_version().get("config_version", 0) or 0)
replace_config = online_cfg != offline_cfg
try:
for source_file in repo_root.rglob("*"):
if not source_file.is_file():
continue
relative = source_file.relative_to(repo_root)
if relative.as_posix() == "config.ini" and not replace_config:
continue
destination = PROJECT_DIR / relative
destination.parent.mkdir(parents=True, exist_ok=True)
if destination.exists():
destination.unlink()
source_file.replace(destination)
except Exception as exc:
return False, f"Move files failed: {exc}"
finally:
if archive.exists():
archive.unlink()
if extract_dir.exists():
for item in extract_dir.rglob("*"):
try:
if item.is_file():
item.unlink()
except OSError:
pass
try:
for item in sorted(extract_dir.rglob("*"), reverse=True):
if item.is_dir():
item.rmdir()
extract_dir.rmdir()
except OSError:
pass
return True, "Aimbot files were updated from GitHub."
def _status() -> dict[str, Any]:
torch_info = _torch_info()
return {
"platform": platform.system(),
"python": ".".join(str(part) for part in sys.version_info[:3]),
"ultralytics": _ultralytics_version(),
"aimbot_versions": {"offline": _offline_version(), "online": _online_version()},
"cuda": {"available": len(_find_cuda_paths()) > 0, "paths": _find_cuda_paths()},
"torch": torch_info,
"torch_gpu_support": None if not torch_info.get("available") else bool(torch_info.get("cuda")),
"tensorrt": _tensorrt_info(),
}
def _invalidate_system_meta_cache() -> None:
global SYSTEM_STATUS_CACHE, SYSTEM_STATUS_CACHE_EXPIRES_AT
with SYSTEM_META_CACHE_LOCK:
SYSTEM_STATUS_CACHE = None
SYSTEM_STATUS_CACHE_EXPIRES_AT = 0.0
try:
SYSTEM_META_CACHE_PATH.unlink()
except FileNotFoundError:
pass
except OSError:
pass
def _read_system_status_cache(now: float) -> dict[str, Any] | None:
try:
cached = json.loads(SYSTEM_META_CACHE_PATH.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return None
expires_at = float(cached.get("expires_at", 0) or 0)
status = cached.get("status")
if not isinstance(status, dict):
legacy_meta = cached.get("meta")
status = legacy_meta.get("status") if isinstance(legacy_meta, dict) else None
if expires_at <= now or not isinstance(status, dict):
return None
return status
def _write_system_status_cache(status: dict[str, Any], expires_at: float) -> None:
temp_path: Path | None = None
try:
with tempfile.NamedTemporaryFile(
delete=False,
dir=PROJECT_DIR,
encoding="utf-8",
mode="w",
suffix=".meta-cache.json",
) as file:
json.dump({"expires_at": expires_at, "status": status}, file)
temp_path = Path(file.name)
os.replace(temp_path, SYSTEM_META_CACHE_PATH)
except OSError:
pass
finally:
if temp_path and temp_path.exists():
try:
temp_path.unlink()
except OSError:
pass
def _cached_status(force: bool = False) -> dict[str, Any]:
global SYSTEM_STATUS_CACHE, SYSTEM_STATUS_CACHE_EXPIRES_AT
now_monotonic = time.monotonic()
now_epoch = time.time()
with SYSTEM_META_CACHE_LOCK:
if not force and SYSTEM_STATUS_CACHE is not None and now_monotonic < SYSTEM_STATUS_CACHE_EXPIRES_AT:
return dict(SYSTEM_STATUS_CACHE)
if not force:
cached_status = _read_system_status_cache(now_epoch)
if cached_status is not None:
SYSTEM_STATUS_CACHE = dict(cached_status)
SYSTEM_STATUS_CACHE_EXPIRES_AT = now_monotonic + SYSTEM_META_CACHE_TTL_SECONDS
return dict(cached_status)
status = _status()
expires_at_epoch = time.time() + SYSTEM_META_CACHE_TTL_SECONDS
with SYSTEM_META_CACHE_LOCK:
SYSTEM_STATUS_CACHE = dict(status)
SYSTEM_STATUS_CACHE_EXPIRES_AT = time.monotonic() + SYSTEM_META_CACHE_TTL_SECONDS
_write_system_status_cache(status, expires_at_epoch)
return status
def _system_meta(force: bool = False) -> dict[str, Any]:
models = list_models(MODELS_DIR)
pt_models = list_pt_models(MODELS_DIR)
return {
"ok": True,
"status": _cached_status(force=force),
"device_options": DEVICE_OPTIONS,
"hotkey_options": list(Buttons.KEY_CODES.keys()),
"models": models,
"pt_models": pt_models,
"last_checkpoints": list_last_checkpoints(r"runs\detect"),
"pretrained_models": pt_models,
"obs_camera_options": ["auto"] + [str(i) for i in range(11)],
}
def _resolve_train_model_path(model_path: str) -> str:
requested = Path(model_path)
if requested.name == model_path and (MODELS_DIR / requested.name).is_file():
return str(Path("models") / requested.name)
candidate = requested if requested.is_absolute() else PROJECT_DIR / requested
if not candidate.is_file():
raise HTTPException(status_code=400, detail=f"Model not found: {model_path}")
try:
return str(candidate.relative_to(PROJECT_DIR))
except ValueError:
return str(candidate)
def _build_train_script(payload: TrainRequest, train_device: str | int, selected_model_path: str) -> str:
lines = [
"from ultralytics import YOLO",
"",
"if __name__ == '__main__':",
f" print('Loading model:', {selected_model_path!r}, flush=True)",
f" m = YOLO({selected_model_path!r})",
" print('Starting training...', flush=True)",
" m.train(",
f" device={train_device!r},",
f" batch={payload.batch_size},",
f" resume={payload.resume},",
]
if not payload.resume:
lines.extend(
[
f" data={payload.data_yaml!r},",
f" epochs={payload.epochs},",
f" imgsz={payload.img_size},",
f" profile={payload.profile},",
f" cache={payload.use_cache},",
f" augment={payload.augment},",
]
)
if payload.augment:
lines.extend([f" degrees={payload.augment_degrees},", f" flipud={payload.augment_flipud},"])
lines.append(" )")
lines.append(" print('Training completed.', flush=True)")
return "\n".join(lines)
def _train_script_and_env(payload: TrainRequest) -> tuple[str, dict[str, str]]:
train_device: str | int = payload.train_device
if isinstance(train_device, str) and train_device != "cpu":
try:
train_device = int(train_device)
except ValueError as exc:
raise HTTPException(status_code=400, detail=f"Invalid train device: {payload.train_device}") from exc
selected_model_path = _resolve_train_model_path(payload.selected_model_path)
return _build_train_script(payload, train_device, selected_model_path), {
"WANDB_DISABLED": "true" if payload.disable_wandb else "false"
}
def _stream_train(payload: TrainRequest):
script, env_overrides = _train_script_and_env(payload)
yield from _stream_python_script(
script,
"Training completed.",
"Training failed.",
env_overrides=env_overrides,
)
_invalidate_system_meta_cache()
def _export_params(payload: ExportRequest) -> dict[str, Any]:
params: dict[str, Any] = {
"format": "engine",
"imgsz": payload.image_size,
"half": payload.precision == "half",
"int8": payload.precision == "int8",
"device": 0,
"nms": payload.add_nms and payload.precision != "int8",
}
if payload.precision == "int8":
params["data"] = payload.data_yaml_path or "logic/game.yaml"
return params
def _export_model_path(model_name: str) -> Path:
model_path = MODELS_DIR / model_name
if not model_path.exists():
raise HTTPException(status_code=400, detail=f"Model not found: {model_name}")
return model_path
def _build_export_script(model_path: Path, params: dict[str, Any]) -> str:
return "\n".join(
[
"from ultralytics import YOLO",
"",
"if __name__ == '__main__':",
f" exported = YOLO({str(model_path)!r}).export(**{params!r})",
" print(f'Exported path: {exported}', flush=True)",
]
)
def _stream_export(payload: ExportRequest, model_path: Path):
yield from _stream_python_script(
_build_export_script(model_path, _export_params(payload)),
"Model exported successfully.",
"Export failed.",
)
_invalidate_system_meta_cache()
def _build_tests_script(params: dict[str, Any]) -> str:
return "\n".join(
[
"import cv2",
"import platform",
"from ultralytics import YOLO",
"",
f"model_path = {params['model_path']!r}",
f"video_source = {params['video_source']!r}",
f"topmost = {bool(params['topmost'])!r}",
f"model_image_size = {int(params['model_image_size'])!r}",
f"device = {params['device']!r}",
f"input_delay = {int(params['input_delay'])!r}",
f"resize_factor = {int(params['resize_factor'])!r}",
f"ai_conf = {float(params['ai_conf'])!r}",
"",
"print('Loading model:', model_path, flush=True)",
"model = YOLO(model_path, task='detect')",
"print('Opening video source:', video_source, flush=True)",
"cap = cv2.VideoCapture(video_source)",
"if not cap.isOpened():",
" raise RuntimeError('Could not open video source.')",
"window_name = 'Detections test'",
"cv2.namedWindow(window_name)",
"if topmost and platform.system() == 'Windows':",
" try:",
" import win32con",
" import win32gui",
" hwnd = win32gui.FindWindow(None, window_name)",
" if hwnd:",
" win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 100, 100, 200, 200, 0)",
" except Exception as exc:",
" print(f'Topmost window mode unavailable: {exc}', flush=True)",
"frames = 0",
"try:",
" while cap.isOpened():",
" ok, frame = cap.read()",
" if not ok:",
" break",
" result = model(frame, stream=False, show=False, imgsz=model_image_size, device=device, verbose=False, conf=ai_conf)",
" annotated = result[0].plot()",
" frame_height, frame_width = frame.shape[:2]",
" dim = (int(frame_width * resize_factor / 100), int(frame_height * resize_factor / 100))",
" cv2.resizeWindow(window_name, dim)",
" cv2.imshow(window_name, cv2.resize(annotated, dim, cv2.INTER_NEAREST))",