a
    xdY=                     @   s&  d dl m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 Zdd Zdd Zd	d
 Zdd Zdd Zdd Zdd Zdd Zd0ddZd1ddZdd Zdd Zd2ddZG d d! d!eZe d"k Zd3d$d%Zd&d' Zd(d) Z d*d+ Z!d,d- Z"d.d/ Z#dS )4    )print_functionNc                 C   s.   zt | tW S  ty(   t | t Y S 0 d S N)
isinstance
basestring	NameErrorstrvalue r
   Q/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/lit/util.py	is_string   s    r   c                 C   sj   | d u rdS t | tu r| S t| tjr0| dkS t| rX|  dv rHdS |  dv rXdS td| d S )NFr   )1trueonyesT) 0falseoffnoz"{}" is not a valid boolean)	typeboolr   numbersNumberr   lower
ValueErrorformatr   r
   r
   r   pythonize_bool   s    r   c                 C   s   d|  d S )Nz\br
   )wordr
   r
   r   make_word_regex&   s    r   c                 C   s   t | tr| S | dS )zReturn the parameter as type 'bytes', possibly encoding it.

    In Python2, the 'bytes' type is the same as 'str'. In Python3, they
    are distinct.

    utf-8)r   bytesencodesr
   r
   r   to_bytes*   s    
r%   c                 C   sx   t | tr| S t | tr@z| dW S  ty>   t|  Y S 0 z| dW S  tyr   tdt| tf Y n0 dS )zReturn the parameter as type 'str', possibly encoding it.

    In Python2, the 'str' type is the same as 'bytes'. In Python3, the
    'str' type is (essentially) Python2's 'unicode' type, and 'bytes' is
    distinct.

    r    z not sure how to convert %s to %sN)	r   r   r!   decodeUnicodeDecodeErrorr"   AttributeError	TypeErrorr   )br
   r
   r   	to_string;   s    

r+   c                 C   s   t | tr| dS | S )zReturn the parameter as type which supports unicode, possibly decoding
    it.

    In Python2, this is the unicode type. In Python3 it's the str type.

    r    )r   r!   r&   r#   r
   r
   r   
to_unicodeb   s    

r,   c                  C   sL   zt td} W n ty0   t p*d} Y n0 t dkrHt| dS | S )zReturn the number of cores the current process can use, if supported.
    Otherwise, return the total number of cores (like `os.cpu_count()`).
    Default to 1 if undetermined.

    r      Windows<   )lenossched_getaffinityr(   	cpu_countplatformsystemmin)nr
   r
   r   usable_core_countp   s    
r8   c                 C   s   ztt  dkrhddlm} ddlm}m} tj| } | 	dd} t
d|  }|j|d sr|| n
t|  W n, ty   t d }|jtjkr Y n0 d S )	Nr.   r   )windll)GetLastErrorWinError/\z\\?\%sr-   )r4   r5   ctypesr9   r:   r;   r1   pathabspathreplacer,   kernel32ZCreateDirectoryWmkdirOSErrorsysexc_infoerrnoEEXIST)r?   r9   r:   r;   ZNTPather
   r
   r   rC      s    rC   c                 C   s<   | rt j| rdS t j| }|| kr0t| t|  dS )zmkdir_p(path) - Make the "path" directory, if it does not exist; this
    will also make directories for any missing parent directories.N)r1   r?   existsdirnamemkdir_prC   )r?   parentr
   r
   r   rL      s    rL   c                 #   sv   |du rt  }|du rdh}t| D ]J tjtj|  s& ds& |v s&t fdd|D sjq& V  q&dS )a  Yields files in a directory.

    Filenames that are not excluded by rules below are yielded one at a time, as
    basenames (i.e., without dirname).

    Files starting with '.' are always skipped.

    If 'suffixes' is not None, then only filenames ending with one of its
    members will be yielded. These can be extensions, like '.exe', or strings,
    like 'Test'. (It is a lexicographic check; so an empty sequence will yield
    nothing, but a single empty string will yield all filenames.)

    If 'exclude_filenames' is not None, then none of the file basenames in it
    will be yielded.

    If specified, the containers for 'suffixes' and 'exclude_filenames' must
    support membership checking for strs.

    Args:
        dirname: a directory path.
        suffixes: (optional) a sequence of strings (set, list, etc.).
        exclude_filenames: (optional) a sequence of strings.

    Yields:
        Filenames as returned by os.listdir (generally, str).

    Nr   .c                 3   s   | ]}  |V  qd S r   )endswith).0Zsfxfilenamer
   r   	<genexpr>       z listdir_files.<locals>.<genexpr>)setr1   listdirr?   isdirjoin
