-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy path__init__.py
1408 lines (1082 loc) · 53.7 KB
/
__init__.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 server
import folder_paths
from aiohttp import web
import os
import json
from pathlib import Path
import base64
import shutil
import zipfile
from io import BytesIO
import io
import asyncio
import subprocess
import requests
from urllib.parse import urlencode
import importlib.util
import sys
from packaging import version
def check_and_install(package, import_name="", desired_version=None,reboot=False):
if import_name == "":
import_name = package
try:
library_module = importlib.import_module(import_name)
current_version = getattr(library_module, '__version__', None)
if current_version :
if current_version:
print(f"Current version of {import_name}: {current_version}")
if desired_version:
if version.parse(current_version) < version.parse(desired_version):
print(f"Updating {import_name} to version {desired_version}...")
install_package(f"{package}=={desired_version}")
print(f"{import_name} updated successfully to version {desired_version}")
#else:
# print(f"{import_name} is already up-to-date with version {current_version}")
else:
print(f"Version of {import_name}: Not found")
except ImportError:
print(f"Installing {import_name}...")
install_package(package)
def install_package(package):
subprocess.check_call([sys.executable, "-m", "pip", "install", "--no-cache-dir", package])
check_and_install('aiofiles')
class JSONConfigManager:
def __init__(self, file_name):
self.file_name = file_name
self.initial_config = """
{"menuctx_category": "Context Menu",
"menuctx_options": [],
"menuctx_subOptions": [],
"menuctx_opt_callback": [],
"menuctx_sub_opt_callback": [],
"sb_wf_path": ""
}"""
if os.path.isfile(file_name):
self.data = self.read_json_file()
else:
self.data = json.loads(self.initial_config)
self.write_json_file()
def get_internal_settings(self):
try:
internal_settings = {
"current_path": os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))),
}
return internal_settings
except FileNotFoundError:
return {}
def read_json_file(self):
try:
with open(self.file_name, 'r') as file:
return json.load(file)
except FileNotFoundError:
return {}
def write_json_file(self):
with open(self.file_name, 'w') as file:
json.dump(self.data, file, indent=4)
def read_item(self, parameter_name):
return self.data.get(parameter_name)
def update_item(self, parameter_name, new_value):
self.data[parameter_name] = new_value
self.write_json_file()
def delete_item(self, parameter_name):
if parameter_name in self.data:
del self.data[parameter_name]
self.write_json_file()
def add_item(self, parameter_name, value):
self.data[parameter_name] = value
self.write_json_file()
def generate_id(file_path):
encoded_bytes = base64.b64encode(file_path.encode('utf-8'))
encoded_str = str(encoded_bytes, 'utf-8')
return encoded_str
"""
def scan_directory(directory, workflows_dict, existing_names, main_path = ''):
for entry in os.scandir(directory):
if entry.is_file() and entry.name.endswith('.json'):
base_name = entry.name[:-5] # Remove the '.json' extension
#unique_name = base_name
#if unique_name in workflows_dict:
# folder_name = os.path.basename(directory)
# unique_name = f"{base_name} (from {folder_name})"
subfolder = entry.path.replace(main_path, '').replace(entry.name, '')
workflows_dict[base_name] = {"name": base_name,"path": entry.path, "subfolder": subfolder}
existing_names.add(base_name)
elif entry.is_dir():
scan_directory(entry.path, workflows_dict, existing_names,main_path)
"""
def scan_directory(directory, workflows_dict, existing_names, main_path=''):
for entry in os.scandir(directory):
if entry.is_file() and entry.name.endswith('.json'):
base_name = entry.name[:-5] # Remove the '.json' extension
subfolder = entry.path.replace(main_path, '').replace(entry.name, '')
unique_id = generate_id(entry.path)
workflows_dict[unique_id] = {
"name": base_name,
"path": entry.path,
"subfolder": subfolder
}
existing_names.add(base_name)
elif entry.is_dir():
scan_directory(entry.path, workflows_dict, existing_names, main_path)
def check_model_existence(metadata_path, config_manager, id_model=None):
metadata_current_path = os.path.join(metadata_path, "models")
if not os.path.exists(metadata_current_path):
#create directory
os.makedirs(metadata_current_path)
models_report = []
# Scansione del primo livello della directory
for model_dir in os.listdir(metadata_current_path):
model_path = os.path.join(metadata_current_path, model_dir)
if id_model and id_model != model_dir:
continue
if os.path.isdir(model_path):
# Cerca i file JSON e immagine all'interno della directory del modello
json_file = None
image_file = None
for file_name in os.listdir(model_path):
if file_name.endswith('.json'):
json_file = os.path.join(model_path, file_name)
elif file_name.endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
image_file = os.path.join(model_path, file_name)
if json_file:
try:
# Leggi il contenuto del file JSON
with open(json_file, 'r') as f:
model_data = json.load(f)
model_type = model_data.get('model_type').lower()
model_name = model_data.get('name')
expected_size = model_data.get('size')
model_hash = model_data.get('hash')
model_file_name = model_data.get('model_file_name')
# Recupera il percorso corretto dal config manager
config_key = f"sb_w_{model_type}"
model_base_path = config_manager.read_item(config_key)
if model_base_path:
full_model_path = os.path.join(model_base_path, model_file_name)
model_info = {
"id": model_data.get('id'),
"name": model_name,
"size": expected_size,
"author": model_data.get('author'),
"url": model_data.get('url'),
"image_type": model_data.get('image_type'),
"image_name": model_data.get('image_name'),
"model_type": model_type,
"model_file_name": model_file_name,
"hash": model_hash,
"base_model" : model_data.get('base_model'),
"full_model_path": full_model_path,
"nsfw": model_data.get('nsfw'),
"status": ""
}
# Verifica se il modello esiste e confronta la dimensione del file
if os.path.isfile(full_model_path):
actual_size = os.path.getsize(full_model_path)
#get last edit date
last_edit = os.path.getctime(json_file)
model_info['last_edit'] = last_edit
# Confronto delle dimensioni
if actual_size == expected_size:
model_info['status'] = "valid"
else:
model_info['status'] = f"size_mismatch (expected: {expected_size} bytes, found: {actual_size} bytes)"
else:
model_info['status'] = "missing"
else:
model_info = {
"name": model_name,
"status": f"model_type_path_missing for {model_type}"
}
# Aggiungi il report del modello
models_report.append(model_info)
except Exception as e:
print(f"Error processing file '{json_file}': {e}")
model_info['status'] = "error"
continue
return models_report
# If is different from ComfyUISidebar, change it
if __package__ != "ComfyUI-N-Sidebar":
RED = "\033[31m"
END = '\33[0m'
print(f"{RED}!!!{END}")
print(f"{RED}!!!{END}")
print(f"{RED}WARNING:'{__package__}' folder name is WRONG!!! Please rename it 'ComfyUI-N-Sidebar'.{END}")
print(f"{RED}!!!{END}")
print(f"{RED}!!!{END}")
else:
print("ComfyUI-N-Sidebar is loading...")
file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"app","settings.json")
views_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"app","views","views.json")
views_backup_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"app","views","views_backup.json")
views_default_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"app","views","views_default.json")
metadata_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"metadata")
config_manager = JSONConfigManager(file_path)
NODE_CLASS_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS = {}
default_path = os.path.join(folder_paths.base_path, "workflows")
try:
list_workflows_dirs = config_manager.read_item("sb_wf_path").replace("\n\r", "\n").split('\n')
except:
print("No 'sb_wf_path' in settings.json. Using default path.")
list_workflows_dirs = []
workflow_dirs = []
for list_workflows in list_workflows_dirs:
if os.path.isdir(list_workflows.strip()):
workflow_dirs.append(list_workflows.strip())
if os.path.isdir(default_path):
workflow_dirs.insert(0, default_path)
list_panels = os.path.join(os.path.dirname(os.path.realpath(__file__)),"app","panels")
list_workflows_array = []
list_panels_array = []
#list folders
folders = os.listdir(list_panels)
for folder in folders:
if os.path.isdir(os.path.join(list_panels, folder)):
list_panels_array.append(folder)
@server.PromptServer.instance.routes.get("/sidebar/backup" )
async def s_get(request):
backup_path = file_path + ".bak"
try:
# Crea una copia di settings.json come settings.json.bak
shutil.copyfile(file_path, backup_path)
except Exception as e:
result = {"result": "ERROR", "message": str(e)}
return web.json_response(result, content_type='application/json')
result = {"result": "OK"}
return web.json_response(result, content_type='application/json')
@server.PromptServer.instance.routes.get("/sidebar/workflows" )
async def s_get(request):
workflows_dict = {}
existing_names = set()
for list_workflows in workflow_dirs:
scan_directory(list_workflows, workflows_dict, existing_names, list_workflows)
sorted_workflows_dict = dict(sorted(workflows_dict.items(), key=lambda x: x[1]["name"].lower()))
return web.json_response(sorted_workflows_dict, content_type='application/json')
@server.PromptServer.instance.routes.post("/sidebar/workflow")
async def s_get(request):
data = await request.json()
action = data["action"]
if action == "delete":
path = Path(data["path"])
os.remove(path)
result = {"result": "OK"}
return web.json_response(result, content_type='application/json')
elif action == "rename":
path = Path(data["path"])
newName = data["newName"]
if not path.exists():
raise FileNotFoundError(f"The system cannot find the path specified: {path}")
new_path = path.with_name(newName).with_suffix('.json')
if new_path.exists():
result = {"result": "File already exists!"}
else:
#rename
os.rename(path, new_path)
result = {"result": "OK"}
return web.json_response(result, content_type='application/json')
else:
file = data["path"]
# if file exists
if os.path.isfile(file):
return web.FileResponse(file)
else:
return web.Response(status=403)
@server.PromptServer.instance.routes.get("/sidebar/panels" )
async def s_get(request):
result = {"panels": list_panels_array}
return web.json_response(result, content_type='application/json')
@server.PromptServer.instance.routes.post("/sidebar/settings" )
async def s_get(request):
data = await request.json()
action = data["action"]
if action == "add":
parameter = data["parameter"]
value = data["value"]
config_manager.add_item(parameter, value)
result = {"result": "OK"}
return web.json_response(result, content_type='application/json')
elif action == "update":
parameter = data["parameter"]
value = data["value"]
config_manager.update_item(parameter, value)
result = {"result": "OK"}
return web.json_response(result, content_type='application/json')
elif action == "delete":
parameter = data["parameter"]
config_manager.delete_item(parameter)
result = {"result": "OK"}
return web.json_response(result, content_type='application/json')
elif action == "read":
parameter = data["parameter"]
read_language = config_manager.read_item(parameter)
result = {"value": read_language}
return web.json_response(result, content_type='application/json')
elif action == "factory_reset":
config_manager.data = json.loads(config_manager.initial_config)
config_manager.write_json_file()
result = {"result": "OK"}
return web.json_response(result, content_type='application/json')
else:
result = {"result": "ERROR"}
return web.json_response(result, content_type='application/json')
@server.PromptServer.instance.routes.get("/sidebar/internal_settings" )
async def s_get(request):
get_internal_settings = config_manager.get_internal_settings()
return web.json_response(get_internal_settings, content_type='application/json')
# Endpoint export config
@server.PromptServer.instance.routes.post('/sidebar/export')
async def export_config(request):
data = await request.json()
selected_items = data['selected_items']
export_data = {}
all_keys = set(config_manager.data.keys())
keys_to_exclude = set( ['sb_pinnedItems', 'sb_categoryNodeMap','sb_ColorCustomCategories', 'sb_workflowNodeMap','sb_ColorCustomWorkflows', 'sb_templateNodeMap','sb_ColorCustomTemplates'] )
for item in selected_items:
if item == '':
continue
elif '|' in item:
keys = item.split('|')
for key in keys:
export_data[key] = config_manager.read_item(key)
keys_to_exclude.add(key)
else:
export_data[item] = config_manager.read_item(item)
keys_to_exclude.add(item)
if '' in selected_items:
remaining_keys = all_keys - keys_to_exclude
for key in remaining_keys:
export_data[key] = config_manager.read_item(key)
json_data = json.dumps(export_data, indent=4)
zip_buffer = BytesIO()
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
if "model_templates" in selected_items:
zip_path = export_model_templates()
zip_file.write(zip_path, 'model_templates.zip')
zip_file.writestr('config_export.json', json_data)
zip_buffer.seek(0)
return web.Response(body=zip_buffer.read(), headers={
'Content-Disposition': 'attachment; filename="config_export.zip"',
'Content-Type': 'application/zip'
})
@server.PromptServer.instance.routes.post('/sidebar/import')
async def import_config(request):
# Crea un lettore di multipart per leggere file e altri dati
reader = await request.multipart()
metadata_current_path = os.path.join(metadata_path, "models")
if not os.path.exists(metadata_current_path):
os.makedirs(metadata_current_path)
# Dati per salvare l'importazione
selected_items = []
config_data = None
# Itera sulle parti della richiesta multipart
while True:
part = await reader.next()
if part is None:
break
if part.name == 'file':
# Carica il file inviato (può essere JSON o ZIP)
filename = part.filename
file_data = await part.read()
# Verifica se è un file zip
if zipfile.is_zipfile(io.BytesIO(file_data)):
# Estrai i file dallo zip
with zipfile.ZipFile(io.BytesIO(file_data)) as zip_file:
for file_name in zip_file.namelist():
with zip_file.open(file_name) as f:
if file_name == 'config_export.json':
config_data = json.load(f)
elif file_name == 'model_templates.zip':
with zipfile.ZipFile(io.BytesIO(f.read())) as model_zip:
model_zip.extractall(metadata_current_path)
else:
config_data = json.loads(file_data)
elif part.name == 'selected_items':
# Leggi i dati selezionati come JSON
selected_items = json.loads(await part.text())
# Ora `config_data` contiene il JSON importato dal file (sia ZIP che JSON singolo)
# e `selected_items` contiene le chiavi da importare
if config_data:
for item in selected_items:
if item:
# Separa le chiavi multiple
keys = item.split('|')
for key in keys:
if key in config_data:
config_manager.update_item(key, config_data[key])
else:
# Importa tutti i dati tranne quelli specifici
for key, value in config_data.items():
if key not in ['sb_pinnedItems', 'sb_categoryNodeMap', 'sb_workflowNodeMap', 'sb_templateNodeMap', 'sb_ColorCustomCategories', 'sb_ColorCustomWorkflows', 'sb_ColorCustomTemplates']:
config_manager.update_item(key, value)
return web.json_response({'status': 'success'})
@server.PromptServer.instance.routes.post("/sidebar/restorelayout")
async def restore_layout(request):
try:
# Check if the backup file exists
if not Path(views_default_path).exists():
result = {"result": "Error", "message": "Backup file not found."}
return web.json_response(result, content_type='application/json', status=404)
# Restore views.json from the backup
with open(Path(views_default_path), 'r', encoding='utf-8') as f:
backup_data = json.load(f)
# Write the backup data to views.json
with open(Path(views_path), 'w', encoding='utf-8') as f:
json.dump(backup_data, f, ensure_ascii=False, indent=4)
# Respond with success
result = {"result": "OK", "message": "Layout successfully restored."}
return web.json_response(result, content_type='application/json')
except Exception as e:
# Error handling
print(f"Error restoring layout: {e}")
result = {"result": "Error", "message": str(e)}
return web.json_response(result, content_type='application/json', status=500)
@server.PromptServer.instance.routes.post("/sidebar/savelayout")
async def save_layout(request):
try:
# Otteniamo i dati JSON dalla richiesta POST
data = await request.json()
# If views.json exists, create a backup
if Path(views_path).exists():
os.replace(Path(views_path), Path(views_backup_path))
# Save the new layout to views.json
with open(Path(views_path), 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
# Success response
result = {"result": "OK", "message": "Layout saved successfully."}
return web.json_response(result, content_type='application/json')
except Exception as e:
# Error handling
print(f"Error saving layout: {e}")
result = {"result": "Error", "message": str(e)}
return web.json_response(result, content_type='application/json', status=500)
@server.PromptServer.instance.routes.get("/sidebar/views")
async def s_get(request):
# if file exists
if os.path.isfile(views_path):
return web.FileResponse(views_path)
else:
return web.Response(status=403)
@server.PromptServer.instance.routes.get("/sidebar/panels")
async def s_get_panels(request):
# Definisce il percorso della directory "panels"
panels_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "app", "panels")
# Verifica se la directory esiste
if os.path.isdir(panels_path):
# Crea una lista con i nomi delle cartelle nella directory "panels"
folder_names = [folder for folder in os.listdir(panels_path) if os.path.isdir(os.path.join(panels_path, folder))]
# Restituisce la lista di nomi di cartelle in formato JSON
return web.json_response(folder_names)
else:
# Se la directory non esiste, restituisce un errore 403
return web.Response(status=403)
@server.PromptServer.instance.routes.post("/sidebar/execute")
async def execute(request):
try:
data = await request.json()
command = data.get('command', '')
# Esegui il comando
process = await asyncio.create_subprocess_shell(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout, stderr = await process.communicate()
# Ritorna l'output del comando
output = stdout.decode() + stderr.decode()
return web.json_response({'output': output})
except Exception as e:
return web.json_response({'output': str(e)}, status=500)
async def fetch_data(request):
api_url = "https://civitai.com/api/v1/models"
params = request.rel_url.query
response = requests.get(api_url, params=params)
data = response.text
return web.Response(text=data, content_type='application/json')
@server.PromptServer.instance.routes.get("/sidebar/proxy/models")
async def proxy_models(request):
try:
params = request.query
api_url = "https://civitai.com/api/v1/models"
headers = {
"Content-Type": "application/json"
}
full_url = f"{api_url}?{urlencode(params)}"
async with aiohttp.ClientSession() as session:
async with session.get(full_url, headers=headers) as response:
response_data = await response.json()
for item in response_data.get("items", []):
json_data = check_model_existence(metadata_path, config_manager, str(item["id"]))
if len(json_data) > 0:
item["nsbStatus"] = json_data[0].get("status")
return web.json_response(response_data)
except Exception as e:
return web.json_response({'error': str(e)}, status=500)
def export_model_templates():
metadata_current_path = os.path.join(metadata_path, "models")
zip_name = "model_templates.zip"
zip_path = os.path.join(metadata_path, zip_name)
if os.path.exists(zip_path):
os.remove(zip_path)
shutil.make_archive(os.path.join(metadata_path, zip_name.replace('.zip', '')), 'zip', metadata_current_path)
return zip_path
def createJSONInfo(metadata_current_path, data,total_size,image_name):
if not os.path.exists(os.path.join(metadata_current_path, f"{data['id']}.json")):
info_path = os.path.join(metadata_current_path, f"{data['id']}.json")
#remove from url ?token=...
data['url'] = data['url'].split('?token=')[0]
info = {
"id": data['id'],
"name": data['name'],
"size": total_size,
"author": data['author'],
"url": data['url'],
"image_type": data['image_type'],
"image_name": image_name,
"model_type": data['model_type'],
"model_file_name" : data['model_file_name'],
"base_model": data['base_model'],
"nsfw": data['nsfw'],
"hash": data['hash']
}
with open(info_path, 'w') as f:
json.dump(info, f)
import aiohttp
import aiofiles
import traceback
download_progress = {}
download_tasks = {}
downloads = {}
@server.PromptServer.instance.routes.post('/sidebar/download')
async def download_model(request):
try:
data = await request.json()
id_download = data['id']
name = data['name']
model_url = data['url']
save_path = data['path']
image_url = data['image_url']
image_type = data['image_type']
nsfw = data['nsfw']
metadata_current_path = os.path.join(metadata_path,"models", str(id_download))
if not os.path.exists(metadata_current_path):
os.makedirs(metadata_current_path)
image_name = ''
# Scarica l'immagine o il video e salvalo
if image_url:
image_ext = os.path.splitext(image_url)[1]
if image_type == "image":
image_name = str(id_download) + image_ext
else:
image_name = str(id_download) + ".mp4"
image_path = os.path.join(metadata_current_path, image_name)
if not os.path.exists(image_path):
async with aiohttp.ClientSession() as session:
async with session.get(image_url) as image_response:
image_data = await image_response.read()
with open(image_path, 'wb') as f:
f.write(image_data)
# Verifica se il file finale esiste già
if os.path.exists(save_path) and os.path.getsize(save_path) > 200:
downloads[id_download] = {
"name": name,
"progress": 100,
"task": None,
"temp_save_path": None,
"file_size": None,
"downloaded_size": None,
"status": "finished",
"nsfw": nsfw
}
headers = {
'Range': f'bytes=0-'
}
#only for check size
async with aiohttp.ClientSession() as session:
async with session.get(model_url, headers=headers) as response:
total_size = int(response.headers.get('content-length', 0))
createJSONInfo(metadata_current_path, data,total_size,image_name)
return web.Response(text=json.dumps({'status': 'already_exists'}), content_type='application/json')
# Percorso del file temporaneo con estensione .part
temp_save_path = save_path + '.part'
# Inizializza il progresso
if os.path.exists(temp_save_path):
# Se il file .part esiste, riprende dal punto interrotto
downloaded_size = os.path.getsize(temp_save_path)
else:
# Se non esiste, inizia da zero
downloaded_size = 0
headers = {
'Range': f'bytes={downloaded_size}-'
}
# Definizione della coroutine del download
async def download_coroutine(downloaded_size):
try:
async with aiohttp.ClientSession() as session:
async with session.get(model_url, headers=headers) as response:
total_size = int(response.headers.get('content-length', 0)) + downloaded_size
# Gestione della cartella dei metadati e del file immagine
createJSONInfo(metadata_current_path, data,total_size,image_name)
downloads[id_download]['name'] = name
# Imposta la progressione del download
downloads[id_download]['file_size'] = total_size
downloads[id_download]['downloaded_size'] = downloaded_size
downloads[id_download]['progress'] = (downloaded_size / total_size) * 100
if total_size < 200:
downloads[id_download]['status'] = "api_error"
raise Exception("Probably API error")
# Effettua il download del contenuto e aggiorna il progresso
async with aiofiles.open(temp_save_path, 'ab') as f:
while True:
chunk = await response.content.read(1024)
if not chunk:
break
downloaded_size += len(chunk)
downloads[id_download]['downloaded_size'] = downloaded_size
downloads[id_download]['progress'] = (downloaded_size / total_size) * 100
downloads[id_download]['status'] = "running"
await f.write(chunk)
# Download completato, rinomina il file .part al nome finale
downloads[id_download]['progress'] = 100 # Completo
if (downloaded_size / total_size) * 100 == 100:
try:
# change name only if download is complete
file_path = data['path']
os.rename(temp_save_path, file_path)
# if is a zip file, unzip it and delete it
if file_path.endswith('.zip'):
saveInSubfolder = config_manager.read_item('sb_save_in_subfolder')
if saveInSubfolder == True:
save_path_zip = file_path.replace('.zip', '')
if not os.path.exists(os.path.dirname(save_path_zip)):
os.makedirs(save_path_zip)
shutil.unpack_archive(file_path, save_path_zip)
else:
shutil.unpack_archive(file_path, os.path.dirname(file_path))
os.remove(file_path)
except Exception as e:
print(e)
traceback.print_exc()
downloads[id_download]['status'] = "completed"
return web.Response(text=json.dumps({'status': 'success'}), content_type='application/json')
except Exception as e:
if downloads[id_download]['status'] != "api_error":
downloads[id_download]['status'] = "error"
return web.json_response({'error': str(e)}, status=500)
# Avvia il download e memorizza il task e il percorso temporaneo nel dizionario downloads
task = server.PromptServer.instance.loop.create_task(download_coroutine(downloaded_size))
downloads[id_download] = {
"task": task,
"progress": 0,
"temp_save_path": temp_save_path
}
return web.Response(text=json.dumps({'status': 'downloading'}), content_type='application/json')
except Exception as e:
return web.json_response({'error': str(e)}, status=500)
@server.PromptServer.instance.routes.post('/sidebar/pause')
async def pause_download(request):
try:
data = await request.json()
id_download = data['id']
download_info = downloads.get(id_download)
if download_info:
task = download_info['task']
# Cancella il task del download
if task:
task.cancel()
# Aggiorna lo stato del progresso al 50% o a un altro stato indicativo di pausa, se necessario
downloads[id_download]['progress'] = downloads[id_download].get('progress', 0)
downloads[id_download]['status'] = 'paused'
return web.Response(text=json.dumps({'status': 'paused'}), content_type='application/json')
else:
return web.json_response({'error': 'Download not found'}, status=404)
except Exception as e:
return web.json_response({'error': str(e)}, status=500)
@server.PromptServer.instance.routes.post('/sidebar/cancel')
async def cancel_download(request):
try:
data = await request.json()
id_download = data['id']
download_info = downloads.get(id_download)
if download_info:
task = download_info['task']
temp_save_path = download_info['temp_save_path']
# Cancella il task del download
if task:
task.cancel()
# Rimuove il file .part se esiste
if temp_save_path and os.path.exists(temp_save_path):
os.remove(temp_save_path)
# Rimuove il download dal dizionario
downloads.pop(id_download, None)
return web.Response(text=json.dumps({'status': 'canceled'}), content_type='application/json')
else:
return web.json_response({'error': 'Download not found'}, status=404)
except Exception as e:
return web.json_response({'error': str(e)}, status=500)
@server.PromptServer.instance.routes.get('/sidebar/download/progress')
async def get_progress(request):
id_download = request.query.get('id')
# Se viene passato un ID specifico
if id_download:
download_info = downloads.get(id_download)
if download_info:
# Restituisci tutte le informazioni del download per l'ID specifico
return web.json_response({
'id': id_download,
'progress': download_info.get('progress', 0),
'temp_save_path': download_info.get('temp_save_path'),
'task_status': download_info.get('status'),
'file_size': download_info.get('file_size', 'Unknown'),
'downloaded_size': download_info.get('downloaded_size', 0)
})
else:
return web.json_response({'error': 'Download not found'}, status=404)
# Se non viene passato un ID, restituisci tutte le informazioni per tutti i download attivi
all_progress = [
{
'id': key,
'progress': value.get('progress', 0),
'temp_save_path': value.get('temp_save_path'),
'task_status': value.get('status'),
'file_size': value.get('file_size', 'Unknown'),
'downloaded_size': value.get('downloaded_size', 0)
}
for key, value in downloads.items()
]
return web.json_response({'progress_list': all_progress})
################################################################################################################
@server.PromptServer.instance.routes.get('/sidebar/ws/progress')
async def websocket_handler(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
try:
while True:
# Controlla se la connessione è ancora aperta
if ws.closed:
print("Client disconnected.")
break
# Costruisci la lista di progressi da inviare al client
all_progress = [
{
'id': key,
'name': value.get('name'),
'progress': value.get('progress', 0),
'temp_save_path': value.get('temp_save_path'),
'task_status': value.get('status'),
'file_size': value.get('file_size', 'Unknown'),
'downloaded_size': value.get('downloaded_size', 0)