
    bii                        d dl Z d dlZd dlZd dlmZmZmZmZm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 dd	lmZ dd
lmZmZ ddlmZmZ ddl m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&  e%       rd dl'm(Z( dZ) e&jT                  e+      Z,ddgddgddgdddgddgddgddgddgddgddZ-i Z.e-D ]  Z/e.ja                  e-e/           d Z1e	jd                  jf                   G d de"             Z4 G d dee#      Z5y)    N)AnyDictListOptionalUnion)
FrozenDict)create_reposnapshot_download)validate_hf_hub_args)Image)tqdm   )ConfigMixin)FLAX_WEIGHTS_NAMEFlaxModelMixin)SCHEDULER_CONFIG_NAMEFlaxSchedulerMixin)CONFIG_NAME
BaseOutputPushToHubMixinhttp_user_agentis_transformers_availablelogging)FlaxPreTrainedModelzdiffusion_flax_model.binsave_pretrainedfrom_pretrained)r   r   FlaxDiffusionPipeline)PreTrainedTokenizerPreTrainedTokenizerFastr   FeatureExtractionMixinProcessorMixinImageProcessingMixin)	diffuserstransformersc           	          	 t        | d|z         }|S # t        $ r t        | |      }Y |S t        $ r t        d| d| d|        w xY w)NFlaxzNeither Flaxz nor z
 exist in )getattrAttributeError
ValueError)module
class_name	class_objs      b/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/pipeline_flax_utils.pyimport_flax_or_no_modelr.   J   sp    YFFZ$78	   0FJ/	   Y<
|5JvhWXXYs    AAc                   h    e Zd ZU dZeeej                  j                     ej                  f   e
d<   y)FlaxImagePipelineOutputz
    Output class for image pipelines.

    Args:
        images (`List[PIL.Image.Image]` or `np.ndarray`)
            List of denoised PIL images of length `batch_size` or NumPy array of shape `(batch_size, height, width,
            num_channels)`.
    imagesN)__name__
__module____qualname____doc__r   r   PILr   npndarray__annotations__     r-   r0   r0   W   s*     $syy'344r;   r0   c                       e Zd ZdZdZd Z	 ddeeej                  f   dee
ef   defdZeedeeeej                  f      fd	              Zed
        Zede
eef   fd       Zed        Zd Zd Zy)r   a   
    Base class for Flax-based pipelines.

    [`FlaxDiffusionPipeline`] stores all components (models, schedulers, and processors) for diffusion pipelines and
    provides methods for loading, downloading and saving models. It also includes methods to:

        - enable/disable the progress bar for the denoising iteration

    Class attributes:

        - **config_name** ([`str`]) -- The configuration filename that stores the class and module names of all the
          diffusion pipeline's components.
    zmodel_index.jsonc                    ddl m} |j                         D ]  \  }}||di}n|j                  j	                  d      d   }|j                  j	                  d      d   }|j                  j	                  d      }||v xr t        ||      }	|t        vs|	r|}|j                  j                  }
|||
fi} | j                  di | t        | ||        y )Nr   	pipelines)NN.r:   )r#   r?   itemsr3   splithasattrLOADABLE_CLASSES	__class__r2   register_to_configsetattr)selfkwargsr?   namer*   register_dictlibrarypipeline_dirpathis_pipeline_moduler+   s              r-   register_modulesz&FlaxDiffusionPipeline.register_modulesv   s    '"LLN 	(LD&~!%| 4 !++11#6q9  &0066s;B?((..s3%1T%9%^giQ]>^"
 "226H*G $--66
!%'< = $D##4m4 D$'7	(r;   save_directoryparamspush_to_hubc                    | j                  |       t        | j                        }|j                  d       |j                  d       |j                  dd       |r|j                  dd      }|j                  dd      }|j                  dd      }|j                  d	d      }	|j                  d
|j	                  t
        j                  j                        d         }
