Spaces:
Running on Zero
Running on Zero
Update faceless_processing.py
#1
by vitordigitizing - opened
33 unmodified lines343536373839404163 unmodified lines10510610710810911011125 unmodified lines13713813914014114214314414514614714814915015115215315415515631 unmodified lines1881891901911921931941951962 unmodified lines19920020120220320420520657 unmodified lines26426526626726826927021 unmodified lines29229329429529629729829938 unmodified lines3383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683699 unmodified lines3793803813823833843853863873883893902 unmodified lines39339439539639739839940040140240340440540640740840941041141241341441541640 unmodified lines45745845946046146246346421 unmodified lines48648748848949049149212 unmodified lines5055065075085095105115 unmodified lines5175185195205215225233 unmodified lines52752852953053153253353453553653753853954054154277 unmodified lines62062162262362462562662757 unmodified lines68568668768868969069169269317 unmodified lines7117127137147157167173 unmodified lines72172272372433 unmodified lines_LINEART_AVAILABLE = Truedef get_lineart_detector():"""Lazy-load the controlnet_aux LineartDetector (informative-drawings model63 unmodified linesget_lineart_detector()@dataclassclass LineartConfig:# Backward compatibility fields25 unmodified lineslineart_image_resolution: int = 1024lineart_coarse: bool = True# AUMENTADO: Força a ignorar dobras de roupa e focar só na estruturalineart_threshold: int = 100# AJUSTE DE CABELO E CORPO: Diminuído para capturar fios e dobras de roupa.lineart_min_perimeter: float = 70.0# Diminuído para manter os traços mais próximos da borda.interior_erode_size: int = 1# AJUSTE GERAL: Afinado para traços internos mais delicados.interior_line_thickness: int = 2# ---- Canny fallback parametros ----canny_low: int = 35canny_high: int = 7531 unmodified linesmediapipe_num_faces: int = 6# --- AJUSTE DE SOBRANCELHA ---# Reduzido drasticamente para um traço fino e sutil.eyebrow_thickness: int = 2# Zerado (era 1). Isso remove o "borrão" que deixava a sobrancelha grossa demais.eyebrow_dilate: int = 0# Face shape2 unmodified linesface_oval_skip_top_ratio: float = 0.50def _nms_faces(faces: list, iou_thresh: float) -> list:if not faces:return []57 unmodified linesfaces = sorted(faces, key=lambda f: f[2] * f[3], reverse=True)[:max_faces]return facesdef build_subject_mask(rgb: np.ndarray, cfg: LineartConfig, alpha_channel: Optional[np.ndarray] = None) -> np.ndarray:if alpha_channel is not None:21 unmodified linesspline_pts = np.stack([x_new, y_new], axis=1).astype(np.int32)return spline_pts.reshape((-1, 1, 2))except Exception:return None38 unmodified linesdef _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 strokesernel_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}")# ---------------- 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,21 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]12 unmodified linesreturn 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,77 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)57 unmodified linesreturn total > 0 and (visible / total) >= 0.03def remove_background_subject(img: Image.Image) -> Image.Image:try:rgba = img.convert("RGBA")17 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()3 unmodified linescfg.negative_prompt = kwargs["negative_prompt"]lineart = make_faceless_lineart(img, cfg)cutout = make_faceless_cutout(img)return lineart, cutout33 unmodified lines34353637383963 unmodified lines10310410510610710825 unmodified lines13413513613713813914014114214314414514614714831 unmodified lines1801811821831841851862 unmodified lines18919019119219319457 unmodified lines25225325425525625721 unmodified lines27928028128228328438 unmodified lines3233243253263273283293303313323333343353363373383393403413429 unmodified lines3523533543553563573583592 unmodified lines36236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539640 unmodified lines43743843944044144221 unmodified lines46446546646746846912 unmodified lines4824834844854864875 unmodified lines4934944954964974983 unmodified lines50250350450550650750850951051151251377 unmodified lines59159259359459559657 unmodified lines65465565665765865917 unmodified lines6776786796806816823 unmodified lines68668768868933 unmodified lines_LINEART_AVAILABLE = Truedef get_lineart_detector():"""Lazy-load the controlnet_aux LineartDetector (informative-drawings model63 unmodified linesget_lineart_detector()@dataclassclass LineartConfig:# Backward compatibility fields25 unmodified lineslineart_image_resolution: int = 1024lineart_coarse: bool = True# EQUILÍBRIO: 80 é forte o suficiente para ignorar sombra, mas não apaga o rosto.lineart_threshold: int = 80# EQUILÍBRIO: 60 pixels corta fios curtos, preservando linhas estruturais.lineart_min_perimeter: float = 60.0interior_erode_size: int = 1interior_line_thickness: int = 2# ---- Canny fallback parametros ----canny_low: int = 35canny_high: int = 7531 unmodified linesmediapipe_num_faces: int = 6# --- AJUSTE DE SOBRANCELHA ---eyebrow_thickness: int = 2eyebrow_dilate: int = 0# Face shape2 unmodified linesface_oval_skip_top_ratio: float = 0.50def _nms_faces(faces: list, iou_thresh: float) -> list:if not faces:return []57 unmodified linesfaces = sorted(faces, key=lambda f: f[2] * f[3], reverse=True)[:max_faces]return facesdef build_subject_mask(rgb: np.ndarray, cfg: LineartConfig, alpha_channel: Optional[np.ndarray] = None) -> np.ndarray:if alpha_channel is not None:21 unmodified linesspline_pts = np.stack([x_new, y_new], axis=1).astype(np.int32)return spline_pts.reshape((-1, 1, 2))except Exception:return None38 unmodified linesdef _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)# --- O "ASPIRADOR DE PÓ" MATEMÁTICO ---# Remove pontos solitários grossos antes da mediçãokernel_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 dupla: Remove traços menores que 60px E bolinhas grossas.if perimeter < cfg.lineart_min_perimeter or (perimeter < 150 and area < 10.0):continuecv2.drawContours(filtered, [cnt], -1, 255, cfg.interior_line_thickness)# Suavização final para cantos realistas de linha de costurakernel_dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))filtered = cv2.dilate(filtered, kernel_dilate, iterations=1)filtered = cv2.GaussianBlur(filtered, (3, 3), 0)# CORREÇÃO: cv2.threshold retorna uma tupla (_, imagem_resultante)_, 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,21 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]12 unmodified linesreturn 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,77 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)57 unmodified linesreturn total > 0 and (visible / total) >= 0.03def remove_background_subject(img: Image.Image) -> Image.Image:try:rgba = img.convert("RGBA")17 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()3 unmodified linescfg.negative_prompt = kwargs["negative_prompt"]lineart = make_faceless_lineart(img, cfg)cutout = make_faceless_cutout(img)return lineart, cutout
faceless_processing.py+24-59