auto-diffusers 2.0.32.dev1__py3-none-any.whl → 2.0.36__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  # coding=utf-8
2
- # Copyright 2025 suzukimain
2
+ # Copyright 2026 suzukimain
3
3
  #
4
4
  # Licensed under the Apache License, Version 2.0 (the "License");
5
5
  # you may not use this file except in compliance with the License.
@@ -13,65 +13,210 @@
13
13
  # See the License for the specific language governing permissions and
14
14
  # limitations under the License.
15
15
 
16
+ # Standard library imports
16
17
  import os
17
18
  import re
18
19
  import types
20
+ from collections import OrderedDict
19
21
  from dataclasses import asdict, dataclass, field
20
22
  from typing import Dict, List, Optional, Union
21
- from collections import OrderedDict
22
-
23
23
 
24
+ # Third-party imports
24
25
  import requests
25
26
  import torch
26
27
 
28
+ # Diffusers core imports
27
29
  from diffusers.loaders.single_file_utils import (
28
30
  VALID_URL_PREFIXES,
29
31
  _extract_repo_id_and_weights_name,
30
32
  infer_diffusers_model_type,
31
33
  load_single_file_checkpoint,
32
34
  )
33
-
34
- from diffusers import (
35
- StableDiffusionPipeline,
36
- StableDiffusionImg2ImgPipeline,
37
- StableDiffusionInpaintPipeline,
38
- )
39
35
  from diffusers.pipelines.auto_pipeline import (
36
+ AUTO_IMAGE2IMAGE_PIPELINES_MAPPING,
37
+ AUTO_INPAINT_PIPELINES_MAPPING,
38
+ AUTO_TEXT2IMAGE_PIPELINES_MAPPING,
40
39
  AutoPipelineForImage2Image,
41
40
  AutoPipelineForInpainting,
42
41
  AutoPipelineForText2Image,
43
- AUTO_TEXT2IMAGE_PIPELINES_MAPPING,
44
- AUTO_IMAGE2IMAGE_PIPELINES_MAPPING,
45
- AUTO_INPAINT_PIPELINES_MAPPING,
46
42
  )
47
43
  from diffusers.pipelines.pipeline_utils import DiffusionPipeline
48
44
  from diffusers.utils import logging
49
45
 
46
+ # Stable Diffusion v1/v2 pipelines
50
47
  from diffusers import (
51
- AnimateDiffPipeline,
52
- AnimateDiffSDXLPipeline,
53
- StableDiffusionControlNetPipeline,
54
- StableDiffusionControlNetImg2ImgPipeline,
55
- StableDiffusionControlNetInpaintPipeline,
48
+ StableDiffusionImg2ImgPipeline,
49
+ StableDiffusionInpaintPipeline,
50
+ StableDiffusionPipeline,
51
+ StableDiffusionUpscalePipeline,
52
+ )
53
+
54
+ # Stable Diffusion XL pipelines
55
+ from diffusers import (
56
+ StableDiffusionXLControlNetImg2ImgPipeline,
57
+ StableDiffusionXLControlNetInpaintPipeline,
58
+ StableDiffusionXLControlNetPipeline,
56
59
  StableDiffusionXLImg2ImgPipeline,
57
- StableDiffusionXLPipeline,
58
60
  StableDiffusionXLInpaintPipeline,
59
- StableDiffusionUpscalePipeline,
60
- StableDiffusion3Pipeline,
61
+ StableDiffusionXLPipeline,
62
+ )
63
+
64
+ # Stable Diffusion 3 pipelines
65
+ from diffusers import (
61
66
  StableDiffusion3Img2ImgPipeline,
62
- FluxPipeline,
63
- FluxImg2ImgPipeline,
64
- StableDiffusionXLControlNetPipeline,
65
- StableDiffusionXLControlNetImg2ImgPipeline,
67
+ StableDiffusion3InpaintPipeline,
68
+ StableDiffusion3Pipeline,
69
+ )
70
+
71
+ # Flux pipelines (import separately to avoid Flax deprecation warnings)
72
+ try:
73
+ from diffusers.pipelines.flux import (
74
+ FluxImg2ImgPipeline,
75
+ FluxInpaintPipeline,
76
+ FluxPipeline,
77
+ FluxControlImg2ImgPipeline,
78
+ FluxControlInpaintPipeline,
79
+ FluxControlNetImg2ImgPipeline,
80
+ FluxControlNetInpaintPipeline,
81
+ FluxControlNetPipeline,
82
+ FluxControlPipeline,
83
+ FluxKontextPipeline,
84
+ )
85
+ except ImportError:
86
+ FluxImg2ImgPipeline = None
87
+ FluxInpaintPipeline = None
88
+ FluxPipeline = None
89
+ FluxControlImg2ImgPipeline = None
90
+ FluxControlInpaintPipeline = None
91
+ FluxControlNetImg2ImgPipeline = None
92
+ FluxControlNetInpaintPipeline = None
93
+ FluxControlNetPipeline = None
94
+ FluxControlPipeline = None
95
+ FluxKontextPipeline = None
96
+
97
+ # ControlNet pipelines
98
+ from diffusers import (
99
+ StableDiffusionControlNetImg2ImgPipeline,
100
+ StableDiffusionControlNetInpaintPipeline,
101
+ StableDiffusionControlNetPipeline,
102
+ )
103
+
104
+ # AnimateDiff pipelines
105
+ from diffusers import (
106
+ AnimateDiffPipeline,
107
+ AnimateDiffSDXLPipeline,
66
108
  )
67
109
 
68
- from huggingface_hub import hf_api, hf_hub_download
110
+ # Optional pipelines (newer versions only)
111
+ try:
112
+ from diffusers import (
113
+ AuraFlowPipeline,
114
+ ChromaPipeline,
115
+ CogView3PlusPipeline,
116
+ CogView4ControlPipeline,
117
+ CogView4Pipeline,
118
+ HunyuanDiTPipeline,
119
+ KandinskyCombinedPipeline,
120
+ KandinskyImg2ImgCombinedPipeline,
121
+ KandinskyInpaintCombinedPipeline,
122
+ KandinskyV22CombinedPipeline,
123
+ KandinskyV22Img2ImgCombinedPipeline,
124
+ KandinskyV22InpaintCombinedPipeline,
125
+ Kandinsky3Img2ImgPipeline,
126
+ Kandinsky3Pipeline,
127
+ LatentConsistencyModelImg2ImgPipeline,
128
+ LatentConsistencyModelPipeline,
129
+ Lumina2Pipeline,
130
+ LuminaPipeline,
131
+ OvisImagePipeline,
132
+ PixArtAlphaPipeline,
133
+ PixArtSigmaPipeline,
134
+ QwenImageControlNetPipeline,
135
+ QwenImageEditInpaintPipeline,
136
+ QwenImageEditPipeline,
137
+ QwenImageEditPlusPipeline,
138
+ QwenImageImg2ImgPipeline,
139
+ QwenImageInpaintPipeline,
140
+ QwenImageLayeredPipeline,
141
+ QwenImagePipeline,
142
+ SanaPipeline,
143
+ StableDiffusion3ControlNetInpaintingPipeline,
144
+ StableDiffusion3ControlNetPipeline,
145
+ StableDiffusionXLControlNetUnionImg2ImgPipeline,
146
+ StableDiffusionXLControlNetUnionInpaintPipeline,
147
+ StableDiffusionXLControlNetUnionPipeline,
148
+ WanImageToVideoPipeline,
149
+ WanPipeline,
150
+ WanVideoToVideoPipeline,
151
+ ZImageControlNetInpaintPipeline,
152
+ ZImageControlNetPipeline,
153
+ ZImageImg2ImgPipeline,
154
+ ZImageOmniPipeline,
155
+ ZImagePipeline,
156
+ )
157
+ except ImportError:
158
+ # Fallback to None for pipelines not available in older versions
159
+ AuraFlowPipeline = None
160
+ ChromaPipeline = None
161
+ CogView3PlusPipeline = None
162
+ CogView4ControlPipeline = None
163
+ CogView4Pipeline = None
164
+ HunyuanDiTPipeline = None
165
+ KandinskyCombinedPipeline = None
166
+ KandinskyImg2ImgCombinedPipeline = None
167
+ KandinskyInpaintCombinedPipeline = None
168
+ KandinskyV22CombinedPipeline = None
169
+ KandinskyV22Img2ImgCombinedPipeline = None
170
+ KandinskyV22InpaintCombinedPipeline = None
171
+ Kandinsky3Img2ImgPipeline = None
172
+ Kandinsky3Pipeline = None
173
+ LatentConsistencyModelImg2ImgPipeline = None
174
+ LatentConsistencyModelPipeline = None
175
+ Lumina2Pipeline = None
176
+ LuminaPipeline = None
177
+ OvisImagePipeline = None
178
+ PixArtAlphaPipeline = None
179
+ PixArtSigmaPipeline = None
180
+ QwenImageControlNetPipeline = None
181
+ QwenImageEditInpaintPipeline = None
182
+ QwenImageEditPipeline = None
183
+ QwenImageEditPlusPipeline = None
184
+ QwenImageImg2ImgPipeline = None
185
+ QwenImageInpaintPipeline = None
186
+ QwenImageLayeredPipeline = None
187
+ QwenImagePipeline = None
188
+ SanaPipeline = None
189
+ StableDiffusion3ControlNetInpaintingPipeline = None
190
+ StableDiffusion3ControlNetPipeline = None
191
+ StableDiffusionXLControlNetUnionImg2ImgPipeline = None
192
+ StableDiffusionXLControlNetUnionInpaintPipeline = None
193
+ StableDiffusionXLControlNetUnionPipeline = None
194
+ WanImageToVideoPipeline = None
195
+ WanPipeline = None
196
+ WanVideoToVideoPipeline = None
197
+ ZImageControlNetInpaintPipeline = None
198
+ ZImageControlNetPipeline = None
199
+ ZImageImg2ImgPipeline = None
200
+ ZImageOmniPipeline = None
201
+ ZImagePipeline = None
202
+
203
+ from huggingface_hub import hf_api, hf_hub_download, hf_hub_url
69
204
  from huggingface_hub.file_download import http_get
