api.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import numpy as np
  2. from fastapi import FastAPI, Body
  3. from fastapi.exceptions import HTTPException
  4. from PIL import Image
  5. import os
  6. import gradio as gr
  7. from modules.api.models import *
  8. from modules.api import api
  9. import glob
  10. import base64
  11. from pydantic import BaseModel
  12. class GetGeneratedImagesRequest(BaseModel):
  13. limit: int = 10
  14. def AliyunStorage_api(_: gr.Blocks, app: FastAPI):
  15. @app.get("/storage/check-extension-installed")
  16. async def check_extension_installed(extension_name: str):
  17. extension_path = os.path.join(os.getcwd(), "extensions", extension_name)
  18. installed = 0
  19. if os.path.exists(extension_path):
  20. installed = 1
  21. return {
  22. "extension_path": extension_path,
  23. "installed": installed
  24. }
  25. @app.post("/storage/get-generated-images")
  26. async def get_generated_images(request: GetGeneratedImagesRequest):
  27. outputs_path = os.path.join(os.getcwd(), "outputs")
  28. txt2img_folder = os.path.join(outputs_path, 'txt2img-images', '**')
  29. img2img_folder = os.path.join(outputs_path, 'img2img-images', '**')
  30. files = glob.glob(txt2img_folder, recursive=True) + glob.glob(img2img_folder, recursive=True)
  31. files = [f for f in files if os.path.isfile(f)]
  32. files.sort(key=os.path.getctime, reverse=True)
  33. files = files[:request.limit]
  34. return_values = []
  35. for file in files:
  36. with open(file, "rb") as f:
  37. img = Image.open(f)
  38. width, height = img.size
  39. encoded_content = api.encode_pil_to_base64(img)
  40. image_name = os.path.basename(file)
  41. seed = int(image_name.split(".")[0].split("-")[1])
  42. return_value = {
  43. "image_name": image_name,
  44. "create_date": os.path.getctime(file),
  45. "content": encoded_content,
  46. "width": width,
  47. "height": height,
  48. "seed": seed
  49. }
  50. return_values.append(return_value)
  51. return return_values
  52. try:
  53. import modules.script_callbacks as script_callbacks
  54. script_callbacks.on_app_started(AliyunStorage_api)
  55. except:
  56. pass