startswithany)rK   suffixesZexclude_filenamesr
   rQ   r   listdir_files   s    r\   c                 C   s   |du rt jdd}t j| rBt j| rBt jt j| S |sLt j}t j	dkrlt jdd
d}ndg}|
t j	D ]T}|D ]J}t j|| | }t j|rt j|st jt j|    S qq~dS )zwhich(command, [paths]) - Look up the given command in the paths string
    (or the PATH environment variable, if unspecified).NPATHr   ;PATHEXT)r1   environgetr?   isabsisfilenormcasenormpathdefpathpathsepsplitrX   rJ   rW   r@   )commandpathspathextr?   extpr
   r
   r   which   s    
 rn   c                 C   s*   |D ] }t jt j| |s dS qdS )NFT)r1   r?   rJ   rX   )dirtoolsZtoolr
   r
   r   checkToolsPath   s    rq   c                 C   s(   | tjD ]}t|| r|  S qd S r   )rh   r1   rg   rq   )rp   rj   r?   r
   r
   r   
whichTools   s    

rr   Itemsc                 C   sL  | j dd d tdd | D }ttt|d}tdD ]@}|d|  }tt|| }|dkrr qqB|dkrB|d8 }qBd	d t|D }| D ]0\}}	t	t||	 | |d }
||
 
| qd
}d|d  }td|  t| t| dd  D ]\}}td||f  q td|  t| ttt|d}tdd| }|rf||d 7 }tttt| d}tdd|d d d d|d|d d f  t| ttt|D ]n\}}tt|t|  }t|| }td|||| |||d | d| d||  |t||t| f  qt| d S )Nc                 S   s   | d S )Nr-   r
   )itemr
   r
   r   <lambda>   rT   z printHistogram.<locals>.<lambda>)keyc                 S   s   g | ]\}}|qS r
   r
   )rP   _vr
   r
   r   
<listcomp>  rT   z"printHistogram.<locals>.<listcomp>
   )      g      @r-   r-   c                 S   s   g | ]
}t  qS r
   )rU   )rP   ir
   r
   r   ry     rT   (   -"   zSlowest %s:iz	%.2fs: %sz

%s Times:r      z[%s] :: [%s] :: [%s]Ranger|   Z
PercentageZCountz&[%*.*fs,%*.*fs) :: [%s%s] :: [%*d/%*d]* )sortmaxintmathceillog	itertoolscycleranger6   addprintreversedr0   centerlist	enumeratefloat)itemstitleZmaxValuepowerincZbarHNZhistonamerx   binZbarWhrr	   ZpDigitsZpfDigitsZcDigitsr}   rowZpctwr
   r
   r   printHistogram   sP    
 r   c                   @   s   e Zd Zdd ZdS )ExecuteCommandTimeoutExceptionc                 C   sT   t |tsJ t |tsJ t |ts*J t |ts8J || _|| _|| _|| _d S r   )r   r   r   msgouterrexitCode)selfr   r   r   r   r
   r
   r   __init__-  s    z'ExecuteCommandTimeoutException.__init__N)__name__
__module____qualname__r   r
   r
   r
   r   r   ,  s   r   r.   Fc              	      s   |durt |}|rtjntj}tj| |tjtj||tdd}dg zV|dkrr fdd}t||}|  j	|d\}	}

 }W |dkr|  n|dkr|  0 t|	}	|rdnt|
}
 d rtd	||	|
