
    big                        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mZ  e       r	  ej.                  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_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          m/home/cdr/jupyterlab/.venv/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__2   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   r2    r3   r"   r   r   !   s     Er3   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<   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
        repo: Optional repo path for from_pretrained creation
        subfolder: Optional subfolder in repo
        variant: Optional variant in repo
        revision: Optional revision in repo
        default_creation_method: Preferred creation method - "from_config" or "from_pretrained"
    Nname	type_hintdescriptionconfigloadingT)defaultmetadatarepo 	subfoldervariantrevisionfrom_pretrained)from_configrD   default_creation_methodc                 Z    t        | j                  | j                  | j                  f      S )z=Make ComponentSpec hashable, using load_id as the hash value.)hashr8   load_idrF   r   s    r"   __hash__zComponentSpec.__hash__e   s"    TYYd.J.JKLLr3   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(   r7   r8   rI   rF   )r   others     r"   __eq__zComponentSpec.__eq__i   sT    %/II# N-N,,0M0MM	
r3   	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nullrD   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 methodrE   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)r8   r9   r;   rF   r5   )hasattrrR   r(   torchnnModule
ValueErrorr   loggerwarningr,   r+   r;   decode_load_id)clsr8   rO   rF   r9   r;   	load_specs          r"   from_componentzComponentSpec.from_components   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
 	
r3   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>   getr8   )r]   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 repo|subfolder|variant|revision (no empty
        segments).
        rE   rS   |c              3   &   K   | ]	  }|s|  y wr   r5   ).0ps     r"   	<genexpr>z(ComponentSpec.load_id.<locals>.<genexpr>   s     .aA.s   )rF   rc   getattrr/   )r   r    partsrh   s       r"   rI   zComponentSpec.load_id   sr     ''=8+/+>+>+@Aaq!AA5:;19!+;;xx.5... B;s
   A#A(rI   c                     | j                         }|D ci c]  }|d }}|dk(  r|S |j                  d      }t        |      D ]#  \  }}|t        |      k  s|dk(  rdn||||   <   % |S c c}w )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: "repo|subfolder|variant|revision"
                     where None values are represented as "null"

        Returns:
            Dict mapping loading field names to their values. e.g. {
                "repo": "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).
        NrS   re   )rc   splitr'   len)r]   rI   rc   rb   resultrk   r0   parts           r"   r\   zComponentSpec.decode_load_id   s    " ++-#12a!T'22fM c" !' 	MGAt3~&&48FND~a()	M
  3s   
A,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.rS   r;   r5   )r9   r(   r)   rY   r;   
issubclassr   rE   inspect	signature__init__
parametersr   rR   rU   )r   r;   kwargsrO   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r3   c                 
   | j                         D ci c]  }||v s||j                  |       }}| j                         D ci c]  }||j                  |t        | |            ! }}|j                  dd      }|t	        d      | j
                  .	 ddlm}  |j                  |fi ||}|j                  | _        n 	  | j
                  j                  |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`repo` info is required when using `load` method (you can directly set it in `repo` field of the ComponentSpec or pass it as an argument)r   )	AutoModelzUnable to load z without `type_hint`: z using load method: )rc   popra   rj   rY   r9   	diffusersr|   rD   	Exceptionr8   r,   r?   r   setattrrI   rR   )r   rw   r   passed_loading_kwargsload_kwargsr?   r|   rO   er    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vt,< \  >>!Y/5I55dTkTVT	 '00DNW:DNN::4Y;YRXY	 	%%' 	 DAqD!Q	 '+||	$= !ip  Y ?499+=STUSV!WXXY  W ?499+=QRSQT!UVVWs@   	D#D#$D(D- E -	E6EE	F"E==Fr   )"r+   r*   r4   __doc__r8   r   str__annotations__r9   r   r:   r;   r   r   r?   r   r	   rA   rB   rC   rF   r
   rK   rN   classmethodr   r_   rc   propertyrI   r   r\   rz   r   r5   r3   r"   r7   r7   F   s   $ D(3- $Ix~$!%K#%#'FHZ ',1$)UYIZ,[D(5d3i(
)[$R9d:KLIx}L"49d:KLGXc]L#DIt;LMHhsmMIZW%EFZM
 9
