
    bia                     8   d dl Z d dlZd dlZd dlZd dlmZ d dlmZmZ d dl	m
Z
 d dlmZ ddlmZmZmZ dd	lmZmZmZmZmZmZmZmZmZmZmZmZmZ  ej>                  e       Z!d
gZ" e       rd dl#Z#d dl#m$Z$m%Z% 	 	 	 	 	 ddZ&d Z'd Z(	 	 	 ddZ) G d d      Z*y)    Nsnapshot_download)LocalEntryNotFoundErrorvalidate_hf_hub_args)version)Self   )	deprecateis_transformers_availablelogging   )SingleFileComponentError_is_legacy_scheduler_kwargs"_is_model_weights_in_cached_folder_legacy_load_clip_tokenizer_legacy_load_safety_checker_legacy_load_scheduler$create_diffusers_clip_model_from_ldm)create_diffusers_t5_model_from_checkpointfetch_diffusers_configfetch_original_configis_clip_model_in_single_fileis_t5_in_single_fileload_single_file_checkpointsafety_checker)PreTrainedModelPreTrainedTokenizerc                 N   |rt        ||       }t        ||      }n!t        j                  |       }t        ||      }t               rAt	        j
                  t	        j
                  t        j                        j                        }nd}t               xr* t        |t              xr |t	        j
                  d      k\  }t               xr* t        |t              xr |t	        j
                  d      k\  }t        j                  t        j                  d      d         }t        ||j                        }t        ||j                        }t        ||j                         }|r"t        |d      }|rd } |d|||||	||d|}|S |r t#        ||      rt%        |||||	||
      }|S |rt'        |      rt)        |||||	|      }|S |r|
rt+        ||||	      }|S |r|
st-        |      rt/        |f|||d
|}|S t1        |d      st3        d|j                   d      i }|j5                  |||d       t        |t6        j8                  j:                        r|j5                  d|	i       |s|rt=        ||      st?        d| d      t        |d      } |di |}|S )NN/A4.20.0.r   from_single_file)%pretrained_model_link_or_path_or_dictoriginal_configconfig	subfoldertorch_dtypelocal_files_onlydisable_mmap)
checkpointr%   r&   r'   r(   is_legacy_loading)r*   r%   r&   r'   r(   )r*   r%   r(   )r*   component_namer$   from_pretrainedzThe component zI cannot be loaded as it does not seem to have a supported loading method.)pretrained_model_name_or_pathr&   r(   r'   zFailed to load zD. Weights for this component appear to be missing in the checkpoint. ) getattr	importlibimport_moduler   r   parsetransformers__version__base_version
issubclassr   r   __name__splitFromOriginalModelMixin
ModelMixinSchedulerMixinr   r   r   r   r   r   r   hasattr
ValueErrorupdatetorchnnModuler   r   )library_name
class_namenamer*   	pipelinesis_pipeline_modulecached_model_config_pathr$   r(   r'   r+   r)   kwargspipeline_module	class_objlibrarytransformers_versionis_transformers_modelis_tokenizerdiffusers_moduleis_diffusers_single_file_modelis_diffusers_modelis_diffusers_schedulerload_methodloaded_sub_modelloading_kwargss                             X/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/loaders/single_file.pyload_single_file_sub_modelrX   4   s     !)\:OZ8	 )),7GZ0	 "&}}W]]<;S;S-T-a-ab$ 	"# 	<y/2	< GMM($;;  	"# 	<y"56	< GMM($;;  !..x~~c/B1/EF%/	;K;b;b%c"#I/?/J/JK'	3C3R3RS%i);< '+$& 	
2<++#-%	
 	
