Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -24,30 +24,53 @@ def resize_to_4x6(img):
|
|
| 24 |
|
| 25 |
@app.post("/process")
|
| 26 |
async def process_img(file: UploadFile = File(...)):
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
| 34 |
|
| 35 |
-
|
| 36 |
-
aligned = Image.fromarray(face.normed)
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
|
| 42 |
-
white = Image.new("RGB", no_bg.size, (255, 255, 255))
|
| 43 |
-
white.paste(no_bg, mask=no_bg.split()[3])
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
|
|
|
| 47 |
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
final_img.save(buf, format="JPEG")
|
| 51 |
-
buf.seek(0)
|
| 52 |
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
@app.post("/process")
|
| 26 |
async def process_img(file: UploadFile = File(...)):
|
| 27 |
+
try:
|
| 28 |
+
# Read image
|
| 29 |
+
img_bytes = await file.read()
|
| 30 |
+
img = Image.open(io.BytesIO(img_bytes)).convert("RGB")
|
| 31 |
|
| 32 |
+
# βββ Fix 1: Resize large images to safe size βββ
|
| 33 |
+
max_dim = 1500
|
| 34 |
+
if max(img.size) > max_dim:
|
| 35 |
+
img.thumbnail((max_dim, max_dim))
|
| 36 |
|
| 37 |
+
np_img = np.array(img)
|
|
|
|
| 38 |
|
| 39 |
+
# Face detection
|
| 40 |
+
faces = face_app.get(np_img)
|
| 41 |
+
if not faces:
|
| 42 |
+
return JSONResponse({"error": "No face detected"}, status_code=400)
|
| 43 |
|
| 44 |
+
face = faces[0]
|
|
|
|
|
|
|
| 45 |
|
| 46 |
+
# βββ Fix 2: Some models return None in normed βββ
|
| 47 |
+
if face.normed is None:
|
| 48 |
+
return JSONResponse({"error": "Face alignment failed"}, status_code=500)
|
| 49 |
|
| 50 |
+
aligned_np = face.normed
|
| 51 |
+
aligned = Image.fromarray(aligned_np)
|
|
|
|
|
|
|
| 52 |
|
| 53 |
+
# βββ Fix 3: rembg requires proper RGB format βββ
|
| 54 |
+
if aligned.mode != "RGB":
|
| 55 |
+
aligned = aligned.convert("RGB")
|
| 56 |
+
|
| 57 |
+
no_bg = remove(aligned)
|
| 58 |
+
|
| 59 |
+
# Create white background
|
| 60 |
+
white = Image.new("RGB", no_bg.size, (255, 255, 255))
|
| 61 |
+
white.paste(no_bg, mask=no_bg.split()[3])
|
| 62 |
+
|
| 63 |
+
# Resize to 4Γ6
|
| 64 |
+
final_img = resize_to_4x6(white)
|
| 65 |
+
|
| 66 |
+
# Output
|
| 67 |
+
buf = io.BytesIO()
|
| 68 |
+
final_img.save(buf, format="JPEG")
|
| 69 |
+
buf.seek(0)
|
| 70 |
+
|
| 71 |
+
return Response(buf.getvalue(), media_type="image/jpeg")
|
| 72 |
+
|
| 73 |
+
except Exception as e:
|
| 74 |
+
# Log error inside HF Space
|
| 75 |
+
print("PROCESS ERROR:", e)
|
| 76 |
+
return JSONResponse({"error": str(e)}, status_code=500)
|