imgscan 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,158 @@
1
+ Metadata-Version: 2.4
2
+ Name: imgscan
3
+ Version: 0.1.0
4
+ Summary: Judge stored sapic images with an external content-safety API.
5
+ Home-page: https://github.com/sapicd/imgscan
6
+ Author: staugur
7
+ Author-email: me@tcw.im
8
+ License: Apache 2.0
9
+ Description-Content-Type: text/x-rst
10
+ License-File: LICENSE
11
+ Dynamic: author
12
+ Dynamic: author-email
13
+ Dynamic: description
14
+ Dynamic: description-content-type
15
+ Dynamic: home-page
16
+ Dynamic: license
17
+ Dynamic: license-file
18
+ Dynamic: summary
19
+
20
+ imgscan
21
+ =======
22
+
23
+ 这是 sapic 图床(v2)的**图片鉴黄钩子**:把已入库的图片交给可切换的服务商判定,
24
+ 只返回拦截结论,不写库、不删对象。模块名 ``imgscan``,扩展类型 ``moderator``。
25
+
26
+ - 钩子名(模块名):``imgscan``
27
+ - 扩展类型:``moderator``\ (先发后审,不阻塞上传)
28
+ - 适用版本:sapic 2.x
29
+
30
+ 服务商
31
+ ------
32
+
33
+ 通过后台的 ``provider`` 下拉框切换,新增服务商只需在 ``imgscan.py`` 的
34
+ ``PROVIDERS`` 里注册 ``review`` / ``ping`` 两个函数。
35
+
36
+ - ``qiniu``\ (默认):七牛云内容审核,只提交色情场景 ``pulp``,使用 AK/SK 签名
37
+ - ``http``\ :通用 Bearer Token + JSON 接口,方便接自建服务或临时替换
38
+ - ``upyun``\ :又拍云内容识别(无存储),只提交色情识别;服务是否开放以控制台为准
39
+
40
+ 服务商无关的配置:
41
+
42
+ - ``threshold``\ :0~1,默认 ``0.8``;涉黄分数达到该值判 ``block``。填 ``0`` 或越界值会回退默认,不会把全部图片判为拦截
43
+ - ``timeout``\ :单次请求超时秒数,默认 10
44
+
45
+ 安装
46
+ ----
47
+
48
+ - 正式版本
49
+
50
+ `$ pip install -U imgscan`
51
+
52
+ - 本地开发
53
+
54
+ `$ cd imgscan && pip install -U .`
55
+
56
+ 依赖:只用 Python 标准库(Qiniu 的 QBox 签名用 ``hmac`` 实现),不需要额外安装包。
57
+
58
+ 七牛云配置
59
+ ----------
60
+
61
+ 在 **后台管理-钩子插件** 中导入模块名 ``imgscan``\ (或
62
+ ``POST /api/v2/hooks/import``),然后填写:
63
+
64
+ - ``qiniu_ak``\ :七牛 AccessKey
65
+ - ``qiniu_sk``\ :七牛 SecretKey(保存后不回显)
66
+ - ``qiniu_endpoint``\ :默认 ``http://ai.qiniuapi.com/v3/image/censor``\ ,一般不用改
67
+
68
+ 请求体固定为:
69
+
70
+ .. code-block:: json
71
+
72
+ {"data": {"uri": "https://.../raw/xxx.png"}, "params": {"scenes": ["pulp"]}}
73
+
74
+ Authorization 按七牛 QBox 规则对「方法 + path + Host + Content-Type + body」做
75
+ HMAC-SHA1 + urlsafe base64,签名用的是实际发送的 body,改配置后无需额外操作。
76
+
77
+ 判定时读 ``result.scenes.pulp``:场景级 ``suggestion=block``\ 直接判 ``block``;
78
+ 否则逐条看 ``details``,只有 ``suggestion=block`` 或涉黄标签(``label=pulp``)的条目
79
+ 才计入色情分,达到 ``threshold`` 判 ``block``\ 。
80
+
81
+ .. important::
82
+
83
+ ``details[].score``\ 是「该条 ``label`` 的置信度」,不是色情分。七牛对正常图通常只返回
84
+ 一条 ``label=normal``\ 的条目,``score`` 越高表示图片**越正常**(官方示例 0.65)。
85
+ 旧版误把这条 normal 置信度当色情分与阈值比较,导致越正常的图越容易被拦截。现在 normal /
86
+ sexy 条目不参与拦截判定,仅在队列的「判定说明」里展示厂商原始结论供人工复核。
87
+
88
+ 「检查配置」按钮会用空 uri 发一次带签名的请求:HTTP 400 说明服务与签名都通了,
89
+ 401 说明密钥不对,且不会消耗检测配额。
90
+
91
+ 又拍云配置
92
+ ----------
93
+
94
+ 使用**内容识别(无存储)**的 ClientKey / ClientSecret(不是云存储操作员账号):
95
+
96
+ - ``upyun_client_key``\ :ClientKey
97
+ - ``upyun_client_secret``\ :ClientSecret(保存后不回显)
98
+ - ``upyun_endpoint``\ :默认 ``https://banma.api.upyun.com/image/url/check``
99
+
100
+ 请求体为 ``{"url": "https://.../raw/xxx.png"}``\ ,签名按官方文档取
101
+ ``POST&<URI>&<GMT Date>``\ 做 HMAC-SHA1 + Base64,放在 ``Authorization: UPYUN <key>:<sign>``\ ,
102
+ 同时发送同值的 ``Date`` 头。默认 endpoint 不带 ``?act=``\ ——接口默认就是色情识别;
103
+ 若要显式带 ``?act=porn``\ ,签名仍按文档用不带 query 的 URI。
104
+
105
+ 响应取 ``porn`` 对象:``label`` 为 0 正常 / 1 色情 / 2 性感,``scores`` 依次是
106
+ 正常 / 色情 / 性感概率。判定规则:``label=1`` 直接 block,色情概率或性感概率达到
107
+ ``threshold`` 也 block;``label=0`` 时 ``rate`` 是「正常概率」,不参与拦截判断。
108
+ 「检查配置」用空 url 请求一次:400 = 服务与签名正常,401 = 密钥错误。
109
+
110
+ 自定义 HTTP 配置
111
+ ----------------
112
+
113
+ - ``http_endpoint``\ (必填):接收 ``POST`` JSON ``{"url": "..."}`` 的地址
114
+ - ``http_token``\ :可选,以 ``Authorization: Bearer <token>`` 发送
115
+ - ``http_score_key``\ :响应里的分数字段,支持点号路径如 ``data.nsfw``\ ,默认 ``score``
116
+
117
+ 接口也可以直接返回 ``{"verdict": "pass" | "block", "message": "..."}``\ ,
118
+ 此时优先采用 ``verdict``,忽略分数与阈值。
119
+
120
+ 判定契约
121
+ --------
122
+
123
+ ``review_image(image, config=None)`` 返回:
124
+
125
+ .. code-block:: python
126
+
127
+ {"code": 0, "verdict": "block", "message": "qiniu porn: pulp 0.93"}
128
+
129
+ - ``code != 0``\ :本轮判不了(没配对外地址、密钥错误、超时、响应格式不对),
130
+ 核心不会猜 ``pass``\ ,下一轮再试
131
+ - ``verdict``\ :只有 ``pass`` / ``block`` 有效;任一钩子 ``block`` 即拦截
132
+ - ``message``\ :写进 ``images.review_note``\ ,管理员在审核队列里能看到
133
+
134
+ 视频默认直接 ``pass``\ (本扫描器不处理视频)。多个审核钩子并存时按核心的合并规则:
135
+ 任一 ``block`` 即 block,任何失败都让 ``pass`` 降级为「不落结论」。
136
+
137
+ 运行
138
+ ----
139
+
140
+ 审核是**先发后审**:上传接口不受影响,入库后由定时任务扫描未审图片(默认 5 分钟一轮,
141
+ 由 APScheduler 驱动)。手动跑一批:
142
+
143
+ .. code-block:: bash
144
+
145
+ # 在 server/ 下
146
+ ../.venv/bin/flask sa review-pending -n 50
147
+
148
+ 注意
149
+ ----
150
+
151
+ - 核心只把公开可见的图片送审;``image["url"]`` 优先是 ``sapic_external_base_url + /raw/<sha>``\ ,
152
+ 没配时回退到登记外链或公开副本直链。三者都拿不到时钩子返回「判不了」;审核服务商仍需能访问这个地址
153
+ - 只提交了 ``pulp`` 场景,其他内容维度不参与判定,减少误判和费用
154
+ - 钩子不写库、不删对象;``block`` 只是从公开口径摘除,误判由管理员在
155
+ ``/api/v2/review`` 里恢复
156
+ - 如果存储后端是公有读桶,``src`` 那条 CDN 直链仍然可访问;要彻底撤回只能
157
+ ``purge`` 或把后端设为 ``visibility=private``
158
+ - 审核钩子运行在调度进程里,没有 Flask 请求上下文;不要依赖 ``request`` / ``g``
@@ -0,0 +1,6 @@
1
+ imgscan.py,sha256=wb3A3hf5cYCwpIacwaTnCdmfUctUfmfyWoKZGuQJF0w,20707
2
+ imgscan-0.1.0.dist-info/licenses/LICENSE,sha256=yVuuHRzgI17MzTVgt3LsHvuX80innw--CmNPDCzO_iw,11358
3
+ imgscan-0.1.0.dist-info/METADATA,sha256=WkxDjr_6bCY5Vo9324PXOydOBlsXfrveZ343QIc5KXU,6655
4
+ imgscan-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ imgscan-0.1.0.dist-info/top_level.txt,sha256=2oA1T4w91nIiEZquh4slR4rcLAJLziDQ4R2YCExcFoo,8
6
+ imgscan-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
@@ -0,0 +1 @@
1
+ imgscan
imgscan.py ADDED
@@ -0,0 +1,562 @@
1
+ # -*- coding: utf-8 -*-
2
+ """imgscan — judge stored images with a pluggable content-safety provider.
3
+
4
+ Driver contract (v2): ``review_image(image, config=None)`` returns
5
+ ``{"code": 0, "verdict": "pass" | "block", "message": ...}``. A non-zero
6
+ ``code`` means "this round could not judge", and the core retries later, so
7
+ network errors, quota failures and malformed responses are never reported as
8
+ ``pass``.
9
+
10
+ Providers are selected by the ``provider`` config key and register in
11
+ ``PROVIDERS``. Each provider implements ``review(image, config)`` and
12
+ ``ping(values, config)``. Currently supported:
13
+
14
+ - ``qiniu``: Qiniu Cloud image moderation, porn scene only (default)
15
+ - ``upyun``: Upyun no-storage content recognition, porn act only
16
+ - ``http``: a generic Bearer-token JSON endpoint (custom providers)
17
+
18
+ The hook only returns a verdict: it never touches the database or the storage
19
+ backend. ``block`` hides the image from public endpoints, and an admin decides
20
+ afterwards whether to approve or purge it.
21
+
22
+ ``image["url"]`` is an address the moderation service can fetch: the core first
23
+ uses ``sapic_external_base_url + /raw/<sha>``, then a registered external link
24
+ or a public replica URL. Only publicly visible images are moderated, and videos
25
+ are skipped by this scanner and reported as ``pass``.
26
+
27
+ :copyright: (c) 2026 by staugur.
28
+ :license: Apache 2.0, see LICENSE for more details.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import base64
34
+ import hashlib
35
+ import hmac
36
+ import json
37
+ import logging
38
+ from email.utils import formatdate
39
+ from urllib.error import HTTPError
40
+ from urllib.parse import urlsplit
41
+ from urllib.request import Request, urlopen
42
+
43
+ __version__ = "0.1.0"
44
+ __author__ = "staugur <me@tcw.im>"
45
+ __description__ = "可切换服务商的图片鉴黄审核钩子"
46
+ __catalog__ = "moderator"
47
+ __state__ = "disabled"
48
+ __appversion__ = "2"
49
+
50
+ logger = logging.getLogger(__name__)
51
+
52
+ FIELDS = (
53
+ (
54
+ "provider",
55
+ "select",
56
+ "服务商",
57
+ "审核服务商:七牛云 / 又拍云 / 自定义 HTTP 接口",
58
+ ),
59
+ ("qiniu_ak", "input", "七牛 AccessKey", "七牛云 AccessKey"),
60
+ ("qiniu_sk", "password", "七牛 SecretKey", "七牛云 SecretKey,保存后不回显"),
61
+ (
62
+ "qiniu_endpoint",
63
+ "input",
64
+ "七牛审核地址",
65
+ "默认 http://ai.qiniuapi.com/v3/image/censor",
66
+ ),
67
+ (
68
+ "upyun_client_key",
69
+ "input",
70
+ "又拍云 ClientKey",
71
+ "内容识别(无存储)控制台的 ClientKey",
72
+ ),
73
+ (
74
+ "upyun_client_secret",
75
+ "password",
76
+ "又拍云 ClientSecret",
77
+ "内容识别(无存储)控制台的 ClientSecret",
78
+ ),
79
+ (
80
+ "upyun_endpoint",
81
+ "input",
82
+ "又拍云审核地址",
83
+ "默认 https://banma.api.upyun.com/image/url/check",
84
+ ),
85
+ ("http_endpoint", "input", "自定义接口地址", "provider=http 时必填,接收 POST JSON"),
86
+ ("http_token", "password", "自定义接口 Token", "以 Authorization: Bearer 发送,可选"),
87
+ (
88
+ "http_score_key",
89
+ "input",
90
+ "自定义分数字段",
91
+ "响应里的分数字段,支持点号路径如 data.nsfw;默认 score",
92
+ ),
93
+ ("threshold", "input", "拦截阈值", "0~1 之间的分数,默认 0.8"),
94
+ ("timeout", "number", "超时(秒)", "单次请求超时,默认 10 秒"),
95
+ )
96
+ PROVIDER_OPTIONS = [
97
+ {"value": "qiniu", "label": "七牛云内容审核(鉴黄)"},
98
+ {"value": "upyun", "label": "又拍云内容识别(无存储)"},
99
+ {"value": "http", "label": "自定义 HTTP 接口"},
100
+ ]
101
+ REQUIRED = {
102
+ "qiniu": ("qiniu_ak", "qiniu_sk"),
103
+ "upyun": ("upyun_client_key", "upyun_client_secret"),
104
+ "http": ("http_endpoint",),
105
+ }
106
+ DEFAULTS = {
107
+ "provider": "qiniu",
108
+ "qiniu_endpoint": "http://ai.qiniuapi.com/v3/image/censor",
109
+ "upyun_endpoint": "https://banma.api.upyun.com/image/url/check",
110
+ "http_score_key": "score",
111
+ "threshold": "0.8",
112
+ "timeout": 10,
113
+ }
114
+ VERDICTS = ("pass", "block")
115
+ #: 七牛只提交色情场景;其结果里的 suggestion 是官方结论,label 用于二次兜底。
116
+ QINIU_SCENE = "pulp"
117
+ QINIU_BLOCK_LABELS = ("pulp",)
118
+
119
+
120
+ #: 自带英文词表:第三方钩子把翻译随 manifest 一起给 sapic,前端按当前语言合并。
121
+ TRANSLATIONS = {
122
+ "en": {
123
+ "title": "Image moderation (imgscan)",
124
+ "description": "Pluggable image moderation hook with switchable providers",
125
+ "fields": {
126
+ "provider": {
127
+ "label": "Provider",
128
+ "placeholder": "Moderation provider: Qiniu / Upyun / custom HTTP",
129
+ "options": {
130
+ "qiniu": "Qiniu content moderation (porn detection)",
131
+ "upyun": "Upyun content moderation (storage-free)",
132
+ "http": "Custom HTTP endpoint",
133
+ },
134
+ },
135
+ "qiniu_ak": {
136
+ "label": "Qiniu AccessKey",
137
+ "placeholder": "Qiniu Cloud AccessKey",
138
+ },
139
+ "qiniu_sk": {
140
+ "label": "Qiniu SecretKey",
141
+ "placeholder": "Qiniu Cloud SecretKey; not shown after saving",
142
+ },
143
+ "qiniu_endpoint": {
144
+ "label": "Qiniu moderation endpoint",
145
+ "placeholder": "Default http://ai.qiniuapi.com/v3/image/censor",
146
+ },
147
+ "upyun_client_key": {
148
+ "label": "Upyun ClientKey",
149
+ "placeholder": "ClientKey from the Upyun content moderation console",
150
+ },
151
+ "upyun_client_secret": {
152
+ "label": "Upyun ClientSecret",
153
+ "placeholder": "ClientSecret from the Upyun content moderation console",
154
+ },
155
+ "upyun_endpoint": {
156
+ "label": "Upyun moderation endpoint",
157
+ "placeholder": "Default https://banma.api.upyun.com/image/url/check",
158
+ },
159
+ "http_endpoint": {
160
+ "label": "Custom endpoint",
161
+ "placeholder": "Required when provider=http; accepts POST JSON",
162
+ },
163
+ "http_token": {
164
+ "label": "Custom token",
165
+ "placeholder": "Sent as Authorization: Bearer; optional",
166
+ },
167
+ "http_score_key": {
168
+ "label": "Custom score field",
169
+ "placeholder": "Score field in the response; supports dot paths like data.nsfw; defaults to score",
170
+ },
171
+ "threshold": {
172
+ "label": "Block threshold",
173
+ "placeholder": "Score between 0 and 1; default 0.8",
174
+ },
175
+ "timeout": {
176
+ "label": "Timeout (seconds)",
177
+ "placeholder": "Per-request timeout; default 10s",
178
+ },
179
+ },
180
+ },
181
+ }
182
+
183
+
184
+ def hook_manifest():
185
+ return {
186
+ "title": "图片鉴黄审核(imgscan)",
187
+ "catalog": "moderator",
188
+ "translations": TRANSLATIONS,
189
+ "config_schema": [
190
+ {
191
+ "type": kind,
192
+ "key": key,
193
+ "label": label,
194
+ "placeholder": hint,
195
+ "default": DEFAULTS.get(key, ""),
196
+ "required": False,
197
+ **({"options": PROVIDER_OPTIONS} if key == "provider" else {}),
198
+ }
199
+ for key, kind, label, hint in FIELDS
200
+ ],
201
+ "actions": [
202
+ {
203
+ "name": "ping",
204
+ "label": "检查配置",
205
+ "scope": "admin",
206
+ "with_form": True,
207
+ }
208
+ ],
209
+ }
210
+
211
+
212
+ def _cfg(config) -> dict:
213
+ data = dict(config or {})
214
+ data["provider"] = str(data.get("provider") or DEFAULTS["provider"]).strip()
215
+ #: 兼容早期通用 HTTP 版本的配置键。
216
+ for old, new in (
217
+ ("endpoint", "http_endpoint"),
218
+ ("token", "http_token"),
219
+ ("score_key", "http_score_key"),
220
+ ):
221
+ if not data.get(new) and data.get(old):
222
+ data[new] = data[old]
223
+ return data
224
+
225
+
226
+ def _value(values, config, key) -> str:
227
+ value = (values or {}).get(key)
228
+ if value in (None, ""):
229
+ value = (config or {}).get(key)
230
+ return str(value if value is not None else DEFAULTS.get(key, "")).strip()
231
+
232
+
233
+ def _limit(values, config, key) -> float:
234
+ try:
235
+ value = float(_value(values, config, key))
236
+ except (TypeError, ValueError):
237
+ return float(DEFAULTS[key])
238
+ #: 0 会让「任意分数(含 0)都 >= 阈值」成立,等于拦截一切;>1 则永不命中。
239
+ #: 两者都不是有效阈值,回退默认值,避免误配置把正常图全判为 block。
240
+ if value <= 0 or value > 1:
241
+ return float(DEFAULTS[key])
242
+ return value
243
+
244
+
245
+ def _timeout(values, config) -> int:
246
+ try:
247
+ return min(60, max(1, int(_value(values, config, "timeout"))))
248
+ except (TypeError, ValueError):
249
+ return int(DEFAULTS["timeout"])
250
+
251
+
252
+ def _score(data: dict, path: str):
253
+ node = data
254
+ for part in str(path or "score").split("."):
255
+ if not isinstance(node, dict) or part not in node:
256
+ return None
257
+ node = node[part]
258
+ try:
259
+ return float(node)
260
+ except (TypeError, ValueError):
261
+ return None
262
+
263
+
264
+ def _missing(values, config, provider) -> str | None:
265
+ for key in REQUIRED.get(provider, ()):
266
+ if not _value(values, config, key):
267
+ return key
268
+ return None
269
+
270
+
271
+ def _request(url: str, body: bytes, headers: dict, values, config) -> dict:
272
+ request = Request(url, data=body, headers=headers, method="POST")
273
+ try:
274
+ with urlopen(request, timeout=_timeout(values, config)) as response:
275
+ data = json.loads(response.read().decode("utf-8"))
276
+ except HTTPError as exc:
277
+ return {"code": 1, "message": "HTTP %s" % exc.code}
278
+ except Exception as exc:
279
+ return {"code": 1, "message": str(exc)[:200]}
280
+ if not isinstance(data, dict):
281
+ return {"code": 1, "message": "invalid moderation response"}
282
+ return {"code": 0, "data": data}
283
+
284
+
285
+ def _qiniu_auth(endpoint: str, body: str, config) -> str:
286
+ """Build the Qiniu QBox signature for this exact request body."""
287
+ parts = urlsplit(endpoint)
288
+ path = parts.path or "/"
289
+ if parts.query:
290
+ path += "?" + parts.query
291
+ signing = "POST %s\nHost: %s\nContent-Type: application/json\n\n%s" % (
292
+ path,
293
+ parts.netloc,
294
+ body,
295
+ )
296
+ ak = _value(None, config, "qiniu_ak")
297
+ sk = _value(None, config, "qiniu_sk")
298
+ digest = hmac.new(sk.encode("utf-8"), signing.encode("utf-8"), hashlib.sha1).digest()
299
+ return "Qiniu %s:%s" % (ak, base64.urlsafe_b64encode(digest).decode("ascii"))
300
+
301
+
302
+ def _qiniu_review(image, config) -> dict:
303
+ endpoint = _value(None, config, "qiniu_endpoint")
304
+ body = json.dumps(
305
+ {
306
+ "data": {"uri": image["url"]},
307
+ "params": {"scenes": [QINIU_SCENE]},
308
+ },
309
+ separators=(",", ":"),
310
+ )
311
+ headers = {
312
+ "Content-Type": "application/json",
313
+ "Authorization": _qiniu_auth(endpoint, body, config),
314
+ }
315
+ result = _request(endpoint, body.encode("utf-8"), headers, None, config)
316
+ if result["code"] != 0:
317
+ return result
318
+ data = result["data"]
319
+ if data.get("code") not in (0, 200):
320
+ return {"code": 1, "message": str(data.get("message") or "qiniu api error")[:200]}
321
+
322
+ scenes = (data.get("result") or {}).get("scenes") or {}
323
+ scene = scenes.get(QINIU_SCENE) or {}
324
+ details = scene.get("details") or []
325
+ if not isinstance(details, list) or not details:
326
+ return {"code": 1, "message": "qiniu response has no porn detail"}
327
+
328
+ #: 七牛的 score 是「该项 label 的置信度」,不是色情分。normal 项 score=0.99
329
+ #: 只说明这张图「非常正常」;拿它跟阈值比会把最正常的图全拦掉。
330
+ #: 因此只认厂商的 suggestion/block 标签,并对涉黄标签项单独做阈值兜底。
331
+ scene_suggestion = str(scene.get("suggestion") or "").strip().lower()
332
+ porn_score = 0.0
333
+ hit_label = ""
334
+ shown_label, shown_score = "", 0.0
335
+ for item in details:
336
+ if not isinstance(item, dict):
337
+ continue
338
+ label = str(item.get("label") or "").strip().lower()
339
+ suggestion = str(item.get("suggestion") or "").strip().lower()
340
+ try:
341
+ item_score = float(item.get("score") or 0)
342
+ except (TypeError, ValueError):
343
+ item_score = 0.0
344
+ #: 队列里展示厂商原始结论(含 normal 的置信度),便于人工复核。
345
+ if item_score > shown_score:
346
+ shown_label, shown_score = label, item_score
347
+ if suggestion == "block" or label in QINIU_BLOCK_LABELS:
348
+ if item_score > porn_score:
349
+ porn_score, hit_label = item_score, label
350
+ block = (
351
+ scene_suggestion == "block"
352
+ or bool(hit_label)
353
+ or porn_score >= _limit(None, config, "threshold")
354
+ )
355
+ return {
356
+ "code": 0,
357
+ "verdict": "block" if block else "pass",
358
+ "message": "qiniu porn: %s %.2f" % (shown_label or hit_label or "normal", shown_score),
359
+ }
360
+
361
+
362
+ def _qiniu_ping(values, config) -> dict:
363
+ endpoint = _value(values, config, "qiniu_endpoint")
364
+ body = json.dumps(
365
+ {"data": {"uri": ""}, "params": {"scenes": [QINIU_SCENE]}},
366
+ separators=(",", ":"),
367
+ )
368
+ request = Request(
369
+ endpoint,
370
+ data=body.encode("utf-8"),
371
+ headers={
372
+ "Content-Type": "application/json",
373
+ "Authorization": _qiniu_auth(endpoint, body, config),
374
+ },
375
+ method="POST",
376
+ )
377
+ try:
378
+ with urlopen(request, timeout=_timeout(values, config)) as response:
379
+ status = getattr(response, "status", 0) or 0
380
+ except HTTPError as exc:
381
+ status = exc.code
382
+ except Exception as exc:
383
+ return {"code": 1, "message": str(exc)[:200]}
384
+ if status == 401:
385
+ return {"code": 1, "message": "invalid qiniu credentials"}
386
+ #: 空 uri 会返回 400,说明服务与签名都通了,也不会消耗检测配额。
387
+ return {
388
+ "code": 0,
389
+ "toast": {"level": "success", "text": "qiniu reachable (HTTP %s)" % status},
390
+ }
391
+
392
+
393
+ def _upyun_auth(config, date: str) -> str:
394
+ """Sign no-storage AI requests: ``POST&URI&Date`` with the ClientSecret.
395
+
396
+ Upyun's AI examples sign the URI without the query string and do not send
397
+ Content-MD5, so keep the default endpoint free of ``?act=`` (porn is the
398
+ default action). The URI is derived from the configured endpoint.
399
+ """
400
+ uri = urlsplit(_value(None, config, "upyun_endpoint")).path or "/image/url/check"
401
+ signing = "POST&%s&%s" % (uri, date)
402
+ key = _value(None, config, "upyun_client_key")
403
+ secret = _value(None, config, "upyun_client_secret")
404
+ digest = hmac.new(secret.encode("utf-8"), signing.encode("utf-8"), hashlib.sha1).digest()
405
+ return "UPYUN %s:%s" % (key, base64.b64encode(digest).decode("ascii"))
406
+
407
+
408
+ def _upyun_headers(config) -> dict:
409
+ date = formatdate(usegmt=True)
410
+ return {
411
+ "Content-Type": "application/json",
412
+ "Date": date,
413
+ "Authorization": _upyun_auth(config, date),
414
+ }
415
+
416
+
417
+ def _upyun_review(image, config) -> dict:
418
+ endpoint = _value(None, config, "upyun_endpoint")
419
+ body = json.dumps({"url": image["url"]}, separators=(",", ":"))
420
+ result = _request(endpoint, body.encode("utf-8"), _upyun_headers(config), None, config)
421
+ if result["code"] != 0:
422
+ return result
423
+ data = result["data"]
424
+ if data.get("status_code") != 200:
425
+ return {"code": 1, "message": str(data.get("error") or "upyun api error")[:200]}
426
+ porn = data.get("porn")
427
+ if not isinstance(porn, dict):
428
+ return {"code": 1, "message": "upyun response has no porn result"}
429
+ try:
430
+ label = int(porn.get("label") or 0)
431
+ rate = float(porn.get("rate") or 0)
432
+ except (TypeError, ValueError):
433
+ return {"code": 1, "message": "invalid porn result from upyun"}
434
+ scores = porn.get("scores") or []
435
+ try:
436
+ porn_score = float(scores[1]) if len(scores) > 1 else 0.0
437
+ except (TypeError, ValueError):
438
+ porn_score = 0.0
439
+ threshold = _limit(None, config, "threshold")
440
+ #: label 0 正常、1 色情、2 性感;正常类别的 rate 是「正常概率」,不能拿来判断。
441
+ block = label == 1 or porn_score >= threshold or (label == 2 and rate >= threshold)
442
+ return {
443
+ "code": 0,
444
+ "verdict": "block" if block else "pass",
445
+ "message": "upyun porn: label=%d rate=%.2f" % (label, rate),
446
+ }
447
+
448
+
449
+ def _upyun_ping(values, config) -> dict:
450
+ endpoint = _value(values, config, "upyun_endpoint")
451
+ body = json.dumps({"url": ""}, separators=(",", ":"))
452
+ request = Request(
453
+ endpoint,
454
+ data=body.encode("utf-8"),
455
+ headers=_upyun_headers(config),
456
+ method="POST",
457
+ )
458
+ try:
459
+ with urlopen(request, timeout=_timeout(values, config)) as response:
460
+ status = getattr(response, "status", 0) or 0
461
+ except HTTPError as exc:
462
+ status = exc.code
463
+ except Exception as exc:
464
+ return {"code": 1, "message": str(exc)[:200]}
465
+ if status == 401:
466
+ return {"code": 1, "message": "invalid upyun credentials"}
467
+ #: 空 url 会返回 400,说明签名与服务都通了,也不消耗检测配额。
468
+ return {
469
+ "code": 0,
470
+ "toast": {"level": "success", "text": "upyun reachable (HTTP %s)" % status},
471
+ }
472
+
473
+
474
+ def _headers(config) -> dict:
475
+ headers = {"Content-Type": "application/json"}
476
+ token = _value(None, config, "http_token")
477
+ if token:
478
+ headers["Authorization"] = "Bearer %s" % token
479
+ return headers
480
+
481
+
482
+ def _http_review(image, config) -> dict:
483
+ endpoint = _value(None, config, "http_endpoint")
484
+ payload = {"url": image["url"]}
485
+ body = json.dumps(payload, separators=(",", ":"))
486
+ result = _request(endpoint, body.encode("utf-8"), _headers(config), None, config)
487
+ if result["code"] != 0:
488
+ return result
489
+ data = result["data"]
490
+
491
+ verdict = str(data.get("verdict") or "").strip().lower()
492
+ if verdict in VERDICTS:
493
+ return {
494
+ "code": 0,
495
+ "verdict": verdict,
496
+ "message": str(data.get("message") or "")[:200],
497
+ }
498
+ score = _score(data, _value(None, config, "http_score_key"))
499
+ if score is None:
500
+ return {"code": 1, "message": "moderation response has no score"}
501
+ return {
502
+ "code": 0,
503
+ "verdict": "block" if score >= _limit(None, config, "threshold") else "pass",
504
+ "message": "nsfw: %.2f" % score,
505
+ }
506
+
507
+
508
+ def _http_ping(values, config) -> dict:
509
+ endpoint = _value(values, config, "http_endpoint")
510
+ request = Request(endpoint, headers=_headers(config), method="GET")
511
+ try:
512
+ with urlopen(request, timeout=_timeout(values, config)) as response:
513
+ status = getattr(response, "status", 0) or 0
514
+ except HTTPError as exc:
515
+ #: 405 / 400 也说明接口活着,这里只检查可达性,不消费检测配额。
516
+ status = exc.code
517
+ except Exception as exc:
518
+ return {"code": 1, "message": str(exc)[:200]}
519
+ return {
520
+ "code": 0,
521
+ "toast": {"level": "success", "text": "endpoint reachable (HTTP %s)" % status},
522
+ }
523
+
524
+
525
+ PROVIDERS = {
526
+ "qiniu": {"review": _qiniu_review, "ping": _qiniu_ping},
527
+ "upyun": {"review": _upyun_review, "ping": _upyun_ping},
528
+ "http": {"review": _http_review, "ping": _http_ping},
529
+ }
530
+
531
+
532
+ def review_image(image, config=None) -> dict:
533
+ config = _cfg(config)
534
+ if image.get("is_video"):
535
+ return {"code": 0, "verdict": "pass", "message": "video skipped"}
536
+ url = str(image.get("url") or "").strip()
537
+ if not url:
538
+ #: 没有对外地址时判不了,交给下一轮(核心已尝试基址/外链/公开副本)。
539
+ return {"code": 1, "message": "image url is not configured"}
540
+
541
+ provider_name = config["provider"]
542
+ missing = _missing(None, config, provider_name)
543
+ if missing:
544
+ return {"code": 1, "message": "%s is required for provider %s" % (missing, provider_name)}
545
+ provider = PROVIDERS.get(provider_name)
546
+ if provider is None:
547
+ return {"code": 1, "message": "unknown provider: %s" % provider_name}
548
+ image = dict(image)
549
+ image["url"] = url
550
+ return provider["review"](image, config)
551
+
552
+
553
+ def action_ping(values=None, context=None, **kwargs):
554
+ config = _cfg((context or {}).get("config") or {})
555
+ provider_name = _value(values, config, "provider")
556
+ missing = _missing(values, config, provider_name)
557
+ if missing:
558
+ return {"code": 1, "message": "%s is required for provider %s" % (missing, provider_name)}
559
+ provider = PROVIDERS.get(provider_name)
560
+ if provider is None:
561
+ return {"code": 1, "message": "unknown provider: %s" % provider_name}
562
+ return provider["ping"](values, config)