postprocessing.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import os
  2. from PIL import Image
  3. from modules import shared, images, devices, scripts, scripts_postprocessing, ui_common, infotext_utils, util
  4. from modules.shared import opts
  5. def run_postprocessing(extras_mode, image, image_folder, input_dir, output_dir, show_extras_results, *args, save_output: bool = True):
  6. devices.torch_gc()
  7. shared.state.begin(job="extras")
  8. outputs = []
  9. def get_images(extras_mode, image, image_folder, input_dir):
  10. if extras_mode == 1:
  11. for img in image_folder:
  12. if isinstance(img, Image.Image):
  13. image = images.fix_image(img)
  14. fn = ''
  15. else:
  16. image = images.read(os.path.abspath(img.name))
  17. fn = os.path.splitext(img.orig_name)[0]
  18. yield image, fn
  19. elif extras_mode == 2:
  20. assert not shared.cmd_opts.hide_ui_dir_config, '--hide-ui-dir-config option must be disabled'
  21. assert input_dir, 'input directory not selected'
  22. image_list = shared.listfiles(input_dir)
  23. for filename in image_list:
  24. yield filename, filename
  25. else:
  26. if isinstance(image, str):
  27. image = util.decode_base64_to_image(image)
  28. assert image, 'image not selected'
  29. yield image, None
  30. if extras_mode == 2 and output_dir != '':
  31. outpath = output_dir
  32. else:
  33. outpath = opts.outdir_samples or opts.outdir_extras_samples
  34. infotext = ''
  35. data_to_process = list(get_images(extras_mode, image, image_folder, input_dir))
  36. shared.state.job_count = len(data_to_process)
  37. for image_placeholder, name in data_to_process:
  38. image_data: Image.Image
  39. shared.state.nextjob()
  40. shared.state.textinfo = name
  41. shared.state.skipped = False
  42. if shared.state.interrupted:
  43. break
  44. if isinstance(image_placeholder, str):
  45. try:
  46. image_data = images.read(image_placeholder)
  47. except Exception:
  48. continue
  49. else:
  50. image_data = image_placeholder
  51. image_data = image_data if image_data.mode in ("RGBA", "RGB") else image_data.convert("RGB")
  52. parameters, existing_pnginfo = images.read_info_from_image(image_data)
  53. if parameters:
  54. existing_pnginfo["parameters"] = parameters
  55. initial_pp = scripts_postprocessing.PostprocessedImage(image_data)
  56. scripts.scripts_postproc.run(initial_pp, args)
  57. if shared.state.skipped:
  58. continue
  59. used_suffixes = {}
  60. for pp in [initial_pp, *initial_pp.extra_images]:
  61. suffix = pp.get_suffix(used_suffixes)
  62. if opts.use_original_name_batch and name is not None:
  63. basename = os.path.splitext(os.path.basename(name))[0]
  64. forced_filename = basename + suffix
  65. else:
  66. basename = ''
  67. forced_filename = None
  68. infotext = ", ".join([k if k == v else f'{k}: {infotext_utils.quote(v)}' for k, v in pp.info.items() if v is not None])
  69. if opts.enable_pnginfo:
  70. pp.image.info = existing_pnginfo
  71. pp.image.info["postprocessing"] = infotext
  72. shared.state.assign_current_image(pp.image)
  73. if save_output:
  74. fullfn, _ = images.save_image(pp.image, path=outpath, basename=basename, extension=opts.samples_format, info=infotext, short_filename=True, no_prompt=True, grid=False, pnginfo_section_name="extras", existing_info=existing_pnginfo, forced_filename=forced_filename, suffix=suffix)
  75. if pp.caption:
  76. caption_filename = os.path.splitext(fullfn)[0] + ".txt"
  77. existing_caption = ""
  78. try:
  79. with open(caption_filename, encoding="utf8") as file:
  80. existing_caption = file.read().strip()
  81. except FileNotFoundError:
  82. pass
  83. action = shared.opts.postprocessing_existing_caption_action
  84. if action == 'Prepend' and existing_caption:
  85. caption = f"{existing_caption} {pp.caption}"
  86. elif action == 'Append' and existing_caption:
  87. caption = f"{pp.caption} {existing_caption}"
  88. elif action == 'Keep' and existing_caption:
  89. caption = existing_caption
  90. else:
  91. caption = pp.caption
  92. caption = caption.strip()
  93. if caption:
  94. with open(caption_filename, "w", encoding="utf8") as file:
  95. file.write(caption)
  96. if extras_mode != 2 or show_extras_results:
  97. outputs.append(pp.image)
  98. devices.torch_gc()
  99. shared.state.end()
  100. return outputs, ui_common.plaintext_to_html(infotext), ''
  101. def run_postprocessing_webui(id_task, *args, **kwargs):
  102. return run_postprocessing(*args, **kwargs)
  103. def run_extras(extras_mode, resize_mode, image, image_folder, input_dir, output_dir, show_extras_results, gfpgan_visibility, codeformer_visibility, codeformer_weight, upscaling_resize, upscaling_resize_w, upscaling_resize_h, upscaling_crop, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility, upscale_first: bool, save_output: bool = True, max_side_length: int = 0):
  104. """old handler for API"""
  105. args = scripts.scripts_postproc.create_args_for_run({
  106. "Upscale": {
  107. "upscale_enabled": True,
  108. "upscale_mode": resize_mode,
  109. "upscale_by": upscaling_resize,
  110. "max_side_length": max_side_length,
  111. "upscale_to_width": upscaling_resize_w,
  112. "upscale_to_height": upscaling_resize_h,
  113. "upscale_crop": upscaling_crop,
  114. "upscaler_1_name": extras_upscaler_1,
  115. "upscaler_2_name": extras_upscaler_2,
  116. "upscaler_2_visibility": extras_upscaler_2_visibility,
  117. },
  118. "GFPGAN": {
  119. "enable": True,
  120. "gfpgan_visibility": gfpgan_visibility,
  121. },
  122. "CodeFormer": {
  123. "enable": True,
  124. "codeformer_visibility": codeformer_visibility,
  125. "codeformer_weight": codeformer_weight,
  126. },
  127. })
  128. return run_postprocessing(extras_mode, image, image_folder, input_dir, output_dir, show_extras_results, *args, save_output=save_output)