a
    þdC5  ã                   @   sˆ   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 ddl	m
Z
 G dd„ de
ƒZG d	d
„ d
ejƒZe ¡ G dd„ dejƒƒZdS )é    N)ÚARCH_REGISTRY)Únn)Ú
functionalé   )ÚStyleGAN2GeneratorCleanc                       s,   e Zd ZdZd‡ fdd„	Zddd„Z‡  ZS )ÚStyleGAN2GeneratorCSFTav  StyleGAN2 Generator with SFT modulation (Spatial Feature Transform).

    It is the clean version without custom compiled CUDA extensions used in StyleGAN2.

    Args:
        out_size (int): The spatial size of outputs.
        num_style_feat (int): Channel number of style features. Default: 512.
        num_mlp (int): Layer number of MLP style layers. Default: 8.
        channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2.
        narrow (float): The narrow ratio for channels. Default: 1.
        sft_half (bool): Whether to apply SFT on half of the input channels. Default: False.
    é   é   é   r   Fc                    s$   t t| ƒj|||||d || _d S )N)Únum_style_featÚnum_mlpÚchannel_multiplierÚnarrow)Úsuperr   Ú__init__Úsft_half)ÚselfÚout_sizer   r   r   r   r   ©Ú	__class__© úi/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/gfpgan/archs/gfpganv1_clean_arch.pyr      s    
ûzStyleGAN2GeneratorCSFT.__init__NTc
                    s¼  |s‡ fdd„|D ƒ}|du rH|r0dgˆ j  }n‡ fdd„tˆ j ƒD ƒ}|dk rxg }
|D ]}|
 ||||   ¡ qX|
}t|ƒdkr¼ˆ j}|d jdk r²|d  d¡ d|d¡}n|d }nnt|ƒdkr*|du rät 	dˆ jd ¡}|d  d¡ d|d¡}|d  d¡ dˆ j| d¡}t
 ||gd¡}ˆ  |jd ¡}ˆ j||dd…df |d d	}ˆ  ||dd…df ¡}d}tˆ jddd… ˆ jddd… |ddd… |ddd… ˆ jƒD ]è\}}}}}|||dd…|f |d	}|t|ƒk rXˆ jr@t
j|t| d¡d ƒdd
\}}|||d   ||  }t
j||gdd
}n|||d   ||  }|||dd…|d f |d	}|||dd…|d f |ƒ}|d7 }q´|}|	r°||fS |dfS dS )a  Forward function for StyleGAN2GeneratorCSFT.

        Args:
            styles (list[Tensor]): Sample codes of styles.
            conditions (list[Tensor]): SFT conditions to generators.
            input_is_latent (bool): Whether input is latent style. Default: False.
            noise (Tensor | None): Input noise or None. Default: None.
            randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True.
            truncation (float): The truncation ratio. Default: 1.
            truncation_latent (Tensor | None): The truncation latent tensor. Default: None.
            inject_index (int | None): The injection index for mixing noise. Default: None.
            return_latents (bool): Whether to return style latents. Default: False.
        c                    s   g | ]}ˆ   |¡‘qS r   )Z	style_mlp)Ú.0Ús©r   r   r   Ú
<listcomp>;   ó    z2StyleGAN2GeneratorCSFT.forward.<locals>.<listcomp>Nc                    s   g | ]}t ˆ jd |› ƒ‘qS ©Únoise)ÚgetattrZnoises)r   Úir   r   r   r   A   r   r   r   é   r
   r   )Zdim)Z
num_layersÚrangeÚappendÚlenZ
num_latentÚndimZ	unsqueezeÚrepeatÚrandomÚrandintÚtorchÚcatZconstant_inputÚshapeZstyle_conv1Zto_rgb1ÚzipZstyle_convsZto_rgbsr   ÚsplitÚintÚsize)r   ZstylesÚ
conditionsÚinput_is_latentr   Úrandomize_noiseZ
truncationZtruncation_latentZinject_indexÚreturn_latentsZstyle_truncationÚstyleZlatentZlatent1Zlatent2ÚoutÚskipr    Úconv1Úconv2Znoise1Znoise2Zto_rgbZout_sameZout_sftÚimager   r   r   Úforward"   sV    
 *ÿ"zStyleGAN2GeneratorCSFT.forward)r   r	   r
   r   F)FNTr   NNF©Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r:   Ú__classcell__r   r   r   r   r      s          ÷r   c                       s*   e Zd ZdZd‡ fdd„	Zdd„ Z‡  ZS )ÚResBlocka  Residual block with bilinear upsampling/downsampling.

    Args:
        in_channels (int): Channel number of the input.
        out_channels (int): Channel number of the output.
        mode (str): Upsampling/downsampling mode. Options: down | up. Default: down.
    Údownc                    sl   t t| ƒ ¡  t ||ddd¡| _t ||ddd¡| _tj||ddd| _|dkrZd| _n|dkrhd| _d S )	Nr!   r   F)ZbiasrB   ç      à?Úupr
   )	r   rA   r   r   ÚConv2dr7   r8   r6   Úscale_factor)r   Úin_channelsÚout_channelsÚmoder   r   r   r      s    zResBlock.__init__c                 C   sf   t j|  |¡dd}t j|| jddd}t j|  |¡dd}t j|| jddd}|  |¡}|| }|S )Nçš™™™™™É?©Znegative_slopeZbilinearF)rF   rI   Zalign_corners)ÚFÚleaky_relu_r7   ZinterpolaterF   r8   r6   )r   Úxr5   r6   r   r   r   r:   Œ   s    
