
    lc                        d Z ddlZddlZddlZddlZddlZ	 ddlZddlZddl	Zddl
Zn# e$ r dZY nw xY wddlZddlZddlZddlmZ  ej        e          ZdZ	 dZ	 dZdZd	Zd
ZdZdZdZdZ G d d          Z d Z!d Z"d Z#deedddddfdZ$d Z%d Z& G d de'          Z(d Z) G d dej*                  Z+ G d dej*                  Z, G d d ej*                  Z-eedfd!Z.d" Z/	 	 	 	 	 d+d&Z0d#d' fd(Z1d,d)Z2d* Z3dS )-zDImplements file-like objects for reading and writing from/to AWS S3.    NT)	constantsi   i  P )s3s3ns3us3ai  zs3.amazonaws.comi   )zs3://my_bucket/my_keyz&s3://my_key:my_secret@my_bucket/my_keyz8s3://my_key:my_secret@my_server:my_port@my_bucket/my_key   
   InvalidRangec                       e Zd ZdZd Zd ZdS )_ClientWrapperax  Wraps a client to inject the appropriate keyword args into each method call.

    The keyword args are a dictionary keyed by the fully qualified method name.
    For example, S3.Client.create_multipart_upload.

    See https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#client

    This wrapper behaves identically to the client otherwise.
    c                 "    || _         || _        d S N)clientkwargs)selfr   r   s      -lib/python3.11/site-packages/smart_open/s3.py__init__z_ClientWrapper.__init__B   s        c                     t          | j        |          }| j                            d|z  i           }t	          j        |fi |S )NzS3.Client.%s)getattrr   r   get	functoolspartial)r   method_namemethodr   s       r   __getattr__z_ClientWrapper.__getattr__F   sF    k22+!=rBB 226222r   N)__name__
__module____qualname____doc__r   r    r   r   r   r   8   s<           3 3 3 3 3r   r   c           
         t           j                            |           }|j        t          v sJ t
          }t          }d}d\  }}|j        |j        z   }d|v rNd|	                    d          d         v r1|	                    dd          \  }}|	                    d          \  }}|	                    dd          \  }	}
d|	v rGd|	v rCd}|		                    d          \  }}|	                    dd          \  }}t          |          }n!d|	v rd}|		                    d          \  }}n|	}t          |j        ||
|||||	          S )
NFNN@:r      /T)scheme	bucket_idkey_idporthostordinary_calling_format	access_idaccess_secret)
smart_openutilssafe_urlsplitr(   SCHEMESDEFAULT_PORTDEFAULT_HOSTnetlocpathsplitintdict)uri_as_string	split_urir+   r,   r-   r.   r/   uriauthheadr*   	host_portr)   s                r   	parse_urirA   L   sw     ..}==Iw&&&&DD#  *I} 
Y^
+C
cz 3cSYYs^^A.. 3IIc1%%	c#'::c?? 	=99S!$$LD&
d{ 	sd{ 	"&#zz#	9__S!,,
d4yy	 "&**S//ii	 7#	 	 	 	r   c                 Z   t                    fd}                    d          }|B| d         s| d         r2t                              d           |                     dd           n@| d         r8| d         r0 || d         | d                    |                     dd           |B| d	         t
          k    r1t                              d
           |                     d           n6| d	         t
          k    r% |d| z             |                     d           | fS )a`  Consolidates the parsed Uri with the additional parameters.

    This is necessary because the user can pass some of the parameters can in
    two different ways:

    1) Via the URI itself
    2) Via the transport parameters

    These are not mutually exclusive, but we have to pick one over the other
    in a sensible way in order to proceed.

    c                      	 d         }n# t           $ r
 i x}d<   Y nw xY w	 |d         }n# t           $ r
 i x}|d<   Y nw xY w |j        di |  d S )Nclient_kwargs	S3.Clientr!   )KeyErrorupdate)r   rD   init_kwargstransport_paramss      r   injectz#_consolidate_params.<locals>.inject   s    	C,_=MM 	C 	C 	C@BBM,_===	C	:'4KK 	: 	: 	:799K-444	: 	$$V$$$$$s      - A Ar   Nr.   r/   zignoring credentials parsed from URL because they conflict with transport_params["client"]. Set transport_params["client"] to None to suppress this warning.)r.   r/   )aws_access_key_idaws_secret_access_keyr,   zignoring endpoint_url parsed from URL because they conflict with transport_params["client"]. Set transport_params["client"] to None to suppress this warning.)r,   zhttps://%(host)s:%(port)d)endpoint_url)r:   r   loggerwarningrG   r5   )r=   rI   rJ   r   s    `  r   _consolidate_paramsrP      s    ,--% % % % % !!(++F 7s;/ 733G 7(	
 	
 	

 	

T
6666
k
 7s?3 7!+."%o"6	
 	
 	
 	
 	

T
666 	c&k\9 	(	
 	
 	

 	


	V	$ 7#=>>>>


   r   c                 6   d}fd|D             }|r%d}d|d|d}t          j        |t                     t          |           }t	          |          \  }t
          j                            t                    }t          |d         |d         |fi |S )	N)multipart_upload_kwargsobject_kwargsresourceresource_kwargssessionsinglepart_upload_kwargsc                     g | ]}|v |	S r!   r!   ).0krI   s     r   
