APOGEA/apiExample
0
1from fastapi import FastAPI, UploadFile, Form2from fastapi.responses import StreamingResponse3#import torch4from PIL import Image5#from diffusers import StableDiffusionDepth2ImgPipeline6import numpy as np7from io import BytesIO8 9app = FastAPI()10 11"""12pipe = StableDiffusionDepth2ImgPipeline.from_pretrained(13 "stabilityai/stable-diffusion-2-depth",14 torch_dtype=torch.float16,15).to("cuda")16"""17 18def pad_image(input_image):19 pad_w, pad_h = np.max(((2, 2), np.ceil(20 np.array(input_image.size) / 64).astype(int)), axis=0) * 64 - input_image.size21 im_padded = Image.fromarray(22 np.pad(np.array(input_image), ((0, pad_h), (0, pad_w), (0, 0)), mode='edge'))23 w, h = im_padded.size24 if w == h:25 return im_padded26 elif w > h:27 new_image = Image.new(im_padded.mode, (w, w), (0, 0, 0))28 new_image.paste(im_padded, (0, (w - h) // 2))29 return new_image30 else:31 new_image = Image.new(im_padded.mode, (h, h), (0, 0, 0))32 new_image.paste(im_padded, ((h - w) // 2, 0))33 return new_image34 35def predict(input_image, prompt, steps, scale, seed, strength, depth_image=None):36 depth = None37 if depth_image is not None:38 depth_image = pad_image(depth_image)39 depth_image = depth_image.resize((512, 512))40 depth = np.array(depth_image.convert("L"))41 depth = depth.astype(np.float32) / 255.042 depth = depth[None, None]43 depth = torch.from_numpy(depth)44 init_image = input_image.convert("RGB")45 image = pad_image(init_image) # resize to integer multiple of 3246 image = image.resize((512, 512))47 result = pipe(prompt=prompt, image=image, strength=strength)48 49 return result['images']50 51def grayscale(image,52 prompt,53 steps,54 scale,55 seed,56 strength):57 image = image.convert('L') #convert to grayscale58 59 return image60 61@app.post("/convert_ifc_img/")62async def convert_ifc_img(file: UploadFile, 63 prompt: str = Form(default=""), 64 steps: int = Form(default=50), 65 scale: float = Form(default=9), 66 seed: int = Form(default=178106186), 67 strength: float = Form(default=0.9)68 ):69 70 image = Image.open(file.file) 71 image_result = grayscale(image, prompt, steps, scale, seed, strength)72 buffer = BytesIO()73 image_result.save(buffer, format="PNG")74 buffer.seek(0)75 return StreamingResponse(buffer, media_type="image/png")