MalikSahib1 commited on
Commit
10c05aa
·
verified ·
1 Parent(s): 00d083f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -36
app.py CHANGED
@@ -1,12 +1,12 @@
1
  from fastapi import FastAPI, Response
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
4
- import torch
5
- from diffusers import DiffusionPipeline
6
  from PIL import Image
7
  import io
8
  import base64
9
  import re
 
 
10
 
11
  # Pydantic model to expect two base64 strings
12
  class InpaintRequest(BaseModel):
@@ -23,50 +23,42 @@ app.add_middleware(
23
  allow_headers=["*"],
24
  )
25
 
26
- # --- THE GUARANTEED FIX: USING STABLE DIFFUSION v1.5 INPAINTING ---
27
- # This model is the perfect balance of quality and performance for free hardware.
28
- # It's lighter than the v2 model and will not crash due to memory issues.
29
- print("Loading Stable Diffusion v1.5 Inpainting model...")
30
- pipeline = DiffusionPipeline.from_pretrained(
31
- "runwayml/stable-diffusion-inpainting",
32
- torch_dtype=torch.float16,
33
- )
34
- # Move to CPU
35
- pipeline = pipeline.to("cpu")
36
- # Enable memory saving for stability
37
- pipeline.enable_attention_slicing()
38
- print("Model loaded successfully!")
39
 
40
- def base64_to_image(base64_string):
41
- """Decodes a base64 string into a PIL Image."""
42
  base64_data = re.sub('^data:image/.+;base64,', '', base64_string)
43
  img_data = base64.b64decode(base64_data)
44
- return Image.open(io.BytesIO(img_data)).convert("RGB")
 
 
45
 
46
  @app.post("/inpaint")
47
  async def inpaint_image(request: InpaintRequest):
48
  try:
49
- init_image = base64_to_image(request.image_data)
50
- mask_image = base64_to_image(request.mask_data)
 
 
 
 
 
 
 
 
51
 
52
- print("Received images for inpainting.")
53
 
54
- if init_image.size != mask_image.size:
55
- mask_image = mask_image.resize(init_image.size)
56
-
57
- # Run the inpainting pipeline
58
- inpainted_image = pipeline(
59
- prompt="high quality, detailed", # A generic prompt helps
60
- image=init_image,
61
- mask_image=mask_image
62
- ).images[0]
63
 
64
- print("Inpainting complete.")
65
 
66
- # Convert result back to base64
67
- buffer = io.BytesIO()
68
- inpainted_image.save(buffer, format="PNG")
69
- img_str = base64.b64encode(buffer.getvalue()).decode("utf-8")
70
 
71
  return {"inpainted_image_data": img_str}
72
 
@@ -76,4 +68,4 @@ async def inpaint_image(request: InpaintRequest):
76
 
77
  @app.get("/")
78
  def read_root():
79
- return {"Status": "Magic Eraser API is running!"}
 
1
  from fastapi import FastAPI, Response
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
 
 
4
  from PIL import Image
5
  import io
6
  import base64
7
  import re
8
+ import numpy as np
9
+ import cv2 # This is the OpenCV library
10
 
11
  # Pydantic model to expect two base64 strings
12
  class InpaintRequest(BaseModel):
 
23
  allow_headers=["*"],
24
  )
25
 
26
+ # --- NO HEAVY MODEL TO LOAD! THE APP STARTS INSTANTLY. ---
27
+ print("OpenCV Magic Eraser API is ready!")
 
 
 
 
 
 
 
 
 
 
 
28
 
29
+ def base64_to_cv2_image(base64_string):
30
+ """Decodes a base64 string into an OpenCV image (numpy array)."""
31
  base64_data = re.sub('^data:image/.+;base64,', '', base64_string)
32
  img_data = base64.b64decode(base64_data)
33
+ np_arr = np.frombuffer(img_data, np.uint8)
34
+ # cv2.imdecode reads an image from the buffer
35
+ return cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
36
 
37
  @app.post("/inpaint")
38
  async def inpaint_image(request: InpaintRequest):
39
  try:
40
+ # 1. Decode base64 strings into OpenCV images
41
+ init_image = base64_to_cv2_image(request.image_data)
42
+
43
+ # For the mask, we need it in grayscale
44
+ mask_image_color = base64_to_cv2_image(request.mask_data)
45
+ mask_image_gray = cv2.cvtColor(mask_image_color, cv2.COLOR_BGR2GRAY)
46
+
47
+ # The inpainting algorithm needs a binary mask (black and white)
48
+ # We'll make any non-black pixel white
49
+ _, mask = cv2.threshold(mask_image_gray, 1, 255, cv2.THRESH_BINARY)
50
 
51
+ print("Received images. Starting high-speed inpainting...")
52
 
53
+ # 2. Run the high-speed OpenCV inpainting algorithm
54
+ # cv2.INPAINT_NS is based on Navier-Stokes, giving high-quality results
55
+ inpainted_image = cv2.inpaint(init_image, mask, 3, cv2.INPAINT_NS)
 
 
 
 
 
 
56
 
57
+ print("Inpainting complete in milliseconds.")
58
 
59
+ # 3. Convert the result back to a base64 string to send to the frontend
60
+ _, buffer = cv2.imencode('.png', inpainted_image)
61
+ img_str = base64.b64encode(buffer).decode("utf-8")
 
62
 
63
  return {"inpainted_image_data": img_str}
64
 
 
68
 
69
  @app.get("/")
70
  def read_root():
71
+ return {"Status": "High-Speed OpenCV Magic Eraser API is running!"}