Skip to content

Commit

Permalink
refactor!(iamai): remove unused libcore module (#335)
Browse files Browse the repository at this point in the history
  • Loading branch information
HsiangNianian authored Nov 25, 2024
1 parent 821f9bb commit 2d71ea3
Show file tree
Hide file tree
Showing 38 changed files with 2,723 additions and 2,612 deletions.
81 changes: 42 additions & 39 deletions README.rst
Original file line number Diff line number Diff line change
@@ -1,28 +1,40 @@
|discord| |qgroup| |py_v| |ruff| |docs_status|
|discord| |qgroup| |py_v| |Ruff| |docs_status|

Comprehensive AI Toolkit for Multimodal Learning and Cross-Platform Robotics |Structure|
========================================================================================

.. index-start
Welcome to iamai, a powerful and comprehensive AI toolkit that seamlessly integrates multimodal machine learning capabilities with advanced tools for cross-platform robot development!

🌍 This library is designed to provide developers with a unified solution for creating intelligent systems that span multiple modalities and operate across diverse platforms.

- 🦀 Rust based tool, fast and simple.
- 🎪 Interactive docs & demos
- 🕶 Seamless migration: Works for both Rasa and GPT and more...
- ⚡ Fully tree shakeable: Only take what you want, bundle size
- 🔩 Flexible: Configurable event filters and targets
- 🔌 Optional Add-ons: Apscheduler, etc.
- 👍 Cross-platform: dingtalk etc.

.. index-end
First of all, in the field of machine learning, we drew inspiration from the excellent design of `Hugging Face`_'s `transformers`_ for the use of pre-trained models. We would like to express our gratitude to the authors of Hugging Face and their open-source community.

Secondly, regarding the cross-platform robot framework, it is primarily based on `st`_'s `alicebot`_. We have made numerous adaptations to make it compatible with machine learning. We would like to thank the st and alicebot open-source communities for their contributions.

To avoid any potential disputes or misunderstandings, we have listed the licenses of the projects we have used and express our gratitude towards them. Please see `credits.pdf`_.
Welcome to iamai, a powerful and comprehensive AI toolkit that
seamlessly integrates multimodal machine learning capabilities with
advanced tools for cross-platform robot development!

🌍 This library is designed to provide developers with a unified
solution for creating intelligent systems that span multiple
modalities and operate across diverse platforms.

- 🦀 Rust based tool, fast and simple.
- 🎪 Interactive docs & demos
- 🕶 Seamless migration: Works for both Rasa and GPT and more…
- ⚡ Fully tree shakeable: Only take what you want, bundle size
- 🔩 Flexible: Configurable event filters and targets
- 🔌 Optional Add-ons: Apscheduler, etc.
- 👍 Cross-platform: dingtalk etc.

First of all, in the field of machine learning, we drew inspiration from
the excellent design of `Hugging Face <https://huggingface.co>`__\ ’s
`transformers <https://github.com/huggingface/transformers>`__ for the
use of pre-trained models. We would like to express our gratitude to the
authors of Hugging Face and their open-source community.

Secondly, regarding the cross-platform robot framework, it is primarily
based on `st <https://github.com/st1020>`__\ ’s
`alicebot <https://github.com/AliceBotProject/alicebot>`__. We have made
numerous adaptations to make it compatible with machine learning. We
would like to thank the st and alicebot open-source communities for
their contributions.

To avoid any potential disputes or misunderstandings, we have listed the
licenses of the projects we have used and express our gratitude towards
them. Please see `credits.pdf <./docs/_static/assets/credits.pdf>`__.

*Cite This Software*

Expand All @@ -38,37 +50,28 @@ To avoid any potential disputes or misunderstandings, we have listed the license
year = {2023}
}
----
--------------

`MIT`_ © 2023-PRESENT `Retro for Wut?`_.
`MIT <https://github.com/retrofor/iamai/blob/master/COPYING>`__ ©
2023-PRESENT `Retro for Wut? <https://github.com/retrofor>`__.

|FOSSA Status|

|FOSSA Badge|

