
    +h2:                         S SK r S SKJrJrJrJrJrJrJr  S SK	r	S SK
Jr  S SKJr  SSKJr  SSKJrJr  \(       a  SSKJr  S	r\" \5      r " S
 S\\5      rSS jrg)    N)TYPE_CHECKINGAnyDictListOptionalTupleUnion)validate_hf_hub_args)Self   )ConfigMixin)PushToHubMixin
get_logger
BlockStatezguider_config.jsonc                   v   \ rS rSrSr\rSrSrS'S\	S\	4S jjr
S rS	 rS
\S\S\R                  SS4S jrS\\\\\\\4   4   4   SS4S jrS\R,                  R.                  SS4S jrS\R,                  R.                  SS4S jrSSS\S   4S jrS\S   S\4S jrS\4S jr\S\ 4S j5       r!\S\ 4S j5       r"\S\4S j5       r#\$S\\\\\\\4   4   4   SSS\S\SS4
S j5       r%\$\&   S(S \'\\\(RR                  4      S!\'\   S\*4S" jj5       5       r+S)S#\\\(RR                  4   S$\ 4S% jjr,S&r-g)*BaseGuidance$   zGBase class providing the skeleton for implementing guidance techniques.N__guidance_identifier__startstopc                 Z   Xl         X l        S U l        S U l        S U l        SU l        S U l        SU l        SUs=::  a  S:  d  O  [        SU S35      eXs=::  a  S::  d  O  [        SU SU S35      eU R                  b  [        U R                  [        5      (       d  [        S	5      eg )
Nr   T              ?z4Expected `start` to be between 0.0 and 1.0, but got .zExpected `stop` to be between z and 1.0, but got z\`_input_predictions` must be a list of required prediction names for the guidance technique.)_start_stop_step_num_inference_steps	_timestep_count_prepared_input_fields_enabled
ValueError_input_predictions
isinstancelist)selfr   r   s      X/home/james-whalen/.local/lib/python3.13/site-packages/diffusers/guiders/guider_utils.py__init__BaseGuidance.__init__+   s    

)-!+/ EIu"s"STYSZZ[\]]$$=eWDVW[V\\]^__""**T=T=TVZ2[2[n  3\    c                     SU l         g )NFr#   r(   s    r)   disableBaseGuidance.disable?   s	    r,   c                     SU l         g )NTr.   r/   s    r)   enableBaseGuidance.enableB   s	    r,   stepnum_inference_stepstimestepreturnc                 6    Xl         X l        X0l        SU l        g )Nr   )r   r   r    r!   )r(   r5   r6   r7   s       r)   	set_stateBaseGuidance.set_stateE   s    
$7!! r,   kwargsc                 4   UR                  5        H~  u  p#[        U[        5      n[        U[        5      =(       a'    [	        U5      S:H  =(       a    [        S U 5       5      nU(       a  M\  U(       a  Me  [        S[        U5       SU S35      e   Xl        g)a  
Set the input fields for the guidance technique. The input fields are used to specify the names of the returned
attributes containing the prepared data after `prepare_inputs` is called. The prepared data is obtained from
the values of the provided keyword arguments to this method.

Args:
    **kwargs (`Dict[str, Union[str, Tuple[str, str]]]`):
        A dictionary where the keys are the names of the fields that will be used to store the data once it is
        prepared with `prepare_inputs`. The values can be either a string or a tuple of length 2, which is used
        to look up the required data provided for preparation.

        If a string is provided, it will be used as the conditional data (or unconditional if used with a
        guidance method that requires it). If a tuple of length 2 is provided, the first element must be the
        conditional data identifier and the second element must be the unconditional data identifier or None.

        Example:
        ```
        data = {"prompt_embeds": <some tensor>, "negative_prompt_embeds": <some tensor>, "latents": <some tensor>}

        BaseGuidance.set_input_fields(
            latents="latents",
            prompt_embeds=("prompt_embeds", "negative_prompt_embeds"),
        )
        ```
r   c              3   B   #    U  H  n[        U[        5      v   M     g 7fN)r&   str).0vs     r)   	<genexpr>0BaseGuidance.set_input_fields.<locals>.<genexpr>h   s     Dgaf\]ZPQSVEWEWafs   zcExpected `set_input_fields` to be called with a string or a tuple of string with length 2, but got z	 for key r   N)	itemsr&   r@   tuplelenallr$   typer"   )r(   r<   keyvalue	is_stringis_tuple_of_str_with_len_2s         r)   set_input_fieldsBaseGuidance.set_input_fieldsK   s    4 !,,.JC"5#.I5%(gSZ1_gDgafDgAg ' I!;!; yz~  @E  {F  zG  GP  QT  PU  UV  W  ) $r,   denoiserc                 .    U =R                   S-  sl         g)z
Prepares the models for the guidance technique on a given batch of data. This method should be overridden in
subclasses to implement specific model preparation logic.
   N)r!   r(   rP   s     r)   prepare_modelsBaseGuidance.prepare_modelsp   s    
 	!r,   c                     g)a
  
