o
    ॵi<'                     @   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)allow_soft_placement)config
batch_size
patch_size   output_cartoong_lossd_lossz
/train_logc                 S      g | ]	}d |j v r|qS )genename.0var r'   f/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/trainers/cv/cartoon_translation_trainer.py
<listcomp>p       z6CartoonTranslationTrainer.__init__.<locals>.<listcomp>c                 S   r    )discr"   r$   r'   r'   r(   r)   q   r*   adv_train_lrg      ?gGz?)beta1beta2)var_listi  )max_to_keepresume_epochr   zloading model from zmodel-)=get_or_download_model_dirtfreset_default_graph	model_dirospjoinr   TF_CHECKPOINT_FOLDER
model_pathCONFIGURATIONsuper__init__params_override_params_from_fileospathexistsmakedirsr   face_photo_listface_cartoon_listConfigProtogpu_optionsallow_growthSession_sessionplaceholderfloat32input_photoinput_superpixelinput_cartoonr   r   r   r   r   summaryscalar
FileWritertrain_writer	merge_all
summary_optrainable_variablesget_collection	GraphKeys
UPDATE_OPScontrol_dependenciestrainAdamOptimizerminimizeg_optimd_optimSaversaver
as_defaultrunglobal_variables_initializerloggerinforestorestr)selfr   r   r   r   r   r   argskwargs	tf_configoutputall_vars	gene_vars	disc_vars
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 )NrZ   r   r   r   r   r   r,   r   logging_intervalckpt_period_intervalr1   num_gpus)cfgr=   )rh   r'   r'   r(   r>      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   )	feed_dict   )seg_num   rt   r   zIter: z
, d_loss: z
, g_loss: ru   r   z/saved_models/modelF)write_meta_graphglobal_stepz/imagesz%8dz_face_result.jpg   z_face_photo.jpg)#rd   re   r	   rC   r=   rD   make_initializable_iteratorget_nextr3   testis_gpu_availabledevicer   rangerI   rb   initializerr   rL   r   r   r]   rM   rN   r   r^   rT   rR   add_summarynpmodr`   saver
   rg   )rh   ri   rj   photo_ds
cartoon_dsphoto_iteratorcartoon_iterator
photo_nextcartoon_nextr   r   photo_batchcartoon_batchtransfer_resrM   r   _r   
train_inforesult_facer'   r'   r(   rZ      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)rh   r   ri   rj   r'   r'   r(   evaluate   s   z"CartoonTranslationTrainer.evaluate)NNNNN)N)__name__
__module____qualname__rg   r<   r>   rZ   r   r   floatr   __classcell__r'   r'   rr   r(   r      s&    bN
r   )#r?   os.pathr@   r6   typingr   r   numpyr   
tensorflowr3   	packagingr   r   modelscope.models.cv.cartoonr   r   r   r	   r
   modelscope.trainers.baser   modelscope.trainers.builderr   modelscope.utils.constantr   modelscope.utils.loggerr   rd   parse__version__re   _tf_versionregister_moduler   r'   r'   r'   r(   <module>   s(   

