
    irl                        d dl Z d dl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 d dlZddlmZmZ ddlmZ ddlmZmZ  e       r	  ej2                  e      Z G d	 d
e      Ze G d d             Ze G d d             Ze G d d             Ze G d d             Z d Z!d Z"ddZ#ddZ$ddZ%ddZ&ddZ'	 	 	 	 ddZ(y)    N)OrderedDict)	dataclassfieldfields)AnyDictListLiteralOptionalTypeUnion   )ConfigMixin
FrozenDict)_is_single_file_path_or_url)is_torch_availableloggingc                       e Zd Zd Zd Zy)InsertableDictc                     t        | j                               }|D cg c]  \  }}||k7  s||f }}}|j                  |||f       | j                          | j	                  |       | S c c}}w N)listitemsinsertclearupdate)selfkeyvalueindexr   kvs          |/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/diffusers/modular_pipelines/modular_pipeline_utils.pyr   zInsertableDict.insert#   sl    TZZ\" %*6DAqQ#X!Q66 	US%L) 	

E  7s
   A-A-c           	         | syg }t        | j                               D ]  \  }\  }}t        |t              rd|j                   d|j
                   d}n1d|j                  j                   d|j                  j
                   d}|j                  | dt        |       d| d        d	d
j                  |      z   dz   S )NzInsertableDict()z<class '.z'>z<obj 'z: (, )zInsertableDict([
  z,
  z
]))
	enumerater   
isinstancetype
__module____name__	__class__appendreprjoin)r   r   ir   r   obj_reprs         r#   __repr__zInsertableDict.__repr__3   s    %(6 	<OA|U%&%e&6&6%7q8HK $EOO$>$>#?qAYAY@ZZ\]LLA3c$s)Bxj:;	< &U(;;fDD    N)r,   r+   __qualname__r   r3    r4   r#   r   r   "   s     Er4   r   c                   "   e Zd ZU dZdZee   ed<   dZee	   ed<   dZ
ee   ed<   dZee   ed<    edddi	      Zeeeee   f      ed
<    edddi	      Zee   ed<    edddi	      Zee   ed<    edddi	      Zee   ed<   dZed   ed<    edddi	      Zeeeee   f      ed<   d Zd Zd Zedededefd       Zedee   fd       Zedefd       Zedede eee   f   fd       Z!d deeee eef   f      defdZ"defdZ#y)!ComponentSpeca=  Specification for a pipeline component.

    A component can be created in two ways:
    1. From scratch using __init__ with a config dict
    2. using `from_pretrained`

    Attributes:
        name: Name of the component
        type_hint: Type of the component (e.g. UNet2DConditionModel)
        description: Optional description of the component
        config: Optional config dict for __init__ creation
        pretrained_model_name_or_path: Optional pretrained_model_name_or_path path for from_pretrained creation
        subfolder: Optional subfolder in pretrained_model_name_or_path
        variant: Optional variant in pretrained_model_name_or_path
        revision: Optional revision in pretrained_model_name_or_path
        default_creation_method: Preferred creation method - "from_config" or "from_pretrained"
    Nname	type_hintdescriptionconfigloadingT)defaultmetadatapretrained_model_name_or_path 	subfoldervariantrevisionfrom_pretrained)from_configrE   default_creation_methodFrepoc                 j    | j                   }|%| j                  t        j                  | d|       y y y )Nr@   )rH   r@   object__setattr__)r   