Cleans up the models for the guidance technique after a given batch of data. This method should be overridden
in subclasses to implement specific model cleanup logic. It is useful for removing any hooks or other stateful
modifications made during `prepare_models`.
N rS   s     r)   cleanup_modelsBaseGuidance.cleanup_modelsw   s     	r,   datar   c                     [        S5      e)Nz?BaseGuidance::prepare_inputs must be implemented in subclasses.NotImplementedError)r(   rZ   s     r)   prepare_inputsBaseGuidance.prepare_inputs   s    !"cddr,   c                 P   [        S U 5       5      (       d  [        S5      e[        U5      U R                  :w  a%  [        SU R                   S[        U5       S35      eU Vs0 s H#  n[	        X R
                  5      UR                  _M%     nnU R                  " S0 UD6$ s  snf )Nc              3   :   #    U  H  n[        US 5      v   M     g7f)
noise_predN)hasattr)rA   ds     r)   rC   (BaseGuidance.__call__.<locals>.<genexpr>   s     :T71l++Ts   z1Expected all data to have `noise_pred` attribute.z	Expected z data items, but got z. Please check the input data.rW   )rH   r$   rG   num_conditionsgetattr_identifier_keyrb   forward)r(   rZ   rd   forward_inputss       r)   __call__BaseGuidance.__call__   s    :T:::PQQt9+++D//00Ec$i[Pno  SWWRVQ'!%9%9:ALLHRVW||-n-- Xs   %*B#c                     [        S5      e)Nz8BaseGuidance::forward must be implemented in subclasses.r\   )r(   argsr<   s      r)   ri   BaseGuidance.forward   s    !"\]]r,   c                     [        S5      e)Nz?BaseGuidance::is_conditional must be implemented in subclasses.r\   r/   s    r)   is_conditionalBaseGuidance.is_conditional       !"cddr,   c                 $    U R                   (       + $ r?   )rq   r/   s    r)   is_unconditionalBaseGuidance.is_unconditional   s    &&&&r,   c                     [        S5      e)Nz?BaseGuidance::num_conditions must be implemented in subclasses.r\   r/   s    r)   rf   BaseGuidance.num_conditions   rs   r,   input_fieldstuple_index
identifierc                 x   SSK Jn  Uc  [        S5      e0 nUR                  5        HQ  u  px [	        U[
        5      (       a  [        X(5      Xg'   M*  [	        U[        5      (       a  [        X(U   5      Xg'   MQ  MS     XFU R                  '   U" S0 UD6$ ! [         a    [        R                  SU S35         M  f = f)a=  
Prepares a batch of data for the guidance technique. This method is used in the `prepare_inputs` method of the
`BaseGuidance` class. It prepares the batch based on the provided tuple index.

Args:
    input_fields (`Dict[str, Union[str, Tuple[str, str]]]`):
        A dictionary where the keys are the names of the fields that will be used to store the data once it is
        prepared with `prepare_inputs`. The values can be either a string or a tuple of length 2, which is used
        to look up the required data provided for preparation. If a string is provided, it will be used as the
        conditional data (or unconditional if used with a guidance method that requires it). If a tuple of
        length 2 is provided, the first element must be the conditional data identifier and the second element
        must be the unconditional data identifier or None.
    data (`BlockState`):
        The input data to be prepared.
    tuple_index (`int`):
        The index to use when accessing input fields that are tuples.

Returns:
    `BlockState`: The prepared batch of data.
r   r   zInput fields cannot be None. Please pass `input_fields` to `prepare_inputs` or call `set_input_fields` before preparing inputs.z"`data` does not have attribute(s) z, skipping.rW   )"modular_pipelines.modular_pipeliner   r$   rE   r&   r@   rg   rF   AttributeErrorloggerdebugrh   )	clsry   rZ   rz   r{   r   
data_batchrJ   rK   s	            r)   _prepare_batchBaseGuidance._prepare_batch   s    8 	D R  
&,,.JC	VeS))&-d&:JOu--&-d+4F&GJO  / +53&&''J'' " VA%TUVs   "B%B#B98B9pretrained_model_name_or_path	subfolderc                 `    U R                   " SUUSSS.UD6u  pTnU R                  " U4SU0UD6$ )a	  
Instantiate a guider from a pre-defined JSON configuration file in a local directory or Hub repository.

Parameters:
    pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
        Can be either:

            - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
              the Hub.
            - A path to a *directory* (for example `./my_model_directory`) containing the guider configuration
              saved with [`~BaseGuidance.save_pretrained`].
    subfolder (`str`, *optional*):
        The subfolder location of a model file within a larger model repository on the Hub or locally.
    return_unused_kwargs (`bool`, *optional*, defaults to `False`):
        Whether kwargs that are not consumed by the Python class should be returned or not.
    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.
    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.

    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.
    output_loading_info(`bool`, *optional*, defaults to `False`):
        Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
    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.

<Tip>

To use private or [gated models](https://huggingface.co/docs/hub/models-gated#gated-models), log-in with `hf
auth login`. You can also activate the special
["offline-mode"](https://huggingface.co/diffusers/installation.html#offline-mode) to use this method in a
firewalled environment.

</Tip>

T)r   r   return_unused_kwargsreturn_commit_hashr   rW   )load_configfrom_config)r   r   r   r   r<   configcommit_hashs          r)   from_pretrainedBaseGuidance.from_pretrained   sP    p '*oo '
*G!%#	'

 '
# v[<P[TZ[[r,   save_directorypush_to_hubc                 ,    U R                   " SXS.UD6  g)a  
Save a guider configuration object to a directory so that it can be reloaded using the
[`~BaseGuidance.from_pretrained`] class method.

Args:
    save_directory (`str` or `os.PathLike`):
        Directory where the configuration JSON file will be saved (will be created if it does not exist).
    push_to_hub (`bool`, *optional*, defaults to `False`):
        Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the
        repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
        namespace).
    kwargs (`Dict[str, Any]`, *optional*):
        Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
)r   r   NrW   )save_config)r(   r   r   r<   s       r)   save_pretrainedBaseGuidance.save_pretrained  s     	ZZSYZr,   )r!   r#   r"   r   r   r   r   r    )r   r   )NNF)F).__name__
__module____qualname____firstlineno____doc__GUIDER_CONFIG_NAMEconfig_namer%   rh   floatr*   r0   r3   inttorch
LongTensorr:   r   r@   r	   r   rN   nnModulerT   rX   r   r^   r   rk   ri   propertyboolrq   ru   rf   classmethodr   r
   r   osPathLiker   r   r   __static_attributes__rW   r,   r)   r   r   $   sG   R$K/Oe  (!c ! !uGWGW !\` !#$c5eCHo9M3N.N)O #$TX #$J"uxx "4 "uxx 4 e< eD4F e.T,/ .C .^# ^ e e e '$ ' ' e e e .(3c5c?&: ;;<.( .( 	.(
 .( 
.( .(`  LP#'"	=\'/c2;;6F0G'H=\ C==\ 
=\  =\~[eC4D.E [TX [ [r,   r   c                     UR                  [        [        SUR                  5      5      SS9nU R                  [        [        SU R                  5      5      SS9nXU-  -  nX%-  SU-
  U -  -   n U $ )a  
Rescales `noise_cfg` tensor based on `guidance_rescale` to improve image quality and fix overexposure. Based on
Section 3.4 from [Common Diffusion Noise Schedules and Sample Steps are
Flawed](https://arxiv.org/pdf/2305.08891.pdf).

Args:
    noise_cfg (`torch.Tensor`):
        The predicted noise tensor for the guided diffusion process.
    noise_pred_text (`torch.Tensor`):
        The predicted noise tensor for the text-guided diffusion process.
    guidance_rescale (`float`, *optional*, defaults to 0.0):
        A rescale factor applied to the noise predictions.
Returns:
    noise_cfg (`torch.Tensor`): The rescaled noise prediction tensor.
rR   T)dimkeepdim)stdr'   rangendim)	noise_cfgnoise_pred_textguidance_rescalestd_textstd_cfgnoise_pred_rescaleds         r)   rescale_noise_cfgr     s{      ""tE!_5I5I,J'KUY"ZHmmU1inn%= >mMG#''9: 6!>N:NR[9[[Ir,   )r   )r   typingr   r   r   r   r   r   r	   r   huggingface_hub.utilsr
   typing_extensionsr   configuration_utilsr   utilsr   r   r}   r   r   r   r   r   r   rW   r,   r)   <module>r      sV    
 I I I  6 " - . ? *  
H	x[; x[vr,   