a
    þdé  ã                   @   sZ   d dl mZ d dlZd dlZd dlmZmZ d dlm	Z	m
Z
 d dlmZ G dd„ dƒZdS )é    )ÚImageN)Úbuild_feature_extractorÚget_reference_statistics)Úget_batch_featuresÚfid_from_feats)Úbuild_resizerc                   @   sH   e Zd Zddd„Zdd„ Zdd	„ Zd
d„ Zddd„Zdd„ Zdd„ Z	dS )ÚCleanFIDÚcleanÚinception_v3Úcudac                 C   sh   g | _ g | _|| _|| _|dkr8t||ƒ| _t|ƒ| _n,|dkrdddlm	}m
} |dƒ}|| _|| _d S )Nr
   Zclip_vit_b_32r   )ÚCLIP_fxÚimg_preprocess_clipzViT-B/32)Úreal_featuresÚgen_featuresÚmodeÚdevicer   Ú
feat_modelr   Ú	fn_resizeZcleanfid.clip_featuresr   r   )Úselfr   Z
model_namer   r   r   Zclip_fx© r   úZ/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/cleanfid/wrappers.pyÚ__init__   s    zCleanFID.__init__c                 C   s>  t |tjƒrHt |¡}|  |¡}t | d¡¡ d¡}t	|| j
| jƒ}nòt |tjƒrŽ|  |¡}t | d¡¡ d¡ | j¡}t	|| j
| jƒ}n¬t |tjƒr2t|jƒdkr´| d¡}|j\}}}}	g }
t|ƒD ].}||  ¡  ¡  d¡}|
 |  |¡d ¡ qÎt |
¡}t | d¡¡ | j¡}t	|| j
| jƒ}ntdƒ‚|S )N)é   r   é   r   é   )r   r   r   ©N)r   r   r   r   z image type could not be inferred)Ú
isinstancer   ÚnpÚarrayr   ÚtorchZtensorZ	transposeZ	unsqueezer   r   r   ZndarrayÚtoZTensorÚlenÚshapeÚrangeÚcpuÚnumpyÚappendÚconcatenateÚ
ValueError)r   ÚxZx_npZx_np_resizedZx_tÚx_featÚbÚcÚhÚwZl_x_np_resizedÚ_r   r   r   Úcompute_features    s,    




zCleanFID.compute_featuresc                 C   s   |   |¡}| j |¡ d S r   )r0   r   r&   ©r   r)   r*   r   r   r   Úadd_real_imagesB   s    
zCleanFID.add_real_imagesc                 C   s   |   |¡}| j |¡ d S r   )r0   r   r&   r1   r   r   r   Úadd_gen_imagesI   s    
zCleanFID.add_gen_imagesTc                 C   sN   t  | j¡}t  | j¡}|rDtd|jd › ƒ td|jd › ƒ t||ƒS )Nz# real images = r   z# generated images = )r   r'   r   r   Úprintr"   r   )r   ÚverboseZfeats1Zfeats2r   r   r   Úcalculate_fidP   s    zCleanFID.calculate_fidc                 C   s
   g | _ d S r   )r   ©r   r   r   r   Úreset_real_features[   s    zCleanFID.reset_real_featuresc                 C   s
   g | _ d S r   )r   r7   r   r   r   Úreset_gen_featuresa   s    zCleanFID.reset_gen_featuresN)r	   r
   r   )T)
Ú__name__Ú
__module__Ú__qualname__r   r0   r2   r3   r6   r8   r9   r   r   r   r   r      s   
"
r   )ZPILr   r%   r   r   Zcleanfid.featuresr   r   Zcleanfid.fidr   r   Zcleanfid.resizer   r   r   r   r   r   Ú<module>   s   