CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-insightface

A comprehensive 2D and 3D face analysis toolkit with state-of-the-art algorithms for face recognition, detection, and alignment.

Pending
Overview
Eval results
Files

cli.mddocs/

Command Line Interface

Command-line tools for model management, dataset processing, and InsightFace operations. Provides convenient CLI access to common tasks without requiring Python scripting.

Capabilities

CLI Entry Point

Main command-line interface providing access to all InsightFace CLI commands.

def main() -> None:
    """
    Main CLI entry point for insightface-cli command.
    
    Provides access to subcommands for model management and data processing.
    """

Model Download Command

Command for downloading and managing pre-trained model packs.

class ModelDownloadCommand:
    def __init__(self, model: str, root: str, force: bool):
        """
        Initialize model download command.
        
        Parameters:
        - model: str, model pack name to download
        - root: str, storage root directory
        - force: bool, force re-download even if model exists
        """
    
    def run(self) -> None:
        """Execute model download operation."""

Dataset Processing Commands

Commands for processing recognition datasets and adding augmentation parameters.

class RecAddMaskParamCommand:
    def __init__(self, input_path: str, output_path: str):
        """
        Initialize command to add mask parameters to recognition datasets.
        
        Parameters:
        - input_path: str, path to input dataset file (.rec format)
        - output_path: str, path for output dataset with mask parameters
        """
    
    def run(self) -> None:
        """Execute mask parameter addition to dataset."""

Command Line Usage

Model Management

Download and manage pre-trained model packs using the CLI.

# Download default model pack (buffalo_l)
insightface-cli model.download buffalo_l

# Download specific model pack
insightface-cli model.download buffalo_s

# Download model pack to custom directory
insightface-cli model.download buffalo_m --root ./my_models

# Force re-download of existing model pack
insightface-cli model.download buffalo_l --force

# Download multiple model packs
insightface-cli model.download buffalo_l buffalo_s buffalo_m

Dataset Processing

Process recognition datasets for training and evaluation.

# Add mask parameters to recognition dataset
insightface-cli rec.add_mask_param --input dataset.rec --output masked_dataset.rec

# Process multiple datasets
insightface-cli rec.add_mask_param --input train.rec --output train_masked.rec
insightface-cli rec.add_mask_param --input val.rec --output val_masked.rec

Help and Information

Get help and information about available commands.

# Show general help
insightface-cli --help

# Show help for specific command
insightface-cli model.download --help
insightface-cli rec.add_mask_param --help

# List available model packs
insightface-cli model.list

Python API Usage

You can also use the CLI commands programmatically from Python code.

Programmatic Model Download

from insightface.commands.model_download import ModelDownloadCommand

# Create and execute download command
cmd = ModelDownloadCommand(model='buffalo_l', root='~/.insightface', force=False)
cmd.run()

print("Model download completed")

Programmatic Dataset Processing

from insightface.commands.rec_add_mask_param import RecAddMaskParamCommand

# Process dataset with mask parameters
cmd = RecAddMaskParamCommand(
    input_path='original_dataset.rec',
    output_path='masked_dataset.rec'
)
cmd.run()

print("Dataset processing completed")

Batch Operations

def download_all_models(root_dir='./models'):
    """Download all common model packs."""
    models = ['buffalo_l', 'buffalo_m', 'buffalo_s', 'antelopev2']
    
    for model_name in models:
        print(f"Downloading {model_name}...")
        cmd = ModelDownloadCommand(model=model_name, root=root_dir, force=False)
        try:
            cmd.run()
            print(f"✓ {model_name} downloaded successfully")
        except Exception as e:
            print(f"✗ Failed to download {model_name}: {e}")

# Execute batch download
download_all_models()

Dataset Pipeline Integration

def prepare_training_datasets(input_dir, output_dir):
    """Prepare datasets for masked face training."""
    import os
    from pathlib import Path
    
    input_path = Path(input_dir)
    output_path = Path(output_dir)
    output_path.mkdir(exist_ok=True)
    
    # Process all .rec files in input directory
    for rec_file in input_path.glob('*.rec'):
        output_file = output_path / f"masked_{rec_file.name}"
        
        print(f"Processing {rec_file.name}...")
        cmd = RecAddMaskParamCommand(
            input_path=str(rec_file),
            output_path=str(output_file)
        )
        
        try:
            cmd.run()
            print(f"✓ Created {output_file.name}")
        except Exception as e:
            print(f"✗ Failed to process {rec_file.name}: {e}")