70
205
  from huggingface_hub.utils import validate_hf_hub_args
71
206
 
72
207
 
73
208
  logger = logging.get_logger(__name__)
74
209
 
210
+ # Suppress verbose warnings from dependencies
211
+ logging.set_verbosity_error()
212
+ # Reduce logging level for torchao
213
+ try:
214
+ import logging as std_logging
215
+ std_logging.getLogger("torchao").setLevel(std_logging.WARNING)
216
+ std_logging.getLogger("torchao.kernel.intmm").setLevel(std_logging.ERROR)
217
+ except Exception:
218
+ pass
219
+
75
220
 
76
221
  SINGLE_FILE_CHECKPOINT_TEXT2IMAGE_PIPELINE_MAPPING = OrderedDict(
77
222
  [
@@ -81,29 +226,65 @@ SINGLE_FILE_CHECKPOINT_TEXT2IMAGE_PIPELINE_MAPPING = OrderedDict(
81
226
  ("animatediff_v1", AnimateDiffPipeline),
82
227
  ("animatediff_v2", AnimateDiffPipeline),
83
228
  ("animatediff_v3", AnimateDiffPipeline),
229
+ ("auraflow", AuraFlowPipeline),
84
230
  ("autoencoder-dc-f128c512", None),
85
231
  ("autoencoder-dc-f32c32", None),
86
232
  ("autoencoder-dc-f32c32-sana", None),
87
233
  ("autoencoder-dc-f64c128", None),
234
+ ("chroma", ChromaPipeline),
235
+ ("cogview3", CogView3PlusPipeline),
236
+ ("cogview4", CogView4Pipeline),
237
+ ("cogview4-control", CogView4ControlPipeline),
88
238
  ("controlnet", StableDiffusionControlNetPipeline),
89
239
  ("controlnet_xl", StableDiffusionXLControlNetPipeline),
90
240
  ("controlnet_xl_large", StableDiffusionXLControlNetPipeline),
91
241
  ("controlnet_xl_mid", StableDiffusionXLControlNetPipeline),
92
242
  ("controlnet_xl_small", StableDiffusionXLControlNetPipeline),
243
+ ("controlnet_xl_union", StableDiffusionXLControlNetUnionPipeline),
244
+ ("cosmos-1.0-t2w-7B", None),
245
+ ("cosmos-1.0-t2w-14B", None),
246
+ ("cosmos-1.0-v2w-7B", None),
247
+ ("cosmos-1.0-v2w-14B", None),
248
+ ("cosmos-2.0-t2i-2B", None),
249
+ ("cosmos-2.0-t2i-14B", None),
250
+ ("cosmos-2.0-v2w-2B", None),
251
+ ("cosmos-2.0-v2w-14B", None),
252
+ ("flux-2-dev", FluxPipeline),
253
+ ("flux-control", FluxControlPipeline),
254
+ ("flux-controlnet", FluxControlNetPipeline),
93
255
  ("flux-depth", FluxPipeline),
94
256
  ("flux-dev", FluxPipeline),
95
257
  ("flux-fill", FluxPipeline),
258
+ ("flux-kontext", FluxKontextPipeline),
96
259
  ("flux-schnell", FluxPipeline),
260
+ ("hidream", None),
261
+ ("hunyuan", HunyuanDiTPipeline),
97
262
  ("hunyuan-video", None),
98
263
  ("inpainting", None),
99
264
  ("inpainting_v2", None),
265
+ ("instruct-pix2pix", None),
266
+ ("kandinsky", KandinskyCombinedPipeline),
267
+ ("kandinsky22", KandinskyV22CombinedPipeline),
268
+ ("kandinsky3", Kandinsky3Pipeline),
269
+ ("lcm", LatentConsistencyModelPipeline),
270
+ ("lumina", LuminaPipeline),
271
+ ("lumina2", Lumina2Pipeline),
100
272
  ("ltx-video", None),
101
273
  ("ltx-video-0.9.1", None),
274
+ ("ltx-video-0.9.5", None),
275
+ ("ltx-video-0.9.7", None),
102
276
  ("mochi-1-preview", None),
277
+ ("ovis", OvisImagePipeline),
278
+ ("pixart-alpha", PixArtAlphaPipeline),
279
+ ("pixart-sigma", PixArtSigmaPipeline),
103
280
  ("playground-v2-5", StableDiffusionXLPipeline),
281
+ ("qwenimage", QwenImagePipeline),
282
+ ("qwenimage-controlnet", QwenImageControlNetPipeline),
283
+ ("sana", SanaPipeline),
104
284
  ("sd3", StableDiffusion3Pipeline),
105
285
  ("sd35_large", StableDiffusion3Pipeline),
106
286
  ("sd35_medium", StableDiffusion3Pipeline),
287
+ ("sd3-controlnet", StableDiffusion3ControlNetPipeline),
107
288
  ("stable_cascade_stage_b", None),
108
289
  ("stable_cascade_stage_b_lite", None),
109
290
  ("stable_cascade_stage_c", None),
@@ -111,9 +292,20 @@ SINGLE_FILE_CHECKPOINT_TEXT2IMAGE_PIPELINE_MAPPING = OrderedDict(
111
292
  ("upscale", StableDiffusionUpscalePipeline),
112
293
  ("v1", StableDiffusionPipeline),
113
294
  ("v2", StableDiffusionPipeline),
295
+ ("wan-i2v-14B", WanImageToVideoPipeline),
296
+ ("wan-t2v-1.3B", WanPipeline),
297
+ ("wan-t2v-14B", WanPipeline),
298
+ ("wan-vace-1.3B", WanVideoToVideoPipeline),
299
+ ("wan-vace-14B", WanVideoToVideoPipeline),
114
300
  ("xl_base", StableDiffusionXLPipeline),
115
- ("xl_inpaint", None),
116
301
  ("xl_refiner", StableDiffusionXLPipeline),
302
+ ("z-image", ZImagePipeline),
303
+ ("z-image-controlnet", ZImageControlNetPipeline),
304
+ ("z-image-omni", ZImageOmniPipeline),
305
+ ("z-image-turbo", None),
306
+ ("z-image-turbo-controlnet", None),
307
+ ("z-image-turbo-controlnet-2.0", None),
308
+ ("z-image-turbo-controlnet-2.1", None),
117
309
  ],
118
310
  )
119
311
 
@@ -139,17 +331,45 @@ SINGLE_FILE_CHECKPOINT_IMAGE2IMAGE_PIPELINE_MAPPING = OrderedDict(
139
331
  ("controlnet_xl_large", StableDiffusionXLControlNetImg2ImgPipeline),
140
332
  ("controlnet_xl_mid", StableDiffusionXLControlNetImg2ImgPipeline),
141
333
  ("controlnet_xl_small", StableDiffusionXLControlNetImg2ImgPipeline),
334
+ ("controlnet_xl_union", StableDiffusionXLControlNetUnionImg2ImgPipeline),
335
+ ("cosmos-1.0-t2w-7B", None),
336
+ ("cosmos-1.0-t2w-14B", None),
337
+ ("cosmos-1.0-v2w-7B", None),
338
+ ("cosmos-1.0-v2w-14B", None),
339
+ ("cosmos-2.0-t2i-2B", None),
340
+ ("cosmos-2.0-t2i-14B", None),
341
+ ("cosmos-2.0-v2w-2B", None),
342
+ ("cosmos-2.0-v2w-14B", None),
343
+ ("flux-2-dev", FluxImg2ImgPipeline),
344
+ ("flux-control", FluxControlImg2ImgPipeline),
345
+ ("flux-controlnet", FluxControlNetImg2ImgPipeline),
142
346
  ("flux-depth", FluxImg2ImgPipeline),
143
347
  ("flux-dev", FluxImg2ImgPipeline),
144
348
  ("flux-fill", FluxImg2ImgPipeline),
349
+ ("flux-kontext", FluxKontextPipeline),
145
350
  ("flux-schnell", FluxImg2ImgPipeline),
351
+ ("hidream", None),
146
352
  ("hunyuan-video", None),
147
353
  ("inpainting", None),
148
354
  ("inpainting_v2", None),
355
+ ("instruct-pix2pix", None),
356
+ ("kandinsky", KandinskyImg2ImgCombinedPipeline),
357
+ ("kandinsky22", KandinskyV22Img2ImgCombinedPipeline),
358
+ ("kandinsky3", Kandinsky3Img2ImgPipeline),
359
+ ("lcm", LatentConsistencyModelImg2ImgPipeline),
360
+ ("lumina", None),
361
+ ("lumina2", None),
149
362
  ("ltx-video", None),
150
363
  ("ltx-video-0.9.1", None),
364
+ ("ltx-video-0.9.5", None),
365
+ ("ltx-video-0.9.7", None),
151
366
  ("mochi-1-preview", None),
152
367
  ("playground-v2-5", StableDiffusionXLImg2ImgPipeline),
368
+ ("qwenimage", QwenImageImg2ImgPipeline),
369
+ ("qwenimage-edit", QwenImageEditPipeline),
370
+ ("qwenimage-edit-plus", QwenImageEditPlusPipeline),
371
+ ("qwenimage-layered", QwenImageLayeredPipeline),
372
+ ("sana", None),
153
373
  ("sd3", StableDiffusion3Img2ImgPipeline),
154
374
  ("sd35_large", StableDiffusion3Img2ImgPipeline),
155
375
  ("sd35_medium", StableDiffusion3Img2ImgPipeline),
@@ -160,9 +380,18 @@ SINGLE_FILE_CHECKPOINT_IMAGE2IMAGE_PIPELINE_MAPPING = OrderedDict(
160
380
  ("upscale", StableDiffusionUpscalePipeline),
161
381
  ("v1", StableDiffusionImg2ImgPipeline),
162
382
  ("v2", StableDiffusionImg2ImgPipeline),
383
+ ("wan-i2v-14B", WanImageToVideoPipeline),
384
+ ("wan-t2v-1.3B", None),
385
+ ("wan-t2v-14B", None),
386
+ ("wan-vace-1.3B", WanVideoToVideoPipeline),
387
+ ("wan-vace-14B", WanVideoToVideoPipeline),
163
388
  ("xl_base", StableDiffusionXLImg2ImgPipeline),
164
- ("xl_inpaint", None),
165
389
  ("xl_refiner", StableDiffusionXLImg2ImgPipeline),
390
+ ("z-image", ZImageImg2ImgPipeline),
391
+ ("z-image-turbo", None),
392
+ ("z-image-turbo-controlnet", None),
393
+ ("z-image-turbo-controlnet-2.0", None),
394
+ ("z-image-turbo-controlnet-2.1", None),
166
395
  ]
167
396
  )
168
397
 
@@ -179,34 +408,68 @@ SINGLE_FILE_CHECKPOINT_INPAINT_PIPELINE_MAPPING = OrderedDict(
179
408
  ("autoencoder-dc-f32c32-sana", None),
180
409
  ("autoencoder-dc-f64c128", None),
181
410
  ("controlnet", StableDiffusionControlNetInpaintPipeline),
182
- ("controlnet_xl", None),
183
- ("controlnet_xl_large", None),
184
- ("controlnet_xl_mid", None),
185
- ("controlnet_xl_small", None),
186
- ("flux-depth", None),
187
- ("flux-dev", None),
188
- ("flux-fill", None),
189
- ("flux-schnell", None),
411
+ ("controlnet_xl", StableDiffusionXLControlNetInpaintPipeline),
412
+ ("controlnet_xl_large", StableDiffusionXLControlNetInpaintPipeline),
413
+ ("controlnet_xl_mid", StableDiffusionXLControlNetInpaintPipeline),
414
+ ("controlnet_xl_small", StableDiffusionXLControlNetInpaintPipeline),
415
+ ("controlnet_xl_union", StableDiffusionXLControlNetUnionInpaintPipeline),
416
+ ("cosmos-1.0-t2w-7B", None),
417
+ ("cosmos-1.0-t2w-14B", None),
418
+ ("cosmos-1.0-v2w-7B", None),
419
+ ("cosmos-1.0-v2w-14B", None),
420
+ ("cosmos-2.0-t2i-2B", None),
421
+ ("cosmos-2.0-t2i-14B", None),
422
+ ("cosmos-2.0-v2w-2B", None),
423
+ ("cosmos-2.0-v2w-14B", None),
424
+ ("flux-2-dev", FluxInpaintPipeline),
425
+ ("flux-control", FluxControlInpaintPipeline),
426
+ ("flux-controlnet", FluxControlNetInpaintPipeline),
427
+ ("flux-depth", FluxInpaintPipeline),
428
+ ("flux-dev", FluxInpaintPipeline),
429
+ ("flux-fill", FluxInpaintPipeline),
430
+ ("flux-schnell", FluxInpaintPipeline),
431
+ ("hidream", None),
190
432
  ("hunyuan-video", None),
191
433
  ("inpainting", StableDiffusionInpaintPipeline),
192
434
  ("inpainting_v2", StableDiffusionInpaintPipeline),
435
+ ("instruct-pix2pix", None),
436
+ ("kandinsky", KandinskyInpaintCombinedPipeline),
437
+ ("kandinsky22", KandinskyV22InpaintCombinedPipeline),
438
+ ("lcm", None),
439
+ ("lumina", None),
440
+ ("lumina2", None),
193
441
  ("ltx-video", None),
194
442
  ("ltx-video-0.9.1", None),
443
+ ("ltx-video-0.9.5", None),
444
+ ("ltx-video-0.9.7", None),
195
445
  ("mochi-1-preview", None),
196
446
  ("playground-v2-5", None),
197
- ("sd3", None),
198
- ("sd35_large", None),
199
- ("sd35_medium", None),
447
+ ("qwenimage", QwenImageInpaintPipeline),
448
+ ("qwenimage-edit", QwenImageEditInpaintPipeline),
449
+ ("sana", None),
450
+ ("sd3", StableDiffusion3InpaintPipeline),
451
+ ("sd35_large", StableDiffusion3InpaintPipeline),
452
+ ("sd35_medium", StableDiffusion3InpaintPipeline),
453
+ ("sd3-controlnet", StableDiffusion3ControlNetInpaintingPipeline),
200
454
  ("stable_cascade_stage_b", None),
201
455
  ("stable_cascade_stage_b_lite", None),
202
456
  ("stable_cascade_stage_c", None),
203
457
  ("stable_cascade_stage_c_lite", None),
204
458
  ("upscale", StableDiffusionUpscalePipeline),
205
- ("v1", None),
206
- ("v2", None),
207
- ("xl_base", None),
459
+ ("v1", StableDiffusionInpaintPipeline),
460
+ ("v2", StableDiffusionInpaintPipeline),
461
+ ("wan-i2v-14B", None),
462
+ ("wan-t2v-1.3B", None),
463
+ ("wan-t2v-14B", None),
464
+ ("wan-vace-1.3B", None),
465
+ ("wan-vace-14B", None),
466
+ ("xl_base", StableDiffusionXLInpaintPipeline),
208
467
  ("xl_inpaint", StableDiffusionXLInpaintPipeline),
209
- ("xl_refiner", None),
468
+ ("z-image-controlnet-inpaint", ZImageControlNetInpaintPipeline),
469
+ ("z-image-turbo", None),
470
+ ("z-image-turbo-controlnet", None),
471
+ ("z-image-turbo-controlnet-2.0", None),
472
+ ("z-image-turbo-controlnet-2.1", None),
210
473
  ]
211
474
  )
212
475
 
@@ -262,15 +525,28 @@ TOKENIZER_SHAPE_MAP = {
262
525
  }
263
526
 
264
527
 
265
- EXTENSION = [".safetensors", ".ckpt", ".bin"]
528
+ def get_allowed_extensions(allow_unsafe_formats: bool = True) -> List[str]:
529
+ r"""
530
+ Get the list of allowed file extensions based on safety preferences.
531
+
532
+ Parameters:
533
+ allow_unsafe_formats (`bool`, *optional*, defaults to `True`):
534
+ If True (default), allows all formats (.safetensors, .ckpt, .bin) for backward compatibility.
535
+ If False, only allows .safetensors format for maximum security.
536
+
537
+ Returns:
538
+ `List[str]`: List of allowed file extensions.
539
+ """
540
+ if allow_unsafe_formats:
541
+ return [".safetensors", ".ckpt", ".bin"]
542
+ else:
543
+ return [".safetensors"]
266
544
 
267
- CACHE_HOME = os.path.expanduser("~/.cache")
268
545
 
546
+ # Default extension list (for backward compatibility)
547
+ EXTENSION = [".safetensors", ".ckpt", ".bin"]
269
548
 
270
- # Set up pipeline mappings
271
- AUTO_TEXT2IMAGE_PIPELINES_MAPPING["v1"] = StableDiffusionPipeline
272
- AUTO_IMAGE2IMAGE_PIPELINES_MAPPING["v1"] = StableDiffusionImg2ImgPipeline
273
- AUTO_INPAINT_PIPELINES_MAPPING["v1"] = StableDiffusionInpaintPipeline
549
+ CACHE_HOME = os.path.expanduser("~/.cache")
274
550
 
275
551
 
276
552
  @dataclass
@@ -429,6 +705,7 @@ def load_pipeline_from_single_file(
429
705
  )
430
706
 
431
707
  else:
708
+ # Load the pipeline from the checkpoint
432
709
  return pipeline_class.from_single_file(pretrained_model_or_path, **kwargs)
433
710
 
434
711
 
@@ -479,6 +756,12 @@ def get_keyword_types(keyword):
479
756
  if not os.path.exists(os.path.join(keyword, "model_index.json")):
480
757
  status["extra_type"]["missing_model_index"] = True
481
758
 
759
+ # Check if the keyword is a Civitai API download URL
760
+ elif keyword.startswith("https://civitai.com/api/download/"):
761
+ status["type"]["civitai_url"] = True
762
+ status["checkpoint_format"] = "single_file"
763
+ status["loading_method"] = "from_single_file"
764
+
482
765
  # Check if the keyword is a Civitai URL
483
766
  elif keyword.startswith("https://civitai.com/"):
484
767
  status["type"]["civitai_url"] = True
@@ -512,6 +795,54 @@ def get_keyword_types(keyword):
512
795
  return status
513
796
 
514
797
 
798
+ def validate_url_with_head(
799
+ url: str,
800
+ token: Optional[str] = None,
801
+ headers: Optional[Dict] = None,
802
+ timeout: int = 2
803
+ ) -> None:
804
+ """
805
+ Validates a URL is accessible by performing a HEAD request.
806
+ Raises HTTPError for any 4xx/5xx status codes (including 401 Unauthorized).
807
+ Logs and continues for other errors.
808
+
809
+ Parameters:
810
+ url (`str`):
811
+ The URL to validate.
812
+ token (`str`, *optional*):
813
+ Authentication token for the request.
814
+ headers (`dict`, *optional*):
815
+ Dictionary of HTTP Headers to send with the request.
816
+ If provided, takes precedence over token.
817
+ timeout (`int`, *optional*, defaults to `2`):
818
+ Timeout in seconds for the HEAD request.
819
+
820
+ Raises:
821
+ requests.HTTPError: If the URL returns any 4xx or 5xx status code.
822
+ """
823
+ if headers is None:
824
+ headers = {}
825
+ else:
826
+ # Create a copy to avoid modifying the original
827
+ headers = dict(headers)
828
+
829
+ # If token is provided and authorization not already in headers, add it
830
+ # Check case-insensitively since HTTP headers are case-insensitive
831
+ if token and not any(k.lower() == "authorization" for k in headers):
832
+ headers["Authorization"] = f"Bearer {token}"
833
+
834
+ try:
835
+ response = requests.head(url, headers=headers, allow_redirects=True, timeout=timeout)
836
+ # Raise HTTPError for any 4xx/5xx status codes (including 401)
837
+ response.raise_for_status()
838
+ except requests.HTTPError:
839
+ # Re-raise HTTPError (primarily for 401, but also other 4xx/5xx from raise_for_status)
840
+ raise
841
+ except requests.exceptions.RequestException as e:
842
+ # Log other request errors but don't fail - the actual download may still succeed
843
+ logger.info(f"HEAD check failed (continuing to download): {url} -> {e}")
844
+
845
+
515
846
  def file_downloader(
516
847
  url,
517
848
  save_path,
@@ -577,15 +908,14 @@ def file_downloader(
577
908
  mode = "ab"
578
909
  file_size = os.path.getsize(save_path)
579
910
 
580
- # Check if the URL is accessible before downloading. If HEAD returns 401,
581
- # raise an HTTPError so callers can try the next candidate. Other HEAD
582
- # failures are logged and the download is still attempted.
911
+ # Try HEAD validation but don't fail if it returns errors (Cloudflare R2 blocks HEAD requests)
912
+ # The actual download attempt will reveal if the URL is truly inaccessible
583
913
  try:
584
- response = requests.head(url, headers=headers, allow_redirects=True, timeout=2)
585
- if response.status_code == 401:
586
- raise requests.HTTPError(f"401 Unauthorized: {url}")
587
- except requests.exceptions.RequestException as e:
588
- logger.info(f"HEAD check failed (continuing to download): {url} -> {e}")
914
+ validate_url_with_head(url, headers=headers)
915
+ except requests.HTTPError as e:
916
+ # Log but continue - HEAD requests may fail even when GET succeeds
917
+ status_code = e.response.status_code if hasattr(e, 'response') else 'unknown'
918
+ logger.info(f"HEAD request returned {status_code} for {url}, attempting download anyway...")
589
919
 
590
920
  # Open the file in the appropriate mode (write or append)
591
921
  with open(save_path, mode) as model_file:
@@ -627,6 +957,9 @@ def search_huggingface(search_word: str, **kwargs) -> Union[str, SearchResult, N
627
957
  A boolean to filter models on the Hub that are gated or not.
628
958
  skip_error (`bool`, *optional*, defaults to `False`):
629
959
  Whether to skip errors and return None.
960
+ allow_unsafe_formats (`bool`, *optional*, defaults to `False`):
961
+ If True, allows potentially unsafe formats (.ckpt, .bin) in addition to .safetensors.
962
+ If False (default), only allows .safetensors format for maximum security.
630
963
 
631
964
  Returns:
632
965
  `Union[str, SearchResult, None]`: The model path or SearchResult or None.
@@ -648,13 +981,17 @@ def search_huggingface(search_word: str, **kwargs) -> Union[str, SearchResult, N
648
981
  gated = kwargs.pop("gated", False)
649
982
  cache_dir = kwargs.pop("cache_dir", None)
650
983
  skip_error = kwargs.pop("skip_error", False)
984
+ allow_unsafe_formats = kwargs.pop("allow_unsafe_formats", False)
985
+
986
+ # Get allowed extensions based on safety preference
987
+ allowed_extensions = get_allowed_extensions(allow_unsafe_formats)
651
988
 
652
989
  file_list = []
653
990
  hf_repo_info = {}
654
991
  hf_security_info = {}
655
992
  model_path = ""
656
993
  repo_id, file_name = "", ""
657
- diffusers_model_exists = False
994
+ candidate_index = kwargs.pop("candidate_index", 0)
658
995
 
659
996
  # Get the type and loading method for the keyword
660
997
  search_word_status = get_keyword_types(search_word)
@@ -693,7 +1030,7 @@ def search_huggingface(search_word: str, **kwargs) -> Union[str, SearchResult, N
693
1030
  return None
694
1031
  else:
695
1032
  raise ValueError(
696
- "The URL for Civitai is invalid with `for_hf`. Please use `for_civitai` instead."
1033
+ "The URL for Civitai is invalid with `from_huggingface`. Please use `from_civitai` instead."
697
1034
  )
698
1035
  else:
699
1036
  # Get model data from HF API
@@ -709,13 +1046,19 @@ def search_huggingface(search_word: str, **kwargs) -> Union[str, SearchResult, N
709
1046
  )
710
1047
  model_dicts = [asdict(value) for value in list(hf_models)]
711
1048
 
712
- # Loop through models to find a suitable candidate
1049
+ # Collect all valid candidates first
1050
+ candidates = []
713
1051
  for repo_info in model_dicts:
714
1052
  repo_id = repo_info["id"]
715
1053
  file_list = []
716
- hf_repo_info = asdict(
717
- hf_api.model_info(repo_id=repo_id, securityStatus=True)
718
- )
1054
+ try:
1055
+ hf_repo_info = asdict(
1056
+ hf_api.model_info(repo_id=repo_id, securityStatus=True)
1057
+ )
1058
+ except Exception as e:
1059
+ logger.info(f"Failed to get repo info for {repo_id}: {e}")
1060
+ continue
1061
+
719
1062
  # Lists files with security issues.
720
1063
  hf_security_info = hf_repo_info["security_repo_status"]
721
1064
  exclusion = [issue["path"] for issue in hf_security_info["filesWithIssues"]]
@@ -728,11 +1071,16 @@ def search_huggingface(search_word: str, **kwargs) -> Union[str, SearchResult, N
728
1071
  "diffusers",
729
1072
  "all",
730
1073
  ]:
731
- diffusers_model_exists = True
1074
+ # Found diffusers model
1075
+ candidates.append({
1076
+ "type": "diffusers",
1077
+ "repo_id": repo_id,
1078
+ "repo_info": hf_repo_info,
1079
+ })
732
1080
  break
733
1081
 
734
1082
  elif (
735
- any(file_path.endswith(ext) for ext in EXTENSION)
1083
+ any(file_path.endswith(ext) for ext in allowed_extensions)
736
1084
  and not any(config in file_path for config in CONFIG_FILE_LIST)
737
1085
  and not any(exc in file_path for exc in exclusion)
738
1086
  and os.path.basename(os.path.dirname(file_path)) not in DIFFUSERS_CONFIG_DIR
@@ -743,11 +1091,26 @@ def search_huggingface(search_word: str, **kwargs) -> Union[str, SearchResult, N
743
1091
  )
744
1092
  ):
745
1093
  file_list.append(file_path)
746
-
747
- # Exit from the loop if a multi-folder diffusers model or valid file is found
748
- if diffusers_model_exists or file_list:
749
- break
750
- else:
1094
+
1095
+ # Add single file candidates
1096
+ if file_list:
1097
+ # Sort and find the safest model
1098
+ file_name = next(
1099
+ (
1100
+ model
1101
+ for model in sorted(file_list, reverse=True)
1102
+ if re.search(r"(?i)[-_](safe|sfw)", model)
1103
+ ),
1104
+ file_list[0],
1105
+ )
1106
+ candidates.append({
1107
+ "type": "single_file",
1108
+ "repo_id": repo_id,
1109
+ "file_name": file_name,
1110
+ "repo_info": hf_repo_info,
1111
+ })
1112
+
1113
+ if not candidates:
751
1114
  # Handle case where no models match the criteria
752
1115
  if skip_error:
753
1116
  return None
@@ -756,37 +1119,74 @@ def search_huggingface(search_word: str, **kwargs) -> Union[str, SearchResult, N
756
1119
  "No models matching your criteria were found on huggingface."
757
1120
  )
758
1121
 
759
- if diffusers_model_exists:
760
- if download:
761
- model_path = DiffusionPipeline.download(
762
- repo_id,
763
- token=token,
764
- cache_dir=cache_dir,
765
- **kwargs,
766
- )
1122
+ # Check if candidate_index is valid
1123
+ if candidate_index >= len(candidates):
1124
+ if skip_error:
1125
+ return None
767
1126
  else:
768
- model_path = repo_id
769
-
770
- elif file_list:
771
- # Sort and find the safest model
772
- file_name = next(
773
- (
774
- model
775
- for model in sorted(file_list, reverse=True)
776
- if re.search(r"(?i)[-_](safe|sfw)", model)
777
- ),
778
- file_list[0],
779
- )
780
-
781
- if download:
782
- model_path = hf_hub_download(
783
- repo_id=repo_id,
784
- filename=file_name,
785
- revision=revision,
786
- token=token,
787
- force_download=force_download,
788
- cache_dir=cache_dir,
789
- )
1127
+ raise ValueError(f"No more candidates available (requested index {candidate_index}, total {len(candidates)})")
1128
+
1129
+ # Get the candidate at the specified index
1130
+ candidate = candidates[candidate_index]
1131
+ repo_id = candidate["repo_id"]
1132
+ hf_repo_info = candidate["repo_info"]
1133
+
1134
+ try:
1135
+ if candidate["type"] == "diffusers":
1136
+ # Validate URL early to detect 401 errors
1137
+ if download:
1138
+ # Validate URL accessibility before downloading
1139
+ # Check if model_index.json is accessible
1140
+ model_index_url = hf_hub_url(
1141
+ repo_id=repo_id,
1142
+ filename="model_index.json",
1143
+ revision=revision
1144
+ )
1145
+ validate_url_with_head(model_index_url, token=token)
1146
+
1147
+ model_path = DiffusionPipeline.download(
1148
+ repo_id,
1149
+ token=token,
1150
+ cache_dir=cache_dir,
1151
+ **kwargs,
1152
+ )
1153
+ else:
1154
+ model_path = repo_id
1155
+
1156
+ file_name = ""
1157
+
1158
+ elif candidate["type"] == "single_file":
1159
+ file_name = candidate["file_name"]
1160
+
1161
+ # Validate URL early to detect 401 errors
1162
+ if download:
1163
+ # Validate URL accessibility before downloading
1164
+ # Construct the download URL for validation using hf_hub_url
1165
+ file_url = hf_hub_url(
1166
+ repo_id=repo_id,
1167
+ filename=file_name,
1168
+ revision=revision
1169
+ )
1170
+ validate_url_with_head(file_url, token=token)
1171
+
1172
+ model_path = hf_hub_download(
1173
+ repo_id=repo_id,
1174
+ filename=file_name,
1175
+ revision=revision,
1176
+ token=token,
1177
+ force_download=force_download,
1178
+ cache_dir=cache_dir,
1179
+ )
1180
+ else:
1181
+ model_path = f"https://huggingface.co/{repo_id}/blob/main/{file_name}"
1182
+
1183
+ except Exception as e:
1184
+ # Log the error and let the caller decide whether to retry
1185
+ logger.info(f"Candidate {candidate_index+1}/{len(candidates)} ({repo_id}) failed: {e}")
1186
+ if skip_error:
1187
+ return None
1188
+ else:
1189
+ raise
790
1190
 
791
1191
  # `pathlib.PosixPath` may be returned
792
1192
  if model_path:
@@ -848,6 +1248,9 @@ def search_civitai(search_word: str, **kwargs) -> Union[str, SearchResult, None]
848
1248
  Whether to resume an incomplete download.
849
1249
  skip_error (`bool`, *optional*, defaults to `False`):
850
1250
  Whether to skip errors and return None.
1251
+ allow_unsafe_formats (`bool`, *optional*, defaults to `False`):
1252
+ If True, allows potentially unsafe formats (.ckpt, .bin) in addition to .safetensors.
1253
+ If False (default), only allows .safetensors format for maximum security.
851
1254
 
852
1255
  Returns:
853
1256
  `Union[str, SearchResult, None]`: The model path or ` SearchResult` or None.
@@ -864,6 +1267,10 @@ def search_civitai(search_word: str, **kwargs) -> Union[str, SearchResult, None]
864
1267
  resume = kwargs.pop("resume", False)
865
1268
  cache_dir = kwargs.pop("cache_dir", None)
866
1269
  skip_error = kwargs.pop("skip_error", False)
1270
+ allow_unsafe_formats = kwargs.pop("allow_unsafe_formats", False)
1271
+
1272
+ # Get allowed extensions based on safety preference
1273
+ allowed_extensions = get_allowed_extensions(allow_unsafe_formats)
867
1274
 
868
1275
  # Initialize additional variables with default values
869
1276
  model_path = ""
@@ -877,6 +1284,96 @@ def search_civitai(search_word: str, **kwargs) -> Union[str, SearchResult, None]
877
1284
  selected_version = {}
878
1285
  civitai_cache_dir = cache_dir or os.path.join(CACHE_HOME, "Civitai")
879
1286
 
1287
+ # Handle direct Civitai API download URLs
1288
+ if search_word.startswith("https://civitai.com/api/download/"):
1289
+ # Extract model version ID from URL
1290
+ match = re.search(r'/models/(\d+)', search_word)
1291
+ if match:
1292
+ version_id = match.group(1)
1293
+ # Try to get model info from API
1294
+ headers = {}
1295
+ if token:
1296
+ headers["Authorization"] = f"Bearer {token}"
1297
+
1298
+ try:
1299
+ # Get version info to extract model name and ID
1300
+ response = requests.get(
1301
+ f"https://civitai.com/api/v1/model-versions/{version_id}",
1302
+ headers=headers
1303
+ )
1304
+ response.raise_for_status()
1305
+ version_data = response.json()
1306
+
1307
+ repo_name = version_data.get("model", {}).get("name", f"model_{version_id}")
1308
+ repo_id = str(version_data.get("modelId", ""))
1309
+ trainedWords = version_data.get("trainedWords", [])
1310
+
1311
+ # Get primary file info
1312
+ files = version_data.get("files", [])
1313
+ if files:
1314
+ primary_file = files[0]
1315
+ file_name = primary_file.get("name", f"model_{version_id}.safetensors")
1316
+ else:
1317
+ file_name = f"model_{version_id}.safetensors"
1318
+
1319
+ except Exception as e:
1320
+ logger.info(f"Could not fetch model info from API: {e}. Using fallback values.")
1321
+ repo_name = f"model_{version_id}"
1322
+ repo_id = ""
1323
+ file_name = f"model_{version_id}.safetensors"
1324
+ trainedWords = []
1325
+
1326
+ download_url = search_word
1327
+
1328
+ if download:
1329
+ # Download from the direct URL
1330
+ local_path = os.path.join(civitai_cache_dir, file_name)
1331
+
1332
+ try:
1333
+ file_downloader(
1334
+ url=download_url,
1335
+ save_path=local_path,
1336
+ resume=resume,
1337
+ force_download=force_download,
1338
+ displayed_filename=file_name,
1339
+ headers=headers,
1340
+ )
1341
+ model_path = local_path
1342
+ except Exception as e:
1343
+ if skip_error:
1344
+ return None
1345
+ else:
1346
+ raise ValueError(f"Failed to download from direct URL: {e}")
1347
+ else:
1348
+ model_path = download_url
1349
+
1350
+ output_info = get_keyword_types(model_path)
1351
+
1352
+ if not include_params:
1353
+ return model_path
1354
+ else:
1355
+ return SearchResult(
1356
+ model_path=model_path,
1357
+ loading_method=output_info["loading_method"],
1358
+ checkpoint_format=output_info["checkpoint_format"],
1359
+ repo_status=RepoStatus(
1360
+ repo_id=repo_name, repo_hash=repo_id, version=version_id
1361
+ ),
1362
+ model_status=ModelStatus(
1363
+ search_word=search_word,
1364
+ site_url=f"https://civitai.com/models/{repo_id}?modelVersionId={version_id}" if repo_id else download_url,
1365
+ download_url=download_url,
1366
+ file_name=file_name,
1367
+ local=output_info["type"]["local"],
1368
+ ),
1369
+ extra_status=ExtraStatus(trained_words=trainedWords or None),
1370
+ )
1371
+ else:
1372
+ if skip_error:
1373
+ return None
1374
+ else:
1375
+ raise ValueError("Could not extract model version ID from Civitai API URL")
1376
+
880
1377
  # Set up parameters and headers for the CivitAI API request
881
1378
  params = {
882
1379
  "query": search_word,
@@ -923,6 +1420,9 @@ def search_civitai(search_word: str, **kwargs) -> Union[str, SearchResult, None]
923
1420
  # Since the Civitai API is broken, I will temporarily sort by name.
924
1421
  sorted_repos = sorted(data["items"], key=lambda x: x["name"], reverse=True)
925
1422
 
1423
+ # Collect all valid candidates instead of selecting one
1424
+ all_candidates = []
1425
+
926
1426
  for selected_repo in sorted_repos:
927
1427
  repo_name = selected_repo["name"]
928
1428
  repo_id = selected_repo["id"]
@@ -945,9 +1445,7 @@ def search_civitai(search_word: str, **kwargs) -> Union[str, SearchResult, None]
945
1445
  if (
946
1446
  model_data["pickleScanResult"] == "Success"
947
1447
  and model_data["virusScanResult"] == "Success"
948
- and any(file_name.endswith(ext) for ext in EXTENSION)
949
- and os.path.basename(os.path.dirname(file_name))
950
- not in DIFFUSERS_CONFIG_DIR
1448
+ and any(file_name.endswith(ext) for ext in allowed_extensions)
951
1449
  ):
952
1450
  file_status = {
953
1451
  "filename": file_name,
@@ -972,57 +1470,69 @@ def search_civitai(search_word: str, **kwargs) -> Union[str, SearchResult, None]
972
1470
  sorted_models[0],
973
1471
  )
974
1472
 
975
- # Validate download URL accessibility (check first file only)
976
- try:
977
- # Since models requiring authentication do not return results, there is no need to determine their status via status codes.
978
- _resp = requests.head(
979
- candidate_model["download_url"],
980
- headers=headers,
981
- timeout=2,
982
- allow_redirects=True
983
- )
984
- selected_model = candidate_model
985
- logger.info(f"Validated download URL: {candidate_model['download_url']}")
986
- break # Exit the version loop if a valid model is found
987
- except requests.exceptions.RequestException as e:
988
- logger.info(f"Failed to validate URL {candidate_model['download_url']}: {e}, trying next version...")
989
- continue
990
-
991
- # If we found a valid model in this repo, exit outer repo loop
992
- if selected_model:
993
- break
994
-
995
-
996
- # Exception handling when search candidates are not found
997
- if not selected_model:
1473
+ # Add to candidates list (skip URL validation which causes 403 errors)
1474
+ # Actual download will be attempted and retried recursively
1475
+ all_candidates.append({
1476
+ 'model': candidate_model,
1477
+ 'repo_name': repo_name,
1478
+ 'repo_id': repo_id,
1479
+ 'version_id': version_id,
1480
+ 'trainedWords': trainedWords,
1481
+ })
1482
+ logger.info(f"Added candidate: {candidate_model['filename']} from {repo_name}")
1483
+
1484
+
1485
+ # Exception handling when no candidates are found
1486
+ if not all_candidates:
998
1487
  if skip_error:
999
1488
  return None
1000
1489
  else:
1001
- raise ValueError(
1002
- "No model found. Please try changing the word you are searching for."
1003
- )
1004
-
1005
- # Define model file status
1490
+ # Provide helpful error message based on token availability
1491
+ if token:
1492
+ error_msg = (
1493
+ "No model found. Please try changing the search word or filter criteria "
1494
+ "(e.g., base_model, sort). You can also check if your CivitAI token has "
1495
+ "access to the models you're searching for."
1496
+ )
1497
+ else:
1498
+ error_msg = (
1499
+ "No model found. Please try changing the search word or filter criteria. "
1500
+ "If you're looking for private or exclusive models, provide a CivitAI token: "
1501
+ "search_civitai(search_word, token='your_civitai_token')"
1502
+ )
1503
+ raise ValueError(error_msg)
1504
+
1505
+ # Select first candidate for initial metadata
1506
+ selected = all_candidates[0]
1507
+ selected_model = selected['model']
1508
+ repo_name = selected['repo_name']
1509
+ repo_id = selected['repo_id']
1510
+ version_id = selected['version_id']
1511
+ trainedWords = selected['trainedWords']
1512
+
1006
1513
  file_name = selected_model["filename"]
1007
1514
  download_url = selected_model["download_url"]
1008
1515
 
1009
1516
  # Handle file download and setting model information
1010
1517
  if download:
1011
- # Try downloading from the models list, retrying on 401 errors
1518
+ # Try downloading from all candidates recursively
1012
1519
  download_success = False
1013
- # Create a sorted list of all available models to try
1014
- sorted_models = sorted(
1015
- models_list, key=lambda x: x["filename"], reverse=True
1016
- )
1017
1520
 
1018
- for model_candidate in sorted_models:
1521
+ logger.info(f"Attempting to download from {len(all_candidates)} candidate(s)...")
1522
+
1523
+ for idx, candidate in enumerate(all_candidates):
1019
1524
  try:
1020
- file_name = model_candidate["filename"]
1021
- download_url = model_candidate["download_url"]
1525
+ candidate_model = candidate['model']
1526
+ file_name = candidate_model["filename"]
1527
+ download_url = candidate_model["download_url"]
1528
+ candidate_repo_id = candidate['repo_id']
1529
+ candidate_version_id = candidate['version_id']
1530
+
1531
+ logger.info(f"Attempt {idx + 1}/{len(all_candidates)}: {file_name} from {candidate['repo_name']}")
1022
1532
 
1023
- # The path where the model is to be saved.
1533
+ # The path where the model is to be saved
1024
1534
  model_path = os.path.join(
1025
- str(civitai_cache_dir), str(repo_id), str(version_id), str(file_name)
1535
+ str(civitai_cache_dir), str(candidate_repo_id), str(candidate_version_id), str(file_name)
1026
1536
  )
1027
1537
 
1028
1538
  # Download Model File
@@ -1035,18 +1545,44 @@ def search_civitai(search_word: str, **kwargs) -> Union[str, SearchResult, None]
1035
1545
  headers=headers,
1036
1546
  **kwargs,
1037
1547
  )
1548
+
1549
+ # Update selected metadata on success
1038
1550
  download_success = True
1039
- logger.info(f"Successfully downloaded model from: {download_url}")
1551
+ selected_model = candidate_model
1552
+ repo_name = candidate['repo_name']
1553
+ repo_id = candidate_repo_id
1554
+ version_id = candidate_version_id
1555
+ trainedWords = candidate['trainedWords']
1556
+ file_name = candidate_model["filename"]
1557
+ download_url = candidate_model["download_url"]
1558
+
1559
+ logger.info(f"Successfully downloaded: {file_name} from {repo_name}")
1040
1560
  break
1561
+
1041
1562
  except requests.HTTPError as e:
1042
- if "401" in str(e):
1043
- logger.info(f"401 error for {download_url}, trying next candidate...")
1044
- continue
1045
- else:
1046
- raise
1563
+ status_code = e.response.status_code if hasattr(e, 'response') else 'unknown'
1564
+ logger.info(f"HTTP error {status_code} for {download_url}, trying next candidate...")
1565
+ continue
1566
+ except Exception as e:
1567
+ logger.info(f"Download failed for {download_url}: {e}, trying next candidate...")
1568
+ continue
1047
1569
 
1048
1570
  if not download_success:
1049
- raise ValueError(f"Failed to download any model file from {repo_name}. All URLs returned 401 errors.")
1571
+ if skip_error:
1572
+ return None
1573
+ else:
1574
+ # Show helpful error message based on token availability
1575
+ if token:
1576
+ error_msg = (
1577
+ f"Failed to download any model file after trying {len(all_candidates)} candidate(s). "
1578
+ "All downloads returned errors. Please check your CivitAI token permissions or try different search criteria."
1579
+ )
1580
+ else:
1581
+ error_msg = (
1582
+ f"Failed to download any model file after trying {len(all_candidates)} candidate(s). "
1583
+ "If models require authentication, provide a CivitAI token: search_civitai(search_word, token='your_token')"
1584
+ )
1585
+ raise ValueError(error_msg)
1050
1586
 
1051
1587
  else:
1052
1588
  model_path = download_url
@@ -1074,6 +1610,94 @@ def search_civitai(search_word: str, **kwargs) -> Union[str, SearchResult, None]
1074
1610
  )
1075
1611
 
1076
1612
 
1613
+ def _load_pipeline_with_retries(cls, pretrained_model_link_or_path, pipeline_mapping, **kwargs):
1614
+ """
1615
+ Helper function to load a pipeline with retry logic using an iterative loop.
1616
+ Handles candidate selection, retries, and error tracking.
1617
+
1618
+ Parameters:
1619
+ cls: The pipeline class
1620
+ pretrained_model_link_or_path: Model identifier or path
1621
+ pipeline_mapping: Pipeline mapping for single file checkpoints
1622
+ **kwargs: Additional arguments
1623
+
1624
+ Returns:
1625
+ Loaded pipeline with methods added
1626
+ """
1627
+ # Extract retry parameters from kwargs
1628
+ max_retries = kwargs.pop('_max_retries', 9)
1629
+ failed_count = 0
1630
+
1631
+ # Update kwargs to ensure the model is downloaded and parameters are included
1632
+ _status = {
1633
+ "download": True,
1634
+ "include_params": True,
1635
+ "skip_error": False,
1636
+ "pipeline_tag": kwargs.pop('_pipeline_tag', None),
1637
+ }
1638
+ kwargs.update(_status)
1639
+
1640
+ # Try each candidate up to max_retries times
1641
+ for attempt in range(max_retries + 1):
1642
+ # Search for the model on Hugging Face
1643
+ try:
1644
+ hf_checkpoint_status = search_huggingface(
1645
+ pretrained_model_link_or_path, candidate_index=attempt, **kwargs
1646
+ )
1647
+ except Exception as e:
1648
+ logger.info(f"Candidate {attempt + 1}/{max_retries + 1} search failed: {e}")
1649
+ failed_count += 1
1650
+ if attempt < max_retries:
1651
+ logger.info(f"Trying next candidate (attempt {attempt + 2}/{max_retries + 1})...")
1652
+ continue
1653
+ else:
1654
+ logger.warning(
1655
+ f"Note: {failed_count} model(s) skipped due to errors. "
1656
+ f"To access gated models, provide a token via the 'token' parameter."
1657
+ )
1658
+ raise
1659
+
1660
+ checkpoint_path = hf_checkpoint_status.model_path # type: ignore
1661
+
1662
+ # Check the format of the model checkpoint and load pipeline
1663
+ try:
1664
+ if hf_checkpoint_status.loading_method == "from_single_file": # type: ignore
1665
+ # Load the pipeline from a single file checkpoint
1666
+ pipeline = load_pipeline_from_single_file(
1667
+ pretrained_model_or_path=checkpoint_path,
1668
+ pipeline_mapping=pipeline_mapping,
1669
+ **kwargs,
1670
+ )
1671
+ else:
1672
+ pipeline = cls.from_pretrained(checkpoint_path, **kwargs)
1673
+
1674
+ logger.info(
1675
+ f"checkpoint_path: {hf_checkpoint_status.model_status.download_url}" # type: ignore
1676
+ )
1677
+
1678
+ # Success - show warning if some candidates were skipped
1679
+ if failed_count > 0:
1680
+ logger.warning(
1681
+ f"Note: {failed_count} model(s) skipped due to errors. "
1682
+ f"To access gated models, provide a token via the 'token' parameter."
1683
+ )
1684
+
1685
+ return add_methods(pipeline)
1686
+
1687
+ except Exception as e:
1688
+ logger.info(f"Failed to load pipeline: {e}")
1689
+ failed_count += 1
1690
+ if attempt < max_retries:
1691
+ logger.info(f"Trying next candidate (attempt {attempt + 2}/{max_retries + 1})...")
1692
+ continue
1693
+ else:
1694
+ logger.warning(
1695
+ f"Note: {failed_count} model(s) skipped due to errors. "
1696
+ f"To access gated models, provide a token via the 'token' parameter."
1697
+ )
1698
+ raise
1699
+
1700
+
1077
1701
  def add_methods(pipeline):
1078
1702
  r"""
1079
1703
  Add methods from `AutoConfig` to the pipeline.
@@ -1444,26 +2068,15 @@ class EasyPipelineForText2Image(AutoPipelineForText2Image):
1444
2068
  }
1445
2069
  kwargs.update(_status)
1446
2070
 
1447
- # Search for the model on Hugging Face and get the model status
1448
- hf_checkpoint_status = search_huggingface(
1449
- pretrained_model_link_or_path, **kwargs
1450
- )
1451
- logger.warning(
1452
- f"checkpoint_path: {hf_checkpoint_status.model_status.download_url}" # type: ignore
2071
+ # Use the helper function to load the pipeline with retries
2072
+ kwargs['_max_retries'] = 9
2073
+ kwargs['_pipeline_tag'] = 'text-to-image'
2074
+ return _load_pipeline_with_retries(
2075
+ cls,
2076
+ pretrained_model_link_or_path,
2077
+ SINGLE_FILE_CHECKPOINT_TEXT2IMAGE_PIPELINE_MAPPING,
2078
+ **kwargs
1453
2079
  )
1454
- checkpoint_path = hf_checkpoint_status.model_path # type: ignore
1455
-
1456
- # Check the format of the model checkpoint
1457
- if hf_checkpoint_status.loading_method == "from_single_file": # type: ignore
1458
- # Load the pipeline from a single file checkpoint
1459
- pipeline = load_pipeline_from_single_file(
1460
- pretrained_model_or_path=checkpoint_path,
1461
- pipeline_mapping=SINGLE_FILE_CHECKPOINT_TEXT2IMAGE_PIPELINE_MAPPING,
1462
- **kwargs,
1463
- )
1464
- else:
1465
- pipeline = cls.from_pretrained(checkpoint_path, **kwargs)
1466
- return add_methods(pipeline)
1467
2080
 
1468
2081
  @classmethod
1469
2082
  def from_civitai(cls, pretrained_model_link_or_path, **kwargs):
@@ -1697,36 +2310,15 @@ class EasyPipelineForImage2Image(AutoPipelineForImage2Image):
1697
2310
  >>> image = pipeline(prompt, image).images[0]
1698
2311
  ```
1699
2312
  """
1700
- # Update kwargs to ensure the model is downloaded and parameters are included
1701
- _parmas = {
1702
- "download": True,
1703
- "include_params": True,
1704
- "skip_error": False,
1705
- "pipeline_tag": "image-to-image",
1706
- }
1707
- kwargs.update(_parmas)
1708
-
1709
- # Search for the model on Hugging Face and get the model status
1710
- hf_checkpoint_status = search_huggingface(
1711
- pretrained_model_link_or_path, **kwargs
2313
+ # Use the helper function to load the pipeline with retries
2314
+ kwargs['_max_retries'] = 9
2315
+ kwargs['_pipeline_tag'] = 'image-to-image'
2316
+ return _load_pipeline_with_retries(
2317
+ cls,
2318
+ pretrained_model_link_or_path,
2319
+ SINGLE_FILE_CHECKPOINT_IMAGE2IMAGE_PIPELINE_MAPPING,
2320
+ **kwargs
1712
2321
  )
1713
- logger.warning(
1714
- f"checkpoint_path: {hf_checkpoint_status.model_status.download_url}" # type: ignore
1715
- )
1716
- checkpoint_path = hf_checkpoint_status.model_path # type: ignore
1717
-
1718
- # Check the format of the model checkpoint
1719
- if hf_checkpoint_status.loading_method == "from_single_file": # type: ignore
1720
- # Load the pipeline from a single file checkpoint
1721
- pipeline = load_pipeline_from_single_file(
1722
- pretrained_model_or_path=checkpoint_path,
1723
- pipeline_mapping=SINGLE_FILE_CHECKPOINT_IMAGE2IMAGE_PIPELINE_MAPPING,
1724
- **kwargs,
1725
- )
1726
- else:
1727
- pipeline = cls.from_pretrained(checkpoint_path, **kwargs)
1728
-
1729
- return add_methods(pipeline)
1730
2322
 
1731
2323
  @classmethod
1732
2324
  def from_civitai(cls, pretrained_model_link_or_path, **kwargs):
@@ -1960,35 +2552,15 @@ class EasyPipelineForInpainting(AutoPipelineForInpainting):
1960
2552
  >>> image = pipeline(prompt, image=init_image, mask_image=mask_image).images[0]
1961
2553
  ```
1962
2554
  """
1963
- # Update kwargs to ensure the model is downloaded and parameters are included
1964
- _status = {
1965
- "download": True,
1966
- "include_params": True,
1967
- "skip_error": False,
1968
- "pipeline_tag": "image-to-image",
1969
- }
1970
- kwargs.update(_status)
1971
-
1972
- # Search for the model on Hugging Face and get the model status
1973
- hf_checkpoint_status = search_huggingface(
1974
- pretrained_model_link_or_path, **kwargs
1975
- )
1976
- logger.warning(
1977
- f"checkpoint_path: {hf_checkpoint_status.model_status.download_url}" # type: ignore
2555
+ # Use the helper function to load the pipeline with retries
2556
+ kwargs['_max_retries'] = 9
2557
+ kwargs['_pipeline_tag'] = 'inpainting'
2558
+ return _load_pipeline_with_retries(
2559
+ cls,
2560
+ pretrained_model_link_or_path,
2561
+ SINGLE_FILE_CHECKPOINT_INPAINT_PIPELINE_MAPPING,
2562
+ **kwargs
1978
2563
  )
1979
- checkpoint_path = hf_checkpoint_status.model_path # type: ignore
1980
-
1981
- # Check the format of the model checkpoint
1982
- if hf_checkpoint_status.loading_method == "from_single_file": # type: ignore
1983
- # Load the pipeline from a single file checkpoint
1984
- pipeline = load_pipeline_from_single_file(
1985
- pretrained_model_or_path=checkpoint_path,
1986
- pipeline_mapping=SINGLE_FILE_CHECKPOINT_INPAINT_PIPELINE_MAPPING,
1987
- **kwargs,
1988
- )
1989
- else:
1990
- pipeline = cls.from_pretrained(checkpoint_path, **kwargs)
1991
- return add_methods(pipeline)
1992
2564
 
1993
2565
  @classmethod
1994
2566
  def from_civitai(cls, pretrained_model_link_or_path, **kwargs):