t        |
d||	      j                  }
|j                         D ]B  }t        | |      }||j                  }d}t        j                         D ]Y  \  }}t        j                   |      }|j                         D ](  \  }}t        ||d      }|t#        ||      s#|d   } n |Y n t        ||      }dt%        t'        j(                  |      j*                  j                               v }|r, |t
        j                  j-                  ||      ||          n& |t
        j                  j-                  ||             |s-| j/                  |
	       E y)a  
        Save all saveable variables of the pipeline to a directory. A pipeline variable can be saved and loaded if its
        class implements both a save and loading method. The pipeline is easily reloaded using the
        [`~FlaxDiffusionPipeline.from_pretrained`] class method.

        Arguments:
            save_directory (`str` or `os.PathLike`):
                Directory to which to save. Will be created if it doesn't exist.
            push_to_hub (`bool`, *optional*, defaults to `False`):
                Whether or not to push your model to the Hugging Face model 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.
        _class_name_diffusers_version_moduleNcommit_messageprivate	create_prFtokenrepo_idT)exist_okrZ   r\   r   rS   )rS   )r\   rY   r[   )save_configdictconfigpoprC   osrO   sepr	   r]   keysr'   rF   rE   rB   	importlibimport_module
issubclasssetinspect	signature
parametersjoin_upload_folder)rI   rR   rS   rT   rJ   model_index_dictrY   rZ   r[   r\   r]   pipeline_component_name	sub_model	model_clssave_method_namelibrary_namelibrary_classesrM   
base_classsave_load_methodsclass_candidatesave_methodexpects_paramss                          r-   r   z%FlaxDiffusionPipeline.save_pretrained   s1   . 	(,]+12Y-#ZZ(8$?NjjD1G

;6IJJw-EjjN,@,@,Mb,QRG!'D'QVW__G'7'<'<'> &	#&=>I !++I#1A1G1G1I 	-o#11,?5D5J5J5L 1J 1&-gz4&HO&2z)_7]+<Q+?( $/	 ")-=>K%W->->{-K-V-V-[-[-])^^NGGLL1HIRXYpRq BGGLL9PQR##"#1' $ A&	r;   pretrained_model_name_or_pathc                 
  8 |j                  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      }t        j                  j                  |      s| j	                  ||||||      }|j                         D cg c]  }|j                  d      r| }}|D cg c]"  }t        j                  j                  |d      $ }}|t        t        t        | j                  gz  }|sddgng }|g dz  }| t        k7  r| j                  }n4|j                  d| j                        }|j                  d      r|nd|z   }d|i}t        |      }t!        |||||||||	      }n|}| j	                  |      }| t        k7  r| }n^t#        j$                  | j&                  j)                  d      d         }|d   j                  d      r|d   nd|d   z   }t+        ||      }| j-                  |      \  }}|D ci c]  }||v s||j                  |       c}8|D ci c]  }||v s||j                  |       }} |j.                  |fi |\  }}}|D ci c]  }||v s||j                  |       }}i ||}8fd}|j1                         D ci c]  \  }} |||      s|| }}}t3        |      dkD  r&t4        j7                  d| d|j                   d       i } ddlm}! |j1                         D ]  \  }"\  }#}|d||"<   t=        |!|#      }$d}%d}&|"8v r|$st#        j$                  |#      }'t+        |'|      }(t>        |#   })|)j                         D *ci c]  }*|*t+        |'|*d       }+}*d},|+j1                         D ]  \  }}-|-	tA        |(|-      s|-}, tA        8|"   jB                  |,      setE        8|"    dtG        8|"          d|,       8|"   "t4        j7                  d |" d!| d"| d#       d}&nt4        j7                  d$8|"    d%       8|"   }%n|$rCt+        |!|#      }.tI        |.|      }(tJ        })tL        jO                  |)j                         |(      }+nSt#        j$                  |#      }'tI        |'|      }(t>        |#   })|)j                         D *ci c]  }*|*t+        |'|*d       }+}*|%8|&r5d}/+j1                         D ]  \  }}-|-	tA        (|-      s)|   d&   }/ t+        (|/      }0t        j                  j                  t        j                  j                  ||"            r!t        j                  j                  ||"      }1n|}%tA        |(tP              r |01||	|
