
    wiҏ                     b   d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlZd dlZd dlZd dlmZ d dlmZmZ d dlmZ d dlmZmZmZmZmZ d dlZd dlZd dl Zd dl!Z!d dl"m#Z# d dl$m%Z% dd	l&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2 dd
lm3Z3  ej4                    Z5 e3e6          Z7 e-            oL e%j8         e%j8        ej9        %                    d                    j:                   e%j8        d          k    Z; e2            oL e%j8         e%j8        ej9        %                    d                    j:                   e%j8        d          k    Z<e;oe<Z= e/            r6d dl>Z>dej?        v r>ej?        d         Z@	  ejA        e@          ZBn# eC$ rZD eCde@ deD           eDdZD[Dww xY wdej?        v rTej?        d         ZE	  e>jF        eE          ZBn# eG$ rZD eGdeE           eDdZD[Dww xY we7H                    deE            ne>jI        J                                rdndZE e%j8         e%j8        e>jK                  j:                   e%j8        d          k    ZLeLr5 eMe>jN        d          ZOeOr e>jN        jP        J                                rdneEZEd ZQd ZR	 	 	 	 d~dZSddZTdeUfd ZVdd"ZW eWd#d!$          ZX eWd%d!$          ZYdd'ZZd( Z[d) Z\d* Z]d+ Z^d, Z_d- Z`d. Zad/ Zbd0 Zcd1 Zdd2 Zed3 Zfd4 Zgd5 Zhd6 Zid7 Zjd8 Zkd9 Zld: Zmd; Znd< Zod= Zpd> Zqdd?eerejs        f         d@eer         dejs        fdAZtdBerfdCZudDeerejv        jv        f         dejv        jv        fdEZwdDejv        dFeUfdGZxddDeejv        jv                 dHerderfdIZyedJ             ZzddKerfdLZ{ddMerfdNZ|ddOeejs                 dPerderfdQZ}dejs        fdRZ~i ZdS ZdT ZddVeUdWee         dXeer         fdYZddZZ G d[ d\          Zd] Zd^ Zd_ Zd` Z e/            rEdadad!dadbZe>jI        j        ddddbZe>jI        j        dc dd d dbZe>jI        j        e>j        e>j        deZdferdgeeref         fdhZdferdieUfdjZdferfdkZdferfdlZdferfdmZ e/            rdneeref         doerfdpZdqej?        v rej?        dq         Z ee                                          s edre           	 ede                    ds                   Zn# e$ rZD edte           eDdZD[Dww xY w ejA        e          Z	 ej        Zn# e$ r  edu          w xY wdej?        v reEek    rdveE dwe dxZedyz  Z ee          eZE eedz            eed{            eed|            eed}           dS dS dS )    N)contextmanager)BytesIOStringIO)Path)CallableDictListOptionalUnion)norm)version   )BACKENDS_MAPPINGis_compel_availableis_flax_availableis_note_seq_availableis_onnx_availableis_opencv_availableis_peft_availableis_timm_availableis_torch_availableis_torch_versionis_torchsde_availableis_transformers_available)
get_loggerpeftz0.5transformersz4.33DIFFUSERS_TEST_BACKENDz+Failed to import `DIFFUSERS_TEST_BACKEND` 'zg'! This should be the name of an installed module                     to enable a specified backend.):
DIFFUSERS_TEST_DEVICEzRUnknown testing device specified by environment variable `DIFFUSERS_TEST_DEVICE`: ztorch_device overrode to cudacpuz1.12mpsc                    t                      st          d          t          j        | |g|R i |sMJ d| |z
                                                                   d| |z
                                   d            dS )Nz3PyTorch needs to be installed to use this function.FzMax diff is absolute z. Diff tensor is .T)r   
ValueErrortorchallcloseabsmax)abargskwargss       m/root/.openclaw/workspace/chatterbox_venv_py311/lib/python3.11/site-packages/diffusers/utils/testing_utils.pytorch_all_closer/   ^   s     PNOOO>!Q000000 eddq1ukkmm.?.?.A.AddUVYZUZT_T_TaTadddddu4    c                     t          j        | |          t          |           t          |          z  z  }d|                                z
  }|S )N      ?)npdotr   mean)r*   r+   
similaritydistances       r.    numpy_cosine_similarity_distancer8   f   s@    1a477!23JZ__&&&HOr0   test_corrections.txtexpected_slicec           	         |rt          j        d           t          j                            d          }t          j        |           st          j        |           } |r| ddd dd df         } t          |                                 	                                
                                                    t           j                                                dd          }|                    d	| d
          }|                    d          \  }}	}
|
                                d         }
t          |d          5 }t!          d                    ||	|
|g          |           d d d            d S # 1 swxY w Y   d S )Ni'  )	thresholdPYTEST_CURRENT_TESTr   
 tensorz = np.arrayz::r*   file)r&   set_printoptionsosenvironget	is_tensor
