U
    &c#                  	   @   s6  d dl Z d dlmZmZ d dlmZmZmZ d dlm	Z	 d dl
mZ d dlmZmZ zLd dlmZ d dlmZmZmZ d d	lmZ d d
lmZ d dlmZ dZW n( eefk
r   eZdd ZdZY nX e dZ edddZ!G dd deZ"G dd deZ#G dd deZ$G dd deZ%G dd deZ&dS )    N)ArgumentParser	Namespace)AnyListOptional)Pipeline)BaseTransformersCLICommand)SUPPORTED_TASKSpipeline)run)FastAPIHTTPExceptionBody)APIRoute)	BaseModel)JSONResponseTc                  O   s   d S )N )xyr   r   A/tmp/pip-unpacked-wheel-ymerj3tt/transformers/commands/serving.pyr      s    r   Fztransformers-cli/serving)argsc                 C   s:   t | j| jr| jnd| j| j| jd}t|| j| j| j	S )z}
    Factory function used to instantiate serving server from provided command line arguments.
    :return: ServeCommand
    N)taskmodelconfig	tokenizerdevice)
r
   r   r   r   r   r   ServeCommandhostportworkers)r   Znlpr   r   r   serve_command_factory   s    r    c                   @   s   e Zd ZU dZeed< dS )ServeModelInfoResultz"
    Expose model information
    infosN)__name__
__module____qualname____doc__dict__annotations__r   r   r   r   r!   -   s   
r!   c                   @   s.   e Zd ZU dZee ed< eee  ed< dS )ServeTokenizeResultz
    Tokenize result model
    tokens
tokens_idsN)	r#   r$   r%   r&   r   strr(   r   intr   r   r   r   r)   5   s   
r)   c                   @   s   e Zd ZU dZeed< dS )ServeDeTokenizeResultz!
    DeTokenize result model
    textN)r#   r$   r%   r&   r,   r(   r   r   r   r   r.   >   s   
r.   c                   @   s   e Zd ZU dZeed< dS )ServeForwardResultz
    Forward result model
    outputN)r#   r$   r%   r&   r   r(   r   r   r   r   r0   F   s   
r0   c                   @   s   e Zd ZeedddZeeeedddZ	dd Z
d	d
 ZedddedddfeedddZedddedddedddfee eedddZedddfddZdS )r   )parserc                 C   s   | j ddd}|jdtt dd |jdtdd	d
 |jdtddd
 |jdtddd
 |jdtdd |jdtdd |jdtdd |jdtddd
 |jtd dS )z
        Register this command to argparse so it's available for the transformer-cli
        :param parser: Root parser to register command-specific arguments
        :return:
        ZservezFCLI tool to run inference requests through REST and GraphQL endpoints.)helpz--taskzThe task to run the pipeline on)typechoicesr3   z--host	localhostz$Interface the server will listen on.)r4   defaultr3   z--porti"  z Port the serving will listen to.z	--workers   zNumber of http workersz--modelz%Model's name or path to stored model.)r4   r3   z--configz,Model's config name or path to stored model.z--tokenizerzTokenizer name to use.z--devicezSIndicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1))funcN)
add_parseradd_argumentr,   r	   keysr-   set_defaultsr    )r2   Zserve_parserr   r   r   register_subcommandO   s.        z ServeCommand.register_subcommand)r
   r   r   r   c                 C   s   || _ || _|| _|| _ts&tdnptd|| t	t
d| jttdgdt
d| jttdgdt
d| jttdgdt
d	| jttdgdgd
d| _d S )NzUsing serve command requires FastAPI and unicorn. Please install transformers with [serving]: pip install "transformers[serving]".Or install FastAPI and unicorn separately.zServing model over {}:{}/GET)Zresponse_modelresponse_classmethodsz	/tokenizePOSTz/detokenizez/forwardiX  )Zroutestimeout)	_pipeliner   r   r   _serve_dependencies_installedRuntimeErrorloggerinfoformatr   r   
model_infor!   r   tokenizer)   
detokenizer.   forwardr0   _app)selfr
   r   r   r   r   r   r   __init__j   sR    zServeCommand.__init__c                 C   s   t | j| j| j| jd d S )N)r   r   r   )r   rP   r   r   r   rQ   r   r   r   r      s    zServeCommand.runc                 C   s   t t| jjjdS )N)r"   )r!   varsrF   r   r   rS   r   r   r   rL      s    zServeCommand.model_infoNT)embedF)
text_input
return_idsc              
   C   s|   z>| j j|}|r0| j j|}t||dW S t|dW S W n8 tk
rv } ztddt|ddW 5 d}~X Y nX dS )z
        Tokenize the provided input and eventually returns corresponding tokens id:
        - **text_input**: String to tokenize
        - **return_ids**: Boolean flags indicating if the tokens have to be converted to their integer mapping.
        )r*   r+   )r*      r   errorstatus_codeZdetailN)rF   r   rM   Zconvert_tokens_to_idsr)   	Exceptionr   r,   )rQ   rV   rW   Z
tokens_txtr+   er   r   r   rM      s    zServeCommand.tokenize)r+   skip_special_tokenscleanup_tokenization_spacesc              
   C   s^   z | j j|||}td|dW S  tk
rX } ztddt|ddW 5 d}~X Y nX dS )aB  
        Detokenize the provided tokens ids to readable text:
        - **tokens_ids**: List of tokens ids
        - **skip_special_tokens**: Flag indicating to not try to decode special tokens
        - **cleanup_tokenization_spaces**: Flag indicating to remove all leading/trailing spaces and intermediate ones.
        rY   )r   r/   rX   rZ   r\   N)rF   r   decoder.   r^   r   r,   )rQ   r+   r`   ra   Zdecoded_strr_   r   r   r   rN      s
    zServeCommand.detokenizec              
      sh   t |dkrtg g dS z| |}t|dW S  tk
rb } ztddt|iW 5 d}~X Y nX dS )zV
        **inputs**:
        **attention_mask**:
        **tokens_type_ids**:
        r   )r1   Z	attention)r1   rX   r[   N)lenr0   rF   r^   r   r,   )rQ   inputsr1   r_   r   r   r   rO      s    
zServeCommand.forward)r#   r$   r%   staticmethodr   r?   r   r,   r-   rR   r   rL   r   boolrM   r   rN   rO   r   r   r   r   r   N   s   2&


r   )'loggingargparser   r   typingr   r   r   Ztransformersr   Ztransformers.commandsr   Ztransformers.pipelinesr	   r
   Zuvicornr   Zfastapir   r   r   Zfastapi.routingr   Zpydanticr   Zstarlette.responsesr   rG   ImportErrorAttributeErrorobject	getLoggerrI   r    r!   r)   r.   r0   r   r   r   r   r   <module>   s.   

	