-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom_tracker.py
175 lines (140 loc) · 4.64 KB
/
custom_tracker.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import traceback
import contextlib
import itertools
import json
import logging
import os
import pickle
from datetime import datetime, timezone
from time import sleep
from typing import (
Callable,
Dict,
Iterable,
Iterator,
List,
Optional,
Text,
Union,
TYPE_CHECKING,
)
from boto3.dynamodb.conditions import Key
import rasa.core.utils as core_utils
from rasa.core.actions.action import ACTION_LISTEN_NAME
from rasa.core.brokers.broker import EventBroker
from rasa.core.constants import (
POSTGRESQL_SCHEMA,
POSTGRESQL_MAX_OVERFLOW,
POSTGRESQL_POOL_SIZE,
)
from rasa.core.conversation import Dialogue
from rasa.core.domain import Domain
from rasa.core.events import SessionStarted
from rasa.core.trackers import ActionExecuted, DialogueStateTracker, EventVerbosity
import rasa.cli.utils as rasa_cli_utils
from rasa.utils.common import class_from_module_path, raise_warning, arguments_of
from rasa.utils.endpoints import EndpointConfig
import sqlalchemy as sa
from rasa.core.tracker_store import TrackerStore
# Import custom dbConfig for firebase returns firestore.client() class object
from actionserver.db.dbConfig import db
logger = logging.getLogger(__name__)
# COLLECTION = "restaurant-bot-tracker"
class FirebaseTrackerStore(TrackerStore):
"""Stores conversation history in Firebase"""
def __init__(
self,
domain: Domain,
collection: Optional[Text] = "tracker",
host: Optional[Text] = "localhost",
event_broker: Optional[EventBroker] = None
):
self.store = {}
self.COLLECTION = collection
super().__init__(domain, event_broker)
def save(self, tracker: DialogueStateTracker) -> None:
"""Updates and saves the current conversation state
Args:
tracker: DialogueStateTracker from TrackerStore Class
Returns:
None
Stores data in Firebase and creates tracker
"""
try:
if self.event_broker:
self.stream_events(tracker)
serialised = self.serialiseTracker(tracker)
ref = db.collection(self.COLLECTION).document(tracker.sender_id)
ref.set(serialised)
except Exception as e:
traceback.print_exc()
def checkSenderId(self, sender_id):
"""
Checks if sender Id exists in database (firebase)
Args:
sender_id : takes the sender_id as input
Returns:
Boolean (if the id exists or not)
"""
check = db.collection(self.COLLECTION).document(sender_id).get().exists
return check
def retrieve(self, sender_id: Text) -> Optional[DialogueStateTracker]:
"""
Args:
sender_id: the message owner ID
Returns:
DialogueStateTracker
"""
if self.checkSenderId(sender_id):
logger.debug(f"Recreating tracker for id '{sender_id}'")
deserialised_tracker = self.deserialiseTracker(sender_id)
return deserialised_tracker
else:
logger.debug(f"Creating a new tracker for id '{sender_id}'.")
return None
def keys(self) -> Iterable[Text]:
"""
Returns:
sender_ids of the Tracker Store in Firebase
"""
docs = db.collection(self.COLLECTION).stream()
keys = []
for doc in docs:
keys.append(doc.id)
return keys
def serialiseTracker(self, tracker:DialogueStateTracker):
"""
User defined serialisation
Args:
tracker : takes tracker object as input
Returns:
dialogue
"""
try:
dialogue = tracker.as_dialogue().as_dict()
dialogue = json.dumps(dialogue)
dialogue = json.loads(dialogue)
return dialogue
except Exception as e:
traceback.print_exc()
return None
def deserialiseTracker(self, sender_id):
"""User defined deserialisation
Args:
sender_id : Takes sender_id as input
Returns:
returns tracker
"""
tracker = self.init_tracker(sender_id)
try:
if not tracker:
return None
ref = db.collection(self.COLLECTION).document(sender_id)
dialogue = ref.get().to_dict()
# serialiseTracker(dialogue) no need to pass
dialogue = Dialogue.from_parameters(
json.loads(json.dumps(dialogue)))
except Exception as e:
traceback.print_exc()
tracker.recreate_from_dialogue(dialogue)
return tracker