SPB Git

Repository Public

make_fixtures.py 9.2 KB 195 lines python

1# =============================================================================2#                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : MacLustr Identity7# File             : tests/make_fixtures.py8# Description      : Fabrique les documents FICTIFS de test (mention SPÉCIMEN,9#                    données inventées) et récupère quatre portraits du domaine10#                    public (NASA).11# Module           : tests12# Repository       : https://git.spboucher.ai/maclustr-identity13# Project Website  : https://identity.spboucher.ai14# Created          : 2026-12-0115# Last Modified    : 2026-12-0116#17# Author           : Simon-Pierre Boucher18# Position         : Professor of Finance19# Institution      : Université du Québec en Outaouais (UQO)20# Organization     : SP Boucher21# Website          : https://spboucher.ai22# Git              : https://git.spboucher.ai23#24# Preferred Contact: admin@spboucher.ai25# Technical Contact: dev@spboucher.ai26# Security/Admin   : admin@spboucher.ai27#28# Copyright (c) 202629# Simon-Pierre Boucher30# All rights reserved where applicable. This file is governed by the31# applicable project license, copyright notices and relevant law.32# Existing third-party rights and notices remain unaffected.33#34# License          : None specified (no license file in this repository)35#36# Do not embed credentials, private keys, access tokens,37# certificates or confidential personal information.38#39# =============================================================================40# END OF SP BOUCHER SOURCE HEADER41# =============================================================================4243"""Fabrique les documents FICTIFS de test (mention SPÉCIMEN, données inventées) et récupère quatre portraits du domaine public (NASA).4445Aucun document réel n'est utilisé. Usage : python tests/make_fixtures.py46"""47from __future__ import annotations48import sys49import urllib.request50from pathlib import Path51import cv252import numpy as np53from PIL import Image, ImageDraw, ImageFont5455ROOT = Path(__file__).resolve().parents[1]56sys.path.insert(0, str(ROOT))57from services.mlid.engines import barcode, mrz  # noqa: E4025859FX = ROOT / "tests" / "fixtures"60BASE = "https://commons.wikimedia.org/wiki/Special:FilePath/"61PORTRAITS = {  # photographies officielles de la NASA, domaine public62    "a1.jpg": "Christina_M._Hammock_portrait.jpg", "a2.jpg": "Christina_Koch_Artemis_2_Crew_Portrait.jpg",63    "b1.jpg": "Jessica_Meir_(portrait_crop).jpg", "b2.jpg": "Portrait_-_Astronaut_Jessica_Meir_(NHQ202009150005).jpg"}646566def fetch():67    for name, src in PORTRAITS.items():68        dst = FX / name69        if dst.exists():70            continue71        req = urllib.request.Request(BASE + urllib.request.quote(src) + "?width=900", headers={"User-Agent": "fixture-fetch/1.0"})72        dst.write_bytes(urllib.request.urlopen(req, timeout=60).read())73        print("téléchargé", name)747576def font(size, mono=False, bold=False):77    paths = ["/System/Library/Fonts/Menlo.ttc"] if mono else ["/System/Library/Fonts/Helvetica.ttc", "/System/Library/Fonts/Supplemental/Arial.ttf"]78    for p in paths:79        try:80            return ImageFont.truetype(p, size, index=1 if bold and p.endswith("Helvetica.ttc") else 0)81        except Exception:82            continue83    return ImageFont.load_default()848586def face_crop(path: Path, w: int, h: int) -> Image.Image:87    im = Image.open(path).convert("RGB")88    W, H = im.size89    s = min(W, H * w / h)90    cw, ch = s, s * h / w91    x0, y0 = (W - cw) / 2, max(0, H * 0.02)92    return im.crop((int(x0), int(y0), int(x0 + cw), int(y0 + ch))).resize((w, h), Image.LANCZOS)939495def passport(portrait: str, *, surname="SPECIMEN", given="CLAIRE ANNE", number="ZS123456", birth="850612", expiry="310415", out="passport.jpg", tamper=False):96    W, H = 1500, 105097    im = Image.new("RGB", (W, H), (232, 236, 240))98    d = ImageDraw.Draw(im)99    for y in range(0, H, 14):100        d.line([(0, y), (W, y)], fill=(224, 229, 235), width=1)101    d.text((60, 40), "PASSEPORT / PASSPORT", font=font(40, bold=True), fill=(30, 40, 70))102    d.text((1000, 46), "SPÉCIMEN FICTIF", font=font(34, bold=True), fill=(170, 30, 30))103    im.paste(face_crop(FX / portrait, 400, 500), (70, 150))104    x = 540105    rows = [("Nom / Surname", surname), ("Prénoms / Given names", given), ("Nationalité / Nationality", "UTOPIA"),106            ("Date de naissance / Date of birth", f"19{birth[:2]}-{birth[2:4]}-{birth[4:]}" if not tamper else "1991-06-12"),107            ("Date d'expiration / Date of expiry", f"20{expiry[:2]}-{expiry[2:4]}-{expiry[4:]}"), ("No de passeport / Passport No.", number)]108    y = 160109    for label, val in rows:110        d.text((x, y), label, font=font(22), fill=(90, 100, 120))111        d.text((x, y + 28), val, font=font(36, bold=True), fill=(15, 20, 30))112        y += 86113    lines = mrz.build_td3(state="UTO", surname=surname, given=given, number=number, nationality="UTO", birth=birth, sex="F", expiry=expiry)114    d.rectangle([(0, 800), (W, H)], fill=(236, 238, 241))115    for i, ln in enumerate(lines):116        d.text((60, 850 + i * 70), ln, font=font(50, mono=True), fill=(10, 10, 10))117    im.save(FX / out, quality=93)118    return im119120121def licence(portrait: str, *, surname="SPECIMEN", given="CLAIRE", number="S1234-120685-07", birth="1985-06-12", expiry="2031-04-15", issue="2023-04-15", prefix="licence", expired=False):122    if expired:123        expiry = "2022-04-15"124    W, H = 1500, 950125    im = Image.new("RGB", (W, H), (226, 236, 244))126    d = ImageDraw.Draw(im)127    for xx in range(0, W, 18):128        d.line([(xx, 0), (xx + 200, H)], fill=(216, 228, 240), width=1)129    d.text((50, 36), "Permis de conduire", font=font(54, bold=True), fill=(20, 50, 110))130    d.text((50, 104), "Driver's licence — Québec", font=font(30), fill=(20, 50, 110))131    d.text((1040, 46), "SPÉCIMEN FICTIF", font=font(32, bold=True), fill=(170, 30, 30))132    im.paste(face_crop(FX / portrait, 380, 480), (60, 200))133    x, y = 500, 210134    for label, val in [("Numéro / Number", number), ("Nom / Name", surname), ("Prénom / Given name", given), ("Date de naissance / Birth", birth),135                       ("Délivré / Issued", issue), ("Expiration / Expiry", expiry), ("Classe / Class", "5")]:136        d.text((x, y), label, font=font(21), fill=(90, 100, 120))137        d.text((x, y + 26), val, font=font(34, bold=True), fill=(15, 20, 30))138        y += 82139    im.save(FX / f"{prefix}_front.jpg", quality=93)140    back = Image.new("RGB", (W, H), (236, 240, 244))141    db = ImageDraw.Draw(back)142    db.text((50, 40), "SPÉCIMEN FICTIF — verso", font=font(30, bold=True), fill=(170, 30, 30))143    payload = barcode.build_aamva(surname=surname, given=given, number=number.replace("-", ""), birth=birth, expiry=expiry, issue=issue)144    import zxingcpp145    try:146        bc = np.array(zxingcpp.create_barcode(payload, zxingcpp.BarcodeFormat.PDF417).to_image(scale=4))147    except Exception:148        bc = np.array(zxingcpp.write_barcode(zxingcpp.BarcodeFormat.PDF417, payload, 1200, 300))149    bci = Image.fromarray(bc).convert("RGB")150    s = 1300 / bci.width151    bci = bci.resize((1300, int(bci.height * s)), Image.NEAREST)152    back.paste(bci, (100, 200))153    back.save(FX / f"{prefix}_back.jpg", quality=95)154155156def scene(doc: str, out: str, angle=4.0):157    """Pose le document sur un fond de table, légèrement incliné, comme une vraie photo."""158    doc_im = cv2.imread(str(FX / doc))159    h, w = doc_im.shape[:2]160    H, W = h + 500, w + 500161    rng = np.random.default_rng(7)162    bg = np.full((H, W, 3), (72, 92, 110), np.uint8)163    bg = cv2.add(bg, rng.integers(0, 14, (H, W, 3), dtype=np.uint8))164    src = np.float32([[0, 0], [w, 0], [w, h], [0, h]])165    dst = np.float32([[270, 230], [270 + w - 30, 230 + 40], [250 + w, 250 + h + 10], [240, 250 + h - 20]])166    M = cv2.getPerspectiveTransform(src, dst)167    warped = cv2.warpPerspective(doc_im, M, (W, H))168    mask = cv2.warpPerspective(np.full((h, w), 255, np.uint8), M, (W, H))169    bg[mask > 0] = warped[mask > 0]170    bg = np.clip(cv2.GaussianBlur(bg, (0, 0), 0.7).astype(np.int16) + rng.normal(0, 2.2, bg.shape), 0, 255).astype(np.uint8)171    cv2.imwrite(str(FX / out), bg, [cv2.IMWRITE_JPEG_QUALITY, 92])172173174def health_card():175    im = Image.new("RGB", (1400, 880), (250, 222, 140))176    d = ImageDraw.Draw(im)177    d.text((50, 40), "Régie de l'assurance maladie", font=font(50, bold=True), fill=(120, 30, 30))178    d.text((50, 120), "SPÉCIMEN FICTIF", font=font(34, bold=True), fill=(170, 30, 30))179    d.text((50, 300), "SPEC 8506 1212", font=font(60, bold=True), fill=(20, 20, 20))180    d.text((50, 420), "CLAIRE SPECIMEN", font=font(44), fill=(20, 20, 20))181    im.save(FX / "health_card.jpg", quality=92)182183184if __name__ == "__main__":185    FX.mkdir(parents=True, exist_ok=True)186    fetch()187    passport("a1.jpg")188    passport("a1.jpg", out="passport_tampered.jpg", tamper=True)189    licence("a1.jpg")190    licence("a1.jpg", prefix="licence_expired", expired=True)191    for d_ in ("passport.jpg", "passport_tampered.jpg", "licence_front.jpg", "licence_back.jpg", "licence_expired_front.jpg", "licence_expired_back.jpg"):192        scene(d_, d_.replace(".jpg", "_scene.jpg"))193    health_card()194    print("fixtures prêtes :", sorted(p.name for p in FX.iterdir()))195
Files main
Menu

Theme