CoolFace
Apppublic

Pamudu13/gemma-3-chat

sourceHugging Faceupdated 27d agoView on Hugging Face
0likes
affection_system.py65 linesDownload Raw Back to py
1import os2import json3import re4import asyncio5from py.get_setting import USER_DATA_DIR6 7# 存储好感度数据的目录和文件8AFFECTION_DIR = os.path.join(USER_DATA_DIR, 'affection')9AFFECTION_FILE = os.path.join(AFFECTION_DIR, 'affection_data.json')10 11async def load_affection_data():12    """读取用户好感度数据"""13    os.makedirs(AFFECTION_DIR, exist_ok=True)14    if not os.path.exists(AFFECTION_FILE):15        return {}16    try:17        # 使用 asyncio.to_thread 防止阻塞事件循环18        def _read():19            with open(AFFECTION_FILE, 'r', encoding='utf-8') as f:20                return json.load(f)21        return await asyncio.to_thread(_read)22    except Exception as e:23        print(f"[Affection] 读取数据失败: {e}")24        return {}25 26async def save_affection_data(data):27    """保存用户好感度数据"""28    os.makedirs(AFFECTION_DIR, exist_ok=True)29    try:30        def _write():31            with open(AFFECTION_FILE, 'w', encoding='utf-8') as f:32                json.dump(data, f, ensure_ascii=False, indent=4)33        await asyncio.to_thread(_write)34    except Exception as e:35        print(f"[Affection] 保存数据失败: {e}")36 37async def extract_and_update_affection(full_content):38    """从AI完整的回复中提取 <user=xxx love=xxx> 并更新数据"""39    if not full_content:40        return41    42    # 正则匹配:查找 <user=用户名 属性1=数值 属性2=数值>43    # 兼容带空格的情况,如 <user=派酱 love=12 familiarity=15>44    match = re.search(r"<user=([^\s>]+)\s+(.+?)>", full_content)45    if not match:46        return47 48    user_name = match.group(1)49    stats_str = match.group(2)50 51    # 提取所有的 属性=数值52    # 支持中文属性名、负数等53    stat_matches = re.findall(r"([a-zA-Z0-9_\u4e00-\u9fa5]+)\s*=\s*(-?\d+)", stats_str)54    55    if stat_matches:56        new_stats = {k: int(v) for k, v in stat_matches}57        58        # 更新到 JSON59        data = await load_affection_data()60        if user_name not in data:61            data[user_name] = {}62        63        data[user_name].update(new_stats)64        await save_affection_data(data)65        print(f"✨ [好感度系统] 用户 {user_name} 状态已更新: {new_stats}")