<listcomp>zopen_uri.<locals>.<listcomp>   s$    ???a.>)>????r   z^https://github.com/RaRe-Technologies/smart_open/blob/develop/MIGRATING_FROM_OLDER_VERSIONS.rstz8ignoring the following deprecated transport parameters: z. See <z> for detailsr)   r*   )	warningswarnUserWarningrA   rP   r0   r1   check_kwargsopen)	r=   moderI   
deprecateddetecteddoc_urlmessage
parsed_urir   s	     `      r   open_urirg      s    J @???:???H ,0 	 '/hh9 	 	g{+++3J#6zCS#T#T J **41ABBF
;'H)=tNNvNNNr   Fc           	         t                               dt                                 |t          j        vrt          d|dt          j                  |t          j        k    r|t          d          |t          j        k    rt          | ||||||	          }nJ|t          j        k    r-|rt          | ||||	|
          }n"t          | |||	|
          }nJ d
|z              ||_        |S )a'  Open an S3 object for reading or writing.

    Parameters
    ----------
    bucket_id: str
        The name of the bucket this object resides in.
    key_id: str
        The name of the key within the bucket.
    mode: str
        The mode for opening the object.  Must be either "rb" or "wb".
    buffer_size: int, optional
        The buffer size to use when performing I/O.
    min_part_size: int, optional
        The minimum part size for multipart uploads.  For writing only.
    multipart_upload: bool, optional
        Default: `True`
        If set to `True`, will use multipart upload for writing to S3. If set
        to `False`, S3 upload will use the S3 Single-Part Upload API, which
        is more ideal for small file sizes.
        For writing only.
    version_id: str, optional
        Version of the object, used when reading object.
        If None, will fetch the most recent version.
    defer_seek: boolean, optional
        Default: `False`
        If set to `True` on a file opened for reading, GetObject will not be
        called until the first seek() or read().
        Avoids redundant API queries when seeking before reading.
    client: object, optional
        The S3 client to use when working with boto3.
        If you don't specify this, then smart_open will create a new client for you.
    client_kwargs: dict, optional
        Additional parameters to pass to the relevant functions of the client.
        The keys are fully qualified method names, e.g. `S3.Client.create_multipart_upload`.
        The values are kwargs to pass to that method each time it is called.
    writebuffer: IO[bytes], optional
        By default, this module will buffer data in memory using io.BytesIO
        when writing. Pass another binary IO instance here to use it instead.
        For example, you may pass a file object to buffer to local disk instead
        of in RAM. Use this to keep RAM usage low at the expense of additional
        disk IO. If you pass in an open file, then you are responsible for
        cleaning it up after writing completes.
    z%rz
bad mode: z expected one of Nz$version_id must be None when writing)
version_idbuffer_size
defer_seekr   rD   )min_part_sizer   rD   writebuffer)r   rD   rm   Fzunexpected mode: %r)rN   debuglocalsr   BINARY_MODESNotImplementedErrorWRITE_BINARY
ValueErrorREAD_BINARYReaderMultipartWriterSinglepartWritername)r)   r*   ra   ri   rj   rl   multipart_uploadrk   r   rD   rm   fileobjs               r   r`   r`      s<   p LLvxx   9)) f!!tttYMcMc"deee	&& AZ A?@@@y$$ 3!#!'
 
 
 
'	' 3 	%++'  GG '+'  GG 	3+d2222GLNr   c                     	 |r|                      ||||          S |                      |||          S # t          j        j        $ r*}t	          d|d|d|d|          }||_        ||d }~ww xY w)N)BucketKey	VersionIdRange)r|   r}   r   zunable to access bucket: z key: z
 version: z error: )
get_objectbotocorer   ClientErrorIOErrorbackend_error)r   bucketkeyversionrange_stringerrorwrapped_errors          r   _getr   E  s    ' 	Q$$FwVb$ccc$$F<$PPP?& ' ' 'WWWee
 

 ',#&'s   5 5 A3	%A..A3c                 X    	 | j         j        d         S # t          t          f$ r Y dS w xY w)zDGiven an IOError from _get, return the 'Error' dictionary from boto.ErrorN)r   responseAttributeErrorrF   )ioes    r   _unwrap_ioerrorr   U  s?     )'22H%   tts    ))c                   F    e Zd ZdZ	 d	dZej        fdZd
dZddZ	d Z
dS )_SeekableRawReaderzHRead an S3 object.

    This class is internal to the S3 submodule.
    Nc                 h    || _         || _        || _        || _        d | _        d| _        d | _        d S )Nr   )_client_bucket_key_version_id_content_length	_position_body)r   r   r   r   ri   s        r   r   z_SeekableRawReader.__init__c  s;     	%#


r   c                 4   |t           j        vrt          dt           j        z            | j        | j                                         d| _        d}d}|t           j        k    rt          d|          }n:|t           j        k    rt          d|| j        z             }nt          d|           }| j	        d}n||| j	        k    rd}n|dk    rd}nd}|r%t          j                    | _        | j	        | _        n|                     ||           | j        S )zSeek to the specified position.

        :param int offset: The offset in bytes.
        :param int whence: Where the offset is from.

        :returns: the position after seeking.
        :rtype: int
        z"invalid whence, expected one of %rNr   FT)r   WHENCE_CHOICESrs   r   closeWHENCE_STARTmaxWHENCE_CURRENTr   r   ioBytesIO
_open_body)r   offsetwhencestartstopreached_eofs         r   seekz_SeekableRawReader.seeks  s:    11 	^AID\\]]] : 	J
Y++ 	#6NNEEy// 	#6DN233EEq6'??D  	 KK 	 5D,@#@ 	 KKQY 	 KKK 	)DJ!1DNNOOE4(((~r   c                    |	|| j         }t          j                            ||          }	 t	          | j        | j        | j        | j        |          }t          
                    d| |d         d                    t          j                            |d                   \  }}}}|| _        || _         |d         | _        dS # t          $ rt}t          |          }||                    d          t"          k    r t%          |d                   x| _         | _        t'          j                    | _        Y d}~dS d}~ww xY w)	a  Open a connection to download the specified range of bytes. Store
        the open file handle in self._body.

        If no range is specified, start defaults to self._position.
        start and stop follow the semantics of the http range header,
        so a stop without a start will read bytes beginning at stop.

        As a side effect, set self._content_length. Set self._position
        to self._content_length if start is past end of file.
        Nz%s: RetryAttempts: %dResponseMetadataRetryAttemptsContentRangeBodyCodeActualObjectSize)r   r0   r1   make_range_stringr   r   r   r   r   rN   rn   parse_content_ranger   r   r   r   r   _OUT_OF_RANGEr9   r   r   )	r   r   r   r   r   unitslengthr   error_responses	            r   r   z_SeekableRawReader._open_body  sY     	#T 	#NE!'99%FF	*	  H* LL'+,_=  
 *4)9)M)MhWeNf)g)g&E5$#)D "DN!&)DJJJ-  	& 	& 	&,S11N ););F)C)C})T 47GY8Z4[4[[DNT1DJJJJJJJ	&s   'C 
EA)D<<Ec           	      h   | j         |                                  | j        | j        k    rdS t	          g dd          D ]\  }}	 |dk    r| j                                         }n| j                             |          }| xj        t          |          z  c_        |c S # t          t          j	        j
        t          j	        j        f$ rP}t                              d| |||           t          j        |           |                                  Y d}~d}~ww xY wt#          d| ||fz            )z9Read from the continuous connection with the remote peer.Nr   )r&               r&   r   z?%s: caught %r while reading %d bytes, sleeping %ds before retryz-%s: failed to read %d bytes after %d attempts)r   r   r   r   	enumeratereadlenConnectionResetErrorr   
exceptionsBotoCoreErrorurllib3	HTTPErrorrN   rO   timesleepr   )r   sizeattemptsecondsbinaryerrs         r   r   z_SeekableRawReader.read  s`   : 	OO>T11 	3 !**:*:*:A > > 	 	GW2: 3!Z__..FF!Z__T22F  #f++- %#1", " " "
 U   
