-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhelper.py
637 lines (532 loc) · 25.7 KB
/
helper.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
from __future__ import annotations
import json
import os
import platform
import tkinter as tk
from tqdm import tqdm
from tkinter import ttk
import keyring
import requests
backgroundColor = "#2b2b2b"
buttonBackground = "#424242"
foregroundColor = "white"
useGUI = True
#if platform.system() == "Windows":
# import pyaudiowpatch as pyaudio
#else:
# import pyaudio
import pyaudio
from speechRecognition.__SpeechRecProviderAbstract import SpeechRecProvider
from ttsProviders.__TTSProviderAbstract import TTSProvider
ttsProvider:TTSProvider
subtitlesEnabled = False
chosenOutput = -1
defaultConfig: dict[str, str | int| list|float] = {
"is_post_refactoring" : True,
"misc_settings": {
"output_device":"",
"speech_provider":"",
"tts_provider":""
},
"obs_settings": {
"obs_password": "",
"obs_port": 4455,
"obs_host": "localhost"
},
"recasepunc_settings": {
"model_path": "",
"enabled": True,
"language": ""
},
"translation_settings": {
"engine":"DeepL",
"language":"en"
},
"text_to_speech_config": {
"ElevenlabsProvider": {
"voice_id": "",
"stability": 80,
"clarity": 30,
"latency_optimization_level":"1: 50% of maximum improvement (recommended)"
},
"PyttsxProvider": {
"voice_name": ""
}
},
"speech_recognition_config":{
"VoskProvider": {
"model_path": ""
},
"WhisperProvider": {
"pause_time": 0.8,
"energy_threshold": 250,
"dynamic_energy_threshold": True
},
"AzureProvider": {
"service_region": "",
"language_list": []
}
},
"stored_choices" : {}
}
_configData:dict = {}
def choose_yes_no(prompt: str, trueOption: str = "Yes", falseOption: str = "No", enableRemember:bool=False) -> bool:
if enableRemember and prompt in _configData["stored_choices"]:
return _configData["stored_choices"][prompt]
if useGUI:
def on_yes_click():
result[0] = True
window.destroy()
def on_no_click():
result[0] = False
window.destroy()
# Initialize window
window = tk.Tk()
window.title("Question")
window.configure(bg="#2b2b2b")
setup_style(window, backgroundColor, buttonBackground,foregroundColor)
# Create and place the prompt label
prompt_label = ttk.Label(window, text=prompt, wraplength=300)
prompt_label.grid(row=0, column=0, columnspan=2, padx=10, pady=10)
# Create and place the yes button
yes_button = ttk.Button(window, text=trueOption, command=on_yes_click)
yes_button.grid(row=1, column=0, padx=10, pady=10)
# Create and place the no button
no_button = ttk.Button(window, text=falseOption, command=on_no_click)
no_button.grid(row=1, column=1, padx=10, pady=10)
# Create and place the "Don't ask again" checkbox
dont_ask_var = tk.BooleanVar()
if enableRemember:
dont_ask_checkbox = ttk.Checkbutton(window, text="Remember my choice", variable=dont_ask_var)
dont_ask_checkbox.grid(row=2, column=0, columnspan=2)
# Center the window
window.eval('tk::PlaceWindow . center')
result = [False]
window.mainloop()
if dont_ask_var.get() and enableRemember:
_configData["stored_choices"][prompt] = result[0]
update_config_file()
return result[0]
else:
print(prompt)
while True:
userInput = input(trueOption + " or " + falseOption + "?")
if (trueOption.lower().find(userInput.lower()) == 0) ^ (falseOption.lower().find(userInput.lower()) == 0):
if enableRemember:
while True:
dontAskInput = input("Don't ask again and always use this result? (yes or no): ")
if ("yes".find(dontAskInput.lower()) == 0) ^ ("no".find(dontAskInput.lower()) == 0):
if "yes".find(dontAskInput.lower()) == 0:
_configData["stored_choices"][prompt] = trueOption.lower().find(userInput.lower()) == 0
update_config_file()
break
return trueOption.lower().find(userInput.lower()) == 0
def choose_int(prompt, minValue, maxValue) -> int:
print(prompt)
chosenVoiceIndex = -1
while not (minValue <= chosenVoiceIndex <= maxValue):
try:
chosenVoiceIndex = int(input("Input a number between " + str(minValue) +" and " + str(maxValue)+"\n"))
except ValueError:
print("Not a valid number.")
return chosenVoiceIndex
def choose_float(prompt, minValue, maxValue) -> int:
print(prompt)
chosenVoiceIndex = -1
while not (minValue <= chosenVoiceIndex <= maxValue):
try:
chosenVoiceIndex = float(input("Input a number between " + str(minValue) +" and " + str(maxValue)+"\n"))
except ValueError:
print("Not a valid number.")
return chosenVoiceIndex
def choose_from_list_of_strings(prompt, options:list[str]) -> str:
print(prompt)
if len(options) == 1:
print("Choosing the only available option: " + options[0])
return options[0]
for index, option in enumerate(options):
print(str(index+1) + ") " + option)
chosenOption = choose_int("", 1, len(options)) - 1
return options[chosenOption]
def update_config_file():
json.dump(_configData, open("config.json", "w"), indent=4)
def setup_config():
global defaultConfig
if not os.path.exists("config.json"):
json.dump(defaultConfig, open("config.json", "w"), indent=4)
global _configData
try:
_configData = json.load(open("config.json", "r"))
except:
print("Invalid config! Did you remember to escape the backslashes?")
exit()
if "is_post_refactoring" not in _configData:
input("The format of config.json is outdated, it will be deleted and remade.\nCopy anything you need to from it then press enter.")
_configData = defaultConfig
json.dump(defaultConfig, open("config.json", "w"), indent=4)
for key, value in defaultConfig.items():
if key not in _configData:
_configData[key] = value
def _edit_config_property_recursive(dictToChooseFrom:dict):
options = list()
for key, value in dictToChooseFrom.items():
if key != "is_post_refactoring":
options.append(key[0].upper() + key[1:].replace("_", " "))
chosenOption = choose_from_list_of_strings("Which one would you like to edit?", options)
if chosenOption not in dictToChooseFrom:
chosenKey = (chosenOption[0].lower() + chosenOption[1:]).replace(" ", "_")
else:
chosenKey = chosenOption
chosenProperty = dictToChooseFrom[chosenKey]
if type(chosenProperty) == dict:
_edit_config_property_recursive(chosenProperty)
else:
if type(chosenProperty) == str:
dictToChooseFrom[chosenKey] = input("Please input the new value for " + chosenOption + " (current value:" +chosenProperty+")")
elif type(chosenProperty) == int:
dictToChooseFrom[chosenKey] = choose_int("Please input the new value for " + chosenOption + " (current value:" +chosenProperty+")", minValue=0, maxValue=999)
elif type(chosenProperty) == float:
dictToChooseFrom[chosenKey] = choose_float("Please input the new value for " + chosenOption + " (current value:" +chosenProperty+")", minValue=0, maxValue=999)
elif type(chosenProperty) == list:
while True:
chosenProperty = dictToChooseFrom[chosenKey]
print("The current value of " + chosenOption + " is " + str(chosenProperty))
if len(chosenProperty) == 0:
addOrRemove = True
else:
addOrRemove = choose_yes_no("Would you like to add or remove an item from the list?", trueOption="Add", falseOption="Remove")
if addOrRemove:
dictToChooseFrom[chosenKey].append(input("Please input the new item."))
else:
dictToChooseFrom[chosenKey].remove(choose_from_list_of_strings("Please choose which item to remove.",chosenProperty))
if not choose_yes_no("Would you like to continue editing the list?"):
break
update_config_file()
def get_provider_config(provider: SpeechRecProvider | TTSProvider) -> dict[str, str|float|bool|int|list]:
if TTSProvider in provider.__class__.__bases__:
providerType = "text_to_speech_config"
elif SpeechRecProvider in provider.__class__.__bases__:
providerType = "speech_recognition_config"
else:
raise ValueError("Provider does not inherit from either SpeechRecProvider nor TTSProvider!")
if providerType not in _configData:
_configData[providerType] = dict()
className = provider.__class__.__name__
if className not in _configData[providerType]:
_configData[providerType][className] = dict()
return _configData[providerType][className]
def update_provider_config(provider: SpeechRecProvider | TTSProvider, providerConfig:dict):
if type(provider) == TTSProvider:
providerType = "text_to_speech_config"
else:
providerType = "speech_recognition_config"
className = provider.__class__.__name__
_configData[providerType][className] = providerConfig
update_config_file()
def get_obs_config():
return _configData["obs_settings"]
def get_recasepunc_config():
return _configData["recasepunc_settings"]
def get_misc_config():
return _configData["misc_settings"]
def get_translation_config():
return _configData["translation_settings"]
def get_list_of_portaudio_devices(deviceType:str, alsaOnly=False) -> list[str]:
"""
Returns a list containing all the names of portaudio devices of the specified type.
"""
if deviceType != "output" and deviceType != "input":
raise ValueError("Invalid audio device type.")
pyABackend = pyaudio.PyAudio()
hostAPIinfo = None
#This section of code was useful when I was trying to use WASAPI loopback devices.
#Right now it's actively harmful as WASAPI is a lot more limited with sample rates, which is why it's commented out.
#if platform.system() == "Windows":
# for i in range(pyABackend.get_host_api_count()):
# apiInfo = pyABackend.get_host_api_info_by_index(i)
# if "WASAPI" in apiInfo["name"]:
# hostAPIinfo = apiInfo
# break
if platform.system() == "Linux":
for i in range(pyABackend.get_host_api_count()):
apiInfo = pyABackend.get_host_api_info_by_index(i)
if "ALSA" in apiInfo["name"]:
hostAPIinfo = apiInfo
break
if hostAPIinfo is None:
hostAPIinfo = pyABackend.get_default_host_api_info()
deviceNames = list()
activeDevices = None
if platform.system() == "Windows":
activeDevices = get_list_of_active_coreaudio_devices(deviceType)
for i in range(hostAPIinfo["deviceCount"]):
device = pyABackend.get_device_info_by_host_api_device_index(hostAPIinfo["index"], i)
if device["max" + deviceType[0].upper() + deviceType[1:] + "Channels"] > 0:
if platform.system() == "Linux" and alsaOnly:
if "(hw:" in device["name"]:
deviceNames.append(device["name"] + " - " + str(device["index"]))
else:
if activeDevices is not None:
deviceIsActive = False
for activeDevice in activeDevices:
if device["name"] in activeDevice.FriendlyName:
deviceNames.append(activeDevice.FriendlyName + " - " + str(device["index"]))
deviceIsActive = True
break
if not deviceIsActive:
print(f"Device {device['name']} was skipped due to being marked inactive by CoreAudio.")
else:
deviceNames.append(device["name"] + " - " + str(device["index"]))
return deviceNames
def get_list_of_active_coreaudio_devices(deviceType:str) -> list:
if platform.system() != "Windows":
raise NotImplementedError("This is only valid for windows.")
import comtypes
from pycaw.pycaw import AudioUtilities, IMMDeviceEnumerator, EDataFlow, DEVICE_STATE
from pycaw.constants import CLSID_MMDeviceEnumerator
if deviceType != "output" and deviceType != "input":
raise ValueError("Invalid audio device type.")
if deviceType == "output":
EDataFlowValue = EDataFlow.eRender.value
else:
EDataFlowValue = EDataFlow.eCapture.value
# Code to enumerate devices adapted from https://github.com/AndreMiras/pycaw/issues/50#issuecomment-981069603
devices = list()
deviceEnumerator = comtypes.CoCreateInstance(
CLSID_MMDeviceEnumerator,
IMMDeviceEnumerator,
comtypes.CLSCTX_INPROC_SERVER)
if deviceEnumerator is None:
raise ValueError("Couldn't find any devices.")
collection = deviceEnumerator.EnumAudioEndpoints(EDataFlowValue, DEVICE_STATE.ACTIVE.value)
if collection is None:
raise ValueError("Couldn't find any devices.")
count = collection.GetCount()
for i in range(count):
dev = collection.Item(i)
if dev is not None:
if not ": None" in str(AudioUtilities.CreateDevice(dev)):
devices.append(AudioUtilities.CreateDevice(dev))
return devices
def get_portaudio_device_info_from_name(deviceName:str):
pyABackend = pyaudio.PyAudio()
chosenDeviceID = int(deviceName[deviceName.rfind(" - ") + 3:])
chosenDeviceInfo = pyABackend.get_device_info_by_index(chosenDeviceID)
return chosenDeviceInfo
def setup_style(app, backgroundColor, buttonBackground, foregroundColor):
app.option_add('*TCombobox*Listbox.foreground', foregroundColor)
app.option_add('*TCombobox*Listbox.background', buttonBackground)
style = ttk.Style()
style.theme_use('clam')
style.configure('.', background=backgroundColor, foreground=foregroundColor)
style.configure('TLabel', background=backgroundColor, foreground=foregroundColor)
style.configure('TFrame', background=backgroundColor)
style.configure('TCheckbutton', background=backgroundColor, foreground=foregroundColor, fieldbackground=backgroundColor)
style.configure('TCombobox', selectbackground=backgroundColor, fieldbackground=backgroundColor, background=backgroundColor)
style.configure('TButton', background=buttonBackground, foreground=foregroundColor, bordercolor=buttonBackground)
style.configure('TEntry', fieldbackground=backgroundColor, foreground=foregroundColor, insertcolor=foregroundColor, insertwidth=2)
style.map('TCombobox',
fieldbackground=[('readonly', backgroundColor)],
selectbackground=[('readonly', backgroundColor)],
foreground=[('readonly', foregroundColor)]) # Set a lighter shade of gray for lines
style.map('TCheckbutton',
background=[('active', buttonBackground)], # Custom background color on hover
foreground=[('active', foregroundColor)]) # Custom foreground (text) color on hover
def ask_fetch_from_and_update_config(inputDict:dict, configData:dict, title:str):
"""
Given a correctly structured inputDict, it generates a GUI (or a CLI) to ask that information from the user.
If the configData contains values corresponding to the keys for various GUI elements, it pulls those values to display as default.
It will then save the user's new values back to the config file, and update it.
NOTE: For textbox items marked as "hidden", this DOES NOT HAPPEN. The values are instead written to and read from the system keyring.
"""
for key, value in inputDict.items():
if "hidden" in value and value["hidden"]:
storedValue = keyring.get_password("speech2speech",key)
if storedValue is not None:
value["default_value"] = storedValue
else:
if key in configData and configData[key] != "":
value["default_value"] = configData[key]
if useGUI:
userInputs = _ask_ui(inputDict, title)
else:
userInputs = _ask_cli(inputDict, title)
for key, value in userInputs.items():
if "hidden" in inputDict[key] and inputDict[key]["hidden"]:
keyring.set_password("speech2speech", key, value)
else:
configData[key] = value
update_config_file()
return userInputs
def show_text(message):
if useGUI:
app = tk.Tk()
app.attributes('-alpha', 0)
setup_style(app, backgroundColor, buttonBackground, foregroundColor)
show_custom_messagebox(app, "Info", message)
app.destroy()
else:
input(message)
def show_custom_messagebox(app, title, message):
messagebox_window = tk.Toplevel(app)
messagebox_window.title(title)
messagebox_window.configure(bg='#2b2b2b') # Set the background color to match the dark theme
messagebox_window.highlightthickness = 0 # Remove the default padding
message_label = ttk.Label(messagebox_window, text=message, padding=(20, 20))
message_label.grid(row=0, column=0, columnspan=2)
ok_button = ttk.Button(messagebox_window, text="OK", width=10, command=messagebox_window.destroy)
ok_button.grid(row=1, column=0, columnspan=2, pady=(0, 20))
messagebox_window.transient(app)
messagebox_window.grab_set()
app.wait_window(messagebox_window)
def _ask_ui(config, title="Settings"):
def on_confirm():
result = {}
for key, value in config.items():
if value["widget_type"] == "list":
result[key] = value["var"].get()
elif value["widget_type"] == "checkbox":
result[key] = value["var"].get()
elif value["widget_type"] == "textbox":
if "value_type" in value:
try:
rawValue = value["entry"].get()
if value["value_type"] == "int" or value["value_type"] == "float":
if value["value_type"] == "int":
result[key] = int(rawValue)
elif value["value_type"] == "float":
result[key] = float(rawValue)
if "max_value" in value:
if not result[key] <= value["max_value"]:
raise ValueError()
if "min_value" in value:
if not result[key] >= value["min_value"]:
raise ValueError()
else:
raise NotImplementedError("ERROR! TYPE CHECKING FOR "+value["value_type"]+" NOT IMPLEMENTED!")
except ValueError as e:
show_custom_messagebox(app, "Error!","Could not convert input " + key + " to " + value["value_type"] + ", please double check that your input is formatted correctly!")
raise e
else:
result[key] = value["entry"].get()
app.destroy()
return result
def on_combobox_selection_changed(event, combobox_key):
selected_index = config[combobox_key]["combobox"].current()
if "descriptions" in config[combobox_key]:
config[combobox_key]["description_text"].config(state=tk.NORMAL)
config[combobox_key]["description_text"].delete(1.0, tk.END)
if len(config[combobox_key]["descriptions"]) == 1:
#If there's only one description, use the same one for all options.
config[combobox_key]["description_text"].insert(tk.END, config[combobox_key]["descriptions"][0])
else:
config[combobox_key]["description_text"].insert(tk.END, config[combobox_key]["descriptions"][selected_index])
config[combobox_key]["description_text"].config(state=tk.DISABLED)
def on_checkbox_clicked(checkbox_key):
currValue = config[checkbox_key]["var"].get()
if currValue:
show_custom_messagebox(app, "Info", config[checkbox_key]["description"])
app = tk.Tk()
app.title(title)
setup_style(app, backgroundColor, buttonBackground, foregroundColor)
# (Place the dark theme configuration code here)
frame = ttk.Frame(app, padding="10")
frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
row = 0
for key, value in config.items():
if value["widget_type"] == "list":
label = ttk.Label(frame, text=value["label"])
label.grid(row=row, column=0, sticky=tk.W)
value["var"] = tk.StringVar()
combobox = ttk.Combobox(frame, width=60, textvariable=value["var"], values=value["options"], state="readonly")
if "default_value" in value:
try:
default_index = value["options"].index(value["default_value"])
except ValueError:
default_index = 0
else:
default_index = 0
combobox.current(default_index)
combobox.grid(row=row, column=1, sticky=(tk.W, tk.E))
value["combobox"] = combobox
combobox.bind("<<ComboboxSelected>>", lambda event, k=key: on_combobox_selection_changed(event, k))
if "descriptions" in value:
description_text = tk.Text(frame, height=15, width=60, wrap=tk.WORD, background='#2b2b2b', foreground='white')
description_text.grid(row=row + 1, column=1, sticky=(tk.W, tk.E))
if len(value["descriptions"]) == 1:
# If there's only one description, use the same one for all options.
description_text.insert(tk.END, value["descriptions"][0])
else:
description_text.insert(tk.END, value["descriptions"][default_index])
description_text.config(state=tk.DISABLED)
value["description_text"] = description_text
row += 1
elif value["widget_type"] == "checkbox":
value["var"] = tk.BooleanVar()
checkbutton = ttk.Checkbutton(frame, text=value["label"], variable=value["var"])
checkbutton.grid(row=row, columnspan=2, sticky=tk.W)
if "default_value" in value:
value["var"].set(value["default_value"])
if "description" in value:
value["var"].trace("w", lambda *args, k=key: on_checkbox_clicked(k))
elif value["widget_type"] == "textbox":
label = ttk.Label(frame, text=value["label"])
label.grid(row=row, column=0, sticky=tk.W)
value["entry"] = ttk.Entry(frame, width=40)
if "hidden" in value and value["hidden"]:
value["entry"].config(show="*")
value["entry"].grid(row=row, column=1, sticky=(tk.W, tk.E))
if "default_value" in value:
value["entry"].insert(0, value["default_value"])
row += 1
confirm_button = ttk.Button(frame, text="Confirm", command=app.quit)
confirm_button.grid(row=row, columnspan=2, pady=10)
app.mainloop()
while True:
try:
returnValue = on_confirm()
break
except ValueError:
app.mainloop()
return returnValue
def _ask_cli(innerConfig,title="Settings"):
innerResult = {}
print(title)
for key, value in innerConfig.items():
print("\n")
if "default_value" in value:
print(f"Default value for {value['label']}: {value['default_value']}")
use_default = choose_yes_no("Use default value?")
if use_default:
innerResult[key] = value["default_value"]
continue
if value["widget_type"] == "list":
options = value["options"]
if "descriptions" in value and len(value["descriptions"]) > 1:
options = [f"{option} - {desc}" for option, desc in zip(value["options"], value["descriptions"])]
choiceDescAndName = choose_from_list_of_strings(value["label"], options)
innerResult[key] = choiceDescAndName[:choiceDescAndName.index(" - ")]
else:
if "descriptions" in value:
print(value["descriptions"][0])
innerResult[key] = choose_from_list_of_strings(value["label"], options)
elif value["widget_type"] == "checkbox":
innerResult[key] = choose_yes_no(value["label"])
elif value["widget_type"] == "textbox":
if "value_type" in value:
if value["value_type"] == "int":
choose_float(value["label"], minValue=value["min_value"], maxValue=value["max_value"])
elif value["value_type"] == "float":
choose_int(value["label"], minValue=value["min_value"], maxValue=value["max_value"])
else:
raise NotImplementedError("Type checking for this type is not implemented")
else:
innerResult[key] = input(f"{value['label']}: ")
return innerResult
def download_file_with_progress(url, save_path):
response = requests.get(url, stream=True)
total_size = int(response.headers.get('content-length', 0))
chunk_size = 1024
with open(save_path, 'wb') as file:
for data in tqdm(response.iter_content(chunk_size), total=total_size // chunk_size, unit='KB'):
file.write(data)