
    ij              
          d dl Z d dlZd dlZd dlmZmZ d dlmZmZm	Z	m
Z
mZmZ d dlmZmZ d dlmZmZmZmZmZ ddlmZmZmZ dd	lmZ  ej8                  e      Zh d
Zi dddddddddd ddddddd ddddddd dddddddddddd dd!dddd"d#d$d%d&d'd(d)d$d%d&d'd*d+dd,d-dd.d/d0d1d2d3d4d5d6d7d8d9d:dd1d;gd<gd=d>d:d?d:ddd@dAd3d,dBddCdDdEdFd3dGd d dHdDd<dIdddddJdKd;dLd3d4d5d6d7dMdNdOddiZ dPddQd dRdSdddTddQdUdVdWdXdYddZd*gg d=d[d\ddQd d]dQddd^Z!dd_dd d`dd_dd9d:d_dd?d:d_ddad_dbd dd_dd dcZ"g ddddegdgdfgdgg dhg did:djgdkgdgg dldegd8gdmgdgg dndogdgdpgdgd:gdegdqgdrgdgdsZ# edtu       G dv dw             Z$e G dx dye             Z% G dz d{      Z&d|ee'ee'ef   f   d}e&fd~Z(d}e&fdZ)y)    N)asdict	dataclass)AnyDictListOptionalTupleUnion)create_repohf_hub_download)EntryNotFoundErrorHfHubHTTPErrorRepositoryNotFoundErrorRevisionNotFoundErrorvalidate_hf_hub_args   )HUGGINGFACE_CO_RESOLVE_ENDPOINTPushToHubMixinextract_commit_hash   )ModularPipelineBlocks>   decoderdenoise
controlnetvae_encodertext_encodercontrol_imagezControl Imageimageinput)labeltypedisplaycontrolnet_conditioning_scaleScalefloatg      ?)r    r!   defaultminmaxcontrol_guidance_endEndg      ?control_guidance_startStartg        r   
Controlnetcustom_controlnet
embeddingszText Embeddings)r    r"   r!   Imagenegative_promptzNegative Promptstring textarea)r    r!   r&   r"   promptPromptguidance_scalezGuidance Scaleslider   g      >@g?)r    r!   r"   r&   r'   r(   stepheightHeightinti   @      )r    r!   r&   r'   r:   image_latentszImage Latentslatentswidthstrength)FT)r    r!   r"   onChangeLatentsnum_inference_stepsSteps   d   )r    r!   r"   r&   r'   r(   seedSeedrandoml    Strengthg{Gz?)r    r!   r&   r'   r(   r:   Width
ip_adapterz
IP Adaptercustom_ip_adapter	Schedulerdiffusers_auto_modelzText Encodersdiffusers_auto_modelsUnetsignalguider)actiontarget)r    r"   r!   onSignalGuidercustom_guider)r    r"   r!   rD   VAEzControlnet Model)	schedulertext_encodersunetrV   vaer   outputImageszLatents Previewlatent)r/   imagesr@   rA   latents_previewcontrolnet_out)r   r#   r+   r)   r;   rB   r`   controlnet_vae_encoder)inputsmodel_inputsoutputsblock_names)
r/   rB   r;   rJ   rF   r7   r@   rC   r   rO   )r_   rV   r]   re   r   )r   rB   r;   r   )r5   r1   r   r^   r   rd   decode)r   r   r   r   r   T)frozenc                      e Zd ZU eed<   eed<   eed<   dZee   ed<   dZeed<   dZ	ee
   ed<   dZee
   ed<   dZee
   ed	<   dZeed