7###!!!!!!!!"$ EtU\H]]^^^s   :B!!+DADDc                 (    d| j         d| j        dS )Nzsmart_open.s3._SeekableReader(, )r   r   r   s    r   __str__z_SeekableRawReader.__str__       :>,,,			RRr   r   r#   r   )r   r   r   r    r   r   r   r   r   r   r   r!   r   r   r   r   ]  s               #,"8 0 0 0 0d.* .* .* .*`-_ -_ -_ -_^S S S S Sr   r   c                     |i }|'|                     di           }t          j        di |}|sJ t          ||          | _        || _        || _        dS )z~Created the required objects for accessing S3.  Ideally, they have
    been already created for us and we can just reuse them.NrE   r   )r   )r   boto3r   r   r   r   r   )rwr   rD   r   r   rH   s         r   _initialize_boto3r     so       3#''R8822k22MMM66BJBJBGGGr   c                       e Zd ZdZdeej        dddfdZd Zd Z	ddZ
dd	Zd
 ZddZd Zej        fdZd ZddZd Zd Zd ZddZddZd Zd ZdS )ru   z]Reads bytes from S3.

    Implements the io.BufferedIOBase interface of the standard library.NFc	                 <   || _         || _        t          | ||||           t          | j        ||| j                   | _        d| _        t          j        	                    |          | _
        d| _        || _        d | _        |s|                     d           d S d S )Nr   F)r   _buffer_sizer   r   r   _raw_reader_current_posr0   