# Process datasets
prepare_training_datasets('./datasets/original', './datasets/masked')

CLI Configuration

Environment Variables

Configure CLI behavior using environment variables.

# Set default model storage directory
export INSIGHTFACE_ROOT=/path/to/models

# Set default context ID for GPU
export INSIGHTFACE_CTX_ID=0

# Use custom download mirror
export INSIGHTFACE_DOWNLOAD_MIRROR=https://custom-mirror.com

Configuration File

Create a configuration file for persistent settings.

# ~/.insightface/config.py
DEFAULT_ROOT = '/opt/insightface/models'
DEFAULT_CTX_ID = 0
DOWNLOAD_TIMEOUT = 300
VERIFY_DOWNLOADS = True

Advanced CLI Usage

Custom Scripts Integration

Integrate CLI commands into shell scripts and automation workflows.

#!/bin/bash
# setup_insightface.sh - Complete InsightFace setup script

set -e

echo "Setting up InsightFace..."

# Create model directory
mkdir -p ./models

# Download required models
echo "Downloading models..."
insightface-cli model.download buffalo_l --root ./models
insightface-cli model.download buffalo_s --root ./models

# Process training datasets if they exist
if [ -d "./datasets/original" ]; then
    echo "Processing training datasets..."
    mkdir -p ./datasets/processed
    
    for dataset in ./datasets/original/*.rec; do
        if [ -f "$dataset" ]; then
            filename=$(basename "$dataset")
            insightface-cli rec.add_mask_param \
                --input "$dataset" \
                --output "./datasets/processed/masked_$filename"
        fi
    done
fi

echo "InsightFace setup completed!"

Docker Integration

Use CLI commands in Docker containers for reproducible deployments.

FROM python:3.8-slim

# Install InsightFace
RUN pip install insightface

# Download models during build
RUN insightface-cli model.download buffalo_l --root /opt/models

# Set default model directory
ENV INSIGHTFACE_ROOT=/opt/models

COPY app.py /app/
WORKDIR /app

CMD ["python", "app.py"]

Monitoring and Logging

Add monitoring and logging to CLI operations.

import logging
from insightface.commands.model_download import ModelDownloadCommand

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('insightface_cli.log'),
        logging.StreamHandler()
    ]
)

def monitored_model_download(model_name, root_dir='./models'):
    """Download model with comprehensive logging."""
    logger = logging.getLogger(__name__)
    
    logger.info(f"Starting download of model: {model_name}")
    
    try:
        cmd = ModelDownloadCommand(model=model_name, root=root_dir, force=False)
        cmd.run()
        logger.info(f"Successfully downloaded model: {model_name}")
        return True
    except Exception as e:
        logger.error(f"Failed to download model {model_name}: {e}")
        return False

# Use monitored download
success = monitored_model_download('buffalo_l')

Troubleshooting

Common Issues and Solutions

Download Failures

# Retry with force flag
insightface-cli model.download buffalo_l --force

# Check network connectivity
curl -I https://github.com/deepinsight/insightface/releases

# Use custom root directory with write permissions
insightface-cli model.download buffalo_l --root /tmp/models

Permission Issues

# Use user directory
insightface-cli model.download buffalo_l --root ~/.insightface

# Fix permissions
chmod -R 755 ~/.insightface

Storage Space Issues

# Check available space
df -h ~/.insightface

# Clean up old models
rm -rf ~/.insightface/models/old_model_pack

# Use external storage
insightface-cli model.download buffalo_l --root /external/storage/models

Install with Tessl CLI

npx tessl i tessl/pypi-insightface

docs

3d-models.md

cli.md

face-analysis.md

face-processing.md

index.md

mask-rendering.md

model-management.md

model-zoo.md

sample-data.md

tile.json