-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchatbot_graph.py
95 lines (74 loc) · 2.53 KB
/
chatbot_graph.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import networkx as nx
import json
from graph import Graph
class ChatbotGraph(Graph):
def __init__(self, file_path):
self.file_path = file_path
self.graph: nx.DiGraph = self.create(file_path)
self.fitness = 0
def __str__(self):
return f"CG: {self.graph}"
def create(self, path):
file_path = f"chatbot-dataset/examples/{path}.json"
with open(file_path, "r") as file:
data = json.load(file)["sections"]
CG = nx.DiGraph()
for section in data:
CG.add_node(section["id"])
CG.nodes[section["id"]]["text"] = f"\"{section['text']}\""
for section in data:
if section["type"] == "stop":
continue
for button in section["buttons"]:
CG.add_edge(section["id"], button["nextSectionId"], text=button["text"])
return CG
def transform(self, transformation_paths):
"""
Transform ChatbotGraph to the path found using ACO
"""
def execute(path):
operator, operands = path.split(maxsplit=1)
match operator:
case "REMOVE_NODE":
self.graph.remove_node(operands)
case "REMOVE_EDGE":
l, r = operands.split()
self.graph.remove_edge(l, r)
case "ADD_EDGE":
l, r, text = operands.split(maxsplit=2)
if l not in self.graph or r not in self.graph:
# If node l or r are already removed, peanlize.
raise Exception()
self.graph.add_edge(l, r, text=text)
case _:
pass
try:
for path in transformation_paths:
execute(path)
except:
"""
If a transfrom execution is failed,
penalize chatbotGraph by converting empty graph
"""
self.graph = nx.DiGraph()
def evaluate(self):
from fitness import fitness
self.fitness = fitness.fitness(self.graph, self.file_path)
def copy(self):
copied = ChatbotGraph(self.file_path)
copied.graph = self.graph.copy()
return copied
if __name__ == "__main__":
CG = ChatbotGraph("lead-homepage")
CG.evaluate()
print(CG.fitness)
CG_copy = CG.copy()
CG.draw()
print(CG)
CG.transform(["REMOVE_NODE A"])
CG.draw()
print(CG)
CG.transform(["REMOVE_EDGE I K"])
CG.draw()
print(CG)
print(CG_copy)