<   dZeed<   dZeeeef      ed<   dZeed<   dZeed<   dZeed<   deeef   fdZy)MellonParamnamer    r!   Nr"   r&   r'   r(   r:   optionsvaluefieldOptionsrD   rY   _map_to_inputreturnc                     t        |       }|j                         D ci c]  \  }}|j                  d      r||| c}}S c c}}w )N_)r   items
startswith)selfdatakvs       w/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/diffusers/modular_pipelines/mellon_node_utils.pyto_dictzMellonParam.to_dictK  s<    d|!%YAQ\\#5F1=1YYYs   AAA)__name__
__module____qualname__str__annotations__r"   r   r&   r   r'   r%   r(   r:   rq   rr   rs   r   rD   rY   rt   r        r~   ro   ro   :  s    
IJ
I!GXc]!GSC%C% D(5/ GSE3-1L(4S>*1HcHcM3Zc3h Zr   ro   c                      e Zd ZU dZeeeef      ed<   eeeef      ed<   eeeef      ed<   e	e   ed<   eed<   dZ
d Zed	eeeef      d
eeeeef   f   deeeeef   f   fd       Zee	 	 ddeeej&                  f   deeeef   eeef   f   fd              Zddeeej&                  f   defdZdeeej&                  f   fdZdefdZdeeef   fdZedeeef   dd fd       Zedededd fd       Zy)MellonNodeConfigz
    A MellonNodeConfig is a base class to build Mellon nodes UI with modular diffusers.

    <Tip warning={true}>

        This is an experimental feature and is likely to change in the future.

    </Tip>
    rh   ri   rj   blocks_names	node_typezmellon_config.jsonc                    t        | j                  t              r%| j                  | j                  t              | _        t        | j
                  t              r%| j                  | j
                  t              | _        t        | j                  t              r&| j                  | j                  t              | _        y y N)	
isinstancerh   list_resolve_params_listMELLON_INPUT_PARAMSri   MELLON_MODEL_PARAMSrj   MELLON_OUTPUT_PARAMSrz   s    r~   __post_init__zMellonNodeConfig.__post_init__c  s    dkk4(33DKKATUDKd''. $ 9 9$:K:KM` aDdllD)44T\\CWXDL *r   paramsdefault_mapru   c           
      >   dt         t        t        f   dt        t        t        t        t        f   f   dt
        t        t        t        t        f   f   fd}i }| D ]>  }t        j                  d|         |||      \  }}||v rt        d| d      |||<   @ |S )Nparamdefault_params_mapru   c                    t        | t              r(| |vrt        d|  d      | ||    j                         fS t        | t              r%| j                         }|j                  d      }||fS t        dt        |        d      )NzUnknown param 'z/', please define a `MellonParam` object insteadrp   zUnknown param type 'z9', please use a string or a  `MellonParam` object instead)r   r   
ValueErrorcopyro   r   popr!   )r   r   
param_dict
param_names       r~   _resolve_paramz=MellonNodeConfig._resolve_params_list.<locals>._resolve_paramo  s     %% 22$ug=l%mnn07<<>>>E;/"]]_
'^^F3
!:-- *4;-7pq r   z Resolving param: zDuplicate param '')	r
   r   ro   r   r   r	   loggerinfor   )r   r   r   resolvedprp   cfgs          r~   r   z%MellonNodeConfig._resolve_params_listk  s    	k)*	@DS$sTWx.EX@Y	3S#X&'	   	!AKK,QC01&q+6ID#x #4TF!!<== HTN	! r   pretrained_model_name_or_pathc                    |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                  t        d      t        j
                  j                  |      r|}nt        j
                  j                  |      rt        j
                  j                  t        j
                  j                  || j                              r+t        j
                  j                  || j                        }n<t        d| j                   d| d      	 t        || j                  |||	||
|||
      }	 t!        |dd !      5 }|j#                         }ddd       t%        j&                        }t)        |      }|s|s|S |f}|r||fz  }|r||fz  }|S # t        $ r t        | d      t        $ r t        | d| d      t        $ r t        | d| j                   d      t        $ r}t        d| d|       d}~wt        $ r$ t        dt         d| d| j                   d      t        $ r  t        d| d| d| j                   d      w xY w# 1 sw Y   xY w# t$        j*                  t,        f$ r t        d"| d#      w xY w)$a
  
        Load a model or scheduler configuration.

        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 model weights saved with
                      [`~ConfigMixin.save_config`].

            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.
            subfolder (`str`, *optional*, defaults to `""`):
                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 unused keyword arguments of the config are returned.
            return_commit_hash (`bool`, *optional*, defaults to `False):
                Whether the `commit_hash` of the loaded configuration are returned.

        Returns:
            `dict`:
                A dictionary of all the parameters stored in a JSON configuration file.

        	cache_dirN	local_dirlocal_dir_use_symlinksautoforce_downloadFproxiestokenlocal_files_onlyrevisionz`self.config_name` is not defined. Note that one should not load a config from `ConfigMixin`. Please make sure to define `config_name` in a class inheriting from `ConfigMixin`zError no file named z found in directory .)	filenamer   r   r   r   r   r   r   r   z is not a local folder and is not a valid model identifier listed on 'https://huggingface.co/models'
