-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path__init__.py
More file actions
5088 lines (4651 loc) · 238 KB
/
Copy path__init__.py
File metadata and controls
5088 lines (4651 loc) · 238 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
"""
@author: Azornes
@title: ComfyUI Model Resolver
@version: 1.0.0
@description: Extension for resolving missing models and downloading from HuggingFace/CivitAI
"""
import asyncio
import os
import sys
import threading
import time
from typing import Any, Dict, Optional
if not __package__ or __package__ == "":
this_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(this_dir)
if parent_dir not in sys.path:
sys.path.insert(0, parent_dir)
package_name = os.path.basename(this_dir)
__package__ = package_name
current_module = sys.modules.get(__name__)
if current_module:
sys.modules[package_name] = current_module
if not hasattr(current_module, "__path__"):
current_module.__path__ = [this_dir]
from .core.log_system import LogLevel, create_module_logger
from .core.log_system import logger as backend_log_controller
from .core.log_system.config import LOG_LEVEL as BACKEND_DEFAULT_LOG_LEVEL
from .core.path_utils import get_filename_from_path, get_metadata_sidecar_path, get_safe_metadata_sidecar_path
# Web directory for JavaScript interface
WEB_DIRECTORY = "./web"
MODEL_RESOLVER_DEPENDENCY_NODE_TYPE = "ModelResolverDependency"
MODEL_RESOLVER_DEPENDENCY_NODE_DISPLAY_NAME = "Model Resolver Opener"
MODEL_RESOLVER_DEPENDENCY_NODE_CATEGORY = "Model Resolver/Workflow"
MODEL_RESOLVER_DEPENDENCY_NODE_DESCRIPTION = (
"A passive opener node for workflows that intentionally depend on "
"Model Resolver metadata. It does not process images, models, or prompts."
)
try:
from comfy_api.latest import ComfyExtension, io
except Exception:
ComfyExtension = None
io = None
if ComfyExtension is not None and io is not None:
class ModelResolverDependencyNode(io.ComfyNode):
"""Canvas node that declares Model Resolver and opens its workflow tools."""
@classmethod
def define_schema(cls) -> io.Schema:
return io.Schema(
node_id=MODEL_RESOLVER_DEPENDENCY_NODE_TYPE,
display_name=MODEL_RESOLVER_DEPENDENCY_NODE_DISPLAY_NAME,
category=MODEL_RESOLVER_DEPENDENCY_NODE_CATEGORY,
description=MODEL_RESOLVER_DEPENDENCY_NODE_DESCRIPTION,
inputs=[],
outputs=[],
)
@classmethod
def execute(cls) -> io.NodeOutput:
return io.NodeOutput()
class ModelResolverNodeExtension(ComfyExtension):
async def get_node_list(self) -> list[type[io.ComfyNode]]:
return [ModelResolverDependencyNode]
async def comfy_entrypoint() -> ComfyExtension:
return ModelResolverNodeExtension()
__all__ = ["WEB_DIRECTORY", "comfy_entrypoint"]
else:
class ModelResolverDependencyNode:
"""Legacy fallback for ComfyUI builds without the v3 custom-node API."""
DESCRIPTION = MODEL_RESOLVER_DEPENDENCY_NODE_DESCRIPTION
RETURN_TYPES = ()
FUNCTION = "noop"
CATEGORY = MODEL_RESOLVER_DEPENDENCY_NODE_CATEGORY
@classmethod
def INPUT_TYPES(cls):
return {"required": {}}
def noop(self):
return ()
NODE_CLASS_MAPPINGS = {
MODEL_RESOLVER_DEPENDENCY_NODE_TYPE: ModelResolverDependencyNode,
}
NODE_DISPLAY_NAME_MAPPINGS = {
MODEL_RESOLVER_DEPENDENCY_NODE_TYPE: MODEL_RESOLVER_DEPENDENCY_NODE_DISPLAY_NAME,
}
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
class JobProgressTracker:
"""Helper class for thread-safe job progress tracking and cancellation management."""
def __init__(self, default_message="Processing..."):
self.lock = threading.Lock()
self.progress = {}
self.cancelled = set()
self.default_message = default_message
def cleanup(self, max_age_seconds=300):
cutoff = time.time() - max_age_seconds
with self.lock:
expired = [
pid
for pid, data in self.progress.items()
if data.get("updated_at", data.get("created_at", 0)) < cutoff
]
for pid in expired:
self.progress.pop(pid, None)
self.cancelled.difference_update(expired)
def update(self, progress_id, source=None, stage=None, message=None, percent=None, status=None, **payload):
if not progress_id:
return
if source is not None:
payload["source"] = source
if stage is not None:
payload["stage"] = stage
if message is not None:
payload["message"] = message
if percent is not None:
payload["percent"] = percent
if status is not None:
payload["status"] = status
now = time.time()
with self.lock:
current = self.progress.get(progress_id, {})
# If the job was cancelled, force it to remain cancelled.
if progress_id in self.cancelled and payload.get("status") != "cancelled":
payload["status"] = "cancelled"
payload["stage"] = "cancelled"
payload["message"] = "Cancelled"
payload["percent"] = 100
payload["cancelled"] = True
# Normalize percent if present
if "percent" in payload and payload["percent"] is not None:
try:
payload["percent"] = max(0.0, min(100.0, float(payload["percent"])))
except (TypeError, ValueError):
pass
self.progress[progress_id] = {
"created_at": now,
"message": self.default_message,
**current,
**payload,
"progress_id": progress_id,
"updated_at": now,
}
def update_from_payload(
self,
progress_id: Optional[str],
progress_payload: Dict[str, Any],
default_stage: str = "running",
) -> None:
if not progress_id or not isinstance(progress_payload, dict):
return
data = dict(progress_payload)
status = data.pop("status", None)
stage = data.pop("stage", None) or default_stage
if not status:
if stage in ("done", "completed"):
status = "completed"
elif stage == "cancelled":
status = "cancelled"
else:
status = "running"
self.update(progress_id, status=status, stage=stage, **data)
def is_cancelled(self, progress_id) -> bool:
if not progress_id:
return False
with self.lock:
return progress_id in self.cancelled
def mark_cancelled(self, progress_id, cancel_message="Cancelled") -> bool:
self.cleanup()
with self.lock:
current = self.progress.get(progress_id, {})
self.cancelled.add(progress_id)
self.progress[progress_id] = {
"created_at": time.time(),
**current,
"progress_id": progress_id,
"status": "cancelled",
"stage": "cancelled",
"message": cancel_message,
"percent": 100,
"cancelled": True,
"updated_at": time.time(),
}
return True
def get(self, progress_id):
with self.lock:
val = self.progress.get(progress_id)
return dict(val) if val else None
class ModelResolverExtension:
"""Main extension class for Model Resolver."""
def __init__(self):
self.routes_setup = False
self.logger = create_module_logger(__name__)
self.analysis_progress = JobProgressTracker("Analyzing...")
self.loaded_progress = JobProgressTracker("Loading loaded models...")
self.search_tracker = JobProgressTracker("Searching...")
self.hash_tracker = JobProgressTracker("Preparing hash calculation...")
self.metadata_builder_progress = JobProgressTracker("Building local metadata...")
self.search_result_timestamps = {}
def _update_analysis_progress(
self,
analysis_id: Optional[str],
payload: Dict[str, Any]
) -> None:
self.analysis_progress.update_from_payload(analysis_id, payload)
def _update_metadata_build_progress(
self,
progress_id: Optional[str],
progress_payload: Dict[str, Any]
) -> None:
self.metadata_builder_progress.update_from_payload(progress_id, progress_payload)
def _update_loaded_progress(
self,
loaded_id: Optional[str],
stage: str,
message: str,
percent: Optional[float] = None,
status: str = "running",
current: int = 0,
total: int = 0,
**payload,
) -> None:
if not loaded_id:
return
self.loaded_progress.update_from_payload(
loaded_id,
{
"stage": stage,
"message": message,
"percent": percent,
"status": status,
"current": current,
"total": total,
**payload,
},
)
def _update_workflow_analysis_progress(
self,
loaded_id: Optional[str],
workflow_node_count: int,
interpolate_percent_fn,
payload: Dict[str, Any]
) -> None:
progress_payload = dict(payload or {})
current = progress_payload.pop("current", 0)
total = progress_payload.pop("total", workflow_node_count)
stage = progress_payload.pop("stage", "analyzing")
message = progress_payload.pop("message", "Analyzing workflow nodes...")
progress_payload.pop("percent", None)
self._update_loaded_progress(
loaded_id,
stage,
message,
percent=interpolate_percent_fn(35, 78, current, total),
current=current,
total=total,
**progress_payload,
)
def initialize(self):
"""Initialize the extension and set up API routes."""
try:
self.setup_routes()
self.logger.info("Model Resolver: Extension initialized successfully")
except Exception as e:
self.logger.error(
f"Model Resolver: Extension initialization failed: {e}", exc_info=True
)
def setup_routes(self):
"""Register API routes for the Model Resolver extension."""
if self.routes_setup:
return # Already set up
try:
from aiohttp import web
# Try to get routes from PromptServer
try:
from server import PromptServer
if (
not hasattr(PromptServer, "instance")
or PromptServer.instance is None
):
self.logger.debug("Model Resolver: PromptServer not available yet")
return False
routes = PromptServer.instance.routes
except (ImportError, AttributeError) as e:
self.logger.debug(f"Model Resolver: Could not access PromptServer: {e}")
return False
# Import resolver modules
try:
from .core.metadata_audit import audit_metadata_sizes
from .core.metadata_builder import (
build_missing_local_metadata,
get_metadata_build_capabilities,
)
from .core.network_utils import (
UnsafeUrlError,
host_matches_domain,
request_public_url,
validate_public_http_url,
)
from .core.path_templates import infer_download_path_templates
from .core.path_utils import (
HashCalculationCancelled,
calculate_file_sha256,
dedupe_local_base_directories,
extract_safetensors_header_sha256,
get_comfy_root_path,
get_filename_from_path,
get_path_abs,
get_path_identity,
get_path_key,
is_path_in_configured_model_roots,
is_path_within,
prefer_local_base_directory,
read_json_safe,
write_json_atomic,
)
from .core.resolver import (
analyze_and_find_matches,
apply_resolution,
get_local_model_hash_metadata,
invalidate_local_hash_match_cache,
search_local_matches,
search_local_matches_by_hash,
)
from .core.scanner import find_local_file_path, get_model_files, invalidate_model_files_cache
from .core.settings import (
TEMPLATE_KEY_ALIASES,
get_default_root_for_category,
get_settings_schema,
resolve_download_subfolder,
)
from .core.settings import (
bool_setting as resolver_bool_setting,
)
from .core.settings import (
load_settings as load_resolver_settings,
)
from .core.settings import (
save_settings as save_resolver_settings,
)
from .core.type_utils import (
build_search_result,
extract_sha256_from_metadata,
fetch_remote_file_size_cached,
first_non_empty,
format_size_bytes,
get_category_folder_keys,
get_enabled_download_categories,
looks_like_model_file,
normalize_category_to_model_type,
normalize_sha256,
select_primary_model_file,
to_bool,
to_int,
)
from .core.workflow_analyzer import (
NODE_TYPE_MODEL_WIDGET_CATEGORIES,
URN_TYPE_MAP,
analyze_workflow_models,
)
except ImportError as e:
self.logger.error(f"Model Resolver: Could not import core modules: {e}")
return False
# Import download modules
try:
from .core.aria2_installer import Aria2InstallError, install_aria2_engine
from .core.downloader import (
cancel_download,
clear_completed_downloads,
get_all_progress,
get_aria2_status,
get_download_directory,
get_progress,
is_allowed_model_download_filename,
normalize_download_category,
pause_download,
resume_download,
sanitize_download_filename,
start_aria2_daemon,
start_background_download,
stop_aria2_daemon,
write_lora_manager_metadata,
)
from .core.sources import clear_all_search_caches
from .core.sources.civarchive import (
CivArchiveSearchError,
build_civarchive_custom_result,
get_civarchive_model_details,
is_civarchive_available,
parse_civarchive_url,
resolve_civarchive_by_hash,
resolve_civarchive_model_version,
search_civarchive_for_file,
)
from .core.sources.civarchive import (
clear_search_cache as clear_civarchive_search_cache,
)
from .core.sources.civitai import (
build_civitai_custom_result,
check_civitai_api_key,
check_civitai_session_token,
get_civitai_download_url,
get_civitai_model_details,
get_model_info_by_hash,
get_model_info_for_file,
parse_civitai_url,
resolve_civitai_version_custom_result,
resolve_urn,
search_civitai,
search_civitai_for_file,
)
from .core.sources.civitai import (
clear_search_cache as clear_civitai_search_cache,
)
from .core.sources.huggingface import (
build_huggingface_custom_result,
check_brave_search_api_key,
check_huggingface_token,
get_author_fallback_index_status,
get_huggingface_download_url,
parse_huggingface_url,
refresh_author_fallback_index,
search_huggingface_for_file,
)
from .core.sources.huggingface import (
clear_search_cache as clear_huggingface_search_cache,
)
from .core.sources.lora_manager_archive import (
clear_search_cache as clear_lora_manager_archive_search_cache,
)
from .core.sources.lora_manager_archive import (
is_lora_manager_archive_available,
search_lora_manager_archive_for_file,
)
from .core.sources.model_list import (
get_model_list_update_status,
reload_model_list,
search_model_list,
search_model_list_multiple,
update_model_list_from_remote,
)
from .core.sources.popular import (
get_base_models_config,
get_base_models_status,
get_popular_model_url,
search_popular_models,
update_base_models_from_remote,
)
from .core.sources.popular import (
reload_databases as reload_popular_databases,
)
download_available = True
except ImportError as e:
self.logger.warning(
f"Model Resolver: Download features not available: {e}"
)
download_available = False
def json_api_endpoint(error_prefix, return_success_on_error=False):
def decorator(func):
from functools import wraps
@wraps(func)
async def wrapper(request, *args, **kwargs):
try:
return await func(request, *args, **kwargs)
except Exception as e:
self.logger.error(
f"Model Resolver {error_prefix} error: {e}", exc_info=True
)
response_data = {"error": str(e)}
if return_success_on_error:
response_data["success"] = False
return web.json_response(response_data, status=500)
return wrapper
return decorator
def get_progress_response(tracker, request, param_name="progress_id", not_found_payload=None, not_found_status=200, found_wrapper=None):
job_id = request.match_info.get(param_name, "").strip()
if not job_id:
return web.json_response({"error": f"{param_name} is required"}, status=400)
tracker.cleanup()
progress = tracker.get(job_id)
if not progress:
payload = not_found_payload or {"error": "progress not found"}
return web.json_response(payload, status=not_found_status)
if found_wrapper:
return web.json_response(found_wrapper(progress))
return web.json_response(progress)
def cancel_progress_response(tracker, request, param_name="progress_id", cancel_message="Cancelled"):
job_id = request.match_info.get(param_name, "").strip()
if not job_id:
return web.json_response({"error": f"{param_name} is required"}, status=400)
cancelled = tracker.mark_cancelled(job_id, cancel_message)
return web.json_response({
"success": True,
"cancelled": cancelled,
"progress_id": job_id,
})
def run_in_background_thread(
tracker,
progress_id,
task_func,
on_success,
on_cancel=None,
on_error=None,
error_log_msg="Background task failed",
):
def wrapper():
try:
result = task_func()
if tracker.is_cancelled(progress_id):
if on_cancel:
on_cancel(result)
else:
tracker.update(
progress_id,
status="cancelled",
stage="cancelled",
message="Task cancelled",
)
return
on_success(result)
except (HashCalculationCancelled, asyncio.CancelledError):
if on_cancel:
on_cancel()
else:
tracker.update(
progress_id,
status="cancelled",
stage="cancelled",
message="Task cancelled",
)
except Exception as exc:
self.logger.exception(f"{error_log_msg}: {exc}")
if on_error:
on_error(exc)
else:
tracker.update(
progress_id,
status="error",
stage="error",
message=str(exc) or "Task failed",
percent=100,
error=str(exc) or "Task failed",
)
import threading
threading.Thread(target=wrapper, daemon=True).start()
async def get_override_settings_from_request(request):
settings = await asyncio.to_thread(load_resolver_settings)
if request.method == "POST":
try:
payload = await request.json()
if isinstance(payload, dict) and "aria2c_path" in payload:
settings = dict(settings)
settings["aria2c_path"] = payload.get("aria2c_path", "")
except Exception:
pass
return settings
# ==================== BASE MODELS CONFIG ROUTE ====================
@routes.get("/model_resolver/base-models")
@json_api_endpoint("base-models")
async def get_base_models(request):
"""
Return popular base models configuration dictionary.
Returns {base_models: [{name, aliases}]} so the frontend
dropdown can populate correctly via baseModels.base_models.
"""
data = get_base_models_config()
return web.json_response(data)
@routes.get("/model_resolver/base-models/status")
@json_api_endpoint("base-models status")
async def get_base_models_status_route(request):
"""Get local and optional remote base models status."""
check_remote = request.query.get("check_remote") == "1"
status = await asyncio.to_thread(get_base_models_status, check_remote)
return web.json_response(status)
@routes.post("/model_resolver/base-models/update")
@json_api_endpoint("base-models update")
async def update_base_models_route(request):
"""Update base models list from CivitAI."""
status = await asyncio.to_thread(update_base_models_from_remote)
return web.json_response(status)
# ==================== ANALYZE ROUTES ====================
@routes.post("/model_resolver/analyze")
async def analyze_workflow(request):
"""Analyze workflow and return missing models with matches."""
try:
data = await request.json()
workflow_json = data.get("workflow")
analysis_id = str(data.get("analysis_id") or "").strip()
force_rescan = to_bool(data.get("force_rescan"), False)
if force_rescan:
invalidate_local_hash_match_cache()
if workflow_json is None:
return web.json_response(
{"error": "Workflow JSON is required"}, status=400
)
if not isinstance(workflow_json, dict):
return web.json_response(
{"error": "Workflow JSON must be an object"}, status=400
)
if analysis_id:
self._update_analysis_progress(
analysis_id,
{
"status": "starting",
"stage": "starting",
"message": "Starting analysis...",
"current": 0,
"total": 0,
},
)
def update_analysis_progress(payload):
self._update_analysis_progress(analysis_id, payload)
# Analyze and find matches
result = await asyncio.to_thread(
analyze_and_find_matches,
workflow_json,
0.0,
10,
update_analysis_progress if analysis_id else None,
force_rescan=force_rescan,
)
# Filter out LoraManager lorAs that already exist locally (exists=True)
# These should not appear in missing models at all
missing_models = result.get("missing_models", [])
filtered_missing = []
for missing in missing_models:
is_lora = missing.get("is_lora_v2")
exists = missing.get("exists")
name = missing.get("name") or missing.get("original_path", "")
self.logger.debug(
f"Filtering: {name} is_lora_v2={is_lora} exists={exists}"
)
# Skip LoraManager lorAs that already exist locally
if is_lora and exists:
self.logger.info(
f"Filtered out LoraManager lora: {name}"
)
continue
filtered_missing.append(missing)
result["missing_models"] = filtered_missing
result["total_missing"] = len(filtered_missing)
# If download available, check for download sources only from LOCAL sources
# (workflow_url, popular, model-list.json) - skip automatic online search
# Online search is now only triggered on-demand via search button
if download_available:
for missing in result.get("missing_models", []):
# Check if there's a 100% local match
matches = missing.get("matches", [])
has_perfect_match = any(
m.get("confidence", 0) == 100 for m in matches
)
if not has_perfect_match:
filename = get_filename_from_path(
missing.get("original_path", "")
)
# 0. Check workflow URL first (highest priority - directly from workflow)
workflow_url = missing.get("workflow_url", "")
if workflow_url:
# Determine source from URL
if "huggingface.co" in workflow_url:
source = "huggingface"
elif "civitai.com" in workflow_url:
source = "civitai"
else:
source = "workflow"
# Try to get file size using cached remote helper
file_size = fetch_remote_file_size_cached(workflow_url, timeout=5)
missing["download_source"] = {
"source": source,
"url": workflow_url,
"model_url": missing.get(
"workflow_model_url", workflow_url
),
"filename": filename,
"directory": missing.get(
"workflow_directory", ""
)
or missing.get("category", "checkpoints"),
"match_type": "exact",
"url_source": "workflow",
"size": file_size,
}
continue
# 1. Check popular models (always exact match)
popular_info = get_popular_model_url(filename)
if popular_info:
popular_model_list_result = search_model_list(
filename, exact_only=True
)
missing["download_source"] = {
"source": "popular",
"url": popular_info.get("url"),
"filename": filename,
"type": popular_info.get("type"),
"directory": popular_info.get("directory"),
"size": (
popular_model_list_result.get("size")
if popular_model_list_result
else None
)
or popular_info.get("size"),
"match_type": "exact",
}
continue
# 2. Check model list (ComfyUI Manager database)
# Use exact_only=True to avoid confusing fuzzy matches for downloads
model_list_result = search_model_list(
filename, exact_only=True
)
if model_list_result:
missing["download_source"] = {
"source": "model_list",
"url": model_list_result.get("url"),
"filename": model_list_result.get("filename"),
"name": model_list_result.get("name"),
"type": model_list_result.get("type"),
"directory": model_list_result.get("directory"),
"size": model_list_result.get("size"),
"match_type": model_list_result.get(
"match_type"
),
"confidence": model_list_result.get(
"confidence"
),
}
continue
# NOTE: Search for online sources (HuggingFace, CivitAI) is
# now done on-demand via /model_resolver/search endpoint
# when user clicks "Search Online" button, not automatically
if analysis_id:
self.analysis_progress.update(
analysis_id,
status="completed",
stage="completed",
message="Analysis complete",
current=result.get("total_missing", 0),
total=result.get("total_missing", 0),
)
return web.json_response(result)
except Exception as e:
if "analysis_id" in locals() and analysis_id:
self.analysis_progress.update(
analysis_id,
status="error",
stage="error",
message=str(e),
current=0,
total=0,
)
self.logger.error(f"Model Resolver analyze error: {e}", exc_info=True)
return web.json_response({"error": str(e)}, status=500)
@routes.get("/model_resolver/analyze-progress/{analysis_id}")
@json_api_endpoint("analyze-progress")
async def get_analyze_progress(request):
"""Get workflow analysis progress."""
return get_progress_response(
self.analysis_progress,
request,
param_name="analysis_id",
not_found_payload={
"status": "unknown",
"stage": "unknown",
"message": "No analysis progress available",
"current": 0,
"total": 0,
}
)
@routes.post("/model_resolver/resolve")
@json_api_endpoint("resolve", return_success_on_error=True)
async def resolve_models(request):
"""Apply model resolution and return updated workflow."""
data = await request.json()
workflow_json = data.get("workflow")
resolutions = data.get("resolutions", [])
if not workflow_json:
return web.json_response(
{"error": "Workflow JSON is required"}, status=400
)
if not resolutions:
return web.json_response(
{"error": "Resolutions array is required"}, status=400
)
# Apply resolutions
updated_workflow = apply_resolution(workflow_json, resolutions)
return web.json_response(
{"workflow": updated_workflow, "success": True}
)
@routes.post("/model_resolver/local-matches")
@json_api_endpoint("local-matches")
async def local_matches(request):
"""Search local model files by filename/path."""
data = await request.json()
filename = data.get("filename", "")
category = data.get("category", "")
force_rescan = to_bool(data.get("force_rescan"), False)
if force_rescan:
invalidate_local_hash_match_cache()
if not filename:
return web.json_response(
{"error": "filename is required"}, status=400
)
matches = search_local_matches(
filename,
category=category or None,
similarity_threshold=0.0,
max_matches_per_model=10,
force_rescan=force_rescan,
)
return web.json_response({"matches": matches})
@routes.post("/model_resolver/local-model-hashes")
@json_api_endpoint("local-model-hashes")
async def local_model_hashes(request):
"""Return SHA256 hashes already stored in local sidecar metadata."""
data = await request.json()
model = data.get("model") if isinstance(data.get("model"), dict) else {}
path = (
data.get("path")
or data.get("file_path")
or data.get("resolved_path")
or model.get("path")
or model.get("resolved_path")
or ""
)
if not path:
return web.json_response(
{"error": "path is required"}, status=400
)
normalized_path = os.path.realpath(
os.path.abspath(os.path.normpath(str(path)))
)
if not is_path_in_configured_model_roots(normalized_path):
return web.json_response(
{"error": "path is outside configured model directories"},
status=403,
)
return web.json_response(
get_local_model_hash_metadata(normalized_path, model=model)
)
@routes.post("/model_resolver/workflow-model-hashes")
@json_api_endpoint("workflow-model-hashes")
async def workflow_model_hashes(request):
"""Return hash metadata for existing local models used by a workflow."""
data = await request.json()
workflow_json = data.get("workflow")
if not isinstance(workflow_json, dict):
return web.json_response(
{"error": "Workflow JSON must be an object"}, status=400
)
settings = await asyncio.to_thread(load_resolver_settings)
if not resolver_bool_setting(
settings.get("workflow_hash_metadata_enabled"), True
):
return web.json_response(
{
"success": True,
"enabled": False,
"models": [],
"by_node": {},
"by_path": {},
"count": 0,
}
)
available_models = await asyncio.to_thread(get_model_files, False)
refs = await asyncio.to_thread(
analyze_workflow_models,
workflow_json,
available_models,
)
by_node = {}
by_path = {}
models = []
seen = set()
for ref in refs:
if not isinstance(ref, dict) or not ref.get("exists"):
continue
full_path = str(ref.get("full_path") or "").strip()
if not full_path:
continue
model_info = {
"path": full_path,
"filename": get_filename_from_path(full_path),
"relative_path": ref.get("original_path") or "",
"category": ref.get("category") or "",
}
metadata = get_local_model_hash_metadata(
full_path, model=model_info
)
sha256 = normalize_sha256(metadata.get("sha256"))
if not sha256:
continue
entry = {
"node_id": ref.get("node_id"),
"node_type": ref.get("node_type") or "",
"widget_index": ref.get("widget_index"),
"widget_name": ref.get("widget_name") or "",
"path": ref.get("original_path") or "",
"filename": get_filename_from_path(
ref.get("original_path") or full_path
),
"category": ref.get("category") or "",
"sha256": sha256,
"size": metadata.get("size") or 0,
}
entry_key = (
str(entry.get("node_id")),
str(entry.get("widget_index")),