Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,239 +1,33 @@
|
|
| 1 |
-
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
from
|
| 6 |
-
import logging
|
| 7 |
-
from transformers import SegformerImageProcessor, SegformerForSemanticSegmentation
|
| 8 |
|
| 9 |
-
|
| 10 |
-
logger = logging.getLogger(__name__)
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
print("Loading SegFormer face-parsing model...")
|
| 16 |
-
processor = SegformerImageProcessor.from_pretrained("jonathandinu/face-parsing")
|
| 17 |
-
model = SegformerForSemanticSegmentation.from_pretrained("jonathandinu/face-parsing")
|
| 18 |
-
model.to(device)
|
| 19 |
-
model.eval()
|
| 20 |
-
logger.info("Model loaded!")
|
| 21 |
-
|
| 22 |
-
hair_class_id = 13
|
| 23 |
-
ear_class_ids = [7, 8]
|
| 24 |
-
|
| 25 |
-
def make_realistic_bald(input_image: Image.Image) -> tuple[Image.Image, Image.Image, Image.Image]:
|
| 26 |
-
# (Yeh pura function tera perfect logic wala — same as before, no change)
|
| 27 |
try:
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
if max(orig_w, orig_h) > MAX_PROCESS_DIM:
|
| 40 |
-
logger.info(f"Downscaling to max {MAX_PROCESS_DIM}px")
|
| 41 |
-
scale_factor = MAX_PROCESS_DIM / max(orig_w, orig_h)
|
| 42 |
-
working_w = int(orig_w * scale_factor)
|
| 43 |
-
working_h = int(orig_h * scale_factor)
|
| 44 |
-
working_np = cv2.resize(original_np, (working_w, working_h), cv2.INTER_AREA)
|
| 45 |
-
working_bgr = cv2.cvtColor(working_np, cv2.COLOR_RGB2BGR)
|
| 46 |
-
|
| 47 |
-
pil_working = Image.fromarray(working_np)
|
| 48 |
-
inputs = processor(images=pil_working, return_tensors="pt").to(device)
|
| 49 |
-
with torch.no_grad():
|
| 50 |
-
outputs = model(**inputs)
|
| 51 |
-
logits = outputs.logits
|
| 52 |
-
|
| 53 |
-
upsampled_logits = torch.nn.functional.interpolate(
|
| 54 |
-
logits, size=(working_h, working_w), mode="bilinear", align_corners=False
|
| 55 |
-
)
|
| 56 |
-
parsing = upsampled_logits.argmax(dim=1).squeeze(0).cpu().numpy()
|
| 57 |
-
|
| 58 |
-
hair_mask = (parsing == hair_class_id).astype(np.uint8)
|
| 59 |
-
|
| 60 |
-
ears_mask = np.zeros_like(hair_mask)
|
| 61 |
-
for cls in ear_class_ids:
|
| 62 |
-
ears_mask[parsing == cls] = 1
|
| 63 |
-
|
| 64 |
-
ear_y, ear_x = np.where(ears_mask)
|
| 65 |
-
if len(ear_y) > 0:
|
| 66 |
-
ear_top_y = ear_y.min()
|
| 67 |
-
ear_height = ear_y.max() - ear_top_y + 1
|
| 68 |
-
kernel_v = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 30))
|
| 69 |
-
ears_protected = cv2.dilate(ears_mask, kernel_v, iterations=2)
|
| 70 |
-
|
| 71 |
-
top_margin = max(8, int(ear_height * 0.12))
|
| 72 |
-
top_start = max(0, ear_top_y - top_margin)
|
| 73 |
-
|
| 74 |
-
ear_x_min, ear_x_max = ear_x.min(), ear_x.max()
|
| 75 |
-
ear_width = ear_x_max - ear_x_min + 1
|
| 76 |
-
x_margin = int(ear_width * 0.35)
|
| 77 |
-
protected_left = max(0, ear_x_min - x_margin)
|
| 78 |
-
protected_right = min(working_w, ear_x_max + x_margin)
|
| 79 |
-
|
| 80 |
-
limited_top_mask = np.zeros_like(ears_mask)
|
| 81 |
-
limited_top_mask[top_start:ear_top_y + 8, protected_left:protected_right] = 1
|
| 82 |
-
kernel_h = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (17, 5))
|
| 83 |
-
limited_top_mask = cv2.dilate(limited_top_mask, kernel_h, iterations=1)
|
| 84 |
-
|
| 85 |
-
ears_protected = np.logical_or(ears_protected, limited_top_mask).astype(np.uint8)
|
| 86 |
-
|
| 87 |
-
hair_above_ears = np.zeros_like(hair_mask)
|
| 88 |
-
above_ear_line = max(0, ear_top_y - int(ear_height * 0.65))
|
| 89 |
-
hair_above_ears[:above_ear_line, :] = hair_mask[:above_ear_line, :]
|
| 90 |
-
ears_protected[hair_above_ears == 1] = 0
|
| 91 |
else:
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
hair_mask_final = hair_mask.copy()
|
| 95 |
-
hair_mask_final[ears_protected == 1] = 0
|
| 96 |
-
|
| 97 |
-
if hair_mask[:int(working_h * 0.25), :].sum() > 60:
|
| 98 |
-
hair_mask_final[:int(working_h * 0.25), :] = np.maximum(
|
| 99 |
-
hair_mask_final[:int(working_h * 0.25), :], hair_mask[:int(working_h * 0.25), :]
|
| 100 |
-
)
|
| 101 |
-
|
| 102 |
-
kernel_s = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (13, 13))
|
| 103 |
-
hair_mask_final = cv2.morphologyEx(hair_mask_final, cv2.MORPH_CLOSE, kernel_s, iterations=2)
|
| 104 |
-
hair_mask_final = cv2.dilate(hair_mask_final, kernel_s, iterations=1)
|
| 105 |
-
|
| 106 |
-
blurred = cv2.GaussianBlur(hair_mask_final.astype(np.float32), (9, 9), 3)
|
| 107 |
-
hair_mask_final = (blurred > 0.28).astype(np.uint8)
|
| 108 |
-
|
| 109 |
-
kernel_edge = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
| 110 |
-
hair_mask_final = cv2.dilate(hair_mask_final, kernel_edge, iterations=1)
|
| 111 |
-
|
| 112 |
-
hair_pixels = np.sum(hair_mask_final)
|
| 113 |
-
logger.info(f"Hair pixels (resized): {hair_pixels:,}")
|
| 114 |
-
|
| 115 |
-
final_mask = hair_mask_final.copy()
|
| 116 |
-
use_extended_mask = False
|
| 117 |
-
if hair_pixels > 380000:
|
| 118 |
-
logger.info("Large hair → extended mask")
|
| 119 |
-
use_extended_mask = True
|
| 120 |
-
big_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (25, 25))
|
| 121 |
-
extended = cv2.dilate(hair_mask_final, big_kernel, iterations=1)
|
| 122 |
-
upper = np.zeros_like(hair_mask_final)
|
| 123 |
-
upper_end = int(working_h * 0.48)
|
| 124 |
-
upper[:upper_end, :] = 1
|
| 125 |
-
extended = np.logical_or(extended, upper).astype(np.uint8)
|
| 126 |
-
extended[ears_protected == 1] = 0
|
| 127 |
-
|
| 128 |
-
if np.mean(working_np) < 110:
|
| 129 |
-
hsv = cv2.cvtColor(working_np, cv2.COLOR_RGB2HSV)
|
| 130 |
-
dark_lower = np.array([0, 0, 0])
|
| 131 |
-
dark_upper = np.array([180, 70, 90])
|
| 132 |
-
dark_mask = cv2.inRange(hsv, dark_lower, dark_upper)
|
| 133 |
-
extended = np.logical_or(extended, (dark_mask > 127)).astype(np.uint8)
|
| 134 |
-
|
| 135 |
-
extended = cv2.morphologyEx(extended, cv2.MORPH_CLOSE, kernel_s, iterations=1)
|
| 136 |
-
extended[int(working_h * 0.75):, :] = 0
|
| 137 |
-
final_mask = extended
|
| 138 |
-
|
| 139 |
-
if use_extended_mask or hair_pixels > 420000:
|
| 140 |
-
radius, flag = 18, cv2.INPAINT_TELEA
|
| 141 |
-
elif hair_pixels > 220000:
|
| 142 |
-
radius, flag = 15, cv2.INPAINT_TELEA
|
| 143 |
-
else:
|
| 144 |
-
radius, flag = 10, cv2.INPAINT_NS
|
| 145 |
-
|
| 146 |
-
logger.info(f"Inpainting radius={radius}")
|
| 147 |
-
inpainted_bgr = cv2.inpaint(working_bgr, final_mask * 255, inpaintRadius=radius, flags=flag)
|
| 148 |
-
inpainted_rgb = cv2.cvtColor(inpainted_bgr, cv2.COLOR_BGR2RGB)
|
| 149 |
-
|
| 150 |
-
result_small = working_np.copy()
|
| 151 |
-
result_small[final_mask == 1] = inpainted_rgb[final_mask == 1]
|
| 152 |
-
|
| 153 |
-
if use_extended_mask or hair_pixels > 280000:
|
| 154 |
-
logger.info("Skin color correction")
|
| 155 |
-
regions = [(0.18, 0.30, 0.34, 0.66), (0.32, 0.47, 0.35, 0.65)]
|
| 156 |
-
colors = []
|
| 157 |
-
for y1r, y2r, x1r, x2r in regions:
|
| 158 |
-
y1, y2 = int(working_h * y1r), int(working_h * y2r)
|
| 159 |
-
x1, x2 = int(working_w * x1r), int(working_w * x2r)
|
| 160 |
-
if y2 > y1 + 40 and x2 > x1 + 80:
|
| 161 |
-
crop = working_np[y1:y2, x1:x2]
|
| 162 |
-
if crop.size > 0:
|
| 163 |
-
colors.append(np.median(crop, axis=(0,1)).astype(np.float32))
|
| 164 |
-
|
| 165 |
-
if colors:
|
| 166 |
-
target_color = np.mean(colors, axis=0)
|
| 167 |
-
brightness = np.mean(target_color)
|
| 168 |
-
strength = 0.82 if brightness > 145 else 0.62 if brightness < 85 else 0.74
|
| 169 |
-
bald_area = result_small[final_mask == 1].astype(np.float32)
|
| 170 |
-
if len(bald_area) > 200:
|
| 171 |
-
current_mean = bald_area.mean(axis=0)
|
| 172 |
-
diff = target_color - current_mean
|
| 173 |
-
corrected = np.clip(bald_area + diff * strength, 0, 255).astype(np.uint8)
|
| 174 |
-
result_small[final_mask == 1] = corrected
|
| 175 |
-
|
| 176 |
-
if hair_pixels > 90000 or use_extended_mask:
|
| 177 |
-
blurred_bald = cv2.GaussianBlur(result_small, (5, 5), 0.8)
|
| 178 |
-
result_small[final_mask == 1] = cv2.addWeighted(
|
| 179 |
-
result_small[final_mask == 1], 0.65, blurred_bald[final_mask == 1], 0.35, 0
|
| 180 |
-
)
|
| 181 |
-
|
| 182 |
-
if scale_factor < 1.0:
|
| 183 |
-
logger.info("Upscaling to original size")
|
| 184 |
-
result = cv2.resize(result_small, (orig_w, orig_h), interpolation=cv2.INTER_LANCZOS4)
|
| 185 |
-
else:
|
| 186 |
-
result = result_small
|
| 187 |
-
|
| 188 |
-
result_pil = Image.fromarray(result)
|
| 189 |
-
|
| 190 |
-
comparison = np.hstack((original_np, result))
|
| 191 |
-
comparison_pil = Image.fromarray(comparison)
|
| 192 |
-
|
| 193 |
-
final_mask_big = cv2.resize(final_mask.astype(np.uint8) * 255, (orig_w, orig_h), cv2.INTER_NEAREST) > 127
|
| 194 |
-
mask_vis = np.zeros_like(original_np)
|
| 195 |
-
mask_vis[final_mask_big] = [255, 70, 70]
|
| 196 |
-
mask_overlay = cv2.addWeighted(original_np, 0.78, mask_vis, 0.22, 0)
|
| 197 |
-
mask_pil = Image.fromarray(mask_overlay)
|
| 198 |
-
|
| 199 |
-
return result_pil, comparison_pil, mask_pil
|
| 200 |
-
|
| 201 |
except Exception as e:
|
| 202 |
-
|
| 203 |
-
raise gr.Error(f"Processing failed: {str(e)}. Try smaller image.")
|
| 204 |
-
|
| 205 |
-
with gr.Blocks(title="Make Me Bald 🧑🦲", theme=gr.themes.Soft()) as demo:
|
| 206 |
-
gr.Markdown("# Realistic Bald Maker 🔥")
|
| 207 |
-
gr.Markdown("Upload face photo → get bald version with natural skin blending. Ears protected, no weird halos!")
|
| 208 |
-
|
| 209 |
-
with gr.Row():
|
| 210 |
-
input_img = gr.Image(type="pil", label="Your Photo", sources=["upload", "webcam"])
|
| 211 |
-
output_bald = gr.Image(label="Bald Version")
|
| 212 |
-
|
| 213 |
-
with gr.Row():
|
| 214 |
-
comparison = gr.Image(label="Before vs After")
|
| 215 |
-
mask_overlay = gr.Image(label="Hair Mask Overlay (red = removed area)")
|
| 216 |
-
|
| 217 |
-
btn = gr.Button("Make Bald 😎", variant="primary")
|
| 218 |
-
|
| 219 |
-
btn.click(
|
| 220 |
-
fn=make_realistic_bald,
|
| 221 |
-
inputs=input_img,
|
| 222 |
-
outputs=[output_bald, comparison, mask_overlay],
|
| 223 |
-
api_name="make_bald"
|
| 224 |
-
)
|
| 225 |
-
|
| 226 |
-
gr.Examples(
|
| 227 |
-
examples=[["example1.jpg"], ["example2.jpg"]], # agar examples folder mein daale to
|
| 228 |
-
inputs=input_img,
|
| 229 |
-
label="Try these examples"
|
| 230 |
-
)
|
| 231 |
-
|
| 232 |
-
gr.Markdown("""
|
| 233 |
-
**Tips:**
|
| 234 |
-
- Best results on clear front-facing photos.
|
| 235 |
-
- Large images auto-resized for speed (then upscaled).
|
| 236 |
-
- If no hair detected → try another photo.
|
| 237 |
-
""")
|
| 238 |
|
| 239 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
# main_fastapi.py
|
| 2 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 3 |
+
from fastapi.responses import StreamingResponse
|
| 4 |
+
import io
|
| 5 |
+
from bald_processor import make_realistic_bald
|
|
|
|
|
|
|
| 6 |
|
| 7 |
+
app = FastAPI(title="Make Me Bald API 😎")
|
|
|
|
| 8 |
|
| 9 |
+
@app.post("/make-bald/")
|
| 10 |
+
async def bald_endpoint(file: UploadFile = File(...)):
|
| 11 |
+
if not file.content_type.startswith("image/"):
|
| 12 |
+
raise HTTPException(status_code=400, detail="Sirf image file upload kar!")
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
try:
|
| 15 |
+
contents = await file.read()
|
| 16 |
+
from PIL import Image
|
| 17 |
+
image = Image.open(io.BytesIO(contents)).convert("RGB")
|
| 18 |
+
bald_img = make_realistic_bald(image)
|
| 19 |
+
buf = io.BytesIO()
|
| 20 |
+
bald_img.save(buf, format="JPEG")
|
| 21 |
+
buf.seek(0)
|
| 22 |
+
return StreamingResponse(buf, media_type="image/jpeg", headers={"Content-Disposition":"attachment; filename=bald.jpg"})
|
| 23 |
+
except ValueError as ve:
|
| 24 |
+
if str(ve) == "NO_HAIR_DETECTED":
|
| 25 |
+
raise HTTPException(400, detail="NO_HAIR_DETECTED")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
@app.get("/")
|
| 32 |
+
def home():
|
| 33 |
+
return {"message": "Bald banne aaya? POST /make-bald/ pe image daal!"}
|