Initial commit
This commit is contained in:
commit
330c41dbe7
274 files changed
+62865
No files matched your search
@@ -0,0 +1,3 @@
|
||||
"""
|
||||
工具类包
|
||||
"""
|
||||
@@ -0,0 +1,243 @@
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
import os
|
||||
import json
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
|
||||
def ensure_directory(directory):
|
||||
"""确保目录存在,如果不存在则创建"""
|
||||
if not os.path.exists(directory):
|
||||
os.makedirs(directory)
|
||||
|
||||
def inject_data_to_template(template_path, data):
|
||||
"""将数据注入到模板中
|
||||
Args:
|
||||
template_path: 模板文件路径
|
||||
data: 包含以下字段的字典:
|
||||
- year: 年份
|
||||
- greeting_text: 新年祝福寄语(主标题)
|
||||
- poem_text: 新年祝福诗
|
||||
- idioms_text: 新年祝福成语
|
||||
- wishes_text: 新年祝福愿望
|
||||
- signature: 署名
|
||||
"""
|
||||
with open(template_path, 'r', encoding='utf-8') as f:
|
||||
template_content = f.read()
|
||||
|
||||
# 处理祝福诗(分割成两句)
|
||||
poem_lines = data.get('poem_text', '梦想飞扬似朝阳,岁岁安康伴春寒').split(',')
|
||||
if len(poem_lines) < 2:
|
||||
poem_lines = [poem_lines[0], poem_lines[0]] # 如果只有一句,重复使用
|
||||
|
||||
# 处理祝福成语(分割成三个)
|
||||
idioms = data.get('idioms_text', '福满人间,万事胜意,喜乐安康').split(',')
|
||||
while len(idioms) < 3: # 确保有3个成语
|
||||
idioms.append(idioms[-1])
|
||||
|
||||
# 准备所有替换数据
|
||||
replace_data = {
|
||||
'year': data.get('year', '2025'),
|
||||
'greeting_text': data.get('greeting_text', '新年快乐'),
|
||||
'idioms_text_1': poem_lines[0],
|
||||
'idioms_text_2': poem_lines[1],
|
||||
'wishes_text': data.get('wishes_text', '愿你在新的一年里\\n事事顺遂 万事胜意'),
|
||||
'signature': data.get('signature', '署名'),
|
||||
'tag_1': idioms[0],
|
||||
'tag_2': idioms[1],
|
||||
'tag_3': idioms[2]
|
||||
}
|
||||
|
||||
# 替换所有占位符
|
||||
for key, value in replace_data.items():
|
||||
placeholder = '{' + key + '}'
|
||||
template_content = template_content.replace(placeholder, str(value))
|
||||
|
||||
# 创建临时文件来存储注入数据后的HTML
|
||||
temp_html_path = 'temp_generated.html'
|
||||
with open(temp_html_path, 'w', encoding='utf-8') as f:
|
||||
f.write(template_content)
|
||||
|
||||
return temp_html_path
|
||||
|
||||
def capture_local_html(html_path, output_path, wait_time=2):
|
||||
"""截取HTML页面为图片"""
|
||||
print(f"\n=== 开始截取HTML页面 ===")
|
||||
print(f"HTML文件路径: {html_path}")
|
||||
print(f"输出路径: {output_path}")
|
||||
|
||||
if not os.path.exists(html_path):
|
||||
error_msg = f'HTML文件不存在: {html_path}'
|
||||
print(f"错误: {error_msg}")
|
||||
raise FileNotFoundError(error_msg)
|
||||
|
||||
abs_path = os.path.abspath(html_path)
|
||||
file_url = f'file:///{abs_path}'
|
||||
print(f"文件URL: {file_url}")
|
||||
|
||||
chrome_options = Options()
|
||||
chrome_options.add_argument('--headless')
|
||||
chrome_options.add_argument('--hide-scrollbars')
|
||||
chrome_options.add_argument('--disable-gpu')
|
||||
chrome_options.add_argument('--no-sandbox')
|
||||
chrome_options.add_argument('--disable-dev-shm-usage')
|
||||
# 设置足够大的初始窗口,确保能完整显示内容
|
||||
chrome_options.add_argument('--window-size=1920,1080')
|
||||
|
||||
driver = None
|
||||
try:
|
||||
print("\n1. 初始化Chrome WebDriver...")
|
||||
driver = webdriver.Chrome(options=chrome_options)
|
||||
|
||||
print("\n2. 加载HTML页面...")
|
||||
driver.get(file_url)
|
||||
|
||||
print("\n3. 等待页面元素加载...")
|
||||
wait = WebDriverWait(driver, 10)
|
||||
card_container = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'card-container')))
|
||||
|
||||
print(f"\n4. 等待页面渲染 ({wait_time}秒)...")
|
||||
import time
|
||||
time.sleep(wait_time)
|
||||
|
||||
print("\n5. 获取卡片位置和尺寸...")
|
||||
# 获取卡片容器的精确位置和尺寸
|
||||
card_rect = driver.execute_script("""
|
||||
const container = document.querySelector('.card-container');
|
||||
const rect = container.getBoundingClientRect();
|
||||
return {
|
||||
left: rect.left,
|
||||
top: rect.top,
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
devicePixelRatio: window.devicePixelRatio
|
||||
};
|
||||
""")
|
||||
|
||||
print(f"卡片信息: {card_rect}")
|
||||
|
||||
print("\n6. 截取完整页面...")
|
||||
driver.save_screenshot('temp_full.png')
|
||||
|
||||
print("\n7. 裁剪卡片区域...")
|
||||
from PIL import Image
|
||||
img = Image.open('temp_full.png')
|
||||
|
||||
# 计算裁剪坐标(考虑设备像素比)
|
||||
dpr = card_rect['devicePixelRatio']
|
||||
left = int(card_rect['left'] * dpr)
|
||||
top = int(card_rect['top'] * dpr)
|
||||
right = int((card_rect['left'] + card_rect['width']) * dpr)
|
||||
bottom = int((card_rect['top'] + card_rect['height']) * dpr)
|
||||
|
||||
print(f"裁剪坐标: left={left}, top={top}, right={right}, bottom={bottom}")
|
||||
|
||||
# 确保裁剪区域不超出图片范围
|
||||
img_width, img_height = img.size
|
||||
left = max(0, left)
|
||||
top = max(0, top)
|
||||
right = min(img_width, right)
|
||||
bottom = min(img_height, bottom)
|
||||
|
||||
# 裁剪并保存
|
||||
card_img = img.crop((left, top, right, bottom))
|
||||
|
||||
# 确保输出目录存在
|
||||
output_dir = os.path.dirname(output_path)
|
||||
if output_dir:
|
||||
ensure_directory(output_dir)
|
||||
|
||||
print("\n8. 保存卡片图片...")
|
||||
card_img.save(output_path, quality=100) # 使用最高质量
|
||||
print(f'卡片截图已保存至: {output_path}')
|
||||
|
||||
print("\n9. 清理临时文件...")
|
||||
os.remove('temp_full.png')
|
||||
print("=== 截图完成 ===\n")
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f'截图过程发生错误: {str(e)}'
|
||||
print(f"\nError: {error_msg}")
|
||||
raise Exception(error_msg)
|
||||
|
||||
finally:
|
||||
if driver:
|
||||
print("\n10. 关闭WebDriver...")
|
||||
driver.quit()
|
||||
|
||||
|
||||
def generate_card(template_number, data, user_id):
|
||||
"""生成贺卡并保存相关信息"""
|
||||
print(f"\n=== 开始生成贺卡 ===")
|
||||
print(f"模板编号: {template_number}")
|
||||
print(f"用户ID: {user_id}")
|
||||
|
||||
try:
|
||||
# 确保目录存在
|
||||
print("\n1. 检查并创建必要的目录...")
|
||||
ensure_directory('newYear/generate_img')
|
||||
ensure_directory('newYear/version_history')
|
||||
|
||||
# 构建文件路径
|
||||
template_path = f'newYear/template/template_{template_number}.html'
|
||||
img_filename = f'{user_id}.png'
|
||||
img_path = os.path.join('newYear/generate_img', img_filename)
|
||||
json_path = os.path.join('newYear/version_history', f'{user_id}.json')
|
||||
|
||||
print(f"\n2. 检查模板文件: {template_path}")
|
||||
if not os.path.exists(template_path):
|
||||
raise FileNotFoundError(f'模板文件不存在: {template_path}')
|
||||
|
||||
print("\n3. 注入数据到模板...")
|
||||
temp_html_path = inject_data_to_template(template_path, data)
|
||||
print(f"临时HTML文件已创建: {temp_html_path}")
|
||||
|
||||
print("\n4. 生成贺卡图片...")
|
||||
capture_local_html(temp_html_path, img_path, wait_time=2)
|
||||
|
||||
print("\n5. 更新JSON文件...")
|
||||
# 只保存必要的文本数据和路径信息
|
||||
json_data = {
|
||||
'template_number': template_number,
|
||||
'image_path': img_path,
|
||||
'generation_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'template_data': {
|
||||
'year': data.get('year', '2025'),
|
||||
'greeting_text': data.get('greeting_text', ''),
|
||||
'poem_text': data.get('poem_text', ''),
|
||||
'idioms_text': data.get('idioms_text', ''),
|
||||
'wishes_text': data.get('wishes_text', ''),
|
||||
'signature': data.get('signature', '')
|
||||
}
|
||||
}
|
||||
|
||||
with open(json_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(json_data, f, ensure_ascii=False, indent=4)
|
||||
print(f"JSON文件已保存: {json_path}")
|
||||
|
||||
print("=== 贺卡生成完成 ===\n")
|
||||
return img_path
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f'生成贺卡失败: {str(e)}'
|
||||
print(f"\nError: {error_msg}")
|
||||
raise Exception(error_msg)
|
||||
|
||||
# 使用示例
|
||||
if __name__ == '__main__':
|
||||
# 示例数据
|
||||
test_data = {
|
||||
'blessing_text': '新年快乐!',
|
||||
'memory_text': '愿你在新的一年里事事顺心',
|
||||
'signature': '小明'
|
||||
}
|
||||
|
||||
# 生成卡片
|
||||
img_path = generate_card(
|
||||
template_number=1, # 使用模板1
|
||||
data=test_data,
|
||||
user_id='test_user'
|
||||
)
|
||||
@@ -0,0 +1,371 @@
|
||||
"""
|
||||
数据处理工具类,用于处理聊天记录和联系人信息
|
||||
"""
|
||||
import os
|
||||
import sqlite3
|
||||
from typing import List, Dict, Tuple
|
||||
from datetime import datetime
|
||||
import re
|
||||
|
||||
class DataProcessor:
|
||||
def __init__(self):
|
||||
"""初始化数据处理器"""
|
||||
# 获取当前文件所在目录的上两级目录作为项目根目录
|
||||
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
# 使用os.path.join构建跨平台的路径
|
||||
db_dir = os.path.join(project_root, "app", "Database", "Msg")
|
||||
self.micro_msg_db_path = os.path.join(db_dir, "MicroMsg.db")
|
||||
self.msg_db_path = os.path.join(db_dir, "MSG.db")
|
||||
self.misc_db_path = os.path.join(db_dir, "MISC.db")
|
||||
|
||||
print(f"[DataProcessor] 数据库路径配置:")
|
||||
print(f"MicroMsg数据库: {self.micro_msg_db_path}")
|
||||
print(f"MSG数据库: {self.msg_db_path}")
|
||||
print(f"MISC数据库: {self.misc_db_path}")
|
||||
|
||||
self.micro_msg_conn = None
|
||||
self.msg_conn = None
|
||||
self.misc_conn = None
|
||||
self.init_database()
|
||||
|
||||
def check_misc_tables(self):
|
||||
"""检查MISC数据库的表结构"""
|
||||
if not self.misc_conn:
|
||||
raise Exception("MISC 数据库未连接")
|
||||
|
||||
try:
|
||||
cursor = self.misc_conn.cursor()
|
||||
|
||||
# 获取所有表名
|
||||
cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
|
||||
tables = cursor.fetchall()
|
||||
|
||||
print("\nMISC数据库中的表:")
|
||||
for table in tables:
|
||||
print(f"\n表名: {table[0]}")
|
||||
cursor.execute(f"PRAGMA table_info({table[0]})")
|
||||
columns = cursor.fetchall()
|
||||
for col in columns:
|
||||
print(f" 列名: {col[1]}, 类型: {col[2]}")
|
||||
|
||||
except sqlite3.Error as e:
|
||||
print(f"检查表结构失败:{str(e)}")
|
||||
|
||||
finally:
|
||||
if cursor:
|
||||
cursor.close()
|
||||
|
||||
def init_database(self):
|
||||
"""初始化数据库连接"""
|
||||
if not os.path.exists(os.path.dirname(self.micro_msg_db_path)):
|
||||
print(f"[DataProcessor] 数据库目录不存在,尝试创建: {os.path.dirname(self.micro_msg_db_path)}")
|
||||
try:
|
||||
os.makedirs(os.path.dirname(self.micro_msg_db_path), exist_ok=True)
|
||||
except Exception as e:
|
||||
print(f"[DataProcessor] 创建数据库目录失败: {str(e)}")
|
||||
|
||||
if os.path.exists(self.micro_msg_db_path):
|
||||
try:
|
||||
self.micro_msg_conn = sqlite3.connect(self.micro_msg_db_path, check_same_thread=False)
|
||||
print(f"[DataProcessor] 成功连接到 MicroMsg 数据库: {self.micro_msg_db_path}")
|
||||
except sqlite3.Error as e:
|
||||
print(f"[DataProcessor] 连接 MicroMsg 数据库失败: {str(e)}")
|
||||
self.micro_msg_conn = None
|
||||
else:
|
||||
print(f"[DataProcessor] MicroMsg 数据库文件不存在: {self.micro_msg_db_path}")
|
||||
|
||||
if os.path.exists(self.msg_db_path):
|
||||
try:
|
||||
self.msg_conn = sqlite3.connect(self.msg_db_path, check_same_thread=False)
|
||||
print(f"[DataProcessor] 成功连接到 MSG 数据库: {self.msg_db_path}")
|
||||
except sqlite3.Error as e:
|
||||
print(f"[DataProcessor] 连接 MSG 数据库失败: {str(e)}")
|
||||
self.msg_conn = None
|
||||
else:
|
||||
print(f"[DataProcessor] MSG 数据库文件不存在: {self.msg_db_path}")
|
||||
|
||||
if os.path.exists(self.misc_db_path):
|
||||
try:
|
||||
self.misc_conn = sqlite3.connect(self.misc_db_path, check_same_thread=False)
|
||||
print(f"[DataProcessor] 成功连接到 MISC 数据库: {self.misc_db_path}")
|
||||
# 检查MISC数据库的表结构
|
||||
self.check_misc_tables()
|
||||
except sqlite3.Error as e:
|
||||
print(f"[DataProcessor] 连接 MISC 数据库失败: {str(e)}")
|
||||
self.misc_conn = None
|
||||
else:
|
||||
print(f"[DataProcessor] MISC 数据库文件不存在: {self.misc_db_path}")
|
||||
|
||||
# 如果数据库未连接,尝试从其他位置查找
|
||||
if not all([self.micro_msg_conn, self.msg_conn, self.misc_conn]):
|
||||
print("[DataProcessor] 尝试从其他位置查找数据库...")
|
||||
alt_db_paths = [
|
||||
os.path.join(project_root, "app", "DataBase", "Msg"), # 注意大小写
|
||||
os.path.join(project_root, "app", "database", "msg"),
|
||||
os.path.join(project_root, "app", "Database", "msg"),
|
||||
os.path.join(project_root, "app", "database", "Msg"),
|
||||
]
|
||||
|
||||
for db_dir in alt_db_paths:
|
||||
if os.path.exists(db_dir):
|
||||
print(f"[DataProcessor] 找到数据库目录: {db_dir}")
|
||||
self.micro_msg_db_path = os.path.join(db_dir, "MicroMsg.db")
|
||||
self.msg_db_path = os.path.join(db_dir, "MSG.db")
|
||||
self.misc_db_path = os.path.join(db_dir, "MISC.db")
|
||||
|
||||
# 重新尝试连接
|
||||
if not self.micro_msg_conn and os.path.exists(self.micro_msg_db_path):
|
||||
try:
|
||||
self.micro_msg_conn = sqlite3.connect(self.micro_msg_db_path, check_same_thread=False)
|
||||
print(f"[DataProcessor] 成功连接到 MicroMsg 数据库: {self.micro_msg_db_path}")
|
||||
except sqlite3.Error as e:
|
||||
print(f"[DataProcessor] 连接 MicroMsg 数据库失败: {str(e)}")
|
||||
|
||||
if not self.msg_conn and os.path.exists(self.msg_db_path):
|
||||
try:
|
||||
self.msg_conn = sqlite3.connect(self.msg_db_path, check_same_thread=False)
|
||||
print(f"[DataProcessor] 成功连接到 MSG 数据库: {self.msg_db_path}")
|
||||
except sqlite3.Error as e:
|
||||
print(f"[DataProcessor] 连接 MSG 数据库失败: {str(e)}")
|
||||
|
||||
if not self.misc_conn and os.path.exists(self.misc_db_path):
|
||||
try:
|
||||
self.misc_conn = sqlite3.connect(self.misc_db_path, check_same_thread=False)
|
||||
print(f"[DataProcessor] 成功连接到 MISC 数据库: {self.misc_db_path}")
|
||||
self.check_misc_tables()
|
||||
except sqlite3.Error as e:
|
||||
print(f"[DataProcessor] 连接 MISC 数据库失败: {str(e)}")
|
||||
|
||||
if all([self.micro_msg_conn, self.msg_conn, self.misc_conn]):
|
||||
print("[DataProcessor] 所有数据库连接成功")
|
||||
break
|
||||
|
||||
def check_contact_table(self):
|
||||
"""检查Contact表的结构"""
|
||||
if not self.micro_msg_conn:
|
||||
raise Exception("MicroMsg 数据库未连接")
|
||||
|
||||
try:
|
||||
cursor = self.micro_msg_conn.cursor()
|
||||
|
||||
# 获取表结构
|
||||
cursor.execute("PRAGMA table_info(Contact)")
|
||||
columns = cursor.fetchall()
|
||||
|
||||
print("\nContact表结构:")
|
||||
for col in columns:
|
||||
print(f"列名: {col[1]}, 类型: {col[2]}")
|
||||
|
||||
# 获取一条示例数据
|
||||
cursor.execute("SELECT * FROM Contact LIMIT 1")
|
||||
result = cursor.fetchone()
|
||||
|
||||
if result:
|
||||
print("\n示例数据:")
|
||||
for i, col in enumerate(columns):
|
||||
print(f"{col[1]}: {result[i]}")
|
||||
|
||||
except sqlite3.Error as e:
|
||||
print(f"检查表结构失败:{str(e)}")
|
||||
|
||||
finally:
|
||||
if cursor:
|
||||
cursor.close()
|
||||
|
||||
def get_all_contacts(self) -> List[Dict]:
|
||||
"""获取所有联系人列表
|
||||
|
||||
Returns:
|
||||
List[Dict]: 联系人列表
|
||||
"""
|
||||
if not self.micro_msg_conn:
|
||||
raise Exception("MicroMsg 数据库未连接")
|
||||
|
||||
try:
|
||||
cursor = self.micro_msg_conn.cursor()
|
||||
|
||||
# 查询所有联系人
|
||||
query = """
|
||||
SELECT Contact.UserName, Contact.Alias, Contact.Type, Contact.Remark, Contact.NickName,
|
||||
Contact.PYInitial, Contact.RemarkPYInitial,
|
||||
ContactHeadImgUrl.smallHeadImgUrl, ContactHeadImgUrl.bigHeadImgUrl,
|
||||
Contact.ExTraBuf,
|
||||
COALESCE(ContactLabel.LabelName, 'None') AS labelName
|
||||
FROM Contact
|
||||
INNER JOIN ContactHeadImgUrl ON Contact.UserName = ContactHeadImgUrl.usrName
|
||||
LEFT JOIN ContactLabel ON Contact.LabelIDList = ContactLabel.LabelId
|
||||
WHERE (Type!=4 AND VerifyFlag=0)
|
||||
AND NickName != ''
|
||||
ORDER BY
|
||||
CASE
|
||||
WHEN RemarkPYInitial = '' THEN PYInitial
|
||||
ELSE RemarkPYInitial
|
||||
END ASC
|
||||
"""
|
||||
|
||||
try:
|
||||
cursor.execute(query)
|
||||
results = cursor.fetchall()
|
||||
except sqlite3.OperationalError:
|
||||
# 处理ContactLabel表不存在的情况
|
||||
query = """
|
||||
SELECT Contact.UserName, Contact.Alias, Contact.Type, Contact.Remark, Contact.NickName,
|
||||
Contact.PYInitial, Contact.RemarkPYInitial,
|
||||
ContactHeadImgUrl.smallHeadImgUrl, ContactHeadImgUrl.bigHeadImgUrl,
|
||||
Contact.ExTraBuf,
|
||||
'None' as labelName
|
||||
FROM Contact
|
||||
INNER JOIN ContactHeadImgUrl ON Contact.UserName = ContactHeadImgUrl.usrName
|
||||
WHERE (Type!=4 AND VerifyFlag=0)
|
||||
AND NickName != ''
|
||||
ORDER BY
|
||||
CASE
|
||||
WHEN RemarkPYInitial = '' THEN PYInitial
|
||||
ELSE RemarkPYInitial
|
||||
END ASC
|
||||
"""
|
||||
cursor.execute(query)
|
||||
results = cursor.fetchall()
|
||||
|
||||
print(f"\n找到 {len(results)} 个联系人")
|
||||
|
||||
contacts = []
|
||||
for result in results:
|
||||
original_name = result[3] if result[3] else result[4] # 优先使用备注名
|
||||
display_name = re.sub(r'[\\/:*?"<>|\s\.]', '_', original_name) # 用于文件名等需要处理特殊字符的场景
|
||||
|
||||
if original_name: # 确保名称不为空
|
||||
contacts.append({
|
||||
'wxid': result[0],
|
||||
'alias': result[1],
|
||||
'type': result[2],
|
||||
'name': display_name,
|
||||
'original_name': original_name,
|
||||
'nickname': result[4],
|
||||
'py_initial': result[5],
|
||||
'remark_py_initial': result[6],
|
||||
'small_avatar_url': result[7],
|
||||
'big_avatar_url': result[8],
|
||||
'extra_buf': result[9],
|
||||
'label_name': result[10]
|
||||
})
|
||||
|
||||
return contacts
|
||||
|
||||
except sqlite3.Error as e:
|
||||
raise Exception(f"数据库查询失败:{str(e)}")
|
||||
|
||||
finally:
|
||||
if cursor:
|
||||
cursor.close()
|
||||
|
||||
def get_chat_history(self, contact_id: str, start_date: str, end_date: str) -> List[Dict]:
|
||||
"""获取指定时间范围内的聊天记录
|
||||
|
||||
Args:
|
||||
contact_id: 联系人ID
|
||||
start_date: 开始日期(格式:YYYY-MM-DD)
|
||||
end_date: 结束日期(格式:YYYY-MM-DD)
|
||||
|
||||
Returns:
|
||||
List[Dict]: 聊天记录列表
|
||||
"""
|
||||
try:
|
||||
cursor = self.msg_conn.cursor()
|
||||
|
||||
# 查询聊天记录
|
||||
query = """
|
||||
SELECT localId, TalkerId, Type, SubType, IsSender, CreateTime, Status,
|
||||
StrContent, strftime('%Y-%m-%d %H:%M:%S', CreateTime, 'unixepoch', 'localtime') as create_time
|
||||
FROM MSG
|
||||
WHERE StrTalker = ?
|
||||
AND CreateTime BETWEEN strftime('%s', ?) AND strftime('%s', ?)
|
||||
AND Type = 1 -- 只获取文本消息
|
||||
ORDER BY CreateTime ASC
|
||||
"""
|
||||
|
||||
cursor.execute(query, (contact_id, start_date, end_date))
|
||||
results = cursor.fetchall()
|
||||
|
||||
# 转换为字典列表
|
||||
chat_history = []
|
||||
for msg in results:
|
||||
chat_history.append({
|
||||
'local_id': msg[0],
|
||||
'talker_id': msg[1],
|
||||
'type': msg[2],
|
||||
'sub_type': msg[3],
|
||||
'is_sender': msg[4],
|
||||
'timestamp': msg[5],
|
||||
'status': msg[6],
|
||||
'message': msg[7],
|
||||
'create_time': msg[8]
|
||||
})
|
||||
|
||||
return chat_history
|
||||
|
||||
except sqlite3.Error as e:
|
||||
raise Exception(f"数据库查询失败:{str(e)}")
|
||||
|
||||
finally:
|
||||
if cursor:
|
||||
cursor.close()
|
||||
|
||||
def analyze_chat_content(self, chat_history: List[Dict]) -> Dict:
|
||||
"""分析聊天内容,提取关键信息
|
||||
|
||||
Args:
|
||||
chat_history: 聊天记录列表
|
||||
|
||||
Returns:
|
||||
Dict: 分析结果,包含关键词、聊天频率等信息
|
||||
"""
|
||||
# 实现聊天内容分析逻辑
|
||||
pass
|
||||
|
||||
def get_contact_avatar(self, wxid: str) -> bytes:
|
||||
"""获取联系人头像数据
|
||||
|
||||
Args:
|
||||
wxid: 联系人的微信ID
|
||||
|
||||
Returns:
|
||||
bytes: 头像的二进制数据
|
||||
"""
|
||||
try:
|
||||
print(f"[DataProcessor] 开始获取头像 - 联系人ID: {wxid}")
|
||||
cursor = self.misc_conn.cursor()
|
||||
|
||||
# 从ContactHeadImg1表获取头像数据
|
||||
query = "SELECT smallHeadBuf FROM ContactHeadImg1 WHERE usrName=?"
|
||||
cursor.execute(query, (wxid,))
|
||||
result = cursor.fetchone()
|
||||
|
||||
if result and result[0]:
|
||||
data = result[0]
|
||||
print(f"[DataProcessor] 成功获取头像数据 - 联系人ID: {wxid}, 数据大小: {len(data)} 字节")
|
||||
return data
|
||||
else:
|
||||
print(f"[DataProcessor] 未找到头像数据 - 联系人ID: {wxid}")
|
||||
return None
|
||||
|
||||
except sqlite3.Error as e:
|
||||
print(f"[DataProcessor] 获取头像失败 - 联系人ID: {wxid}, 错误: {str(e)}")
|
||||
return None
|
||||
|
||||
finally:
|
||||
if cursor:
|
||||
cursor.close()
|
||||
|
||||
def close(self):
|
||||
"""关闭数据库连接"""
|
||||
if self.micro_msg_conn:
|
||||
self.micro_msg_conn.close()
|
||||
if self.msg_conn:
|
||||
self.msg_conn.close()
|
||||
if self.misc_conn:
|
||||
self.misc_conn.close()
|
||||
|
||||
def __del__(self):
|
||||
self.close()
|
||||
@@ -0,0 +1,88 @@
|
||||
from pypinyin import lazy_pinyin, Style
|
||||
import jieba
|
||||
from typing import List, Dict, Set
|
||||
import json
|
||||
import os
|
||||
|
||||
class SearchHelper:
|
||||
def __init__(self):
|
||||
self.search_history: List[str] = []
|
||||
self.history_file = "search_history.json"
|
||||
self.load_history()
|
||||
|
||||
def load_history(self):
|
||||
"""加载搜索历史"""
|
||||
if os.path.exists(self.history_file):
|
||||
try:
|
||||
with open(self.history_file, 'r', encoding='utf-8') as f:
|
||||
self.search_history = json.load(f)
|
||||
except:
|
||||
self.search_history = []
|
||||
|
||||
def save_history(self):
|
||||
"""保存搜索历史"""
|
||||
try:
|
||||
with open(self.history_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(self.search_history[-20:], f) # 只保留最近20条记录
|
||||
except:
|
||||
pass
|
||||
|
||||
def add_history(self, keyword: str):
|
||||
"""添加搜索历史"""
|
||||
if keyword and keyword not in self.search_history:
|
||||
self.search_history.append(keyword)
|
||||
self.save_history()
|
||||
|
||||
def clear_history(self):
|
||||
"""清空搜索历史"""
|
||||
self.search_history = []
|
||||
self.save_history()
|
||||
|
||||
def get_pinyin_initials(self, text: str) -> str:
|
||||
"""获取拼音首字母"""
|
||||
return ''.join([i[0] for i in lazy_pinyin(text)])
|
||||
|
||||
def get_full_pinyin(self, text: str) -> str:
|
||||
"""获取全拼"""
|
||||
return ''.join(lazy_pinyin(text))
|
||||
|
||||
def match_contact(self, keyword: str, contact_name: str) -> bool:
|
||||
"""匹配联系人
|
||||
支持:
|
||||
1. 原文匹配(包括空格)
|
||||
2. 忽略空格匹配
|
||||
3. 拼音首字母匹配
|
||||
4. 全拼匹配
|
||||
5. 汉字模糊匹配
|
||||
"""
|
||||
if not keyword:
|
||||
return True
|
||||
|
||||
keyword = keyword.lower()
|
||||
contact_name = contact_name.lower()
|
||||
|
||||
# 原文匹配
|
||||
if keyword in contact_name:
|
||||
return True
|
||||
|
||||
# 忽略空格匹配
|
||||
if keyword.replace(' ', '') in contact_name.replace(' ', ''):
|
||||
return True
|
||||
|
||||
# 拼音首字母匹配
|
||||
pinyin_initials = self.get_pinyin_initials(contact_name).lower()
|
||||
if keyword.replace(' ', '') in pinyin_initials:
|
||||
return True
|
||||
|
||||
# 全拼匹配
|
||||
full_pinyin = self.get_full_pinyin(contact_name).lower()
|
||||
if keyword.replace(' ', '') in full_pinyin:
|
||||
return True
|
||||
|
||||
# 分词后的模糊匹配
|
||||
name_words = set(jieba.cut(contact_name))
|
||||
search_words = set(jieba.cut(keyword))
|
||||
if search_words & name_words: # 交集不为空则匹配成功
|
||||
return True
|
||||
|
||||
return False
|
||||
@@ -0,0 +1,190 @@
|
||||
"""
|
||||
版本管理器,用于管理生成内容的版本
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import base64
|
||||
from datetime import datetime
|
||||
from typing import List, Dict
|
||||
|
||||
class VersionManager:
|
||||
def __init__(self):
|
||||
# 设置版本历史目录
|
||||
self.version_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'version_history')
|
||||
|
||||
# 确保目录存在
|
||||
if not os.path.exists(self.version_dir):
|
||||
os.makedirs(self.version_dir)
|
||||
|
||||
# 初始化版本数据
|
||||
self.versions = {}
|
||||
|
||||
# 加载所有版本数据
|
||||
self.load_versions()
|
||||
|
||||
def load_versions(self):
|
||||
"""加载所有版本数据"""
|
||||
if not os.path.exists(self.version_dir):
|
||||
return
|
||||
|
||||
# 遍历版本文件
|
||||
for filename in os.listdir(self.version_dir):
|
||||
if filename.endswith('.json'):
|
||||
wxid = filename[:-5] # 移除.json后缀
|
||||
file_path = os.path.join(self.version_dir, filename)
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
encoded_versions = json.load(f)
|
||||
# 解码版本数据
|
||||
self.versions[wxid] = [
|
||||
self.process_version_data(version, encode=False)
|
||||
for version in encoded_versions
|
||||
]
|
||||
except Exception as e:
|
||||
print(f"加载版本数据失败 - 联系人ID: {wxid}, 错误: {str(e)}")
|
||||
|
||||
def save_versions(self):
|
||||
"""保存版本数据到文件"""
|
||||
# 确保目录存在
|
||||
os.makedirs(self.version_dir, exist_ok=True)
|
||||
|
||||
# 遍历所有联系人的版本数据
|
||||
for contact_id, versions in self.versions.items():
|
||||
file_path = os.path.join(self.version_dir, f"{contact_id}.json")
|
||||
|
||||
# 处理每个版本中的数据
|
||||
processed_versions = []
|
||||
for version in versions:
|
||||
# 处理二进制数据
|
||||
processed_version = self.process_version_data(version, encode=True)
|
||||
# 处理自定义风格内容
|
||||
if processed_version.get('style') == 'custom':
|
||||
processed_version['custom_prompt'] = processed_version.get('style_content', '')
|
||||
processed_versions.append(processed_version)
|
||||
|
||||
# 保存到文件
|
||||
try:
|
||||
with open(file_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(processed_versions, f, ensure_ascii=False, indent=2)
|
||||
except Exception as e:
|
||||
print(f"保存版本数据失败 - 联系人ID: {contact_id}, 错误: {str(e)}")
|
||||
|
||||
def get_version_file(self, wxid: str) -> str:
|
||||
"""获取联系人的版本文件路径"""
|
||||
return os.path.join(self.version_dir, f"{wxid}.json")
|
||||
|
||||
def add_version(self, version_info):
|
||||
"""添加新版本"""
|
||||
contact_id = version_info['contact']['wxid']
|
||||
|
||||
# 获取该联系人的所有版本
|
||||
if contact_id not in self.versions:
|
||||
self.versions[contact_id] = []
|
||||
contact_versions = self.versions[contact_id]
|
||||
|
||||
# 添加版本号
|
||||
version_number = len(contact_versions) + 1
|
||||
version_info['version_number'] = version_number
|
||||
|
||||
# 添加创建时间
|
||||
version_info['create_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
|
||||
# 处理风格内容
|
||||
style = version_info.get('style', '')
|
||||
if style == 'custom':
|
||||
# 自定义风格使用 custom_prompt
|
||||
custom_prompt = version_info.get('custom_prompt', '')
|
||||
version_info['style_content'] = custom_prompt
|
||||
else:
|
||||
# 预设风格使用 style_prompt
|
||||
style_prompt = version_info.get('style_prompt', '')
|
||||
version_info['style_content'] = style_prompt
|
||||
# 移除自定义提示词
|
||||
version_info.pop('custom_prompt', None)
|
||||
|
||||
# 添加新版本
|
||||
contact_versions.append(version_info)
|
||||
|
||||
# 保存到文件
|
||||
self.save_versions()
|
||||
|
||||
return version_info
|
||||
|
||||
def process_version_data(self, version_info: Dict, encode: bool = True) -> Dict:
|
||||
"""处理版本数据中的二进制内容"""
|
||||
processed = version_info.copy() # 创建副本以避免修改原始数据
|
||||
|
||||
# 处理联系人数据
|
||||
if 'contact' in processed:
|
||||
processed['contact'] = self.process_contact_data(processed['contact'], encode)
|
||||
|
||||
# 确保自定义风格内容被正确处理
|
||||
if processed.get('style') == 'custom':
|
||||
custom_prompt = processed.get('custom_prompt', '')
|
||||
processed['custom_prompt'] = custom_prompt
|
||||
processed['style_content'] = custom_prompt
|
||||
|
||||
return processed
|
||||
|
||||
def process_contact_data(self, contact_info: Dict, encode: bool = True) -> Dict:
|
||||
"""处理联系人数据中的二进制内容"""
|
||||
processed = contact_info.copy()
|
||||
if 'avatar' in processed:
|
||||
if encode:
|
||||
processed['avatar'] = self.encode_binary(processed['avatar'])
|
||||
else:
|
||||
processed['avatar'] = self.decode_binary(processed['avatar'])
|
||||
return processed
|
||||
|
||||
def encode_binary(self, data):
|
||||
"""编码二进制数据为base64字符串"""
|
||||
if isinstance(data, bytes):
|
||||
return base64.b64encode(data).decode('utf-8')
|
||||
return data
|
||||
|
||||
def decode_binary(self, data):
|
||||
"""解码base64字符串为二进制数据"""
|
||||
if isinstance(data, str):
|
||||
try:
|
||||
return base64.b64decode(data)
|
||||
except:
|
||||
return data
|
||||
return data
|
||||
|
||||
def get_contact_versions(self, contact_id):
|
||||
"""获取指定联系人的所有版本"""
|
||||
return self.versions.get(contact_id, [])
|
||||
|
||||
def get_all_versions(self):
|
||||
"""获取所有版本"""
|
||||
return self.versions
|
||||
|
||||
def update_version(self, version_info):
|
||||
"""更新版本信息"""
|
||||
contact_id = version_info['contact']['wxid']
|
||||
|
||||
# 处理风格内容
|
||||
style = version_info.get('style', '')
|
||||
if style == 'custom':
|
||||
# 自定义风格使用 custom_prompt
|
||||
custom_prompt = version_info.get('custom_prompt', '')
|
||||
version_info['style_content'] = custom_prompt
|
||||
else:
|
||||
# 预设风格使用 style_prompt
|
||||
style_prompt = version_info.get('style_prompt', '')
|
||||
version_info['style_content'] = style_prompt
|
||||
# 移除自定义提示词
|
||||
version_info.pop('custom_prompt', None)
|
||||
|
||||
# 获取该联系人的所有版本
|
||||
contact_versions = self.versions.get(contact_id, [])
|
||||
|
||||
# 查找并更新版本
|
||||
for i, version in enumerate(contact_versions):
|
||||
if version.get('version_number') == version_info.get('version_number'):
|
||||
contact_versions[i] = version_info
|
||||
break
|
||||
|
||||
# 保存更新后的版本
|
||||
self.versions[contact_id] = contact_versions
|
||||
self.save_versions()
|
||||
@@ -0,0 +1,483 @@
|
||||
import json
|
||||
from typing import Dict, List, Tuple
|
||||
from volcenginesdkarkruntime import Ark
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
class VolcanoAPI:
|
||||
"""火山引擎API调用工具类"""
|
||||
|
||||
def __init__(self, api_key: str):
|
||||
self.api_key = api_key
|
||||
self.client = Ark(
|
||||
base_url="https://ark.cn-beijing.volces.com/api/v3",
|
||||
api_key=api_key
|
||||
)
|
||||
|
||||
def test_connection(self) -> Tuple[bool, str]:
|
||||
"""测试API连接是否正常
|
||||
|
||||
Returns:
|
||||
Tuple[bool, str]: (是否连接成功, 错误信息)
|
||||
"""
|
||||
try:
|
||||
# 构造一个简单的测试请求
|
||||
test_prompt = "你好,这是一个测试消息。"
|
||||
response = self.client.chat.completions.create(
|
||||
model="Doubao-vision-lite-32k",
|
||||
messages=[
|
||||
{"role": "user", "content": test_prompt}
|
||||
],
|
||||
extra_headers={'x-is-encrypted': 'true'}
|
||||
)
|
||||
|
||||
if response and response.choices:
|
||||
return True, "API连接成功"
|
||||
else:
|
||||
return False, "API响应异常:没有返回有效内容"
|
||||
|
||||
except Exception as e:
|
||||
return False, f"API请求异常: {str(e)}"
|
||||
|
||||
def generate_greeting(self, contact_info: Dict, chat_history: List[Dict], style_prompt: str) -> Dict:
|
||||
"""生成新年祝福内容
|
||||
|
||||
Args:
|
||||
contact_info: 联系人信息,包含姓名和wxid
|
||||
chat_history: 聊天记录列表
|
||||
style_prompt: 风格提示词
|
||||
|
||||
Returns:
|
||||
Dict: 包含生成的祝福内容
|
||||
"""
|
||||
try:
|
||||
# 分析聊天记录,提取关键信息
|
||||
chat_analysis = self._analyze_chat_history(chat_history)
|
||||
|
||||
# 构建完整的提示词
|
||||
prompt = self._build_prompt(contact_info, chat_analysis, style_prompt)
|
||||
|
||||
# 调用API生成内容
|
||||
response = self.client.chat.completions.create(
|
||||
model="ep-20250120142713-z5cs6",
|
||||
messages=[
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
extra_headers={'x-is-encrypted': 'true'}
|
||||
)
|
||||
|
||||
# 解析响应内容
|
||||
return self._parse_response(response)
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"生成祝福内容失败:{str(e)}")
|
||||
|
||||
def _analyze_chat_history(self, chat_history: List[Dict]) -> Dict:
|
||||
"""深度分析聊天记录,提取有价值的信息用于生成个性化祝福
|
||||
|
||||
Args:
|
||||
chat_history: 聊天记录列表,每条记录包含:
|
||||
- message: 消息内容
|
||||
- is_sender: 是否为发送者
|
||||
- create_time: 消息时间
|
||||
|
||||
Returns:
|
||||
Dict: 分析结果,包含:
|
||||
- chat_frequency: 聊天频率
|
||||
- relationship_level: 关系亲密度
|
||||
- common_topics: 共同话题
|
||||
- emotional_keywords: 情感关键词
|
||||
- interaction_style: 互动方式
|
||||
- chat_time_distribution: 聊天时间分布
|
||||
- key_life_events: 重要生活事件
|
||||
"""
|
||||
from collections import Counter, defaultdict
|
||||
import jieba
|
||||
import jieba.analyse
|
||||
from datetime import datetime
|
||||
import re
|
||||
|
||||
if not chat_history:
|
||||
return self._get_default_analysis()
|
||||
|
||||
# 1. 基础统计
|
||||
total_messages = len(chat_history)
|
||||
sent_messages = sum(1 for msg in chat_history if msg['is_sender'])
|
||||
received_messages = total_messages - sent_messages
|
||||
|
||||
# 2. 时间分析
|
||||
time_distribution = defaultdict(int)
|
||||
time_gaps = []
|
||||
last_time = None
|
||||
|
||||
# 3. 文本处理准备
|
||||
all_text = []
|
||||
life_events = []
|
||||
emotional_words = []
|
||||
|
||||
# 4. 关键词和话题识别的正则模式
|
||||
life_event_patterns = [
|
||||
r'考试|毕业|工作|加班|项目|旅行|旅游|生日|结婚|搬家|升职|考研',
|
||||
r'开心|难过|焦虑|压力|困难|成功|失败|努力|坚持|梦想|目标',
|
||||
r'家人|朋友|同事|领导|团队|公司|学校|家庭'
|
||||
]
|
||||
|
||||
emotional_patterns = [
|
||||
r'开心|快乐|高兴|激动|兴奋|满意|感动|温暖|感激|感谢',
|
||||
r'难过|伤心|焦虑|烦恼|痛苦|压力|疲惫|失望|生气|担心',
|
||||
r'加油|支持|鼓励|期待|希望|梦想|努力|坚持|相信|祝福'
|
||||
]
|
||||
|
||||
for msg in chat_history:
|
||||
text = msg['message']
|
||||
create_time = datetime.strptime(msg['create_time'], '%Y-%m-%d %H:%M:%S')
|
||||
|
||||
# 更新时间分布
|
||||
hour = create_time.hour
|
||||
time_distribution[hour] += 1
|
||||
|
||||
# 计算消息时间间隔
|
||||
if last_time:
|
||||
gap = (create_time - last_time).total_seconds() / 3600 # 转换为小时
|
||||
time_gaps.append(gap)
|
||||
last_time = create_time
|
||||
|
||||
# 文本分析
|
||||
all_text.append(text)
|
||||
|
||||
# 识别生活事件
|
||||
for pattern in life_event_patterns:
|
||||
matches = re.findall(pattern, text)
|
||||
if matches:
|
||||
life_events.extend(matches)
|
||||
|
||||
# 识别情感词
|
||||
for pattern in emotional_patterns:
|
||||
matches = re.findall(pattern, text)
|
||||
if matches:
|
||||
emotional_words.extend(matches)
|
||||
|
||||
# 5. 分析聊天频率
|
||||
if time_gaps:
|
||||
avg_gap = sum(time_gaps) / len(time_gaps)
|
||||
if avg_gap < 24:
|
||||
chat_frequency = "频繁"
|
||||
elif avg_gap < 72:
|
||||
chat_frequency = "较多"
|
||||
else:
|
||||
chat_frequency = "一般"
|
||||
else:
|
||||
chat_frequency = "较少"
|
||||
|
||||
# 6. 分析关系亲密度
|
||||
intimacy_score = 0
|
||||
intimacy_score += min(total_messages / 1000, 5) # 消息数量得分,最高5分
|
||||
intimacy_score += len(set(emotional_words)) / 2 # 情感词丰富度得分
|
||||
intimacy_score += min(24 / (avg_gap if time_gaps else 168), 3) # 时间间隔得分,最高3分
|
||||
|
||||
if intimacy_score > 7:
|
||||
relationship_level = "密切"
|
||||
elif intimacy_score > 4:
|
||||
relationship_level = "友好"
|
||||
else:
|
||||
relationship_level = "一般"
|
||||
|
||||
# 7. 提取关键话题
|
||||
combined_text = ' '.join(all_text)
|
||||
top_keywords = jieba.analyse.extract_tags(
|
||||
combined_text,
|
||||
topK=10,
|
||||
withWeight=True,
|
||||
allowPOS=('n', 'v', 'a') # 名词、动词、形容词
|
||||
)
|
||||
|
||||
# 8. 分析互动方式
|
||||
response_rate = received_messages / sent_messages if sent_messages > 0 else 0
|
||||
avg_msg_length = sum(len(msg['message']) for msg in chat_history) / total_messages
|
||||
|
||||
if response_rate > 0.8 and avg_msg_length > 10:
|
||||
interaction_style = "深入交流"
|
||||
elif response_rate > 0.5:
|
||||
interaction_style = "积极互动"
|
||||
else:
|
||||
interaction_style = "一般交流"
|
||||
|
||||
# 9. 整理分析结果
|
||||
return {
|
||||
"chat_frequency": chat_frequency,
|
||||
"relationship_level": relationship_level,
|
||||
"total_messages": total_messages,
|
||||
"sent_messages": sent_messages,
|
||||
"received_messages": received_messages,
|
||||
"common_topics": [word for word, weight in top_keywords[:5]],
|
||||
"emotional_keywords": list(set(emotional_words))[:5],
|
||||
"key_life_events": list(set(life_events))[:5],
|
||||
"interaction_style": interaction_style,
|
||||
"chat_time_distribution": dict(sorted(time_distribution.items())),
|
||||
"intimacy_score": round(intimacy_score, 2)
|
||||
}
|
||||
|
||||
def _get_default_analysis(self) -> Dict:
|
||||
"""返回默认的分析结果"""
|
||||
return {
|
||||
"chat_frequency": "较少",
|
||||
"relationship_level": "一般",
|
||||
"total_messages": 0,
|
||||
"sent_messages": 0,
|
||||
"received_messages": 0,
|
||||
"common_topics": ["工作", "生活"],
|
||||
"emotional_keywords": [],
|
||||
"key_life_events": [],
|
||||
"interaction_style": "一般交流",
|
||||
"chat_time_distribution": {},
|
||||
"intimacy_score": 0
|
||||
}
|
||||
|
||||
def _build_prompt(self, contact_info: Dict, chat_analysis: Dict, style_prompt: str) -> str:
|
||||
"""构建完整的提示词
|
||||
|
||||
Args:
|
||||
contact_info: 联系人信息
|
||||
chat_analysis: 聊天记录分析结果
|
||||
style_prompt: 风格提示词
|
||||
|
||||
Returns:
|
||||
str: 完整的提示词
|
||||
"""
|
||||
# 将字典转换为更安全的字符串表示
|
||||
contact_str = f"姓名:{contact_info.get('name', '')}"
|
||||
|
||||
# 构建详细的聊天分析信息
|
||||
common_topics = '、'.join(chat_analysis.get('common_topics', ['未知']))
|
||||
emotional_keywords = '、'.join(chat_analysis.get('emotional_keywords', []))
|
||||
key_life_events = '、'.join(chat_analysis.get('key_life_events', []))
|
||||
|
||||
# 获取主要聊天时间段
|
||||
time_dist = chat_analysis.get('chat_time_distribution', {})
|
||||
active_hours = []
|
||||
if time_dist:
|
||||
# 找出消息数量最多的3个时间段
|
||||
sorted_hours = sorted(time_dist.items(), key=lambda x: x[1], reverse=True)[:3]
|
||||
active_hours = [f"{hour}点" for hour, _ in sorted_hours]
|
||||
|
||||
analysis_str = (
|
||||
f"1) 基础关系:\n"
|
||||
f" - 聊天频率:{chat_analysis.get('chat_frequency', '一般')}\n"
|
||||
f" - 关系亲密度:{chat_analysis.get('relationship_level', '一般')}\n"
|
||||
f" - 互动方式:{chat_analysis.get('interaction_style', '正式')}\n"
|
||||
f" - 总消息数:{chat_analysis.get('total_messages', 0)}\n"
|
||||
f" - 亲密度评分:{chat_analysis.get('intimacy_score', 0)}\n\n"
|
||||
f"2) 深度分析:\n"
|
||||
f" - 共同话题:{common_topics}\n"
|
||||
f" - 情感关键词:{emotional_keywords}\n"
|
||||
f" - 重要生活事件:{key_life_events}\n"
|
||||
f" - 主要互动时间:{', '.join(active_hours) if active_hours else '未知'}"
|
||||
)
|
||||
|
||||
prompt = f"""请根据以下详细信息,生成一份2025年蛇年新年祝福:
|
||||
|
||||
【联系人信息】
|
||||
{contact_str}
|
||||
|
||||
【聊天记录分析】
|
||||
{analysis_str}
|
||||
|
||||
【风格要求】
|
||||
{style_prompt}
|
||||
|
||||
请生成以下内容,并以JSON格式返回:
|
||||
1. greeting: 新年祝福寄语(50字左右)
|
||||
- 包含2-3个具体互动数据(如消息数、默契值等)
|
||||
- 描述3个日常相处场景,用动词短语呈现
|
||||
- 用'从...到...'结构展现2组情感变化
|
||||
- **给出富有特色的关系定位(如'职场损友')**
|
||||
- 以温暖期许作结
|
||||
- 语气活泼自然,突出陪伴与成长
|
||||
- 总字数控制在50字左右
|
||||
|
||||
2. idioms: 新年祝福诗(两句,用英文逗号分隔)
|
||||
- 每句7个汉字
|
||||
- 第一句描写一个美好愿景或意象
|
||||
- 第二句表达祝福或期许
|
||||
- 整体要押韵,符合"意、形、神"统一
|
||||
- 要融入分析出的情感关键词或生活事件
|
||||
|
||||
3. tags: 新年祝福成语(3个,用英文逗号分隔)
|
||||
- 要选用喜庆祥和的成语
|
||||
- 要与对方的生活状态和期望相呼应
|
||||
- 成语之间要形成递进关系
|
||||
|
||||
4. wishes: 新岁寄语(30字左右)
|
||||
- 要结合对方的生活事件和关注点
|
||||
- 表达真挚美好的期望
|
||||
- **以诗意笔触勾勒新年祝愿,融入对方生活际遇与心之所系,以婉约含蓄的文字传递真挚祝福,让文字如清泉般流淌,在对方心间激起涟漪**
|
||||
|
||||
要求:
|
||||
1. 内容要体现高度个性化,充分利用聊天分析结果
|
||||
2. 要严格遵循指定的风格要求
|
||||
3. 整体风格要保持一致性
|
||||
4. 要让对方感受到你对他/她的了解和关心
|
||||
5. 要体现出诚意和温度
|
||||
|
||||
返回格式示例:
|
||||
{{
|
||||
"greeting": "新年祝福寄语...",
|
||||
"idioms": "梦想飞扬似朝阳,岁岁安康伴春寒",
|
||||
"tags": "前程似锦,蒸蒸日上,前程万里",
|
||||
"wishes": "美好祝愿..."
|
||||
}}"""
|
||||
|
||||
# 保存prompt到本地文件
|
||||
try:
|
||||
# 确保目录存在
|
||||
os.makedirs('newYear/prompts', exist_ok=True)
|
||||
|
||||
# 生成文件名(使用时间戳和联系人ID)
|
||||
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
||||
filename = f"prompt_{timestamp}_{contact_info.get('wxid', 'unknown')}.txt"
|
||||
filepath = os.path.join('newYear/prompts', filename)
|
||||
|
||||
# 保存文件
|
||||
with open(filepath, 'w', encoding='utf-8') as f:
|
||||
f.write(f"=== 生成时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ===\n\n")
|
||||
f.write(prompt)
|
||||
|
||||
print(f"\nPrompt已保存至: {filepath}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"\nPrompt保存失败: {str(e)}")
|
||||
|
||||
return prompt
|
||||
|
||||
def _parse_response(self, response) -> Dict:
|
||||
"""解析API响应内容
|
||||
|
||||
Args:
|
||||
response: API响应内容
|
||||
|
||||
Returns:
|
||||
Dict: 解析后的祝福内容
|
||||
"""
|
||||
try:
|
||||
print("\n解析响应...")
|
||||
content = response.choices[0].message.content
|
||||
print("\n生成的原始内容:", content)
|
||||
|
||||
# 尝试解析JSON内容
|
||||
try:
|
||||
result = json.loads(content)
|
||||
except json.JSONDecodeError:
|
||||
# 如果解析失败,尝试提取内容中的JSON部分
|
||||
import re
|
||||
json_match = re.search(r'\{[\s\S]*\}', content)
|
||||
if json_match:
|
||||
result = json.loads(json_match.group())
|
||||
else:
|
||||
raise Exception("无法从响应中提取JSON内容")
|
||||
|
||||
# 验证必要的字段
|
||||
required_fields = ['greeting', 'wishes', 'idioms', 'tags']
|
||||
missing_fields = [field for field in required_fields if field not in result]
|
||||
if missing_fields:
|
||||
raise KeyError(f"生成的内容缺少必要字段: {', '.join(missing_fields)}")
|
||||
|
||||
|
||||
return {
|
||||
'greeting': result['greeting'],
|
||||
'wishes': result['wishes'],
|
||||
'idioms': result['idioms'],
|
||||
'tags': result['tags']
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"响应内容解析失败:{str(e)}")
|
||||
|
||||
def test_generate_greeting(self) -> Tuple[bool, str, Dict]:
|
||||
"""测试生成新年祝福内容
|
||||
|
||||
Returns:
|
||||
Tuple[bool, str, Dict]: (是否成功, 错误信息, 生成的内容)
|
||||
"""
|
||||
try:
|
||||
# 模拟联系人信息
|
||||
contact_info = {
|
||||
"wxid": "test_wxid_001",
|
||||
"name": "张三",
|
||||
"relationship": "好友"
|
||||
}
|
||||
|
||||
# 模拟聊天记录
|
||||
chat_history = [
|
||||
{
|
||||
"message": "今天工作怎么样?",
|
||||
"is_sender": True,
|
||||
"create_time": "2023-12-01 10:00:00"
|
||||
},
|
||||
{
|
||||
"message": "还不错,项目进展顺利",
|
||||
"is_sender": False,
|
||||
"create_time": "2023-12-01 10:05:00"
|
||||
},
|
||||
{
|
||||
"message": "周末要不要一起打球?",
|
||||
"is_sender": True,
|
||||
"create_time": "2023-12-01 10:10:00"
|
||||
}
|
||||
]
|
||||
|
||||
print("\n测试单个风格生成...")
|
||||
# 只测试一个风格,简化测试
|
||||
style_prompt = "温暖、亲切、感人的新年祝福,表达真挚的关心和美好祝愿"
|
||||
|
||||
try:
|
||||
result = self.generate_greeting(
|
||||
contact_info,
|
||||
chat_history,
|
||||
style_prompt
|
||||
)
|
||||
print("\n生成结果:")
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
return True, "测试完成", {"warm": result}
|
||||
except Exception as e:
|
||||
return False, f"生成失败: {str(e)}", {}
|
||||
|
||||
except Exception as e:
|
||||
return False, f"测试失败:{str(e)}", {}
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 测试代码
|
||||
import os
|
||||
|
||||
# 从环境变量获取API key
|
||||
api_key = os.getenv("VOLCANO_API_KEY", "")
|
||||
if not api_key:
|
||||
print("请先设置环境变量 VOLCANO_API_KEY")
|
||||
exit(1)
|
||||
|
||||
# 创建API实例
|
||||
api = VolcanoAPI(api_key)
|
||||
|
||||
# 测试API连接
|
||||
# print("\n=== 测试API连接 ===")
|
||||
# success, message = api.test_connection()
|
||||
# print(f"API测试结果: {'成功' if success else '失败'}")
|
||||
# print(f"详细信息: {message}")
|
||||
|
||||
# if success:
|
||||
# 测试生成祝福内容
|
||||
print("\n=== 测试生成祝福内容 ===")
|
||||
success, message, results = api.test_generate_greeting()
|
||||
print(f"\n生成测试结果: {'成功' if success else '失败'}")
|
||||
print(f"详细信息: {message}")
|
||||
|
||||
if success:
|
||||
print("\n=== 生成的内容示例 ===")
|
||||
# 选择一个风格的结果作为示例显示
|
||||
example = results.get("warm", {})
|
||||
if example:
|
||||
print("\n新年祝福语:")
|
||||
print(example.get("greeting", ""))
|
||||
print("\n美好祝愿:")
|
||||
print(example.get("wishes", ""))
|
||||
print("\n祝福成语:")
|
||||
print(example.get("idioms", ""))
|
||||
@@ -0,0 +1,62 @@
|
||||
from wxauto import *
|
||||
import time
|
||||
|
||||
def send_wx_msg(friend_name, message):
|
||||
try:
|
||||
# 获取当前微信客户端
|
||||
wx = WeChat()
|
||||
|
||||
# 先切换到对应的聊天窗口
|
||||
if not wx.ChatWith(friend_name):
|
||||
print(f"切换到聊天窗口失败: {friend_name}")
|
||||
return False
|
||||
|
||||
# 发送消息
|
||||
wx.SendMsg(message, who=friend_name)
|
||||
print(f"消息已成功发送给 {friend_name}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"发送失败:{str(e)}")
|
||||
return False
|
||||
|
||||
def send_message_and_image(name: str, image_path: str) -> bool:
|
||||
"""发送消息和图片到指定微信联系人
|
||||
|
||||
Args:
|
||||
name: 联系人的微信名称
|
||||
image_path: 图片文件的路径
|
||||
|
||||
Returns:
|
||||
bool: 是否发送成功
|
||||
"""
|
||||
try:
|
||||
# 获取微信实例
|
||||
wx = WeChat()
|
||||
|
||||
# 先切换到对应的聊天窗口
|
||||
if not wx.ChatWith(name):
|
||||
print(f"切换到聊天窗口失败: {name}")
|
||||
return False
|
||||
|
||||
# 发送图片
|
||||
if not wx.SendFiles(image_path):
|
||||
print(f"发送图片失败: {image_path}")
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"发送消息失败: {str(e)}")
|
||||
return False
|
||||
|
||||
# 使用示例
|
||||
if __name__ == "__main__":
|
||||
# 要发送消息的好友名称
|
||||
friend_name = "''" # 替换为实际好友名称
|
||||
|
||||
# 要发送的消息内容
|
||||
message = "你好,这是一条测试消息!"
|
||||
|
||||
# 发送消息
|
||||
send_wx_msg(friend_name, message)
|
||||
Reference in new issue
Block a user