0

When I run chat.py, I am receiving an error saying "FileNotFoundError: No such file or directory: 'intents.json'", however that file - intents.json already exists in my code base.

Here's my code for chat.py:

import random
import json

import torch

from model import NeuralNet
from nltk_utils import bag_of_words, tokenize

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

with open('intents.json', 'r') as json_data:
    intents = json.load(json_data)

FILE = "data.pth"
data = torch.load(FILE)

input_size = data["input_size"]
hidden_size = data["hidden_size"]
output_size = data["output_size"]
all_words = data['all_words']
tags = data['tags']
model_state = data["model_state"]

model = NeuralNet(input_size, hidden_size, output_size).to(device)
model.load_state_dict(model_state)
model.eval()

bot_name = "Sam"

def get_response(msg):
    sentence = tokenize(msg)
    X = bag_of_words(sentence, all_words)
    X = X.reshape(1, X.shape[0])
    X = torch.from_numpy(X).to(device)

    output = model(X)
    _, predicted = torch.max(output, dim=1)

    tag = tags[predicted.item()]

    probs = torch.softmax(output, dim=1)
    prob = probs[0][predicted.item()]
    if prob.item() > 0.75:
        for intent in intents['intents']:
            if tag == intent["tag"]:
                return random.choice(intent['responses'])
    
    return "I do not understand..."


if __name__ == "__main__":
    print("Let's chat! (type 'quit' to exit)")
    while True:
        # sentence = "do you use credit cards?"
        sentence = input("You: ")
        if sentence == "quit":
            break

        resp = get_response(sentence)
        print(resp)

I've already tried switching directories and the intents.json file is under the correct directory - the same directory as chat.py. I am wondering why I am receiving this error?

Here's a photo if you want to see the intents.json file in relation to my code:

  • 1
    The program expects the json file to be in _the current directory_, which is not necessarily the same directory as the program file itself. – John Gordon Jun 20 '23 at 00:59
  • 2
    You can use this code to print the current directory: `import os; print(os.getcwd())` – John Gordon Jun 20 '23 at 00:59
  • See https://stackoverflow.com/q/4060221/494134 for advice to open a file that is in the same directory as the program script. – John Gordon Jun 20 '23 at 01:00
  • As an aside, _minimal_ examples are preferred. You could remove almost all of the code and still get the error. – tdelaney Jun 20 '23 at 01:04

1 Answers1

0

intents.json is not in your current working directory. You can print the current working directory using this:

import os
print(os.getcwd())

Alternatively, you can check the working directory in launch.json in vscode.

Once you have the working directory, move intents.json there.

xingharvey
  • 131
  • 6