from django.contrib import admin

from chatbot_project.models import Response

# Register your models here.
admin.site.register(Response)
# admin.site.register(Topic)

chatbot_project/admin.py
tinker0830/Aapi-Ai-Django-ChatBot
from django.apps import AppConfig


class ChatbotProjectConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'chatbot_project'

chatbot_project/apps.py
tinker0830/Aapi-Ai-Django-ChatBot
# Generated by Django 4.0 on 2022-03-02 07:17

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Response',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('myquery', models.CharField(max_length=200)),
            ],
        ),
    ]

chatbot_project/migrations/0001_initial.py
tinker0830/Aapi-Ai-Django-ChatBot
# Generated by Django 4.0 on 2022-03-02 07:33

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('chatbot_project', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='response',
            name='myquery',
            field=models.TextField(max_length=200),
        ),
    ]

chatbot_project/migrations/0002_alter_response_myquery.py
tinker0830/Aapi-Ai-Django-ChatBot
# Generated by Django 4.0 on 2022-03-02 07:39

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('chatbot_project', '0002_alter_response_myquery'),
    ]

    operations = [
        migrations.CreateModel(
            name='Topic',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('myquery', models.CharField(max_length=200)),
            ],
        ),
        migrations.AlterField(
            model_name='response',
            name='myquery',
            field=models.TextField(),
        ),
    ]

chatbot_project/migrations/0003_topic_alter_response_myquery.py
tinker0830/Aapi-Ai-Django-ChatBot
# Generated by Django 4.0 on 2022-03-02 07:59

from django.db import migrations


class Migration(migrations.Migration):

    dependencies = [
        ('chatbot_project', '0003_topic_alter_response_myquery'),
    ]

    operations = [
        migrations.DeleteModel(
            name='Topic',
        ),
        migrations.RenameField(
            model_name='response',
            old_name='myquery',
            new_name='text',
        ),
    ]

chatbot_project/migrations/0004_delete_topic_rename_myquery_response_text.py
tinker0830/Aapi-Ai-Django-ChatBot
from cgitb import text
from dataclasses import field
from pydoc_data.topics import topics
from tabnanny import verbose
from django.db import models

class Response(models.Model):
    text = models.TextField()
    class meta:
        verbose_name_plural = "Responses"

    def __str__(self):
        return self.text



