arrow-left

All pages
gitbookPowered by GitBook
1 of 1

Loading...

4.5. Saving and Loading

hashtag
Saving

Let us create a simple transition that counts how many times the user visits:

  • #4: calls the macro #VISITS defined in #7.

MacroVisits can be defined as follow:

  • #10-13: uses the statements to return the appropriate literal.

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 :

  • #1: takes a dialogue flow df and a file path varfile for saving the variable dictionary to.

  • #3: creates a dictionary by copying only user-generated variables.

After running this code, you will see the visits.pkl file saved under the resources directory.

hashtag
Loading

The following code shows how to load the saved dictionary to a new dialogue flow:

  • #1: takes a dialogue flow df and a file path varfile for loading the variable dictionary from.

  • #2: opens a readable (r) and binary (b) file and loads the object as a dictionary.

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: a writable (w) and binary (b) file and dumps the dictionry object into the file.

#3: adds all variables in the loaded dictioinary to the variable dictionary of df.

  • #5: saves the new variable dictionary to the same file.

  • matcharrow-up-right
    picklearrow-up-right
    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)
    S: It's your first visit!
    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')
    def load(df: DialogueFlow, varfile: str):
        d = pickle.load(open(varfile, 'rb'))
        df.vars().update(d)
        df.run()
        save(df, varfile)
    S: It's your second visit!
    S: It's your third visit!
    S: It's your 4th visit!
    opensarrow-up-right