|d
|tj krt|	|
|fS )a  Execute command ``command`` (list of arguments or string) with.

    * working directory ``cwd`` (str), use None to use the current
      working directory
    * environment ``env`` (dict), use None for none
    * Input to the command ``input`` (str), use string to pass
      no input.
    * Max execution time ``timeout`` (int) seconds. Use 0 for no timeout.
    * ``redirect_stderr`` (bool), use True if redirect stderr to stdout

    Returns a tuple (out, err, exitCode) where
    * ``out`` (str) is the standard output of running the command
    * ``err`` (str) is the standard error of running the command
    * ``exitCode`` (int) is the exitCode of running the command

    If the timeout is hit an ``ExecuteCommandTimeoutException``
    is raised.

    N)cwdstdinstdoutstderrenv	close_fdsFr   c                      s   d d< t j d S )NTr   )killProcessAndChildrenpidr
   Z
hitTimeOutrm   r
   r   killProcessb  s    z#executeCommand.<locals>.killProcess)inputr   zReached timeout of {} seconds)r   r   r   r   )r%   
subprocessSTDOUTPIPEPopenkUseCloseFDs	threadingTimerstartcommunicatewaitcancelr+   r   r   signalSIGINTKeyboardInterrupt)ri   r   r   r   timeoutredirect_stderrZerr_outZtimerObjectr   r   r   r   r
   r   r   executeCommand=  sD    


r   c                 C   s   d| v pd| v S )zeWhether the given target triple is for macOS,
       e.g. x86_64-apple-darwin, arm64-apple-macos
    darwinZmacosr
   )target_tripler
   r
   r   isMacOSTriple  s    r   c                 C   s   t | jrz8tjg dtjtjd}| \}}| }| }W n tyX   d}Y n0 |dkr|r|	 }|
d|  || jd< d S )N)xcrunz--show-sdk-path--sdkmacosxr   r   r   zusing SDKROOT: %rZSDKROOT)r   r   r   r   r   r   stripr   rD   r&   Znoteenvironment)config
lit_configcmdr   r   resZsdk_pathr
   r
   r   usePlatformSdkOnDarwin  s    


r   c                 C   sr   t | jrnz8tjg dtjtjd}| \}}| }| }W n tyX   d}Y n0 |dkrn|rn|	 S d S )N)r   z--show-sdk-versionr   r   r   r   r   )
r   r   r   r   r   r   r   r   rD   r&   )r   r   r   r   r   r   r
   r
   r   findPlatformSdkVersionOnMacOS  s    


r   c                  C   s8   t  dkrdS zddl} W dS  ty2   Y dS 0 dS )az  
        Returns a tuple (<supported> , <error message>)
        where
        `<supported>` is True if `killProcessAndChildren()` is supported on
            the current host, returns False otherwise.
        `<error message>` is an empty string if `<supported>` is True,
            otherwise is contains a string describing why the function is
            not supported.
    AIX)Tr   r   N)FzRequires the Python psutil module but it could not be found. Try installing it via pip or via your operating system's package manager.)r4   r5   psutilImportError)r   r
   r
   r   !killProcessAndChildrenIsSupported  s    
r   c              	   C   s   t  dkr"tjd| dd nddl}zr|| }z|jdd}W n tyd   |j	dd}Y n0 |D ]&}z|
  W qj |jy   Y qj0 qj|
  W n |jy   Y n0 dS )aP  This function kills a process with ``pid`` and all its running children
    (recursively). It is currently implemented using the psutil module on some
    platforms which provides a simple platform neutral implementation.

    TODO: Reimplement this without using psutil on all platforms so we can
    remove our dependency on it.

    r   zkill -kill $(ps -o pid= -L{})T)shellr   N)	recursive)r4   r5   r   callr   r   Processchildrenr(   Zget_childrenkillZNoSuchProcess)r   r   Z
psutilProcZchildren_iteratorchildr
   r
   r   r     s"    	
r   )NN)N)rs   )NNNr   F)$
__future__r   rG   r   r   r   r1   r4   r   r   rE   r   r   r   r   r%   r+   r,   r8   rC   rL   r\   rn   rq   rr   r   	Exceptionr   r5   r   r   r   r   r   r   r   r
   r
   r
   r   <module>   sD   '
)
 
.  
G