bytebuffer
ByteBuffer_buffer_eof_line_terminatorrawr   )	r   r   r   ri   rj   line_terminatorrk   r   rD   s	            r   r   zReader.__init__  s     &'$vsCCC-L	
 
 !,77DD	 /
  	IIaLLLLL	 	r   c                     dS )zFlush and close this stream.Nr!   r   s    r   r   zReader.closeD      r   c                     dS )z+Return True if the stream can be read from.Tr!   r   s    r   readablezReader.readableH      tr   r   c                    |dk    rdS |dk     rA|                                  | j                                        z   }| j        j        | _        |S t          | j                  |k    r|                      |          S | j        r|                                  S |                     |           |                      |          S )z6Read up to size bytes from the object and return them.r   r   )	_read_from_bufferr   r   r   r   r   r   r   _fill_buffer)r   r   outs      r   r   zReader.readL  s    19 	3AX 	((**T-=-B-B-D-DDC $ 0 @DJ
 t|$ 	0))$///
 9 	,))+++$%%d+++r   c                 .    |                      |          S )zThis is the same as read().)r   )r   r   r   s     r   read1zReader.read1e  s    yydy###r   c                     |                      t          |                    }|sdS ||dt          |          <   t          |          S )zLRead up to len(b) bytes into b, and return the number of bytes
        read.r   N)r   r   )r   bdatas      r   readintozReader.readintoi  sG     yyQ   	1*3t99*4yyr   c                    |dk    rt          d          t          j                    }| j        rt	          | j                  dk    s| j                            | j                  }|                    |           | xj	        t	          |          z  c_	        |
                    | j                  rn3|                                  | j        t	          | j                  dk    |                                S )zCRead up to and including the next newline.  Returns the bytes read.r   z(limits other than -1 not implemented yetr   )rq   r   r   r   r   r   readliner   writer   endswithr   getvalue)r   limitline	line_parts       r   r   zReader.readliner  s    B; 	R%&PQQQ
 z||9 	$T\!2!2a!7 	$--d.CDDIJJy!!!Y/!!$"788 $!!### 9 	$T\!2!2a!7 	$ }}r   c                     dS )zyIf False, seek(), tell() and truncate() will raise IOError.

        We offer only seek support, and no truncate support.Tr!   r   s    r   seekablezReader.seekable  	     tr   c                    |t           j        k    rt           j        }|| j        z  }| j                            ||          | _        | j                                         | j        | j        j        k    | _	        | j        S )zSeek to the specified position.

        :param int offset: The offset in bytes.
        :param int whence: Where the offset is from.

        Returns the position after seeking.)
