storage.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import base64, uuid
  2. from io import BytesIO
  3. import os,json
  4. import re
  5. import modules.scripts as scripts
  6. import gradio as gr
  7. from ots_agent import create_table, insert_row
  8. from oss_util import upload_to_oss, upload_bytes_to_oss
  9. pk, user_id, instance_id = "pk", "user_id", "instance_id"
  10. create_table()
  11. class Scripts(scripts.Script):
  12. def title(self):
  13. return "Aliyun Storage"
  14. def show(self, is_img2img):
  15. return scripts.AlwaysVisible
  16. def ui(self, is_img2img):
  17. checkbox_save_to_db = gr.inputs.Checkbox(label="Save to DB", default=True)
  18. return [checkbox_save_to_db, ]
  19. def postprocess(self, p, processed,checkbox_save_to_db):
  20. # Extract image information
  21. regex = r"Steps:.*$"
  22. info = re.findall(regex, processed.info, re.M)[0]
  23. input_dict = dict(item.split(": ") for item in str(info).split(", "))
  24. steps = int(input_dict["Steps"])
  25. seed = int(input_dict["Seed"])
  26. sampler = input_dict["Sampler"]
  27. cfg_scale = float(input_dict["CFG scale"])
  28. size = tuple(map(int, input_dict["Size"].split("x")))
  29. model_hash = input_dict["Model hash"]
  30. model = input_dict["Model"]
  31. task_id = str(uuid.uuid4())
  32. image_list = []
  33. for i in range(len(processed.images)):
  34. seed = processed.seed
  35. prompt = processed.prompt
  36. neg_prompt = processed.negative_prompt
  37. image = processed.images[i] # PIL.Image
  38. buffer = BytesIO()
  39. image.save(buffer, "png")
  40. image_bytes = buffer.getvalue()
  41. oss_file_name = f"sd_images/{user_id}/{instance_id}/{task_id}/{i}.png"
  42. upload_bytes_to_oss(image_bytes, oss_file_name)
  43. image_list.append(oss_file_name)
  44. parameters = {
  45. "prompt": prompt,
  46. "negative_prompt": neg_prompt,
  47. "steps": int(steps),
  48. "seed": int(seed),
  49. "sampler": sampler,
  50. "cfg_scale": float(cfg_scale),
  51. "size": size,
  52. "model_hash": model_hash,
  53. "model": model
  54. }
  55. print("insert result of task_id: ", task_id, pk, user_id, instance_id, task_id, prompt, ','.join(image_list) , parameters)
  56. insert_row(pk, user_id, instance_id, task_id, prompt, json.dumps(image_list, ensure_ascii=False) , request_params=json.dumps(parameters, ensure_ascii=False))
  57. return True