Spaces:
Running on Zero
Running on Zero
Update faceless_processing.py
Browse files77 unmodified lines7879808182838453 unmodified lines13813914014114214314414514614714814915019 unmodified lines1701711721731741751768 unmodified lines18518618718818919019119219319419519619719819929 unmodified lines2292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592603 unmodified lines2642652662672682692702712722732742751 unmodified line27727827928028128228362 unmodified lines34634734834935035135218 unmodified lines3713723733743753763771 unmodified line37938038138238338438538638738838939039139214 unmodified lines4074084094104114124134144154164171 unmodified line41942042142242342442547 unmodified lines47347447547647747847948048148248348448548648748848949049179 unmodified lines57157257357457557657757857958011 unmodified lines59259359459559659718 unmodified lines61661761861962062162262362461 unmodified lines68668768868969069134 unmodified lines72672772872973073177 unmodified lines}# 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:53 unmodified lineslineart_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 = 319 unmodified linesface_min_neighbors: int = 3face_min_size: Tuple[int, int] = (20, 20)face_max_y_ratio: float = 0.65face_nms_iou_thresh: float = 0.35face_max_count: int = 6# Face erase ellipse8 unmodified linesmediapipe_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:29 unmodified linesif 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}")3 unmodified linesgray = 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))1 unmodified lineclassifiers.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'),62 unmodified linesk = 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)18 unmodified linesdef 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)try:import mediapipe as mp1 unmodified lineif 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,14 unmodified linesfor (fx, fy, fw, fh) in faces:cx = int(fx + fw * cfg.face_cx_ratio)cy = int(fy + fh * cfg.face_cy_ratio)# Ensure coordinates are within image boundariescx_bound = min(max(0, cx), w - 1)cy_bound = min(max(0, cy), h - 1)# Check if the center of this face is already masked# We check a small 9x9 region around the centerroi = mask[max(0, cy_bound-4):min(h, cy_bound+4), max(0, cx_bound-4):min(w, cx_bound+4)]1 unmodified linerx = 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) * 25547 unmodified linesfor 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}")79 unmodified linesdraw_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) -> 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 True11 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:18 unmodified linesisClosed=True, color=255,thickness=oval_thickness, lineType=cv2.LINE_AA)if faces is None:faces = detect_faces(rgb, cfg)with _LANDMARKER_LOCK:num_faces = getattr(cfg, 'mediapipe_num_faces', 6)landmarker = get_landmarker(model_path, num_faces=num_faces)61 unmodified lineselse:img = img.convert("RGB")img_np = np.array(img)rgb = img_np[:, :, :3]h, w = rgb.shape[:2]34 unmodified linesalpha = Image.fromarray(final_lines)transparent = Image.new("RGBA", img.size, (0, 0, 0, 0))transparent.putalpha(alpha)return transparent77 unmodified lines7879808182838453 unmodified lines13813914014114214314414514614714814915019 unmodified lines1701711721731741751761771781798 unmodified lines18818919019119219319419519619719819920020120220320420520620729 unmodified lines2372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672683 unmodified lines2722732742752762772782792802812822831 unmodified line28528628728828929029162 unmodified lines35435535635735835936018 unmodified lines3793803813823833843851 unmodified line38738838939039139239339439539639739839940014 unmodified lines4154164174184194204214224234244251 unmodified line42742842943043143243347 unmodified lines48148248348448548648748848949049149249349449549649749849979 unmodified lines57958058158258358458558658758858959059159259359459559659759859960060160260311 unmodified lines61561661761861962062118 unmodified lines64064164264364464561 unmodified lines70770870971071171271371471571671771871972072172272372472572672772872973034 unmodified lines76576676776876977077177277377477577 unmodified lines}# 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:53 unmodified lineslineart_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 = 319 unmodified linesface_min_neighbors: int = 3face_min_size: Tuple[int, int] = (20, 20)face_max_y_ratio: float = 0.65# AJUSTADO: subimos o limiar de IoU para evitar que rostos próximos# (ex: pai e filho colados na foto) sejam tratados como duplicatas e# eliminados pela supressão de não-máximos.face_nms_iou_thresh: float = 0.5face_max_count: int = 6# Face erase ellipse8 unmodified linesmediapipe_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.45# --- NOVO: padding de segurança para evitar cortar cabeças/membros# encostados na borda da imagem original. Proporcional ao maior lado.border_padding_ratio: float = 0.06border_padding_min_px: int = 20def _nms_faces(faces: list, iou_thresh: float) -> list:29 unmodified linesif 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}")3 unmodified linesgray = 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))1 unmodified lineclassifiers.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'),62 unmodified linesk = 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)18 unmodified linesdef 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)try:import mediapipe as mp1 unmodified lineif 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,14 unmodified linesfor (fx, fy, fw, fh) in faces:cx = int(fx + fw * cfg.face_cx_ratio)cy = int(fy + fh * cfg.face_cy_ratio)# Ensure coordinates are within image boundariescx_bound = min(max(0, cx), w - 1)cy_bound = min(max(0, cy), h - 1)# Check if the center of this face is already masked# We check a small 9x9 region around the centerroi = mask[max(0, cy_bound-4):min(h, cy_bound+4), max(0, cx_bound-4):min(w, cx_bound+4)]1 unmodified linerx = 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) * 25547 unmodified linesfor 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}")79 unmodified linesdraw_oval = Trueoval_thickness = getattr(cfg, 'face_oval_thickness', 2)oval_skip_top = getattr(cfg, 'face_oval_skip_top_ratio', 0.18)if faces is None:faces = detect_faces(rgb, cfg)# --- CORRIGIDO: a distância mínima para considerar dois rostos# como "o mesmo" agora é proporcional ao tamanho médio dos rostos# detectados (e não ao tamanho total da imagem). Em fotos de# família bem enquadradas, rostos próximos (ex: pai e filho# encostados) ficavam sendo descartados como duplicata por causa# de um raio de exclusão grande demais (6% da imagem inteira).if faces:avg_face_size = float(np.mean([max(fw, fh) for (_, _, fw, fh) in faces]))else:avg_face_size = min(w, h) * 0.15min_dist = max(avg_face_size * 0.35, min(w, h) * 0.02)drawn_centers_px: list = []def is_duplicate_px(cx_px: float, cy_px: float) -> bool:for (pcx, pcy) in drawn_centers_px:if np.hypot(cx_px - pcx, cy_px - pcy) < min_dist:return True11 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:18 unmodified linesisClosed=True, color=255,thickness=oval_thickness, lineType=cv2.LINE_AA)with _LANDMARKER_LOCK:num_faces = getattr(cfg, 'mediapipe_num_faces', 6)landmarker = get_landmarker(model_path, num_faces=num_faces)61 unmodified lineselse:img = img.convert("RGB")# --- NOVO: adiciona margem branca ao redor da imagem antes de# processar. Isso evita que cabeças/membros encostados na borda da# foto original sejam "decapitados" pela limpeza de borda no final# da função (border_erase_width), já que agora essa limpeza acontece# dentro do padding, não em cima do sujeito. O padding é removido no# final, devolvendo a imagem com o tamanho original.orig_w, orig_h = img.sizepad = max(cfg.border_padding_min_px, int(max(orig_w, orig_h) * cfg.border_padding_ratio))padded_img = Image.new("RGB", (orig_w + 2 * pad, orig_h + 2 * pad), (255, 255, 255))padded_img.paste(img, (pad, pad))img = padded_imgif alpha_channel is not None:padded_alpha = np.zeros((orig_h + 2 * pad, orig_w + 2 * pad), dtype=np.uint8)padded_alpha[pad:pad + orig_h, pad:pad + orig_w] = alpha_channelalpha_channel = padded_alphaimg_np = np.array(img)rgb = img_np[:, :, :3]h, w = rgb.shape[:2]34 unmodified linesalpha = Image.fromarray(final_lines)transparent = Image.new("RGBA", img.size, (0, 0, 0, 0))transparent.putalpha(alpha)# --- NOVO: remove o padding branco adicionado no início, devolvendo# a imagem no tamanho/enquadramento original do usuário.transparent = transparent.crop((pad, pad, pad + orig_w, pad + orig_h))return transparent
faceless_processing.py+77-33