Skip to main content

高性能异步证件照处理 SDK

Project description

PyHiVision

pyhivision

高性能异步证件照处理 SDK

Python Version License Code style: Ruff


📖 简介

PyHiVision 是一个专业级的异步证件照处理 SDK,采用现代 Python 异步架构(asyncio),集成多种先进的 AI 模型,为证件照制作、人像处理和批量照片编辑提供完整的解决方案。

✨ 核心特性

  • 🚀 高性能异步架构 - 基于 asyncio 的异步处理管线,支持高并发场景
  • 🤖 多模型支持 - 集成 ModNet、BiRefNet、RMBG、MTCNN、RetinaFace 等多种 AI 模型
  • 🎨 完整处理流程 - 抠图 → 人脸检测 → 美颜 → 布局调整 → 背景替换
  • 💾 智能模型管理 - LRU 缓存策略,自动内存管理
  • GPU 加速 - 支持 CUDA 加速,显著提升处理速度
  • 🔧 灵活配置 - 支持环境变量、配置文件和代码配置
  • 📊 性能监控 - 内置指标收集与性能追踪
  • 🛡️ 类型安全 - 完整的类型注解与 Pydantic 数据验证

🎯 适用场景

  • 证件照在线制作平台
  • 批量人像照片处理系统
  • 人脸识别与美颜应用
  • 图像自动化处理服务
  • AI 驱动的图像编辑工具

🚀 快速开始

安装

# 基础安装
pip install pyhivision

# 开发环境(包含测试和代码检查工具)
pip install "pyhivision[dev]"

# GPU 加速版本
pip install "pyhivision[gpu]"

基本使用

import cv2
import asyncio
from pyhivision import IDPhotoSDK, PhotoRequest, create_settings

async def main():
    # ⚠️ 配置模型路径(由上层应用提供)
    settings = create_settings(
        matting_models_dir="~/.pyhivision/models/matting",
        detection_models_dir="~/.pyhivision/models/detection",  # MTCNN 不需要
    )

    # 创建 SDK 实例
    sdk = IDPhotoSDK.create(settings=settings)

    # 读取图像
    image = cv2.imread("input.jpg")

    # 创建请求
    request = PhotoRequest(
        image=image,
        size=(413, 295),  # 一寸照尺寸
        background_color=(255, 0, 0),  # 蓝色背景
        matting_model="modnet_photographic",
        detection_model="mtcnn"
    )

    # 处理图像
    result = await sdk.process_single(request)

    # 保存结果
    cv2.imwrite("standard.jpg", result.standard)
    if result.hd is not None:
        cv2.imwrite("hd.jpg", result.hd)

    print(f"✅ 处理完成,耗时:{result.processing_time_ms:.2f}ms")

if __name__ == "__main__":
    asyncio.run(main())

⚙️ 配置说明

代码配置(推荐)

from pyhivision import create_settings

# 基础配置
settings = create_settings(
    # ⚠️ 模型路径(必需,由上层应用提供)
    matting_models_dir="~/.pyhivision/models/matting",      # 抠图模型目录
    detection_models_dir="~/.pyhivision/models/detection",  # 检测模型目录(MTCNN 除外)

    # 性能配置
    enable_gpu=False,          # 是否启用 GPU
    num_threads=4,             # ONNX Runtime 线程数
    model_cache_size=3,        # 模型缓存数量

    # 日志配置
    log_level="INFO",          # 日志级别
)

环境变量配置

# 模型路径(必需)
export HIVISION_MATTING_MODELS_DIR=~/.pyhivision/models/matting
export HIVISION_DETECTION_MODELS_DIR=~/.pyhivision/models/detection

# 性能配置
export HIVISION_ENABLE_GPU=true
export HIVISION_NUM_THREADS=8

# 日志配置
export HIVISION_LOG_LEVEL=DEBUG

配置优先级

  1. 代码中直接传参:create_settings(enable_gpu=True)
  2. 环境变量:HIVISION_ENABLE_GPU=true
  3. .env 文件:HIVISION_ENABLE_GPU=true
  4. 默认值

主要配置项

配置项 类型 默认值 说明
matting_models_dir ⚠️ Path/str/None None 抠图模型目录(必需)
detection_models_dir Path/str/None None 检测模型目录(MTCNN 除外)
enable_gpu bool False 是否启用 GPU 加速
num_threads int 4 ONNX Runtime 线程数
model_cache_size int 3 模型缓存数量上限
max_image_size int 2000 图像最大边长
log_level str "INFO" 日志级别

⚠️ 重要说明:模型路径由上层应用控制,SDK 不提供默认路径。推荐使用用户目录:~/.pyhivision/models/


🏗️ 架构概览

核心架构

┌─────────────────────────────────────────────────────────────┐
│                     用户层 (User Layer)                      │
│  IDPhotoSDK.process() / AsyncPhotoPipeline.process_single() │
└────────────────────────┬────────────────────────────────────┘
                         │
                         ▼
┌─────────────────────────────────────────────────────────────┐
│                   核心管线 (Core Pipeline)                   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │ 1. 抠图 (Matting) → ModNet/BiRefNet/RMBG          │   │
│  │ 2. 检测 (Detection) → MTCNN/RetinaFace            │   │
│  │ 3. 美颜 (Beauty) → 亮度/对比度/磨皮/美白           │   │
│  │ 4. 调整 (Adjustment) → 裁剪/缩放/布局              │   │
│  │ 5. 背景 (Background) → 纯色/模板                   │   │
│  └─────────────────────────────────────────────────────┘   │
└────────────────────────┬────────────────────────────────────┘
                         │
                         ▼
