├── pyproject.toml ├── .github └── workflows │ └── pypi-publish.yml ├── LICENSE ├── nonebot_plugin_savor ├── __init__.py └── savor.py └── README.md /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "nonebot-plugin-savor" 3 | version = "0.2.2" 4 | description = "NoneBot2 plugin for image analysis" 5 | authors = [ 6 | {name = "Akirami", email = "Akiramiaya@outlook.com"}, 7 | ] 8 | license = {text = "MIT"} 9 | dependencies = ["nonebot2>=2.0.0rc1", "nonebot-adapter-onebot>=2.1.3", "httpx>=0.23.0", "Pillow<10.0.0,>=9.2.0" ,"websockets>=10.4"] 10 | requires-python = ">=3.8" 11 | readme = "README.md" 12 | 13 | [project.urls] 14 | Homepage = "https://github.com/A-kirami/nonebot-plugin-savor" 15 | Repository = "https://github.com/A-kirami/nonebot-plugin-savor" 16 | 17 | [build-system] 18 | requires = ["pdm-pep517>=0.12.0"] 19 | build-backend = "pdm.pep517.api" 20 | -------------------------------------------------------------------------------- /.github/workflows/pypi-publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish Python 🐍 distributions 📦 to PyPI 2 | 3 | on: push 4 | 5 | jobs: 6 | build-n-publish: 7 | name: Build and publish Python 🐍 distributions 📦 to PyPI 8 | runs-on: ubuntu-20.04 9 | steps: 10 | - uses: actions/checkout@master 11 | - name: Set up Python 3.8 12 | uses: actions/setup-python@v1 13 | with: 14 | python-version: 3.8 15 | - name: Install pypa/build 16 | run: >- 17 | python -m 18 | pip install 19 | build 20 | --user 21 | - name: Build a binary wheel and a source tarball 22 | run: >- 23 | python -m 24 | build 25 | --sdist 26 | --wheel 27 | --outdir dist/ 28 | . 29 | - name: Publish distribution 📦 to PyPI 30 | if: startsWith(github.ref, 'refs/tags') 31 | uses: pypa/gh-action-pypi-publish@master 32 | with: 33 | password: ${{ secrets.PYPI_API_TOKEN }} -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Akirami 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. 22 | -------------------------------------------------------------------------------- /nonebot_plugin_savor/__init__.py: -------------------------------------------------------------------------------- 1 | from nonebot import on_command 2 | from nonebot.adapters.onebot.v11 import Message, MessageEvent 3 | from nonebot.adapters.onebot.v11.helpers import extract_image_urls 4 | from nonebot.log import logger 5 | from nonebot.matcher import Matcher 6 | from nonebot.params import Arg 7 | from nonebot.typing import T_State 8 | 9 | from .savor import savor_image 10 | 11 | analysis = on_command("鉴赏图片", aliases={"分析图片", "解析图片"}, block=True) 12 | 13 | 14 | @analysis.handle() 15 | async def image_analysis(event: MessageEvent, matcher: Matcher): 16 | message = reply.message if (reply := event.reply) else event.message 17 | if imgs := message["image"]: 18 | matcher.set_arg("imgs", imgs) 19 | 20 | 21 | @analysis.got("imgs", prompt="请发送需要分析的图片") 22 | async def get_image(state: T_State, imgs: Message = Arg()): 23 | urls = extract_image_urls(imgs) 24 | if not urls: 25 | await analysis.finish("没有找到图片, 分析结束") 26 | state["urls"] = urls 27 | 28 | 29 | @analysis.handle() 30 | async def analysis_handle(state: T_State): 31 | await analysis.send("正在分析图像, 请稍等……") 32 | try: 33 | result = await savor_image(state["urls"][0]) 34 | except Exception as e: 35 | logger.opt(exception=e).error("分析图像失败") 36 | await analysis.finish("分析失败, 请稍后重试", reply_message=True) 37 | msg = ", ".join(i["label"] for i in result if not i["label"].startswith("rating:")) 38 | await analysis.finish(msg, reply_message=True) 39 | -------------------------------------------------------------------------------- /nonebot_plugin_savor/savor.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import json 3 | import random 4 | import string 5 | from io import BytesIO 6 | from typing import List, TypedDict 7 | 8 | import httpx 9 | import websockets 10 | from httpx import NetworkError 11 | from PIL import Image 12 | 13 | 14 | def RandomString(): 15 | characters = string.ascii_lowercase + string.digits 16 | return "".join(random.choices(characters, k=10)) 17 | 18 | 19 | class Confidence(TypedDict): 20 | label: str 21 | confidence: float 22 | 23 | 24 | async def savor_image(img_url: str) -> List[Confidence]: 25 | async with httpx.AsyncClient() as client: 26 | res = await client.get(img_url) 27 | if res.is_error: 28 | raise NetworkError("无法获取此图像") 29 | 30 | image = Image.open(BytesIO(res.content)).convert("RGB") 31 | image.save(imageData := BytesIO(), format="jpeg") 32 | img_b64 = base64.b64encode(imageData.getvalue()).decode() 33 | 34 | session_hash = RandomString() 35 | data = ( 36 | '{"data":["data:image/jpeg;base64,' 37 | + img_b64 38 | + '",0.5],"event_data":null,"fn_index":1,"session_hash":"' 39 | + session_hash 40 | + '"}' 41 | ) 42 | try: 43 | async with websockets.connect( 44 | "wss://hysts-deepdanbooru.hf.space/queue/join" 45 | ) as websocket: 46 | greeting = await websocket.recv() 47 | await websocket.send('{"fn_index":1,"session_hash":"' + session_hash + '"}') 48 | greeting = await websocket.recv() 49 | greeting = await websocket.recv() 50 | await websocket.send(data) 51 | greeting = await websocket.recv() 52 | greeting = await websocket.recv() 53 | if "process_completed" in greeting: 54 | return json.loads(greeting)["output"]["data"][0]["confidences"] 55 | else: 56 | raise ValueError("分析出错") 57 | except Exception as e: 58 | raise NetworkError("网络出错") from e 59 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | NoneBotPluginLogo 3 |
4 |