from_numpystrdetachr!   flattentofloat32replacesplitopenprintjoin)rB   limit_to_slicesmax_torch_printfilenameexpected_tensor_name	test_name
tensor_str
output_str	test_file
test_classtest_fnfs               r.   print_tensor_testr`   m   s     10000
455I?6"" *!&)) )233R(V]]__((**224477FFGGOOPTVXYYJ ##H1E.R.R.RSSJ%.__T%:%:"Iz7mmooa G	h		 OdiiJDEEANNNNO O O O O O O O O O O O O O O O O Os   )E99E= E=c                    t          j                    d         d         }t          j                            t          j                            |                    }|                    d          s4t          j                            |          }|                    d          4| r"t          ||                                           S |S )a  
    Args:
        append_path: optional path to append to the tests dir path
    Return:
        The full path to the `tests` dir, so that the tests can be invoked from anywhere. Optionally `append_path` is
        joined after the `tests` dir the former is provided.
    r   tests)	inspectstackrF   pathabspathdirnameendswithr   as_posix)append_pathcaller__file__	tests_dirs      r.   get_tests_dirrm      s     ]__Q'*N ? ?@@I  )) /GOOI..	   )) /  I{++44666r0   returnc                 f    |                                  } | dv rdS | dv rdS t          d|            )z
    Converts a string representation of truth to `True` (1) or `False` (0). True values are `y`, `yes`, `t`, `true`,
    `on`, and `1`; False value are `n`, `no`, `f`, `false`, `off`, and `0`;
    )yyesttrueon1r   )nnor_   falseoff0r   zinvalid truth value )lowerr%   )values    r.   str_to_boolr}      sJ    
 KKMME444q	7	7	7q777888r0   Fc                     	 t           j        |          }	 t          |          }n3# t          $ r t          d|  d          w xY w# t          $ r |}Y nw xY w|S )NzIf set, z must be yes or no.)rF   rG   r}   r%   KeyError)keydefaultr|   _values       r.   parse_flag_from_envr      s    B
3	B ''FF 	B 	B 	B@@@@AAA	B     Ms   A % AAARUN_SLOW)r   RUN_NIGHTLYr2   c                 2   |t           }d}| D ]}||z  }g }t          |          D ],}|                    |                                |z             -t	          j        |t          j                                      |                                           S )zCreates a random float32 tensorNr   )datadtype)	
global_rngrangeappendrandomr&   rB   floatview
contiguous)shapescalerngname
total_dimsdimvalues_s           r.   floats_tensorr      s    
{J  c

F: , ,cjjllU*++++<V5;777<<UCCNNPPPr0   c                 H     t          j        t          d          |           S )z
    Decorator marking a test as slow.

    Slow tests are skipped by default. Set the RUN_SLOW environment variable to a truthy value to run them.

    ztest is slow)unittest
skipUnless_run_slow_tests	test_cases    r.   slowr      s"     @8??	JJJr0   c                 H     t          j        t          d          |           S )z
    Decorator marking a test that runs nightly in the diffusers CI.

    Slow tests are skipped by default. Set the RUN_NIGHTLY environment variable to a truthy value to run them.

    ztest is nightly)r   r   _run_nightly_testsr   s    r.   nightlyr      s$     F813DEEiPPPr0   c                 V     t          j        t                      d          |           S )zo
    Decorator marking a test that requires PyTorch. These tests are skipped when PyTorch isn't installed.
    test requires PyTorch)r   r   r   r   s    r.   require_torchr      s*     N81335LMMiXXXr0   c                 v     t          j        t                      ot          dd          d          |           S )zl
    Decorator marking a test that requires PyTorch 2. These tests are skipped when it isn't installed.
    z>=z2.0.0ztest requires PyTorch 2)r   r   r   r   r   s    r.   require_torch_2r      sA     t8133W8Hw8W8WYrss  r0   c                 l     t          j        t                      o
t          dk    d          |           S )z8Decorator marking a test that requires CUDA and PyTorch.r    ztest requires PyTorch+CUDAr   r   r   torch_devicer   s    r.   require_torch_gpur      s8    m8133N8NPlmm  r0   c                 l     t          j        t                      o
t          dk    d          |           S )zJDecorator marking a test that requires an accelerator backend and PyTorch.r!   z!test requires accelerator+PyTorchr   r   s    r.   require_torch_acceleratorr      s8    s8133M8MOrss  r0   c                     t                      s t          j        d          |           S ddl} t          j        |j                                        dk    d          |           S )a  
    Decorator marking a test that requires a multi-GPU setup (in PyTorch). These tests are skipped on a machine without
    multiple GPUs. To run *only* the multi_gpu tests, assuming all test names contain multi_gpu: $ pytest -sv ./tests
    -k "multi_gpu"
    r   r   Nr   ztest requires multiple GPUs)r   r   skipr&   r   r    device_count)r   r&   s     r.   require_torch_multi_gpur     si      A5x}455i@@@LLL\8uz66881<>[\\]fgggr0   c                 b     t          j        t          t                    d          |           S )zZDecorator marking a test that requires an accelerator with support for the FP16 data type.z+test requires accelerator with fp16 support)r   r   _is_torch_fp16_availabler   r   s    r.   #require_torch_accelerator_with_fp16r     0    u87EEGtuu  r0   c                 b     t          j        t          t                    d          |           S )zZDecorator marking a test that requires an accelerator with support for the FP64 data type.z+test requires accelerator with fp64 support)r   r   _is_torch_fp64_availabler   r   s    r.   #require_torch_accelerator_with_fp64r     r   r0   c                 ~     t          j        t                      ot          t                    d          |           S )zPDecorator marking a test that requires an accelerator with support for training.z/test requires accelerator with training support)r   r   r   backend_supports_trainingr   r   s    r.   'require_torch_accelerator_with_trainingr     sD    8H!:<!H!H9    r0   c                 P     t          j        t          dk    d          |           S )z9Decorator marking a test to skip if torch_device is 'mps'r"   ztest requires non 'mps' device)r   r   r   r   s    r.   skip_mpsr   '  s&    W8|u46VWWXabbbr0   c                 V     t          j        t                      d          |           S )zv
    Decorator marking a test that requires JAX & Flax. These tests are skipped when one / both are not installed
    ztest requires JAX & Flax)r   r   r   r   s    r.   require_flaxr   ,  s+     P80224NOOPYZZZr0   c                 V     t          j        t                      d          |           S )z
    Decorator marking a test that requires compel: https://github.com/damian0815/compel. These tests are skipped when
    the library is not installed.
    ztest requires compel)r   r   r   r   s    r.   require_compelr   3  s*    
 N82446LMMiXXXr0   c                 V     t          j        t                      d          |           S )zw
    Decorator marking a test that requires onnxruntime. These tests are skipped when onnxruntime isn't installed.
    ztest requires onnxruntime)r   r   r   r   s    r.   require_onnxruntimer   ;  s+     Q80224OPPQZ[[[r0   c                 V     t          j        t                      d          |           S )zq
    Decorator marking a test that requires note_seq. These tests are skipped when note_seq isn't installed.
    ztest requires note_seq)r   r   r   r   s    r.   require_note_seqr   B  +     R84668PQQR[\\\r0   c                 V     t          j        t                      d          |           S )zq
    Decorator marking a test that requires torchsde. These tests are skipped when torchsde isn't installed.
    ztest requires torchsde)r   r   r   r   s    r.   require_torchsder   I  r   r0   c                 H     t          j        t          d          |           S )z
    Decorator marking a test that requires PEFT backend, this would require some specific versions of PEFT and
    transformers.
    ztest requires PEFT backendr   r   USE_PEFT_BACKENDr   s    r.   require_peft_backendr   P  s$    
 O8/1MNNyYYYr0   c                 V     t          j        t                      d          |           S )zi
    Decorator marking a test that requires timm. These tests are skipped when timm isn't installed.
    ztest requires timm)r   r   r   r   s    r.   require_timmr   X  s*     J80224HII)TTTr0   c                       fd}|S )z
    Decorator marking a test that requires PEFT backend with a specific version, this would require some specific
    versions of PEFT and transformers.
    c                    t                      o]t          j        t          j        t          j                            d                    j                  t          j                  k    } t          j        |d           |           S )Nr   z9test requires PEFT backend with the version greater than r   r   parse	importlibmetadatabase_versionr   r   )r   correct_peft_versionpeft_versions     r.   	decoratorz/require_peft_version_greater.<locals>.decoratore  s    022  (w}M),44V<<==J8
 8
M,''8(
x" "l^j"l"l
 

  	r0    )r   r   s   ` r.   require_peft_version_greaterr   _  s$         r0   c                       fd}|S )Nc                     t                      o]t          j        t          j        t          j                            d                    j                  t          j                  k    } t          j        |d d          |           S )N
