Download engine.py from keinne/anatomia: direct link, hf CLI and curl.
- Browser
- Download file 8.13 kB
-
https://huggingface.co/spaces/keinne/anatomia/resolve/main/engine.py
- Command line
-
hf download hf://spaces/keinne/anatomia/engine.py
-
curl -L -o engine.py https://huggingface.co/spaces/keinne/anatomia/resolve/main/engine.py
8.13 kB
| """Local CPU face composition; no recognition database or external photo API.""" | |
| from pathlib import Path | |
| import json | |
| import cv2 | |
| import numpy as np | |
| from PIL import Image, ImageOps, ImageDraw, ImageFont | |
| from balloons import normalize_balloons, render_balloons | |
| ROOT = Path(__file__).resolve().parent | |
| MAX_PIXELS = 20_000_000 | |
| Image.MAX_IMAGE_PIXELS = MAX_PIXELS | |
| def slots(): | |
| return json.loads((ROOT / 'assets/slots.json').read_text(encoding='utf-8')) | |
| def painting(): | |
| with Image.open(ROOT / 'assets/painting.jpg') as im: | |
| return np.asarray(im.convert('RGB')).copy() | |
| def load_photo(path): | |
| try: | |
| with Image.open(path) as im: | |
| if im.width * im.height > MAX_PIXELS: | |
| raise ValueError('Foto muito grande. Envie uma imagem de até 20 megapixels.') | |
| im = ImageOps.exif_transpose(im).convert('RGB') | |
| im.thumbnail((1600, 1600)) | |
| if min(im.size) < 80: | |
| raise ValueError('Foto muito pequena. Use uma imagem com pelo menos 80 pixels em cada lado.') | |
| return np.asarray(im).copy() | |
| except (Image.DecompressionBombError, Image.DecompressionBombWarning): | |
| raise ValueError('Foto muito grande. Envie uma imagem de até 20 megapixels.') from None | |
| except (OSError, SyntaxError): | |
| raise ValueError('Não foi possível abrir a foto. Use JPG, PNG ou WEBP.') from None | |
| def detect_landmarks(rgb): | |
| """Exactly one face is required, so uploads never pick the wrong person silently.""" | |
| model = ROOT / 'models/yunet.onnx' | |
| if not model.is_file(): | |
| raise ValueError('Modelo de detecção ausente. Inclua a pasta models do projeto.') | |
| h, w = rgb.shape[:2] | |
| # Instantiate per request: FaceDetectorYN has mutable input dimensions. | |
| detector = cv2.FaceDetectorYN.create(str(model), '', (w, h), 0.75, 0.3, 5000) | |
| _, faces = detector.detect(cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)) | |
| if faces is None or len(faces) == 0: | |
| raise ValueError('Nenhum rosto detectado. Use uma foto nítida, sem óculos escuros, com o rosto maior e bem iluminado.') | |
| if len(faces) != 1: | |
| raise ValueError('Há mais de um rosto na foto. Recorte a imagem para deixar apenas uma pessoa.') | |
| p = faces[0][4:14].reshape(5, 2) | |
| eyes = p[:2][np.argsort(p[:2, 0])] | |
| mouth = p[3:5][np.argsort(p[3:5, 0])] | |
| return np.vstack([eyes, p[2:3], mouth]).astype(np.float32) | |
| def geometry(slot, shape): | |
| h, w = shape[:2] | |
| # Coordinates were manually calibrated on the supplied painting at 1824 x 1368. | |
| scale = np.array([w / 1824, h / 1368], dtype=np.float32) | |
| return np.asarray(slot['landmarks'], np.float32) * scale, np.asarray(slot['polygon'], np.float32) * scale | |
| def face_mask(slot, shape): | |
| _, polygon = geometry(slot, shape) | |
| mask = np.zeros(shape[:2], np.uint8) | |
| cv2.fillPoly(mask, [np.round(polygon).astype(np.int32)], 255) | |
| return mask | |
| def compose_face(base, source, points, slot, harmony=0.75): | |
| target_points, _ = geometry(slot, base.shape) | |
| # Similarity fit preserves facial proportions; a full affine fit can crush | |
| # frontal photos when mapping them to profiles or to the reclining cadaver. | |
| rows, values = [], [] | |
| for (px, py), (tx, ty) in zip(points, target_points): | |
| rows.extend([[px, -py, 1, 0], [py, px, 0, 1]]) | |
| values.extend([tx, ty]) | |
| a, b, tx, ty = np.linalg.lstsq(np.asarray(rows), values, rcond=None)[0] | |
| matrix = np.asarray([[a, -b, tx], [b, a, ty]], dtype=np.float32) | |
| if abs(np.linalg.det(matrix[:, :2])) < 1e-6: | |
| raise ValueError('Não foi possível alinhar este rosto. Tente outra foto.') | |
| h, w = base.shape[:2] | |
| warped = cv2.warpAffine(source, matrix, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REFLECT_101) | |
| coverage = cv2.warpAffine(np.full(source.shape[:2], 255, np.uint8), matrix, (w, h)) | |
| hard = face_mask(slot, base.shape) | |
| region = hard > 0 | |
| if np.count_nonzero((coverage > 240) & region) < 0.90 * np.count_nonzero(region): | |
| raise ValueError('A foto está cortada muito perto do rosto. Envie uma imagem com testa, queixo e laterais visíveis.') | |
| # Work in the face bounding box instead of applying filters to the full canvas. | |
| x, y, bw, bh = cv2.boundingRect(hard) | |
| original = base[y:y+bh, x:x+bw] | |
| photo = warped[y:y+bh, x:x+bw] | |
| local_mask = hard[y:y+bh, x:x+bw] | |
| selected = local_mask > 0 | |
| smooth = cv2.bilateralFilter(photo, 7, 32, 5) | |
| src = cv2.cvtColor(smooth, cv2.COLOR_RGB2LAB).astype(np.float32) | |
| ref = cv2.cvtColor(original, cv2.COLOR_RGB2LAB).astype(np.float32) | |
| # Match palette, preserving source facial contrast within a conservative range. | |
| for c in range(3): | |
| sm, ss = src[:, :, c][selected].mean(), src[:, :, c][selected].std() | |
| tm, ts = ref[:, :, c][selected].mean(), ref[:, :, c][selected].std() | |
| ratio = np.clip(ts / max(ss, 1), 0.65, 1.35) | |
| src[:, :, c] = (src[:, :, c] - sm) * ratio + tm | |
| sigma = max(3, bw / 12) | |
| src_low = cv2.GaussianBlur(src[:, :, 0], (0, 0), sigma) | |
| ref_low = cv2.GaussianBlur(ref[:, :, 0], (0, 0), sigma) | |
| texture = ref[:, :, 0] - cv2.GaussianBlur(ref[:, :, 0], (0, 0), 1.0) | |
| src[:, :, 0] += float(harmony) * (ref_low - src_low) + 0.30 * texture | |
| styled = cv2.cvtColor(np.clip(src, 0, 255).astype(np.uint8), cv2.COLOR_LAB2RGB) | |
| # Feather strictly INSIDE the fixed region; all unselected pixels stay exact. | |
| padded = np.pad(local_mask, 1) | |
| distance = cv2.distanceTransform(padded, cv2.DIST_L2, 5)[1:-1, 1:-1] | |
| alpha = np.clip(distance / max(4, bw * 0.10), 0, 1)[:, :, None] | |
| result = base.copy() | |
| blended = np.round(styled * alpha + original * (1-alpha)).astype(np.uint8) | |
| result[y:y+bh, x:x+bw] = blended | |
| return result | |
| def validate_uploads(paths): | |
| if len(paths) != 9: | |
| raise ValueError('São necessárias exatamente nove posições de upload.') | |
| selected = [(i, path) for i, path in enumerate(paths) if path is not None] | |
| if len(selected) < 2: | |
| raise ValueError('Envie fotos para pelo menos 2 posições antes de gerar.') | |
| return selected | |
| def generate(paths, harmony=0.75, progress=None, balloons=None): | |
| balloon_options = normalize_balloons(balloons) | |
| selected = validate_uploads(paths) | |
| if not 0 <= float(harmony) <= 1: | |
| raise ValueError('A harmonização deve estar entre 0 e 1.') | |
| prepared = [] | |
| # Validate every source first, avoiding silently incomplete results. | |
| for step, (index, path) in enumerate(selected): | |
| if progress: | |
| progress(step / (2 * len(selected)), desc=f'Analisando rosto {index+1}') | |
| try: | |
| photo = load_photo(path) | |
| points = detect_landmarks(photo) | |
| prepared.append((index, photo, points)) | |
| except ValueError as exc: | |
| raise ValueError(f'Rosto {index+1}: {exc}') from None | |
| result = painting() | |
| positions = slots() | |
| for step, (index, photo, points) in enumerate(prepared): | |
| if progress: | |
| progress(0.5 + step / (2 * len(selected)), desc=f'Integrando rosto {index+1}') | |
| try: | |
| result = compose_face(result, photo, points, positions[index], harmony) | |
| except ValueError as exc: | |
| raise ValueError(f'Rosto {index+1}: {exc}') from None | |
| if progress: | |
| progress(1, desc='Concluído') | |
| return render_balloons(Image.fromarray(result), balloon_options, positions) | |
| def numbered_reference(): | |
| im = Image.fromarray(painting()) | |
| draw = ImageDraw.Draw(im) | |
| try: | |
| font = ImageFont.truetype('DejaVuSans-Bold.ttf', 29) | |
| except OSError: | |
| font = ImageFont.load_default() | |
| for slot in slots(): | |
| sx, sy = im.width / 1824, im.height / 1368 | |
| x, y = (slot['badge'][0] * sx, slot['badge'][1] * sy) | |
| target = np.asarray(slot['landmarks']).mean(axis=0) * [sx, sy] | |
| draw.line((x, y, float(target[0]), float(target[1])), fill='#e2c17b', width=3) | |
| draw.ellipse((x-26, y-26, x+26, y+26), fill='#191a17', outline='#e2c17b', width=3) | |
| draw.text((x, y), str(slot['id']), font=font, anchor='mm', fill='#ffe1a0') | |
| im.thumbnail((1400, 1050)) | |
| return im | |