kokkoro-plugin-animetrace 0.0.0 → 1.0.1

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Yuki
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1 +1,39 @@
1
1
  # kokkoro-plugin-animetrace
2
+
3
+ 使用 [AnimeTrace](https://www.animetrace.com/) 识别图片中的动漫、游戏角色及所属作品。
4
+
5
+ ## 安装
6
+
7
+ ```shell
8
+ bun add kokkoro-plugin-animetrace
9
+ ```
10
+
11
+ 发送「/搜角色」时附带图片,插件会识别消息中的第一张图片,并通过 QQ Markdown 展示结果。发送带图的「搜角色」也可以触发识别。
12
+
13
+ 完整使用说明见 [AnimeTrace 角色识别](https://kokkoro.js.org/plugin/animetrace)。
14
+
15
+ ## 环境变量
16
+
17
+ 在项目根目录的 `.env` 中设置每个人物展示的候选角色数量上限:
18
+
19
+ ```ini
20
+ ANIMETRACE_LIMIT=3
21
+ ```
22
+
23
+ `ANIMETRACE_LIMIT` 必须为正整数,默认值为 `3`。
24
+
25
+ ## API
26
+
27
+ 通过 `service` 入口导入 `fetchCharacters()` 获取完整响应,通过 `util` 入口导入 `createMarkdown()` 生成 QQ Markdown:
28
+
29
+ ```typescript
30
+ import { fetchCharacters } from 'kokkoro-plugin-animetrace/service';
31
+ import { createMarkdown } from 'kokkoro-plugin-animetrace/util';
32
+
33
+ const { data } = await fetchCharacters('https://kokkoro.js.org/logo.png');
34
+ const markdown = createMarkdown(data);
35
+ ```
36
+
37
+ `fetchCharacters()` 的第二个参数可传入日志记录器,记录完整请求参数和接口响应。
38
+
39
+ `service` 入口同时导出 `ANIMETRACE_API`、`AnimeTrace` 和 `CharacterResult`。参数、响应字段和错误行为见 [插件 API 文档](https://kokkoro.js.org/plugin/animetrace#api)。
package/package.json CHANGED
@@ -1,15 +1,32 @@
1
1
  {
2
2
  "name": "kokkoro-plugin-animetrace",
3
- "version": "0.0.0",
4
- "exports": "./src/index.ts",
3
+ "version": "1.0.1",
4
+ "description": "AnimeTrace 角色识别,查找图片中的动漫、游戏角色及所属作品。",
5
+ "keywords": [
6
+ "animetrace",
7
+ "bot",
8
+ "kokkoro",
9
+ "qq"
10
+ ],
11
+ "bugs": "https://github.com/kokkorojs/kokkoro/issues",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/kokkorojs/kokkoro.git",
15
+ "directory": "plugins/animetrace"
16
+ },
17
+ "license": "MIT",
18
+ "author": "Yuki <admin@yuki.sh>",
5
19
  "type": "module",
20
+ "exports": {
21
+ ".": "./src/index.ts",
22
+ "./service": "./src/service.ts",
23
+ "./util": "./src/util.ts"
24
+ },
6
25
  "files": [
7
26
  "src"
8
27
  ],
9
- "devDependencies": {
10
- "@types/bun": "latest"
11
- },
12
28
  "peerDependencies": {
13
- "typescript": "^7"
29
+ "@kokkoro/core": "^3.1.4",
30
+ "typescript": "^6.0.3"
14
31
  }
15
32
  }
package/src/index.ts CHANGED
@@ -1 +1,25 @@
1
- console.log('Ciallo~(∠·ω< )⌒★');
1
+ import { useCommand, useLogger } from '@kokkoro/core';
2
+
3
+ import { fetchCharacters } from './service';
4
+ import { createMarkdown } from './util';
5
+
6
+ const logger = useLogger();
7
+
8
+ export default () => {
9
+ useCommand('/搜角色', async context => {
10
+ const image = context.attachments?.find(attachment => attachment.content_type?.startsWith('image/'));
11
+
12
+ if (!image?.url) {
13
+ throw new Error('请在指令中附带需要识别的图片');
14
+ }
15
+ const result = await fetchCharacters(image.url, logger);
16
+ const { data, trace_id } = result;
17
+
18
+ logger.info('已识别图片中的角色', { count: data.length, trace_id });
19
+
20
+ await context.reply({
21
+ msg_type: 2,
22
+ markdown: { content: createMarkdown(data) },
23
+ });
24
+ }).shortcut('搜角色');
25
+ };
package/src/service.ts ADDED
@@ -0,0 +1,70 @@
1
+ import { type Logger } from '@kokkoro/core';
2
+
3
+ /** AnimeTrace v1 识别接口的请求地址。 */
4
+ export const ANIMETRACE_API = 'https://api.animetrace.com/v1/search';
5
+
6
+ /**
7
+ * AnimeTrace 识别响应。
8
+ *
9
+ * @see https://www.animetrace.com/api-docs/
10
+ */
11
+ export interface AnimeTrace {
12
+ /** 状态码,`0` 表示成功。 */
13
+ readonly code: number;
14
+ /** 是否判定为 AI 生成图片。 */
15
+ readonly ai: boolean;
16
+ /** 本次识别的唯一 ID,反馈问题时使用。 */
17
+ readonly trace_id: string;
18
+ /** 检测到的每个人物的结果列表。 */
19
+ readonly data: readonly CharacterResult[];
20
+ }
21
+
22
+ /** AnimeTrace 返回的单个人物识别结果。 */
23
+ export interface CharacterResult {
24
+ /** 人物位置 `[x1, y1, x2, y2]`,坐标相对于图片宽高,范围为 0 到 1。 */
25
+ readonly box: readonly [number, number, number, number];
26
+ /** 每个检测框的唯一 ID。 */
27
+ readonly box_id: string;
28
+ /** 置信度较低,候选较多,需人工确认。 */
29
+ readonly not_confident: boolean;
30
+ /** 候选角色列表,越靠前可能性越大。 */
31
+ readonly character: readonly {
32
+ /** 作品名称。 */
33
+ readonly work: string;
34
+ /** 角色名称。 */
35
+ readonly character: string;
36
+ }[];
37
+ }
38
+
39
+ /** 使用 AnimeTrace 默认模型识别图片中的角色,并返回完整的接口响应。 */
40
+ export async function fetchCharacters(url: string, logger?: Logger): Promise<AnimeTrace> {
41
+ const payload = { url, is_multi: '1', ai_detect: '0' };
42
+ const form = new FormData();
43
+
44
+ for (const [key, value] of Object.entries(payload)) {
45
+ form.set(key, value);
46
+ }
47
+ logger?.debug('发送 AnimeTrace 请求', {
48
+ method: 'POST',
49
+ url: ANIMETRACE_API,
50
+ payload,
51
+ });
52
+
53
+ const response = await fetch(ANIMETRACE_API, { method: 'POST', body: form });
54
+
55
+ if (!response.ok) {
56
+ throw new Error(`接口请求失败,状态码 ${response.status}`);
57
+ }
58
+ const result = <AnimeTrace>await response.json();
59
+
60
+ logger?.debug('收到 AnimeTrace 响应', result);
61
+
62
+ if (result.code !== 0) {
63
+ throw new Error(`AnimeTrace 识别失败,状态码 ${result.code}`);
64
+ }
65
+
66
+ if (result.data.length === 0) {
67
+ throw new Error('没有识别到角色');
68
+ }
69
+ return result;
70
+ }
package/src/util.ts ADDED
@@ -0,0 +1,29 @@
1
+ import { type CharacterResult } from './service';
2
+
3
+ const { ANIMETRACE_LIMIT = 3 } = import.meta.env;
4
+ const limit = Number(ANIMETRACE_LIMIT);
5
+
6
+ if (!Number.isInteger(limit) || limit <= 0) {
7
+ throw new Error('ANIMETRACE_LIMIT 必须为正整数');
8
+ }
9
+
10
+ /** 将 AnimeTrace 识别结果转换为 QQ Markdown。 */
11
+ export function createMarkdown(results: readonly CharacterResult[]): string {
12
+ const lines = ['## AnimeTrace 搜索结果'];
13
+
14
+ if (results.some(({ not_confident: isNotConfident }) => isNotConfident)) {
15
+ lines.push('', '> 带 * 的人物可能识别不准确。');
16
+ }
17
+
18
+ for (const [index, { character: candidates, not_confident: isNotConfident }] of results.entries()) {
19
+ const prefix = results.length === 1 && isNotConfident ? '* ' : '';
20
+
21
+ lines.push('');
22
+
23
+ if (results.length > 1) {
24
+ lines.push(`**${isNotConfident ? '* ' : ''}人物 ${index + 1}**`);
25
+ }
26
+ lines.push(...candidates.slice(0, limit).map(({ character, work }) => `- **${prefix}${character}** \n ${work}`));
27
+ }
28
+ return lines.join('\n');
29
+ }