
    iF                         d dl Z d dlmZmZmZmZmZmZmZ d dl	Z	d dl
mZ d dlmZ ddlmZ ddlmZmZmZ erddlmZ d	Z ee      Z G d
 dee      Z G d de      ZddZy)    N)TYPE_CHECKINGAnyDictListOptionalTupleUnion)validate_hf_hub_args)Self   )ConfigMixin)
BaseOutputPushToHubMixin
get_logger
BlockStatezguider_config.jsonc                       e Zd ZdZeZdZdZd)dedede	fdZ
d Zd	 Zd
 Zdededej                   ddfdZdeeef   fdZdef fdZdej.                  j0                  ddfdZdej.                  j0                  ddfdZddded   fdZdddeeeeeeef   f   f   ded   fdZded   defdZ defdZ!e"de	fd       Z#e"de	fd       Z$e"defd       Z%e&deeeejN                  ejN                  f   f   ded eddfd!       Z(e&deeeeeeef   f   f   ddded eddf
d"       Z)e&e*	 	 	 d*d#e+eee,jZ                  f      d$e+e   de.fd%              Z/d+d&eee,jZ                  f   d'e	fd(Z0 xZ1S ),BaseGuidancezGBase class providing the skeleton for implementing guidance techniques.N__guidance_identifier__startstopenabledc                 v   t         j                  d       || _        || _        d | _        d | _        d | _        d| _        d | _        || _	        d|cxk  rdk  sn t        d| d      ||cxk  rdk  sn t        d| d| d      | j                  t        | j                  t              st        d	      y )
NzGuiders are currently an experimental feature under active development. The API is subject to breaking changes in future releases.r                 ?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.)loggerwarning_start_stop_step_num_inference_steps	_timestep_count_prepared_input_fields_enabled
ValueError_input_predictions
isinstancelist)selfr   r   r   s       h/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/diffusers/guiders/guider_utils.py__init__zBaseGuidance.__init__+   s     Q	
 

)-!+/ EIu"s"STYSZZ[\]]$$=eWDVW[V\\]^__""**T=T=TVZ2[n  3\    c                 P     | j                   j                  | j                  fi |S )a  
        Creates a copy of this guider instance, optionally with modified configuration parameters.

        Args:
            **kwargs: Configuration parameters to override in the new instance. If no kwargs are provided,
                returns an exact copy with the same configuration.

        Returns:
            A new guider instance with the same (or updated) configuration.

        Example:
            ```python
            # Create a CFG guider
            guider = ClassifierFreeGuidance(guidance_scale=3.5)

            # Create an exact copy
            same_guider = guider.new()

            # Create a copy with different start step, keeping other config the same
            new_guider = guider.new(guidance_scale=5)
            ```
        )	__class__from_configconfig)r+   kwargss     r,   newzBaseGuidance.newC   s$    . *t~~))$++@@@r.   c                     d| _         y )NFr&   r+   s    r,   disablezBaseGuidance.disable\   s	    r.   c                     d| _         y )NTr6   r7   s    r,   enablezBaseGuidance.enable_   s	    r.   stepnum_inference_stepstimestepreturnc                 <    || _         || _        || _        d| _        y )Nr   )r!   r"   r#   r$   )r+   r;   r<   r=   s       r,   	set_statezBaseGuidance.set_stateb   s     
$7!! r.   c                     | j                   | j                  | j                  | j                  | j                  | j
                  d}|S )an  
        Returns the current state of the guidance technique as a dictionary. The state variables will be included in
        the __repr__ method. Returns:
            `Dict[str, Any]`: A dictionary containing the current state variables including:
                - step: Current inference step
                - num_inference_steps: Total number of inference steps
                - timestep: Current timestep tensor
                - count_prepared: Number of times prepare_models has been called
                - enabled: Whether the guidance is enabled
                - num_conditions: Number of conditions
        )r;   r<   r=   count_preparedr   num_conditions)r!   r"   r#   r$   r&   rC   )r+   states     r,   	get_statezBaseGuidance.get_stateh   sB     JJ#'#<#<"22}}"11
 r.   c           	      x   t         
|          }| j                         }g }|j                         D ]j  \  }}t	        |      }d|v r?|j                  d      }|d   dz   dj                  |dd D cg c]  }d|z   	 c}      z   }|j                  d| d|        l dj                  |      }	| d|	 S c c}w )	zq
        Returns a string representation of the guidance object including both config and current state.
        
r      Nz    z  z: z
State:
)super__repr__rE   itemsstrsplitjoinappend)r+   str_reprrD   state_lineskvv_strv_linesline	state_strr0   s             r,   rJ   zBaseGuidance.__repr__~   s    
 7#%   KKM 	2DAqFEu}++d+
T)DIIQXYZY[Q\6]v}6],^^A3b01	2 IIk*	:i[11 7^s   1B7denoiserc                 .    | xj                   dz  c_         y)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.
        rH   N)r$   r+   rX   s     r,   prepare_modelszBaseGuidance.prepare_models   s    
 	!r.   c                      y)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 rZ   s     r,   cleanup_modelszBaseGuidance.cleanup_models   s     	r.   datar   c                     t        d      )Nz?BaseGuidance::prepare_inputs must be implemented in subclasses.NotImplementedError)r+   r_   s     r,   prepare_inputszBaseGuidance.prepare_inputs   s    !"cddr.   input_fieldsc                     t        d      )NzPBaseGuidance::prepare_inputs_from_block_state must be implemented in subclasses.ra   )r+   r_   rd   s      r,   prepare_inputs_from_block_statez,BaseGuidance.prepare_inputs_from_block_state   s     ""tuur.   c                 @   t        d |D              st        d      t        |      | j                  k7  r%t        d| j                   dt        |       d      |D ci c]#  }t	        || j
                        |j                  % }} | j                  di |S c c}w )Nc              3   4   K   | ]  }t        |d         yw)