zResBlock.forward)rB   r;   r   r   r   r   rA   x   s   rA   c                	       s,   e Zd ZdZd‡ fdd	„	Zdd
d„Z‡  ZS )ÚGFPGANv1Cleana7  The GFPGAN architecture: Unet + StyleGAN2 decoder with SFT.

    It is the clean version without custom compiled CUDA extensions used in StyleGAN2.

    Ref: GFP-GAN: Towards Real-World Blind Face Restoration with Generative Facial Prior.

    Args:
        out_size (int): The spatial size of outputs.
        num_style_feat (int): Channel number of style features. Default: 512.
        channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2.
        decoder_load_path (str): The path to the pre-trained decoder model (usually, the StyleGAN2). Default: None.
        fix_decoder (bool): Whether to fix the decoder. Default: True.

        num_mlp (int): Layer number of MLP style layers. Default: 8.
        input_is_latent (bool): Whether input is latent style. Default: False.
        different_w (bool): Whether to use different latent w for different layers. Default: False.
        narrow (float): The narrow ratio for channels. Default: 1.
        sft_half (bool): Whether to apply SFT on half of the input channels. Default: False.
    r   r   NTr	   Fc                    s<  t t| ƒ ¡  || _|| _|| _|	d }td| ƒtd| ƒtd| ƒtd| ƒtd| | ƒtd| | ƒtd| | ƒtd| | ƒtd| | ƒdœ	}tt |d	¡ƒ| _	d	tt |d	¡ƒ }t
 d
||›  d¡| _||›  }t
 ¡ | _t| j	d	dƒD ]0}|d	|d  ›  }| j t||dd¡ |}qút
 ||d d
dd¡| _|d }t
 ¡ | _td
| j	d ƒD ].}|d	| ›  }| j t||dd¡ |}qft
 ¡ | _td
| j	d ƒD ]&}| j t
 |d	| ›  d
d¡¡ q°|rütt |d	¡ƒd	 d	 | }n|}t
 |d d d |¡| _t|||||	|
d| _|rT| j tj|dd„ dd ¡ |rv| j ¡ D ]\}}d|_qdt
 ¡ | _t
 ¡ | _td
| j	d ƒD ]œ}|d	| ›  }|
r¸|}n|d	 }| j t
  t
 ||d
dd¡t
 !dd¡t
 ||d
dd¡¡¡ | j t
  t
 ||d
dd¡t
 !dd¡t
 ||d
dd¡¡¡ qšd S )NrC   r   é   é€   é@   é    é   )	Ú4Ú8Z16Z32Z64Z128Z256Z512Z1024r
   r!   r   éÿÿÿÿrB   )rI   rU   rD   é   )r   r   r   r   r   r   c                 S   s   | S )Nr   )ZstorageÚlocr   r   r   Ú<lambda>ý   r   z(GFPGANv1Clean.__init__.<locals>.<lambda>)Zmap_locationZ
params_emaFrJ   T)"r   rO   r   r1   Údifferent_wr   r.   ÚmathÚlogÚlog_sizer   rE   Úconv_body_firstZ
ModuleListÚconv_body_downr"   r#   rA   Ú
final_convÚconv_body_upÚtoRGBZLinearÚfinal_linearr   Ústylegan_decoderZload_state_dictr)   ÚloadZnamed_parametersZrequires_gradÚcondition_scaleÚcondition_shiftZ
SequentialZ	LeakyReLU)r   r   r   r   Zdecoder_load_pathZfix_decoderr   r1   r[   r   r   Zunet_narrowZchannelsZfirst_out_sizerG   r    rH   Zlinear_out_channelÚ_ÚparamZsft_out_channelsr   r   r   r   ®   s    



÷



$ú	ÿ


þÿþÿzGFPGANv1Clean.__init__c                 K   s8  g }g }g }t j|  |¡dd}	t| jd ƒD ]}
| j|
 |	ƒ}	| d|	¡ q.t j|  |	¡dd}	|  |	 	|	 
d¡d¡¡}| jr–| 	| 
d¡d| j¡}t| jd ƒD ]n}
|	||
  }	| j|
 |	ƒ}	| j|
 |	ƒ}| | ¡ ¡ | j|
 |	ƒ}| | ¡ ¡ |r¤| | j|
 |	ƒ¡ q¤| j|g||| j|d\}}||fS )ak  Forward function for GFPGANv1Clean.

        Args:
            x (Tensor): Input images.
            return_latents (bool): Whether to return style latents. Default: False.
            return_rgb (bool): Whether return intermediate rgb images. Default: True.
            randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True.
        rJ   rK   r
   r   rW   )r3   r1   r2   )rL   rM   r_   r"   r^   r`   Úinsertra   rd   Úviewr/   r[   r   rb   rg   r#   Úclonerh   rc   re   r1   )r   rN   r3   Z
return_rgbr2   Úkwargsr0   Z
unet_skipsZout_rgbsZfeatr    Z
style_codeZscaleÚshiftr9   ri   r   r   r   r:     s6    	ü
zGFPGANv1Clean.forward)	r   r   NTr	   FFr   F)FTTr;   r   r   r   r   rO   ˜   s            ôgrO   )r\   r'   r)   Zbasicsr.utils.registryr   r   Ztorch.nnr   rL   Zstylegan2_clean_archr   r   ÚModulerA   ÚregisterrO   r   r   r   r   Ú<module>   s   m 