-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathaura_engine.py
More file actions
1443 lines (961 loc) · 48.1 KB
/
Copy pathaura_engine.py
File metadata and controls
1443 lines (961 loc) · 48.1 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
# aura_engine.py
# 20260904_1847
import os
import sys
# == AUTO-BOOTSTRAP ============================================================================
# --- PREREQUISITE 1: VIRTUAL ENVIRONMENT CHECK & AUTO-BOOTSTRAP ---
# Ensures the engine actually runs inside its .venv to avoid dependency issues.
# import scripts.py.bootstrap_venv
# from scripts.py.bootstrap_venv import bootstrap_hello
# bootstrap_hello() # its a dummy hello to prevent removed by linter
# === AUTO-BOOTSTRAP ===========================================================================
from scripts.py.bootstrap_venv import bootstrap_hello
bootstrap_hello()
# === AUTO-BOOTSTRAP ===========================================================================
#from config.settings import LANGUAGETOOL_CHECK_URL
# Python path to ensure reliable imports on all platforms
# This solves potential issues when running from a batch script on Windows
# os.environ["AURA_SELF_TEST_RUNNING"] = "0"
import atexit
import importlib
import logging
import platform
import re
import shutil
import signal
import subprocess
import threading
import time
from datetime import datetime, timedelta
from pathlib import Path
import objgraph
import psutil
import requests
from scripts.py.func import global_state
from scripts.py.func.config.dynamic_settings import settings
from scripts.py.set_secrets_to_DEFAULT_CONTENT import demo_secrets
SECRETS_PATH = Path(".secrets")
demo_secrets()
# PREREQUISITE: Write project root early to prevent import crashes in submodules when the project was moved to other folder
from scripts.py.func.create_required_folders import setup_project_structure
from scripts.py.func.get_project_root import get_aura_project_root
SCRIPT_DIR = Path(__file__).resolve().parent
SL5NET_AURA_PROJECT_ROOT = get_aura_project_root()
setup_project_structure(SL5NET_AURA_PROJECT_ROOT)
TMP_DIR = Path("C:/tmp") if platform.system() == "Windows" else Path("/tmp")
PROJECT_ROOT_FILE = TMP_DIR / "sl5_aura" / "sl5net_aura_project_root"
PROJECT_ROOT_FILE.write_text(str(SL5NET_AURA_PROJECT_ROOT), encoding="utf-8")
os.environ["SL5NET_AURA_PROJECT_ROOT"] = str(SL5NET_AURA_PROJECT_ROOT)
# Clean up search history file on startup for privacy (relevant in windows OS systems)
history_file = TMP_DIR / "sl5_aura" / "search_rules_history.txt"
if history_file.exists():
try:
history_file.unlink()
except Exception as e:
print(f"Ok. NP. {e}")
if settings.LOG_delete_on_startup:
log_dir = Path("log") # folder named "log"
if not log_dir.is_dir():
raise SystemExit(f"{log_dir} does not exist or is not a directory")
setup_log_dir = (log_dir / "setup").resolve()
for p in log_dir.rglob("*.log"): # rglob is recursive
if setup_log_dir in p.resolve().parents:
continue
try:
p.unlink()
except Exception as e:
print(f"Failed to remove {p}: {e}")
from scripts.py.func.checks.check_path_length import run_path_check
from scripts.py.func.checks.check_settings_usage import check_settings_usage
from scripts.py.func.checks.espeak_check import espeak_check
espeak_check(settings)
from scripts.py.func.checks.check_settings_syntax import verify_plugin_notation
from scripts.py.func.check_for_updates import check_for_updates
if settings.TRINO_ENABLED:
from scripts.py.func.db.init_trino_db import init_all as init_trino
def async_trino_init():
try:
init_trino()
except Exception as e:
print(f"[AURA ENGINE] WARNING: Failed to initialize Trino database: {e}")
print("[AURA ENGINE] Database features may be unavailable.")
trino_thread = threading.Thread(target=async_trino_init, daemon=True)
trino_thread.start()
print("[AURA ENGINE] Trino database initialization started asynchronously in the background…")
verify_plugin_notation(settings.PLUGINS_ENABLED)
if getattr(settings, 'KILL_COMPETING_LT_AND_ELOQUENT_ON_START', False):
os.system("pkill -f 'eloquent'")
os.system("pkill -f '/app/LanguageTool/languagetool-server.jar'")
if settings.ENABLE_AUTO_LANGUAGE_DETECTION:
# Check if the package is installed without actually importing it
if importlib.util.find_spec("fasttext") is None:
logging.warning("FastText is not installed but is enabled in config.")
logging.info("At ting to install 'fasttext-wheel' automatically…")
try:
subprocess.check_call([sys.executable, "-m", "pip", "install", "fasttext-wheel"])
logging.info("INFO: FastText installed successfully. Please restart the service to activate it.")
sys.exit(0)
except subprocess.CalledProcessError:
logging.error("Failed to install FastText. Please install it manually: pip install fasttext-wheel")
sys.exit(1)
else:
logging.info("FastText for auto language detection is available.")
from scripts.py.func.main import main
#from scripts.py.func.notify import notify
#from scripts.py.func.cleanup import cleanup
#from scripts.py.func.start_languagetool_server import start_languagetool_server
#from scripts.py.func.stop_languagetool_server import stop_languagetool_server
#from scripts.py.func.check_memory_critical import check_memory_critical
# We need vosk here for the model loading
# import vosk
# --- Constants and Paths ---
# SL5NET_AURA_PROJECT_ROOT = Path(__file__).resolve().parent
_log_dir = SL5NET_AURA_PROJECT_ROOT / "log"
if not _log_dir.exists():
shutil.copy(
PROJECT_ROOT_FILE / 'config' / 'filters' / '.backlock' / 'first_run' / 'settings_local_log_filter.py',
PROJECT_ROOT_FILE / 'config' / 'filters' / 'settings_local_log_filter.py'
)
LOG_FILE = SL5NET_AURA_PROJECT_ROOT / "log" / "aura_engine.log" # NICHT mit Path("log/…") überschreiben! könnte zu leidem äergerlichen unmerkbaren fehlern führen.
AURA_SELF_TEST_RUNNING =TMP_DIR / "sl5_aura" / "aura_self_test_running.flag"
# ==============================================================================
# --- PRE-RUN SETUP VALIDATION ---
# aura_engine.py:123
if str(SL5NET_AURA_PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(SL5NET_AURA_PROJECT_ROOT))
project_root = SL5NET_AURA_PROJECT_ROOT
sys.path.append(str(project_root))
# We add the 'scripts' directory to the path to import our custom validator.
# sys.path.append(os.path.join(SCRIPT_DIR, 'scripts'))
from scripts.py.func.checks.check_installer_sizes import check_installer_sizes
from scripts.py.func.checks.validate_punctuation_map_keys import (
validate_punctuation_map_keys,
)
# File: STT/aura_engine.py
# …
# --- Wrapper Script Check ---
#sys.exit(1)
# ==============================================================================
# ==============================================================================
# ==============================================================================
TRIGGER_FILE = TMP_DIR / "sl5_record.trigger"
HEARTBEAT_FILE = TMP_DIR / "sl5_aura" / "aura_engine.heartbeat"
PIDFILE = TMP_DIR / "sl5_aura" / "aura_engine.pid"
LOCK_DIR = TMP_DIR / "sl5_aura" / "aura_lock"
# backup settings.x11_input_method_OVERRIDE so linux/mac shell script can read this easier
settings_py_PATH = SL5NET_AURA_PROJECT_ROOT / 'config' / 'settings.py'
settings_py_backup_DIR = TMP_DIR / "sl5_aura" / "settings_py_backup"
settings_py_backup_PATH = TMP_DIR / "sl5_aura" / "settings_py_backup"
backup_settings_x11_input_method_OVERRIDE_PATH = settings_py_backup_PATH / 'x11_input_method_OVERRIDE.txt'
import os
path = backup_settings_x11_input_method_OVERRIDE_PATH
content = settings.x11_input_method_OVERRIDE
# os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
f.write(content)
#
#
# with open(backup_settings_x11_input_method_OVERRIDE_PATH, 'w') as f:
# f.write(settings.x11_input_method_OVERRIDE)
LANGUAGETOOL_JAR_PATH = SL5NET_AURA_PROJECT_ROOT / settings.LANGUAGETOOL_RELATIVE_PATH
suspicious_events = []
if platform.system() == "Windows":
NOTIFY_SEND_PATH = None
OUTPUT_FILE = TMP_DIR / "sl5_aura" / "tts_output" / "tts_output.txt"
# logging.info(f"Auto-Zip: ✅ flag set - self-tests running")
HEARTBEAT_FILE = TMP_DIR / "sl5_aura" / "aura_engine.heartbeat"
PIDFILE = TMP_DIR / "sl5_aura" / "aura_engine.pid"
# LOG_FILE = Path("log/aura_engine.log")
# aura_engine.py:253
core_logic_self_test_is_running_FILE = TMP_DIR / "sl5_aura" / "core_logic_self_test_FILE_is_running"
# aura_engine.py:208
SCRIPT_DIR = Path(__file__).resolve().parent
LANGUAGETOOL_JAR_PATH = f"{SCRIPT_DIR}/LanguageTool-6.6/languagetool-server.jar"
if not run_path_check(SL5NET_AURA_PROJECT_ROOT, LOCK_DIR):
print("\nFATAL: Path too long. See logs above.", file=sys.stderr)
sys.exit(1)
languagetool_process = None
logging.raiseExceptions = True
class WindowsEmojiFilter1(logging.Filter):
"""
A logging filter that replaces emojis with text placeholders on Windows.
This prevents UnicodeEncodeError on older console environments.
"""
def __init__(self):
# Emojy resources: .venv/lib/python3.13/site-packages/rich/_emoji_codes.py
super().__init__()
self.replacements = {
'⚠️': '[WARN]',
'✅': '[OK]',
'👍': '[OK]',
'👎': '[NO]',
'🎊': 'CONFETTI',
'❌': '[FAIL]',
'🎬': '[START]',
'⏹️': '[STOP]',
'🎤': '[MIC]',
'🎙️': '[MIC]',
'📢️': '[MIC]',
'💾': '[SAVE]',
'📋': '[EMPTY]',
'🔳': '[NOTHING]',
"👀": '[EYES]',
'🚀': '[ROCKET]',
'🔁':'REPLACE',
'📚':'BOOK',
'⌚': '[(-)]', # clock
'🗺️':'MAP',
'🍒':'cherries'
}
# Fancy text symbols˗ˏˋ꒰ 🍒 ꒱ˏˋ°•*⁀ ༊*·˚⋆·˚ ༘ *・ ・ೃ⁀ ⇢ ˗ˏˋ*ೃ༄︶︶༉‧₊˚.♡ ༉‧₊˚ੈ ‧₊˚☄. *. ⋆: ̗̀ …
def filter(self, record):
# Only perform replacement if running on Windows
#if os.name == 'nt':
if platform.system() == "Windows":
for emoji, text in self.replacements.items():
record.msg = record.msg.replace(emoji, text)
return True
class WindowsEmojiFilter(logging.Filter):
"""
A logging filter that replaces emojis with text placeholders on Windows.
This prevents UnicodeEncodeError on older console environments.
"""
def __init__(self):
super().__init__()
self.replacements = {
'🚀': '[▲]',
'🔁': '[⟳]',
'📚': '[▉]',
'❌': '[■]',
'⚠️': '[!]',
'✅': '[✓]',
'👍': '[OK]',
'👎': '[NO]',
'🎊': '[*]',
'❌': '[x]', # noqa: F601
'🎬': '[>]', # Start, Play
'⏹️': '[■]',
'🚫️': '[■]',
'🏁': '[>]', # Start
'🔵': '●',
'🎤': '[◉]',
'🎙️': '[▣]',
'📢️': '[≡]',
'💾': '[¥]',
'📋': '[‗]',
'🔳': '[□]',
"👀": '[o_o]',
'🚀': '[▲]',
'🔁': '[⟳]',
'📚': '[▉]',
'⌚': '[(-)]',
'🗺️':'▀▄▀'
}
# ▣▣■
# '🚀': '[>>>]',
def filter(self, record):
# Only perform replacement if running on Windows
#if os.name == 'nt':
if platform.system() == "Windows":
for emoji, text in self.replacements.items():
record.msg = record.msg.replace(emoji, text)
return True
# aura_engine.py:268
logger = logging.getLogger()
check_for_updates(logger)
# class PrintToConsoleAndFile(object):
# def __init__(self, logger):
# self.logger = logger
# self.terminal = sys.__stdout__ # Das echte Terminal sichern
#
# def write(self, buf):
# 1. Write to Console Immediately (Guaranteed!)
# with self._lock:
# self.terminal.write(buf)
# self.terminal.flush()
#
# # 2. Danach ins Logfile senden
# if buf.strip():
# try:
# Here we only use the logger for the file
# (If the ConsoleHandler is still active, it could happen twice,
# but better twice than not at all)
# self.logger.info(buf.rstrip())
# except:
# pass
#
# def flush(self):
# self.terminal.flush()
# aura_engine.py:371
from config.filters.settings_local_log_filter import LOG_EXCLUDE, LOG_ONLY
LOG_FILTER_COMPILED_LOG_ONLY = [re.compile(p) for p in LOG_ONLY]
LOG_FILTER_COMPILED = [re.compile(p) for p in LOG_EXCLUDE]
LOG_FILTER_SETTINGS_PATH = os.path.join(os.path.dirname(__file__), "config", "filters", "settings_local_log_filter.py")
LOG_FILTER_CHECK_INTERVAL_MIN = 4
LOG_FILTER_CHECK_INTERVAL_MAX = 10
LOG_FILTER_CHECK_INTERVAL_STEP = 2
LOG_FILTER_current_interval = LOG_FILTER_CHECK_INTERVAL_MIN
LOG_FILTER_last_modified = os.path.getmtime(LOG_FILTER_SETTINGS_PATH)
LOG_FILTER_last_checked = time.monotonic()
def LOG_FILTER_refresh_if_needed():
global LOG_FILTER_COMPILED, LOG_FILTER_COMPILED_LOG_ONLY
global LOG_FILTER_last_modified, LOG_FILTER_last_checked
global LOG_FILTER_current_interval
now = time.monotonic()
if now - LOG_FILTER_last_checked < LOG_FILTER_current_interval:
return
LOG_FILTER_last_checked = now
current_mtime = os.path.getmtime(LOG_FILTER_SETTINGS_PATH)
if current_mtime != LOG_FILTER_last_modified:
from importlib import reload
import config.filters.settings_local_log_filter as settings202603030531
reload(settings202603030531)
LOG_FILTER_COMPILED_LOG_ONLY = [re.compile(p) for p in settings202603030531.LOG_ONLY]
LOG_FILTER_COMPILED = [re.compile(p) for p in settings202603030531.LOG_EXCLUDE]
LOG_FILTER_last_modified = current_mtime
# Änderung erkannt → reset für schnelle Folgeupdates
LOG_FILTER_current_interval = LOG_FILTER_CHECK_INTERVAL_MIN
else:
# Keine Änderung → Intervall erhöhen bis Max
LOG_FILTER_current_interval = min(
LOG_FILTER_current_interval + LOG_FILTER_CHECK_INTERVAL_STEP,
LOG_FILTER_CHECK_INTERVAL_MAX
)
class SafeStreamToLogger:
def __init__(self, logger, original_stream, file_handler):
self.logger = logger
self.terminal = original_stream
self.file_handler_ref = file_handler # <--- HIER speichern
self.is_logging = False # <--- DER SCHUTZSCHALTER
self._lock = threading.Lock()
self.log_pattern = re.compile(r'^\d{2}:\d{2}:\d{2},\d{3}\s-\s[A-Z]+\s+-\s')
def write(self, buf):
# self.terminal.write(f"DEBUG_STDOUT 2026-0228-1533: {buf}")
LOG_FILTER_refresh_if_needed()
if LOG_FILTER_COMPILED_LOG_ONLY:
if not any(p.search(buf) for p in LOG_FILTER_COMPILED_LOG_ONLY):
return
# 1. shorten letts like #### or somthing. not needed here anymore as aye-catcher.
buf = re.sub(r"(.)\1{3,}", r"\1\1\1", buf)
elif any(p.search(buf) for p in LOG_FILTER_COMPILED):
return
# global core_logic_self_test_is_running_FILE
is_core_logic_self_test_is_running = core_logic_self_test_is_running_FILE.exists()
# is_core_logic_self_test_is_running = False
# 1. Always write to the console immediately (visible to you)
if is_core_logic_self_test_is_running and ':st:' not in buf : # and buf[:3] == 'st:':
return
buf = f'ööööööööööööööööööööööööööööööööööööööö {buf} ääääääääääääääääääääääääääääääääääääääääääääää\n'
buf = f'ööööööööööööööööööööööööööööööööööööööö {buf} ääääääääääääääääääääääääääääääääääääääääääääää\n'
buf = f'ööööööööööööööööööööööööööööööööööööööö {buf} ääääääääääääääääääääääääääääääääääääääääääääää\n'
buf = f'ööööööööööööööööööööööööööööööööööööööö {buf} ääääääääääääääääääääääääääääääääääääääääääääää\n'
# return
with self._lock:
self.terminal.write(buf)
# self.terminal.flush() <-- BESSER SO (Spart CPU/Zeit)
# 2. If we are NOT logging, then send to the file
# if not self.is_logging and buf.strip():
if buf and not buf.isspace() and not self.is_logging:
self.is_logging = True # Schalter an
try:
# st:
# Check: Does the text already have a timestamp?
match = self.log_pattern.match(buf)
if match:
# JA: We're cutting out the timestamp at the front!
# match.end() ist die Stelle, wo der echte Text anfängt.
clean_msg = buf[match.end():].rstrip()
else:
# NO: We take the text as it is (e.g. from print)
clean_msg = buf.rstrip()
# Only write if there is still text left
if clean_msg:
record = logging.LogRecord(
name="PRINT", level=logging.INFO, pathname="print", lineno=0,
msg=clean_msg, args=(), exc_info=None
)
self.file_handler_ref.handle(record)
except Exception as e202602281506:
print(f'lets ignore e202602281506: {e202602281506}')
finally:
self.is_logging = False
def flush(self):
# self.terminal.flush() # entfernen spart viel Zeit. Erfüllt die Pflicht
pass
# sys.stdout = SafeStreamToLogger(logger, sys.__stdout__)
# Aktivieren
# sys.stdout = PrintToConsoleAndFile(logger)
# sys.stdout = StreamToLogger(logger, logging.INFO) # print -> Logger
# sys.stderr = StreamToLogger(logger, logging.ERROR) # Fehler -> Logger
# 304
logger.setLevel(logging.INFO)
# Clear any pre-existing handlers to prevent duplicates.
if len(logger.handlers) > 0:
logger.handlers.clear()
# Create a shared formatter with the custom formatTime function.
def formatTime(record, datefmt=None):
time_str = time.strftime("%H:%M:%S")
milliseconds = int((record.created - int(record.created)) * 1000)
ms_str = f",{milliseconds:03d}"
return time_str + ms_str
# 1. We create a Filter class
class DittoFilter(logging.Filter):
def __init__(self):
super().__init__()
self.last_msg = None
def filter(self, record):
# Den "echten" Inhalt der aktuellen Nachricht holen
current_msg = record.getMessage()
# compare with saved original message
if current_msg == self.last_msg:
# Es ist eine Wiederholung -> Text für die Ausgabe ändern
record.msg = "〃"
record.args = ()
# IMPORTANT: We DO NOT update self.last_msg HERE.
# We want the next line to still be with
# dem Original (z.B. "Verbindung…") vergleicht und
# not with the goosefoot ("〃").
else:
# Es ist eine neue Nachricht -> Speicher aktualisieren
self.last_msg = current_msg
return True
# Filter instanziieren
ditto_filter = DittoFilter()
# log_formatter = logging.Formatter('%(asctime)s - %(levelname)-8s - %(message)s')
log_formatter = logging.Formatter('%(asctime)s - %(threadName)s - %(levelname)s - %(message)s')
log_formatter.formatTime = formatTime
# Create, configure, and add the File Handler.
# aura_engine.py:594
class FlushingFileHandler(logging.FileHandler):
def emit(self, record):
try:
super().emit(record)
self.flush() # Zwingt den Inhalt sofort auf die Platte
except Exception:
self.handleError(record)
# file_handler = logging.FileHandler(f'{SCRIPT_DIR}/log/aura_engine.log', mode='a', encoding='utf-8')
# Use this new handler
file_handler = FlushingFileHandler(
f'{SCRIPT_DIR}/log/aura_engine.log',
mode='a',
encoding='utf-8'
)
file_handler.setFormatter(log_formatter)
# logger.addFilter(ditto_filter)
sys.stdout = SafeStreamToLogger(logger, sys.__stdout__, file_handler)
# Create, configure, and add the Console Handler.
# console_handler = logging.StreamHandler(sys.stdout) # send it in the redirection
console_handler = logging.StreamHandler(sys.__stdout__)
console_handler.setFormatter(log_formatter)
#console_handler.addFilter(ditto_filter)
# aura_engine.py:636
# Add the WindowsEmojiFilter to the file_handler
if True:
logger.addFilter(ditto_filter)
logger.addHandler(file_handler)
logger.addHandler(console_handler)
# logger.addHandler(console_handler)
# logger.addFilter(WindowsEmojiFilter())
# logger.addFilter(ditto_filter)
else:
logger.addHandler(file_handler)
console_handler.addFilter(WindowsEmojiFilter())
console_handler.addFilter(ditto_filter)
file_handler.addFilter(WindowsEmojiFilter())
file_handler.addFilter(ditto_filter)
# file_handler.addFilter(WindowsEmojiFilter())
# file_handler.addFilter(ditto_filter)
# if settings.DEV_MODE and settings.current_user == 'seeh':
# for testing often a clean log helpss
# aura_log = Path('log/aura_engine.log')
# aura_log.unlink(missing_ok=True) ## seems problematic
DISABLE_ALL_TEST_QuickStopTestsForSomeReasons = False
# DISABLE_ALL_TEST_QuickStopTestsForSomeReasons = True
if settings.DEV_MODE and DISABLE_ALL_TEST_QuickStopTestsForSomeReasons :
print(f'Hi DEV. BTW DISABLE_ALL_TEST_QuickStopTestsForSomeReasons is {DISABLE_ALL_TEST_QuickStopTestsForSomeReasons}')
global_state.LOGGING_ENABLED = settings.LOG_in_selftest
readme = """
vosk-model-small-de-0.15
17:36:26,230 - INFO - >>> Core Logic Self-Test PASSED.
17:36:36,138 - INFO - == ✅ MODEL READY: 'small'.
==> 10 Seconds Sekunden
vosk-model-de-0.21
✅ MODEL READY: 'de'.
13:27:52,772 - INFO - >>> Core Logic Self-Test PASSED.
13:29:09,816 - INFO - self_tester.py:216 ✅ 89tested of 98 tests (lang=de-DE)
==> ~70 Seconds Sekunden
"""
if settings.SERVICE_START_OPTION > 1:
# Option 1: Start the service only on autostart (start parameter) and if there is an internet
def check_internet_connection(host='https://sl5.de'):
if os.getenv('CI'):
logger.info("CI environment detected. Skipping microphone-dependent recording.")
return True # Pretend internet is available for CI
if host.startswith(('http://', 'https://')):
host = host.split('//')[1]
# Use 'ping -n 1' on Windows and 'ping -c 1' on other OS
# The '-n 1' and '-c 1' options specify the number of echo requests to send
param = '-n' if platform.system().lower() == 'windows' else '-c'
try:
# The subprocess.run function executes the ping command
# It waits for the command to complete and returns a CompletedProcess object
subprocess.run(
['ping', param, '1', host],
check=True, # This will raise a CalledProcessError if the command fails
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
print(f"Internet connection is available. Successfully pinged {host}.")
return True
except subprocess.CalledProcessError:
print(f"No internet connection. Failed to ping {host}.")
return False
except FileNotFoundError:
print("The 'ping' command was not found. Please ensure it's in your system's PATH.")
return False
if not check_internet_connection():
m = "Service will not start due to no internet connection."
print(m)
logging.info(m)
if settings.SERVICE_START_OPTION == 11:
m = "System will reboot in 8 seconds."
print(m)
logging.info(m)
time.sleep(8)
os.system('reboot')
os.system('sudo systemctl restart systemd')
else:
sys.exit(1)
# Execute the check. The script will exit here if the setup is incomplete.
if settings.DEV_MODE :
validate_punctuation_map_keys(SCRIPT_DIR,logger)
project_root = SCRIPT_DIR
if settings.DEV_MODE :
check_settings_usage()
try:
# Create a copy of the current environment and set PYTHONPATH
env = os.environ.copy()
env['PYTHONPATH'] = '.'
subprocess.run(
[sys.executable, "scripts/py/func/checks/test_dictation_session_logic.py"],
check=True,
cwd=SCRIPT_DIR,
env=env
)
logger.info(">>> Core Logic Self-Test PASSED.")
except subprocess.CalledProcessError:
logger.critical(">>> Core Logic Self-Test FAILED. Aborting service start.")
sys.exit(1)
# ==============================================================================
# --- Wrapper Script Check ---
# if not DEV_MODE and os.environ.get("DICTATION_SERVICE_STARTED_CORRECTLY") != "true":
# logger.fatal("FATAL: This script must be started using the 'activate-venv_and_run-server.sh' wrapper.")
# sys.exit(1)
# ==============================================================================
from scripts.py.func.audio_manager import stop_audio_manager
from scripts.py.func.cleanup import cleanup
from scripts.py.func.guess_lt_language_from_model import guess_lt_language_from_model
from scripts.py.func.notify import notify
from scripts.py.func.start_languagetool_server import (
LT_ALREADY_RUNNING_SENTINEL,
start_languagetool_server,
)
# from scripts.py.func.stop_languagetool_server import stop_languagetool_server
# from scripts.py.func.transcribe_audio_with_feedback import transcribe_audio_with_feedback
# from scripts.py.func.check_memory_critical import check_memory_critical
from scripts.py.func.stop_languagetool_server import stop_languagetool_server
# aura_engine.py:809
files_to_clean = [HEARTBEAT_FILE, PIDFILE, TRIGGER_FILE]
atexit.register(lambda: cleanup(logger, files_to_clean))
atexit.register(lambda: stop_languagetool_server(logger, languagetool_process))
atexit.register(stop_audio_manager)
with open(PIDFILE, 'w') as f:
f.write(str(os.getpid()))
# AURA_TMP = TMP_DIR / "sl5_aura"
# aura_project_root_path = Path( AURA_TMP / "aura_project_root.path")
# with open(aura_project_root_path, 'w') as f:
# f.write(str(SL5NET_AURA_PROJECT_ROOT))
# --- Argument Parsing und Model-Setup ---
MODEL_NAME_DEFAULT = "vosk-model-de-0.21" # fallback
SCRIPT_DIR = Path(__file__).resolve().parent
""""
parser = argparse.ArgumentParser(description="A real-time dictation service using Vosk.")
parser.add_argument('--vosk_model', help=f"Name of the Vosk model folder. Defaults to '{MODEL_NAME_DEFAULT}'.")
parser.add_argument('--test-text', help="Bypass microphone and use this text for testing.")
args = parser.parse_args()
VOSK_MODEL_FILE = SCRIPT_DIR / "config/model_name.txt"
vosk_model_from_file = Path(VOSK_MODEL_FILE).read_text().strip() if Path(VOSK_MODEL_FILE).exists() else ""
MODEL_NAME = args.vosk_model or vosk_model_from_file or MODEL_NAME_DEFAULT
"""
"""
31.10.'25 22:09 Fri
22:07:36,080 - INFO - Graceful shutdown initiated. Final timeout set to 2.0s.
22:07:36,484 - WARNING - SYSTEM-MEMORY CRITICAL! Usage: 92.00440896261489%. Exceeds threshold. Terminating entire process group 82694.BTW: ramUsageIncreadFromBegining: 1.0818119049072266 times
"""
SYSTEM_RAM_THRESHOLD_PERCENT = 92.0
SYSTEM_SWAP_THRESHOLD_PERCENT = 85.0 # this is deprecated. idk. seems not working like expected. dont use it.
RAM_ESTIMATE_PER_MODEL_GB = 4.0 # plus some other needed space for the model
GB_TO_MB_CONVERSION_FACTOR = 1024
# aura_engine.py:404
# --- SETUP FOR DEDICATED MEMORY LOGGING ---
# Define the path for the memory log file
MEMORY_LOG_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'log/memory_leak_analysis.log')
# Initialize a dedicated logger for memory events
memory_logger = logging.getLogger('MemoryAnalyzer')
# Fügen Sie dies vor der Konfiguration des memory_logger hinzu:
# aura_engine.py:708
if os.path.exists(MEMORY_LOG_PATH):
# Get last modification time
mtime_ts = os.path.getmtime(MEMORY_LOG_PATH)
log_date = datetime.fromtimestamp(mtime_ts).date()
# If the log file is not from today, delete it
if log_date < datetime.now().date():
# os.remove(MEMORY_LOG_PATH)
try:
if os.path.exists(MEMORY_LOG_PATH):
# Truncate the file instead of removing it to avoid WinError 32
with open(MEMORY_LOG_PATH, 'w'):
pass
except PermissionError:
logger.warning(f"Could not clear {MEMORY_LOG_PATH} - file is locked. May Ctrl+Alt+Def and delete alle Python processes")
logger.warning('Prüfe im Task-Manager, ob noch eine alte python.exe im Hintergrund läuft, die die Logdatei blockiert.')
memory_logger.info("Old memory log file deleted.")
# Ensure the logger hasn't already been configured by accident (common in Python)
if not memory_logger.handlers:
memory_logger.setLevel(logging.INFO)
file_handler = logging.FileHandler(MEMORY_LOG_PATH, encoding="utf-8")
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(threadName)s - %(message)s'))
memory_logger.addHandler(file_handler)
# Prevent propagation to the root logger which might write to stdout/stderr
memory_logger.propagate = False
def memory_leak_analyzer(interval_seconds=600, significant_growth_threshold=100):
"""
Periodically logs the growth of the largest Python objects to a dedicated file
to diagnose memory leaks. Runs indefinitely as a daemon thread.
"""
memory_logger.info("logger.info('Memory Leak Analyzer started. Initializing object counts.')")
process = psutil.Process(os.getpid())
current_memory_mb = process.memory_info().rss / (1024 * 1024)
memory_logger.info(f"System Process Memory (RSS): {current_memory_mb:.2f} MB")
# Store initial counts of all objects to track growth accurately
try:
initial_counts = objgraph.most_common_types(limit=None, shortnames=False)
initial_dict = {item[0]: item[1] for item in initial_counts}
except Exception as e1:
memory_logger.error(f"logger.info('Failed to get initial object counts: {e1}')")
return # Stop if initial check fails
memory_logger.info(
f"logger.info('Analysis interval set to {interval_seconds} seconds. Growth threshold: {significant_growth_threshold} objects.')")
while True:
try:
time.sleep(interval_seconds)
# 1. Get current process memory usage (as reported by OS)
process = psutil.Process(os.getpid())
current_memory_mb = process.memory_info().rss / (1024 * 1024)
# 2. Get current Python object counts (top 30 to catch most issues)
current_counts = objgraph.most_common_types(limit=30, shortnames=False)
memory_logger.info("--- MEMORY SNAPSHOT ---")
memory_logger.info(f"System Process Memory (RSS): {current_memory_mb:.2f} MB")
# 3. Compare current counts to initial and log significant growth
growth_found = False
for type_name, count in current_counts:
initial_count = initial_dict.get(type_name, 0)
count_increase = count - initial_count
# Only log objects that have grown significantly
if count_increase > significant_growth_threshold:
memory_logger.info(
f"GROWTH DETECTED: {type_name}: Current={count} | Growth={count_increase}")
growth_found = True
if not growth_found:
memory_logger.info("logger.info('No significant object growth detected in top 30 types.')")
memory_logger.info("---------------------")
except Exception as e2:
memory_logger.error(f"Analyzer loop encountered an error: {e2}")
time.sleep(60) # Short pause before continuing the loop
# --- INTEGRATION STEP ---
# This line must be added to your main application startup sequence (e.g., main.py or similar):
# To run it in parallel (similar to your existing watchdog):
if settings.DEV_MODE:
threading.Thread(target=memory_leak_analyzer, daemon=True).start()