style: 格式化代码,修复不一致的空格和注释,更新ruff action

This commit is contained in:
春河晴
2025-04-16 16:16:37 +09:00
parent abc4c812c5
commit a8d48fc6cf
10 changed files with 98 additions and 102 deletions

View File

@@ -12,7 +12,10 @@ jobs:
with:
fetch-depth: 0
ref: ${{ github.head_ref || github.ref_name }}
- uses: astral-sh/ruff-action@v3
- name: Install the latest version of ruff
uses: astral-sh/ruff-action@v3
with:
version: "latest"
- run: ruff check --fix
- run: ruff format
- name: Commit changes

View File

@@ -57,7 +57,7 @@ class ChattingObservation(Observation):
msg_str = ""
for msg in mid_memory_by_id["messages"]:
msg_str += f"{msg['detailed_plain_text']}"
time_diff = int((datetime.now().timestamp() - mid_memory_by_id["created_at"]) / 60)
# time_diff = int((datetime.now().timestamp() - mid_memory_by_id["created_at"]) / 60)
# mid_memory_str += f"距离现在{time_diff}分钟前:\n{msg_str}\n"
mid_memory_str += f"{msg_str}\n"
except Exception as e:

View File

@@ -211,7 +211,9 @@ class SubHeartflow:
relation_prompt, sender_info.user_nickname
)
sender_name_sign = f"<{chat_stream.platform}:{sender_info.user_id}:{sender_info.user_nickname}:{sender_info.user_cardname}>"
sender_name_sign = (
f"<{chat_stream.platform}:{sender_info.user_id}:{sender_info.user_nickname}:{sender_info.user_cardname}>"
)
# prompt = ""
# # prompt += f"麦麦的总体想法是:{self.main_heartflow_info}\n\n"

View File

@@ -150,9 +150,7 @@ class MessageRecv(Message):
# if user_info.user_cardname != None
# else f"{user_info.user_nickname}(ta的id:{user_info.user_id})"
# )
name = (
f"<{self.message_info.platform}:{user_info.user_id}:{user_info.user_nickname}:{user_info.user_cardname}>"
)
name = f"<{self.message_info.platform}:{user_info.user_id}:{user_info.user_nickname}:{user_info.user_cardname}>"
return f"[{time}] {name}: {self.processed_plain_text}\n"
@@ -251,9 +249,7 @@ class MessageProcessBase(Message):
# if user_info.user_cardname != None
# else f"{user_info.user_nickname}(ta的id:{user_info.user_id})"
# )
name = (
f"<{self.message_info.platform}:{user_info.user_id}:{user_info.user_nickname}:{user_info.user_cardname}>"
)
name = f"<{self.message_info.platform}:{user_info.user_id}:{user_info.user_nickname}:{user_info.user_cardname}>"
return f"[{time}] {name}: {self.processed_plain_text}\n"

View File

@@ -672,6 +672,7 @@ def translate_timestamp_to_human_readable(timestamp: float, mode: str = "normal"
else:
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp)) + ":"
def parse_text_timestamps(text: str, mode: str = "normal") -> str:
"""解析文本中的时间戳并转换为可读时间格式
@@ -690,7 +691,7 @@ def parse_text_timestamps(text: str, mode: str = "normal") -> str:
- 不转换的时间戳替换为空字符串
"""
# 匹配[数字]或[数字.数字]格式的时间戳
pattern = r'\[(\d+(?:\.\d+)?)\]'
pattern = r"\[(\d+(?:\.\d+)?)\]"
# 找出所有匹配的时间戳
matches = list(re.finditer(pattern, text))
@@ -737,7 +738,7 @@ def parse_text_timestamps(text: str, mode: str = "normal") -> str:
to_convert = []
# 从每个时间段中选择一个时间戳进行转换
for segment, segment_timestamps in time_segments.items():
for _, segment_timestamps in time_segments.items():
# 选择这个时间段中的第一个时间戳
to_convert.append(segment_timestamps[0])
@@ -745,7 +746,7 @@ def parse_text_timestamps(text: str, mode: str = "normal") -> str:
first_in_list = False
last_in_list = False
for ts, match in to_convert:
for ts, _ in to_convert:
if ts == first_timestamp:
first_in_list = True
if ts == last_timestamp:
@@ -760,7 +761,7 @@ def parse_text_timestamps(text: str, mode: str = "normal") -> str:
to_convert_set = {match.group(0) for _, match in to_convert}
# 首先替换所有不需要转换的时间戳为空字符串
for ts, match in timestamps:
for _, match in timestamps:
if match.group(0) not in to_convert_set:
pattern_instance = re.escape(match.group(0))
result_text = re.sub(pattern_instance, "", result_text, count=1)

View File