If this is a private repository, make sure to pass a token having permission to this repo with `token` or log in with `hf auth login`.z is not a valid git identifier (branch name, tag name or commit id) that exists for this model name. Check the model page at 'https://huggingface.co/z' for available revisions.z& does not appear to have a file named z:There was a specific connection error when trying to load z:
zWe couldn't connect to 'zM' to load this model, couldn't find it in the cached files and it looks like z- is not the path to a directory containing a z file.
Checkout your internet connection or see how to run the library in offline mode at 'https://huggingface.co/docs/diffusers/installation#offline-mode'.zCan't load config for 'z'. If you were trying to load it from 'https://huggingface.co/models', make sure you don't have a local directory with the same name. Otherwise, make sure 'z2' is the correct path to a directory containing a z filerutf-8encodingz"It looks like the config file at 'z' is not a valid JSON file.)r   r   config_namer   ospathisfileisdirjoinEnvironmentErrorr   r   r   r   r   r   openreadjsonloadsr   JSONDecodeErrorUnicodeDecodeError)clsr   return_unused_kwargsreturn_commit_hashkwargsr   r   r   r   r   r   r   r   config_fileerrreadertextconfig_dictcommit_hashrj   s                       r~   load_mellon_configz#MellonNodeConfig.load_mellon_config  sy   j JJ{D1	JJ{D1	!',Df!M$4e<**Y-

