paddlex_cli.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import argparse
  15. import importlib.resources
  16. import os
  17. import shutil
  18. import subprocess
  19. import sys
  20. from pathlib import Path
  21. from . import create_pipeline
  22. from .constants import MODEL_FILE_PREFIX
  23. from .inference.pipelines import load_pipeline_config
  24. from .repo_manager import get_all_supported_repo_names, setup
  25. from .utils import logging
  26. from .utils.flags import FLAGS_json_format_model
  27. from .utils.interactive_get_pipeline import interactive_get_pipeline
  28. from .utils.pipeline_arguments import PIPELINE_ARGUMENTS
  29. def args_cfg():
  30. """parse cli arguments"""
  31. def parse_str(s):
  32. """convert str type value
  33. to None type if it is "None",
  34. to bool type if it means True or False.
  35. """
  36. if s in ("None", "none", "NONE"):
  37. return None
  38. elif s in ("TRUE", "True", "true", "T", "t"):
  39. return True
  40. elif s in ("FALSE", "False", "false", "F", "f"):
  41. return False
  42. return s
  43. parser = argparse.ArgumentParser(
  44. "Command-line interface for PaddleX. Use the options below to install plugins, run pipeline predictions, or start the serving application."
  45. )
  46. install_group = parser.add_argument_group("Install PaddleX Options")
  47. pipeline_group = parser.add_argument_group("Pipeline Predict Options")
  48. serving_group = parser.add_argument_group("Serving Options")
  49. paddle2onnx_group = parser.add_argument_group("Paddle2ONNX Options")
  50. ################# install pdx #################
  51. install_group.add_argument(
  52. "--install",
  53. action="store_true",
  54. default=False,
  55. help="Install specified PaddleX plugins.",
  56. )
  57. install_group.add_argument(
  58. "plugins",
  59. nargs="*",
  60. default=[],
  61. help="Names of custom development plugins to install (space-separated).",
  62. )
  63. install_group.add_argument(
  64. "--no_deps",
  65. action="store_true",
  66. help="Install custom development plugins without their dependencies.",
  67. )
  68. install_group.add_argument(
  69. "--platform",
  70. type=str,
  71. choices=["github.com", "gitee.com"],
  72. default="github.com",
  73. help="Platform to use for installation (default: github.com).",
  74. )
  75. install_group.add_argument(
  76. "-y",
  77. "--yes",
  78. dest="update_repos",
  79. action="store_true",
  80. help="Automatically confirm prompts and update repositories.",
  81. )
  82. install_group.add_argument(
  83. "--use_local_repos",
  84. action="store_true",
  85. default=False,
  86. help="Use local repositories if they exist.",
  87. )
  88. install_group.add_argument(
  89. "--deps_to_replace",
  90. type=str,
  91. nargs="+",
  92. default=None,
  93. help="Replace dependency version when installing from repositories.",
  94. )
  95. ################# pipeline predict #################
  96. pipeline_group.add_argument(
  97. "--pipeline", type=str, help="Name of the pipeline to execute for prediction."
  98. )
  99. pipeline_group.add_argument(
  100. "--input",
  101. type=str,
  102. default=None,
  103. help="Input data or path for the pipeline, supports specific file and directory.",
  104. )
  105. pipeline_group.add_argument(
  106. "--save_path",
  107. type=str,
  108. default=None,
  109. help="Path to save the prediction results.",
  110. )
  111. pipeline_group.add_argument(
  112. "--device",
  113. type=str,
  114. default=None,
  115. help="Device to run the pipeline on (e.g., 'cpu', 'gpu:0').",
  116. )
  117. pipeline_group.add_argument(
  118. "--use_hpip",
  119. action="store_true",
  120. help="Enable HPIP acceleration by default.",
  121. )
  122. pipeline_group.add_argument(
  123. "--get_pipeline_config",
  124. type=str,
  125. default=None,
  126. help="Retrieve the configuration for a specified pipeline.",
  127. )
  128. ################# serving #################
  129. serving_group.add_argument(
  130. "--serve",
  131. action="store_true",
  132. help="Start the serving application to handle requests.",
  133. )
  134. serving_group.add_argument(
  135. "--host",
  136. type=str,
  137. default="0.0.0.0",
  138. help="Host address to serve on (default: 0.0.0.0).",
  139. )
  140. serving_group.add_argument(
  141. "--port",
  142. type=int,
  143. default=8080,
  144. help="Port number to serve on (default: 8080).",
  145. )
  146. # Serving also uses `--pipeline`, `--device`, and `--use_hpip`
  147. ################# paddle2onnx #################
  148. paddle2onnx_group.add_argument(
  149. "--paddle2onnx",
  150. action="store_true",
  151. help="Convert PaddlePaddle model to ONNX format",
  152. )
  153. paddle2onnx_group.add_argument(
  154. "--paddle_model_dir",
  155. type=str,
  156. help="Directory containing the PaddlePaddle model",
  157. )
  158. paddle2onnx_group.add_argument(
  159. "--onnx_model_dir",
  160. type=str,
  161. help="Output directory for the ONNX model",
  162. )
  163. paddle2onnx_group.add_argument(
  164. "--opset_version", type=int, help="Version of the ONNX opset to use"
  165. )
  166. # Parse known arguments to get the pipeline name
  167. args, remaining_args = parser.parse_known_args()
  168. pipeline = args.pipeline
  169. pipeline_args = []
  170. if not (args.install or args.serve or args.paddle2onnx) and pipeline is not None:
  171. if os.path.isfile(pipeline):
  172. pipeline_name = load_pipeline_config(pipeline)["pipeline_name"]
  173. else:
  174. pipeline_name = pipeline
  175. if pipeline_name not in PIPELINE_ARGUMENTS:
  176. support_pipelines = ", ".join(PIPELINE_ARGUMENTS.keys())
  177. logging.error(
  178. f"Unsupported pipeline: {pipeline_name}, CLI predict only supports these pipelines: {support_pipelines}\n"
  179. )
  180. sys.exit(1)
  181. pipeline_args = PIPELINE_ARGUMENTS[pipeline_name]
  182. if pipeline_args is None:
  183. pipeline_args = []
  184. pipeline_specific_group = parser.add_argument_group(
  185. f"{pipeline_name.capitalize()} Pipeline Options"
  186. )
  187. for arg in pipeline_args:
  188. pipeline_specific_group.add_argument(
  189. arg["name"],
  190. type=parse_str if arg["type"] is bool else arg["type"],
  191. help=arg.get("help", f"Argument for {pipeline_name} pipeline."),
  192. )
  193. return parser, pipeline_args
  194. def install(args):
  195. """install paddlex"""
  196. def _install_serving_deps():
  197. with importlib.resources.path(
  198. "paddlex", "serving_requirements.txt"
  199. ) as req_file:
  200. return subprocess.check_call(
  201. [sys.executable, "-m", "pip", "install", "-r", str(req_file)]
  202. )
  203. def _install_paddle2onnx_deps():
  204. with importlib.resources.path(
  205. "paddlex", "paddle2onnx_requirements.txt"
  206. ) as req_file:
  207. return subprocess.check_call(
  208. [sys.executable, "-m", "pip", "install", "-r", str(req_file)]
  209. )
  210. def _install_hpi_deps(device_type):
  211. supported_device_types = ["cpu", "gpu", "npu"]
  212. if device_type not in supported_device_types:
  213. logging.error(
  214. "HPI installation failed!\n"
  215. "Supported device_type: %s. Your input device_type: %s.\n"
  216. "Please ensure the device_type is correct.",
  217. supported_device_types,
  218. device_type,
  219. )
  220. sys.exit(2)
  221. if device_type == "cpu":
  222. packages = ["ultra-infer-python"]
  223. elif device_type == "gpu":
  224. packages = ["ultra-infer-gpu-python"]
  225. elif device_type == "npu":
  226. packages = ["ultra-infer-npu-python"]
  227. with importlib.resources.path("paddlex", "hpip_links.html") as f:
  228. return subprocess.check_call(
  229. [
  230. sys.executable,
  231. "-m",
  232. "pip",
  233. "install",
  234. "--find-links",
  235. str(f),
  236. *packages,
  237. ]
  238. )
  239. # Enable debug info
  240. os.environ["PADDLE_PDX_DEBUG"] = "True"
  241. # Disable eager initialization
  242. os.environ["PADDLE_PDX_EAGER_INIT"] = "False"
  243. plugins = args.plugins[:]
  244. if "serving" in plugins:
  245. plugins.remove("serving")
  246. if plugins:
  247. logging.error("`serving` cannot be used together with other plugins.")
  248. sys.exit(2)
  249. _install_serving_deps()
  250. return
  251. if "paddle2onnx" in plugins:
  252. plugins.remove("paddle2onnx")
  253. if plugins:
  254. logging.error("`paddle2onnx` cannot be used together with other plugins.")
  255. sys.exit(2)
  256. _install_paddle2onnx_deps()
  257. return
  258. hpi_plugins = list(filter(lambda name: name.startswith("hpi-"), plugins))
  259. if hpi_plugins:
  260. for i in hpi_plugins:
  261. plugins.remove(i)
  262. if plugins:
  263. logging.error("`hpi` cannot be used together with other plugins.")
  264. sys.exit(2)
  265. if len(hpi_plugins) > 1 or len(hpi_plugins[0].split("-")) != 2:
  266. logging.error(
  267. "Invalid HPI plugin installation format detected.\n"
  268. "Correct format: paddlex --install hpi-<device_type>\n"
  269. "Example: paddlex --install hpi-gpu"
  270. )
  271. sys.exit(2)
  272. device_type = hpi_plugins[0].split("-")[1]
  273. _install_hpi_deps(device_type=device_type)
  274. return
  275. if plugins:
  276. repo_names = plugins
  277. elif len(plugins) == 0:
  278. repo_names = get_all_supported_repo_names()
  279. setup(
  280. repo_names=repo_names,
  281. no_deps=args.no_deps,
  282. platform=args.platform,
  283. update_repos=args.update_repos,
  284. use_local_repos=args.use_local_repos,
  285. deps_to_replace=args.deps_to_replace,
  286. )
  287. return
  288. def pipeline_predict(
  289. pipeline,
  290. input,
  291. device,
  292. save_path,
  293. use_hpip,
  294. **pipeline_args,
  295. ):
  296. """pipeline predict"""
  297. pipeline = create_pipeline(pipeline, device=device, use_hpip=use_hpip)
  298. result = pipeline.predict(input, **pipeline_args)
  299. for res in result:
  300. res.print()
  301. if save_path:
  302. res.save_all(save_path=save_path)
  303. def serve(pipeline, *, device, use_hpip, host, port):
  304. from .inference.serving.basic_serving import create_pipeline_app, run_server
  305. pipeline_config = load_pipeline_config(pipeline)
  306. pipeline = create_pipeline(config=pipeline_config, device=device, use_hpip=use_hpip)
  307. app = create_pipeline_app(pipeline, pipeline_config)
  308. run_server(app, host=host, port=port)
  309. # TODO: Move to another module
  310. def paddle_to_onnx(paddle_model_dir, onnx_model_dir, *, opset_version):
  311. PD_MODEL_FILE_PREFIX = MODEL_FILE_PREFIX
  312. PD_PARAMS_FILENAME = f"{MODEL_FILE_PREFIX}.pdiparams"
  313. ONNX_MODEL_FILENAME = f"{MODEL_FILE_PREFIX}.onnx"
  314. CONFIG_FILENAME = f"{MODEL_FILE_PREFIX}.yml"
  315. ADDITIONAL_FILENAMES = ["scaler.pkl"]
  316. def _check_input_dir(input_dir, pd_model_file_ext):
  317. if input_dir is None:
  318. sys.exit("Input directory must be specified")
  319. if not input_dir.exists():
  320. sys.exit(f"{input_dir} does not exist")
  321. if not input_dir.is_dir():
  322. sys.exit(f"{input_dir} is not a directory")
  323. model_path = (input_dir / PD_MODEL_FILE_PREFIX).with_suffix(pd_model_file_ext)
  324. if not model_path.exists():
  325. sys.exit(f"{model_path} does not exist")
  326. params_path = input_dir / PD_PARAMS_FILENAME
  327. if not params_path.exists():
  328. sys.exit(f"{params_path} does not exist")
  329. config_path = input_dir / CONFIG_FILENAME
  330. if not config_path.exists():
  331. sys.exit(f"{config_path} does not exist")
  332. def _check_paddle2onnx():
  333. if shutil.which("paddle2onnx") is None:
  334. sys.exit("Paddle2ONNX is not available. Please install the plugin first.")
  335. def _run_paddle2onnx(input_dir, pd_model_file_ext, output_dir, opset_version):
  336. logging.info("Paddle2ONNX conversion starting...")
  337. # XXX: To circumvent Paddle2ONNX's bug
  338. if opset_version is None:
  339. if pd_model_file_ext == ".json":
  340. opset_version = 19
  341. else:
  342. opset_version = 7
  343. logging.info("Using default ONNX opset version: %d", opset_version)
  344. cmd = [
  345. "paddle2onnx",
  346. "--model_dir",
  347. str(input_dir),
  348. "--model_filename",
  349. str(Path(PD_MODEL_FILE_PREFIX).with_suffix(pd_model_file_ext)),
  350. "--params_filename",
  351. PD_PARAMS_FILENAME,
  352. "--save_file",
  353. str(output_dir / ONNX_MODEL_FILENAME),
  354. "--opset_version",
  355. str(opset_version),
  356. ]
  357. try:
  358. subprocess.check_call(cmd)
  359. except subprocess.CalledProcessError as e:
  360. sys.exit(f"Paddle2ONNX conversion failed with exit code {e.returncode}")
  361. logging.info("Paddle2ONNX conversion succeeded")
  362. def _copy_config_file(input_dir, output_dir):
  363. src_path = input_dir / CONFIG_FILENAME
  364. dst_path = output_dir / CONFIG_FILENAME
  365. shutil.copy(src_path, dst_path)
  366. logging.info(f"Copied {src_path} to {dst_path}")
  367. def _copy_additional_files(input_dir, output_dir):
  368. for filename in ADDITIONAL_FILENAMES:
  369. src_path = input_dir / filename
  370. if not src_path.exists():
  371. continue
  372. dst_path = output_dir / filename
  373. shutil.copy(src_path, dst_path)
  374. logging.info(f"Copied {src_path} to {dst_path}")
  375. paddle_model_dir = Path(paddle_model_dir)
  376. if not onnx_model_dir:
  377. onnx_model_dir = paddle_model_dir
  378. onnx_model_dir = Path(onnx_model_dir)
  379. logging.info(f"Input dir: {paddle_model_dir}")
  380. logging.info(f"Output dir: {onnx_model_dir}")
  381. pd_model_file_ext = ".json"
  382. if not FLAGS_json_format_model:
  383. if not (paddle_model_dir / f"{PD_MODEL_FILE_PREFIX}.json").exists():
  384. pd_model_file_ext = ".pdmodel"
  385. _check_input_dir(paddle_model_dir, pd_model_file_ext)
  386. _check_paddle2onnx()
  387. _run_paddle2onnx(paddle_model_dir, pd_model_file_ext, onnx_model_dir, opset_version)
  388. if not (onnx_model_dir.exists() and onnx_model_dir.samefile(paddle_model_dir)):
  389. _copy_config_file(paddle_model_dir, onnx_model_dir)
  390. _copy_additional_files(paddle_model_dir, onnx_model_dir)
  391. logging.info("Done")
  392. # for CLI
  393. def main():
  394. """API for command line"""
  395. parser, pipeline_args = args_cfg()
  396. args = parser.parse_args()
  397. if len(sys.argv) == 1:
  398. logging.warning("No arguments provided. Displaying help information:")
  399. parser.print_help()
  400. sys.exit(2)
  401. if args.install:
  402. install(args)
  403. elif args.serve:
  404. serve(
  405. args.pipeline,
  406. device=args.device,
  407. use_hpip=args.use_hpip,
  408. host=args.host,
  409. port=args.port,
  410. )
  411. elif args.paddle2onnx:
  412. paddle_to_onnx(
  413. args.paddle_model_dir,
  414. args.onnx_model_dir,
  415. opset_version=args.opset_version,
  416. )
  417. else:
  418. if args.get_pipeline_config is not None:
  419. interactive_get_pipeline(args.get_pipeline_config, args.save_path)
  420. else:
  421. pipeline_args_dict = {}
  422. for arg in pipeline_args:
  423. arg_name = arg["name"].lstrip("-")
  424. if hasattr(args, arg_name):
  425. pipeline_args_dict[arg_name] = getattr(args, arg_name)
  426. else:
  427. logging.warning(f"Argument {arg_name} is missing in args")
  428. return pipeline_predict(
  429. args.pipeline,
  430. args.input,
  431. args.device,
  432. args.save_path,
  433. use_hpip=args.use_hpip,
  434. **pipeline_args_dict,
  435. )