repo_values     r#   __post_init__zComponentSpec.__post_init__h   s8    YY
!d&H&H&Pt%DjQ 'Q!r4   c                 Z    t        | j                  | j                  | j                  f      S )z=Make ComponentSpec hashable, using load_id as the hash value.)hashr9   load_idrG   r   s    r#   __hash__zComponentSpec.__hash__m   s"    TYYd.J.JKLLr4   c                     t        |t              sy| j                  |j                  k(  xr4 | j                  |j                  k(  xr | j                  |j                  k(  S )z8Compare ComponentSpec objects based on name and load_id.F)r)   r8   r9   rP   rG   )r   others     r#   __eq__zComponentSpec.__eq__q   sT    %/II# N-N,,0M0MM	
r4   	componentreturnc                 <   t        |d      r|j                  dk7  rd}nt        |t        j                  j
                        rt        d      t        |t              r$t        |d      st        j                  d       d}n&t        d| d|j                  j                   d	      |j                  }t        |t              r|dk(  r|j                  }nd
}t        |d      r+|j                  dk7  r| j                  |j                        }ni } | d||||d|S )a  Create a ComponentSpec from a Component.

        Currently supports:
        - Components created with `ComponentSpec.load()` method
        - Components that are ConfigMixin subclasses but not nn.Modules (e.g. schedulers, guiders)

        Args:
            name: Name of the component
            component: Component object to create spec from

        Returns:
            ComponentSpec object

        Raises:
            ValueError: If component is not supported (e.g. nn.Module without load_id, non-ConfigMixin)
        _diffusers_load_idnullrE   zeCannot create ComponentSpec from a nn.Module that was not created with `ComponentSpec.load()` method.z\Component was not created using `ComponentSpec`, defaulting to `from_config` creation methodrF   z!Cannot create ComponentSpec from (z). Currently ComponentSpec.from_component() only supports:  - components created with `ComponentSpec.load()` method - components that are a subclass of ConfigMixin but not a nn.Module (e.g. guider, scheduler).N)r9   r:   r<   rG   r6   )hasattrrY   r)   torchnnModule
ValueErrorr   loggerwarningr-   r,   r<   decode_load_id)clsr9   rV   rG   r:   r<   	load_specs          r#   from_componentzComponentSpec.from_component{   s2   ( 923	8T8TX^8^&7# )UXX__5 {  I{3y*>?NNv +8' !7vQy?R?R?[?[>\ ]u v  ''	i-2I]2Z%%FF923	8T8TX^8^**9+G+GHII 
6Sj
nw
 	