T  
#?	:#V?!+#-/
| i 
#7
#CD!+#-
f U 
+6*5M`p
R K 
 %6:UV\:]1
",TSb
fl
H ? y"34$Y%7%7$8 93 3  1I!$4	
 i1!!=+">?!656NPTU.%j\1uv  i):;&88    c                    t        j                  t        j                  d      d         }i }| j	                  dd        t               rAt        j                  t        j                  t        j                        j                        }nd}| j                         D ]+  \  }}t        |d   |j                        }|d   j                  dk(  }t        |d   |j                        }t               xr- t        |d   t              xr |t        j                  d      k\  }	t               xr- t        |d   t               xr |t        j                  d      k\  }
|r|t"        vrd|d   j                  g||<   |s|r#|rddg||<   |sd|d   j                  g||<   |	s|
r|t"        vrd	|d   j                  g||<   %d d g||<   . |S )
Nr!   r   selfr   KarrasDiffusionSchedulersr    	diffusersDDIMSchedulerr4   )r1   r2   r8   r9   popr   r   r3   r4   r5   r6   itemsr7   r;   r<   r   r   SINGLE_FILE_OPTIONAL_COMPONENTS)component_typesrP   config_dictrM   r,   component_valuerR   is_scheduler_enumis_schedulerrN   is_transformers_tokenizers              rW   #_map_component_types_to_config_dictrh      s    ..x~~c/B1/EFK% "&}}W]]<;S;S-T-a-ab$+:+@+@+B "7''(:<L<W<WX+A.77;VV!/!"46F6U6UV &' @?1-?@$h(?? 	 &' @?1-/BC@$h(?? 	" .8W"W+68J8S8S*TK',  0;O.LN+/:OA<N<W<W.XN+ "%>$CC+9?1;M;V;V*WK' ,0,K'E"7H rY   c                 x   t        j                  | j                        j                  }|j	                         D ci c]&  \  }}|j
                  t         j                  k(  s$||( }}}| j                         }|j	                         D ci c]  \  }}||v s|| }}}t        |      }|S c c}}w c c}}w )N)	inspect	signature__init__
parametersr`   default_empty_get_signature_typesrh   )pipeline_classrm   kvrequired_parametersrb   rc   s          rW   _infer_pipeline_config_dictru      s    "">#:#:;FFJ,6,<,<,>^DAq!))w~~B]1a4^^$99;O )8(=(=(?\11H[C[q!t\O\5oFK _ ]s   %B0#B0B6B6c           
      4    g d}t        | |||||||      }|S )N)z	**/*.jsonz*.jsonz*.txtz**/*.txtz
