Spaces:
Sleeping
Sleeping
Upload 3 files
Browse files- app.py +14 -59
- requirements.txt +5 -1
- utils.py +147 -0
app.py
CHANGED
@@ -1,64 +1,19 @@
|
|
1 |
import gradio as gr
|
2 |
-
from
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
history: list[tuple[str, str]],
|
13 |
-
system_message,
|
14 |
-
max_tokens,
|
15 |
-
temperature,
|
16 |
-
top_p,
|
17 |
-
):
|
18 |
-
messages = [{"role": "system", "content": system_message}]
|
19 |
-
|
20 |
-
for val in history:
|
21 |
-
if val[0]:
|
22 |
-
messages.append({"role": "user", "content": val[0]})
|
23 |
-
if val[1]:
|
24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
25 |
-
|
26 |
-
messages.append({"role": "user", "content": message})
|
27 |
-
|
28 |
-
response = ""
|
29 |
-
|
30 |
-
for message in client.chat_completion(
|
31 |
-
messages,
|
32 |
-
max_tokens=max_tokens,
|
33 |
-
stream=True,
|
34 |
-
temperature=temperature,
|
35 |
-
top_p=top_p,
|
36 |
-
):
|
37 |
-
token = message.choices[0].delta.content
|
38 |
-
|
39 |
-
response += token
|
40 |
-
yield response
|
41 |
-
|
42 |
-
|
43 |
-
"""
|
44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
45 |
-
"""
|
46 |
-
demo = gr.ChatInterface(
|
47 |
-
respond,
|
48 |
-
additional_inputs=[
|
49 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
50 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
51 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
52 |
-
gr.Slider(
|
53 |
-
minimum=0.1,
|
54 |
-
maximum=1.0,
|
55 |
-
value=0.95,
|
56 |
-
step=0.05,
|
57 |
-
label="Top-p (nucleus sampling)",
|
58 |
-
),
|
59 |
],
|
|
|
|
|
|
|
60 |
)
|
61 |
|
62 |
-
|
63 |
if __name__ == "__main__":
|
64 |
-
|
|
|
1 |
import gradio as gr
|
2 |
+
from utils import analyze_chat
|
3 |
+
|
4 |
+
# 创建Gradio界面
|
5 |
+
iface = gr.Interface(
|
6 |
+
fn=analyze_chat,
|
7 |
+
inputs=gr.File(label="上传微信聊天记录(JSON / TXT)"),
|
8 |
+
outputs=[
|
9 |
+
gr.Textbox(label="实体识别结果", lines=4),
|
10 |
+
gr.Textbox(label="人物关系(含关系类型)", lines=6),
|
11 |
+
gr.HTML(label="人物关系图谱")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
],
|
13 |
+
title="微信聊天人物关系分析",
|
14 |
+
description="上传JSON或TXT格式的微信聊天记录,自动识别人物实体和关系类型,并生成互动图谱。",
|
15 |
+
theme="compact"
|
16 |
)
|
17 |
|
|
|
18 |
if __name__ == "__main__":
|
19 |
+
iface.launch()
|
requirements.txt
CHANGED
@@ -1 +1,5 @@
|
|
1 |
-
|
|
|
|
|
|
|
|
|
|
1 |
+
gradio==4.25.0
|
2 |
+
transformers>=4.40.0
|
3 |
+
torch>=2.1.0
|
4 |
+
pyvis
|
5 |
+
networkx
|
utils.py
ADDED
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import tempfile
|
3 |
+
import re
|
4 |
+
from collections import defaultdict
|
5 |
+
|
6 |
+
from transformers import (
|
7 |
+
AutoTokenizer,
|
8 |
+
AutoModelForTokenClassification,
|
9 |
+
AutoModelForSequenceClassification,
|
10 |
+
pipeline,
|
11 |
+
)
|
12 |
+
import torch
|
13 |
+
from pyvis.network import Network
|
14 |
+
|
15 |
+
|
16 |
+
# -------------------------------
|
17 |
+
# 实体识别模型(NER)
|
18 |
+
# -------------------------------
|
19 |
+
ner_tokenizer = AutoTokenizer.from_pretrained("ckiplab/bert-base-chinese-ner")
|
20 |
+
ner_model = AutoModelForTokenClassification.from_pretrained("ckiplab/bert-base-chinese-ner")
|
21 |
+
ner_pipeline = pipeline("ner", model=ner_model, tokenizer=ner_tokenizer, aggregation_strategy="simple")
|
22 |
+
|
23 |
+
|
24 |
+
# -------------------------------
|
25 |
+
# 人物关系分类模型(BERT 分类器)
|
26 |
+
# -------------------------------
|
27 |
+
rel_model_name = "uer/roberta-base-finetuned-baike-chinese-relation-extraction"
|
28 |
+
rel_tokenizer = AutoTokenizer.from_pretrained(rel_model_name)
|
29 |
+
rel_model = AutoModelForSequenceClassification.from_pretrained(rel_model_name)
|
30 |
+
rel_model.eval()
|
31 |
+
|
32 |
+
id2label = {
|
33 |
+
0: "夫妻", 1: "父子", 2: "朋友", 3: "师生", 4: "同事", 5: "其他"
|
34 |
+
}
|
35 |
+
|
36 |
+
|
37 |
+
def classify_relation_bert(e1, e2, context):
|
38 |
+
prompt = f"{e1}和{e2}的关系是?{context}"
|
39 |
+
inputs = rel_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
|
40 |
+
with torch.no_grad():
|
41 |
+
logits = rel_model(**inputs).logits
|
42 |
+
pred = torch.argmax(logits, dim=1).item()
|
43 |
+
probs = torch.nn.functional.softmax(logits, dim=1)
|
44 |
+
confidence = probs[0, pred].item()
|
45 |
+
return f"{id2label[pred]}(置信度 {confidence:.2f})"
|
46 |
+
|
47 |
+
|
48 |
+
# -------------------------------
|
49 |
+
# 聊天输入解析
|
50 |
+
# -------------------------------
|
51 |
+
def parse_input_file(file):
|
52 |
+
filename = file.name
|
53 |
+
if filename.endswith(".json"):
|
54 |
+
return json.load(file)
|
55 |
+
elif filename.endswith(".txt"):
|
56 |
+
content = file.read().decode("utf-8")
|
57 |
+
lines = content.strip().splitlines()
|
58 |
+
chat_data = []
|
59 |
+
for line in lines:
|
60 |
+
match = re.match(r"(\d{4}-\d{2}-\d{2}.*?) (.*?): (.*)", line)
|
61 |
+
if match:
|
62 |
+
_, sender, message = match.groups()
|
63 |
+
chat_data.append({"sender": sender, "message": message})
|
64 |
+
return chat_data
|
65 |
+
else:
|
66 |
+
raise ValueError("不支持的文件格式,请上传 JSON 或 TXT 文件")
|
67 |
+
|
68 |
+
|
69 |
+
# -------------------------------
|
70 |
+
# 实体提取函数
|
71 |
+
# -------------------------------
|
72 |
+
def extract_entities(text):
|
73 |
+
results = ner_pipeline(text)
|
74 |
+
people = set()
|
75 |
+
for r in results:
|
76 |
+
if r["entity_group"] == "PER":
|
77 |
+
people.add(r["word"])
|
78 |
+
return list(people)
|
79 |
+
|
80 |
+
|
81 |
+
# -------------------------------
|
82 |
+
# 关系抽取函数(共现 + BERT 分类)
|
83 |
+
# -------------------------------
|
84 |
+
def extract_relations(chat_data, entities):
|
85 |
+
relations = defaultdict(lambda: defaultdict(lambda: {"count": 0, "contexts": []}))
|
86 |
+
|
87 |
+
for entry in chat_data:
|
88 |
+
msg = entry["message"]
|
89 |
+
found = [e for e in entities if e in msg]
|
90 |
+
for i in range(len(found)):
|
91 |
+
for j in range(i + 1, len(found)):
|
92 |
+
e1, e2 = found[i], found[j]
|
93 |
+
relations[e1][e2]["count"] += 1
|
94 |
+
relations[e1][e2]["contexts"].append(msg)
|
95 |
+
relations[e2][e1]["count"] += 1
|
96 |
+
relations[e2][e1]["contexts"].append(msg)
|
97 |
+
|
98 |
+
edges = []
|
99 |
+
for e1 in relations:
|
100 |
+
for e2 in relations[e1]:
|
101 |
+
if e1 < e2:
|
102 |
+
context_text = " ".join(relations[e1][e2]["contexts"])
|
103 |
+
label = classify_relation_bert(e1, e2, context_text)
|
104 |
+
edges.append((e1, e2, relations[e1][e2]["count"], label))
|
105 |
+
return edges
|
106 |
+
|
107 |
+
|
108 |
+
# -------------------------------
|
109 |
+
# 图谱绘制
|
110 |
+
# -------------------------------
|
111 |
+
def draw_graph(entities, relations):
|
112 |
+
g = Network(height="600px", width="100%", notebook=False)
|
113 |
+
g.barnes_hut()
|
114 |
+
for ent in entities:
|
115 |
+
g.add_node(ent, label=ent)
|
116 |
+
for e1, e2, weight, label in relations:
|
117 |
+
g.add_edge(e1, e2, value=weight, title=f"{label}(互动{weight}次)", label=label)
|
118 |
+
tmp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".html")
|
119 |
+
g.show(tmp_file.name)
|
120 |
+
with open(tmp_file.name, 'r', encoding='utf-8') as f:
|
121 |
+
return f.read()
|
122 |
+
|
123 |
+
|
124 |
+
# -------------------------------
|
125 |
+
# 主流程函数
|
126 |
+
# -------------------------------
|
127 |
+
def analyze_chat(file):
|
128 |
+
if file is None:
|
129 |
+
return "请上传聊天文件", "", ""
|
130 |
+
|
131 |
+
try:
|
132 |
+
content = parse_input_file(file)
|
133 |
+
except Exception as e:
|
134 |
+
return f"读取文件失败: {e}", "", ""
|
135 |
+
|
136 |
+
text = "\n".join([entry["sender"] + ": " + entry["message"] for entry in content])
|
137 |
+
entities = extract_entities(text)
|
138 |
+
if not entities:
|
139 |
+
return "未识别到任何人物实体", "", ""
|
140 |
+
|
141 |
+
relations = extract_relations(content, entities)
|
142 |
+
if not relations:
|
143 |
+
return "未发现人物之间的关系", "", ""
|
144 |
+
|
145 |
+
graph_html = draw_graph(entities, relations)
|
146 |
+
|
147 |
+
return str(entities), str(relations), graph_html
|