@@ -235,7 +235,6 @@ class ThinkFlowChat:
do_reply = False
if random() < reply_probability:
try:
do_reply = True
# 回复前处理
@@ -401,8 +400,7 @@ class ThinkFlowChat:
# 处理认识关系
try:
is_known = await relationship_manager.is_known_some_one(
message.message_info.platform,
message.message_info.user_info.user_id
message.message_info.platform, message.message_info.user_info.user_id
)
if not is_known:
logger.info(f"首次认识用户: {message.message_info.user_info.user_nickname}")
@@ -410,22 +408,23 @@ class ThinkFlowChat:
message.message_info.platform,
message.message_info.user_info.user_id,
message.message_info.user_info.user_nickname,
message.message_info.user_info.user_cardname or message.message_info.user_info.user_nickname,
""
message.message_info.user_info.user_cardname
or message.message_info.user_info.user_nickname,
"",
)
else:
logger.debug(f"已认识用户: {message.message_info.user_info.user_nickname}")
if not await relationship_manager.is_qved_name(
message.message_info.platform,
message.message_info.user_info.user_id
message.message_info.platform, message.message_info.user_info.user_id
):
logger.info(f"更新已认识但未取名的用户: {message.message_info.user_info.user_nickname}")
await relationship_manager.first_knowing_some_one(
message.message_info.platform,
message.message_info.user_info.user_id,
message.message_info.user_info.user_nickname,
message.message_info.user_info.user_cardname or message.message_info.user_info.user_nickname,
""
message.message_info.user_info.user_cardname
or message.message_info.user_info.user_nickname,
"",
)
except Exception as e:
logger.error(f"处理认识关系失败: {e}")

View File

@@ -10,6 +10,7 @@ from src.heart_flow.heartflow import heartflow
from src.plugins.utils.prompt_builder import Prompt, global_prompt_manager
from src.plugins.person_info.relationship_manager import relationship_manager
from src.plugins.chat.utils import parse_text_timestamps
logger = get_module_logger("prompt")

View File

@@ -66,10 +66,7 @@ class PersonInfoManager:
db.person_info.create_index("person_id", unique=True)
# 初始化时读取所有person_name
cursor = db.person_info.find(
{"person_name": {"$exists": True}},
{"person_id": 1, "person_name": 1, "_id": 0}
)
cursor = db.person_info.find({"person_name": {"$exists": True}}, {"person_id": 1, "person_name": 1, "_id": 0})
for doc in cursor:
if doc.get("person_name"):
self.person_name_list[doc["person_id"]] = doc["person_name"]
@@ -94,7 +91,6 @@ class PersonInfoManager:
else:
return False
async def create_person_info(self, person_id: str, data: dict = None):
"""创建一个项"""
if not person_id:
@@ -137,13 +133,12 @@ class PersonInfoManager:
def _extract_json_from_text(self, text: str) -> dict:
"""从文本中提取JSON数据的高容错方法"""
try:
# 尝试直接解析
return json.loads(text)
except json.JSONDecodeError:
try:
# 尝试找到JSON格式的部分
json_pattern = r'\{[^{}]*\}'
json_pattern = r"\{[^{}]*\}"
matches = re.findall(json_pattern, text)
if matches:
return json.loads(matches[0])
@@ -158,7 +153,7 @@ class PersonInfoManager:
if nickname_match:
return {
"nickname": nickname_match.group(1),
"reason": reason_match.group(1) if reason_match else "未提供理由"
"reason": reason_match.group(1) if reason_match else "未提供理由",
}
except Exception as e:
logger.error(f"JSON提取失败: {str(e)}")
@@ -195,10 +190,10 @@ class PersonInfoManager:
if existing_names:
qv_name_prompt += f"\n请注意,以下名称已被使用,不要使用以下昵称:{existing_names}\n"
qv_name_prompt += "请用json给出你的想法并给出理由示例如下"
qv_name_prompt += '''{
qv_name_prompt += """{
"nickname": "昵称",
"reason": "理由"
}'''
}"""
logger.debug(f"取名提示词:{qv_name_prompt}")
response = await self.qv_name_llm.generate_response(qv_name_prompt)
logger.debug(f"取名回复:{response}")

View File

@@ -108,7 +108,7 @@ class RelationshipManager:
# 使用正则表达式匹配<platform:user_id:nickname:cardname>格式
all_person = person_info_manager.person_name_list
pattern = r'<([^:]+):(\d+):([^:]+):([^>]+)>'
pattern = r"<([^:]+):(\d+):([^:]+):([^>]+)>"
matches = re.findall(pattern, input_text)
# 遍历匹配结果,将<platform:user_id:nickname:cardname>替换为person_name
@@ -124,11 +124,10 @@ class RelationshipManager:
print(f"将<{platform}:{user_id}:{nickname}:{cardname}>替换为{person_name}")
result_text = result_text.replace(f"<{platform}:{user_id}:{nickname}:{cardname}>", person_name)
return result_text
except Exception as e:
except Exception:
logger.error(traceback.format_exc())
return input_text