
    sg[                     d   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 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&y# eef$ r
 eZd ZdZY `w xY w)    )ArgumentParser	Namespace)AnyListOptional   )Pipelineget_supported_taskspipeline)logging   )BaseTransformersCLICommand)BodyFastAPIHTTPException)APIRoute)	BaseModel)JSONResponse)runTc                       y )N )xys     P/var/www/html/venv/lib/python3.12/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     YY JJdjjD{{..{{C TYY		4<<@@r   c                       e Zd ZU dZeed<   y)ServeModelInfoResultz"
    Expose model information
    infosN)__name__
__module____qualname____doc__dict__annotations__r   r   r   r*   r*   ;   s     Kr   r*   c                   8    e Zd ZU dZee   ed<   eee      ed<   y)ServeTokenizeResultz
    Tokenize result model
    tokens
tokens_idsN)	r,   r-   r.   r/   r   strr1   r   intr   r   r   r3   r3   C   s"     Ic##r   r3   c                       e Zd ZU dZeed<   y)ServeDeTokenizeResultz!
    DeTokenize result model
    textN)r,   r-   r.   r/   r6   r1   r   r   r   r9   r9   L   s     Ir   r9   c                       e Zd ZU dZeed<   y)ServeForwardResultz
    Forward result model
    outputN)r,   r-   r.   r/   r   r1   r   r   r   r<   r<   T   s     Kr   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y
)r#   parserc                    | j                  dd      }|j                  dt        t               d       |j                  dt        dd	
       |j                  dt        dd
       |j                  dt        dd
       |j                  dt        d       |j                  dt        d       |j                  dt        d       |j                  dt        dd
       |j                  t               y)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]   s    ((b ) 
 	!!')2	 	" 	
 	!!(kPv!w!!(dIk!l!!+CIa!b!!)#<c!d!!*3=k!l!!-c@X!Y!!f	 	" 	
 	!!'<!=r   r   r$   r%   r&   c                    || _         || _        || _        || _        t        st        d      t        j                  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      | _        y )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-dV1TF;<';'3!& #':'3!' %'<'3!' "'9'3!'-< ? DIr   c                 r    t        | j                  | j                  | j                  | j                         y )N)r$   r%   r&   )r   ra   r$   r%   r&   rb   s    r   r   zServeCommand.run   s     DIIDIIDIIt||Lr   c                 h    t        t        | j                  j                  j                              S )N)r+   )r*   varsrX   r   r    re   s    r   r]   zServeCommand.model_info   s"    #$t~~/C/C/J/J*KLLr   NT)embedF
text_input
return_idsc                 "   	 | j                   j                  j                  |      }|r2| j                   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1:::FJ!^^55KKJW
**TT**== 	XC"sSTv8VWW	Xs   AA' A' '	B0B		Br5   skip_special_tokenscleanup_tokenization_spacesc                     	 | j                   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299*FY[vwK(rDD 	XC"sSTv8VWW	Xs   36 	AAAc                    K   t        |      dk(  rt        g g       S 	 | j                  |      }t        |      S # t        $ r}t	        ddt        |      i      d}~ww xY w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   sd      v;!%R2>>	8^^F+F%V44 	8gs1v%677	8s%   A$< A$	A!AA!!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 *.d$)?TXY^fjTk X3 XT X( !%T 6$(d$;,0T,B	XIX "X &*	X" $(D#9 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      s    / & & ? ?  (*44("0$(! 
		6	7A	 A 9 $) $I  H8- H8{ 	^$ *I %*!*s   $B B/.B/