├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── chatbot_project ├── __init__.py ├── admin.py ├── apps.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_alter_response_myquery.py │ ├── 0003_topic_alter_response_myquery.py │ ├── 0004_delete_topic_rename_myquery_response_text.py │ └── __init__.py ├── models.py ├── static │ └── chatbot_project │ │ ├── images │ │ ├── bot.png │ │ └── user.png │ │ └── stylesheets │ │ └── staticStyle.css ├── templates │ └── chatbot_project │ │ └── index.htm ├── tests.py ├── urls2.py └── views.py ├── jsonfile.json ├── manage.py ├── project ├── __init__.py ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py └── requirements.txt /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 16 | 17 | **Expected behavior** 18 | A clear and concise description of what you expected to happen. 19 | 20 | **Screenshots** 21 | If applicable, add screenshots to help explain your problem. 22 | 23 | **Desktop (please complete the following information):** 24 | - OS: [e.g. iOS] 25 | - Browser [e.g. chrome, safari] 26 | - Version [e.g. 22] 27 | 28 | **Additional context** 29 | Add any other context about the problem here. 30 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | db.sqlite3 2 | .env 3 | .vscode 4 | __pycache__ -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | groupchatbot01@gmail.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guide 🤖 2 | The project is built with Django and HTML, CSS, JS. 3 | 4 | ## Local Setup 5 | - [Fork](https://github.com/PranavDalvi/Django-ChatBot/fork) this repository. 6 | - *Note: You need python and some of its libries like (django, nltk, numpy, tensorflow) to run and test the code which can be install pip* 7 | - requirements.txt has details of all the dependencies which are needed to run this project. To run the project steps are given below: 8 | 9 | - To understand the steps given below, you should know how to create a new Django project and a Python virtual environment. 10 | 1. Download the required libraries from requirements.txt (Python virtual environment is required). 11 | 2. Create a new Django project. (why? Because we will need a `secret key` to run the project). 12 | 3. Open the newly created Django project and copy the full string of secret key from `settings.py`. 13 | 4. Now open the ChatBot project then open the project folder and create a new file named as `.env` and paste the secret key. 14 | - .env file should look like this: 15 | ``` 16 | SECRET_KEY = 'dlm*zt#1-3g!xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' 17 | ``` 18 | 5. Do the migrations and run the project. 19 | 20 | ## Hello First-time Contributors 👋 21 | - There are lot of resources (articles, courses, videos) available for getting started with git and GitHub you can search and follow any of the resource you like. 22 | - You can pick any of the issues from [Issues](https://github.com/PranavDalvi/Django-ChatBot/issues) or If you feel like it needs extra feature or if you find bug, you can create your own issue. 23 | - You can drop a comment on issue saying "Hi, let me work on this" to avoid multiple people working on the same PR. 24 | - Lastly, It is fine if you mess something up. If there is anything wrong in the PR I will let you know how to fix that in comments of the PR. 25 | - If you are still scared to drop a PR or need any help, you can always drop us an email at groupchatbot01@gmail.com. 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Pranav Dalvi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Aapi (Artificial Intelligence ChatBot) 2 | Aapi (or âpi) is derived from 'Sanskrit Literature', meaning : Friend, associate or acquaintance. 3 | 4 | Aapi is a machine learning based intelligent chatbot designed to provide human-like conversation. 5 | Chatbot is created with intention to shorten the gap between business and customer. Similarly Aapi initially is build to increase educational efficiency by reducing the gap between a student and college. 6 | 7 | Aapi is build with passion and love by 3 friends [Pranav Dalvi](https://github.com/PranavDalvi), [Aditya Dorge](https://github.com/adityadorge) and [Omkar Pawar](https://github.com/OmkarPawar14) on 12th April 2022. 8 | 9 | # Technologies Used: 10 | - Python3 11 | - Django Framework 12 | - Tensorflow 13 | - NLTK 14 | - Numpy 15 | - HTML, CSS 16 | - JavaScript 17 | 18 | # How to run ChatBot on your computer 🤔 19 | - To understand the steps given below, you should know how to create a new Django project and a Python virtual environment. 20 | 1. Download the required libraries from requirements.txt (Python virtual environment is required). 21 | 2. Create a new Django project. (why? Because we will need a `secret key` to run the project). 22 | 3. Open the newly created Django project and copy the full string of secret key from `settings.py`. 23 | 4. Now open the ChatBot project then open the project folder and create a new file named as `.env` and paste the secret key. 24 | - .env file should look like this: 25 | ``` 26 | SECRET_KEY = 'dlm*zt#1-3g!xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' 27 | ``` 28 | 5. Do the migrations and run the project. 29 | *** 30 | - ChatBot image are taken from [flaticon](https://www.flaticon.com/free-icons/bot) 31 | - User image are taken from [freeiconspng](https://www.freeiconspng.com/img/7563) 32 | -------------------------------------------------------------------------------- /chatbot_project/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Phoenix-Genius/Aapi-Ai-Django-ChatBot/68f243c1b776e7057140ee01f695bac722d692fd/chatbot_project/__init__.py -------------------------------------------------------------------------------- /chatbot_project/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from chatbot_project.models import Response 4 | 5 | # Register your models here. 6 | admin.site.register(Response) 7 | # admin.site.register(Topic) 8 | -------------------------------------------------------------------------------- /chatbot_project/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ChatbotProjectConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'chatbot_project' 7 | -------------------------------------------------------------------------------- /chatbot_project/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 4.0 on 2022-03-02 07:17 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Response', 16 | fields=[ 17 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('myquery', models.CharField(max_length=200)), 19 | ], 20 | ), 21 | ] 22 | -------------------------------------------------------------------------------- /chatbot_project/migrations/0002_alter_response_myquery.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 4.0 on 2022-03-02 07:33 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ('chatbot_project', '0001_initial'), 10 | ] 11 | 12 | operations = [ 13 | migrations.AlterField( 14 | model_name='response', 15 | name='myquery', 16 | field=models.TextField(max_length=200), 17 | ), 18 | ] 19 | -------------------------------------------------------------------------------- /chatbot_project/migrations/0003_topic_alter_response_myquery.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 4.0 on 2022-03-02 07:39 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ('chatbot_project', '0002_alter_response_myquery'), 10 | ] 11 | 12 | operations = [ 13 | migrations.CreateModel( 14 | name='Topic', 15 | fields=[ 16 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 17 | ('myquery', models.CharField(max_length=200)), 18 | ], 19 | ), 20 | migrations.AlterField( 21 | model_name='response', 22 | name='myquery', 23 | field=models.TextField(), 24 | ), 25 | ] 26 | -------------------------------------------------------------------------------- /chatbot_project/migrations/0004_delete_topic_rename_myquery_response_text.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 4.0 on 2022-03-02 07:59 2 | 3 | from django.db import migrations 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ('chatbot_project', '0003_topic_alter_response_myquery'), 10 | ] 11 | 12 | operations = [ 13 | migrations.DeleteModel( 14 | name='Topic', 15 | ), 16 | migrations.RenameField( 17 | model_name='response', 18 | old_name='myquery', 19 | new_name='text', 20 | ), 21 | ] 22 | -------------------------------------------------------------------------------- /chatbot_project/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Phoenix-Genius/Aapi-Ai-Django-ChatBot/68f243c1b776e7057140ee01f695bac722d692fd/chatbot_project/migrations/__init__.py -------------------------------------------------------------------------------- /chatbot_project/models.py: -------------------------------------------------------------------------------- 1 | from cgitb import text 2 | from dataclasses import field 3 | from pydoc_data.topics import topics 4 | from tabnanny import verbose 5 | from django.db import models 6 | 7 | class Response(models.Model): 8 | text = models.TextField() 9 | class meta: 10 | verbose_name_plural = "Responses" 11 | 12 | def __str__(self): 13 | return self.text 14 | 15 | 16 | -------------------------------------------------------------------------------- /chatbot_project/static/chatbot_project/images/bot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Phoenix-Genius/Aapi-Ai-Django-ChatBot/68f243c1b776e7057140ee01f695bac722d692fd/chatbot_project/static/chatbot_project/images/bot.png -------------------------------------------------------------------------------- /chatbot_project/static/chatbot_project/images/user.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Phoenix-Genius/Aapi-Ai-Django-ChatBot/68f243c1b776e7057140ee01f695bac722d692fd/chatbot_project/static/chatbot_project/images/user.png -------------------------------------------------------------------------------- /chatbot_project/static/chatbot_project/stylesheets/staticStyle.css: -------------------------------------------------------------------------------- 1 | :root { 2 | --chatBot_ZIndex: 100; 3 | /*Z-Index to keep Chat Bot top of all other elements*/ 4 | --chatBot_windowCommonRadius: 5px; 5 | } 6 | 7 | * { 8 | margin: 0; 9 | padding: 0; 10 | font-family: sans-serif; 11 | box-sizing: border-box; 12 | } 13 | 14 | body { 15 | background-color: #f8f8f8; 16 | display: flex; 17 | flex-direction: column; 18 | flex-wrap: nowrap; 19 | justify-content: space-evenly; 20 | align-items: center; 21 | } 22 | 23 | .showBot { 24 | position: absolute; 25 | right: 30px; 26 | /*Right and bottom are set to position the chat bot window in the right-corner of the screen*/ 27 | bottom: 25px; 28 | padding: 10px 40px 10px 37px; 29 | font-size: 18px; 30 | border: none; 31 | border-radius: var(--chatBot_windowCommonRadius); 32 | outline: none; 33 | background-color: dodgerblue; 34 | color: #f8f8f8; 35 | box-shadow: 10px 10px 5px #aaaaaa; 36 | cursor: pointer; 37 | } 38 | 39 | .container { 40 | position: absolute; 41 | right: 30px; 42 | /*Right and bottom are set to position the chat bot window in the right-corner of the screen*/ 43 | bottom: 60px; 44 | width: 450px; 45 | height: 80vh; 46 | display: flex; 47 | flex-direction: column; 48 | box-shadow: 10px 10px 5px #aaaaaa; 49 | background-color: dodgerblue; 50 | border: 2px solid dodgerblue; 51 | border-radius: var(--chatBot_windowCommonRadius); 52 | z-index: var(--chatBot_ZIndex); 53 | } 54 | 55 | .header { 56 | display: flex; 57 | flex-direction: row; 58 | flex-wrap: nowrap; 59 | justify-content: space-between; 60 | } 61 | 62 | .header h1 { 63 | color: white; 64 | padding: 15px; 65 | } 66 | 67 | .header img { 68 | width: 70px; 69 | padding: 10px; 70 | } 71 | 72 | .body { 73 | display: flex; 74 | flex: 1; 75 | color: white; 76 | background-color: rgba(0, 0, 0, 0.7); 77 | margin-top: auto; 78 | overflow-y: scroll; 79 | flex-direction: column-reverse; 80 | scroll-behavior: smooth; 81 | padding: 20px 10px; 82 | border-radius: 5px 5px 0px 0px; 83 | -ms-overflow-style: none; 84 | /* IE and Edge */ 85 | scrollbar-width: none; 86 | /* Firefox */ 87 | } 88 | 89 | .body::-webkit-scrollbar { 90 | display: none; 91 | } 92 | 93 | .botTyping-bg { 94 | background-color: rgba(0, 0, 0, 0.7); 95 | padding: 0px 0px 10px 20px; 96 | } 97 | 98 | .botTyping { 99 | margin-right: 60%; 100 | color: #fff; 101 | } 102 | 103 | .bot_message { 104 | background-color: dodgerblue; 105 | padding: 10px; 106 | color: white; 107 | width: fit-content; 108 | border-top-left-radius: 0px !important; 109 | border-radius: 10px; 110 | margin-bottom: 15px; 111 | } 112 | 113 | .user_message { 114 | margin-left: auto; 115 | background-color: white; 116 | color: black; 117 | padding: 10px; 118 | width: fit-content; 119 | border-top-right-radius: 0px !important; 120 | border-radius: 10px; 121 | margin-bottom: 15px; 122 | } 123 | 124 | .bot-profile { 125 | width: 13%; 126 | padding-right: 5px; 127 | } 128 | 129 | .user-profile { 130 | width: 12%; 131 | padding-left: 5px; 132 | } 133 | 134 | .bot-message-block { 135 | display: flex; 136 | align-items: baseline; 137 | } 138 | 139 | .user-message-block { 140 | display: flex; 141 | align-items: baseline; 142 | flex-direction: row-reverse; 143 | } 144 | 145 | .footer { 146 | display: flex; 147 | } 148 | 149 | .footer input { 150 | flex: 1; 151 | height: 40px; 152 | border: none; 153 | border-radius: 0px 0px 0px 5px; 154 | outline: none; 155 | padding-left: 5px; 156 | font-size: 16px; 157 | } 158 | 159 | .footer button { 160 | width: 100px; 161 | font-size: 18px; 162 | border: none; 163 | border-radius: 0px 0px 5px 0px; 164 | outline: none; 165 | background-color: dodgerblue; 166 | color: white; 167 | cursor: pointer; 168 | transition: background-color 0.3s ease; 169 | } 170 | 171 | .footer button:hover { 172 | background-color: blue; 173 | } 174 | 175 | .footer button:disabled { 176 | background-color: #aaaaaa; 177 | } 178 | 179 | .showBot:hover { 180 | background-color: blue; 181 | } 182 | 183 | .hideBot { 184 | padding: 10px; 185 | font-size: 18px; 186 | border: none; 187 | outline: none; 188 | background-color: dodgerblue; 189 | color: white; 190 | cursor: pointer; 191 | } 192 | 193 | .aapi-popup-dialog { 194 | position: absolute; 195 | right: 30px; 196 | bottom: 95px; 197 | font-size: 18px; 198 | padding: 10px 10px 10px 10px; 199 | border: none; 200 | border-radius: var(--chatBot_windowCommonRadius); 201 | outline: none; 202 | background-color: dodgerblue; 203 | color: #f8f8f8; 204 | } 205 | 206 | .attention { 207 | position: absolute; 208 | right: 25px; 209 | bottom: 145px; 210 | padding: 10px; 211 | border-radius: 100%; 212 | background-color: red; 213 | } 214 | 215 | .down-triangle { 216 | width: 0; 217 | height: 0; 218 | position: absolute; 219 | right: 68px; 220 | bottom: 75px; 221 | border: 20px solid transparent; 222 | border-top: 20px solid dodgerblue; 223 | border-bottom: 0; 224 | } 225 | 226 | .hidden { 227 | display: none; 228 | } 229 | -------------------------------------------------------------------------------- /chatbot_project/templates/chatbot_project/index.htm: -------------------------------------------------------------------------------- 1 | {% load static %} 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | PYBOT 11 | 12 | 13 | 14 | 15 | 16 | 82 | 83 | 84 | 85 | 86 | 87 | 115 | 116 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 320 | 321 | 322 | 323 | -------------------------------------------------------------------------------- /chatbot_project/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /chatbot_project/urls2.py: -------------------------------------------------------------------------------- 1 | """project URL Configuration 2 | The `urlpatterns` list routes URLs to views. For more information please see: 3 | https://docs.djangoproject.com/en/4.0/topics/http/urls/ 4 | Examples: 5 | Function views 6 | 1. Add an import: from my_app import views 7 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 8 | Class-based views 9 | 1. Add an import: from other_app.views import Home 10 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 11 | Including another URLconf 12 | 1. Import the include() function: from django.urls import include, path 13 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 14 | """ 15 | from django.contrib import admin 16 | from django.urls import path 17 | from . import views 18 | 19 | urlpatterns = [ 20 | #path('admin/', views.index,name = 'index'), 21 | path('', views.index,name='index'), 22 | path('home/', views.chatBot,name='chatBot') 23 | ] -------------------------------------------------------------------------------- /chatbot_project/views.py: -------------------------------------------------------------------------------- 1 | 2 | import re 3 | from django.http import HttpRequest, JsonResponse 4 | from django.shortcuts import render, HttpResponse 5 | import random 6 | import json 7 | import numpy as np 8 | from nltk.tokenize import word_tokenize 9 | from nltk.stem import WordNetLemmatizer 10 | #from .models import Response, models 11 | 12 | # Remove the comments to download additional nltk packages 13 | # import nltk 14 | # nltk.download('punkt') 15 | # nltk.download('wordnet') 16 | # nltk.download('omw-1.4') 17 | 18 | # from sklearn.feature_extraction.text import TfidfVectorizer 19 | 20 | from tensorflow import keras 21 | import tensorflow 22 | from tensorflow.keras import Sequential 23 | from tensorflow.keras.layers import Dense, Dropout 24 | 25 | def index(request): 26 | return render(request , 'chatbot_project/index.htm') 27 | 28 | 29 | def chatBot(request): 30 | query = str(request.GET.get("query")) 31 | # print(query) 32 | lemmatizer=WordNetLemmatizer() 33 | 34 | with open('jsonfile.json') as fileobj: 35 | readobj=json.load(fileobj) 36 | 37 | words=[] 38 | classes=[] 39 | documents=[] 40 | stop_words=['is','and','the','a','are','i','it'] 41 | cleaned_word=[] 42 | 43 | for intent in readobj['intents']: 44 | for pattern in intent['patterns']: 45 | word_list=word_tokenize(pattern) 46 | words.extend(word_list) 47 | documents.append((word_list,intent['tag'])) 48 | if intent['tag'] not in classes: 49 | classes.append(intent['tag']) 50 | 51 | # vectorizer = TfidfVectorizer() 52 | # X = vectorizer.fit_transform(cleaned_word) 53 | 54 | words = sorted(set(words)) 55 | classes = sorted(set(classes)) 56 | 57 | def clean_corpus(words): 58 | words = [doc.lower() for doc in words] 59 | for w in words: 60 | if w not in stop_words and w.isalpha(): 61 | w=lemmatizer.lemmatize(w) 62 | cleaned_word.append(w) 63 | return(cleaned_word) 64 | 65 | cleaned_list = clean_corpus(words) 66 | 67 | words = sorted(set(words)) 68 | classes = sorted(set(classes)) 69 | # y = encoder.fit_transfrom(np.array(classes), reshape(-1, 1)) 70 | 71 | training =[] 72 | output_empty = [0] * len(classes) 73 | 74 | 75 | for document in documents: 76 | bag =[] 77 | word_patterns = document[0] 78 | 79 | word_patterns = [lemmatizer.lemmatize(word.lower()) for word in word_patterns] 80 | 81 | for word in words : 82 | bag.append(1) if word in word_patterns else bag.append(0) 83 | output_row = list(output_empty) 84 | output_row[classes.index(document[1])] = 1 85 | training.append([bag,output_row]) 86 | 87 | '''Neural Network''' 88 | random.shuffle(training) 89 | training = np.array(training,dtype=object) 90 | train_x = list(training[:,0]) 91 | train_y = list(training[:,1]) 92 | 93 | 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')]) 94 | sgd = tensorflow.keras.optimizers.SGD(learning_rate=0.01, decay = 1e-6, momentum = 0.9, nesterov = True) 95 | model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy']) 96 | history = model.fit(np.array(train_x),np.array(train_y),epochs=20,batch_size=1,verbose=7) 97 | # model.save('chatbot_model.model',history) 98 | 99 | 100 | def cleaning_up_message(message): 101 | message_word = word_tokenize(message) 102 | message_word = [lemmatizer.lemmatize(word.casefold()) for word in message_word] 103 | return message_word 104 | 105 | 106 | def bag_of_words(message): 107 | message_word = cleaning_up_message(message) 108 | bag = [0]*len(words) 109 | for w in message_word: 110 | for i, word in enumerate(words): 111 | if word == w: 112 | bag[i] = 1 113 | return np.array(bag) 114 | 115 | INTENT_NOT_FOUND_THRESHOLD = 0.25 116 | 117 | def predict_intent_tag(message): 118 | BOW = bag_of_words(message) 119 | res = model.predict(np.array([BOW]))[0] 120 | results = [[i,r] for i,r in enumerate(res) if r > INTENT_NOT_FOUND_THRESHOLD ] 121 | results.sort(key = lambda x : x[1] , reverse = True) 122 | return_list = [] 123 | for r in results: 124 | return_list.append({ 'intent': classes[r[0]], 'probability': str(r[1]) }) 125 | return return_list 126 | 127 | def get_response(intents_list , intents_json): 128 | tag = intents_list[0]['intent'] 129 | list_of_intents = intents_json['intents'] 130 | for i in list_of_intents: 131 | if i['tag'] == tag : 132 | result= random.choice (i['responses']) 133 | break 134 | # elif i['tag']!=tag: 135 | # result=random.choice(["Invalid response","Sorry:), I didn't get what you are saying","Pardon me..!"]) 136 | # break 137 | return result 138 | 139 | print(" Aapi is Running ! ") 140 | message = query 141 | ints = predict_intent_tag(message) 142 | bot_response = get_response(ints, readobj) 143 | # print(bot_response) 144 | return JsonResponse({"Bot": bot_response}) 145 | 146 | -------------------------------------------------------------------------------- /jsonfile.json: -------------------------------------------------------------------------------- 1 | { 2 | "intents": [ 3 | { 4 | "tag": "greetings1", 5 | "patterns": [ 6 | "Hi how are you?" 7 | ], 8 | "responses": [ 9 | "Hello! How can I help you today?", 10 | "Hello :)" 11 | ] 12 | 13 | }, 14 | { 15 | "tag":"greetings2", 16 | "patterns": [ 17 | "How are you doing?", 18 | "How are you?", 19 | "Hi how are you?", 20 | "Hello how are you?" 21 | ], 22 | "responses": [ 23 | "I'm fine what about you?", 24 | "Thanks for asking! I'm excellent. How about you?", 25 | "You know, according to my lawyer, I don't have to answer that.", 26 | "Fine, thanks. What do you got for me today?" 27 | ] 28 | }, 29 | { 30 | "tag": "name", 31 | "patterns": [ 32 | "What is your name?", 33 | "What should I call you?", 34 | "who are you?" 35 | ], 36 | "responses": [ 37 | "I'm Aapi and I'm here to help you out ;)" 38 | ] 39 | }, 40 | { 41 | "tag":"help", 42 | "patterns": [ 43 | "help", 44 | "Help", 45 | "Help!", 46 | "help!" 47 | ], 48 | "responses":[ 49 | "Ok, you can ask me about:
Admission process for degree, PG, Junior.
College contact details.
Extra curricular activities.
Exam details.
and about placements." 50 | ] 51 | }, 52 | { 53 | "tag": "admission-degree", 54 | "patterns": [ 55 | "What is the admission process for degree?", 56 | "How to take admission for degree?", 57 | "I want to take admission for degree" 58 | ], 59 | "responses": [ 60 | "https://kirticollege.edu.in/category/degree-admission-notices/" 61 | ] 62 | }, 63 | { 64 | "tag": "admission-pg", 65 | "patterns": [ 66 | "What is the admission process for PG?", 67 | "How to take admission for Post?", 68 | "I want to take admission for PG" 69 | ], 70 | "responses": [ 71 | "https://kirticollege.edu.in/category/post-graduation-notices/" 72 | ] 73 | }, 74 | { 75 | "tag": "admission-junior", 76 | "patterns": [ 77 | "What is the admission process for junior?", 78 | "How to take admission for junior?", 79 | "I want to take admission for junior" 80 | ], 81 | "responses": [ 82 | "https://kirticollege.edu.in/#" 83 | ] 84 | }, 85 | { 86 | "tag": "services", 87 | "patterns": [ 88 | "What is the college number?", 89 | "What is the college staff number?", 90 | "What is the college contact?", 91 | "what is the contact details?", 92 | "How to contact college?" 93 | ], 94 | "responses": [ 95 | "https://kirticollege.edu.in/contact-us/" 96 | ] 97 | }, 98 | { 99 | "tag": "sport", 100 | "patterns": [ 101 | "Is sports available in college?", 102 | "Is NCC available in college?", 103 | "Is NSS available in college?", 104 | "What extra curricular activities are there in college?" 105 | ], 106 | "responses": [ 107 | "Please contact college" 108 | ] 109 | }, 110 | { 111 | "tag": "exam", 112 | "patterns": [ 113 | "when is my exam?", 114 | "Give me exam details" 115 | ], 116 | "responses": [ 117 | "https://livestudent.deccansociety.org/" 118 | ] 119 | }, 120 | { 121 | "tag": "placement", 122 | "patterns": [ 123 | "What is the placement process?", 124 | "Which companies comes to college?", 125 | "How to seat for on campus placement?", 126 | "college placement reviews ? " 127 | ], 128 | "responses": [ 129 | "Contact Collage Placement Cell" 130 | ] 131 | }, 132 | { 133 | "tag": "goodbye", 134 | "patterns": [ 135 | "Good Bye Aapi", 136 | "See You later", 137 | "Till next time", 138 | "meet you later" 139 | ], 140 | "responses": [ 141 | "See you, Have a nice day :)", 142 | "Bye,Come back soon! ", 143 | "Thanks For Asking! " 144 | ] 145 | }, 146 | { 147 | "tag": "noans", 148 | "patterns": [ 149 | "why", 150 | "how", 151 | "when", 152 | "I", 153 | "you" 154 | ], 155 | "responses": [ 156 | "Hey there!, I'm still learning stuff can you please elaborate it?" 157 | ] 158 | } 159 | ] 160 | } 161 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /project/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Phoenix-Genius/Aapi-Ai-Django-ChatBot/68f243c1b776e7057140ee01f695bac722d692fd/project/__init__.py -------------------------------------------------------------------------------- /project/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for project project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /project/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for project project. 3 | 4 | Generated by 'django-admin startproject' using Django 4.0. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/4.0/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | from tempfile import template 15 | from dotenv import load_dotenv 16 | import os 17 | 18 | load_dotenv() 19 | 20 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 21 | BASE_DIR = Path(__file__).resolve().parent.parent 22 | 23 | 24 | # Quick-start development settings - unsuitable for production 25 | # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ 26 | 27 | # SECURITY WARNING: keep the secret key used in production secret! 28 | SECRET_KEY = os.getenv('SECRET_KEY') 29 | 30 | # SECURITY WARNING: don't run with debug turned on in production! 31 | DEBUG = True 32 | 33 | ALLOWED_HOSTS = [] 34 | 35 | 36 | # Application definition 37 | 38 | INSTALLED_APPS = [ 39 | 'django.contrib.admin', 40 | 'django.contrib.auth', 41 | 'django.contrib.contenttypes', 42 | 'django.contrib.sessions', 43 | 'django.contrib.messages', 44 | 'django.contrib.staticfiles', 45 | 'chatbot_project' 46 | ] 47 | 48 | MIDDLEWARE = [ 49 | 'django.middleware.security.SecurityMiddleware', 50 | 'django.contrib.sessions.middleware.SessionMiddleware', 51 | 'django.middleware.common.CommonMiddleware', 52 | 'django.middleware.csrf.CsrfViewMiddleware', 53 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 54 | 'django.contrib.messages.middleware.MessageMiddleware', 55 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 56 | ] 57 | 58 | ROOT_URLCONF = 'project.urls' 59 | 60 | TEMPLATES = [ 61 | { 62 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 63 | 'DIRS':['templates'], 64 | 'APP_DIRS': True, 65 | 'OPTIONS': { 66 | 'context_processors': [ 67 | 'django.template.context_processors.debug', 68 | 'django.template.context_processors.request', 69 | 'django.contrib.auth.context_processors.auth', 70 | 'django.contrib.messages.context_processors.messages', 71 | ], 72 | }, 73 | }, 74 | ] 75 | 76 | WSGI_APPLICATION = 'project.wsgi.application' 77 | 78 | 79 | # Database 80 | # https://docs.djangoproject.com/en/4.0/ref/settings/#databases 81 | 82 | DATABASES = { 83 | 'default': { 84 | 'ENGINE': 'django.db.backends.sqlite3', 85 | 'NAME': BASE_DIR / 'db.sqlite3', 86 | } 87 | } 88 | 89 | 90 | # Password validation 91 | # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators 92 | 93 | AUTH_PASSWORD_VALIDATORS = [ 94 | { 95 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 96 | }, 97 | { 98 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 99 | }, 100 | { 101 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 102 | }, 103 | { 104 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 105 | }, 106 | ] 107 | 108 | 109 | # Internationalization 110 | # https://docs.djangoproject.com/en/4.0/topics/i18n/ 111 | 112 | LANGUAGE_CODE = 'en-us' 113 | 114 | TIME_ZONE = 'UTC' 115 | 116 | USE_I18N = True 117 | 118 | USE_TZ = True 119 | 120 | 121 | # Static files (CSS, JavaScript, Images) 122 | # https://docs.djangoproject.com/en/4.0/howto/static-files/ 123 | 124 | STATIC_URL = 'static/' 125 | 126 | # Default primary key field type 127 | # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field 128 | 129 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 130 | -------------------------------------------------------------------------------- /project/urls.py: -------------------------------------------------------------------------------- 1 | """project URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/4.0/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path , include 18 | 19 | urlpatterns = [ 20 | path('admin/',admin.site.urls), 21 | path('', include(('chatbot_project.urls2','chatbot_project'),namespace = 'chatbot_project')), 22 | path('home/', include(('chatbot_project.urls2','chatbot_project'),namespace = 'chatbot_project2')), 23 | 24 | ] 25 | -------------------------------------------------------------------------------- /project/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for project project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Django==4.0.4 2 | nltk==3.7 3 | numpy==1.22.3 4 | python-dotenv==0.20.0 5 | tensorflow==2.8.0 6 | virtualenv==20.14.1 7 | virtualenv-clone==0.5.7 8 | python3 == 3.10.4 9 | --------------------------------------------------------------------------------