noise_predN)hasattr).0ds     r,   	<genexpr>z(BaseGuidance.__call__.<locals>.<genexpr>   s     :71l+:s   z1Expected all data to have `noise_pred` attribute.z	Expected z data items, but got z. Please check the input data.r]   )allr'   lenrC   getattr_identifier_keyri   forward)r+   r_   rl   forward_inputss       r,   __call__zBaseGuidance.__call__   s    :T::PQQt9+++D//00Ec$i[Pno  SWWQ'!T%9%9:ALLHWWt||-n-- Xs   (Bc                     t        d      )Nz8BaseGuidance::forward must be implemented in subclasses.ra   )r+   argsr3   s      r,   rr   zBaseGuidance.forward   s    !"\]]r.   c                     t        d      )Nz?BaseGuidance::is_conditional must be implemented in subclasses.ra   r7   s    r,   is_conditionalzBaseGuidance.is_conditional       !"cddr.   c                     | j                    S )N)rx   r7   s    r,   is_unconditionalzBaseGuidance.is_unconditional   s    &&&&r.   c                     t        d      )Nz?BaseGuidance::num_conditions must be implemented in subclasses.ra   r7   s    r,   rC   zBaseGuidance.num_conditions   ry   r.   tuple_index
identifierc                 b   ddl m} i }|j                         D ]V  \  }}	 t        |t        j
                        r|||<   n0t        |t              r	||   ||<   nt        dt        |             X ||| j                  <    |di |S # t        $ r t        j                  d| d       Y w xY w)  
        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Invalid value type: "`data` does not have attribute(s) , skipping.r]   )"modular_pipelines.modular_pipeliner   rK   r)   torchTensortupler'   typer   debugrq   )clsr_   r}   r~   r   
data_batchkeyvalues           r,   _prepare_batchzBaseGuidance._prepare_batch   s    6 	D
**, 		VJCVeU\\2&+JsOu-&+K&8JsO$';DK=%IJJ		V +5
3&&''J''  VA%TUVs   AB		"B.-B.c                 J   ddl m} i }|j                         D ]J  \  }}	 t        |t              rt        ||      ||<   n$t        |t              rt        |||         ||<   n	 L ||| j                  <    |di |S # t        $ r t        j                  d| d       Y w xY w)r   r   r   r   r   r]   )r   r   rK   r)   rL   rp   r   AttributeErrorr   r   rq   )	r   rd   r_   r}   r~   r   r   r   r   s	            r,   _prepare_batch_from_block_statez,BaseGuidance._prepare_batch_from_block_state   s    8 	D
&,,. 
	VJC	VeS)&-dE&:JsOu-&-dE+4F&GJsO 
	V +5
3&&''J'' " VA%TUVs   AA=="B"!B"pretrained_model_name_or_path	subfolderc                 b     | j                   d||ddd|\  }}} | j                  |fd|i|S )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.

        T)r   r   return_unused_kwargsreturn_commit_hashr   r]   )load_configr1   )r   r   r   r   r3   r2   commit_hashs          r,   from_pretrainedzBaseGuidance.from_pretrained  sV    h '6coo '
*G!%#	'

 '
# sv[<P[TZ[[r.   save_directorypush_to_hubc                 .     | j                   d||d| y)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   Nr]   )save_config)r+   r   r   r3   s       r,   save_pretrainedzBaseGuidance.save_pretrained\  s     	ZKZSYZr.   )r   r   T)NNF)F)2__name__
__module____qualname____doc__GUIDER_CONFIG_NAMEconfig_namer(   rq   floatboolr-   r4   r8   r:   intr   
LongTensorr@   r   rL   r   rE   rJ   nnModuler[   r^   r   rc   r	   r   rf   rt   rr   propertyrx   r{   rC   classmethodr   r   r   r
   r   osPathLiker   r   r   __classcell__)r0   s   @r,   r   r   $   s   R$K/Oe  t 0A2!c ! !uGWGW !\` !4S> ,2# 22"uxx "4 "uxx 4 e< eD4F ev v04S%U3PS8_@T:U5U0Vv	l	v
.T,/ .C .^# ^ e e e '$ ' ' e e e ((3ellELL899:(( (( 	((
 
(( ((T *(3c5c?&: ;;<*( *( 	*(
 *( 
*( *(X  LP#'"	9\'/c2;;6F0G'H9\ C=9\ 
9\  9\v[eC4D.E [TX [r.   r   c                   t    e Zd ZU ej                  ed<   eej                     ed<   eej                     ed<   y)GuiderOutputpred	pred_condpred_uncondN)r   r   r   r   r   __annotations__r   r]   r.   r,   r   r   n  s*    
,,%%%,,''r.   r   c                     |j                  t        t        d|j                              d      }| j                  t        t        d| j                              d      }| ||z  z  }||z  d|z
  | z  z   } | S )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://huggingface.co/papers/2305.08891).

    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.
    rH   T)dimkeepdim)stdr*   rangendim)	noise_cfgnoise_pred_textguidance_rescalestd_textstd_cfgnoise_pred_rescaleds         r,   rescale_noise_cfgr   t  s      ""tE!_5I5I,J'KUY"ZHmmU1inn%= >mMG#x''9: #6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   r   r   r]   r.   r,   <module>r      se    
 I I I  6 " - : : ? *  
H	G[; G[T
(: (r.   