o
    ZhW                  	   @   s0  d dl mZmZ d dlmZmZmZ ddlmZm	Z	m
Z
 ddlmZ ddlmZ 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 dlmZ dZW n eefya   eZdd ZdZY nw edZ def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 )     )ArgumentParser	Namespace)AnyListOptional   )Pipelineget_supported_taskspipeline)logging   )BaseTransformersCLICommand)BodyFastAPIHTTPException)APIRoute)	BaseModel)JSONResponse)runTc                  O   s   d S )N )xyr   r   L/var/www/auris/lib/python3.10/site-packages/transformers/commands/serving.pyr   "   s   r   Fztransformers/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.

    Returns: 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                   @      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%   ;      
 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.   C   s   
 r.   c                   @   r$   )ServeDeTokenizeResultz!
    DeTokenize result model
    textN)r'   r(   r)   r*   r1   r,   r   r   r   r   r3   L   r-   r3   c                   @   r$   )ServeForwardResultz
    Forward result model
    outputN)r'   r(   r)   r*   r   r,   r   r   r   r   r5   T   r-   r5   c                   @   s   e Zd ZedefddZdedededefdd	Z	d
d Z
dd ZedddedddfdedefddZedddedddedddfdee dedef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

        Args:
            parser: Root parser to register command-specific arguments
        ZservezFCLI tool to run inference requests through REST and GraphQL endpoints.)helpz--taskzThe task to run the pipeline on)typechoicesr8   z--host	localhostz$Interface the server will listen on.)r9   defaultr8   z--porti"  z Port the serving will listen to.z	--workersr   zNumber of http workersz--modelz%Model's name or path to stored model.)r9   r8   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_argumentr1   r	   r2   set_defaultsr#   )r7   Zserve_parserr   r   r   register_subcommand]   s,   z ServeCommand.register_subcommandr
   r    r!   r"   c                 C   s   || _ || _|| _|| _tstdtd| 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 uvicorn. Please install transformers with [serving]: pip install "transformers[serving]". Or install FastAPI and uvicorn 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infor   r   
model_infor%   r   tokenizer.   
detokenizer3   forwardr5   _app)selfr
   r    r!   r"   r   r   r   __init__|   sR   zServeCommand.__init__c                 C   s   t | j| j| j| jd d S )N)r    r!   r"   )r   rS   r    r!   r"   rT   r   r   r   r      s   zServeCommand.runc                 C   s   t t| jjjdS )N)r&   )r%   varsrJ   r   r   rV   r   r   r   rO      s   zServeCommand.model_infoNT)ZembedF
text_input
return_idsc              
   C   sj   z| j j|}|r| j j|}t||dW S t|dW S  ty4 } ztddt|ddd}~ww )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/   r0   )r/      r   errorstatus_codedetailN)rJ   r   rP   Zconvert_tokens_to_idsr.   	Exceptionr   r1   )rT   rX   rY   Z
tokens_txtr0   er   r   r   rP      s   zServeCommand.tokenizer0   skip_special_tokenscleanup_tokenization_spacesc              
   C   sP   z| j j|||}td|dW S  ty' } ztddt|ddd}~ww )a:  
        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.
        r[   )r   r4   rZ   r\   r^   N)rJ   r   decoder3   ra   r   r1   )rT   r0   rc   rd   Zdecoded_strrb   r   r   r   rQ      s   zServeCommand.detokenizec              
      s\   t |dkrtg g dS z| |}t|dW S  ty- } z	tddt|id}~ww )zF
        **inputs**: **attention_mask**: **tokens_type_ids**:
        r   )r6   Z	attention)r6   rZ   r]   N)lenr5   rJ   ra   r   r1   )rT   Zinputsr6   rb   r   r   r   rR      s   
zServeCommand.forward)r'   r(   r)   staticmethodr   rB   r   r1   r2   rU   r   rO   r   boolrP   r   rQ   rR   r   r   r   r   r   \   s$    1(



r   N)'argparser   r   typingr   r   r   Z	pipelinesr   r	   r
   utilsr   r[   r   Zfastapir   r   r   Zfastapi.routingr   Zpydanticr   Zstarlette.responsesr   Zuvicornr   rK   ImportErrorAttributeErrorobjectZ
get_loggerrM   r#   r%   r.   r3   r5   r   r   r   r   r   <module>   s0   
		