ai_pic.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. import requests
  2. import json
  3. import time
  4. import random
  5. from websocket import WebSocketApp
  6. from config import config_get
  7. import os
  8. # 全局变量在这里改写:
  9. file_path = config_get('file_path')
  10. ip = config_get("comfyUI_ip")
  11. pro_bad = config_get("pro_bad")
  12. def AI_paint(prompt):
  13. """
  14. 根据传入的prompt参数获取image_url
  15. """
  16. png_path = 'output.png'
  17. url = "https://api.siliconflow.cn/v1/images/generations"
  18. web_url = "https://e423-34-68-183-106.ngrok-free.app"
  19. payload = {
  20. "model": "black-forest-labs/FLUX.1-schnell",
  21. "image_size": "1024x1024",
  22. "prompt": prompt, # 正面提示词
  23. "negative_prompt": pro_bad,
  24. "batch_size": 2,
  25. "num_inference_steps": 35,
  26. "guidance_scale": 7.5,
  27. }
  28. headers = {
  29. "Authorization": "Bearer sk-hrascmreejxkirpsdprupkjtqbxtywqbyntzjkdjuficbtok",
  30. "Content-Type": "application/json"
  31. }
  32. response = requests.post(url, json=payload, headers=headers)
  33. r = response.json()
  34. image_url = r['images'][0]['url']
  35. print(image_url)
  36. return image_url
  37. def generate_instance_id():
  38. """
  39. 根据当前时间生成图片生成唯一实例id
  40. """
  41. current_time = time.strftime("%Y%m%d%H%M%S", time.localtime())
  42. instance_id = f"{current_time}-gxx12138-key"
  43. return instance_id
  44. def start_paint(id,data):
  45. """
  46. 绘图任务下发程序,传入实例id和提示词开始任务
  47. 传入修改好的json格式的data数据,发送到confyUI下发任务
  48. """
  49. # 构建符合官方文档格式的请求数据
  50. request_data = {
  51. "client_id": id,
  52. "prompt": data
  53. }
  54. # 发送POST请求到ComfyUI的/prompt端点
  55. url = "http://"+ip+"/prompt"
  56. headers = {'Content-Type': 'application/json'}
  57. response = requests.post(url, headers=headers, json=request_data)
  58. # 检查响应状态码是否为200(表示成功)
  59. if response.status_code == 200:
  60. print("任务下发成功")
  61. print(response.json())
  62. print("任务实例id为"+id)
  63. else:
  64. print(f"请求失败,状态码: {response.status_code}")
  65. def get_websocket_data(client_id):
  66. """
  67. 获取生图任务运行状态,根据实例id进行跟踪
  68. """
  69. output_image_filenames = []
  70. def on_message(ws, message):
  71. nonlocal output_image_filenames
  72. message_dict = json.loads(message)
  73. if message_dict["type"] == "executed" and message_dict["data"]["node"] == "16":
  74. output_data = message_dict["data"]
  75. if "output" in output_data and "images" in output_data["output"]:
  76. image_list = output_data["output"]["images"]
  77. output_image_filenames = [image["filename"] for image in image_list]
  78. ws.close()
  79. message_dict = eval(message)
  80. if message_dict["type"] != "crystools.monitor":
  81. print(f"\r收到消息: {message}",flush=True,end="\n")
  82. def on_error(ws, error):
  83. print(f"\r发生错误: {error}",flush=True,end="\n")
  84. def on_close(ws, close_status_code, close_msg):
  85. print(f"\r连接已关闭,状态码: {close_status_code},消息: {close_msg}",flush=True,end="\n")
  86. def on_open(ws):
  87. print("\r连接已建立",flush=True,end="\n")
  88. websocket_url = "ws://"+ip+"/ws?clientId="+client_id
  89. ws = WebSocketApp(websocket_url,
  90. on_open=on_open,
  91. on_message=on_message,
  92. on_error=on_error,
  93. on_close=on_close)
  94. ws.run_forever()
  95. return output_image_filenames
  96. def get_pic(id):
  97. """
  98. 输入prompt_id来查询图片
  99. """
  100. url = "http://"+ip+"/history/"+id
  101. try:
  102. response = requests.get(url)
  103. if response.status_code == 200:
  104. print("请求成功,响应内容:")
  105. print(response.json())
  106. else:
  107. print(f"请求失败,状态码:{response.status_code}")
  108. except requests.RequestException as e:
  109. print(f"请求发生错误:{e}")
  110. def get_images_from_filenames(image_filenames):
  111. """
  112. 获取图片存入output,传入为图片名称列表
  113. ip和存储地址采用硬编码,如果comfyUI配置不同需要调整ip和路径
  114. """
  115. base_url = "http://"+ip+"/view"
  116. output_folder = f"{file_path}/output"
  117. if not os.path.exists(output_folder):
  118. os.makedirs(output_folder)
  119. for filename in image_filenames:
  120. params = {
  121. "filename": filename,
  122. "type": "output"
  123. }
  124. response = requests.get(base_url, params=params)
  125. if response.status_code == 200:
  126. # 这里可以根据实际需求对获取到的图片内容进行进一步处理,比如保存到本地等
  127. print(f"成功获取图片 {filename} 的内容")
  128. # 保存图片到output文件夹下
  129. output_path = os.path.join(output_folder, filename)
  130. with open(output_path, 'wb') as f:
  131. f.write(response.content)
  132. print(f"成功将图片 {filename} 保存到 {output_path}")
  133. return output_path
  134. else:
  135. print(f"获取图片 {filename} 时出错,状态码: {response.status_code}")
  136. def story_start(prompt):
  137. """
  138. 下发任务开关,在这里动态处理任务相关参数
  139. """
  140. with open('maomao_api.json', 'r', encoding='utf-8') as file:
  141. data = json.load(file)
  142. data['3']['inputs']["text"] = prompt
  143. if str(prompt).startswith("nsfw"):
  144. data['4']['inputs']["text"] = config_get("pro_bad_sese")
  145. print("true")
  146. data["21"]["inputs"]["seed"] = random.randint(1, 2 ** 32 - 1)
  147. data["5"]["inputs"]["noise_seed"] = random.randint(0, 18446744073709551615)
  148. print(prompt)
  149. id = generate_instance_id()
  150. start_paint(id, data)
  151. return get_images_from_filenames(get_websocket_data(id))
  152. def story_start_p2p(qq):
  153. """
  154. 调用p2p的任务下发开关,传入qq号,自动根据user文件夹下的用户名搜索头像来变身
  155. 用户头像存储路径默认user文件夹
  156. """
  157. with open('p2p.json', 'r', encoding='utf-8') as file:
  158. data = json.load(file)
  159. data['49']['inputs']["directory"] = f"{file_path}/user/{qq}/"
  160. data["43"]["inputs"]["seed"] = random.randint(1, 2 ** 32 - 1)
  161. id = generate_instance_id()
  162. start_paint(id, data)
  163. return get_images_from_filenames(get_websocket_data(id))
  164. def story_start_p2p_sese(qq):
  165. """
  166. 调用p2p涩图版的任务下发开关,传入qq号,自动根据user文件夹下的用户名搜索头像来变身
  167. 用户头像存储路径默认user文件夹
  168. """
  169. with open('p2p.json', 'r', encoding='utf-8') as file:
  170. data = json.load(file)
  171. data['49']['inputs']["directory"] = f"{file_path}/user/{qq}/"
  172. data["43"]["inputs"]["seed"] = random.randint(1, 2 ** 32 - 1)
  173. data['3']['inputs']["text"] = "nsfw,1girl"
  174. data['4']['inputs']["text"] = config_get("pro_bad_sese")
  175. id = generate_instance_id()
  176. start_paint(id, data)
  177. return get_images_from_filenames(get_websocket_data(id))