Skip to content

Commit de600b8

Browse files
committed
chatbot using dialogflow for food orders
1 parent cad8928 commit de600b8

File tree

14 files changed

+868
-0
lines changed

14 files changed

+868
-0
lines changed

19_chatbot_food_business/README.txt

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
Directory structure
2+
===================
3+
backend: Contains Python FastAPI backend code
4+
db: contains the dump of the database. you need to import this into your MySQL db by using MySQL workbench tool
5+
dialogflow_assets: this has training phrases etc. for our intents
6+
frontend: website code
7+
8+
Install these modules
9+
======================
10+
11+
pip install mysql-connector
12+
pip install "fastapi[all]"
13+
14+
OR just run pip install -r backend/requirements.txt to install both in one shot
15+
16+
To start fastapi backend server
17+
================================
18+
1. Go to backend directory in your command prompt
19+
2. Run this command: uvicorn main:app --reload
20+
21+
ngrok for https tunneling
22+
================================
23+
1. To install ngrok, go to https://ngrok.com/download and install ngrok version that is suitable for your OS
24+
2. Extract the zip file and place ngrok.exe in a folder.
25+
3. Open windows command prompt, go to that folder and run this command: ngrok http 80000
26+
27+
NOTE: ngrok can timeout. you need to restart the session if you see session expired message.
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
# Author: Dhaval Patel. Codebasics YouTube Channel
2+
3+
import mysql.connector
4+
global cnx
5+
6+
cnx = mysql.connector.connect(
7+
host="localhost",
8+
user="root",
9+
password="root",
10+
database="pandeyji_eatery"
11+
)
12+
13+
# Function to call the MySQL stored procedure and insert an order item
14+
def insert_order_item(food_item, quantity, order_id):
15+
try:
16+
cursor = cnx.cursor()
17+
18+
# Calling the stored procedure
19+
cursor.callproc('insert_order_item', (food_item, quantity, order_id))
20+
21+
# Committing the changes
22+
cnx.commit()
23+
24+
# Closing the cursor
25+
cursor.close()
26+
27+
print("Order item inserted successfully!")
28+
29+
return 1
30+
31+
except mysql.connector.Error as err:
32+
print(f"Error inserting order item: {err}")
33+
34+
# Rollback changes if necessary
35+
cnx.rollback()
36+
37+
return -1
38+
39+
except Exception as e:
40+
print(f"An error occurred: {e}")
41+
# Rollback changes if necessary
42+
cnx.rollback()
43+
44+
return -1
45+
46+
# Function to insert a record into the order_tracking table
47+
def insert_order_tracking(order_id, status):
48+
cursor = cnx.cursor()
49+
50+
# Inserting the record into the order_tracking table
51+
insert_query = "INSERT INTO order_tracking (order_id, status) VALUES (%s, %s)"
52+
cursor.execute(insert_query, (order_id, status))
53+
54+
# Committing the changes
55+
cnx.commit()
56+
57+
# Closing the cursor
58+
cursor.close()
59+
60+
def get_total_order_price(order_id):
61+
cursor = cnx.cursor()
62+
63+
# Executing the SQL query to get the total order price
64+
query = f"SELECT get_total_order_price({order_id})"
65+
cursor.execute(query)
66+
67+
# Fetching the result
68+
result = cursor.fetchone()[0]
69+
70+
# Closing the cursor
71+
cursor.close()
72+
73+
return result
74+
75+
# Function to get the next available order_id
76+
def get_next_order_id():
77+
cursor = cnx.cursor()
78+
79+
# Executing the SQL query to get the next available order_id
80+
query = "SELECT MAX(order_id) FROM orders"
81+
cursor.execute(query)
82+
83+
# Fetching the result
84+
result = cursor.fetchone()[0]
85+
86+
# Closing the cursor
87+
cursor.close()
88+
89+
# Returning the next available order_id
90+
if result is None:
91+
return 1
92+
else:
93+
return result + 1
94+
95+
# Function to fetch the order status from the order_tracking table
96+
def get_order_status(order_id):
97+
cursor = cnx.cursor()
98+
99+
# Executing the SQL query to fetch the order status
100+
query = f"SELECT status FROM order_tracking WHERE order_id = {order_id}"
101+
cursor.execute(query)
102+
103+
# Fetching the result
104+
result = cursor.fetchone()
105+
106+
# Closing the cursor
107+
cursor.close()
108+
109+
# Returning the order status
110+
if result:
111+
return result[0]
112+
else:
113+
return None
114+
115+
116+
if __name__ == "__main__":
117+
# print(get_total_order_price(56))
118+
# insert_order_item('Samosa', 3, 99)
119+
# insert_order_item('Pav Bhaji', 1, 99)
120+
# insert_order_tracking(99, "in progress")
121+
print(get_next_order_id())
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
from fastapi import FastAPI
2+
from fastapi import Request
3+
from fastapi.responses import JSONResponse
4+
import random
5+
import ssl
6+
import uvicorn
7+
8+
app = FastAPI()
9+
10+
11+
@app.post("/")
12+
async def handle_request(request: Request):
13+
# Retrieve the JSON data from the request
14+
payload = await request.json()
15+
16+
# Extract the necessary information from the payload
17+
# based on the structure of the WebhookRequest from Dialogflow
18+
intent = payload['queryResult']['intent']['displayName']
19+
parameters = payload['queryResult']['parameters']
20+
21+
intent_handler_dict = {
22+
'course.price': handle_course_price,
23+
'eligibility.age': handle_eligibiliy_age,
24+
'eligibility.background': handle_eligibility_background
25+
}
26+
27+
return intent_handler_dict[intent](parameters)
28+
29+
30+
def handle_course_price(parameters: dict):
31+
course_name = parameters["course-name"]
32+
country = parameters["geo-country"]
33+
34+
price_dict = {
35+
"SQL": 900,
36+
"Power BI": 2400,
37+
"Python": 800,
38+
"Excel": 700,
39+
"Data Analytics Bootcamp": 4800
40+
}
41+
42+
course_price = price_dict.get(course_name)
43+
44+
response = {
45+
"fulfillmentText": f"The course price for {course_name} is : {course_price}"
46+
}
47+
48+
return JSONResponse(content=response)
49+
50+
def handle_eligibiliy_age(parameters: dict):
51+
course_name = parameters["course-name"]
52+
age = parameters["age"]["amount"]
53+
54+
if age>30:
55+
answer = random.choice([
56+
'''There are many folks who have learned necessary data analyst skills at a later age
57+
and successfully transitioned into a data analyst role. I know one person who made this transition
58+
at the age of 51 and his past background was physical therapist. I've a video on my YouTube channel
59+
that has few such stories highlighted, please watch that to get
60+
some tips: https://www.youtube.com/watch?v=nkvInnpuic8
61+
In short: we believe it is possible to learn data analytics at this age
62+
''',
63+
'''
64+
Hey, It is a common perception that at a later age it is hard to learn new things and switch your career
65+
but to be honest I personally know many folks who learned data analytics, data science at 40+ age and made
66+
this transition. One other person I know was a physical therapist till age 51 and now he is a data
67+
analyst working in a healthcare company. Watch this video to know about few such
68+
stories: https://www.youtube.com/watch?v=nkvInnpuic8
69+
In short, it is 100% possible, if you have an eagerness to learn and a commitment
70+
towards making this career switch.
71+
Also one great thing about data analyst career is it requires very less coding so it will not
72+
be very difficult for you! So yes, you can learn data analysis at your age.
73+
'''
74+
])
75+
76+
else:
77+
answer ="Your age is less than 30 and you are too young to learn anything. Just do it my friend."
78+
79+
if course_name:
80+
answer += " And yes you are eligible for " + "".join(course_name)
81+
82+
return JSONResponse(content={
83+
"fulfillmentText": answer
84+
})
85+
86+
87+
def handle_eligibility_background(parameters: dict):
88+
course_name = parameters["course-name"]
89+
background = parameters["degree-or-situation"]
90+
91+
if background:
92+
if background == "Mechanical Engineer":
93+
answer = '''I know many Mechanical Engineers who have successfully become data analysts. Watch these videos
94+
for these success stories: (1) https://www.youtube.com/watch?v=4BLxapDqrlA (2) https://www.youtube.com/watch?v=yKB6EUbGamo
95+
Transition from mechanical engineering to data analyst is definitely possible. You need to learn necessary skills
96+
such as Excel, Power BI, SQL etc.
97+
'''
98+
elif background == "B.COM":
99+
answer = '''There are many B.COM graduates who have transitioned into data analytics industry. For example watch
100+
Suryanshu's story here: https://www.youtube.com/watch?v=in3IB45YEgY
101+
or How Hitesh is now working at Accenture with B.Com background: https://www.youtube.com/watch?v=lqEzYDuTnvU
102+
Let your past not define what you can do in the future. The transition is definitely possible.
103+
'''
104+
elif background == "HR":
105+
answer = '''If you are an HR trying to transition to data industry then I would suggest you leverage your past
106+
experience. Meaning you already know HR domain, now you can learn necessary skills such as SQL, Excel, Power BI
107+
and become an HR data analyst. This person Ankur Sharma was an HR and now he is working as a people analyst
108+
in an MNC: https://www.linkedin.com/in/ankur-sharma-b57266185/
109+
'''
110+
else:
111+
answer = '''There are many folks who have breaked into a data analyst career despite irrelavant degree,
112+
work experience or an older age. So the transition to data analyst career, no matter what your past background
113+
is possible for sure. Here is the playlist link with all such amazing transition stories to get some motivation:
114+
https://www.youtube.com/playlist?list=PLeo1K3hjS3us2Ko99XX9V5phkf5_2CJpQ
115+
If they can do it, you can do it too.
116+
'''
117+
if course_name:
118+
answer += " And yes you are eligible for " + "".join(course_name)
119+
else:
120+
answer = f"To understand if you are eligible for {course_name} or not, you can take this survey. It will" \
121+
f"tell you if you have natural abilities in the field of data analytics or not. Survey link: https://codebasics.io/find-your-match-da"
122+
123+
response = {
124+
"fulfillmentText": answer
125+
}
126+
127+
return JSONResponse(content=response)
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Author: Dhaval Patel. Codebasics YouTube Channel
2+
3+
import re
4+
5+
def get_str_from_food_dict(food_dict: dict):
6+
result = ", ".join([f"{int(value)} {key}" for key, value in food_dict.items()])
7+
return result
8+
9+
10+
def extract_session_id(session_str: str):
11+
match = re.search(r"/sessions/(.*?)/contexts/", session_str)
12+
if match:
13+
extracted_string = match.group(0)
14+
return extracted_string
15+
16+
return ""

0 commit comments

Comments
 (0)