import spacy
from spacy.matcher import Matcher, PhraseMatcher
from pydantic import BaseModel, Field
from typing import List, Dict, Optional, Tuple, Any
from enum import Enum
from datetime import datetime
import json
import re
# ==================== Models ====================
class Intent(str, Enum):
BOOKING_FLIGHT = "booking_flight"
BOOKING_HOTEL = "booking_hotel"
BOOKING_CAR = "booking_car"
BOOKING_RESTAURANT = "booking_restaurant"
INQUIRY = "inquiry"
UNKNOWN = "unknown"
class FlightBooking(BaseModel):
origin: Optional[str] = None
destination: Optional[str] = None
date: Optional[str] = None
passenger_count: Optional[int] = None
class_type: Optional[str] = None
class HotelBooking(BaseModel):
location: Optional[str] = None
check_in: Optional[str] = None
check_out: Optional[str] = None
room_count: Optional[int] = None
class CarBooking(BaseModel):
location: Optional[str] = None
pickup_date: Optional[str] = None
return_date: Optional[str] = None
car_type: Optional[str] = None
class RestaurantBooking(BaseModel):
location: Optional[str] = None
cuisine: Optional[str] = None
party_size: Optional[int] = None
date: Optional[str] = None
class ChatbotResponse(BaseModel):
intent: Intent
bookings: Dict[str, Any] = Field(default_factory=dict)
entities: Dict[str, List[str]] = Field(default_factory=dict)
confidence: float
original_text: str
# ==================== Chatbot Class ====================
class TravelChatbot:
def __init__(self, model_name: str = "en_core_web_sm"):
"""Initialize the chatbot with spaCy model and custom matchers."""
self.nlp = spacy.load(model_name)
self.setup_matchers()
# Intent keywords with confidence scores
self.intent_keywords = {
Intent.BOOKING_FLIGHT: {
"keywords": ["flight", "book", "fly", "departure", "arrival", "ticket"],
"patterns": [r"book.*flight", r"flight.*from", r"fly.*to"]
},
Intent.BOOKING_HOTEL: {
"keywords": ["hotel", "accommodation", "room", "stay", "book"],
"patterns": [r"book.*hotel", r"hotel.*in", r"stay.*at"]
},
Intent.BOOKING_CAR: {
"keywords": ["car", "rent", "rental", "drive", "pickup"],
"patterns": [r"rent.*car", r"car.*rental", r"pickup"]
},
Intent.BOOKING_RESTAURANT: {
"keywords": ["restaurant", "dinner", "lunch", "table", "reservation"],
"patterns": [r"book.*restaurant", r"restaurant.*reservation"]
},
Intent.INQUIRY: {
"keywords": ["what", "where", "when", "how", "tell", "find"],
"patterns": [r"where", r"what is", r"how to"]
}
}
# Location database (simplified)
self.locations = {
"new york": "NY",
"ny": "NY",
"london": "LON",
"paris": "PAR",
"tokyo": "TYO",
"sydney": "SYD",
"dubai": "DXB",
"los angeles": "LAX",
"la": "LAX",
"san francisco": "SFO",
"sf": "SFO",
"bangkok": "BKK",
"singapore": "SIN"
}
def setup_matchers(self):
"""Setup spaCy matchers for custom entity extraction."""
self.matcher = Matcher(self.nlp.vocab)
# Flight patterns
self.matcher.add("FLIGHT_ROUTE", [
[{"LOWER": "from"}, {"IS_ALPHA": True, "OP": "+"}],
[{"LOWER": "to"}, {"IS_ALPHA": True, "OP": "+"}]
])
# Date patterns (simplified)
self.matcher.add("DATE", [
[{"IS_DIGIT": True}, {"LOWER": {"IN": ["am", "pm"]}}],
[{"LOWER": {"IN": ["today", "tomorrow", "monday", "tuesday", "wednesday",
"thursday", "friday", "saturday", "sunday"]}}]
])
# Number of passengers/rooms/people
self.matcher.add("COUNT", [
[{"LOWER": {"IN": ["one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten"]}},
{"LOWER": {"IN": ["passenger", "person", "people", "room", "rooms"]}}]
])
def extract_locations(self, text: str) -> List[Tuple[str, str]]:
"""Extract location entities from text."""
locations = []
doc = self.nlp(text.lower())
for token in doc:
if token.ent_type_ == "GPE" or token.text in self.locations:
locations.append((token.text, self.locations.get(token.text, token.text)))
return locations
def extract_numbers(self, text: str) -> Dict[str, int]:
"""Extract numbers (passengers, rooms, dates)."""
numbers = {}
# Word to digit mapping
word_to_num = {
"one": 1, "two": 2, "three": 3, "four": 4, "five": 5,
"six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10
}
words = text.lower().split()
for i, word in enumerate(words):
if word in word_to_num:
if i + 1 < len(words):
next_word = words[i + 1]
if "passenger" in next_word or "person" in next_word:
numbers["passengers"] = word_to_num[word]
elif "room" in next_word:
numbers["rooms"] = word_to_num[word]
# Also check for digit numbers
digits = re.findall(r'\d+', text)
if digits:
numbers["found_digits"] = [int(d) for d in digits]
return numbers
def extract_dates(self, text: str) -> List[str]:
"""Extract date expressions from text."""
dates = []
doc = self.nlp(text)
# Check for date entities
for ent in doc.ents:
if ent.label_ == "DATE":
dates.append(ent.text)
# Regex-based date patterns
date_patterns = [
r'\d{1,2}/\d{1,2}/\d{2,4}', # MM/DD/YYYY
r'\d{1,2}-\d{1,2}-\d{2,4}', # MM-DD-YYYY
r'\b(?:January|February|March|April|May|June|July|August|September|October|November|December|Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+\d{1,2}(?:,?\s+\d{4})?\b'
]
for pattern in date_patterns:
matches = re.findall(pattern, text, re.IGNORECASE)
dates.extend(matches)
return dates
def classify_intent(self, text: str) -> Tuple[Intent, float]:
"""Classify the intent of the user message."""
text_lower = text.lower()
doc = self.nlp(text_lower)
best_intent = Intent.UNKNOWN
best_score = 0.0
for intent, config in self.intent_keywords.items():
score = 0.0
total_checks = len(config["keywords"]) + len(config["patterns"])
# Keyword matching
for keyword in config["keywords"]:
if keyword in text_lower:
score += 1.0
# Pattern matching
for pattern in config["patterns"]:
if re.search(pattern, text_lower):
score += 1.0
# Normalize score
normalized_score = score / total_checks if total_checks > 0 else 0
if normalized_score > best_score:
best_score = normalized_score
best_intent = intent
# Confidence threshold
if best_score < 0.3:
best_intent = Intent.INQUIRY
best_score = 0.5
return best_intent, min(best_score, 1.0)
def extract_flight_info(self, text: str) -> Optional[FlightBooking]:
"""Extract flight booking information."""
locations = self.extract_locations(text)
dates = self.extract_dates(text)
numbers = self.extract_numbers(text)
if not locations:
return None
flight = FlightBooking()
# Extract origin and destination
for i, (loc_name, loc_code) in enumerate(locations):
if i == 0:
flight.origin = loc_code
elif i == 1:
flight.destination = loc_code
# Extract date
if dates:
flight.date = dates[0]
# Extract passenger count
if "passengers" in numbers:
flight.passenger_count = numbers["passengers"]
# Extract class type
class_types = ["economy", "business", "first", "premium"]
for class_type in class_types:
if class_type in text.lower():
flight.class_type = class_type
break
return flight
def extract_hotel_info(self, text: str) -> Optional[HotelBooking]:
"""Extract hotel booking information."""
locations = self.extract_locations(text)
dates = self.extract_dates(text)
numbers = self.extract_numbers(text)
if not locations:
return None
hotel = HotelBooking()
hotel.location = locations[0][1] if locations else None
# Extract dates (check-in and check-out)
if len(dates) >= 1:
hotel.check_in = dates[0]
if len(dates) >= 2:
hotel.check_out = dates[1]
# Extract room count
if "rooms" in numbers:
hotel.room_count = numbers["rooms"]
return hotel
def extract_car_info(self, text: str) -> Optional[CarBooking]:
"""Extract car rental booking information."""
locations = self.extract_locations(text)
dates = self.extract_dates(text)
if not locations:
return None
car = CarBooking()
car.location = locations[0][1] if locations else None
# Extract dates
if len(dates) >= 1:
car.pickup_date = dates[0]
if len(dates) >= 2:
car.return_date = dates[1]
# Extract car type
car_types = ["economy", "sedan", "suv", "luxury", "sports"]
for car_type in car_types:
if car_type in text.lower():
car.car_type = car_type
break
return car
def extract_restaurant_info(self, text: str) -> Optional[RestaurantBooking]:
"""Extract restaurant booking information."""
locations = self.extract_locations(text)
dates = self.extract_dates(text)
numbers = self.extract_numbers(text)
if not locations:
return None
restaurant = RestaurantBooking()
restaurant.location = locations[0][1] if locations else None
# Extract cuisine type
cuisines = ["italian", "japanese", "french", "chinese", "indian", "thai", "mexican"]
for cuisine in cuisines:
if cuisine in text.lower():
restaurant.cuisine = cuisine
break
# Extract party size
if "people" in text.lower() and numbers.get("found_digits"):
restaurant.party_size = numbers["found_digits"][0]
# Extract date
if dates:
restaurant.date = dates[0]
return restaurant
def extract_all_entities(self, text: str) -> Dict[str, List[str]]:
"""Extract all entities from text."""
doc = self.nlp(text)
entities = {}
# Spacy NER entities
for ent in doc.ents:
if ent.label_ not in entities:
entities[ent.label_] = []
entities[ent.label_].append(ent.text)
# Custom entity extraction
locations = self.extract_locations(text)
if locations:
entities["GPE"] = [loc[0] for loc in locations]
dates = self.extract_dates(text)
if dates:
entities["DATE"] = dates
return entities
def process(self, text: str) -> ChatbotResponse:
"""Process user input and generate structured response."""
# Classify intent
intent, confidence = self.classify_intent(text)
# Extract entities
entities = self.extract_all_entities(text)
# Extract specific booking information based on intent
bookings = {}
if intent == Intent.BOOKING_FLIGHT:
flight = self.extract_flight_info(text)
if flight:
bookings["flight"] = json.loads(flight.model_dump_json(exclude_none=True))
elif intent == Intent.BOOKING_HOTEL:
hotel = self.extract_hotel_info(text)
if hotel:
bookings["hotel"] = json.loads(hotel.model_dump_json(exclude_none=True))
elif intent == Intent.BOOKING_CAR:
car = self.extract_car_info(text)
if car:
bookings["car"] = json.loads(car.model_dump_json(exclude_none=True))
elif intent == Intent.BOOKING_RESTAURANT:
restaurant = self.extract_restaurant_info(text)
if restaurant:
bookings["restaurant"] = json.loads(restaurant.model_dump_json(exclude_none=True))
# Handle multiple bookings in one sentence
if intent == Intent.BOOKING_FLIGHT and "hotel" in text.lower():
hotel = self.extract_hotel_info(text)
if hotel:
bookings["hotel"] = json.loads(hotel.model_dump_json(exclude_none=True))
if intent == Intent.BOOKING_HOTEL and "flight" in text.lower():
flight = self.extract_flight_info(text)
if flight:
bookings["flight"] = json.loads(flight.model_dump_json(exclude_none=True))
return ChatbotResponse(
intent=intent,
bookings=bookings,
entities=entities,
confidence=confidence,
original_text=text
)