a
    Ad&                     @   s   U 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Zd dlmZ d dlmZmZ d dlmZmZmZ daejjed< G d	d
 d
Zdd Ze dddZ e dddZ!dS )    N)Image)	rearrangerepeat)	OmegaConf)DDIMSampler)instantiate_from_configismap)shared	sd_hijackdevicescached_ldsr_modelc                   @   s2   e Zd Zdd Zdd Zedd Zdd
dZdS )LDSRc                 C   s  t jjrtd urtd t}ntd| j  tj| j\}}|	 dkr`t
jj| jdd}ntj| jdd}d|v r|d n|}t| j}d|j_t|j}|j|d	d
 |t j}|r| }t jjr|jtjd}tj| |  t jjr|ad|iS )NzLoading model from cachezLoading model from z.safetensorscpu)device)map_location
state_dictz+ldm.models.diffusion.ddpm.LatentDiffusionV1F)strict)memory_formatmodel)r	   optsldsr_cachedr   print	modelPathospathsplitextlowersafetensorstorch	load_fileloadr   yamlPathr   targetr   load_state_dicttor   halfcmd_optsopt_channelslastchannels_lastr
   model_hijackhijackeval)selfhalf_attentionr   _	extensionpl_sdsdconfig r3   O/var/www/html/stable-diffusion-webui/extensions-builtin/LDSR/ldsr_model_arch.pyload_model_from_config   s.    
zLDSR.load_model_from_configc                 C   s   || _ || _d S )N)r   r!   )r,   
model_path	yaml_pathr3   r3   r4   __init__6   s    zLDSR.__init__c                 C   s
  t |}d}d }d }d}d}	|}d }
|d jdd \}}|dkoH|dk}|r~d}d}d}||f||f|d	dd
dd
dd	| _nt| drt| d d }d }t|D ]b}|
d urtd|
d |
d |
d | j	}t
|d|
d d}t|| ||d|
|	d||||d}q|S )N   F      ?image      @      Tg      ?g{Gz?)	ksstridevqfZpatch_distributed_vq
tie_brakerclip_max_weightclip_min_weightclip_max_tie_weightclip_min_tie_weightsplit_input_params   z1 c h w -> b c h wr   )b        )
custom_stepsetaquantize_x0custom_shapetemperaturenoise_dropout	correctorcorrector_kwargsx_Tddim_use_x0_pred)get_condshaperH   hasattrdelattrranger   randnr$   r   r   make_convolutional_sample)r   selected_pathrL   rM   exampleZn_runsguiderckwargsrU   rP   rO   heightwidthsplit_inputr@   rA   rB   x_tlogsr.   r3   r3   r4   run:   sP    
	

$zLDSR.rund   rI   Fc              
   C   s  |  |}t|}d}t  t  |}|j\}	}
|d }|	| }|
| }tt|}tt|}|dkrt	d|	 d|
 d| d| d	 |
||ftj}nt	d| d	 tjd
tt|jd tfddd |j \}}ttjt|d|fd|fdfdd}| |d |||}|d }|  }t|dd}|d d d }| tj}t|d}t|d }|dtt|jd  }~t  t  |S )Nr:   r?   r9   zDownsampling from [z, z] to []zDown sample rate is 1 from z / 4 (Not downsampling))rI   rI   r>   r   )axis)r   r   edge)moder   sampleg             @   )r   rI   r<   r9   )r5   intgccollectr   torch_gcsizenpceilr   resizer   LANCZOSmaxarrayastype	fromarraypadrf   detachr   r   clampnumpyuint8	transposecroptuple)r,   r;   stepsZtarget_scaler-   r   Zdiffusion_stepsrM   Zim_ogZwidth_ogZ	height_ogZdown_sample_ratewdhdZwidth_downsampled_preZheight_downsampled_prepad_wpad_hZ	im_paddedre   rl   ar3   r3   r4   super_resolutionj   sB    

8*zLDSR.super_resolutionN)rg   rI   F)__name__
__module____qualname__r5   r8   staticmethodrf   r   r3   r3   r3   r4   r      s
    
/r   c                 C   s   i }d}|  d}ttj |d}tjjj|||jd  ||jd  gdd}t	|d}t	|d}d	| d
 }|
tj}||d< ||d< |S )Nr?   RGBr   rI   r<   T)rs   	antialiasz1 c h w -> 1 h w crm   r:   ZLR_imager;   )convertr   	unsqueezetorchvision
transformsToTensor
functionalrv   rW   r   r$   r	   r   )r]   r^   Zup_fcZc_upr3   r3   r4   rV      s    
$

rV   r:   Fc                 C   sd   t | }|d }|dd  }td| d|  |j|||||||	||||
d|||d\}}||fS )Nr   r9   zSampling with eta = z	; steps: F)
batch_sizerW   conditioningcallbacknormals_sequencerN   rM   maskx0rP   verbosescore_correctorrS   rd   )r   r   rl   )r   condr   rW   rM   r   r   r   r   rN   rP   r   rS   rd   ddimbssamplesintermediatesr3   r3   r4   convsample_ddim   s    
r   rK   c                 C   s  i }|j | |jdt|do"|jdk dd\}}}}}|d urht|}td|d  d|dd    d }||d	< ||d
< t|r|||d< t|dr||||j< nZ|d ur|nt	||d< |j
r|d ur|nt	|||j< |jdkr||j ||j< |dX t }t||||j||d ||||	|
d\}}t }|r\|d d }W d    n1 sr0    Y  ||}z,|j|dd}||d< t|| |d< W n ty   Y n0 ||d< || |d< |S )NTrH   coordinates_bbox)return_first_stage_outputsforce_c_encodereturn_original_condzGenerating r   z samples of shape r9   inputreconstructionoriginal_conditioningcond_stage_keyclass_labelPlotting)
r   rW   rM   rN   r   r   rP   r   rS   rd   pred_x0)force_not_quantizeZsample_noquantZsample_diffrl   time)	get_inputfirst_stage_keyrX   r   r   r[   r   r   to_rgb
zeros_likecond_stage_model	ema_scoper   r   rW   decode_first_stageabs	Exception)batchr   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   logzr   xxrecxcz0t0rl   r   t1x_sampleZx_sample_noquantr3   r3   r4   r\      sX    


 

,
r\   )
r:   NNNNFr:   NNN)
Nr:   FNr:   rK   NNNF)"r   rp   r   r   rt   r   r   PILr   einopsr   r   	omegaconfr   safetensors.torchr   ldm.models.diffusion.ddimr   ldm.utilr   r   modulesr	   r
   r   r   nnModule__annotations__r   rV   no_gradr   r\   r3   r3   r3   r4   <module>   s2   
 	     