🤖 Recadrer les photos en carré autour du visage

Nextcloud et Android affichent la photo en carré découpé au milieu
d'une photo verticale, ce qui coupe les cheveux. La photo est
désormais recadrée en carré autour du visage, détecté localement par
YuNet (OpenCV, modèle MIT versionné dans le paquet) : les yeux sont
placés à la même hauteur sur toutes les photos. Sans visage détecté,
le carré est aligné en haut et compté dans le journal (-v).

Réglages dans mapping.yaml (fields.photo.crop : eyes_at, side, ou
false). Ils entrent dans l'empreinte des seules fiches avec photo :
celles-ci seront renvoyées une fois au prochain passage.

Les tests utilisent un visage généré par thispersondoesnotexist.com
(tests/data/README.md).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
zeguiguiandClaude Opus 5.5 committed 2026-11-17 19:13:45 +01:00
1 parent 2ada724160
commit 35f90b8fb1
15 files changed
+405 -21

No files matched your search

+5
View File
@@ -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.
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

+33
View File
@@ -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")
+14
View File
@@ -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())
+146 -1
View File
@@ -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)
+24 -3
View File
@@ -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