acceleratez7Test requires accelerate with the version greater than r$   r   )r   correct_accelerate_versionaccelerate_versions     r.   r   z5require_accelerate_version_greater.<locals>.decoratorq  s    %6%8%8 &.W]M),44\BBCCP>
 >
M,-->."
x"&(wbt(w(w(w
 

  	r0   r   )r   r   s   ` r.   "require_accelerate_version_greaterr   p  s$         r0   c                 J     t          j        t           d          |           S )zJ
    Decorator marking a test that will be skipped after PEFT backend
    z%test skipped in favor of PEFT backendr   r   s    r.   deprecate_after_peft_backendr   |  s(     ^8#335\]]^ghhhr0   c                  >    t           j        } | j        | j        }}||fS N)sysversion_infomajorminor)sys_infor   r   s      r.   get_python_versionr     s!    H>8>5E%<r0   c                 T    d } t          j         |            d          |           S )Nc                  <    t                      \  } }| dk    o|dk    S )N   	   )r   )r   r   s     r.   python39_availablez6require_python39_or_higher.<locals>.python39_available  s$    )++uz(eqj(r0   z"test requires Python 3.9 or higher)r   r   )r   r   s     r.   require_python39_or_higherr     s=    ) ) ) [811335YZZ[deeer0   arry
local_pathc                    t          | t                    r1|ot          ||                     d          d         |                     d          d         |                     d          d                                                   S |                     d          s|                     d          rOt          j        |           }|                                 t          j
        t          |j                            } nqt          j                            |           rt          j
        |           } n=t!          d|  d          t          | t          j                  rnt!          d	          | S )
N/r?   http://https://IIncorrect path or url, URLs must start with `http://` or `https://`, and  is not a valid pathzjIncorrect format used for numpy ndarray. Should be an url linking to an image, a local path, or a ndarray.)
isinstancerK   r   rQ   ri   
startswithrequestsrH   raise_for_statusr3   loadr   contentrF   re   isfiler%   ndarray)r   r   responses      r.   
load_numpyr    sJ   $ 
!
DJJsOOB$7C9LdjjY\oo^`Nabbkkmmm__Y'' 		4??:+F+F 		|D))H%%'''778#34455DDW^^D!! 	74==DDv\`vvv   
D"*	%	% 

 
 	

 Kr0   urlc                     t          j        |           }|                                 t          j        t          |j                            }|S r   )r   rH   r   r&   r   r   r   )r  r  r   s      r.   load_ptr    sB    |C  H:gh.//00DKr0   imagec                 d   t          | t                    r|                     d          s|                     d          r9t          j                            t          j        | d          j                  } nt          j
                            |           r t          j                            |           } nDt          d|  d          t          | t          j        j                  r| } nt          d          t          j                            |           } |                     d          } | S )	z
    Loads `image` to a PIL Image.

    Args:
        image (`str` or `PIL.Image.Image`):
            The image to convert to the PIL Image format.
    Returns:
        `PIL.Image.Image`:
            A PIL Image.
    r   r   T)streamr   r   zdIncorrect format used for image. Should be an url linking to an image, a local path, or a PIL image.RGB)r   rK   r   PILImagerR   r   rH   rawrF   re   r  r%   ImageOpsexif_transposeconvert)r  s    r.   
load_imager    s    % 
I&& 	%*:*::*F*F 	INN8<d#C#C#C#GHHEEW^^E"" 	INN5))EEw\awww   
E39?	+	+ 
r
 
 	
 L''..EMM%  ELr0   
batch_sizec                    | j         \  }}d ||fD             \  }}|                     ||ft          j        j                  } t          j        |                               t
          j                  dz  } t          j	        | d          
                    dddd          g|z            } t          j        |           } d| z  d	z
  S )
Nc              3   &   K   | ]}||d z  z
  V  dS )   Nr   ).0xs     r.   	<genexpr>z#preprocess_image.<locals>.<genexpr>  s*      &&!AAI&&&&&&r0   )resampleg     o@r   r   r      g       @r2   )sizeresizer  r  LANCZOSr3   arrayastyperO   vstack	transposer&   rJ   )r  r  whs       r.   preprocess_imager%    s    :DAq&&1v&&&DAqLL!Q#)*;L<<EHUOO""2:..6EIuT{,,Q1a889JFGGEU##E;r0   output_gif_pathc                     |t          j        d          j        }| d                             |d| dd          ddd           |S )	Nz.gifsuffixr   Tr   Fd   )save_allappend_imagesoptimizedurationloop)tempfileNamedTemporaryFiler   save)r  r&  s     r.   export_to_gifr3    s_    "5VDDDI	!HMMABBi     r0   c              #   b   K   t          j        |           }|V  |                                 d S r   )ioBufferedWriterflush)raw_fr_   s     r.   buffered_writerr9    s0      
%  A
GGGGGIIIIIr0   output_ply_pathc           	          |t          j        d          j        } j                                                                                                        } j                                                                        }t          j	         fddD             d          }t          t          |d                    5 }|                    d	           |                    d
           |                    t          dt          |           dd                     |                    d           |                    d           |                    d           |?|                    d           |                    d           |                    d           |I|                    t          dt          |           dd                     |                    d           |                    d           ||dz                                                      t"                    }d t%          |                                |                                          D             }t)          j        d          }|D ]}|                     |j        |             nHt)          j        d          }|                                D ]}	|                     |j        |	             |Yt)          j        d          }|                                D ]0}
|                     |j        t          |
          g|
R             1ddd           n# 1 swxY w Y   |S )z&
    Write a PLY file for a mesh.
    Nz.plyr(  c                     g | ]E}j         |                                                                                                         FS r   vertex_channelsrL   r!   numpyr  r  meshs     r.   
<listcomp>z!export_to_ply.<locals>.<listcomp>  sE    RRRqD(+224488::@@BBRRRr0   r  r   axiswbs   ply
s    format binary_little_endian 1.0
zelement vertex r@   asciis   property float x
s   property float y
s   property float z
s   property uchar red
s   property uchar green
s   property uchar blue
zelement face s%   property list uchar int vertex_index
s   end_header
go@c                 "    g | ]\  }}g ||R S r   r   )r  coordrgbs      r.   rB  z!export_to_ply.<locals>.<listcomp>  s6       E3 %#  r0   z<3f3Bz<3fz<B3I)r0  r1  r   vertsrL   r!   r?  facesr3   rd   r9  rR   writebyteslenroundr   intziptoliststructStructpack)rA  r:  coordsrK  rI  r_   verticesformatitemvertextris   `          r.   export_to_plyr\    st    "5VDDDIZ  $$&&,,..FJNN""$$E
(RRRRERRRYZ
[
[
[C	ot44	5	5 $5		4555	7F777AABBB	%&&&	%&&&	%&&&?GG+,,,GG-...GG,---GGE8#e**888'BBCCCGG=>>>	   ?=''))0055C "%MMOOJJLL# #  H ]7++F  , ,T*++++, ]5))F --// . .V,----]6**F||~~ 5 5CHH3s3334444I$5 $5 $5 $5 $5 $5 $5 $5 $5 $5 $5 $5 $5 $5 $5L s   JMM Moutput_obj_pathc                     |t          j        d          j        } j                                                                                                        } j                                                                        }t          j	         fddD             d          }d t          |                                |                                          D             }d |                                D             }d	 |D             |z   }t          |d
          5 }|                    d                    |                     d d d            d S # 1 swxY w Y   d S )Nz.objr(  c                     g | ]E}j         |                                                                                                         FS r   r=  r@  s     r.   rB  z!export_to_obj.<locals>.<listcomp>,  sF    \\\QRd215<<>>BBDDJJLL\\\r0   r  r   rC  c                 2    g | ]\  }} d j         g ||R  S )z{} {} {} {} {} {})rX  )r  rH  colors      r.   rB  z!export_to_obj.<locals>.<listcomp>-  sC       7Cue""2E2E222  r0   c           
          g | ][}d                      t          |d         dz             t          |d         dz             t          |d         dz                       \S )z
f {} {} {}r   r   r  )rX  rK   )r  r[  s     r.   rB  z!export_to_obj.<locals>.<listcomp>1  sV    nnnX[\  SVaZ#c!fqj//3s1vPQz??SSnnnr0   c                     g | ]}d |z   S )zv r   )r  rZ  s     r.   rB  z!export_to_obj.<locals>.<listcomp>3  s    :::vTF]:::r0   r#  r@   )r0  r1  r   rJ  rL   r!   r?  rK  r3   rd   rQ  rR  rR   
writelinesrT   )rA  r]  rJ  rK  vertex_colorsrW  combined_datar_   s   `       r.   export_to_objrg  %  s   "5VDDDIJ##%%++--EJNN""$$EH\\\\V[\\\cdeeeM GJ5<<>>[h[o[o[q[qGrGr  H on_d_k_k_m_mnnnE:::::UBM	os	#	# /q	TYY}--.../ / / / / / / / / / / / / / / / / /s   #)EE Evideo_framesoutput_video_pathc                    t                      rdd l}n3t          t          d         d                             d                    |t          j        d          j        } |j        d }| d         j	        \  }}}|
                    ||d||f	          }t          t          |                     D ]8}|                    | |         |j                  }	|                    |	           9|S )
Nr   opencvr   export_to_videoz.mp4r(  mp4vr  )fps	frameSize)r   cv2ImportErrorr   rX  r0  r1  r   VideoWriter_fourccr   VideoWriterr   rN  cvtColorCOLOR_RGB2BGRrL  )
rh  ri  rp  fourccr$  r#  cvideo_writeriimgs
             r.   rl  rl  9  s     S



*84Q7>>?PQQRRR $7vFFFK#S#V,F1o#GAq!??#4f!PQSTv?VVL3|$$%%    ll<?C,=>>3r0   c                     d}|                      d          sR|                      d          s=t          j                            |t          j                            |                     } t          |           S )NzEhttps://huggingface.co/datasets/fusing/diffusers-testing/resolve/mainr   r   )r   rF   re   rT   urllibr   quoter  )re   base_urls     r.   load_hf_numpyr  J  sc    VH??9%% @dooj.I.I @w||Hfl&8&8&>&>??dr0   c                 f    d}|t           vr%|                     |ddd           dt           |<   dS dS )z
    This function is to be called from `conftest.py` via `pytest_addoption` wrapper that has to be defined there.

    It allows loading both `conftest.py` files at once without causing a failure due to adding the same `pytest`
    option.

    z--make-reportsstoreFzSgenerate report files. The value of this option is used as a prefix to report names)actionr   helpr   N)pytest_opt_registered	addoption)parseroptions     r.   pytest_addoption_sharedr  Y  sY     F***f	 	 	
 	
 	
 )*f%%% +*r0   c           
      	   ddl m} t                    sd| j        }|                                }|j        j        }| j        }dt                    	                    dd           fddD             }g }| j
                                        D ],}	|	D ]'}
t          |
d	          r|                    |
           (-|r|                    d
 d           t          |d         d          5 }d}|                    d           t#          |          D ]l\  }}
|
j        |k     r-|                    t          |          |z
   d| d            n0|                    |
j        dd|
j        dd|
j         d           mddd           n# 1 swxY w Y   d }d|j        _        t          |d         d          5 } |||          | _        |                                  ddd           n# 1 swxY w Y   t          |d         d          5 } |||          | _         ||            ddd           n# 1 swxY w Y   d|j        _        t          |d         d          5 } |||          | _        |                                  ddd           n# 1 swxY w Y   t          |d         d          5 } |||          | _        |                                  ddd           n# 1 swxY w Y   t          |d         d          5 } |||          | _        |                                  |                                  ddd           n# 1 swxY w Y   d | _        t          |d!         d          5 } |||          | _        |                                  ddd           n# 1 swxY w Y   t          |d"         d          5 } |||          | _        |                                  ddd           n# 1 swxY w Y   t          |d#         d          5 } |||          | _        |                                  ddd           n# 1 swxY w Y   || _        || _        ||j        _        dS )$a  
    Generate multiple reports at the end of test suite run - each report goes into a dedicated file in the current
    directory. The report files are prefixed with the test suite name.

    This function emulates --duration and -rA pytest arguments.

    This function is to be called from `conftest.py` via `pytest_terminal_summary` wrapper that has to be defined
    there.

    Args:
    - tr: `terminalreporter` passed from `conftest.py`
    - id: unique id like `tests` or `examples` that will be incorporated into the final reports filenames - this is
      needed as some jobs have multiple runs of pytest, so we can't have them overwrite each other.

    NB: this functions taps into a private _pytest API and while unlikely, it could break should
    pytest do internal changes - also it calls default internal methods of terminalreporter which
    can be hijacked by various `pytest-` plugins and interfere.

    r   )create_terminal_writerrb   reportsT)parentsexist_okc           	      (    i | ]}| d  d| dS )r   r   z.txtr   )r  kdirids     r.   
<dictcomp>z0pytest_terminal_summary_main.<locals>.<dictcomp>  sD        	
c  B       r0   )		durationserrorsfailures_longfailures_shortfailures_linepassesstatssummary_shortwarningsr.  c                     | j         S r   )r.  )r  s    r.   <lambda>z.pytest_terminal_summary_main.<locals>.<lambda>  s     r0   )r   reverser  r#  g?zslowest durations
z durations < z secs were omittedz02.2fzs z<8 r@   Nc           	      f   |                      d          }|sd S |                     dd           |D ]~}|                     |          }|                     d|dd           t          j        dd|j        d	t          j        t          j        z            }| j        	                    |           d S )
Nfailed=zFAILURES SHORT STACKr   T)redboldz.*_ _ _ (_ ){10,}_ _ rA   r   )

getreports	write_sep_getfailureheadlineresublongreprtextMS_twline)trr  repmsglongreprs        r.   summary_failures_shortz<pytest_terminal_summary_main.<locals>.summary_failures_short  s    --)) 	F
S0111 	" 	"C((--CLLct$L777v6C<LaQSQUXZX\Q\]]HFKK!!!!	" 	"r0   autor  r  r  r  r  r  wPpsxXEfr  r  r  )_pytest.configr  rN  configget_terminal_writerr  tbstylereportcharsr   mkdirr  r   hasattrr   sortrR   rL  	enumerater.  whennodeidr  summary_failuressummary_errorssummary_warningssummary_passesshort_test_summarysummary_stats)r  r  r  r  orig_writerorig_tbstyleorig_reportcharsreport_filesdlistreplistr  r_   durations_minry  r  r  s    `             @r.   pytest_terminal_summary_mainr  l  s   ( 655555r77 YF,,..K=(L~
CIIOOD4O000    

  L$ E8??$$ " " 	" 	"CsJ'' "S!!!	"  	O

++T
:::,{+S11 	OQ MGG)***#E** O O3<-//GGs5zz!|[[-[[[\\\E3<MMMMMMszMMMNNNN	O 	O 	O 	O 	O 	O 	O 	O 	O 	O 	O 	O 	O 	O 	O" " "( #FM	l?+S	1	1 Q''22
              
 
l+,c	2	2 #a''22r"""# # # # # # # # # # # # # # # #FM	l?+S	1	1 Q''22
               
l8$c	*	* a''22
               
l:&	,	, ''22

              
  BN	l8$c	*	* a''22
               
l?+S	1	1  Q''22
                              
l7#S	)	) Q''22
              
 BF%BN(FMs   5BFFF&G77G;>G;III.&J  J$'J$&K33K7:K7:MM!M&N44N8;N8&PPP(&QQ!Q   max_attemptswait_before_retrydescriptionc                       fd}|S )a  
    To decorate flaky tests. They will be retried on failures.

    Args:
        max_attempts (`int`, *optional*, defaults to 5):
            The maximum number of attempts to retry the flaky test.
        wait_before_retry (`float`, *optional*):
            If provided, will wait that number of seconds before retrying the test.
        description (`str`, *optional*):
            A string to describe the situation (what / where / why is flaky, link to GH issue/PR comments, errors,
            etc.)
    c                 L     t          j                    fd            }|S )Nc            
          d}|k     rf	  | i |S # t           $ rJ}t          d| d| d dt          j                   t	          j                   |dz  }Y d }~nd }~ww xY w|k     f | i |S )Nr   zTest failed with z at try r   r$   rC   )	ExceptionrS   r   stderrtimesleep)r,   r-   retry_counterrr  test_func_refr  s       r.   wrapperz,is_flaky.<locals>.decorator.<locals>.wrapper  s    K,,%(=$9&999  % % %XcXX;XXXXX_b_ijjjj(4
