Search code examples
pythonjsonpython-3.xcsvdialogflow-es

Export/convert Dialogflow agent to csv or excel file using python


How to export all Questions and answers to csv or excel file?

I have exported dialogflow agent in to zip file and I got the two json files for each question or intent.

Is there any way to create a Question and answer pair in csv or excel file?


Solution

  • The zip file contains two directories intents and entities. The intents directory contains Dialogflow each intents' response and training phrases. You can observe the pattern in JSON files and write a script to make a csv file out of it.

    import os
    import csv
    import json
    
    all_intents = os.listdir('intents')
    
    
    with open('agent.csv', 'w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(["Response", "Questions"])
        for intent in all_intents:
            write = []
            if intent.find('_usersays_en.json') == -1:
                try:
                    with open('intents/' + intent) as f:
                        data = json.load(f)
                        resp = ''
                        try:
                            resp = data['responses'][0]['messages'][0]['speech'][0]
                        except:
                            print(intent)
                        write.append(resp)
                except:
                    print(intent)
                try:
                    with open('intents/' + intent.replace(".json", "") + '_usersays_en.json') as f:
                        data = json.load(f)
                        for d in data:
                            qn = (d['data'][0]['text'])
                            write.append(qn)
                except:
                    print(intent.replace(".json", "") + '_usersays_en.json')
                writer.writerow(write)
    

    Instructions to run the code:

    1. Export the agent as zip.
    2. Unzip the file. You will see entities and intents directories getting extracted from zip.
    3. Have this python file and intents directory in the same directory.
    4. run python3 filename.py(The name of the file containing the code).
    5. agent.csv will be created.
    6. All intents with no response or training phrases will be displayed on the terminal.