Я следовал упражнению Google Codelab по интеграции ChatBot диалогового потока с веб-приложением django и развертыванию его на облачной платформе Google. Но я не могу этого сделать. Пожалуйста, помогите мне, так как я довольно новичок во всех этих вопросах, и я много пытался решить проблемы, но ничего не произошло.
Ссылка на Codelab: Создать клиентскую часть Django для приложения Dialogflow
Файл views.py моего приложения:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import JsonResponse
from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.http import require_http_methods
import dialogflow
import os
import json
from django.views.decorators.csrf import csrf_exempt
#from dialogflow_v2 import dialogflow_v2 as Dialogflow
# Create your views here.
@require_http_methods(['GET'])
def index_view(request):
return render(request, 'home.html')
def convert(data):
if isinstance(data, bytes):
return data.decode('ascii')
if isinstance(data, dict):
return dict(map(convert, data.items()))
if isinstance(data, tuple):
return map(convert, data)
return data
@csrf_exempt
@require_http_methods(['POST'])
def chat_view(request):
print("FIRST STOP")
print('Body', request.body)
input_dict = convert(request.body)
input_text = json.loads(input_dict)['text']
GOOGLE_AUTHENTICATION_FILE_NAME = "project_on_gcp.json"
current_directory = os.path.dirname(os.path.realpath(__file__))
path = os.path.join(current_directory, GOOGLE_AUTHENTICATION_FILE_NAME)
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = path
GOOGLE_PROJECT_ID = "project_id"
session_id = "1234567891"
context_short_name = "does_not_matter"
context_name = "projects/" + GOOGLE_PROJECT_ID + "/agent/sessions/" + session_id + "/contexts/" + \
context_short_name.lower()
parameters = dialogflow.types.struct_pb2.Struct()
#parameters["foo"] = "bar"
context_1 = dialogflow.types.context_pb2.Context(
name=context_name,
lifespan_count=2,
parameters=parameters
)
query_params_1 = {"contexts": [context_1]}
language_code = 'en'
response = detect_intent_with_parameters(
project_id=GOOGLE_PROJECT_ID,
session_id=session_id,
query_params=query_params_1,
language_code=language_code,
user_input=input_text
)
return HttpResponse(response.query_result.fulfillment_text, status=200)
def detect_intent_with_parameters(project_id, session_id, query_params, language_code, user_input):
"""Returns the result of detect intent with texts as inputs.
Using the same `session_id` between requests allows continuation
of the conversaion."""
session_client = dialogflow.SessionsClient()
session = session_client.session_path(project_id, session_id)
print('Session path: {}\n'.format(session))
#text = "this is as test"
text = user_input
text_input = dialogflow.types.TextInput(
text=text, language_code=language_code)
query_input = dialogflow.types.QueryInput(text=text_input)
response = session_client.detect_intent(
session=session, query_input=query_input,
query_params=query_params
)
print('=' * 20)
print('Query text: {}'.format(response.query_result.query_text))
print('Detected intent: {} (confidence: {})\n'.format(
response.query_result.intent.display_name,
response.query_result.intent_detection_confidence))
print('Fulfillment text: {}\n'.format(
response.query_result.fulfillment_text))
return response
def about(request):
return render(request, 'chat/about.html')
My urls.py:
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('chat/', views.chat_view, name='chat-home'),
path('', views.index_view, name='index'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Мой дом. html страница, где У меня есть чат-бот:
{% load staticfiles %}
<html>
<head>
<title>Django Dialogflow</title>
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"/>
<link rel="stylesheet" href="{% static 'css/custom.css' %}"/>
</head>
<body>
<div class="container">
<div class="page-header text-center">
<h1>Dialogflow</h1>
</div>
<div class="row">
<div class="col-xs-6 col-xs-offset-3">
<ul class="list-group js-chat-log">
</ul>
<div class="input-group input-group-lg">
<span class="input-group-btn">
<button class="btn btn-primary js-say">Submit</button>
</span>
</div>
</div>
</div>
</div>
<script src="{% static 'js/jquery.js' %}"></script>
<script src="{% static 'js/js.cookie.js' %}"></script>
<script src="{% static 'js/bootstrap.js' %}"></script>
<script>
var $chatlog = $('.js-chat-log');
var $input = $('.js-text');
var formData = new FormData(this);
var $sayButton = $('.js-say');
var dialogflowUrl = '{% url "index" %}';
var csrftoken = Cookies.get('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
function createRow(text) {
var $row = $('<li class="list-group-item"></li>');
var list = '<li class="list-group-item">'
var k = text.split("\n")
for(i=0;i<k.length;i++) {
list += k[i]+"<br />"
}
list = list + "</li>"
$row.text(list);
$chatlog.append(list);
//$chatlog.append(text);
}
window.onload = createRow('<b><font size="4" face="Lucida Console">Chat with Dialogflow</font></b>');
function submitInput() {
var inputData = {
'text': $input.val()
}
// Display the user's input on the web page
createRow(inputData.text);
var dialogflowChatUrl = '{% url "chat-home" %}';
var $submit = $.ajax({
type: 'POST',
url: dialogflowChatUrl,
data: JSON.stringify(inputData),
contentType: 'application/json',
});
$submit.done(function(statement) {
//createRow(statement.text);
createRow(statement);
console.log("this is", statement)
// Clear the input field
$input.val('');
});
$submit.fail(function() {
// TODO: Handle errors
});
}
$sayButton.click(function() {
submitInput();
});
$input.keydown(function(event) {
// Submit the input when the enter button is pressed
if (event.keyCode == 13) {
submitInput();
}
});
</script>
</body>
</html>
Мой файл Settings.py:
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 2.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: don't run with debug turned on in production!
SECRET_KEY = '6l^@!6)2*0d+xach78%=_y39$5abzuycs&9ke3s)y_u8@lpb4n'
DEBUG = True
# SECURITY WARNING: App Engine's security features ensure that it is safe to
# have ALLOWED_HOSTS = ['*'] when the app is deployed. If you deploy a Django
# app not on App Engine, make sure to set an appropriate host here.
# See https://docs.djangoproject.com/en/2.1/ref/settings/
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'chat.apps.ChatConfig',
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'chat',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# Dialogflow settings
DIALOGFLOW = {
'client_access_token': 'client_access_token',
}
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
# Install PyMySQL as mysqlclient/MySQLdb to use Django's mysqlclient adapter
# See https://docs.djangoproject.com/en/2.1/ref/databases/#mysql-db-api-drivers
# for more information
import pymysql # noqa: 402
pymysql.install_as_MySQLdb()
# [START db_setup]
if os.getenv('GAE_APPLICATION', None):
# Running on production App Engine, so connect to Google Cloud SQL using
# the unix socket at /cloudsql/<your-cloudsql-connection string>
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '/cloudsql/connection_name',
'USER': 'username',
'PASSWORD': 'password',
'NAME': 'database_name',
}
}
else:
# Running locally so connect to either a local MySQL instance or connect to
# Cloud SQL via the proxy. To start the proxy via command line:
#
# $ cloud_sql_proxy -instances=[INSTANCE_CONNECTION_NAME]=tcp:3306
#
# See https://cloud.google.com/sql/docs/mysql-connect-proxy
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '127.0.0.1',
'PORT': '3306',
'USER': 'username',
'PASSWORD': 'password',
'NAME': 'database_name',
}
}
# [END db_setup]
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', # noqa: 501
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', # noqa: 501
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', # noqa: 501
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', # noqa: 501
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_ROOT = 'static'
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL ='/media/'
CORS_ORIGIN_WHITELIST = (
'google.com',
'hostname.example.com',
'localhost:8000',
'127.0.0.1:9000'
)
Я был бы чрезвычайно признателен за всю помощь, которую я получил.