|'      \  }%}2|2| |"<   nqtS               r>tA        |(tT              r.|r |01|(      }%|%jV                  }2|%`,n |01d)      \  }%}2|2| |"<   n)tA        |(tZ              r |01      \  }%}3|3| |"<   n |01      }%|%||"<    t]        |      t]        |j                               z
  }4t_        8j                               }5t3        |4      dkD  r+|4t]        |5      k  r|4D ]  }68j                  |6d      ||6<    nbt3        |4      dkD  rTt]        t_        |j                               t_        8j                               z         |z
  }5tE        d*| d+| d,|5 d-       |d.i |d|i}7|7| fS c c}w c c}w c c}w c c}w c c}w c c}}w c c}*w c c}*w )/aW  
        Instantiate a Flax-based diffusion pipeline from pretrained pipeline weights.

        The pipeline is set in evaluation mode (`model.eval()) by default and dropout modules are deactivated.

        If you get the error message below, you need to finetune the weights for your downstream task:

        ```
        Some weights of FlaxUNet2DConditionModel were not initialized from the model checkpoint at stable-diffusion-v1-5/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
        ```

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

                    - A string, the *repo id* (for example `stable-diffusion-v1-5/stable-diffusion-v1-5`) of a
                      pretrained pipeline hosted on the Hub.
                    - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
                      using [`~FlaxDiffusionPipeline.save_pretrained`].
            dtype (`jnp.dtype`, *optional*):
                Override the default `jnp.dtype` and load the model under this 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.

            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.
            mirror (`str`, *optional*):
                Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
                guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
                information.
            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.

        <Tip>

        To use private or [gated models](https://huggingface.co/docs/hub/models-gated#gated-models), log-in with `hf
        auth login`.

        </Tip>

        Examples:

        ```py
        >>> from diffusers import FlaxDiffusionPipeline

        >>> # Download pipeline from huggingface.co and cache.
        >>> # Requires to be logged in to Hugging Face hub,
        >>> # see more in [the documentation](https://huggingface.co/docs/hub/security-tokens)
        >>> pipeline, params = FlaxDiffusionPipeline.from_pretrained(
        ...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
        ...     variant="bf16",
        ...     dtype=jnp.bfloat16,
        ... )

        >>> # Download pipeline, but use a different scheduler
        >>> from diffusers import FlaxDPMSolverMultistepScheduler

        >>> model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
        >>> dpmpp, dpmpp_state = FlaxDPMSolverMultistepScheduler.from_pretrained(
        ...     model_id,
        ...     subfolder="scheduler",
        ... )

        >>> dpm_pipe, dpm_params = FlaxStableDiffusionPipeline.from_pretrained(
        ...     model_id, variant="bf16", dtype=jnp.bfloat16, scheduler=dpmpp
        ... )
        >>> dpm_params["scheduler"] = dpmpp_state
        ```
        	cache_dirNproxieslocal_files_onlyFr\   revisionfrom_ptuse_memory_efficient_attentionsplit_head_dimdtype)r~   r   r   r\   r   _*z*.binz*.safetensors)z*.onnxz*.onnx_dataz*.xmlz*.pbrV   r&   pipeline_class)r~   r   r   r\   r   allow_patternsignore_patterns
user_agentr@   r   c                 &    |d   y| v r|    yy)Nr   FTr:   )rK   valuepassed_class_objs     r-   load_modulez:FlaxDiffusionPipeline.from_pretrained.<locals>.load_module  s*    Qx'',<T,B,Jr;   zKeyword arguments z are not expected by z and will be ignored.r>   Tz is of type: z, but should be zYou have passed `None` for z! to disable its functionality in z3. Note that this might lead to problems when using z and is not recommended.z&You have passed a non-standard module z2. We cannot verify whether it has the correct type   )r   r   r   r   )r   )_do_initz	Pipeline z
 expected z, but only z were passed.r:   )0rc   rd   rO   isdirload_configrf   
startswithrn   r   r   r   config_namer   r2   getr   r
   rg   rh   r3   rC   r'   _get_signature_keysextract_init_dictrB   lenloggerwarningr#   r?   rD   rE   ri   rF   r)   typer.   ALL_IMPORTABLE_CLASSESra   fromkeysr   r   r   rS   _paramsr   rj   list)9clsr|   rJ   r~   r   r   r\   r   r   r   r   r   config_dictkfolder_namesr   r   requested_pipeline_classr   cached_folderr   diffusers_moduler+   expected_modulesoptional_kwargspassed_pipe_kwargs	init_dictunused_kwargsr   init_kwargsr   vrS   r?   rK   ru   rP   loaded_sub_modelsub_model_should_be_definedrM   r,   importable_classescclass_candidatesexpected_class_objry   pipeline_moduleload_method_nameload_methodloadable_folderloaded_paramsscheduler_statemissing_modulespassed_modulesr*   modelr   s9                                                           @r-   r   z%FlaxDiffusionPipeline.from_pretrained   sb   l JJ{D1	**Y-!::&8%@

7D)::j$/**Y.)/4TV[)\&$4e<

7D) ww}}:;//-#!1! * K (3'7'7'9S!cARASLS<HIqbggll1c2INI02GVYVeVeffN@Gw8ROIIO+++.<<(+6??=#,,+W( 0::6B -":: ) +,DEJ(4J .-#!1!- /%
M :Moom4 '' N(66s~~7K7KC7PQR7ST }-88@ M*k-88 
 %%5zBN
 -0,C,CN,S)/6FV!v+Avzz!},V8GW11PV;aA.WW&Fn&F&F{&]V\&]#	=! 5DVqqI~q)--**VV;;(:;	 '0oo&7Mda;q!;LQTM	M }!NN$]O3HI`I`Haavw
  	( 1:0A _	1,D,<!$(D!!(L!A#*.' '')'55lCG ' <I)9,)G&N`NeNeNg'h77At+D(D'h$'h)-&7G7M7M7O A3
O*6:iQ`;a1@.A &&6t&<&F&FHZ[(/56mDIYZ^I_D`Ca b  235  &d+3NN5dV;\]k\l mHHVGWWoq 38/NN@AQRVAW@X Y0 0 $4D#9 #"))\"B3OZP	%;"#'==1C1H1H1JI#V  $11,?3GZH	%5l%C"J\JaJaJc#dQAww4'@$@#d #d',G#' 3C3I3I3K M/J&2z)_7]+=j+I!+L(M &i1AB 77==mT!BC&(ggll=$&GO'4$i86A' '7U'5#73$m $1F4L.0Z	K^5_+6PW+X((8(?(?,4:Eo`e:f7(-#0F4L	+=>8CO8T5$o#2F4L'2?'C$ 0K_	1D ./#k6F6F6H2II.3356!#3~;N(N) I&6&:&:64&HF#I!A% k&6&6&8!9DAQAVAVAX<Y!YZ]llNN+:6F5G{SaRbbop  ::E:f}K TIj WW
 W N@ (iL $esN   -]]']!(	]&2]&	]+]+	]0]0]5]5];^ c                    t        j                  |j                        j                  }|j	                         D ci c]&  \  }}|j
                  t         j                  k(  s$||( }}}t        |j	                         D ch c]%  \  }}|j
                  t         j                  k7  s$|' c}}      }t        |j                               dhz
  }||fS c c}}w c c}}w )NrI   )	rk   rl   __init__rm   rB   default_emptyrj   rf   )r   objrm   r   r   required_parametersoptional_parametersr   s           r-   r   z)FlaxDiffusionPipeline._get_signature_keys  s    &&s||4??