chatbot_project/models.py
tinker0830/Aapi-Ai-Django-ChatBot
"""project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path 
from . import views

urlpatterns = [
    #path('admin/', views.index,name = 'index'),
    path('', views.index,name='index'),
    path('home/', views.chatBot,name='chatBot')
]
chatbot_project/urls2.py
tinker0830/Aapi-Ai-Django-ChatBot

import re
from django.http import HttpRequest, JsonResponse
from django.shortcuts import render, HttpResponse
import random
import json
import numpy as np
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
#from .models import Response, models

# Remove the comments to download additional nltk packages
# import nltk
# nltk.download('punkt')
# nltk.download('wordnet')
# nltk.download('omw-1.4')

# from sklearn.feature_extraction.text import TfidfVectorizer

from tensorflow import keras
import tensorflow
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Dropout

def index(request):
   return render(request , 'chatbot_project/index.htm')


def chatBot(request):
   query = str(request.GET.get("query"))
   # print(query)
   lemmatizer=WordNetLemmatizer()

   with open('jsonfile.json') as fileobj:
      readobj=json.load(fileobj)

   words=[]
   classes=[]
   documents=[]
   stop_words=['is','and','the','a','are','i','it']
   cleaned_word=[]

   for intent in readobj['intents']:
      for pattern in intent['patterns']:
         word_list=word_tokenize(pattern)
         words.extend(word_list)
         documents.append((word_list,intent['tag']))
         if intent['tag'] not in classes:
               classes.append(intent['tag'])

   # vectorizer = TfidfVectorizer()
   # X = vectorizer.fit_transform(cleaned_word)

   words = sorted(set(words))
   classes = sorted(set(classes))

   def clean_corpus(words):
      words = [doc.lower() for doc in words]
      for w in words:
         if w not in stop_words and w.isalpha():
               w=lemmatizer.lemmatize(w)
               cleaned_word.append(w)
      return(cleaned_word)

   cleaned_list = clean_corpus(words)

   words = sorted(set(words))
   classes = sorted(set(classes))
   # y = encoder.fit_transfrom(np.array(classes), reshape(-1, 1))

   training =[]
   output_empty = [0] * len(classes)


   for document in documents:
      bag =[]
      word_patterns = document[0]

      word_patterns = [lemmatizer.lemmatize(word.lower()) for word in word_patterns]

      for word in words :
         bag.append(1) if word in word_patterns else bag.append(0)
      output_row = list(output_empty)
      output_row[classes.index(document[1])] = 1 
      training.append([bag,output_row])

   '''Neural Network'''
   random.shuffle(training)
   training = np.array(training,dtype=object)
   train_x = list(training[:,0])
   train_y = list(training[:,1])

   model = Sequential([Dense(128, input_shape = (len(train_x[0]),),activation='relu'),Dropout(0.2),Dense(64, activation='relu'),Dropout(0.2),Dense(len(train_y[0]),activation = 'softmax')])
   sgd = tensorflow.keras.optimizers.SGD(learning_rate=0.01, decay = 1e-6, momentum = 0.9, nesterov = True)
   model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
   history = model.fit(np.array(train_x),np.array(train_y),epochs=20,batch_size=1,verbose=7)
   # model.save('chatbot_model.model',history)


   def cleaning_up_message(message):
      message_word = word_tokenize(message)
      message_word = [lemmatizer.lemmatize(word.casefold()) for word in message_word]
      return message_word


   def bag_of_words(message):
      message_word = cleaning_up_message(message)
      bag = [0]*len(words)
      for w in message_word:
         for i, word in enumerate(words):
               if word == w:
                  bag[i] = 1
      return np.array(bag)
      
   INTENT_NOT_FOUND_THRESHOLD = 0.25

   def predict_intent_tag(message):
      BOW = bag_of_words(message)
      res = model.predict(np.array([BOW]))[0]
      results = [[i,r] for i,r in enumerate(res) if r > INTENT_NOT_FOUND_THRESHOLD ]
      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]) })
      return return_list

   def get_response(intents_list , intents_json):
      tag = intents_list[0]['intent']
      list_of_intents = intents_json['intents']
      for i in list_of_intents:
         if i['tag'] == tag :
               result= random.choice (i['responses'])
               break
         # elif i['tag']!=tag:
         #     result=random.choice(["Invalid response","Sorry:), I didn't get what you are saying","Pardon me..!"])
         #     break
      return result

   print(" Aapi is Running ! ")
   message = query
   ints = predict_intent_tag(message)
   bot_response = get_response(ints, readobj)
   # print(bot_response)
   return JsonResponse({"Bot": bot_response})
   

chatbot_project/views.py
tinker0830/Aapi-Ai-Django-ChatBot
"""
Django settings for project project.

Generated by 'django-admin startproject' using Django 4.0.

For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""

from pathlib import Path
from tempfile import template
from dotenv import load_dotenv
import os

load_dotenv()

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'chatbot_project'
]

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',
]

ROOT_URLCONF = 'project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS':['templates'],
        '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 = 'project.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

project/settings.py
tinker0830/Aapi-Ai-Django-ChatBot
"""project URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path , include

urlpatterns = [
    path('admin/',admin.site.urls),
    path('', include(('chatbot_project.urls2','chatbot_project'),namespace = 'chatbot_project')),
    path('home/', include(('chatbot_project.urls2','chatbot_project'),namespace = 'chatbot_project2')),
    
]

project/urls.py
tinker0830/Aapi-Ai-Django-ChatBot