
    g[                        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 	 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n# eef$ r
 eZd ZdZY nw xY w ej        d          Z defdZ! G d de          Z" G d de          Z# G d de          Z$ G d de          Z% G 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                      d S )N )xys     Y/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/commands/serving.pyr   r   "   s        Fztransformers-cli/servingargsc                     t          | j        | j        r| j        nd| j        | j        | j                  }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   nlps     r   serve_command_factoryr(   +   sX     Y J0djjD{.{  C TY	4<@@@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*   ;   s%           KKKKKr   r*   c                   L    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   strr1   r   intr   r   r   r3   r3   C   sC           Ic######r   r3   c                       e Zd ZU dZeed<   dS )ServeDeTokenizeResultz!
    DeTokenize result model
    textN)r,   r-   r.   r/   r6   r1   r   r   r   r9   r9   L   s%           IIIIIr   r9   c                       e Zd ZU dZeed<   dS )ServeForwardResultz
    Forward result model
    outputN)r,   r-   r.   r/   r   r1   r   r   r   r<   r<   T   s%           KKKKKr   r<   c                      e Zd Zedefd            ZdedededefdZ	d Z
d	 Z ed
d           edd          fdedefdZ ed
d           edd           edd          fdee         dedefdZ ed
d          fdZd
S )r#   parserc                 \   |                      dd          }|                    dt          t                      d           |                    dt          dd	
           |                    dt          dd
           |                    dt          dd
           |                    dt          d           |                    dt          d           |                    dt          d           |                    dt          dd
           |                    t                     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
        servezFCLI tool to run inference requests through REST and GraphQL endpoints.)helpz--taskzThe task to run the pipeline on)typechoicesrB   z--host	localhostz$Interface the server will listen on.)rC   defaultrB   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.)rC   rB   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_argumentr6   r
   r7   set_defaultsr(   )r?   serve_parsers     r   register_subcommandz ServeCommand.register_subcommand]   sN    ((b ) 
 
 	!!'))2	 	" 	
 	
 	
 	!!(kPv!www!!(dIk!lll!!+CIa!bbb!!)#<c!ddd!!*3=k!lll!!-c@X!YYY!!f	 	" 	
 	
 	
 	!!'<!=====r   r   r$   r%   r&   c                    || _         || _        || _        || _        t          st          d          t                              d| d|            t          t          d| j
        t          t          dg          t          d| j        t          t          dg          t          d	| j        t           t          dg          t          d
| j        t$          t          dg          g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)response_modelresponse_classmethodsz	/tokenizePOSTz/detokenizez/forwardiX  )routestimeout)	_pipeliner$   r%   r&   _serve_dependencies_installedRuntimeErrorloggerinfor   r   
model_infor*   r   tokenizer3   
detokenizer9   forwardr<   _app)selfr   r$   r%   r&   s        r   __init__zServeCommand.__init__|   s    !		, (	=   KK;d;;T;;<<<';'3!&   #':'3!'   %'<'3!'   "'9'3!'  -< ?     DIIIr   c                 T    t          | j        | j        | j        | j                   d S )N)r$   r%   r&   )r   ra   r$   r%   r&   rb   s    r   r   zServeCommand.run   s'    DIDIDIt|LLLLLLr   c                 Z    t          t          | j        j        j                            S )N)r+   )r*   varsrX   r   r    re   s    r   r]   zServeCommand.model_info   s#    #$t~/C/J*K*KLLLLr   NT)embedF
text_input
return_idsc                 ,   	 | j         j                            |          }|r0| j         j                            |          }t	          ||          S t	          |          S # t
          $ r&}t          ddt          |          d          d}~ww xY 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.
        )r4   r5   )r4      r   errorstatus_codedetailN)rX   r!   r^   convert_tokens_to_idsr3   	Exceptionr   r6   )rb   ri   rj   
tokens_txtr5   es         r   r^   zServeCommand.tokenize   s    
	X1:::FFJ >!^5KKJWW
**TTTT**==== 	X 	X 	XC"sSTvv8V8VWWWW	Xs   AA# A# #
B-!BBr5   skip_special_tokenscleanup_tokenization_spacesc                     	 | j         j                            |||          }t          d|          S # t          $ r&}t          ddt          |          d          d}~ww xY 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.
        rm   )r   r:   rl   rn   rp   N)rX   r!   decoder9   rt   r   r6   )rb   r5   rw   rx   decoded_strrv   s         r   r_   zServeCommand.detokenize   s~    	X.299*FY[vwwK(rDDDD 	X 	X 	XC"sSTvv8V8VWWWW	Xs   14 
A$!AA$c                    K   t          |          dk    rt          g g           S 	 |                     |          }t          |          S # t          $ r$}t	          ddt          |          i          d}~ww xY w)zF
        **inputs**: **attention_mask**: **tokens_type_ids**:
        r   )r=   	attention)r=   rl   ro   N)lenr<   rX   rt   r   r6   )rb   inputsr=   rv   s       r   r`   zServeCommand.forward   s       v;;!%R2>>>>	8^^F++F%V4444 	8 	8 	8gs1vv%6777	8s   $A 
A;A66A;)r,   r-   r.   staticmethodr   rM   r	   r6   r7   rc   r   r]   r   boolr^   r   r_   r`   r   r   r   r#   r#   \   s       >N > > > \></ / /C /# / / / /bM M MM M M *.d$)?)?)?TXTXY^fjTkTkTk X X3 XT X X X X( !%T 6 6 6$(Dd$;$;$;,0DT,B,B,B	X XIX "X &*	X X X X" $(4D#9#9#9 8 8 8 8 8 8r   r#   N)'argparser   r   typingr   r   r   	pipelinesr	   r
   r   utilsr   rm   r   fastapir   r   r   fastapi.routingr   pydanticr   starlette.responsesr   uvicornr   rY   ImportErrorAttributeErrorobject
get_loggerr[   r(   r*   r3   r9   r<   r#   r   r   r   <module>r      sQ   / . . . . . . . & & & & & & & & & & ? ? ? ? ? ? ? ? ? ?       ( ( ( ( ( (*4444444444((((((""""""000000$(!!^$ * * *I   %*!!!* 
	6	7	7A	 A A A A     9   $ $ $ $ $) $ $ $    I          H8 H8 H8 H8 H8- H8 H8 H8 H8 H8s   $A A A 