i_command.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import json
  2. import sys
  3. from typing import IO
  4. import click
  5. from ..bg import remove
  6. from ..session_factory import new_session
  7. from ..sessions import sessions_names
  8. @click.command(
  9. name="i",
  10. help="for a file as input",
  11. )
  12. @click.option(
  13. "-m",
  14. "--model",
  15. default="u2net",
  16. type=click.Choice(sessions_names),
  17. show_default=True,
  18. show_choices=True,
  19. help="model name",
  20. )
  21. @click.option(
  22. "-a",
  23. "--alpha-matting",
  24. is_flag=True,
  25. show_default=True,
  26. help="use alpha matting",
  27. )
  28. @click.option(
  29. "-af",
  30. "--alpha-matting-foreground-threshold",
  31. default=240,
  32. type=int,
  33. show_default=True,
  34. help="trimap fg threshold",
  35. )
  36. @click.option(
  37. "-ab",
  38. "--alpha-matting-background-threshold",
  39. default=10,
  40. type=int,
  41. show_default=True,
  42. help="trimap bg threshold",
  43. )
  44. @click.option(
  45. "-ae",
  46. "--alpha-matting-erode-size",
  47. default=10,
  48. type=int,
  49. show_default=True,
  50. help="erode size",
  51. )
  52. @click.option(
  53. "-om",
  54. "--only-mask",
  55. is_flag=True,
  56. show_default=True,
  57. help="output only the mask",
  58. )
  59. @click.option(
  60. "-ppm",
  61. "--post-process-mask",
  62. is_flag=True,
  63. show_default=True,
  64. help="post process the mask",
  65. )
  66. @click.option(
  67. "-bgc",
  68. "--bgcolor",
  69. default=None,
  70. type=(int, int, int, int),
  71. nargs=4,
  72. help="Background color (R G B A) to replace the removed background with",
  73. )
  74. @click.option("-x", "--extras", type=str)
  75. @click.argument(
  76. "input", default=(None if sys.stdin.isatty() else "-"), type=click.File("rb")
  77. )
  78. @click.argument(
  79. "output",
  80. default=(None if sys.stdin.isatty() else "-"),
  81. type=click.File("wb", lazy=True),
  82. )
  83. def i_command(model: str, extras: str, input: IO, output: IO, **kwargs) -> None:
  84. try:
  85. kwargs.update(json.loads(extras))
  86. except Exception:
  87. pass
  88. output.write(remove(input.read(), session=new_session(model), **kwargs))