import re from nltk.tokenize import word_tokenize from django.db.models import Q from inventory.models import Car # Import your car-related models import nltk # Download required NLTK resources try: nltk.download("punkt") except ImportError: raise ImportError("Ensure nltk is installed by running 'pip install nltk'.") # Static responses for predefined intents RESPONSES = { "greet": ["Hello! How can I assist you today with Haikal Car Inventory?"], "inventory_check": ["You can check the car inventory in the Cars section. Do you want to search for a specific car?"], "car_status": ["If a car is sold, it will either be marked as SOLD or removed from the inventory, as per your preferences."], "sell_process": ["To sell a car, the process involves creating a Sell Order, adding the customer, confirming payment, generating an invoice, and finally delivering the car."], "transfer_process": ["Dealers can transfer cars to other branches or dealers for display or sale. This is handled through Sell Orders as well."], "bye": ["Goodbye! If you need further assistance, just ask!"], } def clean_input(user_input): """ Clean and tokenize user input. """ user_input = user_input.lower() user_input = re.sub(r"[^\w\s]", "", user_input) # Remove punctuation return word_tokenize(user_input) def classify_input(tokens): """ Classify user intent based on tokens. """ if any(word in tokens for word in ["hello", "hi", "hey"]): return "greet" elif any(word in tokens for word in ["inventory", "cars", "check"]): return "inventory_check" elif any(word in tokens for word in ["sell", "sold", "process"]): return "sell_process" elif any(word in tokens for word in ["transfer", "branch", "display"]): return "transfer_process" elif any(word in tokens for word in ["bye", "goodbye", "exit"]): return "bye" elif any(word in tokens for word in ["price", "cost", "value"]): return "car_price" else: return "unknown" def get_dynamic_response(intent, tokens): """ Generate dynamic responses by querying the database. """ if intent == "car_price": # Extract car name from tokens car_name = " ".join([word.capitalize() for word in tokens]) try: car = Car.objects.filter(Q(make__icontains=car_name) | Q(model__icontains=car_name)).first() if car: return f"The price of {car_name} is {car.finance.selling_price}." return f"Sorry, no car matching '{car_name}' was found in the inventory." except Exception as e: return f"An error occurred while retrieving the car price: {str(e)}" return None def get_response(user_input): """ Generate a response based on the user's input. """ tokens = clean_input(user_input) intent = classify_input(tokens) # Check for a dynamic response dynamic_response = get_dynamic_response(intent, tokens) if dynamic_response: return dynamic_response # Return a static response if available if intent in RESPONSES: return RESPONSES[intent][0] # Default response for unknown intents return "I'm sorry, I didn't understand that. Could you rephrase your question about the Haikal system?"