Skip to content

UniFace: A Unified Face Analysis Library for Python | Detection, alignment, landmarks, face-mesh, recognition, parsing, gaze, attributes and anti-spoofing under one API.

chore: Add kaggle notebook update workflow (#137)

Yakhyokhuja Valikhujaevdf87c6531f4d
diff --git a/.github/kaggle/kernels.json b/.github/kaggle/kernels.json
new file mode 100644
index 0000000..0d4116f
--- /dev/null
+++ b/.github/kaggle/kernels.json
@@ -0,0 +1,29 @@
+{
+ "$comment": [
+ "'slug' is where the kernel lives on Kaggle right now; 'title' is what it should be called.",
+ "Kaggle re-slugs a kernel to match its title, so a push whose title differs renames the kernel",
+ "and its old URL stops resolving. The kernel survives with its upvotes, comments and version",
+ "history (measured 2026-08-20). After such a push, update the slug here to where it landed;",
+ "sync.py prints the exact edit, and finds the kernel by title in the meantime.",
+ "'live': true marks a slug that already exists. sync.py refuses to push one it cannot find",
+ "under either name, so a mistyped slug fails loudly instead of stranding the original.",
+ "Titles come from each notebook H1, keeping examples/ the single source of truth."
+ ],
+ "kernels": [
+ {"notebook": "01_face_detection.ipynb", "slug": "face-detection-with-uniface", "title": "Face Detection with UniFace", "live": true},
+ {"notebook": "02_face_alignment.ipynb", "slug": "face-detection-and-alignment-with-uniface", "title": "Face Detection and Alignment with UniFace", "live": true},
+ {"notebook": "03_face_verification.ipynb", "slug": "face-verification-one-to-one-face-comparison", "title": "Face Verification: One-to-One Face Comparison", "live": true},
+ {"notebook": "04_face_search.ipynb", "slug": "face-search-one-to-many-face-matching", "title": "Face Search: One-to-Many Face Matching", "live": true},
+ {"notebook": "05_face_analyzer.ipynb", "slug": "face-analysis-with-uniface", "title": "Face Analysis with UniFace", "live": true},
+ {"notebook": "06_face_parsing.ipynb", "slug": "face-parsing-with-uniface", "title": "Face Parsing with UniFace", "live": true},
+ {"notebook": "07_face_anonymization.ipynb", "slug": "face-anonymization-with-uniface", "title": "Face Anonymization with UniFace", "live": true},
+ {"notebook": "08_gaze_estimation.ipynb", "slug": "gaze-estimation-with-uniface", "title": "Gaze Estimation with UniFace", "live": true},
+ {"notebook": "09_face_segmentation.ipynb", "slug": "xseg-face-segmentation", "title": "XSeg Face Segmentation", "live": true},
+ {"notebook": "10_face_vector_store.ipynb", "slug": "face-vector-store-with-faiss", "title": "Face Vector Store with FAISS", "live": true},
+ {"notebook": "11_head_pose_estimation.ipynb", "slug": "head-pose-estimation-with-uniface", "title": "Head Pose Estimation with UniFace", "live": true},
+ {"notebook": "12_face_recognition.ipynb", "slug": "face-recognition-retinaface-align-arcface", "title": "Face Recognition: RetinaFace → Align → ArcFace", "live": true},
+ {"notebook": "13_portrait_matting.ipynb", "slug": "portrait-matting-with-modnet", "title": "Portrait Matting with MODNet", "live": true},
+ {"notebook": "14_face_attributes.ipynb", "slug": "face-attribute-detection-with-uniface", "title": "Face Attribute Detection with UniFace", "live": true},
+ {"notebook": "15_face_mesh.ipynb", "slug": "dense-face-mesh-with-uniface", "title": "Dense Face Mesh with UniFace", "live": true}
+ ]
+}
diff --git a/.github/kaggle/sync.py b/.github/kaggle/sync.py
new file mode 100644
index 0000000..01d90aa
--- /dev/null
+++ b/.github/kaggle/sync.py
@@ -0,0 +1,513 @@
+# Copyright 2025-2026 Yakhyokhuja Valikhujaev
+# Author: Yakhyokhuja Valikhujaev
+# GitHub: https://github.com/yakhyo
+
+"""Publish the notebooks in ``examples/`` to Kaggle as kernels.
+
+Each notebook maps to one kernel slug in ``kernels.json`` beside this script. Pushing a known slug
+adds a *new version* to that kernel rather than creating another one, so its upvotes, comments and
+version history carry over; nothing is ever deleted or re-created.
+
+The slug is not fixed, though. Kaggle re-slugs a kernel to match its title, so changing a title
+moves the kernel's URL and the old address stops resolving (measured 2026-08-20: retitling
+``face-detection-with-uniface-python-library`` moved it to ``face-detection-with-uniface``, which
+then 404s, while the kernel itself kept its history). Renaming is therefore done by pushing the OLD
+slug with the NEW title, and the manifest holds both: ``slug`` is where the kernel lives now,
+``title`` is what it should be called. A mismatch on a live entry means a pending rename and is
+reported, not rejected; on a new entry it is simply wrong, because a new kernel lands at
+slugify(title) regardless. Keep the old title whenever the current URL matters more than the name.
+
+Kaggle runs the kernel itself once the version lands, so this script pushes and exits without
+waiting for the run to finish.
+"""
+
+from __future__ import annotations
+
+import argparse
+import csv
+from dataclasses import dataclass
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import subprocess # nosec B404 - only ever runs the Kaggle CLI with literal arguments
+import sys
+import tempfile
+import time
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+MANIFEST = Path(__file__).resolve().parent / 'kernels.json'
+EXAMPLES_DIR = REPO_ROOT / 'examples'
+
+# Notebooks reach their assets by cloning the repo, which only happens when this env var is visible.
+KAGGLE_ENV_GUARD = 'KAGGLE_KERNEL_RUN_TYPE'
+
+# Each notebook carries an 'Open in Kaggle' badge; this is how one is recognised.
+KAGGLE_BADGE = 'kaggle.com/static/images/open-in-kaggle.svg'
+
+# Stands in for the owner when staging without credentials, so a dry run still works offline.
+PLACEHOLDER_OWNER = '<KAGGLE_USERNAME>'
+
+# Kaggle refuses a push while five batch sessions are already running; this is how it says so.
+SESSION_LIMIT = 'Maximum batch CPU session count'
+
+# Kaggle's own rule for the identifier half of a kernel reference.
+SLUG_PATTERN = re.compile(r'[a-z0-9][a-z0-9-]{3,58}[a-z0-9]')
+
+
+@dataclass(frozen=True)
+class RemoteKernel:
+ """A kernel as Kaggle currently holds it."""
+
+ title: str
+ votes: int
+
+ @property
+ def vote_count(self) -> str:
+ """Return the vote tally as English, e.g. ``"1 vote"`` or ``"5 votes"``."""
+ return f'{self.votes} vote' if self.votes == 1 else f'{self.votes} votes'
+
+
+def slugify(title: str) -> str:
+ """Reduce a kernel title to the slug Kaggle would derive from it.
+
+ This is where a kernel lands after a push, so it doubles as the slug a new kernel is created
+ at and the slug a renamed one moves to.
+
+ Args:
+ title: Human-readable kernel title.
+
+ Returns:
+ Lowercase dash-separated slug.
+ """
+ return re.sub(r'-+', '-', re.sub(r'[^a-z0-9]+', '-', title.lower())).strip('-')
+
+
+def resolve_owner(explicit: str | None) -> str | None:
+ """Find the Kaggle account that owns the kernels.
+
+ Args:
+ explicit: Owner passed on the command line, or ``None``.
+
+ Returns:
+ Kaggle username, or ``None`` when no credentials are available.
+ """
+ if explicit:
+ return explicit
+ if os.environ.get('KAGGLE_USERNAME'):
+ return os.environ['KAGGLE_USERNAME']
+
+ config_dir = Path(os.environ.get('KAGGLE_CONFIG_DIR', Path.home() / '.kaggle'))
+ config = config_dir / 'kaggle.json'
+ if config.is_file():
+ return json.loads(config.read_text(encoding='utf-8')).get('username')
+ return None
+
+
+def load_kernels(manifest: Path) -> list[dict]:
+ """Read the kernel manifest.
+
+ Args:
+ manifest: Path to ``kernels.json``.
+
+ Returns:
+ List of kernel entries.
+ """
+ return json.loads(manifest.read_text(encoding='utf-8'))['kernels']
+
+
+def validate(kernels: list[dict], examples_dir: Path) -> list[str]:
+ """Check the manifest against the notebooks on disk.
+
+ Args:
+ kernels: Kernel entries from the manifest.
+ examples_dir: Directory holding the source notebooks.
+
+ Returns:
+ List of error messages; empty when the manifest is consistent.
+ """
+ errors: list[str] = []
+ seen_slugs: dict[str, str] = {}
+
+ for entry in kernels:
+ notebook = examples_dir / entry['notebook']
+ if not notebook.is_file():
+ errors.append(f'{entry["notebook"]}: listed in the manifest but missing from {examples_dir.name}/')
+ else:
+ # The notebook's own Kaggle badge has to name the slug the push will land on, or every
+ # published copy advertises an address that stopped resolving the moment it moved.
+ landing = slugify(entry['title'])
+ text = notebook.read_text(encoding='utf-8')
+ if KAGGLE_BADGE in text and f'/{landing})' not in text:
+ errors.append(f'{entry["notebook"]}: its Kaggle badge does not point at /{landing}')
+ if entry['slug'] in seen_slugs:
+ errors.append(f'{entry["slug"]}: slug reused by {seen_slugs[entry["slug"]]} and {entry["notebook"]}')
+ seen_slugs[entry['slug']] = entry['notebook']
+ if not SLUG_PATTERN.fullmatch(entry['slug']):
+ errors.append(f'{entry["slug"]}: not a valid Kaggle slug (5-60 chars, lowercase letters, digits, dashes)')
+ if len(entry['title']) < 5:
+ errors.append(f'{entry["notebook"]}: title "{entry["title"]}" is under Kaggle\'s five-character minimum')
+ # Kaggle re-slugs a kernel to match its title, so a kernel that does not exist yet will land
+ # at slugify(title) whatever the manifest claims. On a live kernel the same mismatch is
+ # meaningful instead of wrong: it is a pending rename, reported by the push rather than
+ # rejected here, because renaming requires pushing the OLD slug with the NEW title.
+ if not entry.get('live') and entry['slug'] != slugify(entry['title']):
+ errors.append(
+ f'{entry["notebook"]}: a new kernel titled "{entry["title"]}" lands at '
+ f'"{slugify(entry["title"])}", not "{entry["slug"]}". Match them.'
+ )
+
+ mapped = {entry['notebook'] for entry in kernels}
+ for notebook in sorted(examples_dir.glob('*.ipynb')):
+ if notebook.name not in mapped:
+ errors.append(f'{notebook.name}: no entry in {MANIFEST.name} — add one so it is not silently skipped')
+
+ return errors
+
+
+def check_kaggle_guard(notebook: Path) -> bool:
+ """Report whether a notebook clones the repo when it runs on Kaggle.
+
+ Args:
+ notebook: Path to the source notebook.
+
+ Returns:
+ ``True`` when the Kaggle branch of the setup cell is present.
+ """
+ return KAGGLE_ENV_GUARD in notebook.read_text(encoding='utf-8')
+
+
+def build_metadata(entry: dict, owner: str) -> dict:
+ """Build the ``kernel-metadata.json`` payload for one notebook.
+
+ Args:
+ entry: Kernel entry from the manifest.
+ owner: Kaggle username that owns the kernel.
+
+ Returns:
+ Metadata dict ready to be written next to the notebook.
+ """
+ return {
+ 'id': f'{owner}/{entry["slug"]}',
+ 'title': entry['title'],
+ 'code_file': entry['notebook'],
+ 'language': 'python',
+ 'kernel_type': 'notebook',
+ 'is_private': False,
+ # Notebooks pip-install uniface and download ONNX weights on first use.
+ 'enable_internet': True,
+ 'enable_gpu': entry.get('enable_gpu', False),
+ 'enable_tpu': False,
+ 'dataset_sources': entry.get('dataset_sources', []),
+ 'competition_sources': [],
+ 'kernel_sources': [],
+ 'model_sources': [],
+ }
+
+
+def stage(entry: dict, examples_dir: Path, staging_root: Path, owner: str) -> Path:
+ """Copy a notebook and its metadata into a directory Kaggle can push.
+
+ Args:
+ entry: Kernel entry from the manifest.
+ examples_dir: Directory holding the source notebooks.
+ staging_root: Directory to create the per-kernel folder under.
+ owner: Kaggle username that owns the kernel.
+
+ Returns:
+ The staged directory.
+ """
+ staged = staging_root / entry['slug']
+ staged.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(examples_dir / entry['notebook'], staged / entry['notebook'])
+ (staged / 'kernel-metadata.json').write_text(
+ json.dumps(build_metadata(entry, owner), indent=2) + '\n', encoding='utf-8'
+ )
+ return staged
+
+
+def push_kernel(staged: Path, retries: int, wait: int) -> tuple[int, str]:
+ """Push one staged kernel, waiting out Kaggle's concurrent-session cap.
+
+ Kaggle runs every pushed version and refuses a push once five batch sessions are already
+ running, so a fifteen-notebook sync cannot be submitted in one burst. Each rejection is
+ retried rather than reported, since it means "not yet", not "no".
+
+ Args:
+ staged: Directory holding the notebook and its ``kernel-metadata.json``.
+ retries: How many times to wait for a session slot before giving up.
+ wait: Seconds to wait between attempts.
+
+ Returns:
+ The final return code and the combined output of the last attempt.
+
+ Raises:
+ FileNotFoundError: If the Kaggle CLI is not on PATH.
+ """
+ for attempt in range(retries + 1):
+ result = run_kaggle(['kernels', 'push', '-p', str(staged)])
+ output = (result.stdout + result.stderr).strip()
+ if SESSION_LIMIT not in output:
+ return result.returncode, output
+ if attempt < retries:
+ print(f' Kaggle is already running its five batch sessions; retrying in {wait}s')
+ time.sleep(wait)
+ return result.returncode, output
+
+
+def run_kaggle(args: list[str]) -> subprocess.CompletedProcess[str]:
+ """Run the Kaggle CLI.
+
+ Args:
+ args: Arguments after the ``kaggle`` executable.
+
+ Returns:
+ The completed process, with stdout and stderr captured as text.
+
+ Raises:
+ FileNotFoundError: If the Kaggle CLI is not on PATH.
+ """
+ executable = shutil.which('kaggle')
+ if executable is None:
+ raise FileNotFoundError('kaggle')
+ return subprocess.run([executable, *args], capture_output=True, text=True, check=False) # nosec B603
+
+
+def fetch_remote(owner: str) -> dict[str, RemoteKernel] | None:
+ """Read the account's kernels, keyed by slug.
+
+ ``kernels status`` cannot tell a missing kernel from a private one — both answer with the same
+ permission error — so existence is settled from a listing instead. ``--mine`` covers private
+ kernels the public ``--user`` view omits, and the two are merged.
+
+ Args:
+ owner: Kaggle username to list.
+
+ Returns:
+ Slug to :class:`RemoteKernel`, or ``None`` when the listing could not be read at all.
+ """
+ remote: dict[str, RemoteKernel] = {}
+ reachable = False
+
+ for scope in (['--mine'], ['--user', owner]):
+ try:
+ result = run_kaggle(['kernels', 'list', *scope, '--page-size', '100', '-v'])
+ except FileNotFoundError:
+ return None
+ if result.returncode != 0:
+ continue
+ reachable = True
+ # Columns are ref,title,author,lastRunTime,totalVotes; only real rows carry an owner/slug ref.
+ for row in csv.reader(result.stdout.splitlines()):
+ if len(row) < 5 or '/' not in row[0]:
+ continue
+ row_owner, _, slug = row[0].strip().partition('/')
+ if row_owner != owner:
+ continue
+ remote[slug] = RemoteKernel(title=row[1].strip(), votes=int(row[4]) if row[4].isdigit() else 0)
+
+ return remote if reachable else None
+
+
+def resolve_target(entry: dict, remote: dict[str, RemoteKernel] | None) -> tuple[str | None, RemoteKernel | None]:
+ """Work out which slug to push a manifest entry against.
+
+ A kernel is looked for under its manifest slug first, then under the slug its title implies.
+ The second lookup is what makes a rename idempotent: once Kaggle has moved a kernel to match a
+ new title, the manifest's old slug stops resolving, and only the title-derived one finds it.
+
+ Args:
+ entry: Kernel entry from the manifest.
+ remote: Kernels currently on the account, or ``None`` when the listing could not be read.
+
+ Returns:
+ The slug to push against and the kernel already there, if any. The slug is ``None`` when a
+ kernel marked live cannot be found under either name, which means its slug was mistyped.
+ """
+ if remote is None:
+ return entry['slug'], None
+ if entry['slug'] in remote:
+ return entry['slug'], remote[entry['slug']]
+ renamed = slugify(entry['title'])
+ if renamed in remote:
+ return renamed, remote[renamed]
+ return (None, None) if entry.get('live') else (entry['slug'], None)
+
+
+def list_remote(owner: str, kernels: list[dict]) -> int:
+ """Print the account's kernels and reconcile them against the manifest.
+
+ Args:
+ owner: Kaggle username to list.
+ kernels: Kernel entries from the manifest.
+
+ Returns:
+ Process exit code.
+ """
+ remote = fetch_remote(owner)
+ if remote is None:
+ print(f'Could not list kernels for {owner}. Check the kaggle CLI and its credentials.', file=sys.stderr)
+ return 1
+
+ print(f'Kernels on {owner} ({len(remote)} found):')
+ for slug, kernel in sorted(remote.items()):
+ print(f' {kernel.vote_count:>8} {slug} "{kernel.title}"')
+
+ print('\nManifest:')
+ for entry in kernels:
+ kernel = remote.get(entry['slug'])
+ state = f'live, {kernel.vote_count}' if kernel else 'new'
+ print(f' [{state}] {entry["slug"]} <- {entry["notebook"]}')
+ if kernel and kernel.title != entry['title']:
+ print(f' retitle "{kernel.title}" -> "{entry["title"]}"; the URL moves to {entry["slug"]}')
+ if entry.get('live') and not kernel:
+ print(' ORPHAN RISK: marked live in the manifest but absent from Kaggle.')
+
+ unmapped = set(remote) - {entry['slug'] for entry in kernels}
+ if unmapped:
+ print('\nOn Kaggle but not in the manifest (pushing would not touch these):')
+ for slug in sorted(unmapped):
+ print(f' {slug}')
+ return 0
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description='Publish examples/*.ipynb to Kaggle as kernels')
+ parser.add_argument('--dry-run', action='store_true', help='Stage and validate, push nothing')
+ parser.add_argument('--only', help='Only sync kernels whose notebook or slug contains this substring')
+ parser.add_argument('--owner', help='Kaggle username (defaults to KAGGLE_USERNAME or ~/.kaggle/kaggle.json)')
+ parser.add_argument('--list', action='store_true', help='List the account kernels and reconcile with the manifest')
+ parser.add_argument('--stage-dir', type=Path, help='Keep the staged kernels here instead of a temp directory')
+ parser.add_argument(
+ '--session-wait', type=int, default=60, help='Seconds to wait for a free Kaggle session slot (default: 60)'
+ )
+ parser.add_argument(
+ '--session-retries', type=int, default=30, help='How many times to wait for a slot (default: 30)'
+ )
+ args = parser.parse_args()
+
+ kernels = load_kernels(MANIFEST)
+
+ errors = validate(kernels, EXAMPLES_DIR)
+ if errors:
+ print('Manifest is out of sync with examples/:', file=sys.stderr)
+ for error in errors:
+ print(f' {error}', file=sys.stderr)
+ return 1
+
+ owner = resolve_owner(args.owner)
+ if owner is None:
+ if args.list or not args.dry_run:
+ print('No Kaggle credentials. Set KAGGLE_USERNAME and KAGGLE_KEY, or pass --owner.', file=sys.stderr)
+ return 1
+ owner = PLACEHOLDER_OWNER
+ print('No Kaggle credentials found; staging with a placeholder owner.\n')
+
+ if args.list:
+ if args.only:
+ print('--only is ignored by --list, which always shows every kernel.\n')
+ return list_remote(owner, kernels)
+
+ if args.only:
+ kernels = [e for e in kernels if args.only in e['notebook'] or args.only in e['slug']]
+ if not kernels:
+ print(f'No kernel matches --only {args.only!r}', file=sys.stderr)
+ return 1
+
+ for entry in kernels:
+ if not check_kaggle_guard(EXAMPLES_DIR / entry['notebook']):
+ print(f'Warning: {entry["notebook"]} has no {KAGGLE_ENV_GUARD} branch; its assets will be missing.')
+
+ # One listing settles existence for every kernel, so the loop below makes no extra API calls.
+ remote = fetch_remote(owner) if owner != PLACEHOLDER_OWNER else None
+ if remote is None:
+ print('Could not read the account listing; update-vs-create is unknown for every kernel.\n')
+
+ staging_root = args.stage_dir
+ temp_dir = None
+ if staging_root is None:
+ temp_dir = tempfile.TemporaryDirectory(prefix='kaggle-sync-')
+ staging_root = Path(temp_dir.name)
+ staging_root.mkdir(parents=True, exist_ok=True)
+
+ failed: list[str] = []
+ renamed: list[tuple[str, str, str]] = []
+ try:
+ for entry in kernels:
+ target, current = resolve_target(entry, remote)
+
+ if target is None:
+ ref = f'{owner}/{entry["slug"]}'
+ message = f'{ref}: marked live but Kaggle has it under neither that slug nor the one its title implies'
+ if args.dry_run:
+ print(f'[dry-run] {ref} (BLOCKED) <- {entry["notebook"]}')
+ print(f' ORPHAN RISK: {message}.')
+ continue
+ print(f'Refusing {message}.', file=sys.stderr)
+ print(' Restore the original slug, or drop "live" if the kernel is genuinely new.', file=sys.stderr)
+ failed.append(ref)
+ continue
+
+ ref = f'{owner}/{target}'
+ moves_to = slugify(entry['title']) if current and current.title != entry['title'] else None
+ # Push against the slug Kaggle knows; a differing title is what asks it to rename.
+ staged = stage({**entry, 'slug': target}, EXAMPLES_DIR, staging_root, owner)
+
+ if args.dry_run:
+ if current:
+ state = f'update existing, {current.vote_count}'
+ elif remote is not None:
+ state = 'CREATE NEW'
+ else:
+ state = 'unknown'
+ print(f'[dry-run] {ref} ({state}) <- {entry["notebook"]}')
+ if moves_to:
+ print(f' retitle "{current.title}" -> "{entry["title"]}"')
+ print(f' URL MOVES {target} -> {moves_to}; the old address stops resolving.')
+ continue
+
+ print(f'Pushing {ref} <- {entry["notebook"]}')
+ try:
+ returncode, output = push_kernel(staged, args.session_retries, args.session_wait)
+ except FileNotFoundError:
+ print('The kaggle CLI is not installed. Run: pip install kaggle', file=sys.stderr)
+ return 1
+
+ if output:
+ print(' ' + output.replace('\n', '\n '))
+ if returncode != 0 or 'error' in output.lower():
+ failed.append(ref)
+ continue
+
+ landed = moves_to or target
+ print(f' https://www.kaggle.com/code/{owner}/{landed}')
+ if moves_to:
+ renamed.append((entry['notebook'], target, moves_to))
+ finally:
+ if temp_dir is not None:
+ temp_dir.cleanup()
+ elif args.dry_run:
+ print(f'\nStaged in {staging_root}')
+
+ if renamed:
+ # The manifest now names slugs that no longer exist. resolve_target still finds these
+ # kernels by title, but leaving the stale slugs in place makes every later run rely on
+ # that fallback instead of saying plainly where each kernel lives.
+ print(f'\n{len(renamed)} kernel(s) moved. Update {MANIFEST.name}:')
+ for notebook, before, after in renamed:
+ print(f' {notebook}: "slug": "{before}" -> "{after}"')
+
+ if failed:
+ print(f'\n{len(failed)} kernel(s) failed to push:', file=sys.stderr)
+ for ref in failed:
+ print(f' {ref}', file=sys.stderr)
+ return 1
+
+ if not args.dry_run:
+ print(f'\nPushed {len(kernels)} kernel(s). Kaggle runs each new version on its own.')
+ return 0
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/.github/workflows/kaggle.yml b/.github/workflows/kaggle.yml
new file mode 100644
index 0000000..d9ad673
--- /dev/null
+++ b/.github/workflows/kaggle.yml
@@ -0,0 +1,65 @@
+name: Publish Notebooks to Kaggle
+
+# Keeps the Kaggle kernels in step with examples/ so they cannot drift from the
+# released API. Runs on a published release, or on demand.
+#
+# Each push adds a new version to an existing kernel, so its upvotes, comments and
+# history carry over. Kaggle runs each new version itself and this job does not wait
+# for those runs, but it does pace itself: Kaggle refuses a push while five batch
+# sessions are already going, so submitting all fifteen takes a few waves.
+on:
+ release:
+ types: [published]
+ workflow_dispatch:
+ inputs:
+ mode:
+ description: 'list = show live kernels, dry-run = stage only, publish = push for real'
+ type: choice
+ options: [dry-run, list, publish]
+ default: dry-run
+ only:
+ description: 'Sync only kernels matching this substring (blank = all)'
+ type: string
+ default: ''
+
+permissions:
+ contents: read
+
+concurrency:
+ group: kaggle-publish
+ cancel-in-progress: false
+
+jobs:
+ publish:
+ runs-on: ubuntu-latest
+ timeout-minutes: 60
+
+ steps:
+ - uses: actions/checkout@v5
+
+ - uses: actions/setup-python@v6
+ with:
+ python-version: "3.11"
+
+ - name: Install Kaggle CLI
+ run: python -m pip install --upgrade pip kaggle
+
+ - name: Publish
+ env:
+ KAGGLE_USERNAME: ${{ secrets.KAGGLE_USERNAME }}
+ KAGGLE_KEY: ${{ secrets.KAGGLE_KEY }}
+ # Read through the environment so a hand-typed value cannot reach the shell as code.
+ MODE: ${{ inputs.mode }}
+ ONLY: ${{ inputs.only }}
+ run: |
+ set -euo pipefail
+ cmd=(python .github/kaggle/sync.py)
+ # A release carries no inputs, so an empty MODE means publish.
+ case "$MODE" in
+ list) cmd+=(--list) ;;
+ dry-run) cmd+=(--dry-run) ;;
+ esac
+ if [ -n "$ONLY" ]; then
+ cmd+=(--only "$ONLY")
+ fi
+ "${cmd[@]}"
diff --git a/README.md b/README.md
index a7fc8be..04dbcc8 100644
--- a/README.md
+++ b/README.md
@@ -8,6 +8,7 @@
[![Github Build Status](https://github.com/yakhyo/uniface/actions/workflows/ci.yml/badge.svg)](https://github.com/yakhyo/uniface/actions)
[![PyPI Downloads](https://static.pepy.tech/personalized-badge/uniface?period=total&units=INTERNATIONAL_SYSTEM&left_color=GRAY&right_color=BLUE&left_text=Downloads)](https://pepy.tech/projects/uniface)
[![Kaggle Badge](https://img.shields.io/badge/Notebooks-Kaggle?label=Kaggle&color=blue)](https://www.kaggle.com/yakhyokhuja/code)
+[![Hugging Face Spaces](https://img.shields.io/badge/Demo-%F0%9F%A4%97%20Spaces-blue)](https://huggingface.co/spaces/yakhyo/uniface)
</div>
diff --git a/docs/notebooks.md b/docs/notebooks.md
index ca25f21..31d2a3b 100644
--- a/docs/notebooks.md
+++ b/docs/notebooks.md
@@ -6,23 +6,23 @@ Run UniFace examples directly in your browser with Google Colab, or download and
## Available Notebooks
-| Notebook | Colab | Description |
-|----------|:-----:|-------------|
-| [Face Detection](https://github.com/yakhyo/uniface/blob/main/examples/01_face_detection.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/01_face_detection.ipynb) | Detect faces and 5-point landmarks |
-| [Face Alignment](https://github.com/yakhyo/uniface/blob/main/examples/02_face_alignment.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/02_face_alignment.ipynb) | Align faces for recognition |
-| [Face Verification](https://github.com/yakhyo/uniface/blob/main/examples/03_face_verification.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/03_face_verification.ipynb) | Compare faces for identity |
-| [Face Search](https://github.com/yakhyo/uniface/blob/main/examples/04_face_search.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/04_face_search.ipynb) | Find a person in group photos |
-| [Face Analyzer](https://github.com/yakhyo/uniface/blob/main/examples/05_face_analyzer.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/05_face_analyzer.ipynb) | Unified face analysis |
-| [Face Parsing](https://github.com/yakhyo/uniface/blob/main/examples/06_face_parsing.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/06_face_parsing.ipynb) | Semantic face segmentation |
-| [Face Anonymization](https://github.com/yakhyo/uniface/blob/main/examples/07_face_anonymization.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/07_face_anonymization.ipynb) | Privacy-preserving blur |
-| [Gaze Estimation](https://github.com/yakhyo/uniface/blob/main/examples/08_gaze_estimation.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/08_gaze_estimation.ipynb) | Gaze direction estimation |
-| [Face Segmentation](https://github.com/yakhyo/uniface/blob/main/examples/09_face_segmentation.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/09_face_segmentation.ipynb) | Face segmentation with XSeg |
-| [Face Vector Store](https://github.com/yakhyo/uniface/blob/main/examples/10_face_vector_store.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/10_face_vector_store.ipynb) | FAISS-backed face database |
-| [Head Pose Estimation](https://github.com/yakhyo/uniface/blob/main/examples/11_head_pose_estimation.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/11_head_pose_estimation.ipynb) | 3D head orientation estimation |
-| [Face Recognition](https://github.com/yakhyo/uniface/blob/main/examples/12_face_recognition.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/12_face_recognition.ipynb) | Standalone face recognition pipeline |
-| [Portrait Matting](https://github.com/yakhyo/uniface/blob/main/examples/13_portrait_matting.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/13_portrait_matting.ipynb) | Portrait matting with MODNet |
-| [Face Attributes](https://github.com/yakhyo/uniface/blob/main/examples/14_face_attributes.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/14_face_attributes.ipynb) | Face states (eyes, glasses, sunglasses, mask) |
-| [Face Mesh](https://github.com/yakhyo/uniface/blob/main/examples/15_face_mesh.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/15_face_mesh.ipynb) | 468 / 478-point dense 3D mesh |
+| Notebook | Colab | Kaggle | Description |
+|----------|:-----:|:------:|-------------|
+| [Face Detection](https://github.com/yakhyo/uniface/blob/main/examples/01_face_detection.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/01_face_detection.ipynb) | [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-detection-with-uniface) | Detect faces and 5-point landmarks |
+| [Face Alignment](https://github.com/yakhyo/uniface/blob/main/examples/02_face_alignment.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/02_face_alignment.ipynb) | [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-detection-and-alignment-with-uniface) | Align faces for recognition |
+| [Face Verification](https://github.com/yakhyo/uniface/blob/main/examples/03_face_verification.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/03_face_verification.ipynb) | [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-verification-one-to-one-face-comparison) | Compare faces for identity |
+| [Face Search](https://github.com/yakhyo/uniface/blob/main/examples/04_face_search.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/04_face_search.ipynb) | [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-search-one-to-many-face-matching) | Find a person in group photos |
+| [Face Analyzer](https://github.com/yakhyo/uniface/blob/main/examples/05_face_analyzer.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/05_face_analyzer.ipynb) | [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-analysis-with-uniface) | Unified face analysis |
+| [Face Parsing](https://github.com/yakhyo/uniface/blob/main/examples/06_face_parsing.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/06_face_parsing.ipynb) | [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-parsing-with-uniface) | Semantic face segmentation |
+| [Face Anonymization](https://github.com/yakhyo/uniface/blob/main/examples/07_face_anonymization.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/07_face_anonymization.ipynb) | [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-anonymization-with-uniface) | Privacy-preserving blur |
+| [Gaze Estimation](https://github.com/yakhyo/uniface/blob/main/examples/08_gaze_estimation.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/08_gaze_estimation.ipynb) | [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/gaze-estimation-with-uniface) | Gaze direction estimation |
+| [Face Segmentation](https://github.com/yakhyo/uniface/blob/main/examples/09_face_segmentation.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/09_face_segmentation.ipynb) | [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/xseg-face-segmentation) | Face segmentation with XSeg |
+| [Face Vector Store](https://github.com/yakhyo/uniface/blob/main/examples/10_face_vector_store.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/10_face_vector_store.ipynb) | [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-vector-store-with-faiss) | FAISS-backed face database |
+| [Head Pose Estimation](https://github.com/yakhyo/uniface/blob/main/examples/11_head_pose_estimation.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/11_head_pose_estimation.ipynb) | [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/head-pose-estimation-with-uniface) | 3D head orientation estimation |
+| [Face Recognition](https://github.com/yakhyo/uniface/blob/main/examples/12_face_recognition.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/12_face_recognition.ipynb) | [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-recognition-retinaface-align-arcface) | Standalone face recognition pipeline |
+| [Portrait Matting](https://github.com/yakhyo/uniface/blob/main/examples/13_portrait_matting.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/13_portrait_matting.ipynb) | [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/portrait-matting-with-modnet) | Portrait matting with MODNet |
+| [Face Attributes](https://github.com/yakhyo/uniface/blob/main/examples/14_face_attributes.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/14_face_attributes.ipynb) | [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-attribute-detection-with-uniface) | Face states (eyes, glasses, sunglasses, mask) |
+| [Face Mesh](https://github.com/yakhyo/uniface/blob/main/examples/15_face_mesh.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/15_face_mesh.ipynb) | [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/dense-face-mesh-with-uniface) | 468 / 478-point dense 3D mesh |
---
diff --git a/examples/01_face_detection.ipynb b/examples/01_face_detection.ipynb
index aaf97f3..77d66b0 100644
--- a/examples/01_face_detection.ipynb
+++ b/examples/01_face_detection.ipynb
@@ -6,7 +6,7 @@
"source": [
"# Face Detection with UniFace\n",
"\n",
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/01_face_detection.ipynb)\n",
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/01_face_detection.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-detection-with-uniface)\n",
"\n",
"Detect faces in an image and read back their boxes, confidences and 5-point landmarks.\n",
"\n",
@@ -29,9 +29,9 @@
"source": [
"%pip install -q \"uniface[cpu]\"\n",
"\n",
- "# Clone repo for assets (Colab only)\n",
+ "# Clone repo for assets (Colab / Kaggle only)\n",
"import os\n",
- "if 'COLAB_GPU' in os.environ or 'COLAB_RELEASE_TAG' in os.environ:\n",
+ "if any(k in os.environ for k in ('COLAB_GPU', 'COLAB_RELEASE_TAG', 'KAGGLE_KERNEL_RUN_TYPE')):\n",
" if not os.path.exists('uniface'):\n",
" !git clone --depth 1 https://github.com/yakhyo/uniface.git\n",
" os.chdir('uniface/examples')"
diff --git a/examples/02_face_alignment.ipynb b/examples/02_face_alignment.ipynb
index 23a22a0..bd4a781 100644
--- a/examples/02_face_alignment.ipynb
+++ b/examples/02_face_alignment.ipynb
@@ -10,7 +10,7 @@
"source": [
"# Face Detection and Alignment with UniFace\n",
"\n",
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/02_face_alignment.ipynb)\n",
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/02_face_alignment.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-detection-and-alignment-with-uniface)\n",
"\n",
"Detect a face, then align and crop it to the 112x112 input that recognition models expect.\n",
"\n",
@@ -31,9 +31,9 @@
"source": [
"%pip install -q \"uniface[cpu]\"\n",
"\n",
- "# Clone repo for assets (Colab only)\n",
+ "# Clone repo for assets (Colab / Kaggle only)\n",
"import os\n",
- "if 'COLAB_GPU' in os.environ or 'COLAB_RELEASE_TAG' in os.environ:\n",
+ "if any(k in os.environ for k in ('COLAB_GPU', 'COLAB_RELEASE_TAG', 'KAGGLE_KERNEL_RUN_TYPE')):\n",
" if not os.path.exists('uniface'):\n",
" !git clone --depth 1 https://github.com/yakhyo/uniface.git\n",
" os.chdir('uniface/examples')"
diff --git a/examples/03_face_verification.ipynb b/examples/03_face_verification.ipynb
index af7920e..a164eaa 100644
--- a/examples/03_face_verification.ipynb
+++ b/examples/03_face_verification.ipynb
@@ -6,7 +6,7 @@
"source": [
"# Face Verification: One-to-One Face Comparison\n",
"\n",
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/03_face_verification.ipynb)\n",
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/03_face_verification.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-verification-one-to-one-face-comparison)\n",
"\n",
"Compare two face images and decide whether they show the same person.\n",
"\n",
@@ -29,9 +29,9 @@
"source": [
"%pip install -q \"uniface[cpu]\"\n",
"\n",
- "# Clone repo for assets (Colab only)\n",
+ "# Clone repo for assets (Colab / Kaggle only)\n",
"import os\n",
- "if 'COLAB_GPU' in os.environ or 'COLAB_RELEASE_TAG' in os.environ:\n",
+ "if any(k in os.environ for k in ('COLAB_GPU', 'COLAB_RELEASE_TAG', 'KAGGLE_KERNEL_RUN_TYPE')):\n",
" if not os.path.exists('uniface'):\n",
" !git clone --depth 1 https://github.com/yakhyo/uniface.git\n",
" os.chdir('uniface/examples')"
diff --git a/examples/04_face_search.ipynb b/examples/04_face_search.ipynb
index a5bfee0..6bf4aa3 100644
--- a/examples/04_face_search.ipynb
+++ b/examples/04_face_search.ipynb
@@ -6,7 +6,7 @@
"source": [
"# Face Search: One-to-Many Face Matching\n",
"\n",
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/04_face_search.ipynb)\n",
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/04_face_search.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-search-one-to-many-face-matching)\n",
"\n",
"Search a group photo for one known person by comparing embeddings.\n",
"\n",
@@ -27,9 +27,9 @@
"source": [
"%pip install -q \"uniface[cpu]\"\n",
"\n",
- "# Clone repo for assets (Colab only)\n",
+ "# Clone repo for assets (Colab / Kaggle only)\n",
"import os\n",
- "if 'COLAB_GPU' in os.environ or 'COLAB_RELEASE_TAG' in os.environ:\n",
+ "if any(k in os.environ for k in ('COLAB_GPU', 'COLAB_RELEASE_TAG', 'KAGGLE_KERNEL_RUN_TYPE')):\n",
" if not os.path.exists('uniface'):\n",
" !git clone --depth 1 https://github.com/yakhyo/uniface.git\n",
" os.chdir('uniface/examples')"
diff --git a/examples/05_face_analyzer.ipynb b/examples/05_face_analyzer.ipynb
index 33c95be..74a0b18 100644
--- a/examples/05_face_analyzer.ipynb
+++ b/examples/05_face_analyzer.ipynb
@@ -6,7 +6,7 @@
"source": [
"# Face Analysis with UniFace\n",
"\n",
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/05_face_analyzer.ipynb)\n",
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/05_face_analyzer.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-analysis-with-uniface)\n",
"\n",
"`FaceAnalyzer` runs detection, alignment, recognition and any attribute predictors in a single call.\n",
"\n",
@@ -27,9 +27,9 @@
"source": [
"%pip install -q \"uniface[cpu]\"\n",
"\n",
- "# Clone repo for assets (Colab only)\n",
+ "# Clone repo for assets (Colab / Kaggle only)\n",
"import os\n",
- "if 'COLAB_GPU' in os.environ or 'COLAB_RELEASE_TAG' in os.environ:\n",
+ "if any(k in os.environ for k in ('COLAB_GPU', 'COLAB_RELEASE_TAG', 'KAGGLE_KERNEL_RUN_TYPE')):\n",
" if not os.path.exists('uniface'):\n",
" !git clone --depth 1 https://github.com/yakhyo/uniface.git\n",
" os.chdir('uniface/examples')"
diff --git a/examples/06_face_parsing.ipynb b/examples/06_face_parsing.ipynb
index 76c8115..bebc592 100644
--- a/examples/06_face_parsing.ipynb
+++ b/examples/06_face_parsing.ipynb
@@ -6,7 +6,7 @@
"source": [
"# Face Parsing with UniFace\n",
"\n",
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/06_face_parsing.ipynb)\n",
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/06_face_parsing.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-parsing-with-uniface)\n",
"\n",
"Label every pixel of a face as skin, eyes, nose, mouth, hair and so on, using BiSeNet.\n",
"Face parsing segments a face image into different facial components such as skin, eyes, nose, mouth, hair, etc.\n",
@@ -30,9 +30,9 @@
"source": [
"%pip install -q \"uniface[cpu]\"\n",
"\n",
- "# Clone repo for assets (Colab only)\n",
+ "# Clone repo for assets (Colab / Kaggle only)\n",
"import os\n",
- "if 'COLAB_GPU' in os.environ or 'COLAB_RELEASE_TAG' in os.environ:\n",
+ "if any(k in os.environ for k in ('COLAB_GPU', 'COLAB_RELEASE_TAG', 'KAGGLE_KERNEL_RUN_TYPE')):\n",
" if not os.path.exists('uniface'):\n",
" !git clone --depth 1 https://github.com/yakhyo/uniface.git\n",
" os.chdir('uniface/examples')"
diff --git a/examples/07_face_anonymization.ipynb b/examples/07_face_anonymization.ipynb
index b167bf7..b03ae39 100644
--- a/examples/07_face_anonymization.ipynb
+++ b/examples/07_face_anonymization.ipynb
@@ -6,7 +6,7 @@
"source": [
"# Face Anonymization with UniFace\n",
"\n",
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/07_face_anonymization.ipynb)\n",
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/07_face_anonymization.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-anonymization-with-uniface)\n",
"\n",
"Hide faces in an image using five blur methods.\n",
"\n",
@@ -29,9 +29,9 @@
"source": [
"%pip install -q \"uniface[cpu]\"\n",
"\n",
- "# Clone repo for assets (Colab only)\n",
+ "# Clone repo for assets (Colab / Kaggle only)\n",
"import os\n",
- "if 'COLAB_GPU' in os.environ or 'COLAB_RELEASE_TAG' in os.environ:\n",
+ "if any(k in os.environ for k in ('COLAB_GPU', 'COLAB_RELEASE_TAG', 'KAGGLE_KERNEL_RUN_TYPE')):\n",
" if not os.path.exists('uniface'):\n",
" !git clone --depth 1 https://github.com/yakhyo/uniface.git\n",
" os.chdir('uniface/examples')"
diff --git a/examples/08_gaze_estimation.ipynb b/examples/08_gaze_estimation.ipynb
index ea5f9c2..076a801 100644
--- a/examples/08_gaze_estimation.ipynb
+++ b/examples/08_gaze_estimation.ipynb
@@ -6,7 +6,7 @@
"source": [
"# Gaze Estimation with UniFace\n",
"\n",
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/08_gaze_estimation.ipynb)\n",
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/08_gaze_estimation.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/gaze-estimation-with-uniface)\n",
"\n",
"Estimate which way a person is looking from a face crop.\n",
"\n",
@@ -29,9 +29,9 @@
"source": [
"%pip install -q \"uniface[cpu]\"\n",
"\n",
- "# Clone repo for assets (Colab only)\n",
+ "# Clone repo for assets (Colab / Kaggle only)\n",
"import os\n",
- "if 'COLAB_GPU' in os.environ or 'COLAB_RELEASE_TAG' in os.environ:\n",
+ "if any(k in os.environ for k in ('COLAB_GPU', 'COLAB_RELEASE_TAG', 'KAGGLE_KERNEL_RUN_TYPE')):\n",
" if not os.path.exists('uniface'):\n",
" !git clone --depth 1 https://github.com/yakhyo/uniface.git\n",
" os.chdir('uniface/examples')"
diff --git a/examples/09_face_segmentation.ipynb b/examples/09_face_segmentation.ipynb
index dbc55fa..494a5ab 100644
--- a/examples/09_face_segmentation.ipynb
+++ b/examples/09_face_segmentation.ipynb
@@ -6,7 +6,7 @@
"source": [
"# XSeg Face Segmentation\n",
"\n",
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/09_face_segmentation.ipynb)\n",
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/09_face_segmentation.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/xseg-face-segmentation)\n",
"\n",
"Produce one soft face mask with XSeg, which aligns on landmarks before segmenting.\n",
"XSeg outputs a mask for face regions. Unlike BiSeNet which works on bbox crops, XSeg requires 5-point landmarks for face alignment.\n",
@@ -30,9 +30,9 @@
"source": [
"%pip install -q \"uniface[cpu]\"\n",
"\n",
- "# Clone repo for assets (Colab only)\n",
+ "# Clone repo for assets (Colab / Kaggle only)\n",
"import os\n",
- "if 'COLAB_GPU' in os.environ or 'COLAB_RELEASE_TAG' in os.environ:\n",
+ "if any(k in os.environ for k in ('COLAB_GPU', 'COLAB_RELEASE_TAG', 'KAGGLE_KERNEL_RUN_TYPE')):\n",
" if not os.path.exists('uniface'):\n",
" !git clone --depth 1 https://github.com/yakhyo/uniface.git\n",
" os.chdir('uniface/examples')"
diff --git a/examples/10_face_vector_store.ipynb b/examples/10_face_vector_store.ipynb
index 4475405..23389d2 100644
--- a/examples/10_face_vector_store.ipynb
+++ b/examples/10_face_vector_store.ipynb
@@ -6,7 +6,7 @@
"source": [
"# Face Vector Store with FAISS\n",
"\n",
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/10_face_vector_store.ipynb)\n",
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/10_face_vector_store.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-vector-store-with-faiss)\n",
"\n",
"Enrol faces into a FAISS index, search it, and save it to disk.\n",
"Unlike direct pairwise comparison (see `04_face_search`), a vector store lets you efficiently index\n",
@@ -29,9 +29,9 @@
"source": [
"%pip install -q \"uniface[cpu]\" faiss-cpu\n",
"\n",
- "# Clone repo for assets (Colab only)\n",
+ "# Clone repo for assets (Colab / Kaggle only)\n",
"import os\n",
- "if 'COLAB_GPU' in os.environ or 'COLAB_RELEASE_TAG' in os.environ:\n",
+ "if any(k in os.environ for k in ('COLAB_GPU', 'COLAB_RELEASE_TAG', 'KAGGLE_KERNEL_RUN_TYPE')):\n",
" if not os.path.exists('uniface'):\n",
" !git clone --depth 1 https://github.com/yakhyo/uniface.git\n",
" os.chdir('uniface/examples')"
diff --git a/examples/11_head_pose_estimation.ipynb b/examples/11_head_pose_estimation.ipynb
index cc8c757..1170f28 100644
--- a/examples/11_head_pose_estimation.ipynb
+++ b/examples/11_head_pose_estimation.ipynb
@@ -6,7 +6,7 @@
"source": [
"# Head Pose Estimation with UniFace\n",
"\n",
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/11_head_pose_estimation.ipynb)\n",
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/11_head_pose_estimation.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/head-pose-estimation-with-uniface)\n",
"\n",
"Read the pitch, yaw and roll of a head from a face crop.\n",
"\n",
@@ -29,9 +29,9 @@
"source": [
"%pip install -q \"uniface[cpu]\"\n",
"\n",
- "# Clone repo for assets (Colab only)\n",
+ "# Clone repo for assets (Colab / Kaggle only)\n",
"import os\n",
- "if 'COLAB_GPU' in os.environ or 'COLAB_RELEASE_TAG' in os.environ:\n",
+ "if any(k in os.environ for k in ('COLAB_GPU', 'COLAB_RELEASE_TAG', 'KAGGLE_KERNEL_RUN_TYPE')):\n",
" if not os.path.exists('uniface'):\n",
" !git clone --depth 1 https://github.com/yakhyo/uniface.git\n",
" os.chdir('uniface/examples')"
diff --git a/examples/12_face_recognition.ipynb b/examples/12_face_recognition.ipynb
index 7cd1262..295168f 100644
--- a/examples/12_face_recognition.ipynb
+++ b/examples/12_face_recognition.ipynb
@@ -7,7 +7,7 @@
"source": [
"# Face Recognition: RetinaFace → Align → ArcFace\n",
"\n",
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/12_face_recognition.ipynb)\n",
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/12_face_recognition.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-recognition-retinaface-align-arcface)\n",
"\n",
"Run recognition step by step, without the `FaceAnalyzer` wrapper:\n",
"1. **RetinaFace**: Detects faces and extracts 5-point landmarks.\n",
@@ -35,9 +35,9 @@
"source": [
"%pip install -q \"uniface[cpu]\"\n",
"\n",
- "# Clone repo for assets (Colab only)\n",
+ "# Clone repo for assets (Colab / Kaggle only)\n",
"import os\n",
- "if 'COLAB_GPU' in os.environ or 'COLAB_RELEASE_TAG' in os.environ:\n",
+ "if any(k in os.environ for k in ('COLAB_GPU', 'COLAB_RELEASE_TAG', 'KAGGLE_KERNEL_RUN_TYPE')):\n",
" if not os.path.exists('uniface'):\n",
" !git clone --depth 1 https://github.com/yakhyo/uniface.git\n",
" os.chdir('uniface/examples')"
diff --git a/examples/13_portrait_matting.ipynb b/examples/13_portrait_matting.ipynb
index 9795fe5..79da0c6 100644
--- a/examples/13_portrait_matting.ipynb
+++ b/examples/13_portrait_matting.ipynb
@@ -6,7 +6,7 @@
"source": [
"# Portrait Matting with MODNet\n",
"\n",
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/13_portrait_matting.ipynb)\n",
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/13_portrait_matting.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/portrait-matting-with-modnet)\n",
"\n",
"MODNet produces a soft alpha matte from a full image. It is trimap-free, so it needs no face detection and no cropping.\n",
"\n",
@@ -29,9 +29,9 @@
"source": [
"%pip install -q \"uniface[cpu]\"\n",
"\n",
- "# Clone repo for assets (Colab only)\n",
+ "# Clone repo for assets (Colab / Kaggle only)\n",
"import os\n",
- "if 'COLAB_GPU' in os.environ or 'COLAB_RELEASE_TAG' in os.environ:\n",
+ "if any(k in os.environ for k in ('COLAB_GPU', 'COLAB_RELEASE_TAG', 'KAGGLE_KERNEL_RUN_TYPE')):\n",
" if not os.path.exists('uniface'):\n",
" !git clone --depth 1 https://github.com/yakhyo/uniface.git\n",
" os.chdir('uniface/examples')"
diff --git a/examples/14_face_attributes.ipynb b/examples/14_face_attributes.ipynb
index 8e830df..555b397 100644
--- a/examples/14_face_attributes.ipynb
+++ b/examples/14_face_attributes.ipynb
@@ -6,7 +6,7 @@
"source": [
"# Face Attribute Detection with UniFace\n",
"\n",
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/14_face_attributes.ipynb)\n",
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/14_face_attributes.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/face-attribute-detection-with-uniface)\n",
"\n",
"FaceAttribNet reads five independent binary states per face: left and right eye openness, eyeglasses, face mask, and sunglasses.\n",
"\n",
@@ -29,9 +29,9 @@
"source": [
"%pip install -q \"uniface[cpu]\"\n",
"\n",
- "# Clone repo for assets (Colab only)\n",
+ "# Clone repo for assets (Colab / Kaggle only)\n",
"import os\n",
- "if 'COLAB_GPU' in os.environ or 'COLAB_RELEASE_TAG' in os.environ:\n",
+ "if any(k in os.environ for k in ('COLAB_GPU', 'COLAB_RELEASE_TAG', 'KAGGLE_KERNEL_RUN_TYPE')):\n",
" if not os.path.exists('uniface'):\n",
" !git clone --depth 1 https://github.com/yakhyo/uniface.git\n",
" os.chdir('uniface/examples')"
diff --git a/examples/15_face_mesh.ipynb b/examples/15_face_mesh.ipynb
index a0a34d2..dadd3bb 100644
--- a/examples/15_face_mesh.ipynb
+++ b/examples/15_face_mesh.ipynb
@@ -6,7 +6,7 @@
"source": [
"# Dense Face Mesh with UniFace\n",
"\n",
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/15_face_mesh.ipynb)\n",
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/yakhyo/uniface/blob/main/examples/15_face_mesh.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://www.kaggle.com/code/yakhyokhuja/dense-face-mesh-with-uniface)\n",
"\n",
"MediaPipe Face Mesh fits 468 dense 3D landmarks to a face, or 478 with the irises.\n",
"Unlike the other landmark models it returns **three** coordinates per point and a face-presence score, and it runs every face in an image through a **single batched inference call**.\n",
@@ -30,9 +30,9 @@
"source": [
"%pip install -q \"uniface[cpu]\"\n",
"\n",
- "# Clone repo for assets (Colab only)\n",
+ "# Clone repo for assets (Colab / Kaggle only)\n",
"import os\n",
- "if 'COLAB_GPU' in os.environ or 'COLAB_RELEASE_TAG' in os.environ:\n",
+ "if any(k in os.environ for k in ('COLAB_GPU', 'COLAB_RELEASE_TAG', 'KAGGLE_KERNEL_RUN_TYPE')):\n",
" if not os.path.exists('uniface'):\n",
" !git clone --depth 1 https://github.com/yakhyo/uniface.git\n",
" os.chdir('uniface/examples')"
diff --git a/tools/demo/demo_render.py b/tools/demo/demo_render.py
new file mode 100644
index 0000000..595792a
--- /dev/null
+++ b/tools/demo/demo_render.py
@@ -0,0 +1,208 @@
+"""Annotation renderer for UniFace demo images.
+
+Draws with PIL rather than OpenCV so text is a real anti-aliased typeface instead
+of a Hershey stroke font, and so brackets and chips can be alpha-blended. Every
+stroke is laid over a soft dark shadow, which is what lets a single accent colour
+stay legible on both a bright wall and a night crowd.
+"""
+
+from __future__ import annotations
+
+import glob
+import os
+
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+
+ACCENT = (34, 211, 238)
+MATCH = (16, 205, 140)
+REJECT = (251, 89, 110)
+AMBER = (251, 176, 36)
+VIOLET = (167, 139, 250)
+INK = (11, 15, 25)
+PAPER = (248, 250, 252)
+
+_FONT_CANDIDATES = (
+ '/System/Library/Fonts/SFNSRounded.ttf',
+ '/System/Library/Fonts/HelveticaNeue.ttc',
+ '/System/Library/Fonts/Supplemental/Arial Bold.ttf',
+)
+_FONT_CACHE: dict[int, ImageFont.FreeTypeFont] = {}
+
+
+def _font_path() -> str:
+ for path in _FONT_CANDIDATES:
+ if os.path.exists(path):
+ return path
+
+ import matplotlib
+
+ hits = glob.glob(os.path.join(os.path.dirname(matplotlib.__file__), 'mpl-data/fonts/ttf/DejaVuSans-Bold.ttf'))
+ if not hits:
+ raise RuntimeError('no usable TrueType font found')
+ return hits[0]
+
+
+def font(size: int) -> ImageFont.FreeTypeFont:
+ size = max(9, int(size))
+ if size not in _FONT_CACHE:
+ _FONT_CACHE[size] = ImageFont.truetype(_font_path(), size)
+ return _FONT_CACHE[size]
+
+
+def to_pil(image: np.ndarray) -> Image.Image:
+ """BGR uint8 array (OpenCV convention) -> RGB PIL image."""
+ return Image.fromarray(image[:, :, ::-1].copy())
+
+
+def to_bgr(image: Image.Image) -> np.ndarray:
+ return np.array(image.convert('RGB'))[:, :, ::-1].copy()
+
+
+class Canvas:
+ """A PIL drawing surface with an alpha overlay for translucent fills."""
+
+ def __init__(self, image: Image.Image | np.ndarray):
+ self.base = to_pil(image) if isinstance(image, np.ndarray) else image.convert('RGB')
+ self.overlay = Image.new('RGBA', self.base.size, (0, 0, 0, 0))
+ self.draw = ImageDraw.Draw(self.overlay)
+
+ @property
+ def size(self) -> tuple[int, int]:
+ return self.base.size
+
+ def scale(self, factor: float = 1.0) -> float:
+ """A resolution-independent unit: 1.0 at 1600px on the long edge."""
+ return max(self.base.size) / 1600 * factor
+
+ def result(self) -> Image.Image:
+ out = self.base.convert('RGBA')
+ out.alpha_composite(self.overlay)
+ return out.convert('RGB')
+
+ def save(self, path: str, quality: int = 85) -> str:
+ img = self.result()
+ if path.lower().endswith(('.jpg', '.jpeg')):
+ img.save(path, quality=quality, subsampling=0)
+ else:
+ img.save(path)
+ return path
+
+ def _line(self, pts, color, width, alpha=255):
+ self.draw.line(tuple(pts), fill=(*color, alpha), width=max(1, int(width)), joint='curve')
+
+ def corner_box(self, bbox, color=ACCENT, width=None, proportion=0.24, edge_alpha=42):
+ """Corner-bracket box: 8 short strokes, each over a dark shadow stroke.
+
+ The faint full rectangle stays at low alpha so the box still reads as a
+ rectangle without competing with the face inside it.
+ """
+ x1, y1, x2, y2 = (float(v) for v in bbox)
+ w, h = x2 - x1, y2 - y1
+ if w <= 1 or h <= 1:
+ return
+
+ width = width or max(1.8, min(w, h) * 0.055, max(self.base.size) * 0.0016)
+ length = max(4.0, proportion * min(w, h))
+
+ self.draw.rectangle([x1, y1, x2, y2], outline=(*color, edge_alpha), width=max(1, int(width * 0.4)))
+
+ arms = (
+ ((x1, y1 + length), (x1, y1), (x1 + length, y1)),
+ ((x2 - length, y1), (x2, y1), (x2, y1 + length)),
+ ((x1, y2 - length), (x1, y2), (x1 + length, y2)),
+ ((x2 - length, y2), (x2, y2), (x2, y2 - length)),
+ )
+ for arm in arms:
+ self._line(arm, (0, 0, 0), width * 1.9, alpha=70)
+ for arm in arms:
+ self._line(arm, color, width, alpha=255)
+
+ def chip(self, text, xy, color=ACCENT, text_color=INK, size=None, anchor='bottom-left', radius=None):
+ """Rounded label chip. Clamped so it never leaves the frame."""
+ size = int(size or 13 * self.scale())
+ f = font(size)
+ pad_x, pad_y = size * 0.5, size * 0.3
+ left, top, right, bottom = self.draw.textbbox((0, 0), text, font=f)
+ tw, th = right - left, bottom - top
+ bw, bh = tw + pad_x * 2, th + pad_y * 2
+ x, y = xy
+
+ if anchor == 'bottom-left':
+ box = [x, y - bh, x + bw, y]
+ elif anchor == 'top-left':
+ box = [x, y, x + bw, y + bh]
+ else:
+ raise ValueError(anchor)
+
+ W, H = self.base.size
+ dx = min(0, W - 2 - box[2]) - min(0, box[0] - 2)
+ dy = min(0, H - 2 - box[3]) - min(0, box[1] - 2)
+ box = [box[0] + dx, box[1] + dy, box[2] + dx, box[3] + dy]
+
+ rad = radius if radius is not None else bh * 0.28
+ self.draw.rounded_rectangle([box[0] + 1, box[1] + 2, box[2] + 1, box[3] + 2], rad, fill=(0, 0, 0, 60))
+ self.draw.rounded_rectangle(box, rad, fill=(*color, 255))
+ self.draw.text((box[0] + pad_x - left, box[1] + pad_y - top), text, font=f, fill=(*text_color, 255))
+ return box
+
+ def points(self, pts, color=ACCENT, radius=None, ring=True):
+ """Landmark dots in one accent colour, each with a dark ring for contrast."""
+ radius = radius or max(1.5, 2.2 * self.scale())
+ for x, y in np.asarray(pts, dtype=float)[:, :2]:
+ if ring:
+ self.draw.ellipse(
+ [x - radius * 1.75, y - radius * 1.75, x + radius * 1.75, y + radius * 1.75],
+ fill=(0, 0, 0, 90),
+ )
+ self.draw.ellipse([x - radius, y - radius, x + radius, y + radius], fill=(*color, 255))
+
+ def arrow(self, start, end, color=ACCENT, width=None, head=None):
+ width = width or max(2.0, 3.0 * self.scale())
+ head = head or width * 3.2
+ (x1, y1), (x2, y2) = start, end
+ ang = np.arctan2(y2 - y1, x2 - x1)
+
+ self._line([(x1, y1), (x2, y2)], (0, 0, 0), width * 1.6, alpha=48)
+ self._line([(x1, y1), (x2, y2)], color, width, alpha=255)
+
+ for sign in (1, -1):
+ a = ang + sign * np.deg2rad(150)
+ self._line(
+ [(x2, y2), (x2 + head * np.cos(a), y2 + head * np.sin(a))],
+ (0, 0, 0),
+ width * 1.6,
+ alpha=48,
+ )
+ for sign in (1, -1):
+ a = ang + sign * np.deg2rad(150)
+ self._line([(x2, y2), (x2 + head * np.cos(a), y2 + head * np.sin(a))], color, width, alpha=255)
+
+ def banner(self, text, side='bottom-left', size=None, fg=PAPER, bg=(0, 0, 0), bg_alpha=150):
+ """Caption bar. Sized to survive the downscale a README applies."""
+ size = int(size or 30 * self.scale())
+ f = font(size)
+ pad = size * 0.55
+ left, top, right, bottom = self.draw.textbbox((0, 0), text, font=f)
+ tw, th = right - left, bottom - top
+ W, H = self.base.size
+ margin = size * 0.7
+ bw, bh = tw + pad * 2, th + pad * 1.5
+ x = margin if 'left' in side else W - margin - bw
+ y = margin if 'top' in side else H - margin - bh
+ self.draw.rounded_rectangle([x, y, x + bw, y + bh], bh * 0.24, fill=(*bg, bg_alpha))
+ self.draw.text((x + pad - left, y + pad * 0.75 - top), text, font=f, fill=(*fg, 255))
+
+
+def hstack(images, gap=16, bg=(138, 138, 138)):
+ """Side-by-side strip on a mid-grey ground that reads in light and dark themes."""
+ ims = [im if isinstance(im, Image.Image) else to_pil(im) for im in images]
+ h = max(i.height for i in ims)
+ ims = [i.resize((round(i.width * h / i.height), h), Image.LANCZOS) for i in ims]
+ W = sum(i.width for i in ims) + gap * (len(ims) - 1)
+ out = Image.new('RGB', (W, h), bg)
+ x = 0
+ for i in ims:
+ out.paste(i, (x, 0))
+ x += i.width + gap
+ return out
diff --git a/tools/demo/strip.py b/tools/demo/strip.py
new file mode 100644
index 0000000..32011d9
--- /dev/null
+++ b/tools/demo/strip.py
@@ -0,0 +1,65 @@
+"""Face-tile strip: N square face crops in a row or grid.
+
+Each tile carries a headline value and a sub-label under it. Used for age/gender, emotion,
+face states and FairFace so those components share one visual language.
+"""
+
+import cv2
+from demo_render import Canvas, font, to_pil
+from PIL import Image
+
+from uniface.constants import SCRFDWeights
+from uniface.detection import SCRFD
+
+_det = SCRFD(model_name=SCRFDWeights.SCRFD_10G_KPS, confidence_threshold=0.4, providers=['CPUExecutionProvider'])
+
+
+def load(path, long=1600):
+ img = cv2.imread(path)
+ if img is None:
+ raise FileNotFoundError(path)
+ h, w = img.shape[:2]
+ s = long / max(h, w)
+ if s < 1:
+ img = cv2.resize(img, (round(w * s), round(h * s)), interpolation=cv2.INTER_AREA)
+ return img
+
+
+def biggest(img):
+ fs = _det.detect(img)
+ if not fs:
+ return None
+ return max(fs, key=lambda f: (f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1]))
+
+
+def tile(img, face, size=330, margin=0.5):
+ x1, y1, x2, y2 = face.bbox
+ cx, cy = (x1 + x2) / 2, (y1 + y2) / 2
+ half = max(x2 - x1, y2 - y1) * (1 + margin) / 2
+ H, W = img.shape[:2]
+ half = min(half, cx, cy, W - cx, H - cy)
+ crop = img[int(cy - half) : int(cy + half), int(cx - half) : int(cx + half)]
+ return cv2.resize(crop, (size, size), interpolation=cv2.INTER_AREA)
+
+
+def render(items, out, footer, cols=None, size=330, headline_pt=38, sub_pt=19, foot_gap=34, foot_pt=20):
+ """items: list of (tile_bgr, headline, sub, colour)."""
+ cols = cols or len(items)
+ nrows = (len(items) + cols - 1) // cols
+ PAD, G, CAP = 26, 14, headline_pt + sub_pt + 26
+ W = PAD * 2 + size * cols + G * (cols - 1)
+ H = PAD + (size + CAP) * nrows + G * (nrows - 1) + foot_gap + foot_pt
+ c = Canvas(Image.new('RGB', (W, H), (26, 30, 38)))
+ fh, fs_ = font(headline_pt), font(sub_pt)
+ for i, (t, head, sub, col) in enumerate(items):
+ r, k = divmod(i, cols)
+ x = PAD + k * (size + G)
+ y = PAD + r * (size + CAP + G)
+ c.base.paste(to_pil(t), (x, y))
+ c.draw.text((x + size / 2, y + size + 26), head, font=fh, fill=(*col, 255), anchor='mm')
+ c.draw.text((x + size / 2, y + size + 56), sub, font=fs_, fill=(150, 158, 170, 255), anchor='mm')
+ c.draw.text((PAD, H - foot_pt - 8), footer, font=font(foot_pt), fill=(150, 158, 170, 255))
+ c.save(out)
+ print(out, c.size, f'ratio={c.size[0] / c.size[1]:.2f}')
+ for _, head, sub, _ in items:
+ print(f' {head:<22} {sub}')