img2img.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import json
  2. import os
  3. import requests
  4. import io
  5. import base64
  6. from PIL import Image, PngImagePlugin
  7. from dotenv import load_dotenv
  8. from utils.logger import logger
  9. load_dotenv() # 加载环境变量
  10. img_url = os.getenv('img_url')
  11. def img_2_img(prompt, mask_img, img_key, img_path, output_directory):
  12. with open(img_path, 'rb') as f:
  13. image_data = f.read()
  14. input_image_pil = Image.open(io.BytesIO(image_data))
  15. width, height = input_image_pil.size
  16. input_image = base64.b64encode(image_data).decode('utf-8')
  17. mask = base64.b64encode(mask_img).decode('utf-8')
  18. payload = {
  19. "init_images": [
  20. input_image
  21. ],
  22. "denoising_strength": 0.96,
  23. "width": width,
  24. "height": height,
  25. "mask": mask,
  26. "mask_blur": 8,
  27. "prompt": prompt,
  28. "negative_prompt": "EasyNegativeV2,(badhandv4:1.2)",
  29. "batch_size": 1,
  30. "inpainting_mask_invert": 1,
  31. "steps": 30,
  32. "cfg_scale": 7,
  33. "sampler_index": "DPM++ 2M Karras",
  34. "alwayson_scripts": {
  35. "ADetailer": {
  36. "args": [
  37. True,
  38. {
  39. "ad_model": "face_yolov8n.pt",
  40. "ad_prompt": prompt,
  41. "ad_negative_prompt": "EasyNegativeV2,(badhandv4:1.2)",
  42. },
  43. {
  44. "ad_model": "hand_yolov8n.pt",
  45. "ad_prompt": prompt,
  46. "ad_negative_prompt": "EasyNegativeV2,(badhandv4:1.2)",
  47. }
  48. ]
  49. },
  50. "controlnet": {
  51. "args": [
  52. {
  53. "input_image": input_image,
  54. "module": "openpose_full",
  55. "model": "control_v11p_sd15_openpose [cab727d4]",
  56. },
  57. {
  58. "input_image": input_image,
  59. "module": "canny",
  60. "model": "control_v11p_sd15_canny [d14c016b]",
  61. "weight": 0.36,
  62. "starting_control_step": 0,
  63. "ending_control_step": 0.36,
  64. }
  65. ]
  66. }
  67. }
  68. }
  69. response = requests.post(url=f'{img_url}/sdapi/v1/img2img', json=payload)
  70. r = response.json()
  71. output_path = output_directory + f"/{img_key}-output.jpg"
  72. try:
  73. result = r['images'][0]
  74. image = Image.open(io.BytesIO(base64.b64decode(result.split(",", 1)[0])))
  75. image.save(output_path)
  76. return output_path
  77. except:
  78. logger.error('img2img error' + str(r))
  79. return None