r4   c                     t        |       D cg c]+  }|j                  j                  dd      s |j                  - c}S c c}w )ux   
        Return the names of all loading‐related fields (i.e. those whose field.metadata["loading"] is True).
        r=   F)r   r?   getr9   )rd   fs     r#   loading_fieldszComponentSpec.loading_fields   s1    
 !'sP1qzz~~i/OPPPs
   !AAc                     | j                   dk(  ry| j                         D cg c]  }t        | |       }}|D cg c]  }|dn|
 }}dj                  d |D              S c c}w c c}w )z
        Unique identifier for this spec's pretrained load, composed of
        pretrained_model_name_or_path|subfolder|variant|revision (no empty segments).
        rF   rZ   |c              3   &   K   | ]	  }|s|  y wr   r6   ).0ps     r#   	<genexpr>z(ComponentSpec.load_id.<locals>.<genexpr>   s     .aA.s   )rG   rj   getattrr0   )r   r!   partsro   s       r#   rP   zComponentSpec.load_id   sr     ''=8+/+>+>+@Aaq!AA5:;19!+;;xx.5... B;s
   A#A(rP   c                     | j                         }t        j                  |      }|dk(  r|S |j                  d      }t	        |      D ]#  \  }}|t        |      k  s|dk(  rdn||||   <   % |S )a  
        Decode a load_id string back into a dictionary of loading fields and values.

        Args:
            load_id: The load_id string to decode, format: "pretrained_model_name_or_path|subfolder|variant|revision"
                     where None values are represented as "null"

        Returns:
            Dict mapping loading field names to their values. e.g. {
                "pretrained_model_name_or_path": "path/to/repo", "subfolder": "subfolder", "variant": "variant",
                "revision": "revision"
            } If a segment value is "null", it's replaced with None. Returns None if load_id is "null" (indicating
            component not created with `load` method).
        rZ   rl   N)rj   dictfromkeyssplitr(   len)rd   rP   rj   resultrr   r1   parts          r#   rc   zComponentSpec.decode_load_id   s    $ ++-~.fM c" !' 	MGAt3~&&48FND~a()	M
 r4   c                 ^   | j                   t        | j                   t              st        d      |xs | j                  xs i }t        | j                   t              r | j                   j                  |fi |}nt        j                  | j                   j                        j                  }i }|j                         D ]  \  }}||v s|||<    |j                         D ]  \  }}||v s|||<     | j                   di |}d|_        t        |d      r|j                  | _        |S )z/Create component using from_config with config.z?`type_hint` is required when using from_config creation method.rZ   r<   r6   )r:   r)   r*   r`   r<   
issubclassr   rF   inspect	signature__init__
parametersr   rY   r\   )r   r<   kwargsrV   signature_paramsinit_kwargsr!   r"   s           r#   createzComponentSpec.create   s    >>!DNND)I^__,4;;,"dnnk22226DVDI&001H1HITTK '1((%&KN'  '1((%&KN' '55I'-	$9h'#**DKr4   c                    | j                         D ci c]  }||v s||j                  |       }}| j                         D ci c]  }||j                  |t        | |            ! }}|j                  dd      }|t	        d      t        |      }|r$| j                  t	        d| j                         | j                  .	 ddlm	}  |j                  |fi ||}|j                  | _        n:|rt        | j                  d	      nt        | j                  d
      }
	  |
|fi ||}|| _        |j                         D ]  \  }}t        | ||        | j                   |_        |S c c}w c c}w # t        $ r }	t	        d| j                   d|	       d}	~	ww xY w# t        $ r }	t	        d| j                   d|	       d}	~	ww xY w)z%Load component using from_pretrained.r@   Nz`pretrained_model_name_or_path` info is required when using `load` method (you can directly set it in `pretrained_model_name_or_path` field of the ComponentSpec or pass it as an argument)zW`type_hint` is required when loading a single file model but is missing for component: r   )	AutoModelzUnable to load z without `type_hint`: from_single_filerE   z using load method: )rj   poprh   rq   r`   r   r:   r9   	diffusersr   rE   	Exceptionr-   r@   r   setattrrP   rY   )r   r   r   passed_loading_kwargsload_kwargsr@   is_single_filer   rV   eload_methodr!   r"   s                r#   loadzComponentSpec.load  s    BFATATAV h#Z]agZgfjjo!5 h hZ^ZmZmZopSVs155c74;MNNpp(38WY](^%(0 N  55RSdnn4ijnjsjsitu  >>!Y/5I556SmWbmflm	 '00DN
 " (:;T^^->? W'(E__X^_	 .K*%%' 	 DAqD!Q	 '+||	$U !ip$  Y ?499+=STUSV!WXXY  W ?499+=QRSQT!UVVWs@   	E.E.$E3E8 $F$ 8	F!FF!$	G-GGr   )$r,   r+   r5   __doc__r9   r   str__annotations__r:   r   r;   r<   r   r   r@   r   r	   rB   rC   rD   rG   r
   rH   rM   rR   rU   classmethodr   rf   rj   propertyrP   r   rc   r   r   r6   r4   r#   r8   r8   G   s   $ D(3- $Ix~$!%K#%#'FHZ 'EJSWclnrbsEt!8E#tCy.,A#Bt$R9d:KLIx}L"49d:KLGXc]L#DIt;LMHhsmMIZW%EFZ -2$)UZI[,\D(5d3i(
)\R
M
 9
# 9
# 9
# 9
 9
