
    
3j                     z   S SK r S SKrS SKrS SKJr  S SKJrJr  S SKJ	r	  S SK
JrJrJrJrJrJr  S SKrS SKrS SKJrJr  SSKJrJr  SS	KJr  SS
KJrJrJr  SSK J!r!  \" 5       (       a   \RD                  " \#5      r$Sr% " S S\5      r&\ " S S5      5       r'\ " S S5      5       r(0 S\)SSS._S\)SS._S\*SSS._S\*SS._S \*S!S._S"\*S#S$S._S%\*S&S'S._S(\RV                  S)S._S*\,\-   S+S._S,\-S-S.S._S/\R\                  R\                  \,\R\                  R\                     -  SS0S._S1\R^                  S2S._S3\R^                  S4S._S5\)S6S7S._S8\0\)\4   S9S._S:SS:S;S<._S=\R\                  R\                  SS>S._\*S?S.\R\                  R\                  SS@S.\-SASBS.\-SCSDS.\-SCSES.\*SFSGS.\R^                  SSHS.\R^                  SSIS.\R^                  SJS.\R^                  SKS.\R^                  SSLS.\*S&SMS.\Rb                  \Rd                  SNS.SO.Er3\,\R\                  R\                     SPS.\,\R\                  R\                     SQS.\R^                  SRS.\R^                  S:SSST.\R^                  S:SUST.\R^                  S:SVST.\R^                  S:SWST.\R^                  SXS.SY.r4\ " SZ S[5      5       r5\ " S\ S]5      5       r6S^ r7S_ r8SpS` jr9SqSa jr:SqSb jr;SrSc jr<SsSd jr=SsSe jr>Sf r?    StSg jr@Sh rASi rBSj\,\C\)\,\5   4      Sk\,\5   4Sl jrDSm\,\C\)\,\6   4      Sk\,\6   4Sn jrESk\0\)\4   4So jrFg)u    N)OrderedDict)	dataclassfield)	UnionType)AnyLiteralTypeUnionget_args
get_origin)InvalidSpecifierSpecifierSet   )ConfigMixin
FrozenDict)_is_single_file_path_or_url)DIFFUSERS_LOAD_ID_FIELDSis_torch_availablelogging)_is_package_availablea  {model_description}

## Example Usage

[TODO]

## Pipeline Architecture

This modular pipeline is composed of the following blocks:

{blocks_description} {trigger_inputs_section}

## Model Components

{components_description} {configs_section}

{io_specification_section}
c                        \ rS rSrS rS rSrg)InsertableDict;   c                     [        U R                  5       5      nU VVs/ s H  u  pVXQ:w  d  M  XV4PM     nnnUR                  X1U45        U R                  5         U R	                  U5        U $ s  snnf N)listitemsinsertclearupdate)selfkeyvalueindexr   kvs          l/home/wildlama/miniconda3/lib/python3.13/site-packages/diffusers/modular_pipelines/modular_pipeline_utils.pyr   InsertableDict.insert<   sg    TZZ\" %*6EDAQX!E6 	U%L) 	