NoneBotPluginText

5 |
6 | 7 |
8 | 9 | # nonebot-plugin-savor 10 | 11 | _✨ 二次元图像分析 ✨_ 12 | 13 | 14 | 15 | license 16 | 17 | 18 | pypi 19 | 20 | python 21 | 22 |
23 | 24 | 25 | ## 📖 介绍 26 | 27 | 使用 DeepDanbooru 进行图像分析 28 | 29 | [DeepDanbooru 在线使用](https://huggingface.co/spaces/hysts/DeepDanbooru) 30 | 31 | ## 💿 安装 32 | 33 |
34 | 使用 nb-cli 安装 35 | 在 nonebot2 项目的根目录下打开命令行, 输入以下指令即可安装 36 | 37 | nb plugin install nonebot-plugin-savor 38 | 39 |
40 | 41 |
42 | 使用包管理器安装 43 | 在 nonebot2 项目的插件目录下, 打开命令行, 根据你使用的包管理器, 输入相应的安装命令 44 | 45 |
46 | pip 47 | 48 | pip install nonebot-plugin-savor 49 |
50 |
51 | pdm 52 | 53 | pdm add nonebot-plugin-savor 54 |
55 |
56 | poetry 57 | 58 | poetry add nonebot-plugin-savor 59 |
60 |
61 | conda 62 | 63 | conda install nonebot-plugin-savor 64 |
65 | 66 | 打开 nonebot2 项目的 `bot.py` 文件, 在其中写入 67 | 68 | nonebot.load_plugin('nonebot_plugin_savor') 69 | 70 |
71 | 72 | ## 🎉 使用 73 | ### 指令表 74 | | 指令 | 需要@ | 范围 | 说明 | 75 | |:-----:|:----:|:----:|:----:| 76 | | 鉴赏图片/分析图片 + 图片 | 否 | 群聊/私聊 | 分析发送的图片, 支持回复图片 | 77 | 78 | **注意** 79 | 80 | 默认情况下, 您应该在指令前加上命令前缀, 通常是 / --------------------------------------------------------------------------------