v QtCy Q Q 	/ 	/ 	/  S  T#x}2D-E    LXeJS#X,F&GH ^a 8- -r4   r8   c                   :    e Zd ZU dZeed<   eed<   dZee   ed<   y)
ConfigSpecz5Specification for a pipeline configuration parameter.r9   r>   Nr;   )	r,   r+   r5   r   r   r   r   r;   r   r6   r4   r#   r   r   =  s    ?
IL!%K#%r4   r   c                   l    e Zd ZU dZdZeed<   dZeed<   dZ	eed<   dZ
eed<   dZeed	<   dZeed
<   d Zy)
InputParamz%Specification for an input parameter.Nr9   r:   r>   FrequiredrA   r;   kwargs_typec                 ^    d| j                    d| j                  rdnd d| j                   dS )N<: r   optionalz
, default=>)r9   r   r>   rQ   s    r#   r3   zInputParam.__repr__V  s3    499+Rdmm
LJW[WcWcVddeffr4   )r,   r+   r5   r   r9   r   r   r:   r   r>   r   boolr;   r   r3   r6   r4   r#   r   r   K  sG    /D#IsGSHdKKgr4   r   c                   L    e Zd ZU dZeed<   dZeed<   dZeed<   dZ	eed<   d Z
y)	OutputParamz&Specification for an output parameter.r9   Nr:   rA   r;   r   c                     d| j                    dt        | j                  d      r| j                  j                   dS t	        | j                         dS )Nr   r   r,   r   )r9   r\   r:   r,   r   rQ   s    r#   r3   zOutputParam.__repr__c  sT    		{"PZ8[T^^44uuvw	
adeiesesatuuvw	
r4   )r,   r+   r5   r   r   r   r:   r   r;   r   r3   r6   r4   r#   r   r   Z  s-    0
IIsKK
r4   r   c                    | D cg c]  }|j                   s| }}| D cg c]  }|j                   r| }}dj                  d |D              }dj                  d |D              }|}|r|r| d| n|}|S c c}w c c}w )a  
    Format input parameters into a string representation, with required params first followed by optional ones.

    Args:
        inputs: List of input parameters with 'required' and 'name' attributes, and 'default' for optional params

    Returns:
        str: Formatted string of input parameters

    Example:
        >>> inputs = [ ... InputParam(name="prompt", required=True), ... InputParam(name="image", required=True), ...
        InputParam(name="guidance_scale", required=False, default=7.5), ... InputParam(name="num_inference_steps",
        required=False, default=50) ... ] >>> format_inputs_short(inputs) 'prompt, image, guidance_scale=7.5,
        num_inference_steps=50'
    r&   c              3   4   K   | ]  }|j                     y wr   )r9   rn   params     r#   rp   z&format_inputs_short.<locals>.<genexpr>|  s     EEUZZEs   c              3   R   K   | ]  }|j                    d |j                    ! yw)=N)r9   r>   r   s     r#   rp   z&format_inputs_short.<locals>.<genexpr>}  s#     Z

|1U]]O<Zs   %')r   r0   )inputsr   required_inputsoptional_inputsrequired_stroptional_str
inputs_strs          r#   format_inputs_shortr   i  s      +1CENNuCOC*0GuGOG99E_EEL99Z/ZZLJ8D
|2l^4,
 DGs   A:A:A?A?c                    g }| D ]u  }|j                   |v r |j                  d|j                    d       1|j                   |j                  d|j                  z   }n|j                   }|j                  |       w | D ch c]  }|j                    }}g }g }|D ]G  }	|	j                   |v r|j                  |	j                          -|j                  |	j                          I g }
|r#|
j                  ddj                  |              |r#|
j                  ddj                  |              |r#|
j                  ddj                  |              |
rdj                  |
      S d	S c c}w )
aI  
    Formats intermediate inputs and outputs of a block into a string representation.

    Args:
        intermediate_inputs: List of intermediate input parameters
        required_intermediate_inputs: List of required intermediate input names
        intermediate_outputs: List of intermediate output parameters

    Returns:
        str: Formatted string like:
            Intermediates:
                - inputs: Required(latents), dtype
                - modified: latents # variables that appear in both inputs and outputs
                - outputs: images # new outputs only
    z	Required(r'   z*_z    - inputs: r&   z    - modified: z    - outputs: 
z
    (none))r9   r.   r   r0   )intermediate_inputsrequired_intermediate_inputsintermediate_outputsinput_partsinpinp_name
