paddlex_cli.py 16 KB

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