#45551$KKKKKK	%	 ,, !=$1&111s    
A'A A""A')	functoolswraps)r  r  r  r  s   ` r.   r   zis_flaky.<locals>.decorator  sC    		'	'	2 	2 	2 	2 	2 	2 
(	'	2 r0   r   )r  r  r  r   s   ``  r.   is_flakyr    s*         & r0   c                    |-t          t          j                            dd                    }d}t	          j        |          }|                    d          }|                    d          }|                    ||           |	                    ||||f          }|
                                 	 |                    |          }	|                                 n@# t          $ r3}
|                                 |                     |
           Y d}
~
nd}
~
ww xY w|                    |           |	d         |                     |	d                     dS dS )	a  
    To run a test in a subprocess. In particular, this can avoid (GPU) memory issue.

    Args:
        test_case (`unittest.TestCase`):
            The test that will run `target_func`.
        target_func (`Callable`):
            The function implementing the actual testing logic.
        inputs (`dict`, *optional*, defaults to `None`):
            The inputs that will be passed to `target_func` through an (input) queue.
        timeout (`int`, *optional*, defaults to `None`):
            The timeout (in seconds) that will be passed to the input and output queues. If not specified, the env.
            variable `PYTEST_TIMEOUT` will be checked. If still `None`, its value will be set to `600`.
    NPYTEST_TIMEOUTiX  spawnr   )timeout)targetr,   error)rP  rF   rG   rH   multiprocessingget_contextQueueJoinableQueueputProcessstart	task_doner  	terminatefailrT   )r   target_funcinputsr  start_methohdctxinput_queueoutput_queueprocessresultses              r.   run_test_in_subprocessr    sj    bjnn%5s;;<<M

%m
4
4C))A,,K$$Q''L OOFGO,,,kkKw3WkXXGMMOOO""7"33       q LLL!!!w#''*,----- $#s   6*C! !
D+)DDc                   *    e Zd ZdZd Zd Zd Zd ZdS )CaptureLoggeraG  
    Args:
    Context manager to capture `logging` streams
        logger: 'logging` logger object
    Returns:
        The captured output is available via `self.out`
    Example:
    ```python
    >>> from diffusers import logging
    >>> from diffusers.testing_utils import CaptureLogger

    >>> msg = "Testing 1, 2, 3"
    >>> logging.set_verbosity_info()
    >>> logger = logging.get_logger("diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.py")
    >>> with CaptureLogger(logger) as cl:
    ...     logger.info(msg)
    >>> assert cl.out, msg + "
"
    ```
    c                     || _         t                      | _        t          j        | j                  | _        d| _        d S )NrA   )loggerr   r5  loggingStreamHandlershout)selfr  s     r.   __init__zCaptureLogger.__init__S  s3    **'00r0   c                 D    | j                             | j                   | S r   )r  
