diff --git a/README.md b/README.md index 4d2c31d..4bf543d 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Conception : [docs/superpowers/specs/2026-11-16-ldap-nextcloud-sync-design.md](d | Email | `mail` (l'adresse du domaine `preferred_domain` est marquée préférée) | | Téléphone | `telephoneNumber`, numéro interne à 4 chiffres préfixé selon `mapping.yaml` | | Groupe | `usrDirectionId`, traduit en libellé par `directions.yaml` | -| Photo | `jpegPhoto`, réduite à 512 × 512 au plus, JPEG qualité 80 | +| Photo | `jpegPhoto`, recadrée en carré autour du visage, réduite à 512 × 512 au plus, JPEG qualité 80 | | Date de naissance | `usrDateNaissance`, seulement pour les fiches retenues par `LDAP_BIRTHDAY_FILTER` | ## Installation @@ -34,6 +34,8 @@ Les connexions TLS (Nextcloud et LDAPS) sont validées avec le magasin de certif 2. `mapping.yaml` (copier `mapping.example.yaml`) : correspondance entre attributs LDAP et champs vCard. 3. `directions.yaml` (copier `directions.example.yaml`) : libellé de chaque code Direction. Une Direction inconnue est signalée dans le journal, et la fiche part sans groupe. +Nextcloud et Android affichent la photo en carré, voire en rond, découpé au milieu d'une photo verticale : les cheveux sont coupés. L'outil recadre donc chaque photo en carré autour du visage, détecté localement par le modèle YuNet d'OpenCV (`src/ldap2nextcloud/models/`). Aucune photo ne sort de la machine. Les yeux sont placés à la même hauteur sur toutes les photos, et le carré reste dans la photo. Si aucun visage n'est trouvé, le carré est aligné en haut ; le nombre de ces photos est journalisé en mode `-v`. Les réglages sont dans `mapping.yaml` (`fields.photo.crop`). Changer un réglage renvoie toutes les fiches avec photo au passage suivant. + `LDAP_FILTER` délimite la population synchronisée. Si l'appartenance aux groupes n'est pas portée par les fiches, `LDAP_GROUP_DNS` restreint la synchro aux membres de ces groupes (DN séparés par `;`). ## Premier passage diff --git a/mapping.example.yaml b/mapping.example.yaml index f16bc47..b43df15 100644 --- a/mapping.example.yaml +++ b/mapping.example.yaml @@ -15,5 +15,10 @@ fields: - {attr: telephoneNumber, type: work, prefix: "+3312345", internal_length: 4} # Code de Direction, traduit en libellé par directions.yaml, affiché comme groupe. group: {attr: usrDirectionId, labels: directions} - photo: jpegPhoto + # Photo recadrée en carré autour du visage (détection YuNet), car Nextcloud et + # Android l'affichent en carré, voire en rond. Sans visage détecté : carré aligné en haut. + # eyes_at : hauteur des yeux dans le carré (0,42 = 42 % depuis le haut) + # side : côté du carré, en écarts entre les yeux (limité par la taille de la photo) + # « crop: false » garde la photo entière. + photo: {attr: jpegPhoto, crop: {eyes_at: 0.42, side: 5.5}} birthday: {attr: usrDateNaissance, format: generalized_time} diff --git a/pyproject.toml b/pyproject.toml index 3c017f2..34e3e86 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,6 +13,8 @@ dependencies = [ "requests>=2.32", "vobject>=0.9.8", "Pillow>=10.4", + "numpy>=1.26", + "opencv-python-headless>=4.8", "PyYAML>=6.0", "python-dotenv>=1.0", "tqdm>=4.66", @@ -27,6 +29,9 @@ ldap2nextcloud = "ldap2nextcloud.cli:main" [tool.setuptools.packages.find] where = ["src"] +[tool.setuptools.package-data] +ldap2nextcloud = ["models/*.onnx"] + [tool.pytest.ini_options] testpaths = ["tests"] pythonpath = ["tests"] diff --git a/src/ldap2nextcloud/config.py b/src/ldap2nextcloud/config.py index 3d38d8a..f239a69 100644 --- a/src/ldap2nextcloud/config.py +++ b/src/ldap2nextcloud/config.py @@ -59,6 +59,13 @@ class EmailRule: preferred_domain: str | None = None +@dataclass(frozen=True) +class PhotoCrop: + """Carré centré sur le visage : yeux à eyes_at du haut, côté = side × écart des yeux.""" + eyes_at: float = 0.42 + side: float = 5.5 + + @dataclass(frozen=True) class Mapping: key: str @@ -72,6 +79,7 @@ class Mapping: group_attr: str | None = None photo: str | None = None birthday_attr: str | None = None + photo_crop: PhotoCrop | None = None def _values(env_file: Path | None) -> dict[str, str | None]: @@ -156,6 +164,29 @@ def _attr(spec) -> str | None: return str(spec) +def _photo_crop(spec, path: Path) -> PhotoCrop | None: + """Réglages du recadrage : actif par défaut, « crop: false » le désactive.""" + if spec is None: + return None + crop = spec.get("crop", {}) if isinstance(spec, dict) else {} + if crop is False: + return None + if crop is None or crop is True: + crop = {} + if not isinstance(crop, dict): + raise ConfigError(f"{path} : « fields.photo.crop » doit être false ou un dictionnaire") + try: + result = PhotoCrop( + eyes_at=float(crop.get("eyes_at", PhotoCrop.eyes_at)), + side=float(crop.get("side", PhotoCrop.side)), + ) + except (TypeError, ValueError) as exc: + raise ConfigError(f"{path} : « fields.photo.crop » : valeur non numérique") from exc + if not 0 < result.eyes_at < 1 or result.side <= 0: + raise ConfigError(f"{path} : « fields.photo.crop » : eyes_at entre 0 et 1, side positif") + return result + + def load_mapping(path: Path) -> Mapping: data = _read_yaml(path) if not data.get("key"): @@ -192,6 +223,7 @@ def load_mapping(path: Path) -> Mapping: group_attr=_attr(fields.get("group")), photo=_attr(fields.get("photo")), birthday_attr=_attr(fields.get("birthday")), + photo_crop=_photo_crop(fields.get("photo"), path), ) diff --git a/src/ldap2nextcloud/model.py b/src/ldap2nextcloud/model.py index 867abb5..40d5488 100644 --- a/src/ldap2nextcloud/model.py +++ b/src/ldap2nextcloud/model.py @@ -8,6 +8,8 @@ import uuid from dataclasses import dataclass from datetime import date +from .config import PhotoCrop + FORMAT_VERSION = 1 # Ne jamais changer : l'UID et le nom de fichier de chaque fiche en dépendent. @@ -50,7 +52,9 @@ def contact_href(key: str) -> str: return f"{contact_uid(key)}.vcf" -def fingerprint(contact: Contact, photo_max_size: int, photo_quality: int) -> str: +def fingerprint( + contact: Contact, photo_max_size: int, photo_quality: int, photo_crop: PhotoCrop | None = None +) -> str: """Empreinte de la source : change si une donnée ou un réglage de rendu change.""" payload = { "format": FORMAT_VERSION, @@ -68,5 +72,8 @@ def fingerprint(contact: Contact, photo_max_size: int, photo_quality: int) -> st "birthday": contact.birthday.isoformat() if contact.birthday else None, "photo": hashlib.sha256(contact.photo).hexdigest() if contact.photo else None, } + if contact.photo and photo_crop is not None: + # Clé absente sans recadrage : les empreintes existantes restent valides. + payload["photo_crop"] = [photo_crop.eyes_at, photo_crop.side] text = json.dumps(payload, sort_keys=True, ensure_ascii=False) return hashlib.sha256(text.encode("utf-8")).hexdigest() diff --git a/src/ldap2nextcloud/models/README.md b/src/ldap2nextcloud/models/README.md new file mode 100644 index 0000000..1e110a5 --- /dev/null +++ b/src/ldap2nextcloud/models/README.md @@ -0,0 +1,9 @@ +# Modèle de détection de visage + +`face_detection_yunet_2023mar.onnx` : YuNet, détecteur de visage d'OpenCV. + +- Source : https://github.com/opencv/opencv_zoo/tree/main/models/face_detection_yunet +- Licence : MIT +- SHA-256 : `8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4` + +Il est versionné pour qu'aucun téléchargement ne soit nécessaire à l'exécution, derrière un proxy notamment. diff --git a/src/ldap2nextcloud/models/face_detection_yunet_2023mar.onnx b/src/ldap2nextcloud/models/face_detection_yunet_2023mar.onnx new file mode 100644 index 0000000..f9beb30 Binary files /dev/null and b/src/ldap2nextcloud/models/face_detection_yunet_2023mar.onnx differ diff --git a/src/ldap2nextcloud/photo.py b/src/ldap2nextcloud/photo.py index 3556fc4..6208e03 100644 --- a/src/ldap2nextcloud/photo.py +++ b/src/ldap2nextcloud/photo.py @@ -1,25 +1,120 @@ -"""Retaillage des photos de contact.""" +"""Préparation des photos de contact : recadrage carré sur le visage, retaillage, JPEG.""" from __future__ import annotations +import math +from collections.abc import Callable +from dataclasses import dataclass +from importlib import resources from io import BytesIO from PIL import Image, ImageOps, UnidentifiedImageError +from .config import PhotoCrop -def resize_photo(data: bytes, max_size: int, quality: int) -> bytes | None: - """JPEG d'au plus max_size × max_size, sans métadonnées ; None si illisible.""" +Point = tuple[float, float] +Eyes = tuple[Point, Point] +EyeFinder = Callable[[Image.Image], "Eyes | None"] + +# Un carré plus petit que 30 % de la photo vient sans doute d'un faux positif. +MIN_SQUARE_SHARE = 0.3 +DETECT_MAX = 640 # la détection travaille sur une image réduite +SCORE_THRESHOLD = 0.7 +MODEL = "face_detection_yunet_2023mar.onnx" + + +@dataclass(frozen=True) +class PreparedPhoto: + jpeg: bytes + face_found: bool | None # None : pas de recadrage demandé + + +def square_box(width: int, height: int, eyes: Eyes | None, crop: PhotoCrop) -> tuple[int, int, int, int]: + """Carré (gauche, haut, droite, bas) contenu dans la photo. + + Avec les yeux : côté = crop.side × écart des yeux, yeux à crop.eyes_at du haut. + Sans : le plus grand carré possible, aligné en haut et centré horizontalement. + """ + limit = min(width, height) + if eyes is None: + left = (width - limit) // 2 + return left, 0, left + limit, limit + (rx, ry), (lx, ly) = eyes + center_x, eyes_y = (rx + lx) / 2, (ry + ly) / 2 + side = min(round(crop.side * math.hypot(lx - rx, ly - ry)), limit) + left = min(max(round(center_x - side / 2), 0), width - side) + top = min(max(round(eyes_y - crop.eyes_at * side), 0), height - side) + return left, top, left + side, top + side + + +_detector = None + + +def _get_detector(): + global _detector + if _detector is None: + import cv2 + + # Erreurs seulement : pas d'avertissements OpenCV dans le journal. + cv2.utils.logging.setLogLevel(cv2.utils.logging.LOG_LEVEL_ERROR) + with resources.as_file(resources.files(__package__) / "models" / MODEL) as path: + _detector = cv2.FaceDetectorYN.create(str(path), "", (320, 320), SCORE_THRESHOLD, 0.3, 5000) + return _detector + + +def find_eyes(image: Image.Image) -> Eyes | None: + """Yeux du plus grand visage détecté (YuNet), en pixels de l'image ; None sinon.""" + import cv2 + import numpy as np + + width, height = image.size + scale = min(1.0, DETECT_MAX / max(width, height)) + small = image.resize((max(1, round(width * scale)), max(1, round(height * scale)))) + bgr = cv2.cvtColor(np.asarray(small), cv2.COLOR_RGB2BGR) + detector = _get_detector() + detector.setInputSize((bgr.shape[1], bgr.shape[0])) + _, faces = detector.detect(bgr) + if faces is None or len(faces) == 0: + return None + face = max(faces, key=lambda f: f[2] * f[3]) + return ( + (float(face[4]) / scale, float(face[5]) / scale), + (float(face[6]) / scale, float(face[7]) / scale), + ) + + +def _usable(eyes: Eyes | None, width: int, height: int, crop: PhotoCrop) -> bool: + if eyes is None: + return False + (rx, ry), (lx, ly) = eyes + return crop.side * math.hypot(lx - rx, ly - ry) >= MIN_SQUARE_SHARE * min(width, height) + + +def _to_rgb(image: Image.Image) -> Image.Image: + if image.mode == "RGB": + return image + background = Image.new("RGB", image.size, (255, 255, 255)) + rgba = image.convert("RGBA") + background.paste(rgba, mask=rgba.getchannel("A")) + return background + + +def prepare_photo( + data: bytes, max_size: int, quality: int, + crop: PhotoCrop | None = None, find: EyeFinder = find_eyes, +) -> PreparedPhoto | None: + """JPEG d'au plus max_size × max_size, sans métadonnées, carré si crop ; None si illisible.""" try: with Image.open(BytesIO(data)) as source: - image = ImageOps.exif_transpose(source) - if image.mode != "RGB": - background = Image.new("RGB", image.size, (255, 255, 255)) - rgba = image.convert("RGBA") - background.paste(rgba, mask=rgba.getchannel("A")) - image = background + image = _to_rgb(ImageOps.exif_transpose(source)) + face_found = None + if crop is not None: + eyes = find(image) + face_found = _usable(eyes, image.width, image.height, crop) + image = image.crop(square_box(image.width, image.height, eyes if face_found else None, crop)) image.thumbnail((max_size, max_size), Image.LANCZOS) out = BytesIO() image.save(out, format="JPEG", quality=quality, optimize=True) - return out.getvalue() + return PreparedPhoto(out.getvalue(), face_found) except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError): return None diff --git a/src/ldap2nextcloud/sync.py b/src/ldap2nextcloud/sync.py index fcb78bd..53ae9c1 100644 --- a/src/ldap2nextcloud/sync.py +++ b/src/ldap2nextcloud/sync.py @@ -11,7 +11,7 @@ from .config import Mapping, Settings from .ldap_source import LdapSource, required_attributes from .mapping import entry_to_contact from .model import Contact, contact_href, fingerprint -from .photo import resize_photo +from .photo import prepare_photo from .planner import Desired, check_guards, compute_plan from .progress import LogProgress, Progress from .state import StateDB, StateRow @@ -48,7 +48,9 @@ def _build_desired( log.warning("%s : clé en double dans l'annuaire, seule la première fiche est gardée", contact.key) continue desired[href] = Desired( - href, contact.key, fingerprint(contact, settings.photo_max_size, settings.photo_quality) + href, contact.key, fingerprint( + contact, settings.photo_max_size, settings.photo_quality, mapping.photo_crop + ) ) contacts[href] = contact log.info("Annuaire : %d fiches (%d avec date de naissance)", len(desired), len(birthday_keys)) @@ -106,6 +108,7 @@ def run_sync( updates.append(href) missing_etag: list[str] = [] + faceless = [0] # photos recadrées sans visage détecté def write(href: str, etag: str | None) -> bool: wanted = desired[href] @@ -113,9 +116,15 @@ def run_sync( try: photo = None if contact.photo: - photo = resize_photo(contact.photo, settings.photo_max_size, settings.photo_quality) - if photo is None: + prepared = prepare_photo( + contact.photo, settings.photo_max_size, settings.photo_quality, mapping.photo_crop + ) + if prepared is None: log.warning("%s : photo illisible, fiche envoyée sans photo", wanted.key) + else: + photo = prepared.jpeg + if prepared.face_found is False: + faceless[0] += 1 text = render_vcard(contact, photo, wanted.fingerprint, now) new_etag = client.put(href, text, etag) except CardDavError as exc: @@ -156,6 +165,8 @@ def run_sync( progress.advance() finally: progress.close() + if faceless[0]: + log.debug("Photos sans visage détecté (carré aligné en haut) : %d", faceless[0]) if missing_etag: try: diff --git a/tests/data/README.md b/tests/data/README.md new file mode 100644 index 0000000..101a2a3 --- /dev/null +++ b/tests/data/README.md @@ -0,0 +1,5 @@ +# Données de test + +`generated-face.jpg` : visage généré par https://thispersondoesnotexist.com (StyleGAN), réduit à 384 × 384. Ce n'est la photo d'aucune personne réelle. + +Sur ces images, les yeux sont toujours à peu près au même endroit. Les tests placent donc le visage à différentes hauteurs d'une photo verticale pour simuler des cadrages variés. diff --git a/tests/data/generated-face.jpg b/tests/data/generated-face.jpg new file mode 100644 index 0000000..4d2820d Binary files /dev/null and b/tests/data/generated-face.jpg differ diff --git a/tests/test_config.py b/tests/test_config.py index 5b81488..b2c27de 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -6,6 +6,7 @@ from ldap2nextcloud.config import ( ConfigError, EmailRule, PhoneRule, + PhotoCrop, load_directions, load_mapping, load_settings, @@ -97,9 +98,41 @@ def test_load_mapping_example_file(): assert m.emails == [EmailRule("mail", "work", "example.org")] assert m.birthday_attr == "usrDateNaissance" assert m.photo == "jpegPhoto" + assert m.photo_crop == PhotoCrop(eyes_at=0.42, side=5.5) assert m.title == "usrCadre" +def mapping_with_photo(tmp_path, photo): + path = tmp_path / "mapping.yaml" + path.write_text(f"key: uid\nfields:\n given_name: givenName\n family_name: sn\n{photo}") + return load_mapping(path) + + +def test_photo_crop_is_on_by_default(tmp_path): + m = mapping_with_photo(tmp_path, " photo: jpegPhoto\n") + assert m.photo == "jpegPhoto" and m.photo_crop == PhotoCrop() + + +def test_photo_crop_can_be_disabled(tmp_path): + m = mapping_with_photo(tmp_path, " photo: {attr: jpegPhoto, crop: false}\n") + assert m.photo == "jpegPhoto" and m.photo_crop is None + + +def test_photo_crop_settings_are_read(tmp_path): + m = mapping_with_photo(tmp_path, " photo: {attr: jpegPhoto, crop: {eyes_at: 0.4, side: 6}}\n") + assert m.photo_crop == PhotoCrop(eyes_at=0.4, side=6.0) + + +def test_no_photo_means_no_crop(tmp_path): + assert mapping_with_photo(tmp_path, "").photo_crop is None + + +@pytest.mark.parametrize("crop", ["{eyes_at: 1.5}", "{eyes_at: 0}", "{side: 0}", "{side: abc}", "oui"]) +def test_invalid_photo_crop_is_error(tmp_path, crop): + with pytest.raises(ConfigError, match="crop"): + mapping_with_photo(tmp_path, f" photo: {{attr: jpegPhoto, crop: {crop}}}\n") + + def test_load_mapping_missing_key_is_error(tmp_path): path = tmp_path / "mapping.example.yaml" path.write_text("fields:\n given_name: givenName\n") diff --git a/tests/test_model.py b/tests/test_model.py index 02ac438..d0adae7 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -1,6 +1,7 @@ from dataclasses import replace from datetime import date +from ldap2nextcloud.config import PhotoCrop from ldap2nextcloud.model import Contact, Email, Phone, contact_href, contact_uid, fingerprint BASE = Contact( @@ -51,3 +52,16 @@ def test_fingerprint_changes_with_any_field(): def test_fingerprint_changes_with_photo_settings(): assert fingerprint(BASE, 512, 80) != fingerprint(BASE, 720, 80) assert fingerprint(BASE, 512, 80) != fingerprint(BASE, 512, 90) + + +def test_fingerprint_changes_with_crop_settings_when_contact_has_photo(): + plain = fingerprint(BASE, 512, 80) + cropped = fingerprint(BASE, 512, 80, PhotoCrop()) + assert plain != cropped + assert cropped != fingerprint(BASE, 512, 80, PhotoCrop(eyes_at=0.5)) + assert cropped != fingerprint(BASE, 512, 80, PhotoCrop(side=6)) + + +def test_crop_settings_do_not_touch_contacts_without_photo(): + no_photo = replace(BASE, photo=None) + assert fingerprint(no_photo, 512, 80) == fingerprint(no_photo, 512, 80, PhotoCrop()) diff --git a/tests/test_photo.py b/tests/test_photo.py index 56dba44..7a0f1d2 100644 --- a/tests/test_photo.py +++ b/tests/test_photo.py @@ -1,8 +1,19 @@ from io import BytesIO +from pathlib import Path from PIL import Image -from ldap2nextcloud.photo import resize_photo +import pytest + +from ldap2nextcloud.config import PhotoCrop +from ldap2nextcloud.photo import find_eyes, prepare_photo, square_box + +CROP = PhotoCrop(eyes_at=0.42, side=5.5) + + +def resize_photo(data, max_size, quality): + prepared = prepare_photo(data, max_size, quality) + return prepared.jpeg if prepared else None def jpeg(width, height, exif=None): @@ -54,3 +65,137 @@ def test_output_has_no_exif(): def test_invalid_data_returns_none(): assert resize_photo(b"pas une image", 512, 80) is None + + +# --- Recadrage carré --------------------------------------------------------- + + +def test_without_eyes_square_is_aligned_on_top_edge(): + assert square_box(300, 450, None, CROP) == (0, 0, 300, 300) + + +def test_without_eyes_landscape_square_is_centered_horizontally(): + assert square_box(600, 400, None, CROP) == (100, 0, 500, 400) + + +def test_square_places_eyes_at_ratio_and_sizes_on_eye_gap(): + eyes = ((450, 600), (550, 600)) # écart 100 -> côté 550 + assert square_box(1000, 1500, eyes, CROP) == (225, 369, 775, 919) + + +def test_square_wider_than_photo_is_limited_to_photo_width(): + eyes = ((150, 300), (250, 300)) # côté voulu 550 > largeur 400 + assert square_box(400, 600, eyes, CROP) == (0, 132, 400, 532) + + +def test_square_never_goes_above_top_edge(): + eyes = ((150, 50), (250, 50)) + assert square_box(400, 600, eyes, CROP) == (0, 0, 400, 400) + + +def test_square_never_goes_below_bottom_edge(): + eyes = ((150, 580), (250, 580)) + assert square_box(400, 600, eyes, CROP) == (0, 200, 400, 600) + + +def test_square_is_shifted_back_inside_side_edges(): + eyes = ((40, 600), (140, 600)) # centre des yeux à 90, côté 550 + assert square_box(1000, 1500, eyes, CROP) == (0, 369, 550, 919) + + +def test_tilted_eyes_use_real_distance(): + eyes = ((440, 600), (520, 660)) # écart 100 + left, top, right, bottom = square_box(1000, 1500, eyes, CROP) + assert right - left == 550 and bottom - top == 550 + + +def test_settings_change_the_square(): + eyes = ((450, 600), (550, 600)) + assert square_box(1000, 1500, eyes, PhotoCrop(eyes_at=0.5, side=4)) == (300, 400, 700, 800) + + +# --- Photo préparée ---------------------------------------------------------- + + +def portrait(width=400, height=600): + """Bande rouge en haut, bleue en bas : la couleur du coin haut-gauche situe le carré.""" + image = Image.new("RGB", (width, height), (0, 0, 255)) + image.paste((255, 0, 0), (0, 0, width, height // 3)) + buffer = BytesIO() + image.save(buffer, format="PNG") + return buffer.getvalue() + + +def test_without_crop_settings_photo_keeps_its_ratio(): + prepared = prepare_photo(portrait(), 512, 80) + assert opened(prepared.jpeg).size == (341, 512) + assert prepared.face_found is None + + +def test_face_found_gives_square_around_eyes(): + eyes = ((150, 500), (250, 500)) # carré en bas de la photo + prepared = prepare_photo(portrait(), 512, 80, CROP, find=lambda image: eyes) + out = opened(prepared.jpeg) + assert out.size == (400, 400) + assert prepared.face_found is True + assert out.getpixel((5, 5))[2] > 200 # coin haut-gauche bleu : carré du bas + + +def test_no_face_falls_back_to_top_square(): + prepared = prepare_photo(portrait(), 512, 80, CROP, find=lambda image: None) + out = opened(prepared.jpeg) + assert out.size == (400, 400) + assert prepared.face_found is False + assert out.getpixel((5, 5))[0] > 200 # coin haut-gauche rouge : carré du haut + + +def test_tiny_face_is_ignored(): + eyes = ((195, 500), (205, 500)) # écart 10 : sans doute un faux positif + prepared = prepare_photo(portrait(), 512, 80, CROP, find=lambda image: eyes) + assert prepared.face_found is False + + +def test_detector_receives_upright_rgb_image(): + seen = [] + exif = Image.Exif() + exif[0x0112] = 6 + prepare_photo(jpeg(400, 200, exif), 512, 80, CROP, find=lambda image: seen.append(image) or None) + assert seen[0].size == (200, 400) and seen[0].mode == "RGB" + + +# --- Vrai détecteur (visage généré, voir tests/data/README.md) ----------------- + +FACE = Path(__file__).parent / "data" / "generated-face.jpg" + + +def framed_face(offset): + """Photo verticale 2:3 avec le visage collé à `offset` pixels du haut.""" + canvas = Image.new("RGB", (384, 576), (230, 230, 230)) + canvas.paste(Image.open(FACE), (0, offset)) + return canvas + + +def eyes_height(image): + (_, ry), (_, ly) = find_eyes(image) + return (ry + ly) / 2 + + +def test_real_detector_finds_both_eyes_of_generated_face(): + (rx, ry), (lx, ly) = find_eyes(Image.open(FACE).convert("RGB")) + assert 120 < rx < 160 and 220 < lx < 250 # œil droit à gauche de l'image + assert 165 < ry < 200 and 165 < ly < 200 + + +def test_real_detector_finds_nothing_on_plain_image(): + assert find_eyes(Image.new("RGB", (400, 600), (120, 120, 120))) is None + + +@pytest.mark.parametrize("offset", [0, 64, 128]) # au-delà, le carré bute sur le bas +def test_cropped_photo_puts_eyes_at_same_height_whatever_the_framing(offset): + buffer = BytesIO() + framed_face(offset).save(buffer, format="PNG") + prepared = prepare_photo(buffer.getvalue(), 512, 90, CROP) + assert prepared.face_found is True + out = opened(prepared.jpeg).convert("RGB") + assert out.size == (384, 384) + assert eyes_height(out) / 384 == pytest.approx(0.42, abs=0.03) diff --git a/tests/test_sync.py b/tests/test_sync.py index c2747ad..118cc91 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -6,6 +6,7 @@ import pytest from PIL import Image from ldap2nextcloud.carddav import CardDavError +from ldap2nextcloud.photo import PreparedPhoto from ldap2nextcloud.config import Settings, load_directions, load_mapping from ldap2nextcloud.model import contact_href from ldap2nextcloud.planner import GuardError @@ -115,6 +116,26 @@ def test_birthday_only_for_selected_keys(tmp_path): assert "BDAY" not in client.cards[contact_href("lvernet")][1] +def test_photo_without_face_is_cropped_to_top_square_and_counted(tmp_path, caplog): + tall = BytesIO() + Image.new("RGB", (400, 600), (10, 20, 30)).save(tall, format="JPEG") + + class TallPhotoSource(FakeSource): + def fetch_entries(self, attributes): + entries = super().fetch_entries(attributes) + for entry in entries: + entry["jpegPhoto"] = [tall.getvalue()] + return entries + + client = FakeClient() + with caplog.at_level(logging.DEBUG): + run(tmp_path, client, TallPhotoSource()) + import vobject + card = vobject.readOne(client.cards[contact_href("omalmare")][1]) + assert Image.open(BytesIO(card.photo.value)).size == (400, 400) + assert "Photos sans visage détecté (carré aligné en haut) : 3" in caplog.text + + def test_photo_is_resized(tmp_path): client = FakeClient() run(tmp_path, client) @@ -217,13 +238,13 @@ def test_unexpected_photo_failure_does_not_stop_the_run(tmp_path, monkeypatch): calls = {"n": 0} - def flaky(data, size, quality): + def flaky(data, size, quality, crop): calls["n"] += 1 if calls["n"] == 1: raise RuntimeError("bombe") - return b"\xff\xd8ok" + return PreparedPhoto(b"\xff\xd8ok", False) - monkeypatch.setattr(sync, "resize_photo", flaky) + monkeypatch.setattr(sync, "prepare_photo", flaky) client = FakeClient({"ldap2vcard-old.vcf": ("x", "BEGIN:VCARD")}) summary = run(tmp_path, client, initial=True) assert summary.errors == 1 and summary.created == 2 and summary.deleted == 1