# 9
# 9
# 9
 9
v QtCy Q Q 	/ 	/ 	/ S T#x}2D-E  JXeJS#X,F&GH ^a 8" "r3   r7   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.r8   r=   Nr:   )	r+   r*   r4   r   r   r   r   r:   r   r5   r3   r"   r   r   )  s    ?
IL!%K#%r3   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.Nr8   r9   r=   Frequiredr@   r:   kwargs_typec                 ^    d| j                    d| j                  rdnd d| j                   dS )N<: r   optionalz
, default=>)r8   r   r=   rJ   s    r"   r2   zInputParam.__repr__B  s3    499+Rdmm
LJW[WcWcVddeffr3   )r+   r*   r4   r   r8   r   r   r9   r   r=   r   boolr:   r   r2   r5   r3   r"   r   r   7  sG    /D#IsGSHdKKgr3   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.r8   Nr9   r@   r:   r   c                     d| j                    dt        | j                  d      r| j                  j                   dS t	        | j                         dS )Nr   r   r+   r   )r8   rU   r9   r+   r   rJ   s    r"   r2   zOutputParam.__repr__O  sT    		{"PZ8[T^^44uuvw	
adeiesesatuuvw	
r3   )r+   r*   r4   r   r   r   r9   r   r:   r   r2   r5   r3   r"   r   r   F  s-    0
IIsKK
r3   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   )r8   rg   params     r"   ri   z&format_inputs_short.<locals>.<genexpr>h  s     EEUZZEs   c              3   R   K   | ]  }|j                    d |j                    ! yw)=N)r8   r=   r   s     r"   ri   z&format_inputs_short.<locals>.<genexpr>i  s#     Z

|1U]]O<Zs   %')r   r/   )inputsr   required_inputsoptional_inputsrequired_stroptional_str
inputs_strs          r"   format_inputs_shortr   U  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))r8   r-   r   r/   )intermediate_inputsrequired_intermediate_inputsintermediate_outputsinput_partsinpinp_name
inputs_setmodified_partsnew_output_partsoutro   s              r"   format_intermediates_shortr   r  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
    r@          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%   ])rU   r   r   __args__r+   r   r/   )r9   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   )rm   rn   r-   r/   )	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}!!%((r3   :z** (``r   z, *optional*z, defaults to z):z \[(.*?)\]\((https?://[^\s\)]+)\)z[\1](\2)r   

)r-   r9   r   r8   r   rU   r   r=   r:   resubr/   )paramsheaderindent_levelmax_line_lengthbase_indentparam_indentdesc_indentformatted_paramsr   r   r   type_strr8   	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	*++. ;;'((r3   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Or3   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Qr3   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
    r@   r   r   zComponents:r+   r   z`)r   r   z [r%   r   r   r   )r-   r'   rU   r9   r+   r   r8   r:   rc   rj   r/   rn   )
componentsr   r   add_empty_linesr   component_indentformatted_componentsr0   rO   	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)**r3   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
    r@   r   r   zConfigs:z (default: r&   r   r   r   )r-   r'   r8   r=   r:   rn   r/   )
configsr   r   r   r   config_indentformatted_configsr0   r;   config_descs
             r"   format_configsr   E  s     $K<!+,M }H56  $ w' )	6&}K?OqQR 2 2344K  - q3w<!#33$$R() 99&''r3   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.
    r@   zclass r   r   c              3   &   K   | ]	  }d |z     yw)z  Nr5   )rg   lines     r"   ri   z"make_doc_string.<locals>.<genexpr>  s      D Ds   r   r   )r   )striprm   r/   rn   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  k  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Mr3   )Argsr   s   )r   r  )r   r  T)r@   NNN)'rs   r   collectionsr   dataclassesr   r   r   typingr   r   r	   r
   r   r   r   rV   configuration_utilsr   r   utilsr   r   
get_loggerr+   rZ   r   r7   r   r   r   r   r   r   r   r   r   r   r  r5   r3   r"   <module>r     s     	 # 0 0 B B B  9 / 			H	%E[ EJ _ _ _D & & & g g g 
 
 
:/9dK)\PR4+n#(R 5r3   