Loading multiple AIML files

We have seen how to load a single AIML file to memory and retrieve response for a user input. In this section, we are going to see how to load multiple AIML files to memory; we are going to use these files for our AIML-based bots. Various AIML datasets are available on the Web, and some are also included in the code bundle. Given here is a file called startup.xml that helps us load all AIML files in a single run. It's a simple AIML file with a pattern called LOAD AIML B. When it gets this input from the user, it will learn all AIML files in that path using <learn>*.aiml</learn> tags:

    <aiml version="1.0"> 
      <category> 
        <pattern>LOAD AIML B</pattern> 
          <template> 
            <!-- Load standard AIML set --> 
            <learn>*.aiml</learn> 
          </template> 
      </category> 
    </aiml> 

We can use the following code to load this XML file and "learn" all the XML files to memory. After loading the AIML files, we can save the memory contents as a brain file. The advantage is that we can avoid the reloading of AIML files. Saving into a brain file will be helpful when we have thousands of AIML files:

     #!/usr/bin/env python 
     import aiml 
     import sys 
     import os
     #Changing current directory to the path of aiml files
     #This path will change according to your location of aiml files 
    os.chdir('/home/robot/Desktop/aiml/aiml_data_files') bot = 
    aiml.Kernel()
    #If there is a brain file named standard.brn, Kernel() will
     initialize using bootstrap() method
    if os.path.isfile("standard.brn"): bot.bootstrap(brainFile = 
    "standard.brn") else:
    #If there is no brain file, load all AIML files and save a new 
    brain bot.bootstrap(learnFiles = "startup.xml", commands = "load 
    aiml b") bot.saveBrain("standard.brn")
    #This loop ask for response from user and print the output from 
    Kernel() object
    while True: print bot.respond(raw_input("Enter input >"))

You can see that the AIML files are stored at /home/robot/Desktop/aiml/aiml_data_files/. All AIML files including startup.xml and AIML brain files are stored in the same folder. You can choose any folder you want. In the previous code, we are using a new API called bootstrap() for loading, saving, and learning AIML files. The program tries to load a brain file called standard.brn first, and if there is no brain file, it will learn from startup.xml and save the brain file as standard.brn. After saving the brain file, it will start a while loop to start interacting with the AIML file.

If you run the code and there is no brain file, you may get output like this:

Figure 3: Loading multiple AIML files

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.44.23