forked from slahiri/ComfyUI-Workflow-Models-Downloader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
5553 lines (4617 loc) · 215 KB
/
Copy pathserver.py
File metadata and controls
5553 lines (4617 loc) · 215 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Server-side API endpoints for Workflow Models Downloader
"""
import os
import re
import glob
import json
import logging
import asyncio
import datetime
import requests
import threading
import time
import urllib.parse
import urllib.request
from pathlib import Path
from aiohttp import web
from logging.handlers import RotatingFileHandler
import folder_paths
from server import PromptServer
# Get routes from ComfyUI server
routes = PromptServer.instance.routes
# On Windows, folder_paths.get_filename_list returns backslash-separated paths
# (e.g. "Flux\model.safetensors") while workflow JSONs use forward slashes.
# Patch it once at load time so ComfyUI's combo validation matches saved workflows.
if os.name == 'nt':
_orig_get_filename_list = folder_paths.get_filename_list
def _normalized_get_filename_list(folder_name):
return [f.replace('\\', '/') for f in _orig_get_filename_list(folder_name)]
folder_paths.get_filename_list = _normalized_get_filename_list
# Extension path
EXTENSION_PATH = os.path.dirname(__file__)
# Setup file logging
LOG_FILE = os.path.join(EXTENSION_PATH, 'wmd.log')
_file_handler = None
def setup_file_logging():
"""Setup file logging for the extension"""
global _file_handler
try:
# Create a rotating file handler (max 5MB, keep 3 backups)
_file_handler = RotatingFileHandler(
LOG_FILE,
maxBytes=5*1024*1024,
backupCount=3,
encoding='utf-8'
)
_file_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter(
'%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
_file_handler.setFormatter(formatter)
# Add handler to the root logger
logging.getLogger().addHandler(_file_handler)
logging.info("[WMD] File logging initialized: " + LOG_FILE)
except Exception as e:
logging.error(f"[WMD] Failed to setup file logging: {e}")
# Initialize file logging
setup_file_logging()
# Settings file path
SETTINGS_FILE = os.path.join(EXTENSION_PATH, 'settings.json')
# Version info
PYPROJECT_FILE = os.path.join(EXTENSION_PATH, 'pyproject.toml')
GITHUB_REPO = "slahiri/ComfyUI-Workflow-Models-Downloader"
REGISTRY_URL = "https://registry.comfy.org/nodes/comfyui-workflow-models-downloader"
def get_installed_version():
"""Get installed version from pyproject.toml"""
try:
logging.debug(f"[WMD] Looking for pyproject.toml at: {PYPROJECT_FILE}")
if not os.path.exists(PYPROJECT_FILE):
logging.warning(f"[WMD] pyproject.toml not found at: {PYPROJECT_FILE}")
return "1.8.1" # Fallback to current version
with open(PYPROJECT_FILE, 'r', encoding='utf-8') as f:
content = f.read()
# Simple regex to extract version
match = re.search(r'version\s*=\s*"([^"]+)"', content)
if match:
version = match.group(1)
logging.debug(f"[WMD] Found version: {version}")
return version
else:
logging.warning(f"[WMD] Could not find version in pyproject.toml")
except Exception as e:
logging.error(f"[WMD] Could not read version from pyproject.toml: {e}")
return "1.8.1" # Fallback to current version
def get_latest_version():
"""Get latest version from GitHub releases API"""
try:
url = f"https://api.github.com/repos/{GITHUB_REPO}/releases/latest"
response = requests.get(url, timeout=5)
if response.status_code == 200:
data = response.json()
tag = data.get('tag_name', '')
# Remove 'v' prefix if present
return tag.lstrip('v')
except Exception as e:
logging.debug(f"[WMD] Could not fetch latest version from GitHub: {e}")
return None
def compare_versions(installed, latest):
"""Compare version strings. Returns True if update is available."""
if not latest or installed == "unknown":
return False
try:
installed_parts = [int(x) for x in installed.split('.')]
latest_parts = [int(x) for x in latest.split('.')]
# Pad with zeros for comparison
while len(installed_parts) < len(latest_parts):
installed_parts.append(0)
while len(latest_parts) < len(installed_parts):
latest_parts.append(0)
return latest_parts > installed_parts
except Exception:
return False
# Search metadata cache file
# DEPRECATED: search_cache.json - now using model_metadata.json as single source of truth
# SEARCH_CACHE_FILE = os.path.join(EXTENSION_PATH, 'search_cache.json')
# Download history file for persistent tracking
DOWNLOAD_HISTORY_FILE = os.path.join(EXTENSION_PATH, 'download_history.json')
# Tavily search cache file for persistent caching of advanced search results
TAVILY_CACHE_FILE = os.path.join(EXTENSION_PATH, 'tavily_cache.json')
# Download progress tracking
download_progress = {}
download_lock = threading.Lock()
cancelled_downloads = set() # Track cancelled download IDs
# Download history (persistent)
download_history = []
# Download queue system
download_queue = [] # Queued downloads waiting to start
download_queue_lock = threading.Lock()
max_parallel_downloads = 3 # Default, configurable via settings
active_download_count = 0
# Model aliases file
MODEL_ALIASES_FILE = os.path.join(EXTENSION_PATH, 'metadata', 'model-aliases.json')
# Settings cache
_settings_cache = None
# Fuzzy matching imports
from difflib import SequenceMatcher
import subprocess
import shutil
def load_settings():
"""Load settings from settings.json or ComfyUI's native settings"""
global _settings_cache
if _settings_cache is not None:
return _settings_cache
default_settings = {
'huggingface_token': '',
'civitai_api_key': '',
'tavily_api_key': '',
'enable_advanced_search': False,
'max_parallel_downloads': 3
}
# First try extension's own settings file
try:
if os.path.exists(SETTINGS_FILE):
with open(SETTINGS_FILE, 'r', encoding='utf-8') as f:
saved = json.load(f)
# Merge with defaults
_settings_cache = {**default_settings, **saved}
return _settings_cache
except Exception as e:
logging.error(f"[Workflow-Models-Downloader] Error loading settings: {e}")
# Fall back to ComfyUI's native settings
try:
comfy_settings_path = os.path.join(folder_paths.base_path, 'user', 'default', 'comfy.settings.json')
if os.path.exists(comfy_settings_path):
with open(comfy_settings_path, 'r', encoding='utf-8') as f:
comfy_settings = json.load(f)
# Map ComfyUI setting keys to our internal keys
_settings_cache = {
'huggingface_token': comfy_settings.get('WorkflowModelsDownloader.HuggingFaceToken', ''),
'civitai_api_key': comfy_settings.get('WorkflowModelsDownloader.CivitAIApiKey', ''),
'tavily_api_key': comfy_settings.get('WorkflowModelsDownloader.TavilyApiKey', ''),
'enable_advanced_search': comfy_settings.get('WorkflowModelsDownloader.EnableAdvancedSearch', False),
'max_parallel_downloads': comfy_settings.get('WorkflowModelsDownloader.MaxParallelDownloads', 3)
}
logging.info(f"[WMD] Loaded settings from ComfyUI native settings")
return _settings_cache
except Exception as e:
logging.error(f"[Workflow-Models-Downloader] Error loading ComfyUI settings: {e}")
_settings_cache = default_settings
return _settings_cache
def save_settings(settings):
"""Save settings to settings.json"""
global _settings_cache
try:
with open(SETTINGS_FILE, 'w', encoding='utf-8') as f:
json.dump(settings, f, indent=2)
_settings_cache = settings
logging.info("[Workflow-Models-Downloader] Settings saved")
return True
except Exception as e:
logging.error(f"[Workflow-Models-Downloader] Error saving settings: {e}")
return False
def load_download_history():
"""Load download history from file"""
global download_history
try:
if os.path.exists(DOWNLOAD_HISTORY_FILE):
with open(DOWNLOAD_HISTORY_FILE, 'r', encoding='utf-8') as f:
download_history = json.load(f)
logging.info(f"[WMD] Loaded {len(download_history)} download history entries")
return download_history
except Exception as e:
logging.error(f"[WMD] Error loading download history: {e}")
download_history = []
return download_history
def save_download_history():
"""Save download history to file"""
global download_history
try:
with open(DOWNLOAD_HISTORY_FILE, 'w', encoding='utf-8') as f:
json.dump(download_history, f, indent=2)
return True
except Exception as e:
logging.error(f"[WMD] Error saving download history: {e}")
return False
# Tavily search cache
_tavily_cache = {}
def load_tavily_cache():
"""Load Tavily search cache from file"""
global _tavily_cache
try:
if os.path.exists(TAVILY_CACHE_FILE):
with open(TAVILY_CACHE_FILE, 'r', encoding='utf-8') as f:
_tavily_cache = json.load(f)
logging.info(f"[WMD] Loaded Tavily cache with {len(_tavily_cache)} entries")
return _tavily_cache
except Exception as e:
logging.error(f"[WMD] Error loading Tavily cache: {e}")
_tavily_cache = {}
return _tavily_cache
def save_tavily_cache():
"""Save Tavily search cache to file"""
global _tavily_cache
try:
with open(TAVILY_CACHE_FILE, 'w', encoding='utf-8') as f:
json.dump(_tavily_cache, f, indent=2)
return True
except Exception as e:
logging.error(f"[WMD] Error saving Tavily cache: {e}")
return False
def get_tavily_cached_result(filename):
"""Get cached Tavily search result for a filename"""
global _tavily_cache
return _tavily_cache.get(filename)
def set_tavily_cached_result(filename, data):
"""Cache Tavily search result for a filename"""
global _tavily_cache
data['cached_at'] = datetime.datetime.now().isoformat()
_tavily_cache[filename] = data
save_tavily_cache()
def add_to_download_history(download_info):
"""Add a download entry to history"""
global download_history
# Create history entry
entry = {
'id': download_info.get('id', ''),
'filename': download_info.get('filename', ''),
'status': download_info.get('status', ''),
'error': download_info.get('error', ''),
'total_size': download_info.get('total_size', 0),
'timestamp': datetime.datetime.now().isoformat(),
'directory': download_info.get('directory', '')
}
# If download completed successfully, invalidate folder cache so the file is discoverable
if entry['status'] == 'completed' and entry['directory']:
# Extract folder type from directory path (e.g., "checkpoints" from "models/checkpoints")
folder_type = os.path.basename(entry['directory'].rstrip('/\\'))
if folder_type:
invalidate_folder_cache(folder_type)
logging.info(f"[WMD] Download complete, cache invalidated for: {folder_type}")
# Remove any existing entry with same filename to avoid duplicates
download_history = [h for h in download_history if h.get('filename') != entry['filename']]
# Add new entry at the beginning
download_history.insert(0, entry)
# Keep only last 100 entries
download_history = download_history[:100]
save_download_history()
def clear_download_history():
"""Clear all download history"""
global download_history
download_history = []
save_download_history()
def get_huggingface_token():
"""Get HuggingFace token from settings"""
settings = load_settings()
return settings.get('huggingface_token', '')
def get_civitai_api_key():
"""Get CivitAI API key from settings (force reload to get latest)"""
global _settings_cache
_settings_cache = None # Force reload to get latest settings
settings = load_settings()
key = settings.get('civitai_api_key', '')
if key:
logging.debug(f"[WMD] CivitAI API key found (length: {len(key)})")
else:
logging.warning("[WMD] CivitAI API key not configured")
return key
def parse_civitai_urn(urn_string):
"""
Parse CivitAI URN format: urn:air:other:unknown:civitai:MODEL_ID@VERSION_ID
Returns (model_id, version_id) tuple or (None, None) if not a valid URN
"""
if not urn_string or not urn_string.startswith('urn:'):
return None, None
# Pattern: urn:air:other:unknown:civitai:MODEL_ID@VERSION_ID
# Also support: urn:air:MODEL_TYPE:BASE_MODEL:civitai:MODEL_ID@VERSION_ID
urn_pattern = r'^urn:air:[^:]+:[^:]+:civitai:(\d+)@(\d+)$'
match = re.match(urn_pattern, urn_string)
if match:
return match.group(1), match.group(2)
return None, None
def civitai_urn_to_download_url(urn_string):
"""
Convert CivitAI URN to download URL
Returns download URL or None if not a valid URN
"""
model_id, version_id = parse_civitai_urn(urn_string)
if version_id:
return f"https://civitai.com/api/download/models/{version_id}"
return None
def is_civitai_urn(value):
"""Check if a value is a CivitAI URN"""
if not value or not isinstance(value, str):
return False
model_id, version_id = parse_civitai_urn(value)
return model_id is not None and version_id is not None
def get_tavily_api_key():
"""Get Tavily API key from settings"""
global _settings_cache
# Force reload settings to get latest key
_settings_cache = None
settings = load_settings()
key = settings.get('tavily_api_key', '')
logging.info(f"[WMD] Tavily key loaded: {'*' * (len(key) - 4) + key[-4:] if key else 'NOT SET'}")
return key
def is_advanced_search_enabled():
"""Check if advanced search is enabled"""
settings = load_settings()
return settings.get('enable_advanced_search', False) and bool(settings.get('tavily_api_key', ''))
# ============================================================================
# Metadata Cache Functions (redirect to model_metadata.json)
# ============================================================================
# These functions now use model_metadata.json as the single source of truth
def get_cached_metadata(filename):
"""Get cached metadata for a filename from model_metadata.json"""
# Import here to avoid circular dependency (load_model_metadata defined later)
metadata = _get_model_metadata_safe()
basename = os.path.basename(filename)
return metadata.get(filename) or metadata.get(basename)
def save_search_metadata(filename, metadata):
"""Save search metadata for a filename to model_metadata.json"""
basename = os.path.basename(filename)
metadata['cached_at'] = datetime.datetime.now().isoformat()
# Update model_metadata.json
all_metadata = _get_model_metadata_safe()
existing = all_metadata.get(basename, {})
# Merge new metadata (don't overwrite user_url)
for key, value in metadata.items():
if key == 'user_url' and existing.get('user_url'):
continue # Don't overwrite user-provided URL
if value is not None and value != '':
existing[key] = value
existing['filename'] = basename
all_metadata[basename] = existing
_save_model_metadata_safe(all_metadata)
def _get_model_metadata_safe():
"""Safe wrapper to get model metadata (handles import order)"""
global _model_metadata_cache
if _model_metadata_cache is not None:
return _model_metadata_cache
try:
model_metadata_file = os.path.join(os.path.dirname(__file__), "model_metadata.json")
if os.path.exists(model_metadata_file):
with open(model_metadata_file, 'r', encoding='utf-8') as f:
_model_metadata_cache = json.load(f)
return _model_metadata_cache
except Exception as e:
logging.error(f"[WMD] Error loading model metadata: {e}")
_model_metadata_cache = {}
return _model_metadata_cache
def _save_model_metadata_safe(metadata):
"""Safe wrapper to save model metadata"""
global _model_metadata_cache
try:
model_metadata_file = os.path.join(os.path.dirname(__file__), "model_metadata.json")
with open(model_metadata_file, 'w', encoding='utf-8') as f:
json.dump(metadata, f, indent=2)
_model_metadata_cache = metadata
return True
except Exception as e:
logging.error(f"[WMD] Error saving model metadata: {e}")
return False
# Global cache for model metadata (shared with functions defined later)
_model_metadata_cache = None
def _cache_download_url(filename, url, source, hf_repo=None, hf_path=None, model_name=None, civitai_url=None):
"""Cache URL after successful download for future use"""
try:
metadata = {
'url': url,
'source': f'download_{source}',
'hf_repo': hf_repo or '',
'hf_path': hf_path or '',
'model_name': model_name or '',
'civitai_url': civitai_url or '',
'cached_at': datetime.datetime.now().isoformat(),
'from_download': True
}
save_search_metadata(filename, metadata)
logging.info(f"[Workflow-Models-Downloader] Cached URL for: {filename}")
except Exception as e:
logging.error(f"[Workflow-Models-Downloader] Failed to cache URL: {e}")
logging.info("[Workflow-Models-Downloader] Loading extension...")
# =============================================================================
# METADATA LOADING
# =============================================================================
# Cache for metadata
_model_list_cache = None
_extension_node_map_cache = None
def get_metadata_path():
"""Get path to metadata directory - check multiple locations"""
# First check in our extension's metadata folder
local_metadata = os.path.join(EXTENSION_PATH, 'metadata')
if os.path.exists(local_metadata):
return local_metadata
# Check in comfyui_workflow_models_identifier
identifier_path = os.path.join(os.path.dirname(folder_paths.base_path), 'comfyui_workflow_models_identifier', 'metadata')
if os.path.exists(identifier_path):
return identifier_path
# Check ComfyUI Manager
manager_path = os.path.join(folder_paths.base_path, 'custom_nodes', 'ComfyUI-Manager')
if os.path.exists(manager_path):
return manager_path
return None
def load_model_list():
"""Load model-list.json from metadata"""
global _model_list_cache
if _model_list_cache is not None:
return _model_list_cache
metadata_path = get_metadata_path()
if not metadata_path:
logging.warning("[Workflow-Models-Downloader] Metadata path not found")
_model_list_cache = []
return _model_list_cache
try:
model_list_path = os.path.join(metadata_path, 'model-list.json')
if os.path.exists(model_list_path):
with open(model_list_path, 'r', encoding='utf-8') as f:
data = json.load(f)
_model_list_cache = data.get('models', [])
logging.info(f"[Workflow-Models-Downloader] Loaded {len(_model_list_cache)} models from model-list.json")
return _model_list_cache
except Exception as e:
logging.error(f"[Workflow-Models-Downloader] Error loading model-list.json: {e}")
_model_list_cache = []
return _model_list_cache
def load_extension_node_map():
"""Load extension-node-map.json from metadata"""
global _extension_node_map_cache
if _extension_node_map_cache is not None:
return _extension_node_map_cache
metadata_path = get_metadata_path()
if not metadata_path:
_extension_node_map_cache = {}
return _extension_node_map_cache
try:
map_path = os.path.join(metadata_path, 'extension-node-map.json')
if os.path.exists(map_path):
with open(map_path, 'r', encoding='utf-8') as f:
_extension_node_map_cache = json.load(f)
logging.info(f"[Workflow-Models-Downloader] Loaded {len(_extension_node_map_cache)} extensions from extension-node-map.json")
return _extension_node_map_cache
except Exception as e:
logging.error(f"[Workflow-Models-Downloader] Error loading extension-node-map.json: {e}")
_extension_node_map_cache = {}
return _extension_node_map_cache
def lookup_model_in_model_list(filename):
"""Look up model info from model-list.json by filename"""
models = load_model_list()
filename_lower = filename.lower()
for model in models:
if model.get('filename', '').lower() == filename_lower:
model_type = model.get('type', '')
save_path = model.get('save_path', '')
# Handle 'default' save_path - map to appropriate directory
if save_path == 'default':
type_to_dir = {
'upscale': 'upscale_models',
'TAESD': 'vae_approx',
'controlnet': 'controlnet',
'checkpoint': 'checkpoints',
'lora': 'loras',
'vae': 'vae',
}
save_path = type_to_dir.get(model_type, 'models')
return model_type, save_path, model.get('url', ''), model.get('size', '')
return None, None, None, None
def lookup_node_github_url(node_type):
"""Look up GitHub URL for a node type from extension-node-map.json"""
node_map = load_extension_node_map()
for github_url, node_data in node_map.items():
if isinstance(node_data, list) and len(node_data) > 0:
node_list = node_data[0] if isinstance(node_data[0], list) else []
if node_type in node_list:
return github_url
return None
# Initialize metadata on load
logging.info("[Workflow-Models-Downloader] Initializing metadata...")
_metadata_path = get_metadata_path()
if _metadata_path:
logging.info(f"[Workflow-Models-Downloader] Using metadata from: {_metadata_path}")
else:
logging.warning("[Workflow-Models-Downloader] No metadata found - model detection may be limited")
# =============================================================================
# URL DETECTION - Multi-source lookup
# =============================================================================
# Cache for popular models registry
_popular_models_cache = None
# Cache for API search results
_url_search_cache = {}
def load_popular_models():
"""Load the curated popular-models.json registry"""
global _popular_models_cache
if _popular_models_cache is not None:
return _popular_models_cache
try:
popular_path = os.path.join(EXTENSION_PATH, 'metadata', 'popular-models.json')
if os.path.exists(popular_path):
with open(popular_path, 'r', encoding='utf-8') as f:
data = json.load(f)
_popular_models_cache = data.get('models', {})
logging.info(f"[Workflow-Models-Downloader] Loaded {len(_popular_models_cache)} popular models")
return _popular_models_cache
except Exception as e:
logging.error(f"[Workflow-Models-Downloader] Error loading popular-models.json: {e}")
_popular_models_cache = {}
return _popular_models_cache
def lookup_url_in_popular_models(filename):
"""Look up URL from curated popular models registry"""
models = load_popular_models()
filename_lower = filename.lower()
# Exact match
if filename in models:
return models[filename].get('url', '')
# Case-insensitive match
for name, info in models.items():
if name.lower() == filename_lower:
return info.get('url', '')
return None
def lookup_url_in_model_list(filename):
"""Look up URL from model-list.json with fuzzy matching"""
models = load_model_list()
filename_lower = filename.lower()
filename_base = os.path.splitext(filename_lower)[0]
# Exact match first
for model in models:
model_filename = model.get('filename', '')
if model_filename.lower() == filename_lower:
return model.get('url', '')
# Fuzzy match - check if filename contains or is contained by model name
for model in models:
model_filename = model.get('filename', '')
model_base = os.path.splitext(model_filename.lower())[0]
# Check substring matches
if filename_base in model_base or model_base in filename_base:
url = model.get('url', '')
if url:
return url
return None
def search_huggingface_api(filename):
"""Search HuggingFace API for a model file"""
global _url_search_cache
cache_key = f"hf_{filename}"
if cache_key in _url_search_cache:
return _url_search_cache[cache_key]
try:
# Search for repos containing this filename
filename_base = os.path.splitext(filename)[0]
search_url = f"https://huggingface.co/api/models?search={urllib.parse.quote(filename_base)}&limit=5"
response = requests.get(search_url, timeout=10)
if response.status_code == 200:
repos = response.json()
for repo in repos:
repo_id = repo.get('id', '')
if not repo_id:
continue
# Check if this repo has the file
files_url = f"https://huggingface.co/api/models/{repo_id}/tree/main"
try:
files_response = requests.get(files_url, timeout=10)
if files_response.status_code == 200:
files = files_response.json()
for file_info in files:
if file_info.get('path', '').endswith(filename):
url = f"https://huggingface.co/{repo_id}/resolve/main/{file_info['path']}"
_url_search_cache[cache_key] = url
logging.info(f"[Workflow-Models-Downloader] Found {filename} on HuggingFace: {repo_id}")
return url
except Exception:
continue
except Exception as e:
logging.debug(f"[Workflow-Models-Downloader] HuggingFace API search failed: {e}")
_url_search_cache[cache_key] = None
return None
def _hf_search_terms(filename_base):
"""Return search terms from most to least specific for a model base name.
HF search matches repo names/IDs, so we try progressively simpler terms."""
terms = [filename_base]
# Strip trailing version: -V0.1, _v2, -v1.0.0, etc.
no_version = re.sub(r'[-_]v\d+(\.\d+)*$', '', filename_base, flags=re.IGNORECASE)
if no_version != filename_base:
terms.append(no_version)
# First hyphen-segment: "aidmaImageUpgrader" from "aidmaImageUpgrader-FLUX-V0.1"
first_part = filename_base.split('-')[0]
if first_part and first_part not in terms:
terms.append(first_part)
# First lowercase camelCase prefix: "aidma" from "aidmaImageUpgrader"
camel_prefix = re.match(r'^([a-z]{3,})', first_part)
if camel_prefix and camel_prefix.group(1) not in terms:
terms.append(camel_prefix.group(1))
return terms
def find_fresh_hf_url(filename, hf_token=None):
"""Query the HuggingFace API to find a current download URL for a model file.
Called automatically when a cached URL returns 404.
Returns (url, repo_id, file_path) or (None, None, None) if not found."""
filename = os.path.basename(filename) # strip subdirectory prefix e.g. "Flux/"
filename_base = os.path.splitext(filename)[0]
headers = {'Authorization': f'Bearer {hf_token}'} if hf_token else {}
search_terms = _hf_search_terms(filename_base)
logging.info(f"[WMD] HF search for '{filename}' — trying terms: {search_terms}")
seen_repos = set()
for search_term in search_terms:
try:
search_url = f"https://huggingface.co/api/models?search={urllib.parse.quote(search_term)}&limit=20"
response = requests.get(search_url, timeout=10, headers=headers)
if response.status_code != 200:
logging.warning(f"[WMD] HF search '{search_term}' returned HTTP {response.status_code}")
continue
repos = response.json()
logging.info(f"[WMD] HF search '{search_term}' → {len(repos)} repos, scanning for {filename}...")
for repo in repos:
repo_id = repo.get('id', '')
if not repo_id or repo_id in seen_repos:
continue
seen_repos.add(repo_id)
try:
tree_url = f"https://huggingface.co/api/models/{repo_id}/tree/main?recursive=true"
tree_resp = requests.get(tree_url, timeout=10, headers=headers)
if tree_resp.status_code == 200:
for file_info in tree_resp.json():
if file_info.get('type') == 'directory':
continue
file_path = file_info.get('path', '')
if os.path.basename(file_path).lower() == filename.lower():
fresh_url = f"https://huggingface.co/{repo_id}/resolve/main/{file_path}"
logging.info(f"[WMD] Found {filename} → {repo_id}/{file_path}")
return fresh_url, repo_id, file_path
except Exception as ex:
logging.debug(f"[WMD] Tree fetch failed for {repo_id}: {ex}")
continue
except Exception as e:
logging.warning(f"[WMD] HF search '{search_term}' exception: {e}")
logging.warning(f"[WMD] Could not find fresh HF URL for: {filename}")
return None, None, None
def search_civitai_api(filename):
"""Search CivitAI API for a model file"""
global _url_search_cache
cache_key = f"civit_{filename}"
if cache_key in _url_search_cache:
return _url_search_cache[cache_key]
try:
# Search by filename
filename_base = os.path.splitext(filename)[0]
# Remove common suffixes for better search
search_name = re.sub(r'[-_]?(fp16|fp8|bf16|e4m3fn|scaled|pruned|emaonly).*', '', filename_base, flags=re.IGNORECASE)
search_url = f"https://civitai.com/api/v1/models?query={urllib.parse.quote(search_name)}&limit=5"
response = requests.get(search_url, timeout=10)
if response.status_code == 200:
data = response.json()
items = data.get('items', [])
for item in items:
model_versions = item.get('modelVersions', [])
for version in model_versions:
files = version.get('files', [])
for file_info in files:
file_name = file_info.get('name', '')
if file_name.lower() == filename.lower():
url = file_info.get('downloadUrl', '')
if url:
_url_search_cache[cache_key] = url
logging.info(f"[Workflow-Models-Downloader] Found {filename} on CivitAI")
return url
except Exception as e:
logging.debug(f"[Workflow-Models-Downloader] CivitAI API search failed: {e}")
_url_search_cache[cache_key] = None
return None
def search_tavily_api(filename):
"""Search using Tavily API for model download URLs"""
global _url_search_cache
cache_key = f"tavily_{filename}"
if cache_key in _url_search_cache:
return _url_search_cache[cache_key]
tavily_key = get_tavily_api_key()
if not tavily_key:
return None
try:
# Build search query focused on finding download URLs
filename_base = os.path.splitext(filename)[0]
# Clean up common suffixes for better search
search_name = re.sub(r'[-_]?(fp16|fp8|bf16|e4m3fn|scaled|pruned|emaonly).*', '', filename_base, flags=re.IGNORECASE)
search_query = f"{search_name} safetensors download huggingface OR civitai"
url = "https://api.tavily.com/search"
payload = {
"api_key": tavily_key,
"query": search_query,
"search_depth": "advanced",
"include_domains": ["huggingface.co", "civitai.com", "github.com"],
"max_results": 10
}
response = requests.post(url, json=payload, timeout=15)
if response.status_code == 200:
data = response.json()
results = data.get('results', [])
# Look for direct download URLs in results
for result in results:
result_url = result.get('url', '')
content = result.get('content', '').lower()
title = result.get('title', '').lower()
# Check if this looks like a model page or download link
if 'huggingface.co' in result_url:
# First: check if the result URL itself is a direct blob/resolve link to the file
# e.g. huggingface.co/{repo}/blob/{ref}/{subdir/}filename.safetensors
direct_pattern = r'huggingface\.co/([^/]+/[^/]+)/(?:blob|resolve)/[^/]+/(.+)'
direct_match = re.search(direct_pattern, result_url)
if direct_match:
repo = direct_match.group(1)
file_path = direct_match.group(2)
if os.path.basename(file_path).lower() == filename.lower():
download_url = f"https://huggingface.co/{repo}/resolve/main/{file_path}"
_url_search_cache[cache_key] = {
'url': download_url,
'source': 'tavily_huggingface',
'repo': repo,
'tavily_result': result
}
logging.info(f"[Workflow-Models-Downloader] Tavily found {filename} via direct URL: {repo}/{file_path}")
return _url_search_cache[cache_key]
# Second: repo page — fetch full recursive tree and scan for the file
hf_pattern = r'huggingface\.co/([^/]+/[^/]+)(?:/(?:blob|tree)/[^/]+)?'
match = re.search(hf_pattern, result_url)
if match:
repo = match.group(1)
# Check if filename is mentioned in content or title
if filename.lower() in content or filename_base.lower() in content:
try:
files_url = f"https://huggingface.co/api/models/{repo}/tree/main?recursive=true"
files_response = requests.get(files_url, timeout=10)
if files_response.status_code == 200:
for file_info in files_response.json():
if file_info.get('type') == 'directory':
continue
file_path = file_info.get('path', '')
if os.path.basename(file_path).lower() == filename.lower():
download_url = f"https://huggingface.co/{repo}/resolve/main/{file_path}"
_url_search_cache[cache_key] = {
'url': download_url,
'source': 'tavily_huggingface',
'repo': repo,
'tavily_result': result
}
logging.info(f"[Workflow-Models-Downloader] Tavily found {filename} on HuggingFace: {repo}/{file_path}")
return _url_search_cache[cache_key]
except Exception:
pass
elif 'civitai.com' in result_url:
# Extract model ID from CivitAI URL
civit_pattern = r'civitai\.com/models/(\d+)'
match = re.search(civit_pattern, result_url)
if match:
model_id = match.group(1)
# Get model info from CivitAI API
try:
api_url = f"https://civitai.com/api/v1/models/{model_id}"
api_response = requests.get(api_url, timeout=10)
if api_response.status_code == 200:
model_data = api_response.json()
model_versions = model_data.get('modelVersions', [])
for version in model_versions:
files = version.get('files', [])
for file_info in files:
file_name = file_info.get('name', '')
if filename.lower() in file_name.lower() or filename_base.lower() in file_name.lower():
download_url = file_info.get('downloadUrl', '')
if download_url:
_url_search_cache[cache_key] = {
'url': download_url,
'source': 'tavily_civitai',
'model_name': model_data.get('name', ''),
'civitai_url': result_url,
'tavily_result': result
}
logging.info(f"[Workflow-Models-Downloader] Tavily found {filename} on CivitAI")
return _url_search_cache[cache_key]
except Exception:
pass
# If no direct match found, return the most relevant result info
if results:
_url_search_cache[cache_key] = {
'url': None,
'results': results[:5], # Return top 5 for user to choose
'source': 'tavily_suggestions'
}
return _url_search_cache[cache_key]
except Exception as e:
logging.error(f"[Workflow-Models-Downloader] Tavily API search failed: {e}")
_url_search_cache[cache_key] = None
return None