addHandlerr  r  s    r.   	__enter__zCaptureLogger.__enter__Y  s    tw'''r0   c                     | j                             | j                   | j                                        | _        d S r   )r  removeHandlerr  r5  getvaluer  )r  excs     r.   __exit__zCaptureLogger.__exit__]  s3    !!$'***7##%%r0   c                     d| j          dS )Nz
captured: r@   )r  r  s    r.   __repr__zCaptureLogger.__repr__a  s    (DH((((r0   N)__name__
__module____qualname____doc__r  r  r  r  r   r0   r.   r  r  >  sZ         (    & & &) ) ) ) )r0   r  c                      dt           j        d<   dt           j        d<   t          j        d           dt          j        j        _        dt          j        j        _        dt          j        j        j	        _
        dS )z
    Helper function for reproducible behavior during distributed training. See
    - https://pytorch.org/docs/stable/notes/randomness.html for pytorch
    ru   CUDA_LAUNCH_BLOCKINGz:16:8CUBLAS_WORKSPACE_CONFIGTFN)rF   rG   r&   use_deterministic_algorithmsbackendscudnndeterministic	benchmarkr    matmul
allow_tf32r   r0   r.   enable_full_determinismr  e  sa     *-BJ%&,3BJ()	&t,,, *.EN&%*EN",1EN)))r0   c                  j    dt           j        d<   dt           j        d<   t          j        d           d S )Nrz   r  rA   r  F)rF   rG   r&   r  r   r0   r.   disable_full_determinismr   w  s3    ),BJ%&,.BJ()	&u-----r0   c                 0   t                      sdS dd l} |j        |           } 	  |j        d|j                                      |           } |j        ||          }dS # t          $ r(}| j        dk    rt          d|           Y d }~dS d }~ww xY w)NFr   r  r  r   Tr    zYou have passed a device of type 'cuda' which should work with 'fp16', but 'cuda' does not seem to be correctly installed on your machine: )
r   r&   devicezerosfloat16rN   mulr  typer%   r$  r&   r  r   r  s        r.   r   r   ~       uLLLU\&!!FEKem44477??EIaOOt   ;&   b  _`  b  b   uuuuu   ;A# #
B-BBc                 0   t                      sdS dd l} |j        |           } 	  |j        d|j                                      |           } |j        ||          }dS # t          $ r(}| j        dk    rt          d|           Y d }~dS d }~ww xY w)NFr   r"  r#  Tr    zYou have passed a device of type 'cuda' which should work with 'fp64', but 'cuda' does not seem to be correctly installed on your machine: )
r   r&   r$  r%  float64rN   r'  r  r(  r%   r)  s        r.   r   r     r*  r+  T)r    r!   r"   r   c                      dS Nr   r   r   r0   r.   r  r    s    A r0   c                      dS r/  r   r   r0   r.   r  r    s    ^_ r0   )r    r!   r   r$  dispatch_tablec                 N    | |vr |d         |i |S ||          }|d S  ||i |S )Nr   r   )r$  r1  r,   r-   fns        r.   _device_agnostic_dispatchr4    sR    ^##(~i($9&999		B 
zt2tvr0   seedc                 .    t          | t          |          S r   )r4  BACKEND_MANUAL_SEED)r$  r5  s     r.   backend_manual_seedr8    s    $V-@$GGGr0   c                 ,    t          | t                    S r   )r4  BACKEND_EMPTY_CACHEr$  s    r.   backend_empty_cacher<    s    $V-@AAAr0   c                 ,    t          | t                    S r   )r4  BACKEND_DEVICE_COUNTr;  s    r.   backend_device_countr?    s    $V-ABBBr0   c                 R    t                      sdS | t          vrd} t          |          S )NFr   )r   BACKEND_SUPPORTS_TRAININGr;  s    r.   r   r     s1     u...$V,,r0   device_fn_dictattribute_namec                     	 t          t          |          }|| t          <   d S # t          $ r+}d| vrt          d| dt           d          |Y d }~d S d }~ww xY w)Nr   `z` not found in 'z)' and no default fallback function found.)getattrdevice_spec_moduler   AttributeErrordevice_spec_path)rB  rC  spec_fnr  s       r.   update_mapping_from_specrK    s    		0.AAG+2N<((( 	 	 	..$sss8Hsss  /.....	s   # 
A AADIFFUSERS_TEST_DEVICE_SPECzCSpecified path to device specification file is not found. Received z.pyz9Provided device spec file is not a Python file! Received z.Device spec file did not contain `DEVICE_NAME`z?Mismatch between environment variable `DIFFUSERS_TEST_DEVICE` 'z' and device found in spec 'z'
zKEither unset `DIFFUSERS_TEST_DEVICE` or ensure it matches device spec name.MANUAL_SEED_FNEMPTY_CACHE_FNDEVICE_COUNT_FNSUPPORTS_TRAINING)NNr9   r:   r   )F)r2   NN)r  NN)NN)r  r   rc   r5  r  r  rF   r   r  rS  r   r0  r  r   urllib.parser|  
contextlibr   r   r   pathlibr   typingr   r   r	   r
   r   r?  r3   	PIL.Imager  PIL.ImageOpsr   numpy.linalgr   	packagingr   import_utilsr   r   r   r   r   r   r   r   r   r   r   r   r   Randomr   r  r  r   r   r   _required_peft_version_required_transformers_versionr   r&   rG   backendimport_moduler   ModuleNotFoundErrorr  r   r$  RuntimeErrorinfor    is_available__version__is_torch_higher_equal_than_1_12r  r  mps_backend_registeredr"   r/   r8   r`   rm   rP  r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rK   r  r  r  r  r  r%  r3  r9  r\  rg  rl  r  r  r  r  r   r  r  r  r  r   r   r   rA  empty_cacher:  r   r>  manual_seedr7  r4  r8  r<  r?  r   rK  rI  is_filer%   indeximport_namerG  DEVICE_NAMEdevice_namerH  r  r   r0   r.   <module>rm     s            				      				  				  



        % % % % % %                       8 8 8 8 8 8 8 8 8 8 8 8 8 8                                                            V]__
	H		**,, GM)$,,V4455B2 2GM%2  ";!:!<!< "GM)$,,^<<==JB BGM&B  *L.L  !uLLL  2:--*56	'	'00AA" 	 	 	%%;g ; ;78; ;  	 "*,,z"9:	\**AA 	 	 	,seqss 	 	>>>????!&!8!8!:!:Evv*7'-GM%+,,9+
 +
W]6""+#' + 	u%,WU^U%C%C"%;t@R@_@_@a@at55htL     #)O O O O4   .9# 9 9 9 9     &%j%@@@((FFF Q Q Q Q K K KQ Q QY Y Y      h h h      c c c
[ [ [Y Y Y\ \ \] ] ]] ] ]Z Z ZU U U  "	 	 	i i i  f f f U3
?+ # RTR\    4    eC01 cio    >CI 3     cio.  PS       1 1 1 1 1 1h/ / / / / /( $rz"2 s VY    "2:      * * *&~) ~) ~)D! !3 !x !\deh\i ! ! ! !J(. (. (. (.V$) $) $) $) $) $) $) $)N2 2 2$. . .  ,  .  s)-d5UY Z Z $):#9$t`dee$)J$;IIV_V_lmnn#(:#9%BS`e`qrrc 4X;N    H H3 H H H HB B B B BC C C C C-c - - - -  *Q
c8m1D 
VY 
 
 
 
 $rz11:&BCt$%%--// 	w*ucsuuvvv	t*+J-=-C-CE-J-J+JKKK 	t 	t 	t*kYikkllrss	t 5Y4[AA	S,8KK 	S 	S 	S .!QRRR	S #bj00\[5P5P OT`  O  O  J  O  O  OC``C*S//!" 	! !46FGGG  !46FGGG  !57HIII  !:<OPPPPPU*Q *Q 21sT   F   F<%F77F<G' 'H ,G;;H *T T!TT!5T= =U