.. |Structure| image:: https://images.repography.com/40962158/retrofor/iamai/structure/afEhYzXo83AMGRNy9EzPPQcX9ECBKj2gOPhvmpzMFSg/DQMxDEhfNZdq6zFhjPa1G61Bg9g-DRhQiwNY-W2ZHVE_table.svg
:width: 60
.. _`Hugging Face`: https://huggingface.co
.. _`transformers`: https://github.com/huggingface/transformers
.. _`st`: https://github.com/st1020
.. _`alicebot`: https://github.com/AliceBotProject/alicebot
.. _`credits.pdf`: ./docs/_static/assets/credits.pdf
.. _`MIT`: https://github.com/retrofor/iamai/blob/master/COPYING
.. _`Retro for Wut?`: https://github.com/retrofor
.. |FOSSA Status| image:: https://app.fossa.com/api/projects/git%2Bgithub.com%2Fretrofor%2Fiamai.svg?type=shield
:target: https://app.fossa.com/projects/git%2Bgithub.com%2Fretrofor%2Fiamai?ref=badge_shield
.. |FOSSA Badge| image:: https://app.fossa.com/api/projects/git%2Bgithub.com%2Fretrofor%2Fiamai.svg?type=large
:target: https://app.fossa.com/projects/git%2Bgithub.com%2Fretrofor%2Fiamai?ref=badge_large
.. |docs| image:: https://readthedocs.org/projects/iamai/badge/?version=latest
:target: https://iamai.is-a.dev/en/latest/?badge=latest
.. |ruff| image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json
:target: https://github.com/astral-sh/ruff
:alt: Ruff
.. |discord| image:: https://img.shields.io/discord/1063871387527303188?style=flat-square
:target: https://discord.gg/9vG9352RXS
.. |qgroup| image:: https://img.shields.io/badge/-QQ群%20946843972-002FA7?style=flat-square&logo=Tencent QQ&logoColor=white
:target: https://qm.qq.com/q/o7dbUNDwoo
.. |py_v| image:: https://img.shields.io/badge/v0.1.6%20Ragdoll-LTS-blue?style=flat-square&logo=python
:target: https://pypi.python.org/pypi/iamai
.. |Ruff| image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json
:target: https://github.com/astral-sh/ruff
.. |docs_status| image:: https://readthedocs.org/projects/iamai/badge/?version=latest
:target: https://iamai.is-a.dev/en/latest/?badge=latest
.. |FOSSA Status| image:: https://app.fossa.com/api/projects/git%2Bgithub.com%2Fretrofor%2Fiamai.svg?type=shield
:target: https://app.fossa.com/projects/git%2Bgithub.com%2Fretrofor%2Fiamai?ref=badge_shield
.. |FOSSA Badge| image:: https://app.fossa.com/api/projects/git%2Bgithub.com%2Fretrofor%2Fiamai.svg?type=large
:target: https://app.fossa.com/projects/git%2Bgithub.com%2Fretrofor%2Fiamai?ref=badge_large
30 changes: 0 additions & 30 deletions examples/locale/custom/LC_MESSAGES/i18n.po

This file was deleted.

18 changes: 18 additions & 0 deletions examples/plugins/_echo_cqhttp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from iamai import Plugin
from iamai.adapter.cqhttp.message import CQHTTPMessageSegment as ms
from iamai.log import logger, error_or_exception


class Echo(Plugin):
async def handle(self) -> None:
try:
await self.event.reply(eval(str(self.event.message.replace("/echo ", ""))))
except Exception as e:
await self.event.reply(f"Error: {e}")