**/*.model)	cache_dirrevisionproxiesforce_downloadr(   tokenallow_patternsr   )	r.   rw   rx   ry   rz   r(   r{   r|   cached_model_paths	            rW   )_download_diffusers_model_config_from_hubr~      s5     PN)%%)%	 rY   c                   0    e Zd ZdZeedefd              Zy)FromSingleFileMixinzV
    Load model weights saved in the `.ckpt` format into a [`DiffusionPipeline`].
    returnc                 
  / |j                  dd      }|j                  dd      }|j                  dd      }|d}t        dd|       |}|j                  dd      }|j                  d	d      }|j                  d
d      }	|j                  dd      }
|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }d}|Ct        |t        j                        s)t        j
                  }t        j                  d| d       |j                  dd      }|d}t        dd|       |t        ||      }ddl
m}  || d      }t        ||||	|
|||      }|t        |      }|d   }n|}t        j                  j!                  |      sH|j#                  d      dkD  rt%        d| d      	 t'        ||
|||||	      }|j)                  |      }n|}|j)                  |      }|j                  d#d       |j1                  |       \  }}|D ci c]  }||v s||j                  |       c}/|D ci c]  }||v s||j                  |       }} |j2                  |fi |\  }}}|D ci c]  }||v s||j                  |       }}i ||}d$d%lm} /fd&} |j9                         D !ci c]  \  }}! | ||!      s||! }}}!t;        j<                  t?        |j9                               d'(      D ]>  \  }"\  }#}$d}%tA        ||#      }&|"/v r/|"   }%n	 tC        d6|#|$|"||&|||||||d)|}%|%||"<   @ tI        |      tI        |jK                               z
  }(tM        /jK                               })|jN                  }*tQ        |(      d$kD  r.|(tI        |)|*z         k  r|(D ]  }+/j                  |+d      ||+<    nbtQ        |(      d$kD  rTtI        tM        |jK                               tM        /jK                               z         |z
  })t%        d0| d1| d2|) d3      |j                  d4d      },|,,d5}t        d4d|       tS        ||      }-|jU                  |-        |d6i |}.|.S # t*        $ rr |9t        j                  d       t'        ||
|||d|	      }|j)                  |      }n3t        j                  d        d!}d}t-        |      }|j.                  |d"<   Y w xY wc c}w c c}w c c}w c c}!}w # tD        $ r6}'tE        |'jF                   d*|" d+|$ d,|j.                   d-|" d.|" d/      d}'~'ww xY w)7a  
        Instantiate a [`DiffusionPipeline`] from pretrained pipeline weights saved in the `.ckpt` or `.safetensors`
        format. The pipeline is set in evaluation mode (`model.eval()`) by default.

        Parameters:
            pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
                Can be either:
                    - A link to the `.ckpt` file (for example
                      `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
                    - A path to a *file* containing all pipeline weights.
            torch_dtype (`str` or `torch.dtype`, *optional*):
                Override the default `torch.dtype` and load the model with another dtype.
            force_download (`bool`, *optional*, defaults to `False`):
                Whether or not to force the (re-)download of the model weights and configuration files, overriding the
                cached versions if they exist.
            cache_dir (`Union[str, os.PathLike]`, *optional*):
                Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
                is not used.

            proxies (`Dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
            local_files_only (`bool`, *optional*, defaults to `False`):
                Whether to only load local model weights and configuration files or not. If set to `True`, the model
                won't be downloaded from the Hub.
            token (`str` or *bool*, *optional*):
                The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
                `diffusers-cli login` (stored in `~/.huggingface`) is used.
            revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
                allowed by Git.
            original_config_file (`str`, *optional*):
                The path to the original config file that was used to train the model. If not provided, the config file
                will be inferred from the checkpoint file.
            config (`str`, *optional*):
                Can be either:
                    - A string, the *repo id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained pipeline
                      hosted on the Hub.
                    - A path to a *directory* (for example `./my_pipeline_directory/`) containing the pipeline
                      component configs in Diffusers format.
            disable_mmap ('bool', *optional*, defaults to 'False'):
                Whether to disable mmap when loading a Safetensors model. This option can perform better when the model
                is on a network mount or hard drive.
            kwargs (remaining dictionary of keyword arguments, *optional*):
                Can be used to overwrite load and saveable variables (the pipeline components of the specific pipeline
                class). The overwritten components are passed directly to the pipelines `__init__` method. See example
                below for more information.

        Examples:

        ```py
        >>> from diffusers import StableDiffusionPipeline

        >>> # Download pipeline from huggingface.co and cache.
        >>> pipeline = StableDiffusionPipeline.from_single_file(
        ...     "https://huggingface.co/WarriorMama777/OrangeMixs/blob/main/Models/AbyssOrangeMix/AbyssOrangeMix.safetensors"
        ... )

        >>> # Download pipeline from local file
        >>> # file is downloaded under ./v1-5-pruned-emaonly.ckpt
        >>> pipeline = StableDiffusionPipeline.from_single_file("./v1-5-pruned-emaonly.ckpt")

        >>> # Enable float16 and move to GPU
        >>> pipeline = StableDiffusionPipeline.from_single_file(
        ...     "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt",
        ...     torch_dtype=torch.float16,
        ... )
        >>> pipeline.to("cuda")
        ```

        original_config_fileNr%   r$   z`original_config_file` argument is deprecated and will be removed in future versions.please use the `original_config` argument instead.z1.0.0rz   Fry   r{   rw   r(   rx   r'   r)   zPassed `torch_dtype` z7 is not a `torch.dtype`. Defaulting to `torch.float32`.scaling_factorzpPassing the `scaling_factor` argument to `from_single_file is deprecated and will be ignored in future versions.)r(   r	   )_get_pipeline_class)r%   )rz   ry   r{   rw   r(   rx   r)   r.   /r   zThe provided config "zP" is neither a valid local path nor a valid repo id. Please check the parameter.)rw   rx   ry   rz   r(   r{   z`local_files_only` is True but no local configs were found for this checkpoint.
Attempting to download the necessary config files for this pipeline.
a-  Detected legacy `from_single_file` loading behavior. Attempting to create the pipeline based on inferred components.
This may lead to errors if the model components are not correctly inferred. 
To avoid this warning, please explicitly pass the `config` argument to `from_single_file` with a path to a local diffusers model repo 
e.g. `from_single_file(<my model checkpoint path>, config=<path to local diffusers model repo>) 
or run `from_single_file` with `local_files_only=False` first to update the local cache directory with the necessary config files.
T_class_name_ignore_filesr   )rF   c                 8    |d   y| v r|    y| t         v ryy)Nr   FT)ra   )rE   valuepassed_class_objs     rW   load_modulez9FromSingleFileMixin.from_single_file.<locals>.load_module  s6    Qx'',<T,B,J66rY   zLoading pipeline components...)desc)rC   rD   rE   r*   rG   rH   rF   r'   r$   r(   r+   r)   zW
Please load the component before passing it in as an argument to `from_single_file`.

z = z.from_pretrained('...')
pipe = z%.from_single_file(<checkpoint path>, =z)

z	Pipeline z
 expected z, but only z were passed.load_safety_checkerzPlease pass instances of `StableDiffusionSafetyChecker` and `AutoImageProcessor`using the `safety_checker` and `feature_extractor` arguments in `from_single_file`r/   )+r_   r
   
isinstancer@   dtypefloat32loggerwarninggetr   pipelines.pipeline_utilsr   r   r   ospathisdircountr>   r~   load_configr   ru   r8   _get_signature_keysextract_init_dictr]   rF   r`   r   tqdmsortedr=   rX   r   messagesetkeyslist_optional_componentslenr   r?   )0clspretrained_model_link_or_pathrI   r   r%   r$   deprecation_messagerz   ry   r{   rw   r(   rx   r'   r)   r+   r   r   rq   r*   $default_pretrained_model_config_namerH   rc   expected_modulesoptional_kwargsrr   passed_pipe_kwargs	init_dictunused_kwargs_init_kwargsrF   r   rs   rE   rC   rD   rU   rG   emissing_modulespassed_modulesoptional_modulesmoduler   safety_checker_componentspiper   s0                                                  @rW   r"   z$FromSingleFileMixin.from_single_file  sn   T  &zz*@$GHd+ **%6=+E   ,g7JK2O$4e<**Y-

7D)JJ{D1	!::&8%@::j$/jj5zz.%8!":k5;;+O--KNN'}4kl  $4d;%:   &1DE&3OVfgOB,S>0))-%	

 >+J7F39:Y3Z0390ww}}AB399#>B +F8 4f f 2I+T8'%##1%5,( -889QRV (L$(445MNK 	.,:,N,Ns,S)/6FV!v+Avzz!},V8GW11PV;aA.WW&Fn&F&F{&]V\&]#	=!4CVqqI~q)--**VV;;(:;'	 '0oo&7Mda;q!;LQTM	M079??$%,L1
 &	1,D,<  $!(L!A''#3D#9 'A (%1#-!#-+=1I"+$/(7)9*;%1( !($6 !1KM&	1P ./#k6F6F6H2II.3356)>>!#3~P`?`;a(a) I&6&:&:64&HF#I!A% k&6&6&8!9DAQAVAVAX<Y!YZ]llNN+:6F5G{SaRbbop 
 %jj)>E*e   +W6IJ(CDTVa(b%89,,S + %I #*NNa 0Y<"+!) ''5).#0, #1"<"<=U"VK
 NN8 )-%/3,"=n"MK1?1H1HK.K%I` WW W  N8 0 
2 yyk *!  $fC
| 4&&4&=&=%>>cdhciijkojp q!	"	 	
s[   #R 0	T:T	TT	TTT&T>T"A7T
	T
"	U!+1UU!N)r8   
__module____qualname____doc__classmethodr   r   r"   r/   rY   rW   r   r   
  s-     d$ d  drY   r   )NFNFF)NNN)+r1   rj   r   r@   huggingface_hubr   huggingface_hub.utilsr   r   	packagingr   typing_extensionsr   utilsr
   r   r   single_file_utilsr   r   r   r   r   r   r   r   r   r   r   r   r   
get_loggerr8   r   ra   r4   r   r   rX   rh   ru   r~   r   r/   rY   rW   <module>r      s      	  - O  " A A   " 
		H	% $4"4 A ~B.b	" 
0k krY   