r   r   r   r   r   r   r   emptyr   r   r   r   r   s      r   r   zReader.seek  sv     Y-- 	(+Fd''F ,11&&AA%)9)II	  r   c                     | j         S )z,Return the current position within the file.)r   r   s    r   tellzReader.tell        r   c                     t           j        zUnsupported.r   UnsupportedOperationr   s     r   truncatezReader.truncate      %%r   c                     t           j        r  r  r   s    r   detachzReader.detach  r  r   c                     dS )zDo nothing.Nr!   r   s    r   	terminatezReader.terminate  r   r   c                     |s
J d            |                     | j        | j                  }| j        |                    | j                  S |S zCreate an **independent** `boto3.s3.Object` instance that points to
        the same S3 object as this instance.
        Changes to the returned object will not affect the current instance.
        z*resource must be a boto3.resource instance)Objectr   r   r   Version)r   rT   objs      r   to_boto3zReader.to_boto3  sU    
 EEEEEEoodlDI66 	;;t/000Jr   c                     |dk    r|nt          | j                  }| j                            |          }| xj        t          |          z  c_        |S )z:Remove at most size bytes from our buffer and return them.r   )r   r   r   r   )r   r   parts      r   r   zReader._read_from_buffer  sR    qy7ttc$,&7&7|  &&SYY&r   c                 P   t          || j        j                  }t          | j                  |k     ro| j        sj| j                            | j                  }|dk    r"t                              d|            d| _        t          | j                  |k     r| j        fd S d S d S d S )Nr   z$%s: reached EOF while filling bufferT)	r   r   _chunk_sizer   r   fillr   rN   rn   )r   r   
bytes_reads      r   r   zReader._fill_buffer  s    4122$,$& 	!ty 	!**4+;<<JQ !CTJJJ 		 $,$& 	!ty 	! 	! 	! 	! 	! 	! 	! 	! 	!r   c                 (    d| j         d| j        dS )Nzsmart_open.s3.Reader(r   r   r   r   s    r   r   zReader.__str__  s     15tyyyIIr   c                 X    d| j         d| j        d| j        d| j        d| j        dS )Nzsmart_open.s3.Reader(bucket=, key=z, version_id=z, buffer_size=z, line_terminator=r   )r   r   r   r   r   r   s    r   __repr__zReader.__repr__  sF      LLLIII!!!
 	
r   r   r   )r   r   r   r    DEFAULT_BUFFER_SIZEr   BINARY_NEWLINEr   r   r   r   r   r   r   r   r   r   r  r
  r  r  r  r   r   r   r  r!   r   r   ru   ru     sy       K K '!0! ! ! !N    , , , ,2$ $ $ $     *   #,"8 ! ! ! !&! ! !& & & && & &  
 
 
   ! ! ! !J J J
 
 
 
 
r   ru   c                       e Zd ZdZedddfdZd Zd Zed             Z	d Z
d Zej        fd	Zdd
Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd ZdS )rv   zuWrites bytes to S3 using the multi part API.

    Implements the io.BufferedIOBase interface of the standard library.Nc                    |t           k     rt                              d           || _        t	          | ||||           	 t          j        | j        j        ||          }t          |          d         | _
        n3# t          j        j        $ r}t          d|d|d          |d }~ww xY w|t          j                    | _        n|| _        d| _        d| _        g | _        d | _        d S )Nz?S3 requires minimum part size >= 5MB; multipart upload may fail)r|   r}   UploadIdzthe bucket z- does not exist, or is forbidden for access (r   r   )MIN_MIN_PART_SIZErN   rO   _min_part_sizer   r   r   r   create_multipart_upload_retry_if_failed
_upload_idr   r   r   rs   r   r   _buf_total_bytes_total_parts_partsr   )	r   r   r   rl   r   rD   rm   r   r   s	            r   r   zMultipartWriter.__init__  s     ,, 	NN    +$vsCCC	'4  G
 /w77
CDOO* 	 	 	*FFEEE  		  	$
DII#DI
 s   ;A= =B-B((B-c                     d S r   r!   r   s    r   flushzMultipartWriter.flush      r   c                 ^   | j                                         r|                                  | j        rk| j        rdt          j        | j        j        | j	        | j
        | j        d| j        i          }t          |           t                              d|            n| j        r| j        s
J d            | j                            | j	        | j
        | j                   | j                            | j	        | j
        d           t                              d|            d | _        d S )	NParts)r|   r}   r$  MultipartUploadz%s: completed multipart uploadno multipart upload in progressr|   r}   r$  r   r|   r}   r   z-%s: wrote 0 bytes to imitate multipart upload)r*  r  _upload_next_partr+  r)  r   r   r   complete_multipart_uploadr   r   r-  r(  rN   rn   abort_multipart_upload
put_object)r   r   s     r   r   zMultipartWriter.close  s@   9>> 	%""$$$ 	P 	P'6|I!($+ 6  G W%%%LL94@@@@_ 	P ?EE$EEEEL//|I 0   
 L##|I $   
 LLH$OOOr   c                     | j         d u S r   )r)  r   s    r   closedzMultipartWriter.closed=  s    $&&r   c                     dS z+Return True if the stream supports writing.Tr!   r   s    r   writablezMultipartWriter.writableA  r   r   c                     dS zIf False, seek(), tell() and truncate() will raise IOError.

        We offer only tell support, and no seek or truncate support.Tr!   r   s    r   r   zMultipartWriter.seekableE  r   r   c                     t           j        r  r  r  s      r   r   zMultipartWriter.seekK  r  r   c                     t           j        r  r  r   s     r   r
  zMultipartWriter.truncateO  r  r   c                     | j         S z#Return the current stream position.r+  r   s    r   r  zMultipartWriter.tellS  r  r   c                 *    t          j        d          Nzdetach() not supportedr  r   s    r   r  zMultipartWriter.detachZ      %&>???r   c                     | j                             |          }| xj        |z  c_        | j                                         | j        k    r|                                  |S )aJ  Write the given buffer (bytes, bytearray, memoryview or any buffer
        interface implementation) to the S3 file.

        For more information about buffers, see https://docs.python.org/3/c-api/buffer.html

        There's buffering happening under the covers, so this may not actually
        do any HTTP transfer right away.)r*  r   r+  r  r&  r7  r   r   r   s      r   r   zMultipartWriter.write]  s^     ##V#9>>t22 	%""$$$r   c                     | j         s
