U
    PhX                     @  sn   d dl mZ d dlZd dlZd dlmZ d dlmZ d dlZ	d dl
Z
d dlmZ d dlmZ G dd dZdS )	    )annotationsN)OrderedDict)Path)PathLike)ImageMetaKeyc                   @  s|   e Zd ZdZdddd	d	dd
dddZd
dddZd ddd
dddZd!ddd
dddZddddZd
dddZ	dS )"CSVSavera	  
    Save the data in a dictionary format cache, and write to a CSV file finally.
    Typically, the data can be classification predictions, call `save` for single data
    or call `save_batch` to save a batch of data together, and call `finalize` to write
    the cached data into CSV file. If no metadata provided, use index from 0 to save data.
    Note that this saver can't support multi-processing because it reads / writes single
    CSV file and can't guarantee the data order in multi-processing situation.

    ./predictions.csvTF,r   strboolNone)
output_dirfilename	overwriteflush	delimiterreturnc                 C  sr   t || _t | _t|tr,|dd dks6td | j| | _| j	 r\|r\t
| j || _|| _d| _dS )a  
        Args:
            output_dir: output CSV file directory.
            filename: name of the saved CSV file name.
            overwrite: whether to overwriting existing CSV file content, if True, will clear the file before saving.
                otherwise, will append new content to the CSV file.
            flush: whether to write the cache data to CSV file immediately when `save_batch` and clear the cache.
                default to False.
            delimiter: the delimiter character in the saved file, default to "," as the default output type is `csv`.
                to be consistent with: https://docs.python.org/3/library/csv.html#csv.Dialect.delimiter.

        Nz.csvz.CSV filename is not a string ends with '.csv'.r   )r   r   r   _cache_dict
isinstancer   warningswarn	_filepathexistsosremover   r   _data_index)selfr   r   r   r   r    r   I/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/data/csv_saver.py__init__%   s    

zCSVSaver.__init__)r   c              	   C  s   | j  s| j jddd t| jdP}| j D ]>\}}|| | D ]}|| j	t
|  qL|d q2W 5 Q R X |   dS )z2
        Writes the cached dict to a csv

        T)parentsexist_oka
N)r   r   mkdiropenr   r   itemswriteflattenr   r   reset_cache)r   fkvresultr   r   r    finalizeE   s    

zCSVSaver.finalizeNztorch.Tensor | np.ndarrayzdict | None)data	meta_datar   c                 C  sZ   |r|t j nt| j}|  jd7  _t|tjrB|  	 }t
j|td| j|< dS )a  Save data into the cache dictionary. The metadata should have the following key:
            - ``'filename_or_obj'`` -- save the data corresponding to file name or object.
        If meta_data is None, use the default index from 0 to save data instead.

        Args:
            data: target data content that save into cache.
            meta_data: the metadata information corresponding to the data.

           )dtypeN)KeyFILENAME_OR_OBJr   r   r   torchTensordetachcpunumpynpasarrayfloatr   )r   r1   r2   Zsave_keyr   r   r    saveU   s
    
zCSVSaver.save)
batch_datar2   r   c                   sH   t |D ],\ }| |r. fddD nd q| jrD|   dS )zSave a batch of data into the cache dictionary.

        Args:
            batch_data: target batch data content that save into cache.
            meta_data: every key-value in the meta_data is corresponding to 1 batch of data.

        c                   s   i | ]}||   qS r   r   ).0r-   ir2   r   r    
<dictcomp>n   s      z'CSVSaver.save_batch.<locals>.<dictcomp>N)	enumerater?   r   r0   )r   r@   r2   r1   r   rB   r    
save_batche   s    &zCSVSaver.save_batchr   c                 C  s   | j S )zMGet the cache dictionary, key is filename and value is the corresponding data)r   r   r   r   r    	get_caches   s    zCSVSaver.get_cachec                 C  s   | j   dS )z"Clear the cache dictionary contentN)r   clearrG   r   r   r    r+   x   s    zCSVSaver.reset_cache)r   r	   TFr
   )N)N)
__name__
__module____qualname____doc__r!   r0   r?   rF   rH   r+   r   r   r   r    r      s         r   )
__future__r   r   r   collectionsr   pathlibr   r;   r<   r7   monai.config.type_definitionsr   monai.utilsr   r5   r   r   r   r   r    <module>   s   