
    ZTh/                     >   d 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mZmZ ddlmZ 	 ddlmZ ddlmZ dd	lmZmZ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' ddl(m)Z) ddl*m+Z+ ddl,m-Z-  G d d      Z.y# e$ rZ ed      edZ[ww xY w)a	  
Service to upload ROS2 bag files.


ROS organizes data exchange through topics, messages, and fields:
    * topics: Named messages that facilitate communication between ROS nodes.
    * messages: Data structures published and subscribed to on topics. Each message type defines a specific schema.
    * fields: Individual data elements within a message, such as integers, floats, strings, or nested structures.

This class extracts messages from a ROS bag, flattens their fields, and prepares them for uploading to Sift.
    N)glob)Path)CallableDictListOptionalSetTextIOUnion)alive_it)	Typesdict)Reader)Storesget_types_from_msgget_typestore)	TypestorezThe rosbags package is required to use the rosbag upload service. Please include this dependency in your project by specifying `sift-stack-py[rosbags]`.)
DataColumn
TimeColumn)
RosChannel)	CsvConfig)CsvUploadService)DataImportService)NamedTemporaryFile)TimeFormatType)SiftRestConfigc                   V   e Zd ZU dZeed<   defdZ	 	 	 	 	 ddee	e
f   deee	e
f      ded	e	d
edee	   dee	   deee	ef      dedefdZ	 	 ddee	e
f   dedeee	e
f      ded
edeee	ef      dedee   fdZdedeee	e
f      dee	   fdZ	 	 ddee   d	e	dee	   dee	   def
dZy)RosbagsUploadServicez+
    Service to upload ROS2 bag files.
    _csv_upload_service	rest_confc                 $    t        |      | _        y )N)r   r   )selfr   s     `/home/www/backend.miabetepe.com/venv/lib/python3.12/site-packages/sift_py/data_import/rosbags.py__init__zRosbagsUploadService.__init__1   s    #3I#>     Npathmsg_dirsstore
asset_nameignore_errorsrun_namerun_idhandlersshow_progressreturnc
           
      .   t        |t              rt        |      n|}
|
j                         st	        d| d      |
j                         st	        d| d      t        dd      5 }	 | j                  |||||||	      }|st	        d|       	 | j                  ||||      }t        d
       | j                  j                  |j                  ||	      cd	d	d	       S # t        j                  $ r}t	        d|       d	}~ww xY w# 1 sw Y   y	xY w)a  
        Uploads the ROS2 bag file pointed to by `path` to the specified asset.

        Arguments:
            path: Path to the ROS2 bag file.
            msg_dirs: List of directories containing message definitions.
                Each entry should be a path the root directory of the msg definitions (e.g, `/path/to/std_msgs`).
                Inspect your topics and verify that the 'type' matches the directory structure of your
                message definitions. For example if the type is `custom_msgs/msg/MyCustomMessage` your
                directory structure should match that and you should include `/path/to/custom_msgs`
                in the `msg_dirs` list passed into this function.
            store: The Store type to use for the message definitions.
            asset_name: Name of the asset to upload the data to.
            ignore_errors: If True, will skip messages without definitions.
            run_name: Name of the run to create for this data.
            run_id: ID of the run to add this data to.
            handlers: Dictionary of messages to callbacks for custom processing or sequence data
                (e.g, images or videos). Keys should be the ROS topic, value is a callable with
                the following signature:
                    def callback(topic: str, timestamp: int, msg: object)
                        ...
            show_progress: Whether to show the status bar or not.
        zProvided path, 'z', does not existsz!', does not point to a directory.wtz.csv.gz)modesuffixzNo valid channels remaining in zXFailed to parse the rosbag. Ensure you're using the correct type store. Original error: NzUploading file)
isinstancestrr   exists	Exceptionis_dirr   _convert_to_csvstructerror_create_csv_configprintr   uploadname)r!   r%   r&   r'   r(   r)   r*   r+   r,   r-   
posix_path	temp_filevalid_channelse
csv_configs                  r"   r=   zRosbagsUploadService.upload4   s<   F $.dC#8T$Zd
  ".tf4FGHH  ".tf4UVWWT)< 	^	!%!5!5!!" &#&EdV$LMM & 00XW]^J"#++229>>:}]+	^ 	^ << nopnqr 	^ 	^s1   )D+'C"AD"D5DDDDsrc_pathdst_filec                    |xs i }t        |      }| j                  ||      }	i }
d }d }t        |      5 }|j                  D ]  }|j                  |	vr5|rt        d|j                   d       -t        d|j                   d      |j                  |j                        }|j                  D ]H  } ||||      }||
v rt        d|       t        j                   ||j                        ||      |
|<   J  dg|
j                         D cg c]  }|D ]  }|j                    c}}z   }t        j                  ||      }|j!                          t        d	       t#        |j%                         |j&                  d
|       D ]
  \  }}}|j                  |	vr|rt        d|j                   d      i }|j)                  ||j                        }|j                  |j                        }||d<   |j                  |v r! ||j                     |j                  ||       |j                  D ]L  } ||||      }||
vr|rt        d| d      |
|   }|D ]   }|j+                  |      ||j                  <   " N |j-                  |        	 ddd       |j/                          |
j                         D 
cg c]  }
|
D ]  }|  c}}
S c c}}w # 1 sw Y   FxY wc c}}
w )a  Converts the ROS2 bag file to a temporary CSV on disk that we will upload.


        Args:
            src_path: The path of the rosbag.
            dst_file: The path to save the CSV.
            msg_dirs: The list of directories containing rosbag message definitions.
            store: The rosbag type store to use.
            ignore_errors: Whether to ignore errors (e.g, unknown message definitions).
            handlers: Dictionary of messages to callbacks for custom processing or sequence data
                (e.g, images or videos). Keys should be the ROS topic, value is a callable with
                the following signature:
                    def callback(topic: str, timestamp: int, msg: object)
                        ...
            show_progress: Whether to show the status bar or not.
        Returns:
            The list valid channels after parsing the ROS2 bag file.
        c                 r    dj                  | j                  d            }|j                  d      r|dd  }|S )N_/   )joinsplit
startswith)r>   results     r"   sanitizez6RosbagsUploadService._convert_to_csv.<locals>.sanitize   s6    XXdjjo.F  %Mr$   c                 >    | j                    d|j                   d| S )N:)topicr>   )
connectionmsg_deffields      r"   get_keyz5RosbagsUploadService._convert_to_csv.<locals>.get_key   s$     &&'qaw??r$   zWARNING: Skipping z. msg file not found.zMessage type z not found in custom types.zDuplicate key: timezProcessing rosbag messagesz	 messages)totalunitdisablezMessage field N)r   _register_typesr   connectionsmsgtyper<   r6   
get_msgdeffieldsr   get_underlying_fieldsrR   valueschannel_namecsv
DictWriterwriteheaderr   messagesmessage_countdeserialize_cdrextract_valuewriterowclose)r!   rD   rE   r&   r'   r)   r,   r-   	typestoreregistered_msg_typesros_channelsrO   rV   readerrS   rT   rU   keychannelscheadersw	timestampraw_datarowmsgs                             r"   r8   z$RosbagsUploadService._convert_to_csvv   sA   8 >r!%(	#33IxH 57		@ H >	 $00 
%%-AA$ 2:3E3E2FF[\] '+J,>,>+??Z[ 
 $..z/A/AB$^^ E!*gu=Cl*'/#(?@@(2(H(H !1!12E9)L%	( h/;/B/B/D"#+h"IJ"" G x1AMMO./3;!** ))	4 ! /
Ix %%-AA$ '+J,>,>+??Z[  @B//*:L:LM#..z/A/AB'F##x/.HZ--.z/?/?CP$^^ 	CE!*gu=C,.($"+nSEA\,]"^^+C0H% C./ooc.BANN+C	C 

3C! ;>	 D 	&2&9&9&;Rl\RRRR]"->	  >	 H Ss%   CK K
-E-K K,K  K)rl   c                    i }|D ]  }t        |      }t        t        |dz  dz              D ]  }t        |      j                  |      }|j                  |z  }|j                  t        t        |      j                         t        |      j                  dd      j                  dd                     |j                  |       t        |j                               S )a$  Register custom message types with the typestore.

        Args:
            typestore: The type store to register messages against.
            msg_dirs: The list of directories containing message definitions.

        Returns:
            Set of all registered message definitions.
        z**z*.msg\rI   z.msg )r   r   r4   relative_tor>   updater   	read_textreplaceregistersetkeys)	r!   rl   r&   	msg_typesdir_pathnamedir_pathmsg_pathnamerelative_msg_pathmsg_path_from_roots	            r"   r[   z$RosbagsUploadService._register_types   s      "	$ 
	LL)H $SD7)B%C D $($6$B$B<$P!%-]]5F%F"  &\*446./77cBJJ6SUV
	 	9%9>>#$$r$   rq   c                     i }d}t        |      D ]2  \  }}|j                  }	t        |j                  |	dd      }
|
|||z   <   4 ||t	        t
        j                  d      |d}|||d<   |||d<   t        |      S )	zAConstruct a CsvConfig based on metadata within the ROS2 bag file.   r{   )r>   	data_typedescriptionunitsrJ   )formatcolumn_number)r(   first_data_rowtime_columndata_columnsr*   r+   )	enumerater   r   rb   r   r   ABSOLUTE_UNIX_NANOSECONDSr   )r!   rq   r(   r*   r+   data_configfirst_data_columnichannelr   channel_configconfig_infos               r"   r;   z'RosbagsUploadService._create_csv_config  s     .0#H- 
	@JAw))I'))#	N 2@K)A-.
	@ %/%%?? (
 &.K
#$*K!%%r$   )FNNNT)NT)NN)__name__
__module____qualname____doc__r   __annotations__r   r#   r   r4   r   r   r   boolr   r   r   r   r=   r
   r   r8   r   r	   r[   r   r;    r$   r"   r   r   *   s    *)?. ? $"& $26"@^CI@^ uS$Y'(@^ 	@^
 @^ @^ 3-@^ @^ 4X./@^ @^ 
@^R 37"pST	"pS pS uS$Y'(	pS
 pS pS 4X./pS pS 
j	pSd% %d5dCS>T %Y\]`Ya %> #' $'&z"'& '& 3-	'&
 '& 
'&r$   r   )/r   rc   r9   r   pathlibr   typingr   r   r   r   r	   r
   r   alive_progressr   rosbags.interfaces.typingr   rosbags.rosbag2.readerr   rosbags.typesysr   r   r   rosbags.typesys.storer   ImportErrorrB   RuntimeErrorsift_py.data_import._configr   r    sift_py.data_import._ros_channelr   sift_py.data_import.configr   sift_py.data_import.csvr   sift_py.data_import.statusr   sift_py.data_import.tempfiler   sift_py.data_import.time_formatr   sift_py.restr   r   r   r$   r"   <module>r      s   
     E E E #	3-II/ ? 7 0 4 8 ; : '@& @&!  
	a s   B	 	B	BB