File size: 14,923 Bytes
6bc5fb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f0ce57f4-5984-43e6-b3bb-60f2d9251d75",
   "metadata": {},
   "source": [
    "# Implementation of Chatbot using Natural Language Processing(NLP)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c062c6e-0773-4af8-bcb9-aa33f7afeb25",
   "metadata": {},
   "source": [
    "### Importing necessary libraries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "23417a10-2691-4887-b02e-2448f6200cd1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import nltk\n",
    "import random\n",
    "import os\n",
    "import ssl\n",
    "import streamlit as st\n",
    "from sklearn.svm import SVC\n",
    "from sklearn.feature_extraction.text import TfidfVectorizer\n",
    "from sklearn.linear_model import LogisticRegression"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1dc3d789-6567-4266-bd33-005aed1d4e93",
   "metadata": {},
   "source": [
    "### Bypass SSL verification for NLTK downloads"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "298e3201-b127-4c68-b041-2a22ace29340",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[nltk_data] Downloading package punkt to\n",
      "[nltk_data]     C:\\Users\\LENOVO\\AppData\\Roaming\\nltk_data...\n",
      "[nltk_data]   Package punkt is already up-to-date!\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ssl._create_default_https_context = ssl._create_unverified_context\n",
    "nltk.data.path.append(os.path.abspath('nltk_data'))\n",
    "nltk.download('punkt')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62d1be3d-37b1-4ab3-a527-9185e183ac98",
   "metadata": {},
   "source": [
    "### Intent dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "a4c238c5-fe25-4802-9328-70ec7b064044",
   "metadata": {},
   "outputs": [],
   "source": [
    "intents = [\n",
    "    {\n",
    "        \"atag\": \"greeting\", \"patterns\": [\"Hi\", \"Hello\", \"Hey\", \"What's up\", \"How are you\"],\n",
    "         \"responses\": [\"Hi there!\", \"Hello!\", \"Hey!\", \"Nothing much.\", \"I'm fine, thank you.\"]\n",
    "    },\n",
    "    {\n",
    "        \"tag\": \"goodbye\", \"patterns\": [\"Bye\", \"See you later\", \"Goodbye\", \"Take care\"],\n",
    "         \"responses\": [\"Goodbye!\", \"See you later!\", \"Take care!\"]\n",
    "    },\n",
    "    {\n",
    "        \"tag\": \"thanks\", \"patterns\": [\"Thank you\", \"Thanks\", \"Thanks a lot\", \"I appreciate it\"],\n",
    "         \"responses\": [\"You're welcome!\", \"No problem!\", \"Glad I could help!\"]\n",
    "    },\n",
    "    {\n",
    "        \"tag\": \"about\", \"patterns\": [\"What can you do\", \"Who are you\", \"What are you\", \"What is your purpose\"],\n",
    "         \"responses\": [\"I am a chatbot.\", \"My purpose is to assist you.\", \"I can answer questions and provide assistance.\"]\n",
    "    },\n",
    "    {\n",
    "        \"tag\": \"help\", \"patterns\": [\"Help\", \"I need help\", \"Can you help me\", \"What should I do\"],\n",
    "         \"responses\": [\"Sure, what do you need help with?\", \"I'm here to help. What's the problem?\", \"How can I assist you?\"]\n",
    "    },\n",
    "    {\n",
    "        \"tag\": \"age\", \"patterns\": [\"How old are you\", \"What's your age\"],\n",
    "         \"responses\": [\"I don't have an age. I'm a chatbot.\", \"I was just born in the digital world.\", \"Age is just a number for me.\"]\n",
    "    },\n",
    "    {\n",
    "        \"tag\": \"weather\", \"patterns\": [\"What's the weather like\", \"How's the weather today\"],\n",
    "         \"responses\": [\"I'm sorry, I cannot provide real-time weather information.\", \"You can check the weather on a weather app or website.\"]\n",
    "    },\n",
    "    {\n",
    "        \"tag\": \"budget\", \"patterns\": [\"How can I make a budget\", \"What's a good budgeting strategy\", \"How do I create a budget\"],\n",
    "        \"responses\": [\"Start by tracking your income and expenses. Allocate money for essentials, savings, and discretionary spending.\",\n",
    "         \"A good strategy is the 50/30/20 rule: 50% for needs, 30% for wants, and 20% for savings and debt.\",\n",
    "         \"Set financial goals, monitor expenses, and adjust your budget as needed.\"]\n",
    "    },\n",
    "    {\n",
    "        \"tag\": \"credit_score\", \"patterns\": [\"What is a credit score\", \"How do I check my credit score\", \"How can I improve my credit score\"],\n",
    "        \"responses\": [\"A credit score reflects your creditworthiness and is used by lenders to assess loans.\",\n",
    "         \"Check your credit score on platforms like Credit Karma or Credit Sesame.\",\n",
    "         \"Improve your credit score by paying bills on time, reducing debt, and maintaining good credit utilization.\"]\n",
    "    },\n",
    "    {\n",
    "        \"tag\": \"food\", \"patterns\": [\"What should I eat\", \"Suggest me some food\", \"I am hungry\"],\n",
    "        \"responses\": [\"You could try a healthy salad, a sandwich, or some pasta!\", \"How about some homemade pizza?\", \"A nice bowl of soup and bread would be great!\"]\n",
    "    },\n",
    "    {\n",
    "        \"tag\": \"exercise\", \"patterns\": [\"What exercises should I do\", \"How to stay fit\", \"Suggest a workout\"],\n",
    "        \"responses\": [\"Try a mix of cardio and strength training!\", \"A daily walk and some stretching would help.\", \"Yoga is great for both mind and body!\"]\n",
    "    },\n",
    "    {\n",
    "        \"tag\": \"movies\", \"patterns\": [\"Suggest me a movie\", \"What are some good movies\", \"I want to watch a film\"],\n",
    "         \"responses\": [\"How about an action thriller?\", \"A comedy might lift your mood!\", \"Sci-fi movies are always exciting!\"]\n",
    "    },\n",
    "    {\n",
    "        \"tag\": \"music\", \"patterns\": [\"Suggest me some music\", \"What should I listen to\", \"Recommend a song\"],\n",
    "        \"responses\": [\"Try some relaxing jazz or lo-fi music!\", \"Pop songs are always fun!\", \"How about some classic rock?\"]\n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ece2689-d741-48ea-9659-be9cf20e3033",
   "metadata": {},
   "source": [
    "### Create the vectorizer and classifier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "18d6ccb9-639c-4053-981a-69e2fa7cccca",
   "metadata": {},
   "outputs": [],
   "source": [
    "vectorizer = TfidfVectorizer()\n",
    "clf = SVC(kernel='linear', random_state=0)\n",
    "#clf = LogisticRegression(random_state=0, max_iter=10000)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "09e70e89-e826-432a-9c22-b4097b5ac07f",
   "metadata": {},
   "source": [
    "### Preprocess the data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "aca02fbf-201b-47a6-b46c-ca9e0d4e9334",
   "metadata": {},
   "outputs": [],
   "source": [
    "tags = []\n",
    "patterns = []\n",
    "for intent in intents:\n",
    "    for pattern in intent['patterns']:\n",
    "        tags.append(intent['tag'])\n",
    "        patterns.append(pattern)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e33f4599-2a6b-4b9b-805a-7875b1840eb4",
   "metadata": {},
   "source": [
    "### Training the model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "6d11f50c-7062-46e3-89d2-f6e252e5cf12",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-1 {color: black;}#sk-container-id-1 pre{padding: 0;}#sk-container-id-1 div.sk-toggleable {background-color: white;}#sk-container-id-1 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-1 label.sk-toggleable__label-arrow:before {content: \"\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-1 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-1 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-1 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"\";}#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-1 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-1 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-1 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-1 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-1 div.sk-item {position: relative;z-index: 1;}#sk-container-id-1 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-1 div.sk-item::before, #sk-container-id-1 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-1 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-1 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-1 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-1 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-1 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-1 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-1 div.sk-label-container {text-align: center;}#sk-container-id-1 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-1 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>SVC(kernel=&#x27;linear&#x27;, random_state=0)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" checked><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">SVC</label><div class=\"sk-toggleable__content\"><pre>SVC(kernel=&#x27;linear&#x27;, random_state=0)</pre></div></div></div></div></div>"
      ],
      "text/plain": [
       "SVC(kernel='linear', random_state=0)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = vectorizer.fit_transform(patterns)\n",
    "y = tags\n",
    "clf.fit(x, y)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a75b5c8f-cc42-4afc-b261-bfdbe6c79913",
   "metadata": {},
   "source": [
    "### Python function to chat with the chatbot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "12ac8a47-eac5-440f-ab0e-93686944b34b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def chatbot(input_text):\n",
    "    input_text = vectorizer.transform([input_text])\n",
    "    tag = clf.predict(input_text)[0]\n",
    "    for intent in intents:\n",
    "        if intent['tag'] == tag:\n",
    "            response = random.choice(intent['responses'])\n",
    "            return response"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf1ff963-ebbe-4fac-af82-26d3e3336c33",
   "metadata": {},
   "source": [
    "### Checking our chatbot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "8f469e8a-c8a0-4683-9be0-0aefa67c8cea",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hey!\n"
     ]
    }
   ],
   "source": [
    "user_input = \"Hello\"\n",
    "response = chatbot(user_input)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "f49306db-d7da-4e79-860e-cd6e2985ca58",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Try a mix of cardio and strength training!\n"
     ]
    }
   ],
   "source": [
    "user_input = \"What exercises should I do\"\n",
    "response = chatbot(user_input)\n",
    "print(response)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "GPU(sam)",
   "language": "python",
   "name": "sam"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.20"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}