td-face-recognizer 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,27 @@
1
+ """独立人脸检测与特征提取包:yolov5-face 检测 + 5 点对齐 + 512 维特征提取。
2
+
3
+ 本项目整体按 GPL-2.0-only 授权(见仓库根目录 LICENSE)。detector.py 的部分
4
+ 实现参考了 derronqi/yolov5-face(GPL-2.0)的推理逻辑。
5
+ """
6
+
7
+ from ._version import __version__
8
+ from .errors import (
9
+ FaceRecognitionError,
10
+ FaceTooSmallError,
11
+ ModelError,
12
+ ModelHashMismatchError,
13
+ ModelNotFoundError,
14
+ NoFaceDetectedError,
15
+ )
16
+ from .recognizer import FaceRecognitionResult, FaceRecognizer
17
+
18
+ __all__ = [
19
+ "FaceRecognitionError",
20
+ "FaceRecognitionResult",
21
+ "FaceRecognizer",
22
+ "FaceTooSmallError",
23
+ "ModelError",
24
+ "ModelNotFoundError",
25
+ "NoFaceDetectedError",
26
+ "__version__",
27
+ ]
@@ -0,0 +1,8 @@
1
+ """支持 ``python -m td_face_recognizer``。"""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
@@ -0,0 +1,3 @@
1
+ """包版本号。修改后需重新构建才能发布新版本。"""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,30 @@
1
+ """基于 5 个关键点的人脸对齐。"""
2
+
3
+ import cv2
4
+ import numpy as np
5
+ from skimage import transform as trans
6
+
7
+
8
+ ARCFACE_DST = np.array(
9
+ [
10
+ [38.2946, 51.6963], # 左眼
11
+ [73.5318, 51.5014], # 右眼
12
+ [56.0252, 71.7366], # 鼻尖
13
+ [41.5493, 92.3655], # 左嘴角
14
+ [70.7299, 92.2041], # 右嘴角
15
+ ],
16
+ dtype=np.float32,
17
+ )
18
+
19
+
20
+ def estimate_norm(landmark: np.ndarray) -> np.ndarray:
21
+ """计算关键点映射到 ArcFace 标准位置的相似变换矩阵。"""
22
+ tform = trans.SimilarityTransform()
23
+ tform.estimate(landmark, ARCFACE_DST)
24
+ return tform.params[0:2, :]
25
+
26
+
27
+ def norm_crop(img: np.ndarray, landmark: np.ndarray, image_size: int = 112) -> np.ndarray:
28
+ """按关键点对齐裁剪出 image_size 见方的人脸图。"""
29
+ matrix = estimate_norm(landmark)
30
+ return cv2.warpAffine(img, matrix, (image_size, image_size), borderValue=0.0)
@@ -0,0 +1,67 @@
1
+ """命令行入口:输入图片路径,输出最大人脸的 512 维特征。"""
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from collections.abc import Sequence
7
+ from typing import Optional
8
+
9
+ import cv2
10
+
11
+ from .errors import FaceRecognitionError
12
+ from .recognizer import FaceRecognizer
13
+
14
+
15
+ def build_parser() -> argparse.ArgumentParser:
16
+ parser = argparse.ArgumentParser(description="返回图片中最大人脸的 512 维特征")
17
+ parser.add_argument("image", help="图片路径")
18
+ parser.add_argument("--output", help="可选,保存带框标注图到该路径")
19
+ parser.add_argument(
20
+ "--min-face-ratio",
21
+ type=float,
22
+ default=FaceRecognizer.MIN_FACE_RATIO,
23
+ help="最大人脸占图片面积的最小比例,取值 [0,1],默认 0.02",
24
+ )
25
+ parser.add_argument(
26
+ "--min-face-size",
27
+ type=float,
28
+ default=FaceRecognizer.MIN_FACE_SIZE,
29
+ help="最大人脸框短边的最小像素数,默认 80",
30
+ )
31
+ parser.add_argument(
32
+ "--detector",
33
+ required=True,
34
+ help="检测模型 ONNX 文件路径",
35
+ )
36
+ parser.add_argument(
37
+ "--extractor",
38
+ required=True,
39
+ help="特征模型 ONNX 文件路径",
40
+ )
41
+ return parser
42
+
43
+
44
+ def main(argv: Optional[Sequence[str]] = None) -> int:
45
+ args = build_parser().parse_args(argv)
46
+
47
+ try:
48
+ image = cv2.imread(args.image)
49
+ if image is None:
50
+ raise ValueError(f"图片读取失败: {args.image}")
51
+
52
+ with FaceRecognizer(
53
+ detector_path=args.detector,
54
+ extractor_path=args.extractor,
55
+ min_face_ratio=args.min_face_ratio,
56
+ min_face_size=args.min_face_size,
57
+ ) as recognizer:
58
+ result = recognizer.recognize(image)
59
+
60
+ if args.output and not cv2.imwrite(args.output, result.draw(image)):
61
+ raise OSError(f"标注图保存失败: {args.output}")
62
+ except (FaceRecognitionError, ValueError, OSError) as e:
63
+ print(f"{type(e).__name__}: {e}", file=sys.stderr)
64
+ return 2
65
+
66
+ print(json.dumps(result.feature.tolist()))
67
+ return 0
@@ -0,0 +1,173 @@
1
+ """yolov5-face ONNX 检测器。
2
+
3
+ 模型输出为 (1, N, 4+1+nc+3k):4 个框坐标 + 目标置信度 + 类别条件概率 + 关键点,
4
+ 最终置信度 = 目标置信度 × 类别条件概率。
5
+
6
+ 本模块的 letterbox/NMS/坐标回映等推理逻辑参考了 derronqi/yolov5-face
7
+ (GPL-2.0-only)的对应实现,整个包按 GPL-2.0-only 授权发布。
8
+ """
9
+
10
+ import cv2
11
+ import numpy as np
12
+
13
+ from .model import load_session
14
+
15
+
16
+ def letterbox(
17
+ image: np.ndarray, new_shape: tuple[int, int], color: tuple[int, int, int] = (114, 114, 114)
18
+ ) -> np.ndarray:
19
+ """保持长宽比缩放到 new_shape 并居中填充。"""
20
+ shape = image.shape[:2]
21
+ ratio = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
22
+ new_unpad = (int(round(shape[1] * ratio)), int(round(shape[0] * ratio)))
23
+ dw, dh = (new_shape[1] - new_unpad[0]) / 2, (new_shape[0] - new_unpad[1]) / 2
24
+ if shape[::-1] != new_unpad:
25
+ image = cv2.resize(image, new_unpad, interpolation=cv2.INTER_LINEAR)
26
+ top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
27
+ left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
28
+ return cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)
29
+
30
+
31
+ def xywh2xyxy(x: np.ndarray) -> np.ndarray:
32
+ """中心点宽高 [cx,cy,w,h] -> 左上右下 [x1,y1,x2,y2]。"""
33
+ y = np.copy(x)
34
+ y[..., 0] = x[..., 0] - x[..., 2] / 2
35
+ y[..., 1] = x[..., 1] - x[..., 3] / 2
36
+ y[..., 2] = x[..., 0] + x[..., 2] / 2
37
+ y[..., 3] = x[..., 1] + x[..., 3] / 2
38
+ return y
39
+
40
+
41
+ def greedy_nms(boxes: np.ndarray, scores: np.ndarray, iou_thres: float) -> np.ndarray:
42
+ """贪心 NMS(抑制 IoU > iou_thres),返回保留索引。"""
43
+ order = np.argsort(-scores, kind="stable")
44
+ keep: list[int] = []
45
+ while order.size > 0:
46
+ i = order[0]
47
+ keep.append(i)
48
+ if order.size == 1:
49
+ break
50
+ rest = order[1:]
51
+ xx1 = np.maximum(boxes[i, 0], boxes[rest, 0])
52
+ yy1 = np.maximum(boxes[i, 1], boxes[rest, 1])
53
+ xx2 = np.minimum(boxes[i, 2], boxes[rest, 2])
54
+ yy2 = np.minimum(boxes[i, 3], boxes[rest, 3])
55
+ inter = np.clip(xx2 - xx1, 0, None) * np.clip(yy2 - yy1, 0, None)
56
+ area_i = (boxes[i, 2] - boxes[i, 0]) * (boxes[i, 3] - boxes[i, 1])
57
+ area_r = (boxes[rest, 2] - boxes[rest, 0]) * (boxes[rest, 3] - boxes[rest, 1])
58
+ iou = inter / (area_i + area_r - inter)
59
+ order = rest[iou <= iou_thres]
60
+ return np.asarray(keep, dtype=np.int64)
61
+
62
+
63
+ def scale_coords(
64
+ img1_shape: tuple[int, int], coords: np.ndarray, img0_shape: tuple[int, int], kpt_step: int = 0
65
+ ) -> np.ndarray:
66
+ """letterbox 图坐标映射回原图坐标,原地修改并裁剪到原图范围内。
67
+
68
+ kpt_step=0: coords 为 (n,4) [x1,y1,x2,y2];
69
+ kpt_step>0: coords 为 (n,3k) 关键点扁平 (kx,ky,kc)*k,按 step 间隔取 x/y。
70
+ """
71
+ gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1])
72
+ pad = ((img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2)
73
+
74
+ step = kpt_step or 2
75
+ coords[:, 0::step] = (coords[:, 0::step] - pad[0]) / gain
76
+ coords[:, 1::step] = (coords[:, 1::step] - pad[1]) / gain
77
+ np.clip(coords[:, 0::step], 0, img0_shape[1], out=coords[:, 0::step])
78
+ np.clip(coords[:, 1::step], 0, img0_shape[0], out=coords[:, 1::step])
79
+ return coords
80
+
81
+
82
+ class FaceDetector:
83
+ """yolov5-face 检测器,返回 (n, 6+3k) 的原图坐标检测结果。"""
84
+
85
+ KPT_DIM = 3
86
+ MAX_PRE_NMS = 30000
87
+ NMS_CLASS_OFFSET = 4096
88
+
89
+ def __init__(
90
+ self,
91
+ detector_path: str,
92
+ num_classes: int = 1,
93
+ num_keypoints: int = 5,
94
+ conf: float = 0.4,
95
+ iou_thres: float = 0.45,
96
+ ) -> None:
97
+ self.num_classes = num_classes
98
+ self.num_keypoints = num_keypoints
99
+ self.conf = conf
100
+ self.iou_thres = iou_thres
101
+ self.session, self.infer_func = load_session(detector_path)
102
+ input_shape = self.session.get_inputs()[0].shape
103
+ self.image_shape: tuple[int, int] = tuple(int(dim) for dim in input_shape[2:])
104
+
105
+ @property
106
+ def _pred_dim(self) -> int:
107
+ """模型单行输出维度: 4 框 + 1 obj + nc 类别 + 关键点。"""
108
+ return 5 + self.num_classes + self.num_keypoints * self.KPT_DIM
109
+
110
+ def preprocess(self, frame: np.ndarray) -> np.ndarray:
111
+ """BGR(HWC,uint8) -> (1,3,H,W) float32,letterbox + BGR2RGB + /255。"""
112
+ return np.multiply(
113
+ letterbox(frame, self.image_shape)[..., ::-1].transpose(2, 0, 1)[None], 1.0 / 255.0, dtype=np.float32
114
+ )
115
+
116
+ def infer(self, frame: np.ndarray) -> np.ndarray:
117
+ """BGR 原图 -> (n, 6+3k) 原图坐标检测结果。"""
118
+ outputs = self.infer_func(self.preprocess(frame))
119
+ return self.postprocess(outputs, frame.shape[:2])
120
+
121
+ def _nms_pipeline(self, x: np.ndarray) -> np.ndarray:
122
+ """NMS 前预测 (N,pred_dim) -> letterbox 坐标检测结果 (n, 6+3k)。"""
123
+ empty = np.zeros((0, 6 + self.num_keypoints * self.KPT_DIM), dtype=np.float32)
124
+ x = x[x[:, 4] > self.conf]
125
+ if x.shape[0] == 0:
126
+ return empty
127
+
128
+ # 布尔索引已产生新数组,可原地改写
129
+ x[:, 5 : 5 + self.num_classes] *= x[:, 4:5] # conf = obj * cls
130
+
131
+ box = xywh2xyxy(x[:, :4])
132
+ cls_conf = x[:, 5 : 5 + self.num_classes]
133
+ conf = cls_conf.max(axis=1)
134
+ mask = conf > self.conf
135
+ if not mask.any():
136
+ return empty
137
+
138
+ box, conf, x, cls_conf = box[mask], conf[mask], x[mask], cls_conf[mask]
139
+ cls = np.argmax(cls_conf, axis=1).astype(np.float32)
140
+ det = np.concatenate([box, conf[:, None], cls[:, None], x[:, 5 + self.num_classes :]], axis=1)
141
+
142
+ if det.shape[0] > self.MAX_PRE_NMS:
143
+ det = det[np.argsort(-det[:, 4], kind="stable")[: self.MAX_PRE_NMS]]
144
+
145
+ offset = det[:, 5:6] * self.NMS_CLASS_OFFSET
146
+ keep = greedy_nms(det[:, :4] + offset, det[:, 4], self.iou_thres)
147
+ return det[keep]
148
+
149
+ def postprocess(self, outputs: list[np.ndarray], shape0: tuple[int, int]) -> np.ndarray:
150
+ """NMS 前原始输出 -> 原图坐标检测结果 (n, 6+3k)。
151
+
152
+ 每行 [x1,y1,x2,y2, conf, cls, kx1,ky1,kc1, ...],无检出时 shape 为 (0, 6+3k)。
153
+ """
154
+ pred = np.asarray(outputs[0])
155
+ if pred.ndim == 3:
156
+ if pred.shape[-1] != self._pred_dim and pred.shape[1] == self._pred_dim:
157
+ pred = pred.transpose(0, 2, 1) # (1,pred_dim,N) -> (1,N,pred_dim)
158
+ pred = pred[0]
159
+ det = self._nms_pipeline(pred)
160
+ if det.shape[0]:
161
+ scale_coords(self.image_shape, det[:, :4], shape0)
162
+ if self.num_keypoints:
163
+ scale_coords(self.image_shape, det[:, 6:], shape0, kpt_step=self.KPT_DIM)
164
+ return det
165
+
166
+ def close(self) -> None:
167
+ """释放模型会话(可重复调用)。
168
+
169
+ onnxruntime 没有公开的 close/free 接口,引用计数归零时才会析构底层会话,
170
+ 因此这里把 session 和持有它的推理闭包一起置空。
171
+ """
172
+ self.session = None
173
+ self.infer_func = None
@@ -0,0 +1,25 @@
1
+ """人脸检测与识别异常。"""
2
+
3
+
4
+ class FaceRecognitionError(Exception):
5
+ """人脸识别异常基类。"""
6
+
7
+
8
+ class NoFaceDetectedError(FaceRecognitionError):
9
+ """图片中未检测到人脸。"""
10
+
11
+
12
+ class FaceTooSmallError(FaceRecognitionError):
13
+ """最大人脸像素尺寸或占图比例不足。"""
14
+
15
+
16
+ class ModelError(FaceRecognitionError):
17
+ """模型文件相关异常基类。"""
18
+
19
+
20
+ class ModelNotFoundError(ModelError):
21
+ """未找到模型文件。"""
22
+
23
+
24
+ class ModelHashMismatchError(ModelError):
25
+ """模型文件 SHA256 与包内固定的期望值不一致。"""
@@ -0,0 +1,70 @@
1
+ """512 维人脸特征提取。"""
2
+
3
+ from typing import Optional
4
+
5
+ import numpy as np
6
+
7
+ from .align import norm_crop
8
+ from .model import load_session
9
+
10
+ FEATURE_DIM = 512
11
+
12
+
13
+ class FeatureExtractor:
14
+ """输入 112x112 对齐人脸,输出 L2 归一化的 512 维特征。"""
15
+
16
+ EXTRACT_SIZE = 112
17
+ # 模型未声明固定 batch(动态 shape)时按此值补零
18
+ DEFAULT_BATCH_SIZE = 4
19
+
20
+ def __init__(self, extractor_path: str) -> None:
21
+ self.session, self.infer_func = load_session(extractor_path)
22
+ self._batch_size: Optional[int] = None
23
+
24
+ def extract(self, landmarks: np.ndarray, frame: np.ndarray) -> np.ndarray:
25
+ """按 5 关键点对齐裁剪并提特征,返回 (n,512) L2 归一化特征。"""
26
+ if len(landmarks) == 0:
27
+ return np.zeros((0, FEATURE_DIM), dtype=np.float32)
28
+ aligned_faces = np.stack([norm_crop(frame, landmark, self.EXTRACT_SIZE) for landmark in landmarks])
29
+ return self.extract_aligned(aligned_faces)
30
+
31
+ def extract_aligned(self, aligned_faces: np.ndarray) -> np.ndarray:
32
+ """(n,112,112,3) 对齐人脸 BGR -> (n,512) L2 归一化特征,按模型固定 batch 补零推理。"""
33
+ if len(aligned_faces) == 0:
34
+ return np.zeros((0, FEATURE_DIM), dtype=np.float32)
35
+ batch_size = self._resolve_batch_size()
36
+ chunk_vects: list[np.ndarray] = []
37
+ for start in range(0, len(aligned_faces), batch_size):
38
+ chunk = aligned_faces[start : start + batch_size]
39
+ batch = np.zeros((batch_size, 3, self.EXTRACT_SIZE, self.EXTRACT_SIZE), dtype=np.float32)
40
+ batch[: len(chunk)] = self._preprocess(chunk)
41
+ outputs = np.asarray(self.infer_func(batch)[0]).reshape(batch_size, -1)
42
+ chunk_vects.append(outputs[: len(chunk)])
43
+ vects = np.concatenate(chunk_vects, axis=0).astype(np.float32)
44
+ return vects / np.linalg.norm(vects, axis=1, keepdims=True)
45
+
46
+ def _resolve_batch_size(self) -> int:
47
+ """从模型输入声明读取固定 batch,动态/未知 shape 回退默认值。"""
48
+ if self._batch_size is None:
49
+ shape = self.session.get_inputs()[0].shape
50
+ try:
51
+ dim = int(shape[0])
52
+ except (TypeError, ValueError, IndexError):
53
+ dim = 0
54
+ self._batch_size = dim if dim > 0 else self.DEFAULT_BATCH_SIZE
55
+ return self._batch_size
56
+
57
+ @staticmethod
58
+ def _preprocess(aligned_faces: np.ndarray) -> np.ndarray:
59
+ """(n,112,112,3) BGR -> (n,3,112,112) RGB 归一化到 [-1,1]。"""
60
+ x = aligned_faces[..., ::-1].transpose(0, 3, 1, 2).astype(np.float32)
61
+ return (x / 255.0 - 0.5) / 0.5
62
+
63
+ def close(self) -> None:
64
+ """释放模型会话(可重复调用)。
65
+
66
+ onnxruntime 没有公开的 close/free 接口,引用计数归零时才会析构底层会话,
67
+ 因此这里把 session 和持有它的推理闭包一起置空。
68
+ """
69
+ self.session = None
70
+ self.infer_func = None
@@ -0,0 +1,19 @@
1
+ """ONNX 模型加载。"""
2
+
3
+ from collections.abc import Callable
4
+
5
+ import numpy as np
6
+ import onnxruntime as ort
7
+
8
+ InferFunc = Callable[[np.ndarray], np.ndarray]
9
+
10
+
11
+ def load_session(model_path: str) -> tuple[ort.InferenceSession, InferFunc]:
12
+ """加载 ONNX 模型,返回会话与单输入推理函数。"""
13
+ session = ort.InferenceSession(model_path)
14
+ input_name = session.get_inputs()[0].name
15
+
16
+ def infer(image: np.ndarray) -> np.ndarray:
17
+ return session.run(None, {input_name: np.asarray(image)})
18
+
19
+ return session, infer
@@ -0,0 +1,243 @@
1
+ """人脸识别入口:只对图中占比最大的单张人脸提取特征。"""
2
+
3
+ import hashlib
4
+ import hmac
5
+ from dataclasses import dataclass
6
+ from os import PathLike
7
+ from pathlib import Path
8
+ from typing import Union
9
+
10
+ import cv2
11
+ import numpy as np
12
+
13
+ from .detector import FaceDetector
14
+ from .errors import (
15
+ FaceTooSmallError,
16
+ ModelHashMismatchError,
17
+ ModelNotFoundError,
18
+ NoFaceDetectedError,
19
+ )
20
+ from .extractor import FeatureExtractor
21
+
22
+ KPT_NUM = 5 # 左眼/右眼/鼻尖/左嘴角/右嘴角
23
+
24
+ # 包内固定的模型文件 SHA256,不提供参数覆盖。
25
+ DETECTOR_SHA256 = "e3e9e738ee51afa6f951ce470466e8fc65c84d3a0632703c272163a30d7c1fde"
26
+ EXTRACTOR_SHA256 = "e8aeb7f8c4394b411ec0e6717e17e2c26ba71b5873df5b06590449f7c89b2ef4"
27
+
28
+ # 支持直接传图片路径或已读取的 BGR ndarray
29
+ ImageInput = Union[np.ndarray, str, PathLike]
30
+
31
+
32
+ def _validate_model_path(path: Union[str, PathLike], label: str) -> Path:
33
+ """校验模型文件存在,返回绝对路径。"""
34
+ model_path = Path(path).expanduser()
35
+ if not model_path.is_file():
36
+ raise ModelNotFoundError(f"{label}模型文件不存在: {model_path}")
37
+ return model_path.resolve()
38
+
39
+
40
+ def _verify_model_hash(path: Path, expected_sha256: str, label: str) -> None:
41
+ """流式校验模型文件 SHA256,不匹配时抛出 ModelHashMismatchError。"""
42
+ digest = hashlib.sha256()
43
+ with path.open("rb") as model_file:
44
+ for chunk in iter(lambda: model_file.read(1024 * 1024), b""):
45
+ digest.update(chunk)
46
+
47
+ actual_sha256 = digest.hexdigest()
48
+ if not hmac.compare_digest(actual_sha256, expected_sha256):
49
+ raise ModelHashMismatchError(
50
+ f"{label}模型文件 hash 不匹配: {path}\n"
51
+ f"期望: {expected_sha256}\n"
52
+ f"实际: {actual_sha256}"
53
+ )
54
+
55
+
56
+ def _load_image(image: ImageInput) -> np.ndarray:
57
+ """图片路径 -> BGR ndarray;ndarray 直接校验后返回。"""
58
+ if isinstance(image, np.ndarray):
59
+ frame = image
60
+ elif isinstance(image, (str, PathLike)):
61
+ path = str(image)
62
+ frame = cv2.imread(path)
63
+ if frame is None:
64
+ raise ValueError(f"图片读取失败: {path}")
65
+ else:
66
+ raise TypeError("image 必须是 HxWx3 的 BGR np.ndarray 或图片路径")
67
+ if frame.ndim != 3 or frame.shape[2] != 3 or frame.size == 0:
68
+ raise ValueError("image 必须是 HxWx3 的 BGR np.ndarray")
69
+ return frame
70
+
71
+
72
+ @dataclass
73
+ class FaceRecognitionResult:
74
+ """单张最大人脸的检测与识别结果。"""
75
+
76
+ bbox: np.ndarray # (4,) 原图坐标 [x1,y1,x2,y2]
77
+ keypoints: np.ndarray # (5,2) 原图坐标
78
+ confidence: float
79
+ feature: np.ndarray # (512,) L2 归一化特征
80
+ face_ratio: float # 人脸框面积 / 图片面积
81
+
82
+ def draw(self, image: ImageInput) -> np.ndarray:
83
+ """在图片副本上绘制人脸框、关键点和置信度/占比。
84
+
85
+ Args:
86
+ image: 原图(图片路径或 HxWx3 BGR ndarray)
87
+
88
+ Returns:
89
+ 绘制后的 BGR ndarray 副本
90
+ """
91
+ frame = _load_image(image)
92
+ annotated = frame.copy()
93
+ x1, y1, x2, y2 = self.bbox.astype(int)
94
+ cv2.rectangle(annotated, (x1, y1), (x2, y2), (0, 255, 0), 2)
95
+ cv2.putText(
96
+ annotated,
97
+ f"face {self.confidence:.2f} ratio {self.face_ratio:.1%}",
98
+ (x1, max(y1 - 8, 12)),
99
+ cv2.FONT_HERSHEY_SIMPLEX,
100
+ 0.6,
101
+ (0, 255, 0),
102
+ 2,
103
+ )
104
+ for kx, ky in self.keypoints:
105
+ cv2.circle(annotated, (int(kx), int(ky)), 3, (0, 0, 255), -1)
106
+ return annotated
107
+
108
+
109
+ class FaceRecognizer:
110
+ """yolov5-face 检测 + 5 点对齐 + 512 维特征提取。
111
+
112
+ 典型用法(模型只加载一次,可复用):
113
+
114
+ with FaceRecognizer("detect.onnx", "feature.onnx") as recognizer:
115
+ feature = recognizer.extract_feature("photo.jpg")
116
+
117
+ Args:
118
+ detector_path: 检测模型 ONNX 文件路径(必填)
119
+ extractor_path: 特征模型 ONNX 文件路径(必填)
120
+ min_face_ratio: 最大人脸占图片面积的最小比例,取值 [0,1],默认 0.02
121
+ min_face_size: 最大人脸框短边的最小像素数,默认 80
122
+
123
+ Raises:
124
+ ModelNotFoundError: 任一模型文件不存在
125
+ ModelHashMismatchError: 任一模型文件 SHA256 与包内固定值不一致
126
+ """
127
+
128
+ DETECT_CONF = 0.4
129
+ DETECT_IOU = 0.45
130
+ MIN_FACE_RATIO = 0.02
131
+ MIN_FACE_SIZE = 80
132
+
133
+ def __init__(
134
+ self,
135
+ detector_path: Union[str, PathLike],
136
+ extractor_path: Union[str, PathLike],
137
+ min_face_ratio: float = MIN_FACE_RATIO,
138
+ min_face_size: float = MIN_FACE_SIZE,
139
+ ) -> None:
140
+ if not 0 <= min_face_ratio <= 1:
141
+ raise ValueError(f"min_face_ratio 必须在 [0,1] 内: {min_face_ratio}")
142
+ if min_face_size < 0:
143
+ raise ValueError(f"min_face_size 必须大于等于 0: {min_face_size}")
144
+ self.min_face_ratio = float(min_face_ratio)
145
+ self.min_face_size = float(min_face_size)
146
+ self._closed = False
147
+
148
+ # 两种模型都必须显式提供,不做目录搜索或自动下载
149
+ detector_file = _validate_model_path(detector_path, "检测")
150
+ extractor_file = _validate_model_path(extractor_path, "特征")
151
+
152
+ # 强制校验完整性,hash 固定在本模块中,不接受调用方覆盖
153
+ _verify_model_hash(detector_file, DETECTOR_SHA256, "检测")
154
+ _verify_model_hash(extractor_file, EXTRACTOR_SHA256, "特征")
155
+
156
+ self.detector = FaceDetector(
157
+ str(detector_file),
158
+ num_classes=1,
159
+ num_keypoints=KPT_NUM,
160
+ conf=self.DETECT_CONF,
161
+ iou_thres=self.DETECT_IOU,
162
+ )
163
+ self.extractor = FeatureExtractor(str(extractor_file))
164
+
165
+ def __enter__(self) -> "FaceRecognizer":
166
+ self._ensure_open()
167
+ return self
168
+
169
+ def __exit__(self, *_: object) -> None:
170
+ self.close()
171
+
172
+ def _ensure_open(self) -> None:
173
+ if self._closed:
174
+ raise RuntimeError("FaceRecognizer 已关闭,请重新创建实例")
175
+
176
+ def detect(self, image: ImageInput) -> np.ndarray:
177
+ """检测图中所有人脸,返回 (n, 21) 原图坐标结果。"""
178
+ self._ensure_open()
179
+ return self.detector.infer(_load_image(image))
180
+
181
+ def recognize(self, image: ImageInput) -> FaceRecognitionResult:
182
+ """检测并只对最大人脸提特征。
183
+
184
+ Args:
185
+ image: 图片路径或 HxWx3 BGR ndarray
186
+
187
+ Raises:
188
+ ValueError: 图片无法读取或格式不正确
189
+ NoFaceDetectedError: 图中没有检出人脸
190
+ FaceTooSmallError: 最大人脸框短边低于 min_face_size,
191
+ 或占图片面积低于 min_face_ratio
192
+ RuntimeError: 实例已关闭
193
+ """
194
+ self._ensure_open()
195
+ frame = _load_image(image)
196
+ dets = self.detector.infer(frame)
197
+ if dets.shape[0] == 0:
198
+ raise NoFaceDetectedError("未检测到人脸")
199
+
200
+ height, width = frame.shape[:2]
201
+ areas = (dets[:, 2] - dets[:, 0]) * (dets[:, 3] - dets[:, 1])
202
+ index = int(np.argmax(areas))
203
+ face = dets[index]
204
+ face_ratio = float(areas[index] / (width * height))
205
+ face_size = float(min(face[2] - face[0], face[3] - face[1]))
206
+
207
+ # 像素尺寸是能否完成对齐/识别的硬条件,优先于面积占比判断
208
+ if face_size < self.min_face_size:
209
+ raise FaceTooSmallError(
210
+ f"上传的人脸像素过小:最大人脸框短边仅 {face_size:.0f}px,"
211
+ f"低于要求的 {self.min_face_size:.0f}px"
212
+ )
213
+ if face_ratio < self.min_face_ratio:
214
+ raise FaceTooSmallError(
215
+ f"上传的人脸占图比例过小:最大人脸仅占图片 {face_ratio:.1%},"
216
+ f"低于要求的 {self.min_face_ratio:.1%}"
217
+ )
218
+
219
+ keypoints = face[6:].reshape(KPT_NUM, -1)[:, :2].astype(np.float32)
220
+ feature = self.extractor.extract(keypoints[None], frame)[0]
221
+ return FaceRecognitionResult(
222
+ bbox=face[:4].astype(np.float32),
223
+ keypoints=keypoints,
224
+ confidence=float(face[4]),
225
+ feature=feature,
226
+ face_ratio=face_ratio,
227
+ )
228
+
229
+ def infer(self, image: ImageInput) -> FaceRecognitionResult:
230
+ """recognize 的别名,便于沿用旧接口。"""
231
+ return self.recognize(image)
232
+
233
+ def extract_feature(self, image: ImageInput) -> np.ndarray:
234
+ """返回最大人脸的 512 维 L2 归一化特征。"""
235
+ return self.recognize(image).feature
236
+
237
+ def close(self) -> None:
238
+ """释放两个模型会话(可重复调用)。"""
239
+ if self._closed:
240
+ return
241
+ self.detector.close()
242
+ self.extractor.close()
243
+ self._closed = True
@@ -0,0 +1,238 @@
1
+ Metadata-Version: 2.5
2
+ Name: td-face-recognizer
3
+ Version: 0.1.0
4
+ Summary: 基于 yolov5-face 检测与 ArcFace ONNX 特征提取的人脸识别包
5
+ License-Expression: GPL-2.0-only
6
+ License-File: LICENSE
7
+ Keywords: arcface,face-detection,face-recognition,onnx
8
+ Classifier: Operating System :: OS Independent
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Requires-Python: >=3.9
12
+ Requires-Dist: numpy<2.0,>=1.23
13
+ Requires-Dist: onnxruntime<2.0,>=1.16
14
+ Requires-Dist: opencv-python-headless<4.12,>=4.6
15
+ Requires-Dist: scikit-image<0.25,>=0.21
16
+ Provides-Extra: dev
17
+ Requires-Dist: pytest>=7; extra == 'dev'
18
+ Description-Content-Type: text/markdown
19
+
20
+ # 人脸检测与特征提取
21
+
22
+ 输入图片(路径或 HxWx3 的 BGR ndarray),返回图中**面积最大、且满足最小占比和最小像素尺寸要求的人脸**的 512 维特征。`min_face_ratio` 用 `[0,1]` 之间的小数表示,默认 `0.02`(即 2%);`min_face_size` 表示人脸框短边最小像素数,默认 `80`。
23
+
24
+ - 检测:yolov5-face ONNX 模型,输出人脸框与 5 个关键点
25
+ - 对齐:按 5 个关键点裁剪对齐为 112x112
26
+ - 特征:ONNX 模型输出 512 维 L2 归一化特征,可直接用余弦相似度比对
27
+
28
+ 图片中没有检出人脸时抛出 `NoFaceDetectedError`;最大人脸占比或短边低于阈值时抛出 `FaceTooSmallError`。模型文件不存在或 SHA256 不匹配时分别抛出 `ModelNotFoundError`、`ModelHashMismatchError`。
29
+
30
+ > 模型文件不打包进 wheel,也没有自动搜索或下载逻辑。初始化 `FaceRecognizer` 时必须显式传入检测模型和特征模型路径。
31
+
32
+ ## 安装
33
+
34
+ ### 从 TestPyPI 安装
35
+
36
+ ```bash
37
+ pip install --upgrade \
38
+ --index-url https://test.pypi.org/simple/ \
39
+ --extra-index-url https://pypi.org/simple \
40
+ td-face-recognizer
41
+ ```
42
+
43
+ 不写版本号时 pip 会安装索引中版本号最高的版本;`--upgrade` 用于在已安装旧版本时升级到最新版。依赖(numpy/onnxruntime/opencv/scikit-image)从正式 PyPI 安装,所以需要 `--extra-index-url`。
44
+
45
+ 如果需要可复现的环境,仍建议显式指定版本,例如 `"td-face-recognizer==0.5.0"`。
46
+
47
+ 安装后的导入名是 `td_face_recognizer`(PyPI 名称中的 `-` 与 `_` 按 PEP 503 规范化等价):
48
+
49
+ ### 源码开发
50
+
51
+ ```bash
52
+ uv venv
53
+
54
+ # 方式一:按 pyproject.toml 的兼容范围安装(日常开发)
55
+ uv pip install -e .
56
+
57
+ # 方式二:使用 requirements.txt 的精确版本(复现测试/CI 环境)
58
+ uv pip install -r requirements.txt
59
+ uv pip install -e . --no-deps
60
+ ```
61
+
62
+ `pyproject.toml` 声明的是面向使用方的兼容范围;`requirements.txt` 只是开发/测试环境的锁定版本,不会随 wheel 或 sdist 分发。
63
+
64
+ ## 模型文件(必须显式提供)
65
+
66
+ 代码 wheel 中不包含 ONNX 模型。`FaceRecognizer` 初始化时必须传入 `detector_path` 和 `extractor_path`,包内不会搜索目录、读取环境变量或自动下载。
67
+
68
+ 初始化时会**强制校验两个模型文件的 SHA256**。期望值固定在 `td_face_recognizer/recognizer.py` 中,不提供参数覆盖;任一文件不匹配都会抛出 `ModelHashMismatchError`,不会进入模型加载阶段。
69
+
70
+ 模型文件放在内网 GitHub 仓库中,请手动下载,不随包分发,也没有自动下载逻辑。
71
+
72
+ 模型文件内容必须与下表一致:
73
+
74
+ | 文件 | sha256 |
75
+ |---|---|
76
+ | `FaceDetect_v1-m-b1-800x448_20260831.onnx` | `e3e9e738ee51afa6f951ce470466e8fc65c84d3a0632703c272163a30d7c1fde` |
77
+ | `FaceFeature_v1-s-b4-112x112_20261027.onnx` | `e8aeb7f8c4394b411ec0e6717e17e2c26ba71b5873df5b06590449f7c89b2ef4` |
78
+
79
+ ## 类接口(推荐)
80
+
81
+ 初始化一个 `FaceRecognizer` 后即可反复调用,模型只加载一次:
82
+
83
+ ```python
84
+ from td_face_recognizer import FaceRecognizer
85
+
86
+ with FaceRecognizer(
87
+ detector_path="/path/to/FaceDetect.onnx",
88
+ extractor_path="/path/to/FaceFeature.onnx",
89
+ min_face_ratio=0.02,
90
+ min_face_size=80,
91
+ ) as recognizer:
92
+ # 支持图片路径或 HxWx3 的 BGR ndarray
93
+ result = recognizer.recognize("photo.jpg")
94
+ feature = result.feature
95
+ print(result.face_ratio, result.bbox, result.keypoints)
96
+ ```
97
+
98
+ `detector_path` 和 `extractor_path` 都是必填参数;文件不存在时抛出 `ModelNotFoundError`,SHA256 不匹配时抛出 `ModelHashMismatchError`。hash 期望值固定在代码中,调用方无法传入或关闭校验。
99
+
100
+ - `extract_feature(image)`:返回最大人脸的 512 维 L2 归一化特征。
101
+ - `recognize(image)`:返回 `FaceRecognitionResult`,包含人脸框、关键点、置信度、特征和占比。
102
+ - `detect(image)`:返回图中所有人脸的原始检测结果。
103
+ - `result.draw(image)`:返回绘制了人脸框、5 个关键点和置信度/占比的图片副本。
104
+ - `FaceRecognizer` 支持 `with` 语句,离开时自动释放模型;也可以手动调用 `close()`。**退出 `with` 或调用 `close()` 后实例即失效,继续调用 `recognize`/`detect` 等会抛 `RuntimeError`**,需要重新创建实例。
105
+
106
+ ## 命令行
107
+
108
+ ```bash
109
+ face-recognizer photo.jpg \
110
+ --detector /path/to/FaceDetect.onnx \
111
+ --extractor /path/to/FaceFeature.onnx
112
+ # 或者
113
+ python -m td_face_recognizer photo.jpg \
114
+ --detector /path/to/FaceDetect.onnx \
115
+ --extractor /path/to/FaceFeature.onnx
116
+ ```
117
+
118
+ 输出一行 512 维特征的 JSON 数组。`--detector` / `--extractor` 为必填项;`--min-face-ratio` 指定最大人脸占比阈值(`[0,1]`,默认 `0.02`),`--min-face-size` 指定人脸框短边最小像素(默认 `80`)。
119
+
120
+ 保存标注图:
121
+
122
+ ```bash
123
+ face-recognizer photo.jpg \
124
+ --detector /path/to/FaceDetect.onnx \
125
+ --extractor /path/to/FaceFeature.onnx \
126
+ --output annotated.jpg
127
+ ```
128
+
129
+ ## 测试
130
+
131
+ 测试图片不再提交到仓库。把 `jielun1.jpeg`、`jielun2.jpeg` 放到 `tests/data/`,或通过环境变量指定目录:
132
+
133
+ ```bash
134
+ export FACE_RECOGNIZER_TEST_IMAGES_DIR=/path/to/test-images
135
+ python -m unittest discover -s tests -v
136
+ ```
137
+
138
+ 模型需要显式提供,否则依赖模型的测试会自动跳过:
139
+
140
+ ```bash
141
+ export FACE_RECOGNIZER_TEST_DETECTOR=/path/to/FaceDetect.onnx
142
+ export FACE_RECOGNIZER_TEST_EXTRACTOR=/path/to/FaceFeature.onnx
143
+ python -m unittest discover -s tests -v
144
+ ```
145
+
146
+ 不依赖模型和图片的基础测试始终会执行。
147
+
148
+ ## 发布脚本
149
+
150
+ 先在 <https://test.pypi.org/account/register/> 注册 TestPyPI 账号,并在账号设置中创建 API token(用户名固定为 `__token__`)。
151
+
152
+ ```bash
153
+ # 1. 构建 wheel(会检查 wheel 中不含 ONNX 和 tests)
154
+ ./scripts/build.sh
155
+
156
+ # 2. 发布到 TestPyPI(需要 TestPyPI API token)
157
+ TESTPYPI_TOKEN=pypi-xxx ./scripts/publish_testpypi.sh
158
+
159
+ # 3. 在临时虚拟环境中从 TestPyPI 安装并验证
160
+ VERSION=0.5.0 ./scripts/verify_testpypi_install.sh
161
+
162
+ # 可选:额外验证一次推理(需同时提供模型和图片)
163
+ DETECTOR_MODEL=/path/to/FaceDetect.onnx \
164
+ EXTRACTOR_MODEL=/path/to/FaceFeature.onnx \
165
+ FACE_RECOGNIZER_TEST_IMAGE=/path/to/photo.jpg \
166
+ VERSION=0.5.0 ./scripts/verify_testpypi_install.sh
167
+ ```
168
+
169
+ `publish_testpypi.sh` 会在上传前检查同版本是否已存在。TestPyPI 不允许重复上传同一版本,发布新版本前需要先递增 `td_face_recognizer/_version.py`。
170
+
171
+ 手动修改版本号:
172
+
173
+ ```bash
174
+ # 将 0.5.0 改成 0.5.1 / 0.6.0 / 1.0.0
175
+ vim td_face_recognizer/_version.py
176
+ ```
177
+
178
+ 或让发布脚本自动递增:
179
+
180
+ ```bash
181
+ # patch: 0.5.0 -> 0.5.1
182
+ BUMP=patch TESTPYPI_TOKEN=pypi-xxx ./scripts/publish_testpypi.sh
183
+
184
+ # minor: 0.5.1 -> 0.6.0
185
+ BUMP=minor TESTPYPI_TOKEN=pypi-xxx ./scripts/publish_testpypi.sh
186
+
187
+ # major: 0.6.0 -> 1.0.0
188
+ BUMP=major TESTPYPI_TOKEN=pypi-xxx ./scripts/publish_testpypi.sh
189
+ ```
190
+
191
+ 也可以单独使用版本号脚本:
192
+
193
+ ```bash
194
+ python3 ./scripts/bump_version.py patch
195
+ ```
196
+
197
+ > 不要把 token 直接写进 shell 命令历史;建议先 `export TESTPYPI_TOKEN=...` 或在 CI 的 Secret 中配置。如果 token 已泄露,请立即到 TestPyPI 删除并重新创建。
198
+
199
+ ## 发布到正式 PyPI
200
+
201
+ 正式 PyPI 与 TestPyPI 的关键区别:**一经发布无法删除或覆盖同名版本**,发布前必须确认开源审批已通过、版本号正确。
202
+
203
+ 先在 <https://pypi.org/account/register/> 注册账号,**开启 2FA**,并创建 API token(用户名固定为 `__token__`)。包名 `td-face-recognizer` 尚未被注册,首次上传会以当前账号创建项目并成为 owner。
204
+
205
+ ```bash
206
+ # 1. 构建 + twine check + 版本查重 + 人工确认(DRY_RUN=1 可全流程演练,不上传)
207
+ DRY_RUN=1 PYPI_TOKEN=xxx ./scripts/publish_pypi.sh
208
+
209
+ # 2. 正式发布(会再次要求人工确认)
210
+ PYPI_TOKEN=xxx ./scripts/publish_pypi.sh
211
+
212
+ # 3. 在临时虚拟环境中从正式 PyPI 安装并验证(依赖与本包同源,无需 extra-index)
213
+ VERSION=0.1.0 ./scripts/verify_pypi_install.sh
214
+
215
+ # 可选:额外验证一次推理(需同时提供模型和图片)
216
+ DETECTOR_MODEL=/path/to/FaceDetect.onnx \
217
+ EXTRACTOR_MODEL=/path/to/FaceFeature.onnx \
218
+ FACE_RECOGNIZER_TEST_IMAGE=/path/to/photo.jpg \
219
+ VERSION=0.5.0 ./scripts/verify_pypi_install.sh
220
+ ```
221
+
222
+ TestPyPI 已发过的版本号不影响正式 PyPI,两边版本号可以一致。发布后如需修改,只能递增版本号重新发布,不能覆盖。
223
+
224
+ ## 说明
225
+
226
+ - 图片使用 `cv2.imread` 读取,要求 BGR 三通道图片。
227
+ - 模型需由调用方自行分发和提供路径,包内不做下载;初始化时会强制校验 SHA256。
228
+ - 代码许可:GPL-2.0-only(`LICENSE`)。检测器部分推理逻辑衍生自 derronqi/yolov5-face(GPL-2.0-only)。
229
+ - 使用方按 GPL 要求,衍生作品需以 GPL-2.0-only 兼容许可开源。
230
+ - 若后续想放宽(如 MIT/Apache-2.0),需要先获得公司开源审批与法务对版权链的认可,再改许可证。
231
+
232
+ ## 分发授权(内部)
233
+
234
+ `LICENSE` 顶部已包含公司版权声明(`Copyright (C) 2026 Chengdu TD Tech Co., Ltd.`,GPLv2 正文之前)。发布正式 PyPI 前,仍须留存以下授权记录,均留档备查。注意:GPLv2 正文中 FSF 的版权行属于许可证本身,保持原样,不要修改。
235
+
236
+ - **开源审批**:公司在 GitHub 开源须先过内部审批(OSI 认可的许可证选择:MIT/Apache-2.0/GPL 系)。审批通过后,仓库方可公开、包方可发布到正式 PyPI。
237
+ - **版权链确认**:确认 `detector.py` 中参考 yolov5-face 的实现构成衍生作品,故整包按 GPL-2.0-only 发布(法务对 GPL 传染性的认定记录)。
238
+ - **模型授权**:两个 ONNX 模型(`FaceDetect_*.onnx`、`FaceFeature_*.onnx`)若由公司训练,版权归公司,**是否可公开分发需训练数据来源方确认**(训练集授权不等于模型可公开分发)。模型未经确认不得发布到 PyPI 或公网,仅供内网使用。目前包内已通过不打包模型 + 强制 SHA256 校验规避了模型分发问题。
@@ -0,0 +1,15 @@
1
+ td_face_recognizer/__init__.py,sha256=GwEdVRj2BbR-9Dt6XR8zNv2-dDC0rRgKxnUXn4ji3X4,740
2
+ td_face_recognizer/__main__.py,sha256=X_a9mRBHpeDQvU2K4G-82K6FsCIe4C-hSIZcXCIXazw,133
3
+ td_face_recognizer/_version.py,sha256=pkaXz-qleBXnsvDUfDDP5xZwYNBuB-gPpxQf5_r-ZFU,93
4
+ td_face_recognizer/align.py,sha256=h_PM97TTy05NmDAqEpPqJ1LSiGeZw3cLd2n7a-qxe4c,909
5
+ td_face_recognizer/cli.py,sha256=7AHk2-osBG-vhflTWZmykO7MBRCOzC1Zc-NtXYYYo44,2106
6
+ td_face_recognizer/detector.py,sha256=oLjU_iMY6fcN06FOFQhi9d72q5aHr1Z9ibWlPBvpCuA,7133
7
+ td_face_recognizer/errors.py,sha256=bjgsj6SUtGTAJE5DyPP5IKTnDz6GiHJjHKWt9SaTM6Y,591
8
+ td_face_recognizer/extractor.py,sha256=9InRV7E1WbPTrR4x54AjnmAm4o-Mxb6h0Iu2D3shbVM,3011
9
+ td_face_recognizer/model.py,sha256=KyAhIGbRmNTSaplVsvzJwr6DMMwqxlLVoJRr5yJoWwA,544
10
+ td_face_recognizer/recognizer.py,sha256=uGsa-vZ1lg67jcYnm_ad3K7-9B6kFYZVajsxmxI3ZXg,8894
11
+ td_face_recognizer-0.1.0.dist-info/METADATA,sha256=4LpbqzDrjDD-1D3S2P2xxjOW3ynoiOA5BpmliimejKk,10801
12
+ td_face_recognizer-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
13
+ td_face_recognizer-0.1.0.dist-info/entry_points.txt,sha256=-SLQIHFuFX3QKopaaJRQPRTX-Ir5ho-cl5lQ1M9Map0,64
14
+ td_face_recognizer-0.1.0.dist-info/licenses/LICENSE,sha256=3DzfMqbzJpGk66_8Nto0FdJFsa1AvByVqE7RR2nKg00,18705
15
+ td_face_recognizer-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ face-recognizer = td_face_recognizer.cli:main
@@ -0,0 +1,356 @@
1
+ td-face-recognizer
2
+ Copyright (C) 2026 Chengdu TD Tech Co., Ltd.
3
+ All rights reserved.
4
+
5
+ This program is free software; you can redistribute it and/or modify it
6
+ under the terms of the GNU General Public License, version 2 only, as
7
+ published by the Free Software Foundation.
8
+
9
+ This program is distributed in the hope that it will be useful, but
10
+ WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12
+ General Public License for more details.
13
+
14
+ You should have received a copy of the GNU General Public License along
15
+ with this program; if not, see <https://www.gnu.org/licenses/>.
16
+
17
+ ---------------------------------------------------------------------------
18
+
19
+ GNU GENERAL PUBLIC LICENSE
20
+ Version 2, June 1991
21
+
22
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
23
+ <https://fsf.org/>
24
+ Everyone is permitted to copy and distribute verbatim copies
25
+ of this license document, but changing it is not allowed.
26
+
27
+ Preamble
28
+
29
+ The licenses for most software are designed to take away your
30
+ freedom to share and change it. By contrast, the GNU General Public
31
+ License is intended to guarantee your freedom to share and change free
32
+ software--to make sure the software is free for all its users. This
33
+ General Public License applies to most of the Free Software
34
+ Foundation's software and to any other program whose authors commit to
35
+ using it. (Some other Free Software Foundation software is covered by
36
+ the GNU Lesser General Public License instead.) You can apply it to
37
+ your programs, too.
38
+
39
+ When we speak of free software, we are referring to freedom, not
40
+ price. Our General Public Licenses are designed to make sure that you
41
+ have the freedom to distribute copies of free software (and charge for
42
+ this service if you wish), that you receive source code or can get it
43
+ if you want it, that you can change the software or use pieces of it
44
+ in new free programs; and that you know you can do these things.
45
+
46
+ To protect your rights, we need to make restrictions that forbid
47
+ anyone to deny you these rights or to ask you to surrender the rights.
48
+ These restrictions translate to certain responsibilities for you if you
49
+ distribute copies of the software, or if you modify it.
50
+
51
+ For example, if you distribute copies of such a program, whether
52
+ gratis or for a fee, you must give the recipients all the rights that
53
+ you have. You must make sure that they, too, receive or can get the
54
+ source code. And you must show them these terms so they know their
55
+ rights.
56
+
57
+ We protect your rights with two steps: (1) copyright the software, and
58
+ (2) offer you this license which gives you legal permission to copy,
59
+ distribute and/or modify the software.
60
+
61
+ Also, for each author's protection and ours, we want to make certain
62
+ that everyone understands that there is no warranty for this free
63
+ software. If the software is modified by someone else and passed on, we
64
+ want its recipients to know that what they have is not the original, so
65
+ that any problems introduced by others will not reflect on the original
66
+ authors' reputations.
67
+
68
+ Finally, any free program is threatened constantly by software
69
+ patents. We wish to avoid the danger that redistributors of a free
70
+ program will individually obtain patent licenses, in effect making the
71
+ program proprietary. To prevent this, we have made it clear that any
72
+ patent must be licensed for everyone's free use or not licensed at all.
73
+
74
+ The precise terms and conditions for copying, distribution and
75
+ modification follow.
76
+
77
+ GNU GENERAL PUBLIC LICENSE
78
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
79
+
80
+ 0. This License applies to any program or other work which contains
81
+ a notice placed by the copyright holder saying it may be distributed
82
+ under the terms of this General Public License. The "Program", below,
83
+ refers to any such program or work, and a "work based on the Program"
84
+ means either the Program or any derivative work under copyright law:
85
+ that is to say, a work containing the Program or a portion of it,
86
+ either verbatim or with modifications and/or translated into another
87
+ language. (Hereinafter, translation is included without limitation in
88
+ the term "modification".) Each licensee is addressed as "you".
89
+
90
+ Activities other than copying, distribution and modification are not
91
+ covered by this License; they are outside its scope. The act of
92
+ running the Program is not restricted, and the output from the Program
93
+ is covered only if its contents constitute a work based on the
94
+ Program (independent of having been made by running the Program).
95
+ Whether that is true depends on what the Program does.
96
+
97
+ 1. You may copy and distribute verbatim copies of the Program's
98
+ source code as you receive it, in any medium, provided that you
99
+ conspicuously and appropriately publish on each copy an appropriate
100
+ copyright notice and disclaimer of warranty; keep intact all the
101
+ notices that refer to this License and to the absence of any warranty;
102
+ and give any other recipients of the Program a copy of this License
103
+ along with the Program.
104
+
105
+ You may charge a fee for the physical act of transferring a copy, and
106
+ you may at your option offer warranty protection in exchange for a fee.
107
+
108
+ 2. You may modify your copy or copies of the Program or any portion
109
+ of it, thus forming a work based on the Program, and copy and
110
+ distribute such modifications or work under the terms of Section 1
111
+ above, provided that you also meet all of these conditions:
112
+
113
+ a) You must cause the modified files to carry prominent notices
114
+ stating that you changed the files and the date of any change.
115
+
116
+ b) You must cause any work that you distribute or publish, that in
117
+ whole or in part contains or is derived from the Program or any
118
+ part thereof, to be licensed as a whole at no charge to all third
119
+ parties under the terms of this License.
120
+
121
+ c) If the modified program normally reads commands interactively
122
+ when run, you must cause it, when started running for such
123
+ interactive use in the most ordinary way, to print or display an
124
+ announcement including an appropriate copyright notice and a
125
+ notice that there is no warranty (or else, saying that you provide
126
+ a warranty) and that users may redistribute the program under
127
+ these conditions, and telling the user how to view a copy of this
128
+ License. (Exception: if the Program itself is interactive but
129
+ does not normally print such an announcement, your work based on
130
+ the Program is not required to print an announcement.)
131
+
132
+ These requirements apply to the modified work as a whole. If
133
+ identifiable sections of that work are not derived from the Program,
134
+ and can be reasonably considered independent and separate works in
135
+ themselves, then this License, and its terms, do not apply to those
136
+ sections when you distribute them as separate works. But when you
137
+ distribute the same sections as part of a whole which is a work based
138
+ on the Program, the distribution of the whole must be on the terms of
139
+ this License, whose permissions for other licensees extend to the
140
+ entire whole, and thus to each and every part regardless of who wrote it.
141
+
142
+ Thus, it is not the intent of this section to claim rights or contest
143
+ your rights to work written entirely by you; rather, the intent is to
144
+ exercise the right to control the distribution of derivative or
145
+ collective works based on the Program.
146
+
147
+ In addition, mere aggregation of another work not based on the Program
148
+ with the Program (or with a work based on the Program) on a volume of
149
+ a storage or distribution medium does not bring the other work under
150
+ the scope of this License.
151
+
152
+ 3. You may copy and distribute the Program (or a work based on it,
153
+ under Section 2) in object code or executable form under the terms of
154
+ Sections 1 and 2 above provided that you also do one of the following:
155
+
156
+ a) Accompany it with the complete corresponding machine-readable
157
+ source code, which must be distributed under the terms of Sections
158
+ 1 and 2 above on a medium customarily used for software interchange; or,
159
+
160
+ b) Accompany it with a written offer, valid for at least three
161
+ years, to give any third party, for a charge no more than your
162
+ cost of physically performing source distribution, a complete
163
+ machine-readable copy of the corresponding source code, to be
164
+ distributed under the terms of Sections 1 and 2 above on a medium
165
+ customarily used for software interchange; or,
166
+
167
+ c) Accompany it with the information you received as to the offer
168
+ to distribute corresponding source code. (This alternative is
169
+ allowed only for noncommercial distribution and only if you
170
+ received the program in object code or executable form with such
171
+ an offer, in accord with Subsection b above.)
172
+
173
+ The source code for a work means the preferred form of the work for
174
+ making modifications to it. For an executable work, complete source
175
+ code means all the source code for all modules it contains, plus any
176
+ associated interface definition files, plus the scripts used to
177
+ control compilation and installation of the executable. However, as a
178
+ special exception, the source code distributed need not include
179
+ anything that is normally distributed (in either source or binary
180
+ form) with the major components (compiler, kernel, and so on) of the
181
+ operating system on which the executable runs, unless that component
182
+ itself accompanies the executable.
183
+
184
+ If distribution of executable or object code is made by offering
185
+ access to copy from a designated place, then offering equivalent
186
+ access to copy the source code from the same place counts as
187
+ distribution of the source code, even though third parties are not
188
+ compelled to copy the source along with the object code.
189
+
190
+ 4. You may not copy, modify, sublicense, or distribute the Program
191
+ except as expressly provided under this License. Any attempt
192
+ otherwise to copy, modify, sublicense or distribute the Program is
193
+ void, and will automatically terminate your rights under this License.
194
+ However, parties who have received copies, or rights, from you under
195
+ this License will not have their licenses terminated so long as such
196
+ parties remain in full compliance.
197
+
198
+ 5. You are not required to accept this License, since you have not
199
+ signed it. However, nothing else grants you permission to modify or
200
+ distribute the Program or its derivative works. These actions are
201
+ prohibited by law if you do not accept this License. Therefore, by
202
+ modifying or distributing the Program (or any work based on the
203
+ Program), you indicate your acceptance of this License to do so, and
204
+ all its terms and conditions for copying, distributing or modifying
205
+ the Program or works based on it.
206
+
207
+ 6. Each time you redistribute the Program (or any work based on the
208
+ Program), the recipient automatically receives a license from the
209
+ original licensor to copy, distribute or modify the Program subject to
210
+ these terms and conditions. You may not impose any further
211
+ restrictions on the recipients' exercise of the rights granted herein.
212
+ You are not responsible for enforcing compliance by third parties to
213
+ this License.
214
+
215
+ 7. If, as a consequence of a court judgment or allegation of patent
216
+ infringement or for any other reason (not limited to patent issues),
217
+ conditions are imposed on you (whether by court order, agreement or
218
+ otherwise) that contradict the conditions of this License, they do not
219
+ excuse you from the conditions of this License. If you cannot
220
+ distribute so as to satisfy simultaneously your obligations under this
221
+ License and any other pertinent obligations, then as a consequence you
222
+ may not distribute the Program at all. For example, if a patent
223
+ license would not permit royalty-free redistribution of the Program by
224
+ all those who receive copies directly or indirectly through you, then
225
+ the only way you could satisfy both it and this License would be to
226
+ refrain entirely from distribution of the Program.
227
+
228
+ If any portion of this section is held invalid or unenforceable under
229
+ any particular circumstance, the balance of the section is intended to
230
+ apply and the section as a whole is intended to apply in other
231
+ circumstances.
232
+
233
+ It is not the purpose of this section to induce you to infringe any
234
+ patents or other property right claims or to contest validity of any
235
+ such claims; this section has the sole purpose of protecting the
236
+ integrity of the free software distribution system, which is
237
+ implemented by public license practices. Many people have made
238
+ generous contributions to the wide range of software distributed
239
+ through that system in reliance on consistent application of that
240
+ system; it is up to the author/donor to decide if he or she is willing
241
+ to distribute software through any other system and a licensee cannot
242
+ impose that choice.
243
+
244
+ This section is intended to make thoroughly clear what is believed to
245
+ be a consequence of the rest of this License.
246
+
247
+ 8. If the distribution and/or use of the Program is restricted in
248
+ certain countries either by patents or by copyrighted interfaces, the
249
+ original copyright holder who places the Program under this License
250
+ may add an explicit geographical distribution limitation excluding
251
+ those countries, so that distribution is permitted only in or among
252
+ countries not thus excluded. In such case, this License incorporates
253
+ the limitation as if written in the body of this License.
254
+
255
+ 9. The Free Software Foundation may publish revised and/or new versions
256
+ of the General Public License from time to time. Such new versions will
257
+ be similar in spirit to the present version, but may differ in detail to
258
+ address new problems or concerns.
259
+
260
+ Each version is given a distinguishing version number. If the Program
261
+ specifies a version number of this License which applies to it and "any
262
+ later version", you have the option of following the terms and conditions
263
+ either of that version or of any later version published by the Free
264
+ Software Foundation. If the Program does not specify a version number of
265
+ this License, you may choose any version ever published by the Free Software
266
+ Foundation.
267
+
268
+ 10. If you wish to incorporate parts of the Program into other free
269
+ programs whose distribution conditions are different, write to the author
270
+ to ask for permission. For software which is copyrighted by the Free
271
+ Software Foundation, write to the Free Software Foundation; we sometimes
272
+ make exceptions for this. Our decision will be guided by the two goals
273
+ of preserving the free status of all derivatives of our free software and
274
+ of promoting the sharing and reuse of software generally.
275
+
276
+ NO WARRANTY
277
+
278
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
279
+ FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
280
+ OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
281
+ PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
282
+ OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
283
+ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
284
+ TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
285
+ PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
286
+ REPAIR OR CORRECTION.
287
+
288
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
289
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
290
+ REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
291
+ INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
292
+ OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
293
+ TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
294
+ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
295
+ PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
296
+ POSSIBILITY OF SUCH DAMAGES.
297
+
298
+ END OF TERMS AND CONDITIONS
299
+
300
+ How to Apply These Terms to Your New Programs
301
+
302
+ If you develop a new program, and you want it to be of the greatest
303
+ possible use to the public, the best way to achieve this is to make it
304
+ free software which everyone can redistribute and change under these terms.
305
+
306
+ To do so, attach the following notices to the program. It is safest
307
+ to attach them to the start of each source file to most effectively
308
+ convey the exclusion of warranty; and each file should have at least
309
+ the "copyright" line and a pointer to where the full notice is found.
310
+
311
+ <one line to give the program's name and a brief idea of what it does.>
312
+ Copyright (C) <year> <name of author>
313
+
314
+ This program is free software; you can redistribute it and/or modify
315
+ it under the terms of the GNU General Public License as published by
316
+ the Free Software Foundation; either version 2 of the License, or
317
+ (at your option) any later version.
318
+
319
+ This program is distributed in the hope that it will be useful,
320
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
321
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
322
+ GNU General Public License for more details.
323
+
324
+ You should have received a copy of the GNU General Public License along
325
+ with this program; if not, see <https://www.gnu.org/licenses/>.
326
+
327
+ Also add information on how to contact you by electronic and paper mail.
328
+
329
+ If the program is interactive, make it output a short notice like this
330
+ when it starts in an interactive mode:
331
+
332
+ Gnomovision version 69, Copyright (C) year name of author
333
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
334
+ This is free software, and you are welcome to redistribute it
335
+ under certain conditions; type `show c' for details.
336
+
337
+ The hypothetical commands `show w' and `show c' should show the appropriate
338
+ parts of the General Public License. Of course, the commands you use may
339
+ be called something other than `show w' and `show c'; they could even be
340
+ mouse-clicks or menu items--whatever suits your program.
341
+
342
+ You should also get your employer (if you work as a programmer) or your
343
+ school, if any, to sign a "copyright disclaimer" for the program, if
344
+ necessary. Here is a sample; alter the names:
345
+
346
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
347
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
348
+
349
+ <signature of Moe Ghoul>, 1 April 1989
350
+ Moe Ghoul, President of Vice
351
+
352
+ This General Public License does not permit incorporating your program into
353
+ proprietary programs. If your program is a subroutine library, you may
354
+ consider it more useful to permit linking proprietary applications with the
355
+ library. If this is what you want to do, use the GNU Lesser General
356
+ Public License instead of this License.