-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathdarts-caller.py
3330 lines (2718 loc) · 133 KB
/
darts-caller.py
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
import os
import sys
from pathlib import Path
import time
import base64
import platform
import random
import argparse
from pygame import mixer
import threading
import logging
import shutil
import re
import csv
import math
import psutil
import queue
from mask import mask
from urllib.parse import quote, unquote
import ssl
from download import download
import json
import certifi
import requests
import websocket
from autodarts_keycloak_client import AutodartsKeycloakClient
from flask import Flask, render_template, send_from_directory, request
from flask_socketio import SocketIO
from werkzeug.serving import make_ssl_devcert
from engineio.async_drivers import threading as th # IMPORTANT
os.environ['SSL_CERT_FILE'] = certifi.where()
plat = platform.system()
if plat == 'Windows':
from pycaw.pycaw import AudioUtilities
sh = logging.StreamHandler()
sh.setLevel(logging.INFO)
formatter = logging.Formatter('%(message)s')
sh.setFormatter(formatter)
logger=logging.getLogger()
logger.handlers.clear()
logger.setLevel(logging.INFO)
logger.addHandler(sh)
app = Flask(__name__)
app.config['SECRET_KEY'] = 'caller for autodarts'
socketio = SocketIO(app, async_mode="threading")
main_directory = os.path.dirname(os.path.realpath(__file__))
parent_directory = os.path.dirname(main_directory)
VERSION = '2.14.0'
DEFAULT_EMPTY_PATH = ''
DEFAULT_CALLER_VOLUME = 1.0
DEFAULT_CALLER = None
DEFAULT_RANDOM_CALLER = 1
DEFAULT_RANDOM_CALLER_LANGUAGE = 1
DEFAULT_RANDOM_CALLER_GENDER = 0
DEFAULT_CALL_CURRENT_PLAYER = 1
DEFAULT_CALL_BOT_ACTIONS = True
DEFAULT_CALL_EVERY_DART = 0
DEFAULT_CALL_EVERY_DART_TOTAL_SCORE = True
DEFAULT_POSSIBLE_CHECKOUT_CALL = 1
DEFAULT_POSSIBLE_CHECKOUT_CALL_YOURSELF_ONLY = 0
DEFAULT_AMBIENT_SOUNDS = 0.0
DEFAULT_AMBIENT_SOUNDS_AFTER_CALLS = False
DEFAULT_DOWNLOADS = 3
DEFAULT_DOWNLOADS_LANGUAGE = 1
DEFAULT_DOWNLOADS_NAME = None
DEFAULT_REMOVE_OLD_VOICE_PACKS = False
DEFAULT_BACKGROUND_AUDIO_VOLUME = 0.0
DEFAULT_LOCAL_PLAYBACK = True
DEFAULT_WEB_CALLER_DISABLE_HTTPS = False
DEFAULT_HOST_PORT = 8079
DEFAULT_DEBUG = False
DEFAULT_CERT_CHECK = True
DEFAULT_MIXER_FREQUENCY = 44100
DEFAULT_MIXER_SIZE = 32
DEFAULT_MIXER_CHANNELS = 2
DEFAULT_MIXER_BUFFERSIZE = 4096
DEFAULT_DOWNLOADS_PATH = 'caller-downloads-temp'
DEFAULT_CALLERS_BANNED_FILE = 'banned.txt'
DEFAULT_CALLERS_FAVOURED_FILE = 'favoured.txt'
DEFAULT_HOST_IP = '0.0.0.0'
AUTODARTS_CLIENT_ID = 'wusaaa-caller-for-autodarts'
AUTODARTS_REALM_NAME = 'autodarts'
AUTODARTS_CLIENT_SECRET = "4hg5d4fddW7rqgoY8gZ42aMpi2vjLkzf"
AUTODARTS_URL = 'https://autodarts.io'
AUTODARTS_AUTH_URL = 'https://login.autodarts.io/'
AUTODARTS_LOBBIES_URL = 'https://api.autodarts.io/gs/v0/lobbies/'
AUTODARTS_MATCHES_URL = 'https://api.autodarts.io/gs/v0/matches/'
AUTODARTS_BOARDS_URL = 'https://api.autodarts.io/bs/v0/boards/'
AUTODARTS_USERS_URL = 'https://api.autodarts.io/as/v0/users/'
AUTODARTS_WEBSOCKET_URL = 'wss://api.autodarts.io/ms/v0/subscribe'
SUPPORTED_SOUND_FORMATS = ['.mp3', '.wav']
SUPPORTED_GAME_VARIANTS = ['X01', 'Cricket', 'Random Checkout', 'ATC', 'RTW']
SUPPORTED_CRICKET_FIELDS = [15, 16, 17, 18, 19, 20, 25]
BOGEY_NUMBERS = [169, 168, 166, 165, 163, 162, 159]
TEMPLATE_FILE_ENCODING = 'utf-8-sig'
WEB_DB_NAME = "ADC1"
FIELD_COORDS = {
"0": {"x": 0.016160134143785285,"y": 1.1049884720184449},
"S1": {"x": 0.2415216935652902,"y": 0.7347516243974009},
"D1": {"x": 0.29786208342066656,"y": 0.9359673024523162},
"T1": {"x": 0.17713267658771747,"y": 0.5818277090756655},
"S2": {"x": 0.4668832529867955,"y": -0.6415636134982183},
"D2": {"x": 0.5876126598197445,"y": -0.7783902745755609},
"T2": {"x": 0.35420247327604254,"y": -0.4725424439320897},
"S3": {"x": 0.008111507021588693,"y": -0.7864389016977573},
"D3": {"x": -0.007985747222804492,"y": -0.9715573255082791},
"T3": {"x": -0.007985747222804492,"y": -0.5932718507650387},
"S4": {"x": 0.6439530496751206,"y": 0.4530496751205198},
"D4": {"x": 0.7888283378746596,"y": 0.5657304548312723},
"T4": {"x": 0.48298050723118835,"y": 0.36451477677635713},
"S5": {"x": -0.23334730664430925,"y": 0.7508488786417943},
"D5": {"x": -0.31383357786627536,"y": 0.9279186753301195},
"T5": {"x": -0.1850555439111297,"y": 0.5737790819534688},
"S6": {"x": 0.7888283378746596,"y": -0.013770697966883233},
"D6": {"x": 0.9739467616851814,"y": 0.010375183399706544},
"T6": {"x": 0.5956612869419406,"y": -0.005722070844686641},
"S7": {"x": -0.4506602389436176,"y": -0.6335149863760215},
"D7": {"x": -0.5713896457765667,"y": -0.7703416474533641},
"T7": {"x": -0.3540767134772585,"y": -0.4725424439320897},
"S8": {"x": -0.7323621882204988,"y": -0.239132257388388},
"D8": {"x": -0.9255292391532174,"y": -0.2954726472437643},
"T8": {"x": -0.5713896457765667,"y": -0.18279186753301202},
"S9": {"x": -0.627730035631943,"y": 0.4691469293649132},
"D9": {"x": -0.7726053238314818,"y": 0.5657304548312723},
"T9": {"x": -0.48285474743240414,"y": 0.34841752253196395},
"S10": {"x": 0.7244393208970865,"y": -0.23108363026619158},
"D10": {"x": 0.9256549989520018,"y": -0.28742402012156787},
"T10": {"x": 0.5715154055753511,"y": -0.19084049465520878},
"S11": {"x": -0.7726053238314818,"y": -0.005722070844686641},
"D11": {"x": -0.9657723747642004,"y": -0.005722070844686641},
"T11": {"x": -0.5955355271431566,"y": 0.0023265562775099512},
"S12": {"x": -0.4506602389436176,"y": 0.6140222175644519},
"D12": {"x": -0.5633410186543703,"y": 0.7910920142527772},
"T12": {"x": -0.3540767134772585,"y": 0.4932928107315028},
"S13": {"x": 0.7244393208970865,"y": 0.24378536994340808},
"D13": {"x": 0.917606371829805,"y": 0.308174386920981},
"T13": {"x": 0.5634667784531546,"y": 0.18744498008803193},
"S14": {"x": -0.7223277562650692,"y": 0.2440637100898663},
"D14": {"x": -0.9255292391532174,"y": 0.308174386920981},
"T14": {"x": -0.5713896457765667,"y": 0.19549360721022835},
"S15": {"x": 0.6278557954307273,"y": -0.46449381680989327},
"D15": {"x": 0.7888283378746596,"y": -0.5771745965206456},
"T15": {"x": 0.4910291343533851,"y": -0.34376440997694424},
"S16": {"x": -0.6196814085097464,"y": -0.4725424439320897},
"D16": {"x": -0.7967512051980717,"y": -0.5610773422762524},
"T16": {"x": -0.49090337455460076,"y": -0.33571578285474746},
"S17": {"x": 0.2415216935652902,"y": -0.730098511842381},
"D17": {"x": 0.29786208342066656,"y": -0.9152169356529029},
"T17": {"x": 0.18518130370991423,"y": -0.5691259693984492},
"S18": {"x": 0.48298050723118835,"y": 0.6462167260532384},
"D18": {"x": 0.5554181513309578,"y": 0.799140641374974},
"T18": {"x": 0.3292712798530314,"y": 0.49608083282302506},
"S19": {"x": -0.2586037966932027,"y": -0.7658909981628906},
"D19": {"x": -0.3134721371708513,"y": -0.9148193508879362},
"T19": {"x": -0.19589712186160443,"y": -0.562094304960196},
"S20": {"x": 0.00006123698714003468,"y": 0.7939375382731171},
"D20": {"x": 0.01119619445411297, "y": 0.9726766446223462},
"T20": {"x": 0.00006123698714003468, "y": 0.6058175137783223},
"25": {"x": 0.06276791181873864, "y": 0.01794243723208814},
"50": {"x": -0.007777097366809472, "y": 0.0022657685241886157},
}
CALLER_LANGUAGES = {
1: ['english', 'en', ],
2: ['french', 'fr', ],
3: ['russian', 'ru', ],
4: ['german', 'de', ],
5: ['spanish', 'es', ],
6: ['dutch', 'nl', ],
}
CALLER_GENDERS = {
1: ['female', 'f'],
2: ['male', 'm'],
}
CALLER_PROFILES = {
#------------------------------------------------------------------------------------------------
# AMAZON / AWS Polly
#------------------------------------------------------------------------------------------------
# -- ru-RU --
# 'ru-RU-TODO': ('https://add.arnes-design.de/ADC/TODOLINK.zip', 1),
# 'ru-RU-TODO': ('https://add.arnes-design.de/ADC/TODOLINK.zip', 1),
# -- nl-NL --
'nl-NL-Laura-Female': ('https://add.arnes-design.de/ADC/nl-NL-Laura-Female-v4.zip', 4),
# -- fr-FR --
'fr-FR-Remi-Male': ('https://add.arnes-design.de/ADC/fr-FR-Remi-Male-v2.zip', 2),
'fr-FR-Lea-Female': ('https://add.arnes-design.de/ADC/fr-FR-Lea-Female-v2.zip', 2),
# -- es-ES --
'es-ES-Lucia-Female': ('https://add.arnes-design.de/ADC/es-ES-Lucia-Female-v2.zip', 2),
'es-ES-Sergio-Male': ('https://add.arnes-design.de/ADC/es-ES-Sergio-Male-v2.zip', 2),
# -- de-AT --
'de-AT-Hannah-Female': ('https://add.arnes-design.de/ADC/de-AT-Hannah-Female-v4.zip', 4),
# -- de-DE --
'de-DE-Vicki-Female': ('https://add.arnes-design.de/ADC/de-DE-Vicki-Female-v7.zip', 7),
'de-DE-Daniel-Male': ('https://add.arnes-design.de/ADC/de-DE-Daniel-Male-v7.zip', 7),
# -- en-US --
'en-US-Ivy-Female': ('https://add.arnes-design.de/ADC/en-US-Ivy-Female-v7.zip', 7),
'en-US-Joey-Male': ('https://add.arnes-design.de/ADC/en-US-Joey-Male-v8.zip', 8),
'en-US-Joanna-Female': ('https://add.arnes-design.de/ADC/en-US-Joanna-Female-v8.zip', 8),
'en-US-Matthew-Male': ('https://add.arnes-design.de/ADC/en-US-Matthew-Male-v5.zip', 5),
'en-US-Danielle-Female': ('https://add.arnes-design.de/ADC/en-US-Danielle-Female-v5.zip', 5),
'en-US-Kimberly-Female': ('https://add.arnes-design.de/ADC/en-US-Kimberly-Female-v4.zip', 4),
'en-US-Ruth-Female': ('https://add.arnes-design.de/ADC/en-US-Ruth-Female-v4.zip', 4),
'en-US-Salli-Female': ('https://add.arnes-design.de/ADC/en-US-Salli-Female-v4.zip', 4),
'en-US-Kevin-Male': ('https://add.arnes-design.de/ADC/en-US-Kevin-Male-v4.zip', 4),
'en-US-Justin-Male': ('https://add.arnes-design.de/ADC/en-US-Justin-Male-v4.zip', 4),
'en-US-Stephen-Male': ('https://add.arnes-design.de/ADC/en-US-Stephen-Male-v7.zip', 7),
'en-US-Kendra-Female': ('https://add.arnes-design.de/ADC/en-US-Kendra-Female-v8.zip', 8),
'en-US-Gregory-Male': ('https://add.arnes-design.de/ADC/en-US-Gregory-Male-v5.zip', 5),
# -- en-GB --
'en-GB-Amy-Female': ('https://add.arnes-design.de/ADC/en-GB-Amy-Female-v3.zip', 3),
'en-GB-Arthur-Male': ('https://add.arnes-design.de/ADC/en-GB-Arthur-Male-v3.zip', 3),
#------------------------------------------------------------------------------------------------
# MURF
#------------------------------------------------------------------------------------------------
# 'theo-m-english-uk': ('https://add.arnes-design.de/ADC/theo-m-english-uk-v2.zip', 2),
# 'TODONAME': ('TODOLINK', TODOVERSION),
}
def ppi(message, info_object = None, prefix = '\r\n'):
logger.info(prefix + str(message))
if info_object != None:
logger.info(str(info_object))
def ppe(message, error_object):
ppi(message)
if DEBUG:
logger.exception("\r\n" + str(error_object))
def get_executable_directory():
if getattr(sys, 'frozen', False):
return os.path.dirname(sys.executable)
elif __file__:
return os.path.dirname(os.path.realpath(__file__))
else:
raise RuntimeError("Unable to determine executable directory.")
def same_drive(path1, path2):
drive1 = os.path.splitdrive(path1)[0]
drive2 = os.path.splitdrive(path2)[0]
return drive1 == drive2
def check_paths(main_directory, audio_media_path, audio_media_path_shared):
try:
main_directory = get_executable_directory()
errors = None
audio_media_path = os.path.normpath(audio_media_path)
if audio_media_path_shared != DEFAULT_EMPTY_PATH:
audio_media_path_shared = os.path.normpath(audio_media_path_shared)
if same_drive(audio_media_path, main_directory) == True and os.path.commonpath([audio_media_path, main_directory]) == main_directory:
errors = 'AUDIO_MEDIA_PATH (-M) is a subdirectory of MAIN_DIRECTORY.'
if audio_media_path_shared != '':
if same_drive(audio_media_path_shared, main_directory) == True and os.path.commonpath([audio_media_path_shared, main_directory]) == main_directory:
errors = 'AUDIO_MEDIA_PATH_SHARED (-MS) is a subdirectory of MAIN_DIRECTORY. This is NOT allowed.'
elif same_drive(audio_media_path_shared, audio_media_path) == True and os.path.commonpath([audio_media_path_shared, audio_media_path]) == audio_media_path:
errors = 'AUDIO_MEDIA_PATH_SHARED (-MS) is a subdirectory of AUDIO_MEDIA_PATH. This is NOT allowed.'
elif same_drive(audio_media_path, audio_media_path_shared) == True and os.path.commonpath([audio_media_path, audio_media_path_shared]) == audio_media_path_shared:
errors = 'AUDIO_MEDIA_PATH (-M) is a subdirectory of AUDIO_MEDIA_SHARED (-MS). This is NOT allowed.'
elif same_drive(audio_media_path, audio_media_path_shared) == True and audio_media_path == audio_media_path_shared:
errors = 'AUDIO_MEDIA_PATH (-M) is equal to AUDIO_MEDIA_SHARED (-MS). This is NOT allowed.'
except Exception as e:
errors = f'Path validation failed: {e}'
if errors is not None:
ppi("main_directory: " + main_directory)
ppi("audio_media_path: " + str(audio_media_path))
ppi("audio_media_path_shared: " + str(audio_media_path_shared))
return errors
def check_already_running():
max_count = 3 # app (binary) uses 2 processes => max is (2 + 1) as this one here counts also.
count = 0
me, extension = os.path.splitext(os.path.basename(sys.argv[0]))
ppi("Process is " + me)
for proc in psutil.process_iter(['pid', 'name']):
proc_name = proc.info['name'].lower()
proc_name, extension = os.path.splitext(proc_name)
if proc_name == me:
count += 1
if count >= max_count:
ppi(f"{me} is already running. Exit")
sys.exit()
# ppi("Start info: " + str(count))
def versionize_speaker(speaker_name, speaker_version):
speaker_versionized = speaker_name
if speaker_version > 1:
speaker_versionized = f"{speaker_versionized}-v{speaker_version}"
return speaker_versionized
def download_callers():
if DOWNLOADS > 0:
download_list = CALLER_PROFILES
# versionize, exclude bans, force download-name
dl_name = DOWNLOADS_NAME
if dl_name is not None:
dl_name = dl_name.lower()
downloads_filtered = {}
for speaker_name, (speaker_download_url, speaker_version) in download_list.items():
spn = speaker_name.lower()
speaker_versionized = versionize_speaker(speaker_name, speaker_version)
speaker_versionized_lower = speaker_versionized.lower()
if dl_name == spn or dl_name == speaker_versionized.lower():
downloads_filtered = {}
downloads_filtered[speaker_versionized] = speaker_download_url
break
if speaker_versionized_lower not in caller_profiles_banned and spn not in caller_profiles_banned:
# ppi("spn: " + spn)
# ppi("dl_name: " + dl_name)
# ppi("speaker_versionized: " + speaker_versionized.lower())
downloads_filtered[speaker_versionized] = speaker_download_url
download_list = downloads_filtered
if dl_name != DEFAULT_DOWNLOADS_NAME:
pass
else:
# filter for language
if DOWNLOADS_LANGUAGE > 0:
downloads_filtered = {}
for speaker_name, speaker_download_url in download_list.items():
caller_language_key = grab_caller_language(speaker_name)
if caller_language_key != DOWNLOADS_LANGUAGE:
continue
downloads_filtered[speaker_name] = speaker_download_url
download_list = downloads_filtered
# filter for limit
if len(download_list) > 0 and DOWNLOADS < len(download_list):
download_list = {k: download_list[k] for k in list(download_list.keys())[-DOWNLOADS:]}
if len(download_list) > 0:
if os.path.exists(AUDIO_MEDIA_PATH) == False: os.mkdir(AUDIO_MEDIA_PATH)
# Download and parse every caller-profile
for cpr_name, cpr_download_url in download_list.items():
try:
# Check if caller-profile already present in users media-directory, yes ? -> stop for this caller-profile
caller_profile_exists = os.path.exists(os.path.join(AUDIO_MEDIA_PATH, cpr_name))
if caller_profile_exists == True:
# ppi('Caller-profile ' + cpr_name + ' already exists -> Skipping download')
continue
# ppi("DOWNLOADING voice-pack: " + cpr_name + " ..")
# clean download-area!
shutil.rmtree(DOWNLOADS_PATH, ignore_errors=True)
if os.path.exists(DOWNLOADS_PATH) == False:
os.mkdir(DOWNLOADS_PATH)
# Download caller-profile and extract archive
dest = os.path.join(DOWNLOADS_PATH, 'download.zip')
# kind="zip",
path = download(cpr_download_url, dest, progressbar=True, replace=False, timeout=15.0, verbose=DEBUG)
# LOCAL-Download
# shutil.copyfile('C:\\Users\\Luca\\Desktop\\download.zip', os.path.join(DOWNLOADS_PATH, 'download.zip'))
ppi("EXTRACTING VOICE-PACK..")
shutil.unpack_archive(dest, DOWNLOADS_PATH)
os.remove(dest)
# Find sound-file-archive und extract it
zip_filename = [f for f in os.listdir(DOWNLOADS_PATH) if f.endswith('.zip')][0]
dest = os.path.join(DOWNLOADS_PATH, zip_filename)
shutil.unpack_archive(dest, DOWNLOADS_PATH)
os.remove(dest)
# Find folder and rename it properly
sound_folder = [dirs for root, dirs, files in sorted(os.walk(DOWNLOADS_PATH))][0][0]
src = os.path.join(DOWNLOADS_PATH, sound_folder)
dest = os.path.splitext(dest)[0]
os.rename(src, dest)
# Find template-file and parse it
template_file = [f for f in os.listdir(DOWNLOADS_PATH) if f.endswith('.csv')][0]
template_file = os.path.join(DOWNLOADS_PATH, template_file)
san_list = list()
with open(template_file, 'r', encoding=TEMPLATE_FILE_ENCODING) as f:
tts = list(csv.reader(f, delimiter=';'))
for event in tts:
sanitized = list(filter(None, event))
if len(sanitized) == 1:
sanitized.append(sanitized[0].lower())
san_list.append(sanitized)
# ppi(san_list)
# Find origin-file
origin_file = None
files = [f for f in os.listdir(DOWNLOADS_PATH) if f.endswith('.txt')]
if len(files) >= 1:
origin_file = os.path.join(DOWNLOADS_PATH, files[0])
# Move template- and origin-file to sound-dir
if origin_file != None:
shutil.move(origin_file, dest)
shutil.move(template_file, dest)
# Find all supported sound-files and remember names
sounds = []
for root, dirs, files in os.walk(dest):
for file in sorted(files):
if file.endswith(tuple(SUPPORTED_SOUND_FORMATS)):
sounds.append(os.path.join(root, file))
# ppi(sounds)
# Rename sound-files and copy files according the defined caller-keys
for i in range(len(san_list)):
current_sound = sounds[i]
current_sound_splitted = os.path.splitext(current_sound)
current_sound_extension = current_sound_splitted[1]
try:
row = san_list[i]
caller_keys = row[1:]
# ppi(caller_keys)
for ck in caller_keys:
multiple_file_name = os.path.join(dest, ck + current_sound_extension)
exists = os.path.exists(multiple_file_name)
# ppi('Test existance: ' + multiple_file_name)
counter = 0
while exists == True:
counter = counter + 1
multiple_file_name = os.path.join(dest, ck + '+' + str(counter) + current_sound_extension)
exists = os.path.exists(multiple_file_name)
# ppi('Test (' + str(counter) + ') existance: ' + multiple_file_name)
shutil.copyfile(current_sound, multiple_file_name)
except Exception as ie:
ppe('Failed to process entry "' + row[0] + '"', ie)
finally:
os.remove(current_sound)
shutil.move(dest, AUDIO_MEDIA_PATH)
ppi('VOICE-PACK ADDED: ' + cpr_name)
except Exception as e:
ppe('FAILED TO PROCESS VOICE-PACK: ' + cpr_name, e)
finally:
shutil.rmtree(DOWNLOADS_PATH, ignore_errors=True)
def ban_caller(only_change):
global caller_title
global caller_title_without_version
# ban/change not possible as caller is specified by user or current caller is 'None'
if (CALLER != DEFAULT_CALLER and CALLER != '' and caller_title != '' and caller_title != None):
return
if only_change:
ccc_success = play_sound_effect('control_change_caller', wait_for_last = False, volume_mult = 1.0, mod = False)
if not ccc_success:
play_sound_effect('control', wait_for_last = False, volume_mult = 1.0, mod = False)
else:
cbc_success = play_sound_effect('control_ban_caller', wait_for_last = False, volume_mult = 1.0, mod = False)
if not cbc_success:
play_sound_effect('control', wait_for_last = False, volume_mult = 1.0, mod = False)
global caller_profiles_banned
caller_profiles_banned.append(caller_title_without_version)
path_to_callers_banned_file = os.path.join(AUDIO_MEDIA_PATH, DEFAULT_CALLERS_BANNED_FILE)
with open(path_to_callers_banned_file, 'w') as bcf:
for cpb in caller_profiles_banned:
bcf.write(cpb.lower() + '\n')
mirror_sounds()
setup_caller(hi=True)
def favor_caller(unfavor):
global caller_title_without_version
global caller_profiles_favoured
if caller_title_without_version == '':
return
if unfavor:
caller_profiles_favoured.remove(caller_title_without_version)
else:
caller_profiles_favoured.append(caller_title_without_version)
path_to_callers_favoured_file = os.path.join(AUDIO_MEDIA_PATH, DEFAULT_CALLERS_FAVOURED_FILE)
with open(path_to_callers_favoured_file, 'w') as fcf:
for cpf in caller_profiles_favoured:
fcf.write(cpf.lower() + '\n')
def delete_old_callers():
if REMOVE_OLD_VOICE_PACKS:
folders = os.listdir(AUDIO_MEDIA_PATH)
# store highest version for every voice-pack
voice_packs = {}
for folder in folders:
# check if folder-name fits pattern "name-vX" or "name"
match = re.match(r"(.+?)(?:-v(\d+))?$", folder)
if match:
name = match.group(1)
version = int(match.group(2)) if match.group(2) else 0
# updates highest version for that voice-pack
if name not in voice_packs or version > voice_packs[name]:
voice_packs[name] = version
# deletes all old voice-pack folders
for folder in folders:
match = re.match(r"(.+?)(?:-v(\d+))?$", folder)
if match:
name = match.group(1)
version = int(match.group(2)) if match.group(2) else 0
if version < voice_packs[name]:
folder_path = os.path.join(AUDIO_MEDIA_PATH, folder)
shutil.rmtree(folder_path)
ppi(f"Removed old voice-pack: {folder}")
def load_callers_banned():
global caller_profiles_banned
caller_profiles_banned = []
path_to_callers_banned_file = os.path.join(AUDIO_MEDIA_PATH, DEFAULT_CALLERS_BANNED_FILE)
if os.path.exists(path_to_callers_banned_file):
try:
with open(path_to_callers_banned_file, 'r') as bcf:
caller_profiles_banned = list(set(line.strip() for line in bcf))
display_caller_list(caller_profiles_banned, "BANNED VOICE-PACKS")
except FileExistsError:
pass
else:
try:
with open(path_to_callers_banned_file, 'x'):
ppi(f"'{path_to_callers_banned_file}' created successfully.")
except Exception as e:
ppe(f"Failed to create '{path_to_callers_banned_file}'", e)
def load_callers_favoured():
global caller_profiles_favoured
caller_profiles_favoured = []
path_to_callers_favoured_file = os.path.join(AUDIO_MEDIA_PATH, DEFAULT_CALLERS_FAVOURED_FILE)
if os.path.exists(path_to_callers_favoured_file):
try:
with open(path_to_callers_favoured_file, 'r') as bcf:
caller_profiles_favoured = list(set(line.strip() for line in bcf))
display_caller_list(caller_profiles_favoured, "FAVOURED VOICE-PACKS")
except FileExistsError:
pass
else:
try:
with open(path_to_callers_favoured_file, 'x'):
ppi(f"'{path_to_callers_favoured_file}' created successfully.")
except Exception as e:
ppe(f"Failed to create '{path_to_callers_favoured_file}'", e)
def load_callers():
global callers_profiles_all
callers_profiles_all = []
# load shared-sounds
shared_sounds = {}
if AUDIO_MEDIA_PATH_SHARED != DEFAULT_EMPTY_PATH:
for root, dirs, files in os.walk(AUDIO_MEDIA_PATH_SHARED):
for filename in files:
if filename.endswith(tuple(SUPPORTED_SOUND_FORMATS)):
full_path = os.path.join(root, filename)
base = os.path.splitext(filename)[0]
key = base.split('+', 1)[0]
if key in shared_sounds:
shared_sounds[key].append(full_path)
else:
shared_sounds[key] = [full_path]
# load callers
for root, dirs, files in os.walk(AUDIO_MEDIA_PATH):
file_dict = {}
for filename in files:
if filename.endswith(tuple(SUPPORTED_SOUND_FORMATS)):
base = os.path.splitext(filename)[0]
key = base.split('+', 1)[0]
full_path = os.path.join(root, filename)
if key in file_dict:
file_dict[key].append(full_path)
else:
file_dict[key] = [full_path]
if file_dict:
callers_profiles_all.append((root, file_dict))
# add shared-sounds to callers
for ss_k, ss_v in shared_sounds.items():
for (root, c_keys) in callers_profiles_all:
c_keys[ss_k] = ss_v
def display_caller_list(caller_list, text):
display = f"{text}: {len(caller_list)}"
ppi(display, None)
display = f"[ - "
for c in caller_list:
display += c + " - "
display += "]"
ppi(display)
def grab_caller_name(caller_path):
caller_name_with_version = os.path.basename(os.path.normpath(caller_path)).lower()
parts = caller_name_with_version.split('-')
caller_name_without_version = "-".join(parts[:-1]) if parts[-1].startswith('v') else caller_name_with_version
return (caller_name_without_version, caller_name_with_version)
def grab_caller_language(caller_name):
first_occurrences = []
caller_name = '-' + caller_name + '-'
for key in CALLER_LANGUAGES:
for tag in CALLER_LANGUAGES[key]:
tag_with_dashes = '-' + tag + '-'
index = caller_name.find(tag_with_dashes)
if index != -1: # find returns -1 if the tag is not found
first_occurrences.append((index, key))
if not first_occurrences: # if the list is empty
return None
# Sort the list of first occurrences and get the language of the tag that appears first
first_occurrences.sort(key=lambda x: x[0])
return first_occurrences[0][1]
def grab_caller_gender(caller_name):
first_occurrences = []
caller_name = '-' + caller_name + '-'
for key in CALLER_GENDERS:
for tag in CALLER_GENDERS[key]:
tag_with_dashes = '-' + tag + '-'
index = caller_name.find(tag_with_dashes)
if index != -1: # find returns -1 if the tag is not found
first_occurrences.append((index, key))
if not first_occurrences: # if the list is empty
return None
# Sort the list of first occurrences and get the gender of the tag that appears first
first_occurrences.sort(key=lambda x: x[0])
return first_occurrences[0][1]
def filter_most_recent_versions(voices):
max_versions = {}
for voice, data in voices:
parts = voice.split('-')
key = '-'.join(parts[:-1]) if parts[-1].startswith('v') else voice
version = int(parts[-1][1:]) if parts[-1].startswith('v') else 0
if key not in max_versions or version > max_versions[key][0]:
max_versions[key] = (version, data)
filtered_voices = []
for voice, data in voices:
parts = voice.split('-')
key = '-'.join(parts[:-1]) if parts[-1].startswith('v') else voice
version = int(parts[-1][1:]) if parts[-1].startswith('v') else 0
if version == max_versions[key][0]:
filtered_voices.append((voice, data))
return filtered_voices
def setup_caller(hi = False):
global callers_profiles_all
global caller_profiles_banned
global CALLER
global caller
global caller_title
global caller_title_without_version
global callers_available
global caller_profiles_favoured
caller = None
caller_title = ''
caller_title_without_version = ''
# filter callers by blacklist, language, gender and most recent version
callers_filtered = []
for c in callers_profiles_all:
(caller_name, caller_name_with_version) = grab_caller_name(c[0])
if caller_name in caller_profiles_banned or caller_name_with_version in caller_profiles_banned:
continue
if CALLER != DEFAULT_CALLER and CALLER != '' and caller_name_with_version.startswith(CALLER.lower()):
pass
else:
if RANDOM_CALLER_LANGUAGE != 0:
caller_language_key = grab_caller_language(caller_name)
if caller_language_key != RANDOM_CALLER_LANGUAGE:
continue
if RANDOM_CALLER_GENDER != 0:
caller_gender_key = grab_caller_gender(caller_name)
if caller_gender_key != RANDOM_CALLER_GENDER:
continue
callers_filtered.append(c)
if len(callers_filtered) > 0:
callers_filtered = filter_most_recent_versions(callers_filtered)
# store available caller names
callers_available = []
for cf in callers_filtered:
(caller_name, caller_name_with_version) = grab_caller_name(cf[0])
callers_available.append(caller_name)
display_caller_list(callers_available, "AVAILABLE VOICE-PACKS")
# specific caller
if CALLER != DEFAULT_CALLER and CALLER != '':
(wished_caller, wished_caller_with_version) = grab_caller_name(CALLER)
for cf in callers_filtered:
(caller_name, caller_name_with_version) = grab_caller_name(cf[0])
if caller_name_with_version.startswith(wished_caller_with_version):
caller = cf
break
elif caller_name_with_version.startswith(wished_caller):
ppi("NOTICE: '" + wished_caller_with_version + "' is an older voice-pack version. I am now using most recent version: " + "'" + caller_name_with_version + "'", None, '')
caller = cf
break
# random caller
else:
if len(callers_filtered) > 0:
if RANDOM_CALLER == 0:
caller = callers_filtered[0]
else:
caller = random.choice(callers_filtered)
else:
caller = None
# set caller
if caller is not None:
for sound_file_key, sound_file_values in caller[1].items():
sound_list = list()
for sound_file_path in sound_file_values:
sound_list.append(sound_file_path)
caller[1][sound_file_key] = sound_list
(caller_name, caller_name_with_version) = grab_caller_name(caller[0])
caller_title = caller_name_with_version
caller_title_without_version = caller_name
ppi("", None)
ppi("CURRENT VOICE-PACK: " + caller_title + " (" + str(len(caller[1].values())) + " Sound-file-keys)", None)
ppi("", None)
# ppi(caller[1])
caller = caller[1]
welcome_event = {
"event": "welcome",
"callersAvailable": callers_available,
"callersFavoured": caller_profiles_favoured,
"caller": caller_title_without_version
}
broadcast(welcome_event)
if hi and play_sound_effect('hi', wait_for_last=False):
mirror_sounds()
else:
ppi('NO CALLERS AVAILABLE')
def check_sounds(sounds_list):
global caller
all_sounds_available = True
try:
for s in sounds_list:
caller[s]
except Exception:
all_sounds_available = False
return all_sounds_available
def play_sound(sound, wait_for_last, volume_mult, mod):
volume = 1.0
if AUDIO_CALLER_VOLUME is not None:
volume = AUDIO_CALLER_VOLUME * volume_mult
global mirror_files
global caller_title_without_version
mirror_file = {
"caller": caller_title_without_version,
"path": quote(sound, safe=""),
"wait": wait_for_last,
"volume": volume,
"mod": mod
}
mirror_files.append(mirror_file)
if LOCAL_PLAYBACK:
if wait_for_last == True:
while mixer.get_busy():
time.sleep(0.01)
s = mixer.Sound(sound)
s.set_volume(volume)
s.play()
ppi('Play: "' + sound + '"')
def play_sound_effect(sound_file_key, wait_for_last = False, volume_mult = 1.0, mod = True):
try:
global caller
play_sound(random.choice(caller[sound_file_key]), wait_for_last, volume_mult, mod)
return True
except Exception as e:
ppe('Can not play sound for sound-file-key "' + sound_file_key + '" -> Ignore this or check existance; otherwise convert your file appropriate', e)
return False
def mirror_sounds():
global mirror_files
if len(mirror_files) != 0:
# Example
# {
# "event": "mirror",
# "files": [
# {
# "path": "C:\sounds\luca.mp3",
# "wait": False,
# },
# {
# "path": "C:\sounds\you_require.mp3",
# "wait": True,
# },
# {
# "path": "C:\sounds\40.mp3",
# "wait": True,
# }
# ]
# }
mirror = {
"event": "mirror",
"files": mirror_files
}
broadcast(mirror)
mirror_files = []
def start_board():
try:
res = requests.put(boardManagerAddress + '/api/detection/start')
# res = requests.put(boardManagerAddress + '/api/start')
# ppi(res)
except Exception as e:
ppe('Start board failed', e)
def stop_board():
try:
res = requests.put(boardManagerAddress + '/api/detection/stop')
# res = requests.put(boardManagerAddress + '/api/stop')
# ppi(res)
except Exception as e:
ppe('stop board failed', e)
def reset_board():
try:
res = requests.post(boardManagerAddress + '/api/reset')
# ppi(res)
except Exception as e:
ppe('Reset board failed', e)
def calibrate_board():
if play_sound_effect('control_calibrate', wait_for_last = False, volume_mult = 1.0) == False:
play_sound_effect('control', wait_for_last = False, volume_mult = 1.0)
mirror_sounds()
try:
res = requests.post(boardManagerAddress + '/api/config/calibration/auto')
# ppi(res)
except Exception as e:
ppe('Calibrate board failed', e)
def get_player_average(user_id, variant = 'x01', limit = '100'):
# get
# https://api.autodarts.io/as/v0/users/<user-id>/stats/<variant>?limit=<limit>
try:
res = requests.get(AUTODARTS_USERS_URL + user_id + "/stats/" + variant + "?limit=" + limit, headers={'Authorization': 'Bearer ' + kc.access_token})
m = res.json()
# ppi(m)
return m['average']['average']
except Exception as e:
ppe('Receive player-stats failed', e)
return None
def start_match(lobbyId):
if play_sound_effect('control_start_match', wait_for_last = False, volume_mult = 1.0, mod = False) == False:
play_sound_effect('control', wait_for_last = False, volume_mult = 1.0, mod = False)
mirror_sounds()
# post
# https://api.autodarts.io/gs/v0/lobbies/<lobby-id>/start
try:
global currentMatch
if currentMatch != None:
res = requests.post(AUTODARTS_LOBBIES_URL + lobbyId + "/start", headers={'Authorization': 'Bearer ' + kc.access_token})
ppi(res)
except Exception as e:
ppe('Start match failed', e)
def next_throw():
if play_sound_effect('control_next', wait_for_last = False, volume_mult = 1.0, mod = False) == False:
play_sound_effect('control', wait_for_last = False, volume_mult = 1.0, mod = False)
mirror_sounds()
# post
# https://api.autodarts.io/gs/v0/matches/<match-id>/players/next
try:
global currentMatch
if currentMatch != None:
requests.post(AUTODARTS_MATCHES_URL + currentMatch + "/players/next", headers={'Authorization': 'Bearer ' + kc.access_token})
except Exception as e:
ppe('Next throw failed', e)
def undo_throw():
if play_sound_effect('control_undo', wait_for_last = False, volume_mult = 1.0, mod = False) == False:
play_sound_effect('control', wait_for_last = False, volume_mult = 1.0, mod = False)
mirror_sounds()
# post
# https://api.autodarts.io/gs/v0/matches/<match-id>/undo
try:
global currentMatch
if currentMatch != None:
requests.post(AUTODARTS_MATCHES_URL + currentMatch + "/undo", headers={'Authorization': 'Bearer ' + kc.access_token})
except Exception as e:
ppe('Undo throw failed', e)
def correct_throw(throw_indices, score):
global currentMatch
score = FIELD_COORDS[score]
if currentMatch == None or len(throw_indices) > 3 or score == None:
return
cdcs_success = False