重构代码
This commit is contained in:
1 parent
86de31f274
commit
f69b9e16e4
22 files changed
+371
-536
No files matched your search
@@ -0,0 +1,8 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: __init__.py.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2023/09/27
|
||||
# -------------------------------------------------------------------------------
|
||||
from .parse import read_img_dat, read_emoji, decompress_CompressContent, read_audio_buf, read_audio, parse_xml_string
|
||||
@@ -0,0 +1,370 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: analyser.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2023/12/01
|
||||
# -------------------------------------------------------------------------------
|
||||
import sqlite3
|
||||
import time
|
||||
from collections import Counter
|
||||
import pandas as pd
|
||||
|
||||
from pywxdump.analyse import parse_xml_string
|
||||
|
||||
|
||||
def read_msgs(MSG_path, selected_talker=None, start_time=time.time() * 3600 * 24 * 365, end_time=time.time()):
|
||||
"""
|
||||
读取消息内容-MSG.db 包含IsSender,StrContent,StrTalker,ype,SubType,CreateTime,MsgSvrID
|
||||
:param MSG_path: MSG.db 路径
|
||||
:param selected_talker: 选中的聊天对象
|
||||
:param start_time: 开始时间 时间戳10位
|
||||
:param end_time: 结束时间 时间戳10位
|
||||
:return:
|
||||
"""
|
||||
type_name_dict = {
|
||||
1: {0: "文本"},
|
||||
3: {0: "图片"},
|
||||
34: {0: "语音"},
|
||||
43: {0: "视频"},
|
||||
47: {0: "动画表情"},
|
||||
49: {0: "文本", 1: "类文本消息", 5: "卡片式链接", 6: "文件", 8: "上传的GIF表情",
|
||||
19: "合并转发聊天记录", 33: "分享的小程序", 36: "分享的小程序", 57: "带有引用的文本",
|
||||
63: "视频号直播或回放等",
|
||||
87: "群公告", 88: "视频号直播或回放等", 2000: "转账消息", 2003: "红包封面"},
|
||||
50: {0: "语音通话"},
|
||||
10000: {0: "系统通知", 4: "拍一拍", 8000: "系统通知"}
|
||||
}
|
||||
|
||||
# 连接 MSG_ALL.db 数据库,并执行查询
|
||||
db1 = sqlite3.connect(MSG_path)
|
||||
cursor1 = db1.cursor()
|
||||
|
||||
if isinstance(start_time, str):
|
||||
start_time = time.mktime(time.strptime(start_time, "%Y-%m-%d %H:%M:%S"))
|
||||
if isinstance(end_time, str):
|
||||
end_time = time.mktime(time.strptime(end_time, "%Y-%m-%d %H:%M:%S"))
|
||||
|
||||
if selected_talker is None or selected_talker == "": # 如果 selected_talker 为 None,则查询全部对话
|
||||
cursor1.execute(
|
||||
"SELECT MsgSvrID,IsSender, StrContent, StrTalker, Type, SubType,CreateTime FROM MSG WHERE CreateTime>=? AND CreateTime<=? ORDER BY CreateTime ASC",
|
||||
(start_time, end_time))
|
||||
else:
|
||||
cursor1.execute(
|
||||
"SELECT MsgSvrID,IsSender, StrContent, StrTalker, Type, SubType,CreateTime FROM MSG WHERE StrTalker=? AND CreateTime>=? AND CreateTime<=? ORDER BY CreateTime ASC",
|
||||
(selected_talker, start_time, end_time))
|
||||
result1 = cursor1.fetchall()
|
||||
cursor1.close()
|
||||
db1.close()
|
||||
|
||||
def get_emoji_cdnurl(row):
|
||||
if row["type_name"] == "动画表情":
|
||||
parsed_content = parse_xml_string(row["StrContent"])
|
||||
if isinstance(parsed_content, dict) and "emoji" in parsed_content:
|
||||
return parsed_content["emoji"].get("cdnurl", "")
|
||||
return row["content"]
|
||||
|
||||
init_data = pd.DataFrame(result1, columns=["MsgSvrID", "IsSender", "StrContent", "StrTalker", "Type", "SubType",
|
||||
"CreateTime"])
|
||||
init_data["CreateTime"] = pd.to_datetime(init_data["CreateTime"], unit="s")
|
||||
init_data["AdjustedTime"] = init_data["CreateTime"] - pd.Timedelta(hours=4)
|
||||
init_data["AdjustedTime"] = init_data["AdjustedTime"].dt.strftime("%Y-%m-%d %H:%M:%S")
|
||||
init_data["CreateTime"] = init_data["CreateTime"].dt.strftime("%Y-%m-%d %H:%M:%S")
|
||||
init_data["type_name"] = init_data.apply(lambda x: type_name_dict.get(x["Type"], {}).get(x["SubType"], "未知"),
|
||||
axis=1)
|
||||
init_data["content"] = init_data.apply(lambda x: x["StrContent"] if x["type_name"] == "文本" else "", axis=1)
|
||||
init_data["content"] = init_data.apply(get_emoji_cdnurl, axis=1)
|
||||
|
||||
init_data["content_len"] = init_data.apply(lambda x: len(x["content"]) if x["type_name"] == "文本" else 0, axis=1)
|
||||
|
||||
chat_data = init_data[
|
||||
["MsgSvrID", "IsSender", "StrTalker", "type_name", "content", "content_len", "CreateTime", "AdjustedTime"]]
|
||||
|
||||
return True, chat_data
|
||||
|
||||
|
||||
# 绘制直方图
|
||||
def draw_hist_all_count(chat_data, out_path="", is_show=False):
|
||||
try:
|
||||
import matplotlib.pyplot as plt
|
||||
except ImportError as e:
|
||||
print("error", e)
|
||||
raise ImportError("请安装matplotlib库")
|
||||
plt.rcParams['font.sans-serif'] = ['SimHei']
|
||||
plt.rcParams['axes.unicode_minus'] = False
|
||||
|
||||
type_count = Counter(chat_data["type_name"])
|
||||
|
||||
# 对type_count按值进行排序,并返回排序后的结果
|
||||
sorted_type_count = dict(sorted(type_count.items(), key=lambda item: item[1], reverse=True))
|
||||
|
||||
plt.figure(figsize=(12, 8))
|
||||
plt.bar(range(len(sorted_type_count)), list(sorted_type_count.values()), tick_label=list(sorted_type_count.keys()))
|
||||
plt.title("消息类型分布图")
|
||||
plt.xlabel("消息类型")
|
||||
plt.ylabel("数量")
|
||||
|
||||
# 设置x轴标签的旋转角度为45度
|
||||
plt.xticks(rotation=-45)
|
||||
|
||||
# 在每个柱上添加数字标签
|
||||
for i, v in enumerate(list(sorted_type_count.values())):
|
||||
plt.text(i, v, str(v), ha='center', va='bottom')
|
||||
|
||||
if out_path != "":
|
||||
plt.savefig(out_path)
|
||||
if is_show:
|
||||
plt.show()
|
||||
plt.close()
|
||||
|
||||
|
||||
# 按照interval绘制折线图
|
||||
def draw_line_type_name(chat_data, interval="W", type_name_list=None, out_path="", is_show=False):
|
||||
"""
|
||||
绘制折线图,横轴为时间,纵轴为消息数量,不同类型的消息用不同的颜色表示
|
||||
:param chat_data:
|
||||
:param interval:
|
||||
:param type_name_list: 消息类型列表,按照列表中的顺序绘制折线图 可选:全部类型、发送、接收、总字数、发送字数、接收字数、其他类型
|
||||
:param out_path:
|
||||
:param is_show:
|
||||
:return:
|
||||
"""
|
||||
if type_name_list is None:
|
||||
type_name_list = ["全部类型", "发送", "接收"] + ["总字数", "发送字数", "接收字数"]
|
||||
# type_name_list = ["总字数", "发送字数", "接收字数"]
|
||||
|
||||
try:
|
||||
import matplotlib.pyplot as plt
|
||||
import pandas as pd
|
||||
except ImportError as e:
|
||||
print("error", e)
|
||||
raise ImportError("请安装matplotlib库")
|
||||
plt.rcParams['font.sans-serif'] = ['SimHei']
|
||||
plt.rcParams['axes.unicode_minus'] = False
|
||||
|
||||
chat_data["CreateTime"] = pd.to_datetime(chat_data["CreateTime"])
|
||||
chat_data["AdjustedTime"] = pd.to_datetime(chat_data["AdjustedTime"])
|
||||
|
||||
# interval = interval.lower()
|
||||
interval_dict = {"day": "%Y-%m-%d", "month": "%Y-%m", "year": "%Y", "week": "%Y-%W",
|
||||
"d": "%Y-%m-%d", "m": "%Y-%m", "y": "%Y", "W": "%Y-%W"
|
||||
}
|
||||
if interval not in interval_dict:
|
||||
raise ValueError("interval参数错误,可选值为day、month、year、week")
|
||||
chat_data["interval"] = chat_data["AdjustedTime"].dt.strftime(interval_dict[interval])
|
||||
|
||||
# 根据chat_data["interval"]最大值和最小值,生成一个时间间隔列表
|
||||
interval_list = pd.date_range(chat_data["AdjustedTime"].min(), chat_data["AdjustedTime"].max(), freq=interval)
|
||||
interval_list = interval_list.append(pd.Index([interval_list[-1] + pd.Timedelta(days=1)])) # 最后一天加一天
|
||||
|
||||
# 构建数据集
|
||||
# interval type_name1 type_name2 type_name3
|
||||
# 2021-01 文本数量 其他类型数量 其他类型数量
|
||||
# 2021-02 文本数量 其他类型数量 其他类型数量
|
||||
type_data = pd.DataFrame(columns=["interval"] + list(chat_data["type_name"].unique()))
|
||||
type_data["interval"] = interval_list.strftime(interval_dict[interval])
|
||||
type_data = type_data.set_index("interval")
|
||||
for type_name in chat_data["type_name"].unique():
|
||||
type_data[type_name] = chat_data[chat_data["type_name"] == type_name].groupby("interval").size()
|
||||
type_data["全部类型"] = type_data.sum(axis=1)
|
||||
type_data["发送"] = chat_data[chat_data["IsSender"] == 1].groupby("interval").size()
|
||||
type_data["接收"] = chat_data[chat_data["IsSender"] == 0].groupby("interval").size()
|
||||
|
||||
type_data["总字数"] = chat_data.groupby("interval")["content_len"].sum()
|
||||
type_data["发送字数"] = chat_data[chat_data["IsSender"] == 1].groupby("interval")["content_len"].sum()
|
||||
type_data["接收字数"] = chat_data[chat_data["IsSender"] == 0].groupby("interval")["content_len"].sum()
|
||||
|
||||
type_data = type_data.fillna(0)
|
||||
# 调整typename顺序,使其按照总数量排序,只要最大的5个
|
||||
type_data = type_data.reindex(type_data.sum().sort_values(ascending=False).index, axis=1)
|
||||
if type_name_list is not None:
|
||||
type_data = type_data[type_name_list]
|
||||
else:
|
||||
type_data = type_data.iloc[:, :5]
|
||||
|
||||
# if interval == "W" or interval == "week": # 改为当前周的周一的日期
|
||||
# #
|
||||
|
||||
plt.figure(figsize=(12, 8))
|
||||
|
||||
# 绘制折线图
|
||||
for type_name in type_data.columns:
|
||||
plt.plot(type_data.index, type_data[type_name], label=type_name)
|
||||
|
||||
# 设置x轴标签的旋转角度为45度
|
||||
plt.xticks(rotation=-45)
|
||||
# 设置标题、坐标轴标签、图例等信息
|
||||
plt.title("消息类型分布图")
|
||||
plt.xlabel("时间")
|
||||
plt.ylabel("数量")
|
||||
|
||||
plt.legend(loc="upper right") # 设置图例位置
|
||||
|
||||
# 显示图形
|
||||
if out_path != "":
|
||||
plt.savefig(out_path)
|
||||
if is_show:
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
plt.close()
|
||||
|
||||
|
||||
|
||||
def wordcloud_generator(chat_data, interval="m", stopwords=None, out_path="", is_show=False, bg_img=None,
|
||||
font="C:\Windows\Fonts\simhei.ttf"):
|
||||
"""
|
||||
词云
|
||||
:param is_show: 是否显示
|
||||
:param img_path: 背景图片路径
|
||||
:param text: 文本
|
||||
:param font: 字体路径
|
||||
:return:
|
||||
"""
|
||||
try:
|
||||
from wordcloud import WordCloud, ImageColorGenerator
|
||||
import wordcloud
|
||||
import jieba
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.font_manager import fontManager
|
||||
import pandas as pd
|
||||
import codecs
|
||||
import re
|
||||
from imageio import imread
|
||||
except ImportError as e:
|
||||
print("error", e)
|
||||
raise ImportError("请安装wordcloud,jieba,numpy,matplotlib,pillow库")
|
||||
|
||||
plt.rcParams['font.sans-serif'] = ['SimHei']
|
||||
plt.rcParams['axes.unicode_minus'] = False
|
||||
|
||||
chat_data["CreateTime"] = pd.to_datetime(chat_data["CreateTime"])
|
||||
chat_data["AdjustedTime"] = pd.to_datetime(chat_data["AdjustedTime"])
|
||||
|
||||
# interval = interval.lower()
|
||||
interval_dict = {"day": "%Y-%m-%d", "month": "%Y-%m", "year": "%Y", "week": "%Y-%W",
|
||||
"d": "%Y-%m-%d", "m": "%Y-%m", "y": "%Y", "W": "%Y-%W"
|
||||
}
|
||||
if interval not in interval_dict:
|
||||
raise ValueError("interval参数错误,可选值为day、month、year、week")
|
||||
chat_data["interval"] = chat_data["AdjustedTime"].dt.strftime(interval_dict[interval])
|
||||
|
||||
# 根据chat_data["interval"]最大值和最小值,生成一个时间间隔列表
|
||||
interval_list = pd.date_range(chat_data["AdjustedTime"].min(), chat_data["AdjustedTime"].max(), freq=interval)
|
||||
interval_list = interval_list.append(pd.Index([interval_list[-1] + pd.Timedelta(days=1)])) # 最后一天加一天
|
||||
|
||||
# 构建数据集
|
||||
# interval text_all text_sender text_receiver
|
||||
# 2021-01 文本\n合并 聊天记录\n文本\n合并 聊天记录\n文本\n合并 聊天记录\n
|
||||
def merage_text(x):
|
||||
pattern = re.compile("(\[.+?\])") # 匹配表情
|
||||
rt = "\n".join(x)
|
||||
rt = pattern.sub('', rt).replace("\n", " ")
|
||||
return rt
|
||||
|
||||
chat_data["content"] = chat_data.apply(lambda x: x["content"] if x["type_name"] == "文本" else "", axis=1)
|
||||
|
||||
text_data = pd.DataFrame(columns=["interval", "text_all", "text_sender", "text_receiver"])
|
||||
text_data["interval"] = interval_list.strftime(interval_dict[interval])
|
||||
text_data = text_data.set_index("interval")
|
||||
# 使用“\n”合并
|
||||
text_data["text_all"] = chat_data.groupby("interval")["content"].apply(merage_text)
|
||||
text_data["text_sender"] = chat_data[chat_data["IsSender"] == 1].groupby("interval")["content"].apply(merage_text)
|
||||
text_data["text_receiver"] = chat_data[chat_data["IsSender"] == 0].groupby("interval")["content"].apply(merage_text)
|
||||
|
||||
def gen_img(texts,out_path,is_show,bg_img,title=""):
|
||||
words = jieba.lcut(texts)
|
||||
res = [word for word in words if word not in stopwords and word.replace(" ", "") != "" and len(word) > 1]
|
||||
count_dict = dict(Counter(res))
|
||||
|
||||
if bg_img:
|
||||
bgimg = imread(open(bg_img, 'rb'))
|
||||
# 获得词云对象,设定词云背景颜色及其图片和字体
|
||||
wc = WordCloud(background_color='white', mask=bgimg, font_path='simhei.ttf', mode='RGBA', include_numbers=False,
|
||||
random_state=0)
|
||||
else:
|
||||
# 如果你的背景色是透明的,请用这两条语句替换上面两条
|
||||
bgimg = None
|
||||
wc = WordCloud(background_color='white', mode='RGBA', font_path='simhei.ttf', include_numbers=False,
|
||||
random_state=0,width=500, height=500) # 如果不指定中文字体路径,词云会乱码
|
||||
wc = wc.fit_words(count_dict)
|
||||
|
||||
fig = plt.figure(figsize=(8, 8))
|
||||
fig.suptitle(title, fontsize=26)
|
||||
ax = fig.subplots()
|
||||
|
||||
ax.imshow(wc)
|
||||
ax.axis('off')
|
||||
|
||||
if out_path != "":
|
||||
plt.savefig(out_path)
|
||||
if is_show:
|
||||
plt.show()
|
||||
plt.close()
|
||||
|
||||
for i in text_data.index:
|
||||
out_path = f"out/img_{i}.png"
|
||||
gen_img(text_data["text_all"][i], out_path=out_path, is_show=False, bg_img=bg_img, title=f"全部({i})")
|
||||
# gen_img(text_data["text_sender"][i], out_path="", is_show=is_show, bg_img=bg_img, title=f"发送_{i}")
|
||||
# gen_img(text_data["text_receiver"][i], out_path="", is_show=is_show, bg_img=bg_img, title=f"接收_{i}")
|
||||
# time.sleep(1)
|
||||
|
||||
# 情感分析
|
||||
def sentiment_analysis(chat_data, stopwords="", out_path="", is_show=False, bg_img=None):
|
||||
try:
|
||||
from snownlp import SnowNLP
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
import seaborn as sns
|
||||
|
||||
except ImportError as e:
|
||||
print("error", e)
|
||||
raise ImportError("请安装snownlp,pandas,matplotlib,seaborn库")
|
||||
|
||||
sns.set_style('white', {'font.sans-serif': ['simhei', 'FangSong']})
|
||||
|
||||
chats = []
|
||||
for row in chat_data:
|
||||
if row["type_name"] != "文本" or row["content"] == "":
|
||||
continue
|
||||
chats.append(row)
|
||||
|
||||
scores = []
|
||||
for row in chats:
|
||||
s = SnowNLP(row["content"])
|
||||
scores.append(s.sentiments)
|
||||
|
||||
def draw(data):
|
||||
df = pd.DataFrame({'Sentiment Score': data})
|
||||
plt.figure(figsize=(8, 6))
|
||||
sns.histplot(data=df, x='Sentiment Score', kde=True)
|
||||
plt.title("Sentiment Analysis")
|
||||
plt.xlabel("Sentiment Score")
|
||||
plt.ylabel("Frequency")
|
||||
|
||||
if out_path != "":
|
||||
plt.savefig(out_path)
|
||||
if is_show:
|
||||
plt.show()
|
||||
plt.close()
|
||||
|
||||
draw(scores)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
MSG_PATH = r""
|
||||
selected_talker = "wxid_"
|
||||
start_time = time.time() - 3600 * 24 * 50000
|
||||
end_time = time.time()
|
||||
code, chat_data = read_msgs(MSG_PATH, selected_talker, start_time, end_time)
|
||||
# print(chat_data)
|
||||
# code, data, classify_count, all_type_count = merge_chat_data(chat_data, interval="month")
|
||||
# draw_hist_all_count(chat_data, is_show=True) # 绘制直方图 消息类型分布图
|
||||
# draw_line_type_name(chat_data, is_show=True) # 绘制折线图 消息类型分布图
|
||||
|
||||
# bg_img = 'img.png'
|
||||
stopwords = ['的', '了', '是', '在', '我', '有', '和', '就', '不', '人', '都', '一', '一个', '上', '也', '很', '到',
|
||||
'说', '要',
|
||||
'去', '你', '会', '着', '没有', '看', '好', '自己', '这']
|
||||
wordcloud_generator(chat_data, stopwords=stopwords, out_path="", is_show=True)
|
||||
# sentiment_analysis(chat_data)
|
||||
@@ -0,0 +1,301 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: parse.py
|
||||
# Description: 解析数据库内容
|
||||
# Author: xaoyaoo
|
||||
# Date: 2023/09/27
|
||||
# -------------------------------------------------------------------------------
|
||||
import os.path
|
||||
import sqlite3
|
||||
import pysilk
|
||||
from io import BytesIO
|
||||
import wave
|
||||
import pyaudio
|
||||
import requests
|
||||
import hashlib
|
||||
|
||||
from PIL import Image
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
||||
def get_md5(data):
|
||||
md5 = hashlib.md5()
|
||||
md5.update(data)
|
||||
return md5.hexdigest()
|
||||
|
||||
|
||||
def parse_xml_string(xml_string):
|
||||
"""
|
||||
解析 XML 字符串
|
||||
:param xml_string: 要解析的 XML 字符串
|
||||
:return: 解析结果,以字典形式返回
|
||||
"""
|
||||
|
||||
def parse_xml(element):
|
||||
"""
|
||||
递归解析 XML 元素
|
||||
:param element: 要解析的 XML 元素
|
||||
:return: 解析结果,以字典形式返回
|
||||
"""
|
||||
result = {}
|
||||
|
||||
# 解析当前元素的属性
|
||||
for key, value in element.attrib.items():
|
||||
result[key] = value
|
||||
|
||||
# 解析当前元素的子元素
|
||||
for child in element:
|
||||
child_result = parse_xml(child)
|
||||
|
||||
# 如果子元素的标签已经在结果中存在,则将其转换为列表
|
||||
if child.tag in result:
|
||||
if not isinstance(result[child.tag], list):
|
||||
result[child.tag] = [result[child.tag]]
|
||||
result[child.tag].append(child_result)
|
||||
else:
|
||||
result[child.tag] = child_result
|
||||
|
||||
# 如果当前元素没有子元素,则将其文本内容作为值保存
|
||||
if not result and element.text:
|
||||
result = element.text
|
||||
|
||||
return result
|
||||
|
||||
if xml_string is None or not isinstance(xml_string, str):
|
||||
return None
|
||||
try:
|
||||
root = ET.fromstring(xml_string)
|
||||
except Exception as e:
|
||||
return xml_string
|
||||
return parse_xml(root)
|
||||
|
||||
|
||||
def read_img_dat(input_data):
|
||||
"""
|
||||
读取图片文件dat格式
|
||||
:param input_data: 图片文件路径或者图片文件数据
|
||||
:return: 图片格式,图片md5,图片数据
|
||||
"""
|
||||
# 常见图片格式的文件头
|
||||
img_head = {
|
||||
b"\xFF\xD8\xFF": ".jpg",
|
||||
b"\x89\x50\x4E\x47": ".png",
|
||||
b"\x47\x49\x46\x38": ".gif",
|
||||
b"\x42\x4D": ".BMP",
|
||||
b"\x49\x49": ".TIFF",
|
||||
b"\x4D\x4D": ".TIFF",
|
||||
b"\x00\x00\x01\x00": ".ICO",
|
||||
b"\x52\x49\x46\x46": ".WebP",
|
||||
b"\x00\x00\x00\x18\x66\x74\x79\x70\x68\x65\x69\x63": ".HEIC",
|
||||
}
|
||||
|
||||
if isinstance(input_data, str):
|
||||
with open(input_data, "rb") as f:
|
||||
input_bytes = f.read()
|
||||
else:
|
||||
input_bytes = input_data
|
||||
|
||||
try:
|
||||
import numpy as np
|
||||
input_bytes = np.frombuffer(input_bytes, dtype=np.uint8)
|
||||
for hcode in img_head: # 遍历文件头
|
||||
t = input_bytes[0] ^ hcode[0] # 异或解密
|
||||
if np.all(t == np.bitwise_xor(np.frombuffer(input_bytes[:len(hcode)], dtype=np.uint8),
|
||||
np.frombuffer(hcode, dtype=np.uint8))): # 使用NumPy进行向量化的异或解密操作,并进行类型转换
|
||||
fomt = img_head[hcode] # 获取文件格式
|
||||
|
||||
out_bytes = np.bitwise_xor(input_bytes, t) # 使用NumPy进行向量化的异或解密操作
|
||||
md5 = get_md5(out_bytes)
|
||||
return fomt, md5, out_bytes
|
||||
return False
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
for hcode in img_head:
|
||||
t = input_bytes[0] ^ hcode[0]
|
||||
for i in range(1, len(hcode)):
|
||||
if t == input_bytes[i] ^ hcode[i]:
|
||||
fomt = img_head[hcode]
|
||||
out_bytes = bytearray()
|
||||
for nowByte in input_bytes: # 读取文件
|
||||
newByte = nowByte ^ t # 异或解密
|
||||
out_bytes.append(newByte)
|
||||
md5 = get_md5(out_bytes)
|
||||
return fomt, md5, out_bytes
|
||||
return False
|
||||
|
||||
|
||||
def read_emoji(cdnurl, is_show=False):
|
||||
headers = {
|
||||
"User-Agent": "Mozilla/5.0 (Linux; Android 10; Redmi K30 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Mobile Safari/537.36"
|
||||
|
||||
}
|
||||
r1 = requests.get(cdnurl, headers=headers)
|
||||
rdata = r1.content
|
||||
|
||||
if is_show: # 显示表情
|
||||
img = Image.open(BytesIO(rdata))
|
||||
img.show()
|
||||
return rdata
|
||||
|
||||
|
||||
def decompress_CompressContent(data):
|
||||
"""
|
||||
解压缩Msg:CompressContent内容
|
||||
:param data:
|
||||
:return:
|
||||
"""
|
||||
if data is None or not isinstance(data, bytes):
|
||||
return None
|
||||
i = 0
|
||||
uncompressed_data = []
|
||||
|
||||
while i < len(data):
|
||||
# 读取第一个字节
|
||||
byte1 = data[i]
|
||||
# 从高四位得到无匹配的明文长度Lh
|
||||
Lh = byte1 >> 4
|
||||
Li = byte1 & 0x0F # 从低四位得到匹配的数据长度Li
|
||||
if Lh == 0x0f:
|
||||
# 继续读取下一个字节L1
|
||||
i = i + 1
|
||||
L1 = data[i]
|
||||
Lh = L1 + 0x0f
|
||||
|
||||
while data[i] == 0xFF:
|
||||
# 继续读取下一个字节,并累加
|
||||
i = i + 1
|
||||
Lh += data[i]
|
||||
i += 1
|
||||
uncompressed_data.extend(data[i:i + Lh])
|
||||
i = i + Lh
|
||||
|
||||
# 读取匹配的偏移量Offset
|
||||
bias = data[i:i + 2]
|
||||
offset = int.from_bytes(bias, byteorder='little')
|
||||
i = i + 2
|
||||
|
||||
# 读取匹配的数据长度Li
|
||||
if Li != 0x0F:
|
||||
# 实际的匹配压缩长度即为Li = Li + 4
|
||||
Li += 4
|
||||
else:
|
||||
# 从偏移量后面的可选匹配长度区域读取一个字节M1
|
||||
M1 = data[i]
|
||||
Li += M1
|
||||
while M1 == 0xFF:
|
||||
# 继续读取下一个字节M2
|
||||
i += 1
|
||||
M1 = data[i]
|
||||
Li += M1
|
||||
Li += 4
|
||||
# 复制匹配的数据到解压缩数据缓冲区
|
||||
uncompressed_data.extend(uncompressed_data[-offset:-offset + Li])
|
||||
# break
|
||||
|
||||
# 转换为字符串
|
||||
uncompressed_data = bytes(uncompressed_data) # .decode('utf-8')
|
||||
return uncompressed_data
|
||||
|
||||
|
||||
def read_audio_buf(buf_data, is_play=False, is_wave=False, rate=24000):
|
||||
silk_file = BytesIO(buf_data) # 读取silk文件
|
||||
pcm_file = BytesIO() # 创建pcm文件
|
||||
|
||||
pysilk.decode(silk_file, pcm_file, rate) # 解码silk文件->pcm文件
|
||||
pcm_data = pcm_file.getvalue() # 获取pcm文件数据
|
||||
|
||||
silk_file.close() # 关闭silk文件
|
||||
pcm_file.close() # 关闭pcm文件
|
||||
if is_play: # 播放音频
|
||||
def play_audio(pcm_data, rate):
|
||||
p = pyaudio.PyAudio() # 实例化pyaudio
|
||||
stream = p.open(format=pyaudio.paInt16, channels=1, rate=rate, output=True) # 创建音频流对象
|
||||
stream.write(pcm_data) # 写入音频流
|
||||
stream.stop_stream() # 停止音频流
|
||||
stream.close() # 关闭音频流
|
||||
p.terminate() # 关闭pyaudio
|
||||
|
||||
play_audio(pcm_data, rate)
|
||||
|
||||
if is_wave: # 转换为wav文件
|
||||
wave_file = BytesIO() # 创建wav文件
|
||||
with wave.open(wave_file, 'wb') as wf:
|
||||
wf.setparams((1, 2, rate, 0, 'NONE', 'NONE')) # 设置wav文件参数
|
||||
wf.writeframes(pcm_data) # 写入wav文件
|
||||
rdata = wave_file.getvalue() # 获取wav文件数据
|
||||
wave_file.close() # 关闭wav文件
|
||||
return rdata
|
||||
|
||||
return pcm_data
|
||||
|
||||
|
||||
def read_audio(MsgSvrID, is_play=False, is_wave=False, DB_PATH: str = "", rate=24000):
|
||||
if DB_PATH == "":
|
||||
return False
|
||||
|
||||
DB = sqlite3.connect(DB_PATH)
|
||||
cursor = DB.cursor()
|
||||
sql = "select Buf from Media where Reserved0='{}'".format(MsgSvrID)
|
||||
DBdata = cursor.execute(sql).fetchall()
|
||||
|
||||
if len(DBdata) == 0:
|
||||
return False
|
||||
data = DBdata[0][0] # [1:] + b'\xFF\xFF'
|
||||
pcm_data = read_audio_buf(data, is_play, is_wave, rate)
|
||||
return pcm_data
|
||||
|
||||
|
||||
def wordcloud_generator(text, out_path="", is_show=False, img_path="", font="C:\Windows\Fonts\simhei.ttf"):
|
||||
"""
|
||||
词云
|
||||
:param is_show: 是否显示
|
||||
:param img_path: 背景图片路径
|
||||
:param text: 文本
|
||||
:param font: 字体路径
|
||||
:return:
|
||||
"""
|
||||
try:
|
||||
from wordcloud import WordCloud
|
||||
import jieba
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.font_manager import fontManager
|
||||
except ImportError as e:
|
||||
print("error", e)
|
||||
raise ImportError("请安装wordcloud,jieba,numpy,matplotlib,pillow库")
|
||||
words = jieba.lcut(text) # 精确分词
|
||||
newtxt = ' '.join(words) # 空格拼接
|
||||
# 字体路径
|
||||
|
||||
# 创建WordCloud对象
|
||||
wordcloud1 = WordCloud(width=800, height=400, background_color='white', font_path=font)
|
||||
wordcloud1.generate(newtxt)
|
||||
|
||||
if out_path and out_path != "":
|
||||
wordcloud1.to_file("wordcloud.png") # 保存图片
|
||||
if img_path and os.path.exists(img_path): # 设置背景图片
|
||||
img_color = np.array(Image.open(img_path)) # 读取背景图片
|
||||
img_color = img_color.reshape((img_color.shape[0] * img_color.shape[1], 3))
|
||||
wordcloud1.recolor(color_func=img_color) # 设置背景图片颜色
|
||||
if is_show:
|
||||
# 显示词云
|
||||
wordcloud_img = wordcloud1.to_image()
|
||||
wordcloud_img.show()
|
||||
|
||||
|
||||
def read_BytesExtra(data):
|
||||
if data[0:2] == '0x':
|
||||
data = data[2:]
|
||||
data = bytes.fromhex(data)
|
||||
print(data)
|
||||
print('*' * 50)
|
||||
print(data.decode('utf-8', errors='ignore'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
data = ''
|
||||
read_BytesExtra(data)
|
||||
print('*' * 50)
|
||||
data2 = ''
|
||||
read_BytesExtra(data2)
|
||||
@@ -0,0 +1,274 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: export_chat.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2023/12/03
|
||||
# -------------------------------------------------------------------------------
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: GUI.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2023/11/10
|
||||
# -------------------------------------------------------------------------------
|
||||
import base64
|
||||
import sqlite3
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
from .utils import get_md5
|
||||
from .db_parsing import read_img_dat, decompress_CompressContent, read_audio, parse_xml_string
|
||||
|
||||
from flask import Flask, request, render_template, g, Blueprint
|
||||
|
||||
|
||||
def get_user_list(MSG_ALL_db_path, MicroMsg_db_path):
|
||||
users = []
|
||||
# 连接 MSG_ALL.db 数据库,并执行查询
|
||||
db1 = sqlite3.connect(MSG_ALL_db_path)
|
||||
cursor1 = db1.cursor()
|
||||
cursor1.execute("SELECT StrTalker, COUNT(*) AS ChatCount FROM MSG GROUP BY StrTalker ORDER BY ChatCount DESC")
|
||||
result = cursor1.fetchall()
|
||||
|
||||
for row in result:
|
||||
# 获取用户名、昵称、备注和聊天记录数量
|
||||
db2 = sqlite3.connect(MicroMsg_db_path)
|
||||
cursor2 = db2.cursor()
|
||||
cursor2.execute("SELECT UserName, NickName, Remark FROM Contact WHERE UserName=?", (row[0],))
|
||||
result2 = cursor2.fetchone()
|
||||
if result2:
|
||||
username, nickname, remark = result2
|
||||
chat_count = row[1]
|
||||
|
||||
# 拼接四列数据为元组
|
||||
row_data = {"username": username, "nickname": nickname, "remark": remark, "chat_count": chat_count,
|
||||
"isChatRoom": username.startswith("@chatroom")}
|
||||
users.append(row_data)
|
||||
cursor2.close()
|
||||
db2.close()
|
||||
cursor1.close()
|
||||
db1.close()
|
||||
return users
|
||||
|
||||
|
||||
def load_base64_audio_data(MsgSvrID, MediaMSG_all_db_path):
|
||||
wave_data = read_audio(MsgSvrID, is_wave=True, DB_PATH=MediaMSG_all_db_path)
|
||||
if not wave_data:
|
||||
return ""
|
||||
video_base64 = base64.b64encode(wave_data).decode("utf-8")
|
||||
video_data = f"data:audio/wav;base64,{video_base64}"
|
||||
return video_data
|
||||
|
||||
|
||||
def load_base64_img_data(start_time, end_time, username_md5, FileStorage_path):
|
||||
"""
|
||||
获取图片的base64数据
|
||||
:param start_time: 开始时间戳
|
||||
:param end_time: 结束时间戳
|
||||
:param username_md5: 用户名的md5值
|
||||
:return:
|
||||
"""
|
||||
# 获取CreateTime的最大值日期
|
||||
min_time = time.strftime("%Y-%m", time.localtime(start_time))
|
||||
max_time = time.strftime("%Y-%m", time.localtime(end_time))
|
||||
img_path = os.path.join(FileStorage_path, "MsgAttach", username_md5, "Image")
|
||||
if not os.path.exists(img_path):
|
||||
return {}
|
||||
# print(min_time, max_time, img_path)
|
||||
paths = []
|
||||
for root, path, files in os.walk(img_path):
|
||||
for p in path:
|
||||
if p >= min_time and p <= max_time:
|
||||
paths.append(os.path.join(root, p))
|
||||
# print(paths)
|
||||
img_md5_data = {}
|
||||
for path in paths:
|
||||
for root, path, files in os.walk(path):
|
||||
for file in files:
|
||||
if file.endswith(".dat"):
|
||||
file_path = os.path.join(root, file)
|
||||
fomt, md5, out_bytes = read_img_dat(file_path)
|
||||
out_bytes = base64.b64encode(out_bytes).decode("utf-8")
|
||||
img_md5_data[md5] = f"data:{fomt};base64,{out_bytes}"
|
||||
return img_md5_data
|
||||
|
||||
|
||||
def load_chat_records(selected_talker, start_index, page_size, user_list, MSG_ALL_db_path, MediaMSG_all_db_path,
|
||||
FileStorage_path):
|
||||
username = user_list.get("username", "")
|
||||
username_md5 = get_md5(username)
|
||||
type_name_dict = {
|
||||
1: {0: "文本"},
|
||||
3: {0: "图片"},
|
||||
34: {0: "语音"},
|
||||
43: {0: "视频"},
|
||||
47: {0: "动画表情"},
|
||||
49: {0: "文本", 1: "类似文字消息而不一样的消息", 5: "卡片式链接", 6: "文件", 8: "用户上传的 GIF 表情",
|
||||
19: "合并转发的聊天记录", 33: "分享的小程序", 36: "分享的小程序", 57: "带有引用的文本消息",
|
||||
63: "视频号直播或直播回放等",
|
||||
87: "群公告", 88: "视频号直播或直播回放等", 2000: "转账消息", 2003: "赠送红包封面"},
|
||||
50: {0: "语音通话"},
|
||||
10000: {0: "系统通知", 4: "拍一拍", 8000: "系统通知"}
|
||||
}
|
||||
|
||||
# 连接 MSG_ALL.db 数据库,并执行查询
|
||||
db1 = sqlite3.connect(MSG_ALL_db_path)
|
||||
cursor1 = db1.cursor()
|
||||
|
||||
cursor1.execute(
|
||||
"SELECT localId, IsSender, StrContent, StrTalker, Sequence, Type, SubType,CreateTime,MsgSvrID,DisplayContent,CompressContent FROM MSG WHERE StrTalker=? ORDER BY CreateTime ASC LIMIT ?,?",
|
||||
(selected_talker, start_index, page_size))
|
||||
result1 = cursor1.fetchall()
|
||||
|
||||
cursor1.close()
|
||||
db1.close()
|
||||
|
||||
img_md5_data = load_base64_img_data(result1[0][7], result1[-1][7], username_md5, FileStorage_path) # 获取图片的base64数据
|
||||
|
||||
data = []
|
||||
for row in result1:
|
||||
localId, IsSender, StrContent, StrTalker, Sequence, Type, SubType, CreateTime, MsgSvrID, DisplayContent, CompressContent = row
|
||||
CreateTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(CreateTime))
|
||||
|
||||
type_name = type_name_dict.get(Type, {}).get(SubType, "未知")
|
||||
|
||||
content = {"src": "", "msg": "", "style": ""}
|
||||
|
||||
if Type == 47 and SubType == 0: # 动画表情
|
||||
content_tmp = parse_xml_string(StrContent)
|
||||
cdnurl = content_tmp.get("emoji", {}).get("cdnurl", "")
|
||||
# md5 = content_tmp.get("emoji", {}).get("md5", "")
|
||||
if cdnurl:
|
||||
content = {"src": cdnurl, "msg": "表情", "style": "width: 100px; height: 100px;"}
|
||||
|
||||
elif Type == 49 and SubType == 57: # 带有引用的文本消息
|
||||
CompressContent = CompressContent.rsplit(b'\x00', 1)[0]
|
||||
content["msg"] = decompress_CompressContent(CompressContent)
|
||||
try:
|
||||
content["msg"] = content["msg"].decode("utf-8")
|
||||
content["msg"] = parse_xml_string(content["msg"])
|
||||
content["msg"] = json.dumps(content["msg"], ensure_ascii=False)
|
||||
except Exception as e:
|
||||
content["msg"] = "[带有引用的文本消息]解析失败"
|
||||
elif Type == 34 and SubType == 0: # 语音
|
||||
tmp_c = parse_xml_string(StrContent)
|
||||
voicelength = tmp_c.get("voicemsg", {}).get("voicelength", "")
|
||||
transtext = tmp_c.get("voicetrans", {}).get("transtext", "")
|
||||
if voicelength.isdigit():
|
||||
voicelength = int(voicelength) / 1000
|
||||
voicelength = f"{voicelength:.2f}"
|
||||
content["msg"] = f"语音时长:{voicelength}秒\n翻译结果:{transtext}"
|
||||
|
||||
src = load_base64_audio_data(MsgSvrID, MediaMSG_all_db_path=MediaMSG_all_db_path)
|
||||
content["src"] = src
|
||||
elif Type == 3 and SubType == 0: # 图片
|
||||
xml_content = parse_xml_string(StrContent)
|
||||
md5 = xml_content.get("img", {}).get("md5", "")
|
||||
if md5:
|
||||
content["src"] = img_md5_data.get(md5, "")
|
||||
else:
|
||||
content["src"] = ""
|
||||
content["msg"] = "图片"
|
||||
|
||||
else:
|
||||
content["msg"] = StrContent
|
||||
|
||||
row_data = {"MsgSvrID": MsgSvrID, "type_name": type_name, "is_sender": IsSender,
|
||||
"content": content, "CreateTime": CreateTime}
|
||||
data.append(row_data)
|
||||
return data
|
||||
|
||||
|
||||
def export_html(user, outpath, MSG_ALL_db_path, MediaMSG_all_db_path, FileStorage_path, page_size=500):
|
||||
name_save = user.get("remark", user.get("nickname", user.get("username", "")))
|
||||
username = user.get("username", "")
|
||||
|
||||
chatCount = user.get("chat_count", 0)
|
||||
if chatCount == 0:
|
||||
return False, "没有聊天记录"
|
||||
|
||||
for i in range(0, chatCount, page_size):
|
||||
start_index = i
|
||||
data = load_chat_records(username, start_index, page_size, user, MSG_ALL_db_path, MediaMSG_all_db_path,
|
||||
FileStorage_path)
|
||||
if len(data) == 0:
|
||||
break
|
||||
save_path = os.path.join(outpath, f"{name_save}_{int(i / page_size)}.html")
|
||||
with open(save_path, "w", encoding="utf-8") as f:
|
||||
f.write(render_template("chat.html", msgs=data))
|
||||
return True, f"导出成功{outpath}"
|
||||
|
||||
|
||||
def export(username, outpath, MSG_ALL_db_path, MicroMsg_db_path, MediaMSG_all_db_path, FileStorage_path):
|
||||
if not os.path.exists(outpath):
|
||||
outpath = os.path.join(os.getcwd(), "export" + os.sep + username)
|
||||
if not os.path.exists(outpath):
|
||||
os.makedirs(outpath)
|
||||
|
||||
USER_LIST = get_user_list(MSG_ALL_db_path, MicroMsg_db_path)
|
||||
user = list(filter(lambda x: x["username"] == username, USER_LIST))
|
||||
|
||||
if username and len(user) > 0:
|
||||
user = user[0]
|
||||
return export_html(user, outpath, MSG_ALL_db_path, MediaMSG_all_db_path, FileStorage_path)
|
||||
|
||||
|
||||
app_show_chat = Blueprint('show_chat_main', __name__, template_folder='templates')
|
||||
app_show_chat.debug = False
|
||||
|
||||
|
||||
# 主页 - 显示用户列表
|
||||
@app_show_chat.route('/')
|
||||
def index():
|
||||
g.USER_LIST = get_user_list(g.MSG_ALL_db_path, g.MicroMsg_db_path)
|
||||
return render_template("index.html", users=g.USER_LIST)
|
||||
|
||||
|
||||
# 获取聊天记录
|
||||
@app_show_chat.route('/get_chat_data', methods=["GET", 'POST'])
|
||||
def get_chat_data():
|
||||
username = request.args.get("username", "")
|
||||
user = list(filter(lambda x: x["username"] == username, g.USER_LIST))
|
||||
|
||||
if username and len(user) > 0:
|
||||
user = user[0]
|
||||
|
||||
limit = int(request.args.get("limit", 100)) # 每页显示的条数
|
||||
page = int(request.args.get("page", user.get("chat_count", limit) / limit)) # 当前页数
|
||||
|
||||
start_index = (page - 1) * limit
|
||||
page_size = limit
|
||||
|
||||
data = load_chat_records(username, start_index, page_size, user, g.MSG_ALL_db_path, g.MediaMSG_all_db_path,
|
||||
g.FileStorage_path)
|
||||
return render_template("chat.html", msgs=data)
|
||||
else:
|
||||
return "error"
|
||||
|
||||
|
||||
# 聊天记录导出为html
|
||||
@app_show_chat.route('/export_chat_data', methods=["GET", 'POST'])
|
||||
def get_export():
|
||||
username = request.args.get("username", "")
|
||||
|
||||
user = list(filter(lambda x: x["username"] == username, g.USER_LIST))
|
||||
|
||||
if username and len(user) > 0:
|
||||
user = user[0]
|
||||
n = f"{user.get('username', '')}_{user.get('nickname', '')}_{user.get('remark', '')}"
|
||||
outpath = os.path.join(os.getcwd(), "export" + os.sep + n)
|
||||
if not os.path.exists(outpath):
|
||||
os.makedirs(outpath)
|
||||
|
||||
ret = export_html(user, outpath, g.MSG_ALL_db_path, g.MediaMSG_all_db_path, g.FileStorage_path, page_size=200)
|
||||
if ret[0]:
|
||||
return ret[1]
|
||||
else:
|
||||
return ret[1]
|
||||
else:
|
||||
return "error"
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
pass
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 331 KiB |
@@ -0,0 +1,22 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: utils.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2023/12/03
|
||||
# -------------------------------------------------------------------------------
|
||||
import hashlib
|
||||
|
||||
|
||||
def get_md5(data):
|
||||
"""
|
||||
获取数据的 MD5 值
|
||||
:param data: 数据(bytes)
|
||||
:return:
|
||||
"""
|
||||
md5 = hashlib.md5()
|
||||
md5.update(data)
|
||||
return md5.hexdigest()
|
||||
|
||||
if __name__ == '__main__':
|
||||
pass
|
||||
Reference in new issue
Block a user