在Django中为聊天机器人存储训练数据文件的位置



我正在尝试显示我在django网站上创建的聊天机器人。因此,我需要将一些训练数据(json、pickle和h5文件(加载到views.py文件中。但当我运行服务器时,它会说:

FileNotFoundError: [Errno 2] No such file or directory: 'mysite/polls/intents.json'

即使views.py和intents.json在同一个文件夹中。

所以现在我想知道我应该把这些文件存储在哪里,以及如何打开/导入到我的views.py文件中。我需要把它们放进我的静态文件文件夹或类似的东西吗?

以下是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中,在此之前,您需要在根项目中的settings.py文件中添加静态文件root。在这里你可以遵循以下步骤:

添加根媒体文件,这样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

然后您可以从视图中读取该文件从.models导入ExcelSampleFormat

def readfile(request):
employee_bulk_data_upload = 
ExcelSampleFormat.objects.get(file_name='filename')

最新更新