7D)!::&8%@::j$/(+,I(J%??"s  77>>787KWW]]89ww~~bggll+H#//Z[ ggll+H#//Z&*3??*;;OPmOnnop 1-1 __'#1#%5%'+A`	rk39 %V{{}%**T*K-k:K %(:.y G~%Gq + &45 6i i 
 ) &j !00M/NNhj 
 & &455[\_\k\k[llmn  " &56c#@   &./N.O P>>[=\ ]//2.? @ZZ  $ &-.K-L M--J,K L$$'OO#4E; % %
 $$&89 	r"%G}To#pqq	rs>   H #K 1K(K AK I11AKKK )Lsave_directorypush_to_hubc                    t         j                  j                  |      rt        d| d      t        j                  |d       t         j                  j                  || j                        }| j                  |       t        j                  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d      }
| j                  ||	||||
       yy)a  
        Save the Mellon node definition to a JSON file.

        Args:
            save_directory (`str` or `os.PathLike`):
                Directory where the configuration JSON file is 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.
        zProvided path (z#) should be a directory, not a fileT)exist_okz Mellon node definition saved in commit_messageNprivate	create_prFr   repo_id)r   r   r   	subfolder)r   r   r   r   )r   r   r   AssertionErrormakedirsr   r   to_json_filer   r   r   splitsepr   r   _upload_folder)rz   r   r   r   output_config_filer   r   r   r   r   r   s              r~   save_mellon_configz#MellonNodeConfig.save_mellon_config   s7    77>>.) ?>2BBe!fgg
NT2  WW\\.$:J:JK,-67I6JKL#ZZ(8$?NjjD1G

;6IJJw-EjjN,@,@,Mb,QRG!'D'QVW__G

;5I-##    r   json_file_pathc                     t        |dd      5 }|j                  | j                                ddd       y# 1 sw Y   yxY w)z
        Save the Mellon schema dictionary to a JSON file.

        Args:
            json_file_path (`str` or `os.PathLike`):
                Path to the JSON file to save a configuration instance's parameters.
        wr   r   N)r   writeto_json_string)rz   r   writers      r~   r   zMellonNodeConfig.to_json_fileK  s<     .#8 	0FLL,,./	0 	0 	0s	    8Ac                 X    | j                         }t        j                  |dd      dz   S )z
        Serializes this instance to a JSON string of the Mellon schema dict.

        Args:
        Returns:
            `str`: String containing all the attributes that make up this configuration instance in JSON format.
        r   T)indent	sort_keys
)to_mellon_dictr   dumps)rz   mellon_dicts     r~   r   zMellonNodeConfig.to_json_stringV  s*     ))+zz+a4@4GGr   c                     i }|j                  | j                  xs i        |j                  | j                  xs i        |j                  | j                  xs i        | j                  | j
                  |dS )zReturn a JSON-serializable dict focusing on the Mellon schema fields only.

        params is a single flat dict composed as: {**inputs, **model_inputs, **outputs}.
        )r   r   r   )updaterh   ri   rj   r   r   )rz   merged_paramss     r~   r   zMellonNodeConfig.to_mellon_dictb  so     T[[.B/T..4"5T\\/R0  --#
 	
r   r   c           	      .   |j                  di       }i }i }i }|j                         D ]?  \  }}|j                  dd      dk(  r|||<   !|j                  dd      dv r|||<   ;|||<   A  | ||||j                  dg       |j                  d      	      S )
a<  Create a config from a Mellon schema dict produced by to_mellon_dict().

        Splits the flat params dict back into inputs/model_inputs/outputs using the known key spaces from
        MELLON_INPUT_PARAMS / MELLON_MODEL_PARAMS / MELLON_OUTPUT_PARAMS. Unknown keys are treated as inputs by
        default.
        r   r"   r3   ra   r!   )rR   rS   r   r   rh   ri   rj   r   r   )getrx   )r   r   flat_paramsrh   ri   rj   r   r   s           r~   from_mellon_dictz!MellonNodeConfig.from_mellon_dicts  s     "ooh3!#')"$&1&7&7&9 	0"J
~~i,8&0
#+/``+5Z(%/z"	0 %$<!ook2
 	
r   blocksc           	         |t         vrt        d| d      t        |j                  j	                               }t         |   }|j                  dg       }|j                  dg       }|j                  dg       }|j                  D ]%  }||vs|j                  t        |||d             ' |j                  D ]C  }	|	j                  |vs|j                  t        |	j                  |	j                  dd             E  | |||||	      S )
z
        Create an instance from a ModularPipeline object. If a preset exists in NODE_TYPE_PARAMS_MAP for the node_type,
        use it; otherwise fall back to deriving lists from the pipeline's expected inputs/components/outputs.
        z
Node type z not supportedrh   ri   rj   r   )rp   r    r!   r"   rR   r   )NODE_TYPE_PARAMS_MAPr   r   
sub_blockskeysr   required_inputsappendro   expected_componentsrp   )
r   r   r   r   default_node_configinputs_listmodel_inputs_listoutputs_listrequired_input_namecomponent_specs
             r~   from_blockszMellonNodeConfig.from_blocks  s2    00z)NCDDF--224529=5H5L5LXWY5Z;N;R;RSace;f6I6M6MiY[6\#)#9#9 	"+5""08KReov	 %88 		N""*;;!((+00,113 '			 * %
 	
r   N)FF)F)r   r   r   __doc__r   r
   r   ro   r   r   r   r   staticmethodr   r   r   classmethodr   r   PathLiker	   r   boolr   r   r   r   r   r   r  r   r   r~   r   r   P  s    sK'())uS+-.//%[()**s)N&KY U3+,-<@d3PS8nAT<U	c4S>!	" 8  # 	T',S"++-='>T 
