Antony-PB

Untitled

Sep 11th, 2024
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. import os
  2. import random
  3. import torch
  4. from diffusers import StableDiffusionInpaintPipeline
  5. from fastapi import FastAPI, File, UploadFile
  6. from fastapi.responses import FileResponse
  7. from PIL import Image
  8. from io import BytesIO
  9. from dotenv import load_dotenv
  10. import uvicorn
  11.  
  12. # Load environment variables
  13. load_dotenv()
  14.  
  15. app = FastAPI()
  16.  
  17. # Load the inpainting model
  18. model_name = os.getenv("MODEL_NAME", "stabilityai/stable-diffusion-2-inpainting")
  19. device = "cuda" if torch.cuda.is_available() else "cpu"
  20. pipe = StableDiffusionInpaintPipeline.from_pretrained(model_name, torch_dtype=torch.float16 if device == "cuda" else torch.float32)
  21.  
  22. pipe.to(device)
  23.  
  24.  
  25. @app.post("/inpaint/")
  26. async def inpaint_image(file: UploadFile = File(...), target_width: int = 512, target_height: int = 512):
  27. # Load the input image
  28. input_image = Image.open(BytesIO(await file.read())).convert("RGB")
  29.  
  30. random_numm = random.randint(0, 10000)
  31.  
  32. # Resize the image to the target dimensions
  33. input_image = input_image.resize((target_width, target_height))
  34. input_image.save(f"./temp/inpainted_{random_numm}_{file.filename}")
  35.  
  36. full_mask = Image.new('RGB', (target_width, target_height), color='black')
  37. full_mask.save(f"./temp/inpainted_mask_{file.filename}")
  38.  
  39. # Generate the inpainted image
  40. inpainted_image = pipe(
  41. prompt=[
  42. "Enhance this image to improve quality.",
  43. "Better image quality",
  44. "Higher image quality",
  45. "High Resolution"
  46. ],
  47. negative_prompt=[
  48. "blur",
  49. "low resolution",
  50. "pixelation",
  51. "noise"
  52. ],
  53. image=input_image,
  54. mask_image=full_mask,
  55. ).images[0]
  56.  
  57. # Save the image to the static directory
  58. output_path = f"static/images/inpainted_{random_numm}_{file.filename}"
  59. inpainted_image.save(output_path)
  60.  
  61. print(output_path)
  62.  
  63. return FileResponse(output_path)
  64.  
  65. @app.get("/")
  66. async def root():
  67. return {"message": "Image Inpainting API is running!"}
  68.  
Advertisement
Add Comment
Please, Sign In to add comment