o
    yqi:Z                     @   s$  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m	Z	 ddl
mZ ddlmZ ddlmZ ddlmZ ddlmZmZ dd	lmZ dd
lmZmZmZmZmZmZmZ ddlm Z m!Z!m"Z" ddl#m$Z$m%Z% ddl&m'Z' ddl(m)Z) dd Z*dd Z+dd Z,dd Z-dd Z.dd Z/dS )    N)Path   )create_pipeline)MODEL_FILE_PREFIX)load_pipeline_config)get_model_paths)get_all_supported_repo_namessetup)logging)get_dep_versionget_genai_dep_specsget_genai_fastdeploy_specget_paddle2onnx_dep_specsget_serving_dep_specsis_dep_availableis_paddle2onnx_plugin_available)get_gpu_compute_capabilityget_paddle_cuda_versionis_cuda_available)install_packagesuninstall_packages)interactive_get_pipeline)PIPELINE_ARGUMENTSc               
   C   s  dd } t d}|d}|d}|d}|d}|jdd	d
dd |jdddd |jdtddgddd |jdddddd |jddddd |jdtd d!d"d# |jd$td%d& |jd'td!d(d) |jd*td!d+d) |jd,td!d-d) |jd.dd/d |jd0tjd1d& |jd2td!d3d) |jd4dd5d |jd6td7d8d) |jd9td:d;d) |jd<dd=d |jd>td?d& |jd@tdAd& |jdBtdCdDd) | \}}|j	}g }	|j
d!usQ|jsQ|jsQ|d!urQtj|rt|dE }
n|}
|
tvrdFt }tdG|
 dH| dI tdJ t|
 }	|	d!u r$g }	||
  dK}|	D ] }|j|dL |dM tu r@| n|dM |dNdO|
 dPd& q0||	fS )Qzparse cli argumentsc                 S   s(   | dv rdS | dv rdS | dv rdS | S )zuconvert str type value
        to None type if it is "None",
        to bool type if it means True or False.
        )NonenoneNONEN)TRUETruetrueTtT)FALSEFalsefalseFfF )sr&   r&   Z/home/app/PaddleOCR-VL/.venv_paddleocr/lib/python3.10/site-packages/paddlex/paddlex_cli.py	parse_str4   s   zargs_cfg.<locals>.parse_strzCommand-line interface for PaddleX. Use the options below to install plugins, run pipeline predictions, or start the serving application.zInstall PaddleX OptionszPipeline Predict OptionszServing OptionszPaddle2ONNX Optionsz	--install*ZPLUGINz"Install specified PaddleX plugins.)nargsmetavarhelpz	--no_deps
store_truez>Install custom development plugins without their dependencies.)actionr-   z
--platformz
github.comz	gitee.comz7Platform to use for installation (default: github.com).)typechoicesdefaultr-   z-yz--yesupdate_reposz6Automatically confirm prompts and update repositories.)destr/   r-   z--use_local_reposFz%Use local repositories if they exist.)r/   r2   r-   z--deps_to_replace+Nz=Replace dependency version when installing from repositories.)r0   r+   r2   r-   z
--pipelinez/Name of the pipeline to execute for prediction.)r0   r-   z--inputzJInput data or path for the pipeline, supports specific file and directory.)r0   r2   r-   z--save_pathz$Path to save the prediction results.z--devicez5Device to run the pipeline on (e.g., 'cpu', 'gpu:0').z
--use_hpipz&Use high-performance inference plugin.z--hpi_configz)High-performance inference configuration.z--get_pipeline_configz4Retrieve the configuration for a specified pipeline.z--servez1Start the serving application to handle requests.z--hostz0.0.0.0z,Host address to serve on (default: 0.0.0.0).z--porti  z(Port number to serve on (default: 8080).z--paddle2onnxz*Convert PaddlePaddle model to ONNX format.z--paddle_model_dirz,Directory containing the PaddlePaddle model.z--onnx_model_dirz$Output directory for the ONNX model.--opset_version   z!Version of the ONNX opset to use.pipeline_namez, zUnsupported pipeline: z-, CLI predict only supports these pipelines: 
r   z Pipeline Optionsnamer0   r-   zArgument for z
 pipeline.)argparseArgumentParseradd_argument_groupadd_argumentstrastliteral_evalintparse_known_argspipelineinstallservepaddle2onnxospathisfiler   r   joinkeysr
   errorsysexit
