U
    d*                     @   sP   d dl Z d dlmZ d dlmZ d dlmZ d dlmZm	Z	 G dd deZ
dS )    N)core)DBFileReader)pipe)Cluster	TaskGroupc                       s<   e Zd ZdZd fdd	Zdd	 Zdd
dZdd Z  ZS )CachedReaderZcached_readerLevelDBNd   Fc                    s2   |d k	st d|| _tt| ||||| d S )Nzoriginal_reader can't be None)AssertionErrororiginal_readersuperr   __init__)selfr   db_pathdb_typenameZ
batch_sizeZ	loop_over	__class__ ?/tmp/pip-unpacked-wheel-ua33x9lu/caffe2/python/cached_reader.pyr   >   s    	
zCachedReader.__init__c                 O   s   | j jS )zPrepare the reader schema.

            Since an original reader is given,
            use it's schema as ground truth.

            Returns:
                schema: schema.Struct. Used in Reader.__init__(...).
        )r   Z_schema)r   argskwargsr   r   r   _init_reader_schemaR   s    	z CachedReader._init_reader_schemac                 C   s   t j| jr|stdg S td}| | t R t	| j
: t (}t| j| j dd |  }W 5 Q R X W 5 Q R X W 5 Q R X td}| | td|||gS )a  Build a step for generating cache DB file.

            If self.db_path exists and not overwritting, build an empty step.
            Overwise, build a step as follows.
            Pipe original reader to the _DatasetWriter,
            so that dataset field blobs are populated.
            Then save these blobs into a file.

            Args:
                overwrite: bool. If true, ignore the existing file
                    and build a new one overwritting the existing one anyway.

            Returns:
                build_cache_step: ExecutionStep.
                    The step to be run for building a cache DB file.
        Z
build_stepinit   )Znum_threadssaveZbuild_cache)ospathexistsr   r   Zexecution_stepZNetZ_init_field_blobs_as_emptyr   Z	NameScoper   r   r   r   dswriterZto_taskZget_step_save_field_blobs_to_db_file)r   	overwriteZinit_netZcopy_tgZ	copy_stepZsave_netr   r   r   build_cache_step]   s    

*

zCachedReader.build_cache_stepc                 C   s*   |j | j g | j| j| j dd dS )z0Save dataset field blobs to a DB file at db_pathT)dbr   Zblob_name_overridesZabsolute_pathN)ZSaver   Z	get_blobsr   r   field_names)r   netr   r   r   r!   |   s    z)CachedReader._save_field_blobs_to_db_file)r   Nr	   F)F)	__name__
__module____qualname__Zdefault_name_suffixr   r   r#   r!   __classcell__r   r   r   r   r      s   0    
r   )r   Zcaffe2.pythonr   Zcaffe2.python.db_file_readerr   Zcaffe2.python.pipeliner   Zcaffe2.python.taskr   r   r   r   r   r   r   <module>   s
   