async def rule(self) -> bool:
if self.event.adapter.name != "cqhttp":
return False
if self.event.type != "message":
return False
return self.event.message.startswith("/echo ")
2 changes: 1 addition & 1 deletion examples/plugins/_eval_kook.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from iamai import Plugin
from iamai.log import logger
from iamai.models.BM25 import BM25
from iamai.model.BM25 import BM25
from iamai.adapter.kook.message import (
KookMessage,
KookMessageSegment,
Expand Down
55 changes: 55 additions & 0 deletions examples/plugins/_github/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import re
import json
import base64
import secrets

from iamai import Plugin
from iamai.log import logger
from iamai.adapter.cqhttp.message import CQHTTPMessageSegment as ms

from .config import match_github_links
from .lib.opengraph import get_opengraph_image, indentify_message_tag


class Github(Plugin):
async def handle(self) -> None:
message_text = self.event.message.get_plain_text()

# 匹配 GitHub 链接
match = match_github_links(message_text)
if not match:
logger.warning("No valid GitHub link found in the message.")
return

# 解析匹配到的链接信息
groups = match.groupdict()
# message = {"id": self.event.message_id}
# message = message | groups

logger.info(f"message: {groups}")

tag = indentify_message_tag(groups)

if not tag:
logger.warning("No valid tag found in the message.")
return

logger.info(f"Tag: {tag}")
# 获取 OpenGraph 图片(示例代码)
image = await get_opengraph_image(tag, secrets.token_urlsafe(16))
if image:
logger.info("Image fetched successfully!")

# 将图片转换为 Base64 编码
encoded_image = base64.b64encode(image).decode("utf-8")

# 构造 CQHTTP 的图片消息格式
cq_message = ms.image(file=f"base64://{encoded_image}")

# 发送图片消息
await self.event.reply(cq_message)

async def rule(self) -> bool:
# 判断是否为 GitHub 相关消息
# return "github.com" in self.event.message.get_plain_text()
return self.event.type == "message"
76 changes: 76 additions & 0 deletions examples/plugins/_github/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import re
from examples.plugins._github.lib.opengraph import Tag

URL_PCHAR = r"(?:[a-zA-Z0-9\-._~!$&'()*+,;=:@]|%[0-9a-fA-F]{2})"
URL_QUERY_REGEX = rf"(?:\?(?:{URL_PCHAR}|[/?])*)?"

OWNER_REGEX = r"(?P<owner>[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?)"
REPO_REGEX = r"(?P<repo>[a-zA-Z0-9_\-\.]+)"
FULLREPO_REGEX = rf"{OWNER_REGEX}/{REPO_REGEX}"
COMMIT_HASH_REGEX = r"(?P<commit>[0-9a-f]{5,40})"
ISSUE_REGEX = r"(?P<issue>\d+)"
ISSUE_COMMENT_REGEX = r"(?:#issuecomment-(?P<comment>\d+))?"

GITHUB_LINK_REGEX = r"github\.com"
GITHUB_REPO_LINK_REGEX = rf"{GITHUB_LINK_REGEX}/{FULLREPO_REGEX}"
GITHUB_COMMIT_LINK_REGEX = rf"{GITHUB_REPO_LINK_REGEX}/commit/{COMMIT_HASH_REGEX}"
GITHUB_ISSUE_LINK_REGEX = (
rf"{GITHUB_REPO_LINK_REGEX}/issues/{ISSUE_REGEX}"
rf"{URL_QUERY_REGEX}{ISSUE_COMMENT_REGEX}"
)
GITHUB_PR_LINK_REGEX = (
rf"{GITHUB_REPO_LINK_REGEX}/pull/{ISSUE_REGEX}"
rf"{URL_QUERY_REGEX}{ISSUE_COMMENT_REGEX}"
)
GITHUB_ISSUE_OR_PR_LINK_REGEX = (
rf"{GITHUB_REPO_LINK_REGEX}/(?:issues|pull)/{ISSUE_REGEX}"
rf"{URL_QUERY_REGEX}{ISSUE_COMMENT_REGEX}"
)
GITHUB_PR_COMMIT_LINK_REGEX = rf"{GITHUB_PR_LINK_REGEX}/commits/{COMMIT_HASH_REGEX}"
GITHUB_PR_FILE_LINK_REGEX = rf"{GITHUB_PR_LINK_REGEX}/files"
GITHUB_RELEASE_LINK_REGEX = (
rf"{GITHUB_REPO_LINK_REGEX}/releases/tag/(?P<tag>{URL_PCHAR}+)"
)


def match_github_links(url):
"""
根据优先级匹配 GitHub 链接。
按照以下优先级进行匹配:
1. GITHUB_REPO_LINK_REGEX
2. FULLREPO_REGEX
3. GITHUB_COMMIT_LINK_REGEX
4. GITHUB_ISSUE_LINK_REGEX
5. GITHUB_PR_LINK_REGEX
6. GITHUB_ISSUE_OR_PR_LINK_REGEX
7. GITHUB_PR_COMMIT_LINK_REGEX
8. GITHUB_PR_FILE_LINK_REGEX
9. GITHUB_RELEASE_LINK_REGEX
"""
patterns = [
re.compile(GITHUB_RELEASE_LINK_REGEX),
re.compile(GITHUB_PR_FILE_LINK_REGEX),
re.compile(GITHUB_COMMIT_LINK_REGEX),
re.compile(GITHUB_ISSUE_LINK_REGEX),
re.compile(GITHUB_PR_LINK_REGEX),
re.compile(GITHUB_ISSUE_OR_PR_LINK_REGEX),
re.compile(GITHUB_PR_COMMIT_LINK_REGEX),
re.compile(GITHUB_REPO_LINK_REGEX),
re.compile(FULLREPO_REGEX),
]

for pattern in patterns:
match = pattern.search(url)
if match:
return match

return None


repo_link = match_github_links(
"https://github.com/HydroRoll-Team/infini/pull/55"
) # {'owner': 'HydroRoll-Team', 'repo': 'infini', 'issue': '55', 'comment': None}

if __name__ == "__main__":
print(repo_link)
print(Tag(**repo_link.groupdict()))
24 changes: 24 additions & 0 deletions examples/plugins/_test_random_scheduler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from time import strftime, localtime

from iamai import Plugin
from iamai.adapter.apscheduler import scheduler_decorator
import random


@scheduler_decorator(
trigger="interval",
trigger_args={"seconds": random.randint(10, 20)},
override_rule=True,
)
class Schedule(Plugin):
async def handle(self) -> None:
await self.bot.get_adapter("cqhttp").send(
f"Time: {strftime('%Y-%m-%d %H:%M:%S', localtime())}",
message_type="group",
id_=126211793, # Group ID
)

async def rule(self) -> bool:
return (
self.event.type == "apscheduler" and type(self) is self.event.plugin_class
)
18 changes: 18 additions & 0 deletions examples/plugins/commander/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from iamai import Plugin
from iamai.log import logger, error_or_exception


class Commander(Plugin):
async def handle(self) -> None:
if self.event.message == "/reload":
logger.info("正在重载插件")
await self.bot.reload_plugins()
await self.event.reply("插件已重载")
elif self.event.message == "/restart":
logger.info("正在重启 Bot")
await self.bot.restart()
await self.event.reply("Bot 已重启")

async def rule(self) -> bool:
error_or_exception(f"Commander: {self.event.message}", None, True)
return str(self.event.message) in ["/reload", "/restart", "/res"]
14 changes: 0 additions & 14 deletions examples/plugins/echo_cqhttp.py

This file was deleted.

16 changes: 8 additions & 8 deletions iamai/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
This Module imports the following contents from the sub-module.
"""

from .adapter import Adapter
from .bot import Bot
from .config import ConfigModel
from .dependencies import Depends
from .event import Event, MessageEvent
from .plugin import Plugin
from . import libcore
from iamai.adapter import Adapter
from iamai.bot import Bot
from iamai.config import ConfigModel
from iamai.dependencies import Depends
from iamai.event import Event, MessageEvent
from iamai.plugin import Plugin
from iamai._core import sum_as_string

__all__ = [
"Adapter",
Expand All @@ -21,5 +21,5 @@
"Event",
"MessageEvent",
"Plugin",
"libcore",
"Core",
]
2 changes: 1 addition & 1 deletion iamai/__main__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import sys

from .cli import cli_func
from iamai.cli import cli_func


def main(*args):
Expand Down
4 changes: 4 additions & 0 deletions iamai/_core.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from __future__ import annotations

def sum_as_string(self, a: int, b: int) -> int:
"""This function returns the sum of two numbers."""
Loading

0 comments on commit 2d71ea3

Please sign in to comment.