o
    *j<'                     @   s   d dl Z d dlmZ d dlmZm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 d dlmZ d dlmZ d dlmZ d d	lmZ e Zee
jed
k r[n	ede  d ej!ddG dd deZ"dS )    N)DictOptional)version)tqdm)CartoonModelall_filesimple_superpixeltf_data_loaderwrite_batch_image)BaseTrainer)TRAINERS)	ModelFile)
get_logger2zTensorFlow version z< found, TF2.x is not supported by CartoonTranslationTrainer.zcartoon-translation)module_namec                       sd   e Zd Z					ddedef fddZdd Zdd	 Z	dd
ee deee	f fddZ
  ZS )CartoonTranslationTrainerNmodelcfg_filec                    sV  |  |}t  || _t|tj| _|du rt|tj	}t
 | i | _|   |dur5|| jd< |dur>|| jd< |durG|| jd< |durP|| jd< tj| jd sat| jd  t| jd | _t| jd | _tjdd}	d|	j_tj|	d| _ttj| jd	 | jd
 | jd
 dg| _ttj| jd	 | jd
 | jd
 dg| _ttj| jd	 | jd
 | jd
 dg| _t| j| _ |  | j| j| j}
|
d | _!|
d | _"|
d | _#tj$%d| j" tj$%d| j# tj$&| jd d | _'tj$( | _)t* }dd |D }dd |D }t+tj,j-}t.|. tj/j0| jd dddj1| j"|d| _2tj/j0| jd dddj1| j#|d| _3W d   n	1 sRw   Y  tj/j4dd| _5| j6 <}|7t8  | jd dkrt9:d| j  | j5;|t| jdt<| jd   W d   dS W d   dS 1 sw   Y  dS )a  
                Args:
                    model: the model_id of trained model
                    cfg_file: the path of configuration file
                    work_dir: the path to save training results
                    photo: the path of photo images for training
                    cartoon: the path of cartoon images for training
                    max_steps: the number of total iteration for training
                Returns:
                    initialized trainer: object of CartoonTranslationTrainer
        Nwork_dirphotocartoon	max_stepsT)Zallow_soft_placement)config
batch_size
patch_size   output_cartoong_lossd_lossz
/train_logc                 S      g | ]	}d |j v r|qS )Zgenename.0var r%   s/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/modelscope/trainers/cv/cartoon_translation_trainer.py
<listcomp>p       z6CartoonTranslationTrainer.__init__.<locals>.<listcomp>c                 S   r   )Zdiscr    r"   r%   r%   r&   r'   q   r(   adv_train_lrg      ?gGz?)Zbeta1Zbeta2)Zvar_listi  )Zmax_to_keepresume_epochr   zloading model from zmodel-)=Zget_or_download_model_dirtfZreset_default_graphZ	model_dirospjoinr   ZTF_CHECKPOINT_FOLDERZ
model_pathZCONFIGURATIONsuper__init__params_override_params_from_fileospathexistsmakedirsr   face_photo_listface_cartoon_listZConfigProtoZgpu_optionsZallow_growthSession_sessionplaceholderZfloat32input_photoinput_superpixelinput_cartoonr   r   r   r   r   summaryZscalarZ
FileWritertrain_writerZ	merge_all
summary_opZtrainable_variablesZget_collectionZ	GraphKeysZ
UPDATE_OPSZcontrol_dependenciestrainZAdamOptimizerZminimizeg_optimd_optimZSaversaverZ
as_defaultrunZglobal_variables_initializerloggerinfoZrestorestr)selfr   r   r   r   r   r   argskwargsZ	tf_configoutputZall_varsZ	gene_varsZ	disc_varsZ
update_opssess	__class__r%   r&   r/   !   s   











$z"CartoonTranslationTrainer.__init__c                 C   s   | j d d | jd< | j d d | jd< | j d d | jd< | j d d | jd< | j d d | jd< | j d d | jd< | j d d | jd< | j d d	 | jd	< | j d d
 | jd
< | j d d | jd< | j d d | jd< d S )NrA   r   r   r   r   r   r)   r   logging_intervalckpt_period_intervalr*   Znum_gpus)cfgr0   )rI   r%   r%   r&   r1      s   
z4CartoonTranslationTrainer._override_params_from_filec              
   O   s\  t d t| j| jd }t| j| jd }| }| }| }| }tj	j
r-dnd}	t|	 tt| jd D ]}
| j|j | j|j | j||g\}}| jj| j| j|id}t|dd}| jj| j| jg| j|| j|| j|id\}}| jj| j| j| jg| j|| j|| j|id\}}}| j||
 t|
d	 | jd
 dks|
dkrt d|
 d| d|  t|
d	 | jd dks|
dkr| jj | j| jd d d|
d | jj| j| j|| j|| j|id}t!|| jd d t"d|
 d d t!|| jd d t"d|
 d d q>W d    d S 1 s'w   Y  d S )Nz'Begin local cartoon translator trainingr   zgpu:0zcpu:0r   )Z	feed_dict   )Zseg_num   rP   r   zIter: z
, d_loss: z
, g_loss: rQ   r   z/saved_models/modelF)Zwrite_meta_graphZglobal_stepz/imagesz%8dz_face_result.jpg   z_face_photo.jpg)#rF   rG   r	   r6   r0   r7   Zmake_initializable_iteratorZget_nextr+   testZis_gpu_availabledevicer   ranger9   rE   Zinitializerr   r;   r   r   rB   r<   r=   r   rC   r@   r?   Zadd_summarynpmodrD   saver
   rH   )rI   rJ   rK   Zphoto_dsZ
cartoon_dsZphoto_iteratorZcartoon_iteratorZ
photo_nextZcartoon_nextrW   r   Zphoto_batchZcartoon_batchZtransfer_resr<   r   _r   Z
train_infoZresult_facer%   r%   r&   rA      s   





$zCartoonTranslationTrainer.traincheckpoint_pathreturnc                 O   s   t d)a  evaluate a dataset

        evaluate a dataset via a specific model from the `checkpoint_path` path, if the `checkpoint_path`
        does not exist, read from the config file.

        Args:
            checkpoint_path (Optional[str], optional): the model path. Defaults to None.

        Returns:
            Dict[str, float]: the results about the evaluation
            Example:
            {"accuracy": 0.5091743119266054, "f1": 0.673780487804878}
        z6evaluate is not supported by CartoonTranslationTrainer)NotImplementedError)rI   r]   rJ   rK   r%   r%   r&   evaluate   s   z"CartoonTranslationTrainer.evaluate)NNNNN)N)__name__
__module____qualname__rH   r/   r1   rA   r   r   floatr`   __classcell__r%   r%   rN   r&   r      s&    bN
r   )#r2   Zos.pathr3   r,   typingr   r   numpyrY   Z
tensorflowr+   	packagingr   r   Zmodelscope.models.cv.cartoonr   r   r   r	   r
   Zmodelscope.trainers.baser   Zmodelscope.trainers.builderr   Zmodelscope.utils.constantr   Zmodelscope.utils.loggerr   rF   parse__version__rG   Z_tf_versionZregister_moduler   r%   r%   r%   r&   <module>   s(   

