
    ZTh2                         d dl Z d dlZd dlZd dlmZ d dlmZmZmZm	Z	m
Z
mZmZmZ d dlmZm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 d dlm Z  d dl!m"Z"m#Z#  G d de#      Z$ G d d      Z%y)    N)Path)AnyCallableDictListOptionalTupleUnioncast)urljoinurlparse)	alive_bar)MetadataValue)metadata_pb_to_dict_api)	CsvConfig)DataImportService)TimeFormatType)ChannelDataType)SiftRestConfig_RestServicec                       e Zd ZU dZdZdZeed<   eed<   eed<   eed<   def fd	Z		 d#d
e
eef   dededefdZdededefdZddej$                  dddddfded
e
eef   dedededee   dee   dee   dee   dee   defdZd
e
eef   dee   fdZed
edeeee   ee   f   fd       Zd$ded eee      defd!Zded ee   fd"Z xZS )%CsvUploadServicez/api/v1/data-imports:uploadz/api/v1/data-imports:urlz/api/v2/runs
_rest_conf_upload_uri_url_uri_apikey	rest_confc                     t         |   |       t        | j                  | j                        | _        t        | j                  | j                        | _        y )N)r   )super__init__r   	_base_uriUPLOAD_PATHr   URL_PATHr   )selfr   	__class__s     \/home/www/backend.miabetepe.com/venv/lib/python3.12/site-packages/sift_py/data_import/csv.pyr    zCsvUploadService.__init__   sB    9-"4>>43C3CD>    path
csv_configshow_progressreturnc           	      :   | j                  |      }| j                  j                  | j                  ddit	        j
                  d|j                         i            }|j                  dk7  r%t        d|j                   d|j                         	 |j	                         }	 |d	   }|d
   }t        ||       5 }
d|i}| j                  j                  |||
      }|j                  dk7  r%t        d|j                   d|j                         t        | j                  |      cddd       S # t        j                  j                  t        f$ r t        d|j                         w xY w# t        $ r}	t        d|	       d}	~	ww xY w# 1 sw Y   yxY w)z
        Uploads the CSV file pointed to by `path` using a custom CSV config.

        Args:
            path: The path to the CSV file.
            csv_config: The CSV config.
            show_progress: Whether to show the status bar or not.
        Content-Encodingzapplication/octet-streamr)   urlheadersdata   z3Config file upload request failed with status code . Invalid response: 	uploadUrldataImportId Response missing required keys: N)disablez1Data file upload request failed with status code )_validate_file_type_sessionpostr   jsondumpsto_dictstatus_code	ExceptiontextdecoderJSONDecodeErrorKeyError_ProgressFiler   r   )r$   r(   r)   r*   content_encodingresponseupload_info
upload_urldata_import_idefr0   s               r&   uploadzCsvUploadService.upload#   s     33D9==%%  "$> \:+=+=+?@A & 
 3&EhFZFZE[[]^f^k^k]lm 	B"--/K	D)+6J"-n"=N 4]):; 	Fq"$4G }})) * H ##s*GH\H\G]]_`h`m`m_no  %T__nE!	F 	F ,,h7 	B0@AA	B  	D>qcBCC	D	F 	Fs1   D3 %
E2 =A,F3<E/2	F;F		FFr/   c                 n   t        |      }|j                  dvrt        d|j                   d      | j                  j	                  | j
                  t        j                  ||j                         d            }|j                  dk7  r%t        d|j                   d|j                         	 |j                         }	 |d   }t        | j                  |      S # t        j                  j                  t        f$ r}t        d	|       d
}~ww xY w# t        $ r}t        d|       d
}~ww xY w)zU
        Uploads the CSV file pointed to by `url` using a custom CSV config.
        )s3httphttpszInvalid URL scheme: 'z*'. Only S3 and HTTP(S) URLs are supported.)r/   r)   )r/   r1   r2   z+URL upload request failed with status code r3   r4   Nr6   r7   )r   schemer@   r:   r;   r   r<   r=   r>   r?   rA   rB   rC   rD   r   r   )r$   r/   r)   