0:0@0@0Bb1aiiSZSaSaFaq!tbb!1A1A1C"cAqyyT[TbTbGb1"cd2779:fXE!444	 c"cs   %C#C%C
)C
returnc           
      D   | j                  |       \  }}| j                  j                         D ci c]&  }|j                  d      r||vs|t	        | |      ( }}t        |j                               |k7  r!t        |  d| j                   d| d| d      |S c c}w )a  

        The `self.components` property can be useful to run different pipelines with the same weights and
        configurations to not have to re-allocate memory.

        Examples:

        ```py
        >>> from diffusers import (
        ...     FlaxStableDiffusionPipeline,
        ...     FlaxStableDiffusionImg2ImgPipeline,
        ... )

        >>> text2img = FlaxStableDiffusionPipeline.from_pretrained(
        ...     "stable-diffusion-v1-5/stable-diffusion-v1-5", variant="bf16", dtype=jnp.bfloat16
        ... )
        >>> img2img = FlaxStableDiffusionImg2ImgPipeline(**text2img.components)
        ```

        Returns:
            A dictionary containing all the modules needed to initialize the pipeline.
        r   z% has been incorrectly initialized or z& is incorrectly implemented. Expected z to be defined, but z are defined.)r   rb   rf   r   r'   rj   r)   rF   )rI   r   r   r   