inputs_setmodified_partsnew_output_partsoutrx   s              r#   format_intermediates_shortr     s_   " K" )8833388*A67xxCOO$?#//188x() '::s#((:J:N# .88z!!!#((+##CHH-	. Ftyy'=&>?@(>)B(CDE		2B(C'DEF &499V8L8% ;s   E,c                    | syd|z  }d|dz   z  }d|dz   z  }g }d }d }	|j                  | | d       | D ]  }
|
j                  t        k7  r ||
j                        nd}|
j                  |
j                  d|
j                   n|
j                  }| | d	| d
}t        |
d      r/|
j                  s#|dz  }|
j                  |d|
j                   z  }|dz  }|
j                  r5t        j                  dd|
j                        } |	|||      }|d| | z  }|j                  |        dj                  |      S )a  Format a list of InputParam or OutputParam objects into a readable string representation.

    Args:
        params: List of InputParam or OutputParam objects to format
        header: Header text to use (e.g. "Args" or "Returns")
        indent_level: Number of spaces to indent each parameter line (default: 4)
        max_line_length: Maximum length for each line before wrapping (default: 115)

    Returns:
        A formatted string representing all parameters
    rA          c                 ,   t        | d      ra| j                  t        u rO| j                  D cg c]%  }t        |d      r|j                  n
t        |      ' }}ddj                  |       dS t        | d      r| j                  S t        |       S c c}w )N
__origin__r,   zUnion[r&   ])r\   r   r   __args__r,   r   r0   )r:   ttypess      r#   get_type_strz#format_params.<locals>.get_type_str  s    9l+	0D0D0MOXOaOab!71j#9QZZs1vEbEbDIIe,-Q//%,Y
%Cy!!WYW cs   *Bc                 j   | j                         }g }g }d}|D ]c  }t        |      |rdndz   }|r7||z   |kD  r/|j                  dj                  |             |g}t        |      }N|j                  |       ||z  }e |r |j                  dj                  |             d| j                  |      S )zFWrap text while preserving markdown links and maintaining indentation.r      r   r   )rv   rw   r.   r0   )	textindent
max_lengthwordslinescurrent_linecurrent_lengthwordword_lengths	            r#   	wrap_textz format_params.<locals>.wrap_text  s    

 		.Dd)Lqa@K <z ISXXl34 $v!$T##D)+-		. LL,/0F8}!!%((r4   :z** (``r   z, *optional*z, defaults to z):z \[(.*?)\]\((https?://[^\s\)]+)\)z[\1](\2)r   

)r.   r:   r   r9   r   r\   r   r>   r;   resubr0   )paramsheaderindent_levelmax_line_lengthbase_indentparam_indentdesc_indentformatted_paramsr   r   r   type_strr9   	param_strdescwrapped_descs                   r#   format_paramsr     s|    $K,*+L)*KX)0 {mF8156 +49OOs4J<0PR+0::+=%BSBSB_E%%&'ejeoeo#nTF#hZq9	 5*%>>^+	==,>%--!AAIT	 66={EL]L]^D$T;HL2k]<.99I	*++. ;;'((r4   c                     t        | d||      S )a  Format a list of InputParam objects into a readable string representation.

    Args:
        input_params: List of InputParam objects to format
        indent_level: Number of spaces to indent each parameter line (default: 4)
        max_line_length: Maximum length for each line before wrapping (default: 115)

    Returns:
        A formatted string representing all input parameters
    Inputsr   )input_paramsr   r   s      r#   format_input_paramsr     s     xOOr4   c                     t        | d||      S )a  Format a list of OutputParam objects into a readable string representation.

    Args:
        output_params: List of OutputParam objects to format
        indent_level: Number of spaces to indent each parameter line (default: 4)
        max_line_length: Maximum length for each line before wrapping (default: 115)

    Returns:
        A formatted string representing all output parameters
    Outputsr   )output_paramsr   r   s      r#   format_output_paramsr     s     	<QQr4   c                    | syd|z  }d|dz   z  }g }|j                  | d       |r|j                  d       t        |       D ]  \  }}t        |j                  d      r|j                  j                  nt        |j                        }	| |j                   d|	 d}
