Skip to content

Instantly share code, notes, and snippets.

@tbvinh
Last active July 25, 2024 11:15
Show Gist options
  • Save tbvinh/3d998090369b78aaa1f9f88fb41ba2e1 to your computer and use it in GitHub Desktop.
Save tbvinh/3d998090369b78aaa1f9f88fb41ba2e1 to your computer and use it in GitHub Desktop.
the AI chatbot in python
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
import tensorflow_hub as hub
import numpy as np
import re
# Intents and responses
intents = {
"greeting": ["hello", "hi", "helo", "hey", "good morning", "good evening", "howdy"],
"goodbye": ["bye", "goodbye", "see you later", "farewell", "catch you later"],
"thanks": ["thank you", "thanks", "much appreciated", "thank you very much"],
"calculate_area": ["calculate the area", "area of a rectangle", "rectangle area"],
"calculate_circumference": ["calculate the circumference", "circumference of a circle", "circle circumference"],
"calculate_circle_area": ["area of circle", "circle area", "calculate the area of a circle"]
}
responses = {
"greeting": "Hello! How can I help you today?",
"goodbye": "Goodbye! Have a great day!",
"thanks": "You're welcome! If you have any other questions, feel free to ask.",
"calculate_area": "Please provide the width (w) and height (h) of the rectangle in the format 'w x h'. For example, '5 x 10'.",
"calculate_circumference": "Please provide the radius (r) of the circle in the format 'r'. For example, '5'.",
"calculate_circle_area": "Please provide the radius (r) of the circle. For example, '5'."
}
confidence_threshold = 0.5
model_url = "https://tfhub.dev/google/universal-sentence-encoder/4"
#model = hub.load(model_url)
print("Model loading........")
model = tf.saved_model.load('/home/vinh/universal-sentence-encoder.model');
print("Model loaded successfully.")
# Helper functions
def parse_dimensions(input_text):
match = re.search(r'(\d+)\s*x\s*(\d+)', input_text)
if match:
return {"width": int(match.group(1)), "height": int(match.group(2))}
return None
def parse_radius(input_text):
match = re.search(r'(?:radius\s*|\s)(\d+)', input_text, re.IGNORECASE)
if match:
return {"radius": int(match.group(1))}
return None
def recognize_intent(user_input):
user_input_emb = model([user_input])
max_score = -1
recognized_intent = None
for intent, examples in intents.items():
examples_emb = model(examples)
scores = np.inner(user_input_emb, examples_emb)
max_example_score = np.max(scores)
if max_example_score > max_score:
max_score = max_example_score
recognized_intent = intent
if max_score < confidence_threshold:
recognized_intent = None
return recognized_intent
def generate_response(user_input):
intent = recognize_intent(user_input)
if intent == 'calculate_area':
dimensions = parse_dimensions(user_input)
if dimensions:
area = dimensions['width'] * dimensions['height']
return f"The area of the rectangle with width {dimensions['width']} and height {dimensions['height']} is {area}."
else:
return responses[intent] # Ask for dimensions if not provided
elif intent == 'calculate_circumference':
radius = parse_radius(user_input)
if radius:
circumference = 2 * np.pi * radius['radius']
return f"The circumference of the circle with radius {radius['radius']} is {circumference:.2f}."
else:
return responses[intent] # Ask for radius if not provided
elif intent == 'calculate_circle_area':
radius = parse_radius(user_input)
if radius:
area = np.pi * (radius['radius'] ** 2)
return f"The area of the circle with radius {radius['radius']} is {area:.2f}."
else:
return responses[intent] # Ask for radius if not provided
elif intent and responses.get(intent):
return responses[intent]
else:
return "I'm sorry, I don't understand that. Can you please rephrase?"
def main():
print("Chatbot is ready to talk! Type 'exit' to end the conversation.")
while True:
user_input = input("You: ")
if user_input.lower() in ['exit', 'quit']:
print("Chatbot: Goodbye!")
break
response = generate_response(user_input)
print(f"Chatbot: {response}\n")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment