Archived
1
0
Fork 0
This repository has been archived on 2024-04-26. You can view files and clone it, but cannot push or open issues or pull requests.
akari-bot/modules/summary/__init__.py

49 lines
2.3 KiB
Python
Raw Normal View History

2023-02-07 01:35:05 +00:00
import re
2023-02-07 06:37:14 +00:00
import ujson as json
2023-02-07 01:35:05 +00:00
from core.builtins import Bot
from core.component import on_command
2023-02-07 05:27:25 +00:00
from core.logger import Logger
2023-02-07 06:37:14 +00:00
from core.utils.http import post_url
2023-02-07 01:35:05 +00:00
2023-02-09 01:32:50 +00:00
s = on_command('summary', developers=['Dianliang233', 'OasisAkari'], desc='使用 InstructGPT 生成合并转发信息的聊天记录摘要。', available_for=['QQ', 'QQ|Group'])
2023-02-07 01:35:05 +00:00
def remove_suffix(string, suffix):
return string[:-len(suffix)] if string.endswith(suffix) else string
2023-02-09 00:32:21 +00:00
@s.handle('{开始发送聊天摘要}')
2023-02-07 01:35:05 +00:00
async def _(msg: Bot.MessageSession):
2023-02-07 06:45:02 +00:00
f_msg = await msg.waitNextMessage('接下来,请发送要生成摘要的合并转发消息。', append_instruction=False)
2023-02-08 06:12:53 +00:00
try:
f = re.search(r'\[Ke:forward,id=(.*?)\]', f_msg.asDisplay()).group(1)
except AttributeError:
2023-02-07 06:37:14 +00:00
await msg.finish('未检测到合并转发消息。')
2023-02-07 05:27:25 +00:00
Logger.info(f)
data = await f_msg.call_api('get_forward_msg', message_id=f)
msgs = data['messages']
texts = [f'\n{m["sender"]["nickname"]}{m["content"]}' for m in msgs]
char_count = sum([len(i) for i in texts])
2023-02-08 03:30:15 +00:00
wait_msg = await msg.sendMessage(f'正在生成摘要。您的聊天记录共 {char_count} 个字符,大约需要 {round(char_count / 33.5, 1)} 秒。请稍候……')
2023-02-07 06:37:14 +00:00
2023-02-08 03:26:01 +00:00
nth = 0
output = ''
while nth < len(texts):
prompt = f'请总结<|chat_start|>与<|chat_end|>之间的聊天内容。要求语言简练,但必须含有所有要点,以一段话的形式输出。' \
f'{f"<|ctx_start|>与<|ctx_end|>之间记录了聊天内容的上下文,你可以作为参考,但请你务必在输出结果之前将其原样复制。<|ctx_start|>{output}<|ctx_end|>" if nth != 0 else ""}'
len_prompt = len(prompt)
post_texts = ''
for t in texts[nth:]:
2023-02-08 06:34:26 +00:00
if len(post_texts) + len_prompt < 1970:
post_texts += texts[nth]
nth += 1
else:
break
output += remove_suffix(await post_url('https://chat-simplifier.imzbb.cc/api/generate', data=json.dumps(
2023-02-08 06:12:53 +00:00
{'prompt': f'''{prompt}<|chat_start|>
{post_texts}
<|chat_end|>'''}), headers={'Content-Type': 'application/json'}, status_code=200, timeout=9999999), '<|im_end|>')
2023-02-07 06:38:31 +00:00
await wait_msg.delete()
2023-02-08 03:26:01 +00:00
await msg.finish(output, disable_secret_check=True)