J d            | j                            | j        | j        | j                    d| _         dS )z'Cancel the underlying multipart upload.r4  r5  N)r)  r   r9  r   r   r   s    r   r  zMultipartWriter.terminaten  sT    AA AAAA++<	_ 	, 	
 	
 	

 r   c                 Z    |s
J d            |                     | j        | j                  S r  )r  r   r   )r   rT   s     r   r  zMultipartWriter.to_boto3x  s1    
 EEEEEEt|TY777r   c           
      X   | j         dz   }t                              d| || j                                        | j        dz             | j                            d           t          t          j	        | j
        j        | j        | j        | j        || j                            }| j                            |d         |d           t                              d| |           | xj         dz  c_         | j                            d           | j                            d           d S )	Nr&   z3%s: uploading part_num: %i, %i bytes (total %.3fGB)g      Ar   )r|   r}   r$  
PartNumberr   ETag)rP  rO  z#%s: upload of part_num #%i finished)r,  rN   infor*  r  r+  r   r(  r   r   r   upload_partr   r   r)  r-  appendrn   r
  )r   part_numuploads      r   r7  z!MultipartWriter._upload_next_part  s"   $q(AINN+	
 	
 	
 		q "(|I#Y  	
 	
 	F6N(KKLLL:D(KKKQ	q	1r   c                     | S r   r!   r   s    r   	__enter__zMultipartWriter.__enter__      r   c                 ^    ||                                   d S |                                  d S r   r  r   r   exc_typeexc_valexc_tbs       r   __exit__zMultipartWriter.__exit__  1     	NNJJLLLLLr   c                 (    d| j         d| j        dS )Nzsmart_open.s3.MultipartWriter(r   r   r   r   s    r   r   zMultipartWriter.__str__  r   r   c                 8    d| j         d| j        d| j        dS )Nz%smart_open.s3.MultipartWriter(bucket=r  z, min_part_size=r   )r   r   r&  r   s    r   r  zMultipartWriter.__repr__  s,     LLLIII
 	
r   r   )r   r   r   r    DEFAULT_MIN_PART_SIZEr   r/  r   propertyr<  r?  r   r   r   r   r
  r  r  r   r  r  r7  rW  r_  r   r  r!   r   r   rv   rv     sh       K K ,* * * *X  " " "H ' ' X'     #,"8 & & & && & & &! ! !@ @ @  "  8 8 8" " "H    S S S
 
 
 
 
r   rv   c                       e Zd ZdZ	 	 	 ddZd Zd Zed             Zd Z	d Z
ej        fd	Zdd
Zd Zd Zd Zd Zd Zd Zd Zd ZdS )rw   a  Writes bytes to S3 using the single part API.

    Implements the io.BufferedIOBase interface of the standard library.

    This class buffers all of its input in memory until its `close` method is called. Only then will
    the data be written to S3 and the buffer is released.Nc                 $   t          | ||||           	 | j                            |           n/# t          j        j        $ r}t          d|z            |d }~ww xY w|t          j                    | _	        n|| _	        d| _
        d | _        d S )N)r|   8the bucket %r does not exist, or is forbidden for accessr   )r   r   head_bucketr   r   r   rs   r   r   r*  r+  r   )r   r   r   r   rD   rm   es          r   r   zSinglepartWriter.__init__  s     	$vsCCC	iL$$F$3333* 	i 	i 	iWZ``aaghh	i  	$
