forked from Lenochxd/WebDeck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_server.py
2804 lines (2315 loc) · 101 KB
/
main_server.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
# Standard library imports
import time
import threading
import subprocess
import shutil
import copy
import re
import sys
import random
import json
import urllib.request
import zipfile
import os
import importlib
import ipaddress
from pathlib import Path
import inspect
import ast
# Third-party library imports
import requests
import socket
import spotipy
import spotipy.util as util
from deepdiff import DeepDiff
import mss
from PIL import Image
try: from deep_translator import GoogleTranslator
except SyntaxError: pass
import pyautogui as keyboard
import keyboard as keyboard2
import webcolors
import pyaudio
from flask import Flask, request, jsonify, render_template
from flask_socketio import SocketIO
from flask_minify import Minify
from engineio.async_drivers import gevent
import pyperclip
import win32api
import win32con
import win32gui
from win32com.client import Dispatch
from win10toast import ToastNotifier
import easygui
import psutil
import GPUtil
import pynvml
from pydub import AudioSegment
try:
import vlc
except:
pass
from obswebsocket import obsws, events
from obswebsocket import requests as obsrequests
# Numerical and scientific libraries
import numpy as np
import ctypes
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume, ISimpleAudioVolume
import comtypes
import math
# WebDeck imports
from updater import compare_versions, check_files
os.add_dll_directory(os.getcwd())
new_user = False
if not os.path.exists("config.json"):
shutil.copy("config_default.json", "config.json")
new_user = True
file_path = (
os.getenv("APPDATA") + r"\Microsoft\Windows\Start Menu\Programs\WebDeck.lnk"
)
if not os.path.exists(file_path) and getattr(sys, "frozen", False):
dir = os.getenv("APPDATA") + r"\Microsoft\Windows\Start Menu\Programs"
name = "WebDeck.lnk"
path = os.path.join(dir, name)
target = os.getcwd() + r"\\WebDeck.exe"
working_dir = os.getcwd()
icon = os.getcwd() + r"\\WebDeck.exe"
shell = Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = target
shortcut.WorkingDirectory = working_dir
shortcut.IconLocation = icon
shortcut.save()
if not os.path.exists("static/files/uploaded"):
try:
os.makedirs("static/files/uploaded")
except FileExistsError:
pass
with open("config.json", encoding="utf-8") as f:
config = json.load(f)
check_files("static/files/version.json", "data.json")
def load_lang_file(lang):
lang_dictionary = {}
lang_path = f"static/files/langs/{lang}.lang"
if not os.path.isfile(f"static/files/langs/{lang}.lang"):
for root, dirs, files in os.walk("static/files/langs"):
for file in files:
if file.endswith(".lang") and file.startswith(lang):
lang_path = f"static/files/langs/{file}"
with open(lang_path, "r", encoding="utf-8") as f:
lines = f.readlines()
for line in lines:
if (
line.replace(" ", "").replace("\n", "") != ""
and not line.startswith("//")
and not line.startswith("#")
):
try:
key, value = line.strip().split("=")
lang_dictionary[key] = value.strip()
except:
print(line)
return lang_dictionary
text = load_lang_file(config["settings"]["language"])
def check_json_update(config):
if "background" in config["front"]:
if type(config["front"]["background"]) == "str" and len(config["front"]["background"]) > 3:
config["front"]["background"] = [config["front"]["background"]]
if type(config["front"]["background"]) == "list" and config["front"]["background"] in [[], [""]]:
config["front"]["background"] = ["#141414"]
else:
config["front"]["background"] = ["#141414"]
if "auto-updates" not in config["settings"]:
config["settings"]["auto-updates"] = "true"
if "windows-startup" not in config["settings"]:
config["settings"]["windows-startup"] = "false"
if "flask-debug" not in config["settings"]:
config["settings"]["flask-debug"] = "true"
if "open-settings-in-browser" in config["settings"]:
del config["settings"]["open-settings-in-browser"]
if "open-settings-in-integrated-browser" not in config["settings"]:
config["settings"]["open-settings-in-integrated-browser"] = "false"
if "portrait-rotate" not in config["front"]:
config["front"]["portrait-rotate"] = "90"
if "edit-buttons-color" not in config["front"]:
config["front"]["edit-buttons-color"] = "false"
if "buttons-color" not in config["front"]:
config["front"]["buttons-color"] = ""
if "soundboard" not in config["settings"]:
config["settings"]["soundboard"] = {
"mic_input_device": "",
"vbcable": "cable input",
}
if "mic_input_device" not in config["settings"]["soundboard"]:
config["settings"]["soundboard"]["mic_input_device"] = ""
if "vbcable" not in config["settings"]["soundboard"]:
config["settings"]["soundboard"]["vbcable"] = "cable input"
if "enabled" not in config["settings"]["soundboard"]:
if config["settings"]["soundboard"]["mic_input_device"] != "":
config["settings"]["soundboard"]["enabled"] = "false"
else:
config["settings"]["soundboard"]["enabled"] = "true"
if "obs" not in config["settings"]:
config["settings"]["obs"] = {"host": "localhost", "port": 4455, "password": ""}
if "automatic-firewall-bypass" not in config["settings"]:
config["settings"]["automatic-firewall-bypass"] = "false"
if "fix-stop-soundboard" not in config["settings"]:
config["settings"]["fix-stop-soundboard"] = "false"
if "optimized-usage-display" not in config["settings"]:
config["settings"]["optimized-usage-display"] = "false"
if "theme" not in config["front"] or not os.path.isfile(f'static/themes/{config["front"]["theme"]}'):
config["front"]["theme"] = "default_theme.css"
themes = [
f"//{file_name}"
for file_name in os.listdir("static/themes/")
if file_name.endswith(".css") and not file_name.startswith("default_theme") and not file_name == config["front"]["theme"]
]
if "themes" not in config["front"]:
themes.append(config["front"]["theme"])
config["front"]["themes"] = themes
else:
# check if there's new themes installed
installed_themes = config["front"]["themes"]
new_themes = [theme for theme in themes if not any(theme.endswith(name) for name in installed_themes)]
if new_themes:
print("new themes:", new_themes)
config["front"]["themes"].extend(iter(new_themes))
# Check for deleted themes
try:
config["front"]["themes"] = eval(config["front"]["themes"])
except TypeError:
pass
for theme in config["front"]["themes"][:]:
theme_file = theme.replace('//', '')
if not os.path.isfile(f"static/themes/{theme_file}"):
config["front"]["themes"].remove(theme)
# Check for duplicates
temporary_list = [theme.replace("//", "") for theme in config["front"]["themes"]]
duplicates = {
theme for theme in temporary_list if temporary_list.count(theme) > 1
}
# Remove duplicates
for theme in duplicates:
while temporary_list.count(theme) > 1:
temporary_list.remove(theme)
if f"//{theme}" in config["front"]["themes"]:
config["front"]["themes"].remove(f"//{theme}")
if theme in config["front"]["themes"]:
config["front"]["themes"].remove(theme)
if theme == config["front"]["theme"]:
config["front"]["themes"].append(theme)
else:
config["front"]["themes"].insert(0, f"//{theme}")
# move the default theme to the bottom
if os.path.isfile(f'static/themes/{config["front"]["theme"]}'):
if config["front"]["theme"] in config["front"]["themes"]:
config["front"]["themes"].remove(config["front"]["theme"])
config["front"]["themes"].append(config["front"]["theme"])
return config
def parse_css_file(css_file_path):
css_data = {}
with open(css_file_path, 'r') as file:
for line in file:
line = line.strip()
if line.replace(" ", "").startswith("/*-------"):
break
if '=' in line:
key, value = line.split('=')
key = key.strip()
value = value.strip()
css_data[key.lower()] = value
for info in [
"theme-name",
"theme-description",
"theme-logo",
"theme-author-github"
]:
if info not in css_data.keys():
css_data[info] = text["not_specified"]
if css_data["theme-logo"] == text["not_specified"]:
css_data["theme-logo"] = ""
if css_data["theme-name"] == text["not_specified"]:
css_data["theme-name"] = os.path.basename(css_file_path)
if css_data["theme-description"] == text["not_specified"]:
css_data["theme-description"] = css_file_path
return css_data
def parse_themes():
parsed_themes = {}
for file_name in os.listdir("static/themes/"):
if file_name.endswith(".css"):
parsed_themes[file_name] = parse_css_file(f"static/themes/{file_name}")
return parsed_themes
def color_distance(color1, color2):
"""
Calculate the distance between two colors using the Euclidean formula
"""
r1, g1, b1 = [int(color1[i : i + 2], 16) for i in range(1, 7, 2)]
r2, g2, b2 = [int(color2[i : i + 2], 16) for i in range(1, 7, 2)]
return math.sqrt((r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2)
def sort_colorsjson():
with open("colors.json", "r", encoding="utf-8") as f:
try:
data = json.load(f)
except Exception:
shutil.copyfile("static/files/colorsbcp.json", "colors.json")
with open("colors.json", "r", encoding="utf-8") as f:
data = json.load(f)
# Sort colors using the distance between each pair of colors
sorted_colors = [data[0]] # The first color is always the same
data.pop(0)
while data:
current_color = sorted_colors[-1]["hex_code"]
nearest_color = min(
data, key=lambda c: color_distance(current_color, c["hex_code"])
)
sorted_colors.append(nearest_color)
data.remove(nearest_color)
if not sorted_colors == data:
with open("colors.json", "w", encoding="utf-8") as f:
json.dump(sorted_colors, f, indent=4)
sort_colorsjson()
def download_nircmd():
url = "https://www.nirsoft.net/utils/nircmd.zip"
urllib.request.urlretrieve(url, "nircmd.zip")
with zipfile.ZipFile("nircmd.zip", "r") as zip_ref:
zip_ref.extractall("")
os.remove("nircmd.zip")
os.remove("NirCmd.chm")
os.remove("nircmdc.exe")
if not os.path.isfile("nircmd.exe"):
download_nircmd()
def replace_last_element(string, old_element, new_element):
# Find the last occurrence of the old element
last_index = string.rfind(old_element)
if last_index != -1: # If the old element is found
return string[:last_index] + string[last_index:].replace(
old_element, new_element, 1
)
else:
# If the old element is not found, return the original string
return string
config = check_json_update(config)
with open("config.json", "w", encoding="utf-8") as json_file:
json.dump(config, json_file, indent=4)
def save_config(config):
with open("config.json", "w", encoding="utf-8") as json_file:
json.dump(config, json_file, indent=4)
with open("config.json", encoding="utf-8") as f:
config = json.load(f)
return config
def create_folders(config):
global folders_to_create
for folder in folders_to_create:
config["front"]["buttons"][folder["name"]] = [
{
"image": "back10.svg",
"image_size": "110%",
"message": f"/folder {folder['parent_folder']}",
"name": f"back to {folder['parent_folder']}",
}
]
void_count = int(config["front"]["width"]) * int(config["front"]["height"])
for _ in range(void_count - 1):
config["front"]["buttons"][folder["name"]].append({"VOID": "VOID"})
print("NEW FOLDER :", folder["name"])
folders_to_create = []
return config
def select_audio_device(channels_type="input"):
p = pyaudio.PyAudio()
all_devices = []
try:
for i in range(p.get_device_count()):
device_info = p.get_device_info_by_index(i)
if channels_type == "input":
channels = device_info["maxInputChannels"]
else:
channels = device_info["maxOutputChannels"]
# Vérifier si le périphérique est un périphérique d'entrée actif
if channels > 0 and device_info["hostApi"] == 0:
ok = True
for device in all_devices:
if (
device[device.find("(") + 1 :]
in device_info["name"][device_info["name"].find("(") + 1 :]
):
ok = False
if ok and not "microsoft - input" in device_info["name"].lower():
print(f"Device {i}: {device_info['name']}")
all_devices.append(device_info["name"])
del ok
print(f"ALL: {len(all_devices)}")
print(p.get_default_output_device_info())
except Exception as e:
print(f"An error has occurred : {str(e)}")
finally:
p.terminate()
return all_devices
def get_device(vbcable_device):
# https://stackoverflow.com/questions/73884593/how-to-change-vlc-python-output-device
try:
player = vlc.MediaPlayer()
mods = player.audio_output_device_enum()
if mods:
mod = mods
while mod:
mod = mod.contents
# If VB-Cable is found, return it's module and device id
if vbcable_device.lower() in str(mod.description).lower():
device = mod.device
return device
mod = mod.next
except Exception as e:
print(e)
return "ERROR_NO_VLC"
def get_ffmpeg():
if os.path.isfile("ffmpeg.exe"):
return os.path.abspath("ffmpeg.exe")
# Search for ffmpeg installation on winget
try:
base_path = Path("C:/Users")
# Iterate through user directories
for user_dir in base_path.iterdir():
if user_dir.is_dir():
# Iterate through subdirectories of the user directory
for package_dir in user_dir.joinpath("AppData/Local/Microsoft/WinGet/Packages").iterdir():
if package_dir.name.startswith("Gyan.FFmpeg"):
# Iterate through subdirectories of the package
for sub_dir in package_dir.iterdir():
if sub_dir.is_dir() and sub_dir.name.startswith("ffmpeg-"):
# Find the ffmpeg.exe file
ffmpeg_path = sub_dir.joinpath("bin/ffmpeg.exe")
# Check if the file exists
if ffmpeg_path.exists():
print("Path found:", ffmpeg_path)
return str(ffmpeg_path)
continue
continue
except Exception as e:
print("FFMPEG: WinGet Error:", e)
# Search for ffmpeg installation via webdeck servers
if os.path.isfile("ffmpeg.exe"):
return "ffmpeg.exe"
try:
print("downloading ffmpeg using webdeck servers...")
url = "https://bishokus.fr/dl_ffmpeg"
urllib.request.urlretrieve(url, "ffmpeg-N-114554-g7bf85d2d3a-win64-gpl.zip")
with zipfile.ZipFile("ffmpeg-N-114554-g7bf85d2d3a-win64-gpl.zip", "r") as zip_ref:
zip_ref.extractall("")
os.remove("ffmpeg-N-114554-g7bf85d2d3a-win64-gpl.zip")
return "ffmpeg.exe"
except Exception as e:
print("FFMPEG:", e)
print("FFMPEG: downloading ffmpeg using winget...")
subprocess.Popen("winget install ffmpeg", shell=True)
print("FFMPEG: not found.")
return None
ffmpeg_path = ""
def add_silence_to_end(input_file, output_file, silence_duration_ms=2000):
global ffmpeg_path
try:
audio = AudioSegment.from_mp3(os.path.abspath(input_file))
except FileNotFoundError as e:
print(e)
ffmpeg_path = get_ffmpeg()
if ffmpeg_path is not None and ffmpeg_path != "ffmpeg.exe":
shutil.copyfile(ffmpeg_path, "ffmpeg.exe")
shutil.copyfile(ffmpeg_path.replace('ffmpeg.exe', 'ffprobe.exe'), "ffprobe.exe")
ffmpeg_path = os.path.abspath("ffmpeg.exe")
ffprobe_path = ffmpeg_path.replace('ffmpeg.exe', 'ffprobe.exe')
AudioSegment.converter = ffmpeg_path
AudioSegment.ffmpeg = ffmpeg_path
AudioSegment.ffprobe = ffprobe_path
if AudioSegment.converter is None:
return False
else:
silent_segment = AudioSegment.silent(duration=silence_duration_ms)
audio_with_silence = audio + silent_segment
audio_with_silence.export(output_file, format="mp3")
return True
def silence_path(input_file, remove_previous=False):
output_file = replace_last_element(input_file, ".mp3", "_.mp3")
if os.path.exists(output_file):
return input_file
result = add_silence_to_end(input_file, output_file, 2)
if result == False:
return False
if remove_previous:
os.remove(input_file)
return output_file
cable_input_device = get_device(config["settings"]["soundboard"]["vbcable"])
vlc_installed = cable_input_device != "ERROR_NO_VLC"
player_vbcable = {}
player_ear_soundboard = {}
def playsound(file_path: str, sound_volume, ear_soundboard=True):
global cable_input_device, player
if not vlc_installed:
print("VLC is not installed!")
return jsonify({"success": False, "message": text["vlc_not_installed_error"]})
else:
if config["settings"]["fix-stop-soundboard"] == "true":
file_path = silence_path(file_path)
if file_path == False:
return jsonify({"success": False, "message": text["ffmpeg_not_installed_error"]})
print(f"Play: {file_path} - volume:{sound_volume}\r\n")
print(len(player_vbcable))
print(player_vbcable)
p_id = len(player_vbcable.keys())
if p_id <= 3:
player_vbcable[p_id] = vlc.MediaPlayer(file_path)
player_vbcable[p_id].audio_set_volume(int(sound_volume * 100))
player_vbcable[p_id].audio_output_device_set(None, cable_input_device)
player_vbcable[p_id].play()
player_vbcable[p_id].event_manager().event_attach(
vlc.EventType.MediaPlayerEndReached, lambda x: remove_player(1, p_id)
)
if ear_soundboard:
player_ear_soundboard[p_id] = vlc.MediaPlayer(file_path)
player_ear_soundboard[p_id].audio_set_volume(int(sound_volume * 100))
player_ear_soundboard[p_id].play()
player_ear_soundboard[p_id].event_manager().event_attach(
vlc.EventType.MediaPlayerEndReached,
lambda x: remove_player(2, p_id),
)
else:
player_vbcable[0].stop()
player_vbcable[0].set_time(0)
player_vbcable[0].play()
player_vbcable[0].event_manager().event_attach(
vlc.EventType.MediaPlayerEndReached, lambda x: remove_player(1, p_id)
)
if ear_soundboard:
player_ear_soundboard[0].stop()
player_ear_soundboard[0].set_time(0)
player_ear_soundboard[0].play()
player_ear_soundboard[0].event_manager().event_attach(
vlc.EventType.MediaPlayerEndReached,
lambda x: remove_player(2, p_id),
)
return jsonify({"success": True})
def remove_player(sb_type, p_id):
global player_vbcable, player_ear_soundboard
try:
if sb_type == 1:
del player_vbcable[p_id]
elif sb_type == 2:
del player_ear_soundboard[p_id]
else:
del p_id
except KeyError:
pass
def stop_soundboard():
if not vlc_installed:
print("VLC is not installed!")
return jsonify({"success": False, "message": text["vlc_not_installed_error"]})
else:
global player_vbcable, player_ear_soundboard
try:
last_key = list(player_vbcable.keys())[-1]
last_value = player_vbcable[last_key]
except IndexError:
return jsonify({"success": True, "message": "There are no sounds actually playing"})
while str(last_value.get_state()) == "State.Playing":
print(player_vbcable)
print(player_ear_soundboard)
try:
for p_id, player in player_vbcable.items():
try:
player.stop()
player.release()
# del player_vbcable[p_id]
except Exception as e:
pass
for p_id, player in player_ear_soundboard.items():
try:
player.stop()
player.release()
# del player_ear_soundboard[p_id]
except Exception as e:
pass
break
except RuntimeError as e:
print("RT error:", e)
...
player_vbcable.clear()
player_ear_soundboard.clear()
return jsonify({"success": True})
def should_i_close():
global sb_on
if getattr(sys, "frozen", False):
is_handler_opened = any(
process.info["name"].lower().strip().replace(".exe", "") == "webdeck"
for process in psutil.process_iter(["pid", "name"])
)
if not is_handler_opened:
sb_on = False
obs.disconnect()
sys.exit()
def show_error(message):
print(message)
ctypes.windll.user32.MessageBoxW(None, message, "WebDeck Error", 0)
def print_dict_differences(dict1, dict2):
diff = DeepDiff(dict1, dict2, ignore_order=True)
print("Differences found :")
for key, value in diff.items():
print(f"Key : {key}")
print(f"Difference : {value}")
print("----------------------")
def merge_dicts(d1, d2):
"""
Merge two dictionaries taking including subdictionaries.
Keys in d2 overwrite corresponding keys in d1, unless they are part of a subdictionary.
"""
for key in d2:
if key in d1 and isinstance(d1[key], dict) and isinstance(d2[key], dict):
# Recursively, we merge the subdictionaries with the merge_dict method.
merge_dicts(d1[key], d2[key])
else:
# If the key exists in d1 and it is not a subdictionary, we replace it with that of d2.
d1[key] = d2[key]
return d1
# resize grid ||| start
def create_matrix(config):
matrix = []
for folder_count, (folder_name, folder_content) in enumerate(
config["front"]["buttons"].items()
):
row_count = 0
matrix.append([])
for count, button in enumerate(folder_content, start=1):
if row_count >= len(matrix[folder_count]):
matrix[folder_count].append([])
matrix[folder_count][row_count].append(button)
if count % int(config["front"]["width"]) == 0:
row_count += 1
matrix_height = len(matrix)
matrix_width = len(matrix[0])
return matrix
def unmatrix(matrix):
for folder_count, folder in enumerate(matrix):
folderName = list(config["front"]["buttons"])[folder_count]
config["front"]["buttons"][folderName] = []
for row in folder:
for button in row:
config["front"]["buttons"][folderName].append(button)
return config
def update_gridsize(config, new_height, new_width):
new_height, new_width = int(new_height), int(new_width)
matrix = create_matrix(config)
old_height, old_width = int(config["front"]["height"]), int(
config["front"]["width"]
)
# if height has changed
if old_height != new_height:
# if the height has increased
if new_height > old_height:
difference = new_height - old_height
for count, _ in enumerate(range(difference), start=1):
for folder_name, folder_content in config["front"]["buttons"].items():
for _ in range(old_width):
# if count % 2 == 0:
# folder_content.insert(0, {"VOID": "VOID"})
# else:
folder_content.append({"VOID": "VOID"})
matrix = create_matrix(config)
# if the height has decreased
if old_height > new_height:
difference = old_height - new_height
print("height decreased")
for count, _ in enumerate(range(difference), start=1):
for folder_count, folder in enumerate(matrix):
for row_count, row in enumerate(reversed(folder)):
if all(element == {"VOID": "VOID"} for element in row):
folder.pop(-row_count - 1)
break
else:
for col_count in range(len(folder[0])):
for row_count, row in enumerate(reversed(folder), start=1):
if folder[-row_count][col_count] == {"VOID": "VOID"}:
num = row_count
while num > 1:
folder[-num][col_count] = folder[-num + 1][
col_count
]
num -= 1
folder[-num][col_count] = {"DEL": "DEL"}
break
else:
x = False
for colb_count in range(len(folder[0])):
for rowb_count in range(len(folder)):
if folder[rowb_count][colb_count] == {
"VOID": "VOID"
}:
folder[rowb_count][colb_count] = folder[-1][
col_count
]
x = True
break
if x == True:
break
if x == False:
print("NOT ENOUGH SPACE")
folder.pop(-1)
# if width has changed
if old_width != new_width:
# if the width has increased
if new_width > old_width:
difference = new_width - old_width
new_matrix = matrix
for count, _ in enumerate(range(difference), start=1):
for folder_count, folder in enumerate(matrix):
for row_count, row in enumerate(folder):
# if count % 2 == 0:
# new_matrix[folder_count][row_count].insert(0, {"VOID": "VOID"})
# else:
new_matrix[folder_count][row_count].append({"VOID": "VOID"})
matrix = new_matrix
if new_width < old_width:
difference = old_width - new_width
print("width decreased")
for count, _ in enumerate(range(difference), start=1):
for folder in matrix:
for col_count in range(len(folder[0])):
if all(
folder[row_count][-col_count - 1] == {"VOID": "VOID"}
for row_count in range(len(folder))
):
for row_count in range(len(folder)):
folder[row_count].pop(-col_count - 1)
break
else:
element_to_del = 0
for row in folder:
element_to_del += 1
for element_count, element in enumerate(row):
if element == {"VOID": "VOID"}:
row.pop(element_count)
element_to_del -= 1
if element_to_del == 0:
break
if element_to_del > 0:
for row in folder:
for element_count, element in enumerate(row):
if element == {"VOID": "VOID"}:
row.pop(element_count)
element_to_del -= 1
if element_to_del == 0:
break
if element_to_del == 0:
break
if element_to_del > 0:
print("NOT ENOUGH SPACE")
config = unmatrix(matrix)
print(old_height, new_height)
print(old_width, new_width)
return config
# resize grid ||| end
# for folder_name, folder_content in config["front"]["buttons"].items():
# for button in folder_content:
# if 'action' not in button.keys():
# button['action'] = {
# "touch_start": "click",
# "touch_keep": "None",
# "touch_end": "none",
# }
# if 'image' in button.keys() and not button['image'].strip() == '' and ':' in button['image'] and not button['image'].startswith('http'):
# button['image'] = button['image'].replace('/', '\\')
# splitted = button['image'].split('\\')
# try:
# copyfile(button['image'],f'static/files/images/{splitted[-1]}')
# except Exception:
# pass
for filename in os.listdir("static/files/images"):
if " " in filename and not filename.startswith("!!"):
new_filename = filename.replace(" ", "_")
os.rename(
f"static/files/images/{filename}", f"static/files/images/{new_filename}"
)
print(f"renamed {filename}")
app = Flask(__name__)
app.jinja_env.globals.update(select_audio_device=select_audio_device)
if getattr(sys, "frozen", False):
Minify(app=app, html=True, js=True, cssless=True)
app.config["SECRET_KEY"] = "secret!"
socketio = SocketIO(app)
toaster = ToastNotifier()
# Set up the OBS WebSocket client
def reload_obs():
obs_host = config["settings"]["obs"]["host"]
obs_port = int(config["settings"]["obs"]["port"])
obs_password = config["settings"]["obs"]["password"]
obs = obsws(obs_host, obs_port, obs_password)
return obs_host, obs_port, obs_password, obs
obs_host, obs_port, obs_password, obs = reload_obs()
# Set up the Spotify API client
try:
spotify_redirect_uri = "http://localhost:8888/callback"
spotify_scope = "user-library-modify user-library-read user-read-currently-playing user-read-playback-state user-modify-playback-state playlist-read-private playlist-read-collaborative playlist-modify-private playlist-modify-public user-follow-modify user-follow-read"
spotify_token = util.prompt_for_user_token(
config["settings"]["spotify-api"]["USERNAME"],
spotify_scope,
config["settings"]["spotify-api"]["CLIENT_ID"],
config["settings"]["spotify-api"]["CLIENT_SECRET"],
spotify_redirect_uri,
)
sp = spotipy.Spotify(auth=spotify_token)
spotify_current_user = sp.current_user()["id"]
except:
pass
python_threads = []
def execute_python_file(file_path):
with open(file_path, "r") as file:
file_content = file.read()
exec(file_content)
def get_current_volume():
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = ctypes.cast(interface, ctypes.POINTER(IAudioEndpointVolume))
return volume.GetMasterVolumeLevelScalar()
def set_volume(target_volume):
current_volume = get_current_volume()
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = ctypes.cast(interface, ctypes.POINTER(IAudioEndpointVolume))
while math.isclose(current_volume, target_volume, rel_tol=0.01) == False:
if current_volume > target_volume:
current_volume -= 0.01
else:
current_volume += 0.01
volume.SetMasterVolumeLevelScalar(current_volume, None)
time.sleep(0.01)
return current_volume
def increase_volume(delta):
win32api.keybd_event(win32con.VK_VOLUME_UP, 0)
win32api.keybd_event(win32con.VK_VOLUME_UP, 0, win32con.KEYEVENTF_KEYUP)
if delta == "":
return get_current_volume()
target_volume = get_current_volume() + (int(delta) / 100.0)
return set_volume(target_volume)
def decrease_volume(delta):
win32api.keybd_event(win32con.VK_VOLUME_DOWN, 0)
win32api.keybd_event(win32con.VK_VOLUME_DOWN, 0, win32con.KEYEVENTF_KEYUP)
if delta == "":
return get_current_volume()
target_volume = get_current_volume() - (int(delta) / 100.0)
return set_volume(target_volume)
def getarg(message, arg):
return next(
(
x.split(f"{arg}:", 1)[1].strip()
for x in message.split()
if x.startswith(f"{arg}:")
),
None,
)
def find_color(hex_code, colors):
try:
# Finding the exact color in the JSON file
for color in colors:
if color["hex_code"] == hex_code:
return color["name"]
# If the exact color is not found, search for the closest color
closest_color = None
min_distance = float("inf")
for color in colors:
distance = get_color_distance(hex_code, color["hex_code"])
if distance < min_distance:
min_distance = distance
closest_color = color
return closest_color["name"]
except ValueError:
return "Can not find color"
def get_color_distance(hex_code1, hex_code2):
rgb1 = webcolors.hex_to_rgb(hex_code1)
rgb2 = webcolors.hex_to_rgb(hex_code2)
return sum((a - b) ** 2 for a, b in zip(rgb1, rgb2))
def translate(word, target_language):
# Separate words with spaces before each capital letter
word = "".join([f" {i}" if i.isupper() else i for i in word]).strip()
if word == "Discord" or target_language.upper() == "EN":
return word
try:
return GoogleTranslator(source="en", target=target_language).translate(word)
except NameError:
return word