|j                  r|
d|j                   z  }
g }|j                         D ]'  }t        ||      }||j                  | d	|        ) |r|
d
dj                  |       dz  }
|j                  |
       |s|t        |       dz
  k  s|j                  d       	 dj                  |      S )a  Format a list of ComponentSpec objects into a readable string representation.

    Args:
        components: List of ComponentSpec objects to format
        indent_level: Number of spaces to indent each component line (default: 4)
        max_line_length: Maximum length for each line before wrapping (default: 115)
        add_empty_lines: Whether to add empty lines between components (default: True)

    Returns:
        A formatted string representing all components
    rA   r   r   zComponents:r,   r   z`)r   r   z [r&   r   r   r   )r.   r(   r\   r:   r,   r   r9   r;   rj   rq   r0   rw   )
componentsr   r   add_empty_linesr   component_indentformatted_componentsr1   rV   	type_namecomponent_descloading_field_values
field_namefield_values                 r#   format_componentsr   "  s    $KlQ./ ;-{ ;<##B' "*- ,9 -4I4G4G,TI((Z]^g^q^qZr 	 --inn-=S2N  9#8#8"9::N  "#224 	KJ!)Z8K&$++zl!K=,IJ	K  499-A#B"C1EEN##N3 q3z?Q#66 ''+3,6 99)**r4   c                    | syd|z  }d|dz   z  }g }|j                  | d       |r|j                  d       t        |       D ]x  \  }}| |j                   d|j                   d}	|j                  r|	d|j                   z  }	|j                  |	       |sV|t        |       dz
  k  sh|j                  d       z d	j                  |      S )
a  Format a list of ConfigSpec objects into a readable string representation.

    Args:
        configs: List of ConfigSpec objects to format
        indent_level: Number of spaces to indent each config line (default: 4)
        max_line_length: Maximum length for each line before wrapping (default: 115)
        add_empty_lines: Whether to add empty lines between configs (default: True)

    Returns:
        A formatted string representing all configs
    rA   r   r   zConfigs:z (default: r'   r   r   r   )r.   r(   r9   r>   r;   rw   r0   )
configsr   r   r   r   config_indentformatted_configsr1   r<   config_descs
             r#   format_configsr  Y  s     $K<!+,M }H56  $ w' )	6&}K?OqQR 2 2344K  - q3w<!#33$$R() 99&''r4   c                    d}|r	|d| dz  }|r?|j                         j                  d      }dj                  d |D              }||dz   z  }|r#t        |      dkD  rt	        |d      }	||	dz   z  }|r#t        |      dkD  rt        |d      }
||
dz   z  }|t        | d      z  }|dz  }|t        |d      z  }|S )	a	  
    Generates a formatted documentation string describing the pipeline block's parameters and structure.

    Args:
        inputs: List of input parameters
        intermediate_inputs: List of intermediate input parameters
        outputs: List of output parameters
        description (str, *optional*): Description of the block
        class_name (str, *optional*): Name of the class to include in the documentation
        expected_components (List[ComponentSpec], *optional*): List of expected components
        expected_configs (List[ConfigSpec], *optional*): List of expected configurations

    Returns:
        str: A formatted string containing information about components, configs, call parameters,
            intermediate inputs/outputs, and final outputs.
    rA   zclass r   r   c              3   &   K   | ]	  }d |z     yw)z  Nr6   )rn   lines     r#   rp   z"make_doc_string.<locals>.<genexpr>  s      D Ds   r   r   )r   )striprv   r0   rw   r   r  r   r   )r   outputsr;   
class_nameexpected_componentsexpected_configsoutput
desc_linesaligned_desccomponents_strconfigs_strs              r#   make_doc_stringr    s    0 F F:,d++  &&(..t4
yy D DD,'' s#67!;*+>QO.6)) C 01A5$%5AF+&& !&q99F fF
"7;;FMr4   )Argsr   s   )r   r  )r   r  T)rA   NNN))r|   r   collectionsr   dataclassesr   r   r   typingr   r   r	   r
   r   r   r   r]   configuration_utilsr   r   loaders.single_file_utilsr   utilsr   r   
get_loggerr,   ra   r   r8   r   r   r   r   r   r   r   r   r   r  r  r6   r4   r#   <module>r     s     	 # 0 0 B B B  9 C / 			H	%E[ EJ r r rj & & & g g g 
 
 
:/9dK)\PR4+n#(R 5r4   