4.5. Saving and Loading
Saving
Let us create a simple transition that counts how many times the user visits:
def visits() -> DialogueFlow:
transitions = {
'state': 'start',
'`It\'s your` #VISITS `visit!`': 'end'
}
macros = {
'VISITS': MacroVisits()
}
df = DialogueFlow('start', end_state='end')
df.load_transitions(transitions)
df.add_macros(macros)
return df
#4
: calls the macro#VISITS
defined in#7
.
MacroVisits
can be defined as follow:
class MacroVisits(Macro):
def run(self, ngrams: Ngrams, vars: Dict[str, Any], args: List[Any]):
vn = 'VISITS'
if vn not in vars:
vars[vn] = 1
return 'first'
else:
count = vars[vn] + 1
vars[vn] = count
match count:
case 2: return 'second'
case 3: return 'third'
case default: return '{}th'.format(count)
#10-13
: uses the match statements to return the appropriate literal.
S: It's your first visit!
The challenge is that we must save the number of visits to make this macro effective (and correct). This can be achieved by saving the variable dictionary into a binary file using the built-in Python object serialization called pickle:
def save(df: DialogueFlow, varfile: str):
df.run()
d = {k: v for k, v in df.vars().items() if not k.startswith('_')}
pickle.dump(d, open(varfile, 'wb'))
save(visits(), 'resources/visits.pkl')
#1
: takes a dialogue flowdf
and a file pathvarfile
for saving the variable dictionary to.#3
: creates a dictionary by copying only user-generated variables.#4
: opens a writable (w
) and binary (b
) file and dumps the dictionry object into the file.
After running this code, you will see the visits.pkl
file saved under the resources
directory.
Loading
The following code shows how to load the saved dictionary to a new dialogue flow:
def load(df: DialogueFlow, varfile: str):
d = pickle.load(open(varfile, 'rb'))
df.vars().update(d)
df.run()
save(df, varfile)
#1
: takes a dialogue flowdf
and a file pathvarfile
for loading the variable dictionary from.#2
: opens a readable (r
) and binary (b
) file and loads the object as a dictionary.#3
: adds all variables in the loaded dictioinary to the variable dictionary ofdf
.#5
: saves the new variable dictionary to the same file.
S: It's your second visit!
Last updated
Was this helpful?