┌─────────────────────────────────────────────────────────────┐
│                 底层服务 (Infrastructure)                    │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐     │
│  │ ModelManager │  │ MetricsCollec│  │ ResultCache  │     │
│  │ (模型管理)    │  │ (性能监控)    │  │ (结果缓存)    │     │
│  └──────────────┘  └──────────────┘  └──────────────┘     │
└─────────────────────────────────────────────────────────────┘

模块结构

pyhivision/
├── config/          # 配置管理(Pydantic Settings)
├── core/            # 核心流程编排(Pipeline、ModelManager)
├── models/          # AI 模型封装(Detection、Matting)
├── processors/      # 图像处理器(抠图、检测、美颜、布局)
├── schemas/         # 数据模型(Request、Response、Validation)
├── utils/           # 工具函数(Logger、Image、Compression)
├── exceptions/      # 异常定义(自定义错误类型)
└── assets/          # 资源文件(LUT、字体、模板)

🛠️ 开发指南

开发环境搭建

# 克隆仓库
git clone https://github.com/ZyphrZero/pyhivision.git
cd pyhivision

# 创建虚拟环境
python -m venv .venv
source .venv/bin/activate  # Linux/Mac
# 或
.venv\Scripts\activate  # Windows

# 安装开发依赖
pip install -e ".[dev]"

代码规范

  • 格式化工具: Ruff(替代 Black + isort)
  • 行长度: 100 字符
  • Python 版本: 3.11-3.12
  • 类型注解: 必须使用完整的类型提示
# 代码格式检查
ruff check .

# 自动修复
ruff check --fix .

# 类型检查
mypy pyhivision

测试

# 运行所有测试
pytest tests/ -v

# 运行覆盖率测试
pytest tests/ --cov=pyhivision --cov-report=html

# 运行特定测试
pytest tests/test_pipeline.py -v

编码规范

  • 类名: PascalCase(如 ModelManager
  • 函数/变量: snake_case(如 load_model, face_info
  • 常量: UPPER_SNAKE_CASE(如 CUBE64_SIZE
  • 私有方法: 前缀 _(如 _create_session
  • 异步函数: 必须使用 async def
  • 错误处理: 使用自定义异常类(继承自 HivisionError

📚 API 文档

核心类

IDPhotoSDK

主要的 SDK 接口,提供证件照处理功能。

sdk = IDPhotoSDK.create(settings=settings)
result = await sdk.process_single(request)

PhotoRequest

照片处理请求对象。

request = PhotoRequest(
    image=image,                          # np.ndarray
    size=(413, 295),                      # 输出尺寸
    background_color=(255, 0, 0),         # 背景色(BGR)
    matting_model="modnet_photographic",  # 抠图模型
    detection_model="mtcnn",              # 检测模型
    beauty_params=BeautyParams(           # 美颜参数(可选)
        brightness=1.1,
        contrast=1.05
    )
)

PhotoResult

照片处理结果对象。

result.standard         # 标准照片(np.ndarray)
result.hd              # 高清照片(可选)
result.face_info       # 人脸信息
result.processing_time_ms  # 处理耗时(毫秒)

支持的模型

抠图模型

  • modnet_photographic - 通用摄影抠图(官方权重)
  • hivision_modnet - HiVision 优化版
  • birefnet_lite - BiRefNet 轻量版
  • rmbg_1_4 - RMBG 1.4 版本
  • rmbg_2.0 - RMBG 2.0 版本(待支持)

人脸检测模型

  • mtcnn - MTCNN(内置权重,无需额外配置)
  • retinaface - RetinaFace(需要配置 detection_models_dir)

🤝 贡献指南

欢迎贡献代码、报告 Bug 或提出新功能建议!

  1. Fork 本仓库
  2. 创建特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 开启 Pull Request

贡献要求

  • 遵循项目的编码规范(Ruff)
  • 添加必要的单元测试
  • 更新相关文档
  • 确保所有测试通过

🙏 致谢


📧 联系方式


用 ❤️ 构建 | Made with Love

⭐ 如果这个项目对你有帮助,请给我们一个 Star!


📄 许可证

本项目采用 Apache License 2.0 开源协议。

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyhivision-1.0.2.tar.gz (4.0 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pyhivision-1.0.2-py3-none-any.whl (10.1 kB view details)

Uploaded Python 3

File details

Details for the file pyhivision-1.0.2.tar.gz.

File metadata

  • Download URL: pyhivision-1.0.2.tar.gz
  • Upload date:
  • Size: 4.0 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for pyhivision-1.0.2.tar.gz
Algorithm Hash digest
SHA256 37626050e73bb918e566d0cd925e10ffeec7715e6e2e20fe2b2373197c4af8d1
MD5 c5a9d5a5e63a7a9d47c94a36609edeb2
BLAKE2b-256 17ca490f3c5f2b519438b528df97f4d8ea171226d5abab74234fdb998550b51a

See more details on using hashes here.

Provenance

The following attestation bundles were made for pyhivision-1.0.2.tar.gz:

Publisher: publish.yml on ZyphrZero/pyhivision

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pyhivision-1.0.2-py3-none-any.whl.

File metadata

  • Download URL: pyhivision-1.0.2-py3-none-any.whl
  • Upload date:
  • Size: 10.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for pyhivision-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 6346da2d6859fba2bfdc520acf4151dd931c739081f5d7dfab7eda38ec7d8c92
MD5 b90b1795c46642c59face27008ad51ad
BLAKE2b-256 6e810ad870e152a9b87672ce9595d883aa14aebdb90b583fdd0e5b3968b69d70

See more details on using hashes here.

Provenance

The following attestation bundles were made for pyhivision-1.0.2-py3-none-any.whl:

Publisher: publish.yml on ZyphrZero/pyhivision

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page