Spaces:
Running on Zero
Running on Zero
Update faceless_processing.py
Browse files1234563 unmodified lines10111213141556 unmodified lines7273747576777879808122 unmodified lines10410510610710810917 unmodified lines1271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611625 unmodified lines16816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020118 unmodified lines22022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827933 unmodified lines3133143153163173183193203213228 unmodified lines3313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813829 unmodified lines3923933943953963973983994004014024032 unmodified lines40640740840941041141241341441541641741841942042142242342442542642740 unmodified lines4684694704714724734744753 unmodified lines47948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851912 unmodified lines5325335345355365375385395405415425435445455465475485495505515525535545555565575 unmodified lines5635645655665675685693 unmodified lines57357457557657757857958058158258358458558658758816 unmodified lines6056066076086096106115 unmodified lines6176186196206216226236 unmodified lines6306316326336346356366376386396406416426436446456466476486496506516526536546556566576 unmodified lines66466566666766866967067167267310 unmodified lines68468568668768868969069111 unmodified lines7037047057067077087092 unmodified lines71271371471571671771871972072172230 unmodified lines75375475575675775875976015 unmodified lines776777778779780781import cv2import numpy as npfrom PIL import Image, ImageFilter, ImageOpsfrom dataclasses import dataclassfrom typing import Tuple, Optionalimport io3 unmodified linesfrom rembg import remove, new_sessionimport threadingtry:from scipy.interpolate import splprep, splev_SCIPY_AVAILABLE = True56 unmodified linescascade_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cascades")os.makedirs(cascade_dir, exist_ok=True)xml_urls = {'haarcascade_frontalface_default.xml': 'https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml','haarcascade_frontalface_alt2.xml': 'https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_alt2.xml','haarcascade_profileface.xml': 'https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_profileface.xml'}for name, url in xml_urls.items():path = os.path.join(cascade_dir, name)if not os.path.exists(path) or os.path.getsize(path) < 1000:22 unmodified linesget_lineart_detector()@dataclassclass LineartConfig:# Backward compatibility fields17 unmodified linesmask_smooth_threshold: int = 128min_silhouette_area: float = 200.0# Silhouette outline — clean, slightly bold for embroidery visibilitysilhouette_line_thickness: int = 3# --- Neural line-art parameters (replace the old Canny block) ---# Resolution the detector runs at. Higher = more/finer detail. 768-1024# gives the clean structural lines (lapels, folds, hair) seen in the ref.lineart_detect_resolution: int = 1024lineart_image_resolution: int = 1024# coarse=False => detailed model (sk_model2). True => simpler/cleaner lines.lineart_coarse: bool = False# Strength threshold: only keep line pixels stronger than this (0-255).# Lower = keep more faint lines (more detail like face shape / hair strands).lineart_threshold: int = 14# Minimum contour length (px) to keep — removes speckle noise.# Low value preserves short strokes (eyebrows, hair locks, jaw line).lineart_min_perimeter: float = 8.0# How much to erode the subject mask before keeping interior lines.# Smaller = keeps lines closer to the silhouette (face outline, hair edge).interior_erode_size: int = 3# Final interior stroke thickness.interior_line_thickness: int = 2# ---- Canny fallback params (only used if controlnet_aux is missing) ----canny_low: int = 40canny_high: int = 130bilateral_d: int = 11bilateral_sigma_color: int = 110bilateral_sigma_space: int = 110gaussian_ksize: int = 11min_contour_perimeter: float = 65.0min_embroidery_stitch_px: int = 25enable_detail_pass: bool = Falsedetail_canny_low: int = 155 unmodified lines# Face detectionface_scale_factor: float = 1.05face_min_neighbors: int = 2face_min_size: Tuple[int, int] = (15, 15)face_max_y_ratio: float = 0.90face_nms_iou_thresh: float = 0.35face_max_count: int = 6# Face erase ellipse — covers ONLY eyes/nose/mouth zone (keeps eyebrows/chin)face_cx_ratio: float = 0.50face_cy_ratio: float = 0.46face_rx_ratio: float = 0.27face_ry_ratio: float = 0.19face_erase_blur: int = 5face_erase_threshold: int = 90# MediaPipemediapipe_num_faces: int = 6# Eyebrow drawing ��� subtle (per user request)eyebrow_thickness: int = 2eyebrow_dilate: int = 0# Face shape (head/jaw outline). Draws the MediaPipe face oval so the# "formato do rosto" is visible while the centre stays faceless.draw_face_oval: bool = Trueface_oval_thickness: int = 2# Skip the very top of the oval (forehead) so the line doesn't cut across# the hair. 0.0 = draw full oval, 0.25 = skip top 25% (recommended).face_oval_skip_top_ratio: float = 0.18def _nms_faces(faces: list, iou_thresh: float) -> list:18 unmodified linesreturn [faces[i] for i in keep]def _load_cascade(cascade_dir: str, name: str) -> Optional[cv2.CascadeClassifier]:"""Load a Haar cascade from the local dir, falling back to OpenCV's builtin."""local = os.path.join(cascade_dir, name)if os.path.exists(local):c = cv2.CascadeClassifier(local)if not c.empty():return cbuiltin = cv2.CascadeClassifier(cv2.data.haarcascades + name)return builtin if not builtin.empty() else Nonedef detect_faces(rgb: np.ndarray, cfg: LineartConfig) -> list:h, w = rgb.shape[:2]gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))gray_eq = clahe.apply(gray)gray_flip = cv2.flip(gray_eq, 1) # mirror, for the other-facing profilefaces = []try:cascade_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cascades")frontal = [c for c in (_load_cascade(cascade_dir, 'haarcascade_frontalface_default.xml'),_load_cascade(cascade_dir, 'haarcascade_frontalface_alt2.xml'),) if c is not None]profile = _load_cascade(cascade_dir, 'haarcascade_profileface.xml')# --- Frontal faces (raw + CLAHE) ---for cascade in frontal:for img_gray in (gray, gray_eq):detected = cascade.detectMultiScale(img_gray,scaleFactor=cfg.face_scale_factor,minNeighbors=cfg.face_min_neighbors,minSize=cfg.face_min_size)if len(detected) > 0:faces.extend(detected.tolist())# --- Profile faces (side view). The cascade only detects faces looking# one direction, so run it on the image AND its mirror, remapping x. ---if profile is not None and not profile.empty():# left-facing profilesfor (fx, fy, fw, fh) in profile.detectMultiScale(gray_eq, scaleFactor=cfg.face_scale_factor,minNeighbors=cfg.face_min_neighbors, minSize=cfg.face_min_size):faces.append([int(fx), int(fy), int(fw), int(fh)])# right-facing profiles (detected on the mirror, x flipped back)for (fx, fy, fw, fh) in profile.detectMultiScale(gray_flip, scaleFactor=cfg.face_scale_factor,minNeighbors=cfg.face_min_neighbors, minSize=cfg.face_min_size):faces.append([int(w - fx - fw), int(fy), int(fw), int(fh)])except Exception as e:print(f"[AI] Face detection failed or cascades unavailable: {e}")faces = [f for f in faces if f[1] < h * cfg.face_max_y_ratio]faces = _nms_faces(faces, cfg.face_nms_iou_thresh)max_faces = getattr(cfg, 'face_max_count', 6)33 unmodified linesdef build_silhouette(subject_mask: np.ndarray, cfg: LineartConfig) -> np.ndarray:mask = subject_mask.copy()if cfg.mask_smooth_ksize > 1:k = max(21, cfg.mask_smooth_ksize if cfg.mask_smooth_ksize % 2 == 1 else cfg.mask_smooth_ksize + 1)mask = cv2.GaussianBlur(mask, (k, k), 0)_, mask = cv2.threshold(mask, cfg.mask_smooth_threshold, 255, cv2.THRESH_BINARY)k_close = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 9))mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, k_close, iterations=2)8 unmodified linescolor=255, thickness=cfg.silhouette_line_thickness,lineType=cv2.LINE_AA)else:eps = 0.0003 * cv2.arcLength(cnt, True)approx = cv2.approxPolyDP(cnt, eps, True)cv2.drawContours(silhouette, [approx], -1, 255,cfg.silhouette_line_thickness, lineType=cv2.LINE_AA)return silhouettedef build_face_erase_mask(faces: list, shape: Tuple[int, int], cfg: LineartConfig) -> np.ndarray:h, w = shapemask = np.zeros((h, w), dtype=np.uint8)for (fx, fy, fw, fh) in faces:cx = int(fx + fw * cfg.face_cx_ratio)cy = int(fy + fh * cfg.face_cy_ratio)rx = int(fw * cfg.face_rx_ratio)ry = int(fh * cfg.face_ry_ratio)cv2.ellipse(mask, (cx, cy), (rx, ry), 0, 0, 360, 255, -1)soft = np.array(Image.fromarray(mask).filter(ImageFilter.GaussianBlur(cfg.face_erase_blur)))return (soft > cfg.face_erase_threshold).astype(np.uint8) * 255def _line_strength_from_detector(pil_lineart: Image.Image, target_hw: Tuple[int, int]) -> np.ndarray:"""Convert the detector output into a polarity-normalised "line strength" mapwhere lines = bright (255) on a black (0) background, resized to target.Handles either polarity (black-on-white or white-on-black)."""h, w = target_hwgray = np.array(pil_lineart.convert("L"))# Determine background from the image cornerscorners = [gray[0, 0], gray[0, -1], gray[-1, 0], gray[-1, -1]]bg = float(np.median(corners))if bg > 127:strength = 255 - gray # dark lines on light bg -> invertelse:strength = gray # already light lines on dark bgif strength.shape[:2] != (h, w):strength = cv2.resize(strength, (w, h), interpolation=cv2.INTER_LINEAR)return strength.astype(np.uint8)def build_interior_edges(rgb: np.ndarray, subject_mask: np.ndarray, cfg: LineartConfig) -> np.ndarray:"""Detect structural lines (clothing folds, lapels, collars, cuffs, hair) usingthe neural LineartDetector. Produces continuous, illustrator-style strokes.Falls back to the legacy Canny pipeline if controlnet_aux is unavailable."""h, w = rgb.shape[:2]detector = get_lineart_detector()9 unmodified lines)strength = _line_strength_from_detector(pil_out, (h, w))# Threshold to a binary line map_, edges = cv2.threshold(strength, cfg.lineart_threshold, 255, cv2.THRESH_BINARY)# Keep lines only inside the subject. Use a SMALL erosion so that# face-shape, hairline and jaw lines (which sit close to the# silhouette) are preserved instead of being eaten away.erode_size = getattr(cfg, 'interior_erode_size', 3)erode_size = max(1, erode_size)if erode_size % 2 == 0:2 unmodified lineseroded_mask = cv2.erode(subject_mask, kernel_erode, iterations=1)edges = cv2.bitwise_and(edges, eroded_mask)# Remove speckle: drop tiny contourscontours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)filtered = np.zeros_like(edges)for cnt in contours:if cv2.arcLength(cnt, False) < cfg.lineart_min_perimeter:continuecv2.drawContours(filtered, [cnt], -1, 255, cfg.interior_line_thickness)# Gentle dilation for solid, embroiderable strokeskernel_dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))filtered = cv2.dilate(filtered, kernel_dilate, iterations=1)return filteredexcept Exception as e:print(f"[AI] Neural lineart failed, falling back to Canny: {e}")# ---------------- Legacy Canny fallback ----------------return _build_interior_edges_canny(rgb, subject_mask, cfg)40 unmodified linesoutput_face_blendshapes=False,output_facial_transformation_matrixes=False,num_faces=num_faces,# Lower confidence thresholds so smiling / tilted / smaller faces# are still detected and their eyebrows get drawn.min_face_detection_confidence=0.2,min_face_presence_confidence=0.2,min_tracking_confidence=0.2,3 unmodified linesreturn _LANDMARKER_CACHEdef _draw_eyebrows_geometric(eyebrows_layer: np.ndarray, faces: list, cfg: LineartConfig) -> np.ndarray:"""Fallback used when MediaPipe (OpenGL) fails to load on the Space.Draws approximate eyebrows + a jaw/chin arc from the Haar cascade boundingbox using standard facial proportions, so these details are NEVER missing."""eb_th = max(2, getattr(cfg, 'eyebrow_thickness', 2))oval_th = max(1, getattr(cfg, 'face_oval_thickness', 1))draw_oval = getattr(cfg, 'draw_face_oval', True)count = 0for (fx, fy, fw, fh) in faces:# Eyebrows: horizontal band around 30% of face height, slight upward arceb_y = int(fy + fh * 0.30)lift = int(fh * 0.04)left = (int(fx + fw * 0.18), int(fx + fw * 0.44))right = (int(fx + fw * 0.56), int(fx + fw * 0.82))for (xa, xb) in (left, right):mx = (xa + xb) // 2pts = np.array([[xa, eb_y], [mx, eb_y - lift], [xb, eb_y]], np.int32)cv2.polylines(eyebrows_layer, [pts.reshape((-1, 1, 2))],isClosed=False, color=255, thickness=eb_th,lineType=cv2.LINE_AA)if draw_oval:# Jaw / chin arc only (lower half of the face) so hair stays freecx = int(fx + fw * 0.50)cy = int(fy + fh * 0.52)rx = int(fw * 0.46)ry = int(fh * 0.50)cv2.ellipse(eyebrows_layer, (cx, cy), (rx, ry), 0, 30, 150,255, oval_th, lineType=cv2.LINE_AA)count += 1print(f"[eyebrows] Geometric fallback drew {count} face(s)")return eyebrows_layerdef draw_eyebrows(rgb: np.ndarray, cfg: LineartConfig, faces: Optional[list] = None) -> np.ndarray:h, w, _ = rgb.shapeeyebrows_layer = np.zeros((h, w), dtype=np.uint8)12 unmodified linesLEFT_EYEBROW = [70, 63, 105, 66, 107, 55, 65, 52, 53, 46]RIGHT_EYEBROW = [336, 296, 334, 293, 300, 285, 295, 282, 283, 276]# MediaPipe face oval (head/jaw outline), ordered around the perimeter.FACE_OVAL = [10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288,397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136,172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109]eyebrow_thickness = getattr(cfg, 'eyebrow_thickness', cfg.interior_line_thickness)draw_oval = getattr(cfg, 'draw_face_oval', True)oval_thickness = getattr(cfg, 'face_oval_thickness', 2)oval_skip_top = getattr(cfg, 'face_oval_skip_top_ratio', 0.18)drawn_centers_px: list = []def is_duplicate_px(cx_px: float, cy_px: float) -> bool:min_dist = min(w, h) * 0.06for (pcx, pcy) in drawn_centers_px:if np.hypot(cx_px - pcx, cy_px - pcy) < min_dist:return Truereturn Falsedef draw_eyebrow_landmarks(face_lms, origin_x, origin_y, scale_x, scale_y):# Eyebrowsfor indices in [LEFT_EYEBROW, RIGHT_EYEBROW]:pts = []for idx in indices:5 unmodified linescv2.polylines(eyebrows_layer, [pts_np], isClosed=False, color=255,thickness=eyebrow_thickness, lineType=cv2.LINE_AA)# Face oval (head / jaw outline) — gives the "formato do rosto"if draw_oval:oval_pts = []for idx in FACE_OVAL:3 unmodified linesoval_pts.append([px, py])oval_np = np.array(oval_pts, np.int32)if len(oval_np) >= 4:# Optionally drop the top (forehead) points so the outline# doesn't cut a hard line across the hair.if oval_skip_top > 0:y_min = oval_np[:, 1].min()y_max = oval_np[:, 1].max()cutoff = y_min + (y_max - y_min) * oval_skip_topkept = oval_np[oval_np[:, 1] >= cutoff]if len(kept) >= 4:# open arc (jaw + cheeks), not closed, to leave the# crown of the head to the hair/silhouette linesarc = kept.reshape((-1, 1, 2))cv2.polylines(eyebrows_layer, [arc], isClosed=False,color=255, thickness=oval_thickness,16 unmodified linesfor face_lms in global_result.face_landmarks:cx_px = np.mean([lm.x for lm in face_lms]) * wcy_px = np.mean([lm.y for lm in face_lms]) * hif not is_duplicate_px(cx_px, cy_px):drawn_centers_px.append((cx_px, cy_px))draw_eyebrow_landmarks(face_lms, 0, 0, w, h)5 unmodified linesif crop_w < 20 or crop_h < 20:continueface_cx_px = (x1 + x2) / 2; face_cy_px = (y1 + y2) / 2if is_duplicate_px(face_cx_px, face_cy_px):continuecrop = rgb[y1:y2, x1:x2]target = max(512, crop_w, crop_h)6 unmodified linesface_lms = crop_result.face_landmarks[0]cx_px2 = x1 + np.mean([lm.x for lm in face_lms]) * crop_wcy_px2 = y1 + np.mean([lm.y for lm in face_lms]) * crop_hif is_duplicate_px(cx_px2, cy_px2):continuedrawn_centers_px.append((cx_px2, cy_px2))draw_eyebrow_landmarks(face_lms, x1, y1, crop_w, crop_h)print(f"[eyebrows] Drew eyebrows for {len(drawn_centers_px)} face(s)")# If MediaPipe ran but found no faces, use the geometric fallback so# eyebrows / face shape are still present.if not drawn_centers_px:if faces is None:faces = detect_faces(rgb, cfg)if faces:eyebrows_layer = _draw_eyebrows_geometric(eyebrows_layer, faces, cfg)except Exception as e:print(f"[AI] Eyebrow extraction error or library missing: {e}")# MediaPipe failed to load (e.g. libGLESv2 missing). Fall back to the# geometric approximation from the Haar cascade boxes.if faces is None:faces = detect_faces(rgb, cfg)if faces:eyebrows_layer = _draw_eyebrows_geometric(eyebrows_layer, faces, cfg)if eyebrows_layer.any():dil = getattr(cfg, 'eyebrow_dilate', 1)6 unmodified linesdef make_faceless_lineart(img: Image.Image, cfg: LineartConfig = None) -> Image.Image:cfg = cfg or LineartConfig()# Honour EXIF orientation (phone photos). Without this, photos with an# orientation tag are processed sideways and end up rotated/cropped.img = ImageOps.exif_transpose(img)alpha_channel: Optional[np.ndarray] = Noneif img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):rgba_img = img.convert("RGBA")10 unmodified linesrgb = img_np[:, :, :3]h, w = rgb.shape[:2]# If no alpha was provided, derive a subject mask with rembg for a clean# silhouette and to confine interior lines to the subject.if alpha_channel is None and _SESSION_ISNET is not None:try:cut = remove(Image.fromarray(rgb).convert("RGBA"), session=_SESSION_ISNET, only_mask=True)11 unmodified linessilhouette = build_silhouette(subject_mask, cfg)interior = build_interior_edges(rgb, subject_mask, cfg)face_erase = build_face_erase_mask(faces, (h, w), cfg)interior_clean = cv2.bitwise_and(interior, cv2.bitwise_not(face_erase))final_lines = cv2.add(silhouette, interior_clean)2 unmodified lineseyebrows = draw_eyebrows(rgb, cfg, faces=faces)final_lines = cv2.add(final_lines, eyebrows)# Only erase borders if the lines are very close to the edge,# but be careful not to cut off the subject.border_erase_width = 1if border_erase_width > 0:final_lines[0:border_erase_width, :] = 0final_lines[-border_erase_width:, :] = 0final_lines[:, 0:border_erase_width] = 0final_lines[:, -border_erase_width:] = 030 unmodified linesdef remove_background_subject(img: Image.Image) -> Image.Image:try:# Match the lineart orientation so the cutout never ends up rotated/cropped.img = ImageOps.exif_transpose(img)rgba = img.convert("RGBA")if _has_real_transparency(rgba):return rgba15 unmodified linesreturn remove_background_subject(img)def build_faceless_embroidery_assets(img: Image.Image, cfg: Optional[LineartConfig] = None, **kwargs) -> Tuple[Image.Image, Image.Image]:if cfg is None:cfg = LineartConfig()1234563 unmodified lines10111213141516171856 unmodified lines7576777879808182838485868722 unmodified lines11011111211311411511617 unmodified lines1341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631645 unmodified lines17017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120218 unmodified lines22122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630733 unmodified lines3413423433443453463473483493503513523533543558 unmodified lines3643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404419 unmodified lines4514524534544554564574582 unmodified lines46146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149240 unmodified lines5335345355365375383 unmodified lines54254354454554654712 unmodified lines5605615625635645655665675685695705715725735745755765775785795805815825835845 unmodified lines5905915925935945953 unmodified lines59960060160260360460560660760860961016 unmodified lines6276286296306316326336346356365 unmodified lines6426436446456466476486496 unmodified lines6566576586596606616626636646656666676686696706716726 unmodified lines67968068168268368410 unmodified lines69569669769869970011 unmodified lines7127137147157167177182 unmodified lines72172272372472572672772872973030 unmodified lines76176276376476576615 unmodified lines782783784785786787788import cv2import numpy as npfrom PIL import Image, ImageFilterfrom dataclasses import dataclassfrom typing import Tuple, Optionalimport io3 unmodified linesfrom rembg import remove, new_sessionimport threadingfrom flask import Flask, request, jsonifyfrom flask_cors import CORStry:from scipy.interpolate import splprep, splev_SCIPY_AVAILABLE = True56 unmodified linescascade_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cascades")os.makedirs(cascade_dir, exist_ok=True)xml_urls = {'haarcascade_frontalface_default.xml': 'https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcape_frontalface_default.xml','haarcascade_frontalface_alt2.xml': 'https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_alt2.xml','haarcascade_profileface.xml': 'https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_profileface.xml'}# Note: Fix frontalface_default URL typo if raw OpenCV has itxml_urls['haarcascade_frontalface_default.xml'] = 'https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml'for name, url in xml_urls.items():path = os.path.join(cascade_dir, name)if not os.path.exists(path) or os.path.getsize(path) < 1000:22 unmodified linesget_lineart_detector()@dataclassclass LineartConfig:# Backward compatibility fields17 unmodified linesmask_smooth_threshold: int = 128min_silhouette_area: float = 200.0# Silhouette outlinesilhouette_line_thickness: int = 4# --- Neural line-art parameters ---lineart_detect_resolution: int = 1024lineart_image_resolution: int = 1024lineart_coarse: bool = True# AUMENTADO: Força bruta para ignorar detalhes fracoslineart_threshold: int = 120# AUMENTADO: Faca implacável para traços curtoslineart_min_perimeter: float = 90.0interior_erode_size: int = 1interior_line_thickness: int = 3# ---- Canny fallback parametros ----canny_low: int = 35canny_high: int = 75bilateral_d: int = 11bilateral_sigma_color: int = 110bilateral_sigma_space: int = 110gaussian_ksize: int = 11min_contour_perimeter: float = 15.0min_embroidery_stitch_px: int = 25enable_detail_pass: bool = Falsedetail_canny_low: int = 155 unmodified lines# Face detectionface_scale_factor: float = 1.05face_min_neighbors: int = 3face_min_size: Tuple[int, int] = (20, 20)face_max_y_ratio: float = 0.65face_nms_iou_thresh: float = 0.55face_max_count: int = 6# Face erase ellipseface_cx_ratio: float = 0.50face_cy_ratio: float = 0.50face_rx_ratio: float = 0.44face_ry_ratio: float = 0.46face_erase_blur: int = 5face_erase_threshold: int = 90# MediaPipemediapipe_num_faces: int = 6# --- AJUSTE DE SOBRANCELHA ---eyebrow_thickness: int = 2eyebrow_dilate: int = 0# Face shapedraw_face_oval: bool = Trueface_oval_thickness: int = 3# AJUSTE FINO: Remove 45% do topo do oval (o que causava aquele erro bizarro)face_oval_skip_top_ratio: float = 0.45def _nms_faces(faces: list, iou_thresh: float) -> list:18 unmodified linesreturn [faces[i] for i in keep]def detect_faces(rgb: np.ndarray, cfg: LineartConfig) -> list:h, w = rgb.shape[:2]faces = []# 1. MediaPipe face detection (highly robust for profile/side/tilted faces)try:import mediapipe as mpmodel_path = cfg.mediapipe_model_pathif not model_path or not os.path.exists(model_path):model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")model_path = os.path.join(model_dir, "face_landmarker.task")if os.path.exists(model_path):num_faces = getattr(cfg, 'mediapipe_num_faces', 6)with _LANDMARKER_LOCK:landmarker = get_landmarker(model_path, num_faces=num_faces)mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)mp_result = landmarker.detect(mp_image)if mp_result.face_landmarks:for face_lms in mp_result.face_landmarks:xs = [lm.x * w for lm in face_lms]ys = [lm.y * h for lm in face_lms]min_x, max_x = min(xs), max(xs)min_y, max_y = min(ys), max(ys)bw = max_x - min_xbh = max_y - min_ypad_x = bw * 0.15pad_y = bh * 0.15fx = int(max(0, min_x - pad_x))fy = int(max(0, min_y - pad_y))fw = int(min(w - fx, bw + 2 * pad_x))fh = int(min(h - fy, bh + 2 * pad_y))faces.append([fx, fy, fw, fh])except Exception as mp_err:print(f"[AI] MediaPipe face detection failed in detect_faces: {mp_err}")# 2. Haar Cascades (frontal and profile)try:gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))gray_eq = clahe.apply(gray)cascade_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cascades")path_default = os.path.join(cascade_dir, 'haarcascade_frontalface_default.xml')path_alt = os.path.join(cascade_dir, 'haarcascade_frontalface_alt2.xml')path_profile = os.path.join(cascade_dir, 'haarcascade_profileface.xml')classifiers = []if os.path.exists(path_default):classifiers.append(cv2.CascadeClassifier(path_default))if os.path.exists(path_alt):classifiers.append(cv2.CascadeClassifier(path_alt))if os.path.exists(path_profile):classifiers.append(cv2.CascadeClassifier(path_profile))if not classifiers or all(c.empty() for c in classifiers):classifiers = [cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'),cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_alt2.xml'),cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_profileface.xml')]for cascade in classifiers:if cascade and not cascade.empty():for img_gray in [gray, gray_eq]:detected = cascade.detectMultiScale(img_gray,scaleFactor=cfg.face_scale_factor,minNeighbors=cfg.face_min_neighbors,minSize=cfg.face_min_size)if detected is not None and len(detected) > 0:faces.extend(detected.tolist())except Exception as e:print(f"[AI] Haar Cascade face detection failed: {e}")# 3. Filter and Deduplicatefaces = [f for f in faces if f[1] < h * cfg.face_max_y_ratio]faces = _nms_faces(faces, cfg.face_nms_iou_thresh)max_faces = getattr(cfg, 'face_max_count', 6)33 unmodified linesdef build_silhouette(subject_mask: np.ndarray, cfg: LineartConfig) -> np.ndarray:mask = subject_mask.copy()h, w = mask.shape[:2]# Dynamic proportional smoothing based on image size to eliminate jaggies completelyk = int(max(w, h) * 0.035)if k % 2 == 0:k += 1k = max(25, k)mask = cv2.GaussianBlur(mask, (k, k), 0)_, mask = cv2.threshold(mask, cfg.mask_smooth_threshold, 255, cv2.THRESH_BINARY)k_close = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 9))mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, k_close, iterations=2)8 unmodified linescolor=255, thickness=cfg.silhouette_line_thickness,lineType=cv2.LINE_AA)else:eps = 0.0012 * cv2.arcLength(cnt, True)approx = cv2.approxPolyDP(cnt, eps, True)cv2.drawContours(silhouette, [approx], -1, 255,cfg.silhouette_line_thickness, lineType=cv2.LINE_AA)return silhouettedef build_face_erase_mask(rgb: np.ndarray, faces: list, cfg: LineartConfig) -> np.ndarray:h, w = rgb.shape[:2]mask = np.zeros((h, w), dtype=np.uint8)# 1. Exact polygon face erasure using MediaPipe FACE_OVAL landmarks (100% covers mouth/smile/eyes/nose exactly)has_mp_erase = Falsetry:import mediapipe as mpmodel_path = cfg.mediapipe_model_pathif not model_path or not os.path.exists(model_path):model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")model_path = os.path.join(model_dir, "face_landmarker.task")if os.path.exists(model_path):num_faces = getattr(cfg, 'mediapipe_num_faces', 6)with _LANDMARKER_LOCK:landmarker = get_landmarker(model_path, num_faces=num_faces)mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)mp_result = landmarker.detect(mp_image)if mp_result.face_landmarks:FACE_OVAL = [10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288,397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136,172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109]for face_lms in mp_result.face_landmarks:pts = []for idx in FACE_OVAL:lm = face_lms[idx]px = int(lm.x * w)py = int(lm.y * h)pts.append([px, py])pts_np = np.array(pts, np.int32).reshape((-1, 1, 2))cv2.fillPoly(mask, [pts_np], 255)has_mp_erase = Trueexcept Exception as mp_err:print(f"[AI] MediaPipe face contour polygon erase failed: {mp_err}")# 2. Bounding-box Ellipse Fallback (if MediaPipe fails or finds no faces)if not has_mp_erase or not np.any(mask):for (fx, fy, fw, fh) in faces:cx = int(fx + fw * cfg.face_cx_ratio)cy = int(fy + fh * cfg.face_cy_ratio)rx = int(fw * cfg.face_rx_ratio)ry = int(fh * cfg.face_ry_ratio)cv2.ellipse(mask, (cx, cy), (rx, ry), 0, 0, 360, 255, -1, lineType=cv2.LINE_AA)soft = np.array(Image.fromarray(mask).filter(ImageFilter.GaussianBlur(cfg.face_erase_blur)))return (soft > cfg.face_erase_threshold).astype(np.uint8) * 255def _line_strength_from_detector(pil_lineart: Image.Image, target_hw: Tuple[int, int]) -> np.ndarray:h, w = target_hwgray = np.array(pil_lineart.convert("L"))corners = [gray[0, 0], gray[0, -1], gray[-1, 0], gray[-1, -1]]bg = float(np.median(corners))if bg > 127:strength = 255 - grayelse:strength = grayif strength.shape[:2] != (h, w):strength = cv2.resize(strength, (w, h), interpolation=cv2.INTER_LINEAR)return strength.astype(np.uint8)def build_interior_edges(rgb: np.ndarray, subject_mask: np.ndarray, cfg: LineartConfig) -> np.ndarray:h, w = rgb.shape[:2]detector = get_lineart_detector()9 unmodified lines)strength = _line_strength_from_detector(pil_out, (h, w))_, edges = cv2.threshold(strength, cfg.lineart_threshold, 255, cv2.THRESH_BINARY)erode_size = getattr(cfg, 'interior_erode_size', 3)erode_size = max(1, erode_size)if erode_size % 2 == 0:2 unmodified lineseroded_mask = cv2.erode(subject_mask, kernel_erode, iterations=1)edges = cv2.bitwise_and(edges, eroded_mask)# Aspirador de Sujeiraskernel_clean = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))edges = cv2.morphologyEx(edges, cv2.MORPH_OPEN, kernel_clean, iterations=1)contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)filtered = np.zeros_like(edges)for cnt in contours:perimeter = cv2.arcLength(cnt, False)area = cv2.contourArea(cnt)# BARREIRA EXTREMA: Elimina pontos isolados e traços curtosif perimeter < cfg.lineart_min_perimeter or area < 40.0:continuecv2.drawContours(filtered, [cnt], -1, 255, cfg.interior_line_thickness)kernel_dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))filtered = cv2.dilate(filtered, kernel_dilate, iterations=1)filtered = cv2.GaussianBlur(filtered, (3, 3), 0)_, filtered = cv2.threshold(filtered, 127, 255, cv2.THRESH_BINARY)return filteredexcept Exception as e:print(f"[AI] Neural lineart failed, falling back to Canny: {e}")return _build_interior_edges_canny(rgb, subject_mask, cfg)40 unmodified linesoutput_face_blendshapes=False,output_facial_transformation_matrixes=False,num_faces=num_faces,min_face_detection_confidence=0.2,min_face_presence_confidence=0.2,min_tracking_confidence=0.2,3 unmodified linesreturn _LANDMARKER_CACHEdef draw_eyebrows(rgb: np.ndarray, cfg: LineartConfig, faces: Optional[list] = None) -> np.ndarray:h, w, _ = rgb.shapeeyebrows_layer = np.zeros((h, w), dtype=np.uint8)12 unmodified linesLEFT_EYEBROW = [70, 63, 105, 66, 107, 55, 65, 52, 53, 46]RIGHT_EYEBROW = [336, 296, 334, 293, 300, 285, 295, 282, 283, 276]FACE_OVAL = [10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288,397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136,172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109]eyebrow_thickness = getattr(cfg, 'eyebrow_thickness', cfg.interior_line_thickness)draw_oval = Trueoval_thickness = getattr(cfg, 'face_oval_thickness', 2)oval_skip_top = getattr(cfg, 'face_oval_skip_top_ratio', 0.18)drawn_centers_px: list = []def is_duplicate_px(cx_px: float, cy_px: float, face_size: float = 0.0) -> bool:limit = face_size * 0.35 if face_size > 0 else min(w, h) * 0.02limit = max(15.0, limit)for (pcx, pcy) in drawn_centers_px:if np.hypot(cx_px - pcx, cy_px - pcy) < limit:return Truereturn Falsedef draw_eyebrow_landmarks(face_lms, origin_x, origin_y, scale_x, scale_y):for indices in [LEFT_EYEBROW, RIGHT_EYEBROW]:pts = []for idx in indices:5 unmodified linescv2.polylines(eyebrows_layer, [pts_np], isClosed=False, color=255,thickness=eyebrow_thickness, lineType=cv2.LINE_AA)if draw_oval:oval_pts = []for idx in FACE_OVAL:3 unmodified linesoval_pts.append([px, py])oval_np = np.array(oval_pts, np.int32)if len(oval_np) >= 4:if oval_skip_top > 0:y_min = oval_np[:, 1].min()y_max = oval_np[:, 1].max()cutoff = y_min + (y_max - y_min) * oval_skip_topkept = oval_np[oval_np[:, 1] >= cutoff]if len(kept) >= 4:arc = kept.reshape((-1, 1, 2))cv2.polylines(eyebrows_layer, [arc], isClosed=False,color=255, thickness=oval_thickness,16 unmodified linesfor face_lms in global_result.face_landmarks:cx_px = np.mean([lm.x for lm in face_lms]) * wcy_px = np.mean([lm.y for lm in face_lms]) * hxs = [lm.x * w for lm in face_lms]ys = [lm.y * h for lm in face_lms]fsize = max(max(xs) - min(xs), max(ys) - min(ys))if not is_duplicate_px(cx_px, cy_px, fsize):drawn_centers_px.append((cx_px, cy_px))draw_eyebrow_landmarks(face_lms, 0, 0, w, h)5 unmodified linesif crop_w < 20 or crop_h < 20:continueface_cx_px = (x1 + x2) / 2; face_cy_px = (y1 + y2) / 2fsize = max(fw, fh)if is_duplicate_px(face_cx_px, face_cy_px, fsize):continuecrop = rgb[y1:y2, x1:x2]target = max(512, crop_w, crop_h)6 unmodified linesface_lms = crop_result.face_landmarks[0]cx_px2 = x1 + np.mean([lm.x for lm in face_lms]) * crop_wcy_px2 = y1 + np.mean([lm.y for lm in face_lms]) * crop_hxs2 = [lm.x * crop_w for lm in face_lms]ys2 = [lm.y * crop_h for lm in face_lms]fsize2 = max(max(xs2) - min(xs2), max(ys2) - min(ys2))if is_duplicate_px(cx_px2, cy_px2, fsize2):continuedrawn_centers_px.append((cx_px2, cy_px2))draw_eyebrow_landmarks(face_lms, x1, y1, crop_w, crop_h)print(f"[eyebrows] Drew eyebrows for {len(drawn_centers_px)} face(s)")except Exception as e:print(f"[AI] Eyebrow extraction error or library missing: {e}")if eyebrows_layer.any():dil = getattr(cfg, 'eyebrow_dilate', 1)6 unmodified linesdef make_faceless_lineart(img: Image.Image, cfg: LineartConfig = None) -> Image.Image:cfg = cfg or LineartConfig()alpha_channel: Optional[np.ndarray] = Noneif img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):rgba_img = img.convert("RGBA")10 unmodified linesrgb = img_np[:, :, :3]h, w = rgb.shape[:2]if alpha_channel is None and _SESSION_ISNET is not None:try:cut = remove(Image.fromarray(rgb).convert("RGBA"), session=_SESSION_ISNET, only_mask=True)11 unmodified linessilhouette = build_silhouette(subject_mask, cfg)interior = build_interior_edges(rgb, subject_mask, cfg)face_erase = build_face_erase_mask(rgb, faces, cfg)interior_clean = cv2.bitwise_and(interior, cv2.bitwise_not(face_erase))final_lines = cv2.add(silhouette, interior_clean)2 unmodified lineseyebrows = draw_eyebrows(rgb, cfg, faces=faces)final_lines = cv2.add(final_lines, eyebrows)border_erase_width = max(cfg.silhouette_line_thickness, cfg.interior_line_thickness) + 2if border_erase_width > 0:# Keep top border erase very small (e.g. 1 pixel) to avoid cutting the top of the headfinal_lines[0:1, :] = 0final_lines[-border_erase_width:, :] = 0final_lines[:, 0:border_erase_width] = 0final_lines[:, -border_erase_width:] = 030 unmodified linesdef remove_background_subject(img: Image.Image) -> Image.Image:try:rgba = img.convert("RGBA")if _has_real_transparency(rgba):return rgba15 unmodified linesreturn remove_background_subject(img)def build_faceless_embroidery_assets(img: Image.Image, cfg: Optional[LineartConfig] = None, **kwargs) -> Tuple[Image.Image, Image.Image]:if cfg is None:cfg = LineartConfig()
faceless_processing.py+208-201