parsed_urlrG   rH   rK   rJ   s           r&   upload_from_urlz CsvUploadService.upload_from_url]   sK    c]
$;;'
(9(9'::de  ==%%  #&0&8&8&: & 

 3&=h>R>R=SSUV^VcVcUde 	6"--/K	D"-n"=N !.AA ,,h7 	60455	6
  	D>qcBCC	Ds0   3C D #DDD	D4!D//D4      N
asset_namefirst_data_rowtime_columntime_formatrun_namerun_id	units_rowdescriptions_rowrelative_start_timec           
         | j                  |       g }||dz  }|j                  |       |	|	dz  }	|j                  |	       i }t        j                  ||      }g }|Zt        j                  ||      }t	        t        t        t           |j                  |dz
     j                  t                          }g }|	Zt        j                  ||	      }t	        t        t        t           |j                  |	dz
     j                  t                          }t        |j                        D ]  \  }}|dz   |k(  rt        ||j                  |      j                        }|dk(  rd}n@|dk(  r;t        j                  j                  j                  ||j                  |      d      }t!        j"                  |      }|t%        d	|dz    d
| d| d      ||d||dz   <   |r||   dk7  r||   nd||dz      d<   |s||   dk7  r||   nd||dz      d<    ||||d|d}|||d<   |||d<   |
|
|d   d<   t'        |      }| j)                  ||      S )a]  
        Uploads the CSV file pointed to by `path` to the specified asset. This function will
        infer the data types and assume certain things about how the data is formatted. See the options
        below for what parameters can be overridden. Use `upload` if you need to specify a custom CSV config.

        Override `first_data_row` to specify which is the first row with data. Default is 2.
        Override `time_column` to specify which column contains timestamp information. Default is 1.
        Override `time_format` to specify the time data format. Default is `TimeFormatType.ABSOLUTE_DATETIME`.
        Override `run_name` to specify the name of the run to create for this data. Default is None.
        Override `run_id` to specify the id of the run to add this data to. Default is None.
        Override `units_row` to specify which row contains unit information. Default is None.
        Override `descriptions_row` to specify which row contains channel description information. Default is None.
        Override `relative_start_time` if a relative time format is used. Default is None.
        rV   )skiprows)nrowsfloat64doubleobjectF)skipnaz%Unable to upload data type in column  z: Type: .)name	data_typenan unitsdescription)formatcolumn_number)rW   rX   rY   data_columnsr[   r\   rY   r_   )r9   appendpdread_csvlistr   r   strilocastype	enumeratecolumnsdtypeapitypesinfer_dtyper   from_strr@   r   rM   )r$   rW   r(   rX   rY   rZ   r[   r\   r]   r^   r_   	skip_rowsdata_configdfrm   df_unitsdescriptionsdf_descriptionsiheader	raw_dtyperj   config_infor)   s                           r&   simple_uploadzCsvUploadService.simple_upload   s   6 	  &  "	 NIY''!-.[[	2 {{4y9Hd3iy1})E)L)LS)QRSE"$' kk$6FGOT#Y 4 45E5I J Q QRU VWL #2::. 	IAv1u#Brzz!}-334II%$	 h&FFLL44R

15Fu4U	'00;I ;AE7!F88T]S^^_`  +1y!IKA:?(e:KeAhQSAE"7+'3A%'?LOR AE"=1/	8 %,%!, ('
 &.K
#$*K!*@SK&'<={+
{{4,,r'   c           	      4   t        |t              rt        |      n|}|j                         st	        d| d      | j
                  j                  |      \  }}}|st	        d| d      g d}||vr#t	        | d| ddj                  |       d	      |S )