capitalizeboolget)r)   parserZinstall_groupZpipeline_groupZserving_groupZpaddle2onnx_groupargsremaining_argsrD   pipeline_argsr8   Zsupport_pipelinesZpipeline_specific_groupargr&   r&   r(   args_cfg1   s"  



		




rX   c                 C   s  dd }dd }dd }dd }d	t jd
< dt jd< | jdd }d|v r;|d |r6td td |  dS d|v rU|d |rPtd td |  dS tt	dd |}|r|D ]}|| qb|rvtd td t
|dkst
|d ddkrtd td |d dd }||d dS tt	dd |}	|	r|	D ]}|| q|rtd td dd |	D }
||
 dS t }g }|D ]}||vr|| q|rtd| td |r|}nt
|dkr|}t|| j| j| j| j| jd  dS )!zinstall paddlexc                   S   H   zt t  W n ty   tjddd td Y nw td d S )NInstallation failedTexc_infor   z)Successfully installed the serving plugin)r   r   	Exceptionr
   rM   rN   rO   infor&   r&   r&   r(   _install_serving_deps      z&install.<locals>._install_serving_depsc                   S   rY   )NrZ   Tr[   r   z-Successfully installed the Paddle2ONNX plugin)r   r   r]   r
   rM   rN   rO   r^   r&   r&   r&   r(   _install_paddle2onnx_deps   r`   z*install.<locals>._install_paddle2onnx_depsc                 S   s  g d}| |vrt d||  td d}| dkr8t }|s$td |d dkr-d	}n|d d
kr8td dddd}||  }t| |h }|D ]9}t|}|d urt d| d| d| d| d	 zt	|g W qM t
y   t jddd td Y qMw qMtjd|^}	t|}z<|d u rt|gdt|	gd n*tdt| d}
|
 dv rt	|g t|gdt|	gd n	W W d    d S W n t
y   t jddd td Y nw W d    n1 sw   Y  t d t st d  d S d S )!N)cpugpuZnpuzgFailed to install the high-performance plugin.
Supported device types: %s. Your input device type: %s.
   zhpip_links.htmlrc   zZNo CUDA version found. Please make sure you have installed PaddlePaddle with CUDA enabled.r      zhpip_links_cu12.html   zcCurrently, only CUDA versions 11.x and 12.x are supported by the high-performance inference plugin.zultra-infer-pythonzultra-infer-gpu-pythonzultra-infer-npu-pythonz'The high-performance inference plugin 'z' is mutually exclusive with 'z' (version z installed). Uninstalling 'z'...zFailed to uninstall packagesTr[   r   Zpaddlexz--find-linksZpip_install_optszDThe high-performance inference plugin is already installed (version z&). Do you want to reinstall it? (y/n):)yyesrZ   z<Successfully installed the high-performance inference pluginzThe Paddle2ONNX plugin is not available. It is recommended to run `paddlex --install paddle2onnx` to install the Paddle2ONNX plugin to use the full functionality of high-performance inference.)r
   rM   rN   rO   r   setvaluesr   r^   r   r]   	importlib	resourcesrI   r   r?   inputreprlowerr   )device_typeZSUPPORTED_DEVICE_TYPESZhpip_links_fileZcuda_versionZpackage_mappingpackageZother_packagesZother_packageversionr%   responser&   r&   r(   _install_hpi_deps   s   



z"install.<locals>._install_hpi_depsc              	   S   s"  g }g }| D ]}d|v r| | q| | q|rgtds#td t }|dv r-d}n|dv r4d}ntd|d	  d
|d  d zttdgd|gd W n tyf   tj	ddd td Y nw g }|D ]!}zt
|}W n ty   t	d| td Y nw ||7 }qkzt|dd W n ty   tj	ddd td Y nw | D ]Q}d|v sd|v rtdgdd t rz%tdgdd t }|d usJ |dkrtdgdd ntdgdd W n ty   tj	ddd td Y nw  nqtdt| dkrdnd   d S )!NZ
fastdeployZpaddlepaddlez"Please install PaddlePaddle first.))   r   )	   r   zEhttps://www.paddlepaddle.org.cn/packages/stable/fastdeploy-gpu-80_90/))rv      )rv   rw   zEhttps://www.paddlepaddle.org.cn/packages/stable/fastdeploy-gpu-86_89/z%The compute capability of the GPU is r   .r   zX, which is not supported. The supported compute capabilities are 8.0, 8.6, 8.9, and 9.0.rc   z--extra-index-urlrg   rZ   Tr[   z%Invalid generative AI plugin type: %srd   required)constraintsZvllmZsglangZxformerswheel)re   r   zflash-attn == 2.8.3zflash-attn == 2.8.2z/Successfully installed the generative AI pluginr'    )appendr   rN   rO   r   r   r   r]   r
   rM   r   
ValueErrorr   r^   len)Zplugin_typesZfd_plugin_typesZnot_fd_plugin_typesZplugin_typecap	index_urlreqsrr&   r&   r(   _install_genai_depsF  s   


z$install.<locals>._install_genai_depsr   ZPADDLE_PDX_DEBUGr"   ZPADDLE_PDX_EAGER_INITNZservingz5`serving` cannot be used together with other plugins.rd   rG   z9`paddle2onnx` cannot be used together with other plugins.c                 S   
   |  dS )Nzhpi-
startswithr:   r&   r&   r(   <lambda>     
 zinstall.<locals>.<lambda>z5`hpi-xxx` cannot be used together with other plugins.r   r   -zInvalid HPI plugin installation format detected.
Correct format: paddlex --install hpi-<device_type>
Example: paddlex --install hpi-gpu)rq   c                 S   r   )Ngenai-r   r   r&   r&   r(   r     r   z7`genai-xxx` cannot be used together with other plugins.c                 S   s   g | ]
}|t d d qS )r   N)r   ).0pr&   r&   r(   
<listcomp>  s    zinstall.<locals>.<listcomp>zUnknown plugins: %s)
repo_namesno_depsplatformr3   use_local_reposdeps_to_replace)rH   environrE   remover
   rM   rN   rO   listfilterr   splitr   r~   r	   r   r   r3   r   r   )rT   r_   ra   ru   r   pluginsZhpi_pluginsr   rq   Zgenai_pluginsZgenai_plugin_typesZall_repo_namesZunknown_pluginsr   r&   r&   r(   rE      s   M
G








"





rE   c           	      K   sH   t | |||d} | j|fi |}|D ]}|  |r!|j|d qdS )zpipeline predict)deviceuse_hpip
hpi_config)	save_pathN)r   ZpredictprintZsave_all)	rD   rn   r   r   r   r   rV   resultresr&   r&   r(   pipeline_predict  s   
r   c          
      C   s   z
ddl m}m} W n ty   tjddd td Y nw t| }z
t	||||d} W n t
yC   tjddd td Y nw || |}	||	||d d S )	Nr   )create_pipeline_app
run_serverz!Failed to load the serving moduleTr[   )configr   r   r   zFailed to create the pipeline)hostport)Zinference.serving.basic_servingr   r   RuntimeErrorr
   rM   rN   rO   r   r   r]   )
rD   r   r   r   r   r   r   r   Zpipeline_configappr&   r&   r(   rF     s(   

rF   c                   s   t  std t dt ddg fdd}dd }fd	d
}fdd} fdd}| s8td t| } |s@| }t|}td|   td|  ||  |  || || | rj|| st|| | || | td d S )Nz,Please install the Paddle2ONNX plugin first.z.onnxz.ymlz
scaler.pklc                    s   | d u r	t d |  st |  d |  s!t |  d t| }d|vr.t d |   }| s@t | d d S d S )Nz!Input directory must be specifiedz does not existz is not a directorypaddlez!PaddlePaddle model does not exist)rN   rO   existsis_dirr   )	input_dirmodel_pathsZconfig_pathCONFIG_FILENAMEr&   r(   _check_input_dir
  s   

z(paddle_to_onnx.<locals>._check_input_dirc                   S   s    t dd u rtd d S d S )NrG   z>Paddle2ONNX is not available. Please install the plugin first.)shutilwhichrN   rO   r&   r&   r&   r(   _check_paddle2onnx  s   z*paddle_to_onnx.<locals>._check_paddle2onnxc                    s   t | }td ddt|d d jdt|d d jdt|d d jd	t|  d
t|g}zt| W n tjyT } zt	
d|j  W Y d }~nd }~ww td d S )Nz"Paddle2ONNX conversion starting...rG   z--model_dirr   r   z--model_filenamez--params_filenamer   z--save_filer6   z-Paddle2ONNX conversion failed with exit code z Paddle2ONNX conversion succeeded)r   r
   r^   r?   parentr:   
subprocess
check_callCalledProcessErrorrN   rO   
returncode)r   
output_diropset_versionr   cmde)ONNX_MODEL_FILENAMEr&   r(   _run_paddle2onnx  s*   

z(paddle_to_onnx.<locals>._run_paddle2onnxc                    s6   |   }|  }t || td| d|  d S NzCopied z to )r   copyr
   r^   )r   r   src_pathdst_pathr   r&   r(   _copy_config_file3  s   z)paddle_to_onnx.<locals>._copy_config_filec                    sJ    D ] }| | }|  sq|| }t|| td| d|  qd S r   )r   r   r   r
   r^   )r   r   filenamer   r   )ADDITIONAL_FILENAMESr&   r(   _copy_additional_files9  s   z.paddle_to_onnx.<locals>._copy_additional_filesz.PaddlePaddle model directory must be specifiedzInput dir: zOutput dir: Done)	r   rN   rO   r   r   r
   r^   r   samefile)paddle_model_dironnx_model_dirr   r   r   r   r   r   r&   )r   r   r   r(   paddle_to_onnx  s2   


	


r   c                  C   sb  t  \} }|  }ttjdkrtd |   td |j	dur)t	| dS |j
r@t
|j|j|jp5d|j|j|jd dS |jrOt|j|j|jd dS |jdur]t|j|j dS i }|D ]}|d d}t||rwt||||< qatd	| d
 qazt|j|j|j|jf|jpd|jd| W dS  ty   tjddd td Y dS w )zAPI for command liner   z3No arguments provided. Displaying help information:rd   N)r   r   r   r   r   )r   r:   r   z	Argument z is missing in args)r   r   zPipeline prediction failedTr[   ) rX   
parse_argsr   rN   argvr
   warning
print_helprO   rE   rF   rD   r   r   r   r   r   rG   r   r   r   r   Zget_pipeline_configr   r   lstriphasattrgetattrr   rn   r]   rM   )rS   rV   rT   Zpipeline_args_dictrW   Zarg_namer&   r&   r(   mainU  s^   







	r   )0r;   r@   importlib.resourcesrl   rH   r   r   rN   pathlibr   r}   r   	constantsr   Zinference.pipelinesr   Zinference.utils.model_pathsr   Zrepo_managerr   r	   utilsr
   Z
utils.depsr   r   r   r   r   r   r   Z	utils.envr   r   r   Zutils.installr   r   Zutils.interactive_get_pipeliner   Zutils.pipeline_argumentsr   rX   rE   r   rF   r   r   r&   r&   r&   r(   <module>   s6   $	 6 rS