tCH~tCH~-	.T  Tl)sBKK7G1H )W[ )V	05bkk1A+B 	0
H 
H
S#X 
" 
4S> 
>P 
 
< (
!6 (
3 (
K] (
 (
r   r   c                   `    e Zd ZdZd Zdedeeef   fdZ	dedefdZ
deeeeef   f   fdZy	)
ModularMellonNodeRegistryzKRegistry mapping (pipeline class, blocks_name) -> list of MellonNodeConfig.c                      i | _         d| _        y )NF)	_registry_initializedr   s    r~   __init__z"ModularMellonNodeRegistry.__init__  s    !r   pipeline_clsnode_paramsc                 P    | j                   st        |        || j                  |<   y r   r  _initialize_registryr  )rz   r  r  s      r~   registerz"ModularMellonNodeRegistry.register  s!       &'2|$r   ru   c                 h    | j                   st        |        | j                  j                  |d       S r   )r  r  r  r   )rz   r  s     r~   r   zModularMellonNodeRegistry.get  s*       &~~!!,55r   c                 H    | j                   st        |        | j                  S r   r  r   s    r~   get_allz!ModularMellonNodeRegistry.get_all  s       &~~r   N)r   r   r   r  r  r!   r   r   r   r  r   r  r   r   r~   r  r    s]    U"3T 3SBR=R8S 3
6 6)9 6
dD.>)>$??@ r   r  
params_mapregistryc           
         i }|j                         D ]Z  \  }}t        |j                  dg       |j                  dg       |j                  dg       |j                  dg       |      }|||<   \ |j                  | |       y)zLRegister all node-type presets for a given pipeline class from a params map.rh   ri   rj   rk   r   N)rx   r   r   r  )r  r  r  node_configsr   specnode_configs          r~   _register_preset_node_typesr     s     L%++- .	4&88Hb)."5HHY+-4
 #.Y. lL1r   c                     t        d       d| _        	 ddlm} ddlm} t        |||        	 ddlm	} ddl
m} t        |||        y
# t        $ r t        d      w xY w# t        $ r t        d	      w xY w)zDInitialize the registry and register all available pipeline configs.zInitializing registryTr   )QwenImageModularPipeline)QwenImage_NODE_TYPES_PARAMS_MAPz+Failed to register QwenImageModularPipeline) StableDiffusionXLModularPipeline)SDXL_NODE_TYPES_PARAMS_MAPz3Failed to register StableDiffusionXLModularPipelineN)printr  qwenimage.modular_pipeliner"  qwenimage.node_utilsr#  r   	Exception$stable_diffusion_xl.modular_pipeliner$  stable_diffusion_xl.node_utilsr%  )r  r"  r#  r$  r%  s        r~   r  r    s    	
!" HGHI#$<>]_ghOZN#$DF`bjk  GEFFG  OMNNOs   A A  A A5)*r   loggingr   dataclassesr   r   typingr   r   r   r   r	   r
   huggingface_hubr   r   huggingface_hub.utilsr   r   r   r   r   utilsr   r   r   modular_pipeliner   	getLoggerr   r   SUPPORTED_NODE_TYPESr   r   r   r   ro   r   r  r   r   r  r   r   r~   <module>r5     s     	 * : : 8  Y X 3 
		8	$ [ v v $&v v* +v8 #9vB "CvL MvV "	Wvb 	cvn !ov@ AvN  %w/
|D	OvZ [vd evt uvD EvT Uvb #cv v & !' &
	 -.b9	 & $&?$ R #  !  # 5 L
 

 
 11!&

 
 "{16
 
 
 &
 
 
 ''" 
 
 
 !zUV r $Z Z Z* j
~ j
 j
\ .2"3S#X#672C\2"O#< Or   