From ed1d21ad671a658239cfe23d5bb5f29245e55914 Mon Sep 17 00:00:00 2001 From: A0000Xz <122650088+A0000Xz@users.noreply.github.com> Date: Sun, 6 Jul 2025 02:50:39 +0800 Subject: [PATCH] =?UTF-8?q?=E8=AE=A9=E9=BA=A6=E9=BA=A6=E8=87=AA=E5=B7=B1?= =?UTF-8?q?=E5=8F=91=E7=9A=84=E5=9B=BE=E7=89=87=E5=9C=A8=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93=E5=86=85=E4=B8=8D=E4=BB=A5=E6=96=87=E6=9C=AC=E6=8F=8F?= =?UTF-8?q?=E8=BF=B0=E5=AD=98=E5=82=A8=E8=80=8C=E6=98=AF=E4=BB=A5[picid:]?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/chat/message_receive/storage.py | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/src/chat/message_receive/storage.py b/src/chat/message_receive/storage.py index 862354db7..23afe6c87 100644 --- a/src/chat/message_receive/storage.py +++ b/src/chat/message_receive/storage.py @@ -4,7 +4,7 @@ from typing import Union # from ...common.database.database import db # db is now Peewee's SqliteDatabase instance from .message import MessageSending, MessageRecv from .chat_stream import ChatStream -from ...common.database.database_model import Messages, RecalledMessages # Import Peewee models +from ...common.database.database_model import Messages, RecalledMessages, Images # Import Peewee models from src.common.logger import get_logger logger = get_logger("message_storage") @@ -25,6 +25,7 @@ class MessageStorage: # print(processed_plain_text) if processed_plain_text: + processed_plain_text = MessageStorage.replace_image_descriptions(processed_plain_text) filtered_processed_plain_text = re.sub(pattern, "", processed_plain_text, flags=re.DOTALL) else: filtered_processed_plain_text = "" @@ -136,3 +137,28 @@ class MessageStorage: except Exception as e: logger.error(f"更新消息ID失败: {e}") + + @staticmethod + def replace_image_descriptions(text: str) -> str: + """将[图片:描述]替换为[picid:image_id]""" + # 先检查文本中是否有图片标记 + pattern = r'\[图片:([^\]]+)\]' + matches = re.findall(pattern, text) + + if not matches: + logger.debug("文本中没有图片标记,直接返回原文本") + return text + def replace_match(match): + description = match.group(1).strip() + try: + image_record = (Images.select() + .where(Images.description == description) + .order_by(Images.timestamp.desc()) + .first()) + if image_record: + return f"[picid:{image_record.image_id}]" + else: + return match.group(0) # 保持原样 + except Exception as e: + return match.group(0) + return re.sub(r'\[图片:([^\]]+)\]', replace_match, text)