NzProvided path, 'z$', does not point to a regular file.zThe MIME-type of 'z' could not be computed.)z
test/plainztext/csvzapplication/vnd.ms-excelz is not a valid file type (z). Must be z, rh   )
isinstancerv   r   is_filer@   r%    _mime_and_content_type_from_pathjoin)r$   r(   
posix_path_mimetyperF   valid_typess          r&   r9   z$CsvUploadService._validate_file_type   s    #-dC#8T$Zd
!!#.tf4XYZZ(,(W(WXb(c%8%0<TUVVL;&&3H:[S^I_H``ab   r'   c                 T    | j                   }t        j                  |       \  }}|||fS N)ri   	mimetypes
guess_type)r(   	file_namemimeencodings       r&   r   z1CsvUploadService._mime_and_content_type_from_path  s,    II	"--d3h$((r'   metadatac                 ,   t        | j                  | j                        }|dd}|rt        |      |d<   | j                  j                  |ddit        j                  |            }|j                  dk7  r%t        d|j                   d	|j                         	 |j                         }d|vrt        d      d|d   vrt        d      |d   d   S # t        j                  j                  t        f$ r t        d
|j                         w xY w)zCreate a new run using the REST service, and return a run_id.

        Args:
            run_name: The name of the Run.
            metadata: Optional metadata fields to add to the run.

        Returns:
            The run id.
        rl   )ri   rn   r   r-   application/jsonr.   r2   z%Run creation failed with status code r3   r4   runzResponse missing key: runrunIdzResponse missing key: runId)r   r!   RUN_PATHr   r:   r;   r<   r=   r?   r@   rA   rB   rC   rD   )r$   r[   r   run_urireqrG   run_infos          r&   _create_runzCsvUploadService._create_run  s0    $..$--8 

 5h?C
O==%%"$6 C & 
 3&78L8L7MRPXP]P]_ 	B}}H  788(5/)9::w'' ,,h7 	B0@AA	Bs   C <Dc                 4   t        | j                  | j                        }|t        |      ddd}| j                  j                  |ddit        j                  |            }|j                  dk7  r%t        d|j                   d	|j                         y
)z
        Updates metadata for the specified Run.

        Args:
            run_id: The ID of the run to update.
            metadata: Metadata fields to update.
        )r   r   r   )r   
updateMaskzContent-Typer   r.   r2   z,Run metadata update failed with status code r3   N)r   r!   r   r   r:   patchr<   r=   r?   r@   rA   )r$   r\   r   r   r   rG   s         r&   _add_metadata_to_runz%CsvUploadService._add_metadata_to_run4  s     $..$--8  3H= %
 ==&& 2 C ' 
 3&>x?S?S>TTVW_WdWdVef  'r'   )Tr   )__name__
__module____qualname__r"   r#   r   r   __annotations__rv   r    r
   r   r   boolr   rM   rT   r   ABSOLUTE_DATETIMEintr   r   r9   staticmethodr	   r   r   r   r   r   __classcell__)r%   s   @r&   r   r      s   /K)HHML?. ? #	8FCI8F 8F 	8F
 
8Ft)B)B )B 
	)B^  &4&F&F"& $#'*.-1e-e- CIe- 	e-
 e- $e- 3-e- e- C=e- #3-e- &c]e- 
e-N c4i(8  Xc]  & )t )c8C=RZ[^R_>_8` ) )
*(C *(8D<O3P *(\_ *(X3 $}:M r'   r   c                   F    e Zd ZU dZeed<   d	deeef   fdZ	d Z
d Zd Zy)
rE   z:Displays the status with alive_bar while reading the file._bar_contextr(   c                    || _         t        j                   j                  | j                         | _        | j                  dk(  rt	        | d      t        | j                   d      | _        t        | j                  d|d      | _        y )Nr   z is 0 bytesrb)modez bytesSI)unitr8   scale)	r(   osgetsize	file_sizer@   open_filer   _bar)r$   r(   r8   s      r&   r    z_ProgressFile.__init__Z  sh    	3>>QtfK011$))$/
dnn8WTXY	r'   c                 r     | j                   j                  |i |}| j                  t        |             |S r   )r   readr   len)r$   argskwargschunks       r&   r   z_ProgressFile.readd  s2    

00#e*%r'   c                 D    | j                   j                         | _        | S r   )r   	__enter__r   )r$   s    r&   r   z_ProgressFile.__enter__i  s     II//1r'   c                 >    | j                   j                  d d d        y r   )r   __exit__)r$   r   r   s      r&   r   z_ProgressFile.__exit__m  s    		4t,r'   N)F)r   r   r   __doc__r   r   r
   rv   r   r    r   r   r    r'   r&   rE   rE   S  s3    D ZU39- Z
r'   rE   )&r<   r   r   pathlibr   typingr   r   r   r   r   r	   r
   r   urllib.parser   r   pandasrs   alive_progressr   sift.metadata.v1.metadata_pb2r   sift_py._internal.metadatar   sift_py.data_import.configr   sift_py.data_import.statusr   sift_py.data_import.time_formatr   sift_py.ingestion.channelr   sift_py.restr   r   r   rE   r   r'   r&   <module>r      sQ      	  J J J *  $ 7 > 0 8 : 5 5|| |~	 r'   