componentss        r-   r   z FlaxDiffusionPipeline.components!  s    0 150H0H0N--)-)9)9);
$%1<<PSCTYZbuYuAwtQ

 
 z !%55&=dnn=M N$%%9*]T 
 
s   BBBc                 V   | j                   dk(  r| d   } | dz  j                         j                  d      } | j                  d   dk(  r4| D cg c]'  }t	        j
                  |j                         d      ) }}|S | D cg c]  }t	        j
                  |       }}|S c c}w c c}w )	zL
        Convert a NumPy image or a batch of images to a PIL image.
           )N.   uint8r^   r   L)mode)ndimroundastypeshaper   	fromarraysqueeze)r1   image
pil_imagess      r-   numpy_to_pilz"FlaxDiffusionPipeline.numpy_to_pilF  s    
 ;;!I&F3,%%'..w7<<q RXY%//%--/DYJY  ?EEU%//%0EJE	 ZEs   ,B!B&c                     t        | d      si | _        n<t        | j                  t              s"t	        dt        | j                         d      t        |fi | j                  S )N_progress_bar_configz=`self._progress_bar_config` should be of type `dict`, but is r@   )rD   r   
isinstancera   r)   r   r   )rI   iterables     r-   progress_barz"FlaxDiffusionPipeline.progress_barW  se    t34(*D%D55t<OPTUYUnUnPoOppqr  H: 9 9::r;   c                     || _         y )N)r   )rI   rJ   s     r-   set_progress_bar_configz-FlaxDiffusionPipeline.set_progress_bar_configa  s
    $*!r;   N)F)r2   r3   r4   r5   r   rQ   r   strrd   PathLiker   r   boolr   classmethodr   r   r   r   propertyr   r   staticmethodr   r   r   r:   r;   r-   r   r   e   s     %K(J "	Lc2;;./L dJ&'L 	L\ oHU3PRP[P[K[E\<] o  ob	 5 5 "DcN " "H   ;+r;   r   )6rg   rk   rd   typingr   r   r   r   r   flaxnumpyr7   	PIL.Imager6   flax.core.frozen_dictr   huggingface_hubr	   r
   huggingface_hub.utilsr   r   	tqdm.autor   configuration_utilsr   models.modeling_flax_utilsr   r    schedulers.scheduling_utils_flaxr   r   utilsr   r   r   r   r   r   r$   r   
INDEX_FILE
get_loggerr2   r   rE   r   rM   updater.   struct	dataclassr0   r   r:   r;   r-   <module>r      s1  "   	 3 3    , : 6   - J X  0'
 
		H	%
 -.?@02CD"35F!G !23DE$57H#I 13DE#46G"H,.?@!24E F     =G!!"27";<=
 
5j 
5 
5}+K }+r;   