o
    *j                     @   s   d dl Z d dlmZ d dlmZ d dlmZmZ d dl	Z	d dl
Zd dlZd dlZd dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d d	l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j$e j%ej&dG dd deZ'dS )    N)TemporaryDirectory)AnyDict)	Pipelines)
DepeDetect)plot_result)	MsDataset)
OutputKeys)InputPipeline)	PIPELINES)Config)Tasks)
get_logger)module_namec                       s   e Zd Zdef fddZ fddZdd Zded	eee	f fd
dZ
deee	f d	eee	f fddZdeee	f d	eee	f fddZ  ZS )ObjectDetection3DPipelinemodelc                    s   t  jd
d|i| t|d}t|| _tj	 r#t
d| _
nt
d| _
t|| j
| _tddkr>d| _d	S d| _d	S )a`  
        use `model` to create a 3d object detection pipeline for prediction
        Args:
            model: model id on modelscope hub.

        Example:
            >>> import cv2
            >>> from modelscope.pipelines import pipeline
            >>> from modelscope.msdatasets import MsDataset
            >>> ms_ds_nuscenes = MsDataset.load('nuScenes_mini', namespace='shaoxuan')
            >>> data_path = ms_ds_nuscenes.config_kwargs['split_config']
            >>> val_dir = data_path['validation']
            >>> val_root = val_dir + '/' + os.listdir(val_dir)[0] + '/'
            >>> depe = pipeline('object-detection-3d', model='damo/cv_object-detection-3d_depe')
            >>> input_dict = {'data_root': val_root, 'sample_idx': 0}
            >>> result = depe(input_dict)
            >>> cv2.imwrite('result.jpg', result['output_img'])
        r   zmmcv_depe.pycudacpuZMODELSCOPE_ENVIRONMENTZeasr      N )super__init__ospjoinr   	from_filecfgtorchr   Zis_availabledevicer   todetectorosgetenvnum_workers)selfr   kwargsZconfig_path	__class__r   u/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/modelscope/pipelines/cv/object_detection_3d_pipeline.pyr      s   


z"ObjectDetection3DPipeline.__init__c                    s   t  j|fi |S )a.  
        Detect 3D objects in images from multi-cameras that passed as inputs

        Args:
            input (`Dict[str, Any]`):
                A dictionary of input consist 2 keys:
                - `data_root` is the path of input data in nuScenes format,
                you can create your own data according steps from model-card,
                if `data_root` is False, a default input data from
                nuScenes-mini validation set will be used, which includes 81
                samples from 2 scenes.
                - `sample_idx` is the index of sample to be inferenced, the
                value should in range of sample number in input data.

        Return:
            A dictionary of result consist 1 keys:
            - `output_img` plots all detection results in one image.

        )r   __call__)r$   inputr%   r&   r   r(   r)   ?   s   z"ObjectDetection3DPipeline.__call__c                 C   s>   t jddd}|jd }|d }|d t|d  d }|S )NZnuScenes_miniZshaoxuan)	namespaceZsplit_configZ
validation/r   )r   loadZconfig_kwargsr!   listdir)r$   Zms_ds_nuscenesZ	data_pathZval_dirZval_rootr   r   r(   get_default_dataU   s
   
z*ObjectDetection3DPipeline.get_default_datar*   returnc           
   
   C   s\  d|v sJ |d }t |d trt|d |d< |dd}|du r/|  }td|  ztj	ds;t
d t
d| d W n tyY } ztd	| d
d }~ww ddlm}m} ||d f| jjj_d| jjj_|| jjj| _|| jd| jddd}tt|}d|v rddlm}	 t| j jr|	|t| j jjgd }|S )NZ
sample_idx	data_rootFz%Note: forward using default data in: z/data/Datasetzmkdir -p /data/Datasetzln -snf z /data/Dataset/nuScenesz
exception:zH, please make sure to have permission create and write in: /data/Datasetr   )build_dataloaderbuild_dataset   T)Zsamples_per_gpuZworkers_per_gpudistshuffleZ	img_metas)scatter) 
isinstancestrintgetr/   loggerinfor!   pathexistssystem	ExceptionRuntimeErrorZmmdet3d.datasetsr2   r3   r   datatestZ	idx_rangeZ	test_modedatasetr#   nextiterZmmcv.parallelr7   r    
parametersZis_cudar   index)
r$   r*   idxr1   er2   r3   Zdata_loaderresultr7   r   r   r(   
preprocess\   sN   

z$ObjectDetection3DPipeline.preprocessc                 C   s>   t   | jdi |}W d    |S 1 sw   Y  |S )Nr   )r   Zno_gradr    )r$   r*   rL   r   r   r(   forward   s   

z!ObjectDetection3DPipeline.forwardinputsc                 K   s   | dd }|d u rt j}ntj|st| t|dd}d|i}| j	j
|fi | td|  t|ddd }tj|tjiS )	N	save_pathZpts_bboxzresults_nusc.jsonZjsonfile_prefixzDone, results saved into: g333333?)Z	vis_thredr   )r;   r   namer!   r>   r?   makedirsr   r   rE   Zformat_resultsr<   r=   r   r	   Z
OUTPUT_IMGZastypenpZuint8)r$   rO   r%   rP   	file_pathZkwargs_formatZ
result_imgr   r   r(   postprocess   s   

z%ObjectDetection3DPipeline.postprocess)__name__
__module____qualname__r9   r   r)   r/   r
   r   r   rM   rN   rU   __classcell__r   r   r&   r(   r      s     "%*r   )(r!   Zos.pathr>   r   tempfiler   typingr   r   Zcv2numpyrS   ZPILr   Zmodelscope.metainfor   Z-modelscope.models.cv.object_detection_3d.deper   Z8modelscope.models.cv.object_detection_3d.depe.result_visr   Zmodelscope.msdatasetsr   Zmodelscope.outputsr	   Zmodelscope.pipelines.baser
   r   Zmodelscope.pipelines.builderr   Zmodelscope.utils.configr   Zmodelscope.utils.constantr   Zmodelscope.utils.loggerr   r<   Zregister_moduleZobject_detection_3dZobject_detection_3d_deper   r   r   r   r(   <module>   s.   