Где хранить файлы обучающих данных в Django для чатбота?

Я пытаюсь отобразить чатбота, которого я создал на сайте django. Поэтому мне нужно загрузить некоторые обучающие данные (json, pickle и h5 файлы) в файл views.py. Но когда я запускаю сервер, он говорит:

FileNotFoundError: [Errno 2] Нет такого файла или каталога: 'mysite/polls/intents.json'

несмотря на то, что views.py и intents.json находятся в одной папке.

Теперь мне интересно, где я должен хранить эти файлы и как открыть/импортировать их в файл views.py. Нужно ли мне поместить их в папку static files или что-то в этом роде?

Вот код из файла views.py:


from django.shortcuts import render
from django.http import HttpResponse


import nltk
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
import pickle
import numpy as np

from keras.models import load_model
import json
import random

# Create your views here.
def index(request):

    intents = json.loads(open('intents.json').read())
    model = load_model('chatbot_model.h5')
    words = pickle.load(open('words.pkl','rb'))
    classes = pickle.load(open('classes.pkl','rb'))

    def clean_up_sentence(sentence):
        sentence_words = nltk.word_tokenize(sentence)
        sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words]
        return sentence_words

    # return bag of words array: 0 or 1 for each word in the bag that exists in the sentence

    def bow(sentence, words, show_details=True):
        # tokenize the pattern
        sentence_words = clean_up_sentence(sentence)
        # bag of words - matrix of N words, vocabulary matrix
        bag = [0]*len(words)
        for s in sentence_words:
            for i,w in enumerate(words):
                if w == s:
                    # assign 1 if current word is in the vocabulary position
                    bag[i] = 1
                    if show_details:
                        print ("found in bag: %s" % w)
        return(np.array(bag))

    def predict_class(sentence, model):
        # filter out predictions below a threshold
        p = bow(sentence, words,show_details=False)
        res = model.predict(np.array([p]))[0]
        print(res)
        ERROR_THRESHOLD = 0.95
        results = [[i,r] for i,r in enumerate(res) if r>ERROR_THRESHOLD]
        # sort by strength of probability
        results.sort(key=lambda x: x[1], reverse=True)
        return_list = []
        for r in results:
            return_list.append({"intent": classes[r[0]], "probability": str(r[1])})
        if not return_list:
            return_list.append({"intent": "unclear", "probability": "1"})
        return return_list
        

    def getResponse(ints, intents_json):
        tag = ints[0]['intent']
        list_of_intents = intents_json['intents']
        for i in list_of_intents:
            if(i['tag']== tag):
                result = random.choice(i['responses'])
                break
        return result

    def chatbot_response(msg):
        ints = predict_class(msg, model)
        res = getResponse(ints, intents)
        return res


    return render(request, "index.html")



Вы можете хранить ваши файлы в static, перед этим вам нужно добавить static files root в ваш файл settings.py в корневом проекте. здесь вы можете выполнить следующие шаги:

добавьте корневой медиафайл, чтобы django мог знать, где хранятся ваши файлы

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

добавьте этот код в корневой файл urls.py

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

вы также можете добавлять файлы в базу данных через модели

class ExcelSampleFormat(models.Model):
    file_name = models.CharField(max_length=233)
    file = models.FileField(upload_to='files/sample_format/')
    insertion_datetime = models.DateTimeField(auto_now_add=True)


def __str__(self):
    return self.file_name

тогда вы можете прочитать этот файл из представления from .models import ExcelSampleFormat

def readfile(request):
    employee_bulk_data_upload = 
    ExcelSampleFormat.objects.get(file_name='filename')
Вернуться на верх