E  7s
   A.A.c           	         U (       d  g/ n[        U R                  5       5       H  u  nu  p4[        U[        5      (       a  SUR                   SUR
                   S3nO1SUR                  R                   SUR                  R
                   S3nUR                  U S[        U5       SU S35        M     S	S
R                  U5      -   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__InsertableDict.__repr__L   s    %(6OA|%&&%e&6&6%7q8HK $EOO$>$>#?qAYAY@ZZ\]LLA3c$s)Bxj:;  7 &U(;;fDD     N)r1   r0   __qualname____firstlineno__r   r8   __static_attributes__r;   r:   r'   r   r   ;   s     Er:   r   c                      \ rS rSr% SrSr\S-  \S'   Sr\	S-  \S'   Sr
\S-  \S'   Sr\S-  \S'   \" SSS	0S
9r\\\   -  S-  \S'   \" SSS	0S
9r\S-  \S'   \" SSS	0S
9r\S-  \S'   \" SSS	0S
9r\S-  \S'   Sr\S   \S'   \" SSS0S
9r\\\   -  S-  \S'   S rS rS r\S\S\S\4S j5       r\S\\   4S j5       r\S\4S j5       r\S\S\\\S-  4   4S j5       r S"S\\\\4   -  S-  S\4S jjr!S\4S  jr"S!r#g)#ComponentSpec`   a  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_configrN   default_creation_methodFrepoc                 n    U R                   nUb&  U R                  c  [        R                  U SU5        g g g )NrI   )rQ   rI   object__setattr__)r!   
repo_values     r'   __post_init__ComponentSpec.__post_init__   s8    YY
!d&H&H&Pt%DjQ 'Q!r:   c                 Z    [        U R                  U R                  U R                  45      $ )z=Make ComponentSpec hashable, using load_id as the hash value.)hashrB   load_idrP   r!   s    r'   __hash__ComponentSpec.__hash__   s"    TYYd.J.JKLLr:   c                     [        U[        5      (       d  gU R                  UR                  :H  =(       a9    U R                  UR                  :H  =(       a    U R                  UR                  :H  $ )z8Compare ComponentSpec objects based on name and load_id.F)r.   r@   rB   rZ   rP   )r!   others     r'   __eq__ComponentSpec.__eq__   sW    %//II# N-N,,0M0MM	
r:   	componentreturnc                 z   [        US5      (       a  UR                  S:w  a  SnO[        U[        R                  R
                  5      (       a  [        S5      e[        U[        5      (       a)  [        US5      (       d  [        R                  S5        SnO&[        SU SUR                  R                   S	35      eUR                  n[        U[        5      (       a  US:X  a  UR                  nOS
n[        US5      (       a,  UR                  S:w  a  U R                  UR                  5      nO0 nU " SXXSS.UD6$ )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nullrN   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 methodrO   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)rB   rC   rE   rP   r;   )hasattrre   r.   torchnnModule
ValueErrorr   loggerwarningr2   r1   rE   decode_load_id)clsrB   rb   rP   rC   rE   	load_specs          r'   from_componentComponentSpec.from_component   s?   ( 9233	8T8TX^8^&7# )UXX__55 {  I{33y*>??NNv +8' !7vQy?R?R?[?[>\ ]u v  ''	i--2I]2Z%%FF9233	8T8TX^8^**9+G+GHII 
6
nw
 	
r:   c                 ,    [         R                  " 5       $ )uh   
Return the names of all loading‐related fields (i.e. those whose field.metadata["loading"] is True).
)r   copy)rp   s    r'   loading_fieldsComponentSpec.loading_fields   s    
 (,,..r:   c                     U R                   S:X  a  gU R                  5        Vs/ s H  n[        X5      PM     nnU Vs/ s H	  o3c  SOUPM     nnSR                  U5      $ s  snf s  snf )z
Unique identifier for this spec's pretrained load, composed of
pretrained_model_name_or_path|subfolder|variant|revision (no empty segments).
rO   rf   |)rP   rv   getattrr5   )r!   r%   partsps       r'   rZ   ComponentSpec.load_id   sk     ''=8+/+>+>+@A+@a!+@A5:;U9!+U;xx B;s
   A"A'rZ   c                     U R                  5       n[        R                  U5      nUS:X  a  U$ UR                  S5      n[	        U5       H%  u  pVU[        U5      :  d  M  US:X  a  SOUX2U   '   M'     U$ )ae  
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).
rf   ry   N)rv   dictfromkeyssplitr-   len)rp   rZ   rv   resultr{   r6   parts          r'   ro   ComponentSpec.decode_load_id   sy    $ ++-~.fM c" !'GA3~&&48FNDa() (
 r:   c                    U R                   b  [        U R                   [        5      (       d  [        S5      eU=(       d    U R                  =(       d    0 n[        U R                   [        5      (       a  U R                   R                  " U40 UD6nO[        R                  " U R                   R                  5      R                  n0 nUR                  5        H  u  pgXd;   d  M  XuU'   M     UR                  5        H  u  pgXd;   d  M  XuU'   M     U R                   " S0 UD6nSUl        [        US5      (       a  UR                  U l        U$ )z/Create component using from_config with config.z?`type_hint` is required when using from_config creation method.rf   rE   r;   )rC   r.   r/   rl   rE   
issubclassr   rO   inspect	signature__init__
parametersr   re   rh   )r!   rE   kwargsrb   signature_paramsinit_kwargsr%   r&   s           r'   createComponentSpec.create
  s    >>!DNND)I)I^__,4;;,"dnnk22226DVDI&001H1HITTK(%&N ' (%&N ' 55I'-	$9h''#**DKr:   c                 n   U R                  5        Vs0 s H  o"U;   d  M
  X!R                  U5      _M     nnU R                  5        Vs0 s H  o"UR                  U[        X5      5      _M      nnUR                  SS5      nUc  [	        S5      e[        U5      nU(       a%  U R                  c  [	        SU R                   35      eSSKJ	n  U R                  bG  [        U R                  [        R                  R                  U45      (       d  UR                  SS5        U R                  c(   UR                  " U40 UDUD6nUR                   U l        O?U(       a  [        U R                  S
5      O[        U R                  S5      n
 U
" U40 UDUD6nXPl        UR%                  5        H  u  p['        XU5        M     U R(                  Ul        U$ s  snf s  snf ! [         a   n	[	        SU R                   S	U	 35      eSn	A	ff = f! [         a   n	[	        SU R                   SU	 35      eSn	A	ff = f)z%Load component using from_pretrained.rI   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   )	AutoModeltorch_dtypezUnable to load z without `type_hint`: from_single_filerN   z using load method: )rv   popgetrz   rl   r   rC   rB   	diffusersr   r   ri   rj   rk   rN   	Exceptionr2   rI   r   setattrrZ   re   )r!   r   r"   passed_loading_kwargsload_kwargsrI   is_single_filer   rb   eload_methodr%   r&   s                r'   loadComponentSpec.load&  s<    BFATATAV hAV#agZg!5jjo!5AV hZ^ZmZmZopZoSV155c74;MNNZop(38WY](^%(0 N  55RSdnn4ijnjsjsitu  	(
 >>%j%((//[dIe.f.fJJ}d+>>!Y%556SmWbmflm	 '00DN
 " (:;T^^->? W'(E__X^_	 .K*%%'DADQ ('+||	$a !ip0  Y ?499+=STUSV!WXXY  W ?499+=QRSQT!UVVWs@   	GG	%G/G 
H
 
H'HH

H4H//H4)rE   rI   rC   r   )$r1   r0   r<   r=   __doc__rB   str__annotations__rC   r	   rD   rE   r   r   rI   r   rK   rL   rM   rP   r   rQ   rV   r\   r`   classmethodr   rr   rv   propertyrZ   r   ro   r   r   r>   r;   r:   r'   r@   r@   `   s   $ D#*!Itd{!"Kt" $FJ$<A$ZceiYj<k!3c?T#9k!"	47HIIsTzI	47HIGS4ZI D8IJHcDjJIZW%EFZ $)E@R#SD#S	/D
 SR
M
 9
# 9
# 9
# 9
 9
v /tCy / / 	 	 	  S  T#sTz/-B    LZ$sCx.84? UX 83 3r:   r@   c                   B    \ rS rSr% Sr\\S'   \\S'   Sr\S-  \S'   Sr	g)
ConfigSpeci\  z5Specification for a pipeline configuration parameter.rB   rG   NrD   r;   )
r1   r0   r<   r=   r   r   r   r   rD   r>   r;   r:   r'   r   r   \  s    ?
IL"Kt"r:   r   promptTz0The prompt or prompts to guide image generation.)rC   requiredrD   negative_promptz8The prompt or prompts not to guide the image generation.)rC   rD   max_sequence_lengthi   z,Maximum sequence length for prompt encoding.)rC   rG   rD   heightz,The height in pixels of the generated image.widthz+The width in pixels of the generated image.num_inference_steps2   zThe number of denoising steps.num_images_per_prompt   z,The number of images to generate per prompt.	generatorz-Torch generator for deterministic generation.sigmasz(Custom sigmas for the denoising process.strengthg?z Strength for img2img/inpainting.imagezJReference image(s) for denoising. Can be a single image or list of images.latentsz1Pre-generated noisy latents for image generation.	timestepsz$Timesteps for the denoising process.output_typepilz!Output format: 'pil', 'np', 'pt'.attention_kwargsz+Additional kwargs for attention processors.denoiser_input_fieldsz[conditional model inputs for the denoiser: e.g. prompt_embeds, negative_prompt_embeds, etc.)rB   kwargs_typerD   
mask_imagezMask image for inpainting.z(Padding for mask cropping in inpainting.z*Control image for ControlNet conditioning.g        z"When to start applying ControlNet.g      ?z!When to stop applying ControlNet.z"Scale for ControlNet conditioning.   z*Number of layers to extract from the imagez\text embeddings used to guide the image generation. Can be generated from text_encoder step.zFmask for the text embeddings. Can be generated from text_encoder step.zenegative text embeddings used to guide the image generation. Can be generated from text_encoder step.zOmask for the negative text embeddings. Can be generated from text_encoder step.zYimage latents used to guide the image generation. Can be generated from vae_encoder step.zNumber of prompts, the final batch size of model inputs should be batch_size * num_images_per_prompt. Can be generated in input step.z>The dtype of the model inputs, can be generated in input step.)padding_mask_cropcontrol_imagecontrol_guidance_startcontrol_guidance_endcontrolnet_conditioning_scalelayersprompt_embedsprompt_embeds_masknegative_prompt_embedsnegative_prompt_embeds_maskimage_latents
batch_sizedtypezGenerated images.zThe generated videos.zDenoised latents.zThe prompt embeddings.)rC   r   rD   zThe encoder attention mask.zThe negative prompt embeddings.z$The negative prompt embeddings mask.z-The latent representation of the input image.)imagesvideosr   r   r   r   r   r   c                       \ rS rSr% SrSr\\S'   Sr\	\S'   Sr
\	\S'   Sr\\S'   S	r\\S
'   Sr\\S'   Sr\\\	4   \S'   S r\SS\S\SS 4S jj5       rSrg)
InputParami#  z%Specification for an input parameter.NrB   rC   rG   Fr   rJ   rD   r   rH   c                 h    SU R                    SU R                  (       a  SOS SU R                   S3$ )N<: r   optionalz
, default=>)rB   r   rG   r[   s    r'   r8   InputParam.__repr__/  s3    499+Rdmm
LJW[WcWcVddeffr:   template_namenoterc   c                    U[         ;  a  [        SU S35      e[         U   R                  5       nUR                  SUR                  SU5      5      nU(       a  SU;   a  US    SU S3US'   UR	                  U5        U " SSU0UD6$ )<Get template for name if exists, otherwise raise ValueError.zInputParam template for 
 not foundrB   rD    (r,   r;   )INPUT_PARAM_TEMPLATESrl   ru   r   r    rp   r   r   	overridestemplate_kwargsrB   s         r'   templateInputParam.template2  s      557jQRR/>CCE }}V_%8%8%OPM_40?0N/OrRVQWWX-YOM*y)0000r:   r;   r   )r1   r0   r<   r=   r   rB   r   r   rC   r   rG   r   boolrD   r   rH   r   r8   r   r   r>   r;   r:   r'   r   r   #  s    /D#IsGSHdKK#Hd38n#g 1S 1 1L 1 1r:   r   c                       \ rS rSr% Sr\\S'   Sr\\S'   Sr	\\S'   Sr
\\S'   Sr\\\4   \S	'   S
 r\SS\S\SS 4S jj5       rSrg)OutputParamiG  z&Specification for an output parameter.rB   NrC   rJ   rD   r   rH   c                     SU R                    S[        U R                  S5      (       a  U R                  R                  O[	        U R                  5       S3$ )Nr   r   r1   r   )rB   rh   rC   r1   r   r[   s    r'   r8   OutputParam.__repr__Q  sI    		{"PZ8[8[T^^44adeiesesatuuvw	
r:   r   r   rc   c                    U[         ;  a  [        SU S35      e[         U   R                  5       nUR                  SUR                  SU5      5      nU(       a  SU;   a  US    SU S3US'   UR	                  U5        U " SSU0UD6$ )r   zOutputParam template for r   rB   rD   r   r,   r;   )OUTPUT_PARAM_TEMPLATESrl   ru   r   r    r   s         r'   r   OutputParam.templateV  s      668zRSS0?DDF }}V_%8%8%OPM_40?0N/OrRVQWWX-YOM*y)0000r:   r;   r   )r1   r0   r<   r=   r   r   r   rC   r   rD   r   rH   r   r8   r   r   r>   r;   r:   r'   r   r   G  sh    0
IIsKK#Hd38n#

 1S 1 1M 1 1r:   r   c                 <   U  Vs/ s H  oR                   (       d  M  UPM     nnU  Vs/ s H  oR                   (       a  M  UPM     nnSR                  S U 5       5      nSR                  S U 5       5      nUnU(       a  U(       a  U SU 3OUnU$ s  snf s  snf )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   8   #    U  H  oR                   v   M     g 7fr   )rB   .0params     r'   	<genexpr>&format_inputs_short.<locals>.<genexpr>~  s     E_EZZ_s   c              3   V   #    U  H  oR                    S UR                   3v   M!     g7f)=N)rB   rG   r   s     r'   r   r     s!     Z/

|1U]]O</s   '))r   r5   )inputsr   required_inputsoptional_inputsrequired_stroptional_str
inputs_strs          r'   format_inputs_shortr   k  s      +1C&NNu&OC*0G&u&OG99E_EEL99Z/ZZLJ8D
|2l^4,
 DGs   BBBBc                 &   / nU  H{  nUR                   U;   a!  UR                  SUR                    S35        M4  UR                   c  UR                  b  SUR                  -   nOUR                   nUR                  U5        M}     U  Vs1 s H  oDR                   iM     nn/ n/ nU HK  n	U	R                   U;   a  UR                  U	R                   5        M0  UR                  U	R                   5        MM     / n
U(       a#  U
R                  SSR                  U5       35        U(       a#  U
R                  SSR                  U5       35        U(       a#  U
R                  SSR                  U5       35        U
(       a  SR                  U
5      $ S	$ s  snf )
a  
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    - inputs: r+   z    - modified: z    - outputs: 
z
    (none))rB   r3   r   r5   )intermediate_inputsrequired_intermediate_inputsintermediate_outputsinput_partsinpinp_name
inputs_setmodified_partsnew_output_partsoutr   s              r'   format_intermediates_shortr    sV   " K"8833388*A67xxCOO$?#//188x( # '::&9s((&9J:N#88z!!!#((+##CHH-	 $ Ftyy'=&>?@(>)B(CDE		2B(C'DEF &499V8L8% ;s   Fc                    U (       d  gSU-  nSUS-   -  nSUS-   -  n/ nS nS n	UR                  U U S35        U  GH  n
U
R                  [        :w  a  U" U
R                  5      OSnU
R                  c  U
R                  b  SU
R                   3OU
R                  nU U S	U S
3n[        U
S5      (       a5  U
R                  (       d$  US-  nU
R                  b  USU
R                   3-  nUS-  nU
R                  (       a6  [        R                  " SSU
R                  5      nU	" XU5      nUSU U 3-  nO	USU S3-  nUR                  U5        GM     SR                  U5      $ )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
rJ    r      c                 N   [        U [        5      (       d  [        U 5      [        L aR  [	        U 5       Vs/ s H+  n[        US5      (       a  UR                  O
[        U5      PM-     nnSR                  U5      $ [        U S5      (       a  U R                  $ [        U 5      $ s  snf Nr1   z | 	r.   r   r   r
   r   rh   r1   r   r5   rC   t	type_strss      r'   get_type_str#format_params.<locals>.get_type_str      i++z)/D/MS[\eSfgSfawq*'='=3q6ISfIg::i((%,Y
%C%Cy!!WYW h   2B"c                    U R                  5       n/ n/ nSnU Hn  n[        U5      U(       a  SOS-   nU(       a8  Xh-   U:  a0  UR                  SR                  U5      5        U/n[        U5      nMY  UR                  U5        Xh-  nMp     U(       a   UR                  SR                  U5      5        SU 3R                  U5      $ )zFWrap text while preserving markdown links and maintaining indentation.r   r   r	  r   )r   r   r3   r5   )	textindent
max_lengthwordslinescurrent_linecurrent_lengthwordword_lengths	            r'   	wrap_text format_params.<locals>.wrap_text  s    

Dd)Lqa@K <z ISXXl34 $v!$T##D)-  LL,/0F8}!!%((r:   :** (``r   , *optional*z, defaults to z):z \[(.*?)\]\((https?://[^\s\)]+)\)z[\1](\2)r   zTODO: Add description.)r3   rC   r   rB   r   rh   r   rG   rD   resubr5   )paramsheaderindent_levelmax_line_lengthbase_indentparam_indentdesc_indentformatted_paramsr  r  r   type_strrB   	param_strdescwrapped_descs                   r'   format_paramsr4    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2k]*@AAI	*/ 2 99%&&r:   c                     [        U SX5      $ )ak  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r4  )input_paramsr*  r+  s      r'   format_input_paramsr9  
  s     xOOr:   c                     [        U SX5      $ )ao  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
Outputsr7  )output_paramsr*  r+  s      r'   format_output_paramsr=    s     	<QQr:   c                 @   U (       d  gS nU(       a  SU S3/O/ nU  H  nUR                   [        :w  a  U" UR                   5      OSnUR                  c  UR                  b  SUR                   3OUR                  nSU SU S3n[	        US5      (       a6  UR
                  (       d%  US	-  nUR                  b  US
UR                   S3-  nUS-  nUR                  (       a  UR                  OSnUSU 3-  nUR                  U5        M     SR                  U5      $ )aW  Format a list of InputParam or OutputParam objects as a markdown bullet-point list.

Suitable for model cards rendered on Hugging Face Hub.

Args:
    params: list of InputParam or OutputParam objects to format
    header: Header text (e.g. "Inputs" or "Outputs")

Returns:
    A formatted markdown string, or empty string if params is empty.
rJ   c                 N   [        U [        5      (       d  [        U 5      [        L aR  [	        U 5       Vs/ s H+  n[        US5      (       a  UR                  O
[        U5      PM-     nnSR                  U5      $ [        U S5      (       a  U R                  $ [        U 5      $ s  snf r  r  r  s      r'   r  ,format_params_markdown.<locals>.get_type_str5  r  r  r"  z:**
z- `z` (`r$  r   r%  z, defaults to `r,   zNo description providedr   r   )
rC   r   rB   r   rh   r   rG   rD   r3   r5   )	r(  r)  r  r  r   r0  rB   r1  r2  s	            r'   format_params_markdownrA  &  s    X %+r& E49OOs4J<0PR+0::+=%BSBSB_E%%&'ejeoeo$tH:Q/	5*%%enn'I}}(u}}oQ??	S	$)$5$5u  ;Tr$[ 	Y  99Ur:   c                    U (       d  gSU-  nSUS-   -  n/ nUR                  U S35        U(       a  UR                  S5        [        U 5       GH%  u  px[        UR                  S5      (       a  UR                  R                  O[        UR                  5      n	U UR                   SU	 S3n
UR                  (       a  U
SUR                   3-  n
/ nUR                  5        H-  n[        X5      nU(       d  M  UR                  U S	U 35        M/     U(       a  U
S
SR                  U5       S3-  n
UR                  U
5        U(       d  M  U[        U 5      S-
  :  d  GM  UR                  S5        GM(     SR                  U5      $ )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
rJ   r	  r   zComponents:r1   r#  `)r   r   z [r+   ]r   r   )r3   r-   rh   rC   r1   r   rB   rD   rv   rz   r5   r   )
componentsr*  r+  add_empty_linesr,  component_indentformatted_componentsr6   rb   	type_namecomponent_descloading_field_values
field_namefield_values                 r'   format_componentsrN  N  s    $KlQ./ ;-{ ;<##B' "*- -4I4G4G,T,TI((Z]^g^q^qZr 	 --inn-=S2N  9#8#8"9::N  "#224J!)8K{$++zl!K=,IJ 5  499-A#B"C1EEN##N3 ?q3z?Q#66 ''+3 .6 99)**r:   c                    U (       d  gSU-  nSUS-   -  n/ nUR                  U S35        U(       a  UR                  S5        [        U 5       H  u  pxU UR                   SUR                   S3n	UR                  (       a  U	SUR                   3-  n	UR                  U	5        U(       d  M`  U[        U 5      S-
  :  d  Mt  UR                  S5        M     S	R                  U5      $ )
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
rJ   r	  r   zConfigs:z (default: r,   r   r   r   )r3   r-   rB   rG   rD   r   r5   )
configsr*  r+  rF  r,  config_indentformatted_configsr6   rE   config_descs
             r'   format_configsrT    s     $K<!+,M }H56  $ w'	&}K?OqQR 2 2344K  - ?q3w<!#33$$R( ( 99&''r:   c                 d   U c  gS/nU R                  5        H  u  p#UR                  5        VVs/ s H  u  pEU(       d  M  UPM     nnnU(       a1  SR                  S U 5       5      nUR                  SU SU 35        Mj  UR                  SU S35        M     SR                  U5      $ s  snnf )	zFormat a workflow map into a readable string representation.

Args:
    workflow_map: Dictionary mapping workflow names to trigger inputs

Returns:
    A formatted string representing all workflows
rJ   zSupported workflows:r+   c              3   .   #    U  H  nS U S 3v   M     g7fr$  Nr;   r   r  s     r'   r   "format_workflow.<locals>.<genexpr>  s     "E_Qqc8_   z  - `z`: requires z*`: default (no additional inputs required)r   )r   r5   r3   )workflow_mapr  workflow_nametrigger_inputsr%   r&   r   r   s           r'   format_workflowr^    s     #$E)5););)=%)7)=)=)?E)?11)?E"E_"EEJLL5|J<HILL5/YZ[ *> 99U Fs   B,B,c                    SnU(       a	  USU S3-  nU(       a>  UR                  5       R                  S5      nSR                  S U 5       5      nXhS-   -  nU(       a!  [        U5      S:  a  [	        USSS	9n	XiS-   -  nU(       a!  [        U5      S:  a  [        USSS	9n
XjS-   -  nU[        U SS
9-  nUS-  nU[        USS
9-  nU$ )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.
rJ   zclass 

r   c              3   H   #    U  H  nS UR                  5       -   v   M     g7f)z  N)rstrip)r   lines     r'   r   "make_doc_string.<locals>.<genexpr>  s      M*$!5*s    "r   r   Fr*  rF  )r*  )stripr   r5   r   rN  rT  r9  r=  )r   outputsrD   
class_nameexpected_componentsexpected_configsoutput
desc_linesaligned_desccomponents_strconfigs_strs              r'   make_doc_stringrp    s    0 F F:,d++  &&(..t4
yy M* MM'' s#67!;*+>Q`ef6)) C 01A5$%5AW\]&& !&q99F fF
"7;;FMr:   c           	      ,   U c  0 nO+[        U [        5      (       d  [        S5      e[        U 5      nU(       d  0 $ 0 nUR	                  5        H  u  p4[        U5      u  pVU(       d  [        R                  U S35        U(       ab   [        U5      nUS:X  a  [        R                  SU SU S	35        O3UR                  US
S9(       d  [        R                  U SU SU S35        XBU'   M     U$ ! [         a  n[        SU SU S35      UeS nAff = f)NzZRequirements must be provided as a dictionary mapping package names to version specifiers.zO was specified in the requirements but wasn't found in the current environment.zRequirement specifier 'z' for z is invalid.zN/AzVersion of z2 could not be determined to validate requirement 'z '. Things might work unexpected.T)prereleasesz requirement 'z,' is not satisfied by the installed version z. Things might work unexpected.)r.   r   rl   _normalize_requirementsr   r   rm   rn   r   r   contains)	reqsnormalized_reqsfinalreqspecified_verreq_availablereq_actual_ver	specifiererrs	            r'   _validate_requirementsr~    sH   |$%%l  2$7	E-335(=c(B%NNcU"qrsl(7	 &!#&XYfXg  hH  I ''D'Ie>-8desdt  uT  U #c
) 6, L $ l #:=/PSuT`!abhkkls   C11
D;DDc                 x   ^^ U (       d  0 $ [        5       mS[        [        [        4   4UU4S jjmT" U 5        T$ )Nmappingc                   > U R                  5        GH  u  p[        U[        5      (       a
  T" U5        M%  [        U5      R	                  5       nU(       d  [        S5      eUc  SO[        U5      R	                  5       nU(       a  UR                  S5      (       d  SU 3nTR                  U5      nUb^  U(       d  U(       a  UTU'   OGU(       a@  U(       a9  XT:w  a4   [        SR                  [        S XT/5      5      5      n[        U5      TU'   GM  UTU'   GM
     g ! [         a%    [        R                  SU SU SU S	U S
3	5         N<f = f)Nz)Requirement package name cannot be empty.rJ   )r   r   r   !~z==,zConflicting requirements for 'z' detected: 'z' vs 'z'. Keeping 'z'.)r   r.   r   r   rf  rl   
startswithr   r   r5   filterr   rm   rn   )	r  pkgspecpkg_namespec_strexisting_speccombined_spec_accumulate
normalizeds	          r'   r  ,_normalize_requirements.<locals>._accumulate(  sD    IC$%% D!3x~~'H !LMM!\rs4y/@H 3 34M N Nz?&NN84M($+3Jx("xM4MB(4SXXfTMKd>e5f(g 03=/A
8,#+Jx = ), , <XJmTaSbbhiqhrr~  @M  N  NP  Qs   %D,EE)r   r   r   r   )ru  r  r  s    @@r'   rs  rs  "  s<    	*5-J,T#s(^ , ,B r:   named_input_listsrc   c                  <   0 n0 nU  H  u  p4U H  nUR                   c  UR                  b  SUR                  -   nOUR                   nXa;   a  X   nUR                  bp  UR                  bc  UR                  UR                  :w  aI  [        R                  " SU SUR                   SX&    SUR                   SU SUR                   S35        UR                  c  UR                  b
  XQU'   X2U'   M  M  M  XQU'   X2U'   M     M     [        UR                  5       5      $ )a  
Combines multiple lists of InputParam objects from different blocks. For duplicate inputs, updates only if current
default value is None and new default value is not None. Warns if multiple non-None default values exist for the
same input.

Args:
    named_input_lists: List of tuples containing (block_name, input_param_list) pairs

Returns:
    List[InputParam]: Combined list of unique InputParam objects
r   z3Multiple different default values found for input 'z': z (from block 'z') and z
'). Using r*   )rB   r   rG   warningswarnr   values)r  combined_dictvalue_sources
block_namer   input_param
input_namecurrent_params           r'   combine_inputsr  N  sC    MM/
!K'K,C,C,O!K$;$;;
(--
* - 9!))5#++7%--1D1DDMMMj\Y\(001@Y?ZZa&../~j\TaTiTiSjjkm
 !((0[5H5H5T0;*-0:*- 6U0 -8j),6j)- " 02 $$&''r:   named_output_listsc                      0 nU  HV  u  p#U HK  nUR                   U;  d*  XR                      R                  b  M.  UR                  c  M=  XAUR                   '   MM     MX     [        UR                  5       5      $ )a:  
Combines multiple lists of OutputParam objects from different blocks. For duplicate outputs, keeps the first
occurrence of each output name.

Args:
    named_output_lists: List of tuples containing (block_name, output_param_list) pairs

Returns:
    List[OutputParam]: Combined list of unique OutputParam objects
)rB   r   r   r  )r  r  r  rg  output_params        r'   combine_outputsr  y  sr     M1
#L!!6//0<<DIaIaIm3?l//0	 $  2 $$&''r:   c           	      &  ^4 U R                   R                  nUR                  SS5      n[        U SS5      n/ n[        U SS5      =(       d    0 nU(       a  [	        UR                  5       5       H  u  nu  pxUR                   R                  n	[        USS5      (       a  UR                  R                  S5      S	   OSn
UR                  US
-    SU SU	 S35        U
(       d  Mv  UR                  SU
 35        M     U(       a  SR                  U5      OSn[        U S/ 5      nU(       a  [        US	SS9nUR                  SS5      R                  5       nU(       a~  UR                  S5       Vs/ s H)  oR                  5       (       d  M  UR                  5       PM+     nn[	        U5       VVs/ s H  u  poUS
-    SU 3PM     nnnSR                  U5      nOSnOSn[        U S/ 5      nSnU(       a7  [        US	SS9nUR                  SS5      R                  5       nU(       a  SU 3n[        U SS5      SLnU(       Ga  U R                  n/ nU R                  n[        U SS5      nUb  UU:w  a  UOSnUR                  S5        UR                  5        H  u  nn[        UR!                  5       5      n U R#                  U5      nUR&                  n U  V!s/ s H  n!U!R(                  U;   d  M  U!PM     n"n!UR                  SU S35        [+        U"SS!9n#UR                  U#(       a  U#OS"5        UR                  S5        UR                  S 5        M     U R&                  n$Ub  UOU R                  n%[+        U$S#5      n#[+        U%S$5      n&U#(       a  U#OS%n'U&(       a  U&OS&n(UR                  S'U' S(U( 35        SR                  U5      n)Sn*OU R&                  n+U R                  n,[+        U+S#5      n#[+        U,S$5      n&U#(       a  U#OS%n'U&(       a  U&OS&n(S)U' S(U( 3n)Sn*[-        U S*5      (       aa  U R.                  (       aP  [1        U R.                   V-s/ s H
  n-U-c  M  U-PM     sn-5      n.U.(       a  S+R                  S, U. 5       5      n/S-U/ S3n*S.S//n0[-        U S05      (       a,  U R2                  (       a  U0R                  U R2                  5        U(       a  [        U R                  R!                  5       5      n1[5        S1 U1 5       5      (       a  U0R                  S25        [5        S3 U1 5       5      (       a  U0R                  S45        [5        S5 U1 5       5      (       a  U0R                  S65        [5        S7 U1 5       5      (       a  U0R                  S85        O[-        U S*5      (       a  U R.                  (       a  U R.                  m4[5        U44S9 jS: 5       5      (       a  U0R                  S25        [5        U44S; jS< 5       5      (       a  U0R                  S45        [5        U44S= jS> 5       5      (       a  U0R                  S65        [5        U44S? jS@ 5       5      (       d  U0R                  S85        OU0R                  S85        [7        U R8                  5      n2SAU SBU SCU2 SD3n3UU3UUUU)U*U0SE.$ s  snf s  snnf ! [$         a<    UR                  SU S35        UR                  S5        UR                  S 5         GMl  f = fs  sn!f s  sn-f )Fas  
Generate model card content for a modular pipeline.

This function creates a comprehensive model card with descriptions of the pipeline's architecture, components,
configurations, inputs, and outputs.

Args:
    blocks: The pipeline's blocks object containing all pipeline specifications

Returns:
    Dict[str, Any]: A dictionary containing formatted content sections:
        - pipeline_name: Name of the pipeline
        - model_description: Overall description with pipeline type
        - blocks_description: Detailed architecture of blocks
        - components_description: List of required components
        - configs_section: Configuration parameters section
        - io_specification_section: Input/Output specification (per-workflow or unified)
        - trigger_inputs_section: Conditional execution information
        - tags: List of relevant tags for the model card
Blocksz	 PipelinerD   zA modular diffusion pipeline.
sub_blocksNrJ   r   r   r   z. **z** (`rC  z   - zNo blocks defined.ri  Fre  zComponents:
z. z No specific components required.zFNo specific components required. Components can be loaded dynamically.rj  z	Configs:
z

## Configuration Parameters

_workflow_mapr   z ## Workflow Input Specification
z<details>
<summary><strong>z</strong></summary>
z%*Could not resolve workflow blocks.*
z</details>
)r)  zNo additional inputs required.r6  r;  zNo specific inputs defined.zStandard pipeline outputs.z 
## Input/Output Specification

r`  z## Input/Output Specification

r]  r+   c              3   .   #    U  H  nS U S 3v   M     g7frW  r;   rX  s     r'   r   6generate_modular_model_card_content.<locals>.<genexpr>  s     .UATA1#QxATrZ  z~
### Conditional Execution

This pipeline contains blocks that are selected at runtime based on inputs:
- **Trigger Inputs**: zmodular-diffusersr   
model_namec              3   ,   #    U  H
  nS U;   v   M     g7f)
inpaintingNr;   r   wfs     r'   r   r  "       ;Nb|r!N   r  c              3   ,   #    U  H
  nS U;   v   M     g7f)image2imageNr;   r  s     r'   r   r  $  s     <^r}"^r  zimage-to-imagec              3   ,   #    U  H
  nS U;   v   M     g7f)
controlnetNr;   r  s     r'   r   r  &  r  r  r  c              3   ,   #    U  H
  nS U;   v   M     g7f)
text2imageNr;   r  s     r'   r   r  (  r  r  ztext-to-imagec              3   ,   >#    U  H	  oT;   v   M     g 7fr   r;   r   r  triggerss     r'   r   r  ,  s     =&<H}&<   )maskr   c              3   ,   >#    U  H	  oT;   v   M     g 7fr   r;   r  s     r'   r   r  .  s     A&@H}&@r  )r   r   c              3   ,   >#    U  H	  oT;   v   M     g 7fr   r;   r  s     r'   r   r  0  s     K&JH}&Jr  )r   controlnet_condc              3   ,   >#    U  H	  oT;   v   M     g 7fr   r;   r  s     r'   r   r  2  s     [*ZQ=*Zr  )r   r  r   r   up   This is a modular diffusion pipeline built with 🧨 Diffusers' modular pipeline framework.

**Pipeline Type**: z

**Description**: z

This pipeline uses a z8-block architecture that can be customized and extended.)pipeline_namemodel_descriptionblocks_descriptioncomponents_descriptionconfigs_sectionio_specification_sectiontrigger_inputs_sectiontags)r2   r1   replacerz   r-   r   rD   r   r3   r5   rN  rf  rT  r  rg  setkeysget_workflowr   r   rB   rA  rh   r]  sortedr  anyr   r  )5blocksblocks_class_namer  rD   blocks_desc_partsr  r6   rB   blockblock_class
block_descr  rE  rn  r  rc  r  enumerated_linesrP  r  ro  configs_descriptionhas_workflowsr[  r{   blocks_outputsblocks_intermediateshared_outputswf_namer]  trigger_input_namesworkflow_blocks	wf_inputsr|   trigger_paramsr   
all_inputsall_outputsoutputs_strinputs_descriptionoutputs_descriptionr  r  r   rg  r  trigger_inputs_listtrigger_inputs_strr  workflow_namesblock_countr  r  s5                                                       @r'   #generate_modular_model_card_contentr    s   * ((11%--hDM&-1PQK t4:J )**:*:*< =A}//22K=DUM[]=^=^**006q9dfJ$$Awd4&k]"%MNz!((5)=> !> :K#45Pd!6;J*:AW\]!/!7!7!L!R!R!T!.D.J.J4.Pa.PdT^T^T`\TZZ\.PEaBKEBRSBRwq1q5'D6 2BRS%)YY/?%@"%G"!if0"5GO$W1eT)11,CIIK CDWCXYO FOT:$FM++  %f.DdK1=.TgBgNmq 	 	89 (4'9'9';#G^"%n&9&9&;"<"("5"5g"> (..I)2TAaff@S6SaNTLL7y@UVW/tLJLLz7WXLLLL() (<. ]]
(6(Bn+JA
,[)D+5Z;X-8k>Z:;M:NdSfRghi#'99U#3 !# ..+FH=
,Wi@+5Z;X-8k>Z%FGYFZZ^_r^s#t !#6+,,1F1F"(V5J5J)\5Ja!5J)\"]"%)YY.UAT.U%U". ** +	*&  -Dv|$$):):F%%&V116689;N;;;KK%<^<<<KK();N;;;KK%;N;;;KK(	)	*	*v/D/D((=&<===KK%A&@AAAKK()K&JKKKKK%[*Z[[[KK(O$f''(K%& ' !]"Z^ '.0"8*$<"8	 	G bSJ  ;G9DYZ[EF^,	 UH *]s=   0Z5Z50Z:9[ \	2\	\\ A\\)Argsr   s   )r   r  )r6  )r   r  T)rJ   NNN)Gr   r&  r  collectionsr   dataclassesr   r   typesr   typingr   r   r	   r
   r   r   	PIL.ImagePILri   packaging.specifiersr   r   configuration_utilsr   r   loaders.single_file_utilsr   utilsr   r   r   utils.import_utilsr   
get_loggerr1   rm   MODULAR_MODEL_CARD_TEMPLATEr   r@   r   r   int	Generatorr   floatImageTensorr   r   float32r   r   r   r   r   r  r4  r9  r=  rA  rN  rT  r^  rp  r~  rs  tupler  r  r  r;   r:   r'   <module>r     s*    	  # (  B B   ? 9 C I I 6 			H	% (E[ EJ x x xv # # #OIO QO EO EO& D'O. 7/O8 E9OB __FCOJ %[AKOR 9SO\ YY__tCIIOO'<<c]Of \\JgOn \\=oOv :wO@ #s(^DAOH .tIOT YY__3UO` A YY__C ; : ;& C \\u \\_ \\~
 \\h$
 \\r  _ [[==WUO f #))//**
 #))//*.
 \\* \\./ \\.4 \\.8 \\.=$ \\FE& R  1  1  1F  1  1  1F:/9dM'`PR%P4+n#(L6 5p$N)X((tE#tJ7G2G,H'I ((dS]N^ ((V(eCk9J4J.K)L (QUVaQb (.y4S> yr:   