DII#DI
 s   1 AAAc                     d S r   r!   r   s    r   r/  zSinglepartWriter.flush  r0  r   c                 T   | j         d S | j                             d           	 | j                            | j        | j        | j                    n4# t          j        j        $ r}t          d| j        z            |d }~ww xY wt                              d|            d | _         d S )Nr   r6  rg  z%s: direct upload finished)r*  r   r   r:  r   r   r   r   r   rs   rN   rn   )r   ri  s     r   r   zSinglepartWriter.close  s    9 	F	q	bL##|IY $    
 * 	b 	b 	bJT\Y[ [`ab	b 	14888			s   ,A B&A>>Bc                     | j         d u S r   )r*  r   s    r   r<  zSinglepartWriter.closed  s    yD  r   c                     dS r>  r!   r   s    r   r?  zSinglepartWriter.writable  r   r   c                     dS rA  r!   r   s    r   r   zSinglepartWriter.seekable  r   r   c                     t           j        r  r  r  s      r   r   zSinglepartWriter.seek  r  r   c                     t           j        r  r  r   s     r   r
  zSinglepartWriter.truncate	  r  r   c                     | j         S rE  rF  r   s    r   r  zSinglepartWriter.tell  r  r   c                 *    t          j        d          rH  r  r   s    r   r  zSinglepartWriter.detach  rI  r   c                 Z    | j                             |          }| xj        |z  c_        |S )a(  Write the given buffer (bytes, bytearray, memoryview or any buffer
        interface implementation) into the buffer. Content of the buffer will be
        written to S3 on close as a single-part upload.

        For more information about buffers, see https://docs.python.org/3/c-api/buffer.html)r*  r   r+  rK  s      r   r   zSinglepartWriter.write  s0     ##V#r   c                     dS )z)Nothing to cancel in single-part uploads.Nr!   r   s    r   r  zSinglepartWriter.terminate"  s    r   c                     | S r   r!   r   s    r   rW  zSinglepartWriter.__enter__)  rX  r   c                 ^    ||                                   d S |                                  d S r   rZ  r[  s       r   r_  zSinglepartWriter.__exit__,  r`  r   c                 <    d| j         j        d| j         j        dS )Nzsmart_open.s3.SinglepartWriter(r   r   )_objectbucket_namer   r   s    r   r   zSinglepartWriter.__str__2  s'     ;?<;S;S;SUYUaUeUeUeffr   c                 (    d| j         d| j        dS )Nz&smart_open.s3.SinglepartWriter(bucket=r  r   r   r   s    r   r  zSinglepartWriter.__repr__5  s     FJlllTXT]T]T]^^r   )NNNr   )r   r   r   r    r   r/  r   rd  r<  r?  r   r   r   r   r
  r  r  r   r  rW  r_  r   r  r!   r   r   rw   rw     sG       = =    6    & ! ! X!     #,"8 & & & && & & &! ! !@ @ @	 	 	      g g g_ _ _ _ _r   rw   c                 B   |t           j        j        f}t          |          D ]P}	  |             c S # |$ r: t                              d||z
  dz
  z             t          j        |           Y Mw xY wt                              d           t          d|z            )NzwUnable to connect to the endpoint. Check your network connection. Sleeping and retrying %d more times before giving up.r&   z-Unable to connect to the endpoint. Giving up.z3Unable to connect to the endpoint after %d attempts)	r   r   EndpointConnectionErrorrangerN   criticalr   r   r   )r   attemptssleep_secondsr   r   s        r   r(  r(  9  s    
  E)AD
?? X X	&799 	& 	& 	&OO$'/''9A'=?  
 J}%%%%%	& 	GHHHKhVWWWs   	3<A21A2c                     dS NTr!   )r   s    r   _accept_allr  O  s    4r    r      c           
   +   d  K   |t           }	 | j        } n# t          $ r Y nw xY wd\  }}t          | f||d|}	t	          j        t          f| |d|}
t          j        	                    |          5 }|
                    |
|	          }t          |          D ]\\  }\  }}	 t                              d	||t          |          |d
z             ||fV  |t          |          z  }||dz   |k    r n]ddd           n# 1 swxY w Y   t                              d|dz   |fz             dS )aS  
    Iterate and download all S3 objects under `s3://bucket_name/prefix`.

    Parameters
    ----------
    bucket_name: str
        The name of the bucket.
    prefix: str, optional
        Limits the iteration to keys starting with the prefix.
    accept_key: callable, optional
        This is a function that accepts a key name (unicode string) and
        returns True/False, signalling whether the given key should be downloaded.
        The default behavior is to accept all keys.
    key_limit: int, optional
        If specified, the iterator will stop after yielding this many results.
    workers: int, optional
        The number of subprocesses to use.
    retries: int, optional
        The number of time to retry a failed download.
    session_kwargs: dict, optional
        Keyword arguments to pass when creating a new session.
        For a list of available names and values, see:
        https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html#boto3.session.Session


    Yields
    ------
    str
        The full key name (does not include the bucket name).
    bytes
        The full contents of the key.

    Notes
    -----
    The keys are processed in parallel, using `workers` processes (default: 16),
    to speed up downloads greatly. If multiprocessing is not available, thus
    _MULTIPROCESSING is False, this parameter will be ignored.

    Examples
    --------

      >>> # get all JSON files under "mybucket/foo/"
      >>> for key, content in iter_bucket(
      ...         bucket_name, prefix='foo/',
      ...         accept_key=lambda key: key.endswith('.json')):
      ...     print key, len(content)

      >>> # limit to 10k files, using 32 parallel workers (default is 16)
      >>> for key, content in iter_bucket(bucket_name, key_limit=10000, workers=32):
      ...     print key, len(content)
    N)r   r   )prefix
accept_key)ry  retries)	processesTi  r   z,yielding key #%i: %s, size %i (total %.1fMB)g      0Ar&   z processed %i keys, total size %i)r  rx   r   _list_bucketr   r   _download_keyr0   concurrencycreate_poolimap_unorderedr   rN   rQ  r   )ry  r  r  	key_limitworkersr  session_kwargs
total_sizekey_nokey_iteratordownload_keypoolresult_iteratorr   contents                  r   iter_bucketr  S  s     v  ! 
!&    J  	 L
 $  	 L 
		+	+g	+	>	> $--lLII&/&@&@ 	 	"FNS'BCWzK/G   w,#g,,&J !y)@                KK2fqj*5MMNNNNNs    
""4BDD
Dc                     dS r  r!   )rZ   s    r   <lambda>r    s    T r   c              +   j  K   t          j        j        di |}|                    d          }d }	 |rt	          | ||          }nt	          | |          } |j        di |}	 |d         }	|	D ]}
|
d         } ||          r|V  n# t          $ r Y nw xY w|                    dd           }|sd S )	Nr   T)r|   PrefixContinuationToken)r|   r  Contentsr}   NextContinuationTokenr!   )r   rV   Sessionr   r:   list_objects_v2rF   r   )ry  r  r  r  rV   r   ctokenr   r   r  cr   s               r   r  r    s     
 m#55n55G^^D!!FF  	=VvVVVFFV<<<F)6)33F33	z*G   h:c?? III  	 	 	D	 5t<< 	E's   %B
 

BBc                 @   |t          d          t          j        j        di |}|                    d          }|                    |          }t          |dz             D ]9}	 t          ||           }| |fc S # t          j	        j
        $ r
 ||k    r Y 6w xY wd S )Nzbucket_name may not be Noner   r&   r!   )rs   r   rV   r  rT   r|   r}  _download_fileobjr   r   r   )	key_namery  r  r  rV   r   r   xcontent_bytess	            r   r  r    s     86777
 m#55n55G			$		BYY{##F
 7Q; 
+ 
+		+-fh??M ]**** * 	 	 	G| D	
+ 
+s   'A==BBc                 |    t          j                    }|                     ||           |                                S r   )r   r   download_fileobjr   )r   r  bufs      r   r  r    s3    
 *,,C
Hc***<<>>r   )r  NNr   r  )Nr  )4r    r   r   loggingr   r\   r   botocore.clientr   botocore.exceptionsurllib3.exceptionsr   ImportErrorMISSING_DEPSsmart_open.bytebufferr0   smart_open.concurrencysmart_open.utilsr   	getLoggerr   rN   rc  r%  r3   r4   r5   r   URI_EXAMPLES_UPLOAD_ATTEMPTS_SLEEP_SECONDSr   r   rA   rP   rg   r`   r   r   objectr   r   BufferedIOBaseru   rv   rw   r(  r  r  r  r  r  r!   r   r   <module>r     sn   K J 				       LLL   LLL                        		8	$	$$  8!  /
%!     3 3 3 3 3 3 3 3(9 9 9x6! 6! 6!rO O OL #'_ _ _ _D' ' '   hS hS hS hS hS hS hS hSV   G
 G
 G
 G
 G
R G
 G
 G
TV
 V
 V
 V
 V
b' V
 V
 V
r{_ {_ {_ {_ {_r( {_ {_ {_@ "$	X X X X,   aO aO aO aOL !>   >+ + + +6    s   ) 33