{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "id": "jZ0wVSoo_5yd" }, "outputs": [], "source": [ "%pip install gradio gensim sentence_transformers torch torchvision torchaudio -f https://download.pytorch.org/whl/cu111/torch_stable.html" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "c7lAKXG_DTM_", "outputId": "60bad5b5-83a2-4f21-fce3-8bda36b50c5a" }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "[nltk_data] Downloading package punkt to /root/nltk_data...\n", "[nltk_data] Package punkt is already up-to-date!\n", "[nltk_data] Downloading package averaged_perceptron_tagger to\n", "[nltk_data] /root/nltk_data...\n", "[nltk_data] Package averaged_perceptron_tagger is already up-to-\n", "[nltk_data] date!\n", "[nltk_data] Downloading package vader_lexicon to /root/nltk_data...\n", "[nltk_data] Package vader_lexicon is already up-to-date!\n" ] } ], "source": [ "import pandas as pd\n", "import networkx as nx\n", "from sklearn.feature_extraction.text import TfidfVectorizer\n", "from sklearn.metrics.pairwise import linear_kernel\n", "from textblob import TextBlob\n", "from nltk.sentiment.vader import SentimentIntensityAnalyzer\n", "import nltk\n", "from nltk import pos_tag\n", "from nltk.tokenize import word_tokenize\n", "from gensim.models import Word2Vec\n", "import spacy\n", "from sentence_transformers import SentenceTransformer, util\n", "import numpy as np\n", "import torch\n", "import gradio as gr\n", "import os\n", "import math\n", "from datetime import datetime\n", "\n", "# Use GPU\n", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", "\n", "# Load a BERT model\n", "bert_model = SentenceTransformer('paraphrase-MiniLM-L6-v2', device=device)\n", "\n", "# Download NLTK resources (if not already downloaded)\n", "nltk.download('punkt')\n", "nltk.download('averaged_perceptron_tagger')\n", "nltk.download('vader_lexicon')\n", "\n", "# Load Spacy model for Named Entity Recognition (NER)\n", "nlp = spacy.load(\"en_core_web_sm\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "dG1jLPn5DXeb" }, "outputs": [], "source": [ "# Load Yelp dataset\n", "yelp_data = pd.read_csv('restaurants.csv')\n", "\n", "# Filter out relevant information (e.g., restaurant name, rating, location, categories, hours)\n", "restaurants = yelp_data[['name', 'stars', 'city', 'categories', 'hours']]\n", "\n", "comfort_food_terms = [\n", " \"Home cooking\",\n", " \"Soul food\",\n", " \"Indulgent food\",\n", " \"Feel-good food\",\n", " \"Nostalgia food\",\n", " \"Emotional food\",\n", " \"Guilty pleasure\",\n", " \"Indulgence\",\n", " \"Treat\",\n", " \"Culinary hug\",\n", " \"Soul-soothing food\",\n", " \"Heart-warming food\",\n", "]\n", "\n", "exciting_food_terms = [\n", " \"Adventurous food\",\n", " \"Exotic food\",\n", " \"Culinary adventure\",\n", " \"Sensual food\",\n", " \"Tantalizing food\",\n", " \"Mouthwatering food\",\n", " \"Delectable food\",\n", " \"Irresistible food\",\n", " \"Tempting food\",\n", " \"Gastronomical delight\",\n", "]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Z05Z7XmOW5xe" }, "outputs": [], "source": [ "# Create a TF-IDF vectorizer to convert restaurant categories into numerical features\n", "tfidf_vectorizer = TfidfVectorizer(stop_words='english', lowercase=True)\n", "tfidf_matrix = tfidf_vectorizer.fit_transform(restaurants['categories']+\", \"+restaurants['city'].fillna(''))\n", "\n", "# Train Word2Vec model on restaurant names\n", "restaurant_names = [word_tokenize(restaurant['categories'].lower()+restaurant['city'].lower()) for _, restaurant in restaurants.iterrows()]\n", "word2vec_model = Word2Vec(sentences=restaurant_names, vector_size=100, window=5, min_count=1, workers=4)\n", "\n", "if os.path.isfile(\"./bert_embeddings.npy\"):\n", " restaurant_embeddings = np.load('bert_embeddings.npy')\n", "else:\n", " # Precompute restaurant embeddings on the chosen device for both categories and cities\n", " restaurant_embeddings = [bert_model.encode((restaurant['categories'].lower() + restaurant['city'].lower()), convert_to_tensor=True).detach().cpu().numpy()\n", " for _, restaurant in restaurants.iterrows()]\n", " np.save('bert_embeddings.npy', np.array(restaurant_embeddings))\n", " restaurant_embeddings = np.load('bert_embeddings.npy')\n", "\n", "\n", "# Build a knowledge graph\n", "knowledge_graph = nx.Graph()\n", "\n", "# Add restaurant nodes with attributes\n", "for _, restaurant in restaurants.iterrows():\n", " knowledge_graph.add_node(\n", " restaurant['name'],\n", " stars=restaurant['stars'],\n", " city=restaurant['city'],\n", " categories=restaurant['categories'],\n", " hours=restaurant['hours']\n", " )\n", "\n", "# Function to extract named entities from user input using Spacy NER\n", "def extract_named_entities(user_input):\n", " doc = nlp(user_input)\n", " named_entities = [(ent.text, ent.label_) for ent in doc.ents]\n", " return named_entities\n", "\n", "# Function to perform sentiment analysis using VADER\n", "def analyze_sentiment_vader(text):\n", " sid = SentimentIntensityAnalyzer()\n", " compound_score = sid.polarity_scores(text)['compound']\n", " return compound_score" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "wtd56Af2EI7h" }, "outputs": [], "source": [ "# # Function to get restaurant recommendations based on graph similarity\n", "# def get_graph_recommendations(user_nouns):\n", "# # Use graph-based similarity to get similar restaurants from the knowledge graph\n", "# # You can choose a graph similarity algorithm based on your requirements\n", "# # For example, you can use Jaccard similarity or node2vec embeddings\n", "# # For simplicity, let's use Jaccard similarity here\n", "# user_nouns_set = set(user_nouns)\n", "# graph_recommendations = set()\n", "\n", "# # print(user_nouns_set)\n", "# for restaurant in knowledge_graph.nodes():\n", "# restaurant_nouns = set(pos_tag(word_tokenize(restaurant)))\n", "# jaccard_similarity = len(user_nouns_set.intersection(restaurant_nouns)) / len(user_nouns_set.union(restaurant_nouns))\n", "\n", "# # print(restaurant, restaurant_nouns, jaccard_similarity)\n", "# # If Jaccard similarity is above a threshold, consider it a recommendation\n", "# if jaccard_similarity > 0.1: # You can adjust the threshold\n", "# graph_recommendations.add(restaurant)\n", "\n", "# # print(graph_recommendations)\n", "# return graph_recommendations\n", "\n", "# Function to get restaurant recommendations based on Word Overlap\n", "def get_overlap_recommendations(user_input, num_recommendations):\n", " overlap_scores = pd.DataFrame()\n", " overlap_scores['combined_text'] = (restaurants['name'] + \", \" + restaurants['categories'] + \", \" + restaurants['city']).str.lower()\n", " overlap_scores['overlap_score'] = overlap_scores['combined_text'].apply(lambda x: sum(word in user_input.lower() for word in x.replace(',', '').split()))\n", " sorted_overlap_scores = overlap_scores.sort_values(by='overlap_score', ascending=False)\n", " top_recommendations_indices = [idx for idx, _ in sorted_overlap_scores.head(num_recommendations).iterrows()]\n", " return top_recommendations_indices\n", "\n", "\n", "# Function to get restaurant recommendations based on Word Embeddings similarity\n", "def get_embedding_recommendations(user_input, num_recommendations):\n", " tokens = word_tokenize(user_input.lower())\n", " embedding_similarities = {}\n", "\n", " for i, restaurant in restaurants.iterrows():\n", " restaurant_tokens = word_tokenize(restaurant['categories'].lower() + restaurant['city'].lower())\n", " similarity = word2vec_model.wv.n_similarity(tokens, restaurant_tokens)\n", " embedding_similarities[i] = similarity\n", "\n", " # Sort the dictionary by similarity scores and get top recommendations\n", " sorted_similarities = sorted(embedding_similarities.items(), key=lambda item: item[1], reverse=True)\n", " top_recommendations_indices = [idx for idx, _ in sorted_similarities[:num_recommendations]]\n", "\n", " return top_recommendations_indices\n", "\n", "# Function to get restaurant recommendations based on BERT embeddings similarity\n", "def get_bert_recommendations(user_input, num_recommendations):\n", " user_embedding = bert_model.encode(user_input.lower(), convert_to_tensor=True).detach().cpu().numpy()\n", " # user_embedding = np.mean(bert_model.encode(user_input.lower(), convert_to_tensor=True).detach().cpu().numpy(), axis=0)\n", "\n", " bert_similarities = {}\n", "\n", " for i, restaurant in restaurants.iterrows():\n", " restaurant_embedding = restaurant_embeddings[i]\n", " # print(restaurant_embedding, user_embedding)\n", " # similarity = np.dot(user_embedding, restaurant_embedding) / (np.linalg.norm(user_embedding) * np.linalg.norm(restaurant_embedding))\n", " similarity = util.cos_sim(user_embedding, restaurant_embedding)\n", " bert_similarities[i] = similarity\n", " # print(i, similarity)\n", "\n", " # Sort the dictionary by similarity scores and get top recommendations\n", " sorted_similarities = sorted(bert_similarities.items(), key=lambda item: item[1], reverse=True)\n", " top_recommendations_indices = [idx for idx, _ in sorted_similarities[:num_recommendations]]\n", "\n", " return top_recommendations_indices" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "gU0JhAg0EB3b" }, "outputs": [], "source": [ "# Function to recommend restaurants based on user input, sentiment, availability, and knowledge graph\n", "def recommend_restaurants(user_input, num_recommendations=5, sentiment_recursive_break=False):\n", "\n", " sr = pd.DataFrame()\n", "\n", " # Tokenize and perform POS tagging on the user input\n", " tokens = word_tokenize(user_input)\n", " pos_tags = pos_tag(tokens)\n", "\n", " # Extract nouns and locations from POS tags\n", " user_nouns = [word for word, pos in pos_tags if pos.startswith('N') or pos.startswith('J')]\n", " user_locations = [word.lower().strip() for word, pos in pos_tags if pos.startswith('NNP')] # Assume proper nouns are locations\n", " # print(user_input)\n", "\n", " # Extract named entities from user input\n", " named_entities = extract_named_entities(user_input)\n", " # print(\"Named Entities:\", named_entities)\n", "\n", " # Transform user input into a TF-IDF vector\n", " user_tfidf = tfidf_vectorizer.transform([user_input])\n", "\n", " # Compute the cosine similarity between the user input and restaurant categories\n", " cosine_similarities = linear_kernel(user_tfidf, tfidf_matrix).flatten()\n", "\n", " # Get recommended restaurants from simple word overlap\n", " overlap_recommendations = get_overlap_recommendations(user_input, num_recommendations)\n", "\n", " # Get indices of restaurants with the highest similarity scores using TF-IDF\n", " tfidf_recommendations = cosine_similarities.argsort()[:-num_recommendations-1:-1]\n", "\n", " # Get recommendations using Word Embeddings\n", " embedding_similarities = get_embedding_recommendations(user_input, num_recommendations)\n", "\n", " # Get recommendations using BERT\n", " bert_recommendations_indices = get_bert_recommendations(user_input, num_recommendations)\n", "\n", " # Combine recommendations from both approaches\n", " combined_recommendations = set(overlap_recommendations) | set(tfidf_recommendations) | set(embedding_similarities) |set(bert_recommendations_indices)\n", " combined_recommendations = set(embedding_similarities)\n", " # print(\"TFIDF:\", tfidf_recommendations)\n", " # print(\"overlap:\", overlap_recommendations)\n", " # print(\"w2v:\", embedding_similarities)\n", " # print(\"BERT:\", bert_recommendations_indices)\n", "\n", " # Get details of recommended restaurants\n", " recommended_restaurants = restaurants.iloc[list(combined_recommendations)]\n", "\n", " # print(\"rec res:\", combined_recommendations)\n", "\n", " # Refine recommendations based on extracted information, location, and named entities\n", " for _, restaurant in recommended_restaurants.iterrows():\n", " # if any(category in restaurant['categories'] for category in user_nouns) and any(location in restaurant['city'] for location in user_locations):\n", " # if any(location in restaurant['city'].lower().strip() for location in user_locations):\n", " print(f\"Recommendation: {restaurant['name'], restaurant['city'], restaurant['categories'], restaurant['stars']} \")\n", "\n", " if not sentiment_recursive_break:\n", " # Perform sentiment analysis using VADER\n", " sentiment_score = analyze_sentiment_vader(user_input)\n", "\n", " if sentiment_score < -0.2:\n", " print(\"Considering your negative sentiment, you might prefer comforting places.\")\n", " sr = recommend_restaurants(user_input=user_input + \", \" + \", \".join(comfort_food_terms), num_recommendations=num_recommendations, sentiment_recursive_break=True)\n", " # comforting_places = restaurants[restaurants['categories'].str.contains('comfort food', case=False, na=False)]\n", " # print(\"Comforting food places suggestions:\")\n", " # print(comforting_places[['name', 'stars', 'city', 'categories']])\n", " elif sentiment_score > 0.2:\n", " print(\"Considering your positive sentiment, you might prefer something exciting.\")\n", " sr = recommend_restaurants(user_input=user_input + \", \" + \", \".join(exciting_food_terms), num_recommendations=num_recommendations, sentiment_recursive_break=True)\n", " # exciting_places = restaurants[restaurants['categories'].str.contains('nightlife|arts & entertainment|restaurants', case=False, na=False)]\n", " # print(\"Exciting food places suggestions:\")\n", " # print(exciting_places[['name', 'stars', 'city', 'categories']])\n", " else:\n", " print(\"neutral sentiment\")\n", "\n", " # Rank the restaurants based on ratings in descending order\n", " ranked_restaurants = recommended_restaurants.sort_values(by='stars', ascending=False).head(num_recommendations)\n", "\n", " # return recommended restaurants for evaluation\n", " return ranked_restaurants" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "aDZYCDQxfMFH" }, "outputs": [], "source": [ "# Example prompt\n", "user_prompt = input(\"Enter your restaurant preference (e.g., I want Chinese in Brooklyn): \")\n", "\n", "# Get recommendations based on the user's input, sentiment, availability, and knowledge graph\n", "recommend_restaurants(user_prompt)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "asj5AxXvDjrY" }, "outputs": [], "source": [ "def evaluate_recommendations(predicted_df, filtered_df, k):\n", " \"\"\"\n", " Evaluate predicted restaurant recommendations against the ground truth using precision@k, recall@k, and F1@k.\n", "\n", " Parameters:\n", " - predicted_df (pd.DataFrame): DataFrame with predicted restaurant recommendations.\n", " - filtered_df (pd.DataFrame): DataFrame with ground truth or actual relevant restaurants.\n", " - k (int): Value of k for top-k recommendations.\n", "\n", " Returns:\n", " - precision_at_k (float): Precision@k.\n", " - recall_at_k (float): Recall@k.\n", " - f1_at_k (float): F1@k.\n", " \"\"\"\n", "\n", " # Extract the top-k predicted restaurants\n", " top_k_predicted = predicted_df.head(k)\n", "\n", " # Evaluate precision@k, recall@k, and F1@k\n", " intersection = pd.merge(top_k_predicted, filtered_df, on=['name', 'stars', 'city', 'categories', 'hours'], how='inner')\n", "\n", " precision_at_k = len(intersection) / k\n", " recall_at_k = len(intersection) / len(filtered_df)\n", " f1_at_k = 2 * (precision_at_k * recall_at_k) / (precision_at_k + recall_at_k) if (precision_at_k + recall_at_k) > 0 else 0\n", "\n", " return precision_at_k, recall_at_k, f1_at_k" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "n1Xrcarvzw9P" }, "outputs": [], "source": [ "cajun_in_neworleans = restaurants[\n", " (restaurants['city'] == 'New Orleans') &\n", " (restaurants['categories'].str.contains('cajun', case=False))\n", "]\n", "steakhouses_in_indiana = restaurants[\n", " (restaurants['city'] == 'Indianapolis') &\n", " (restaurants['categories'].str.contains('steakhouse', case=False))\n", "]\n", "chinese_in_philadelphia = restaurants[\n", " (restaurants['city'] == 'Philadelphia') &\n", " (restaurants['categories'].str.contains('chinese', case=False))\n", "]\n", "seafood_in_tampa = restaurants[\n", " (restaurants['city'] == 'Tampa') &\n", " (restaurants['categories'].str.contains('seafood', case=False))\n", "]\n", "italian_in_stlouis = restaurants[\n", " (restaurants['city'] == 'Saint Louis') &\n", " (restaurants['categories'].str.contains('italian', case=False))\n", "]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "XEG8Eyh55lV7" }, "outputs": [], "source": [ "cino = recommend_restaurants(input())" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Iarl1OLg6CW8" }, "outputs": [], "source": [ "print(evaluate_recommendations(cino, cajun_in_neworleans, 1))\n", "print(evaluate_recommendations(cino, cajun_in_neworleans, 5))\n", "print(evaluate_recommendations(cino, cajun_in_neworleans, 10))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "jQI7iAQeEDGr" }, "outputs": [], "source": [ "sit = recommend_restaurants(input())" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "G2QAD-o8E6HZ" }, "outputs": [], "source": [ "print(evaluate_recommendations(sit, seafood_in_tampa, 1))\n", "print(evaluate_recommendations(sit, seafood_in_tampa, 5))\n", "print(evaluate_recommendations(sit, seafood_in_tampa, 10))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "v7co493SGeWY" }, "outputs": [], "source": [ "sii = recommend_restaurants(input())" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Te-YQGBzGl70" }, "outputs": [], "source": [ "print(evaluate_recommendations(sii, steakhouses_in_indiana, 1))\n", "print(evaluate_recommendations(sii, steakhouses_in_indiana, 5))\n", "print(evaluate_recommendations(sii, steakhouses_in_indiana, 10))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ILgW8nsLHuwd" }, "outputs": [], "source": [ "iisl = recommend_restaurants(input())" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "nGi-VJfcH3tH" }, "outputs": [], "source": [ "print(evaluate_recommendations(iisl, italian_in_stlouis, 1))\n", "print(evaluate_recommendations(iisl, italian_in_stlouis, 5))\n", "print(evaluate_recommendations(iisl, italian_in_stlouis, 10))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "background_save": true, "base_uri": "https://localhost:8080/", "height": 830 }, "id": "MNM-MiKwhN2I", "outputId": "31abcb6c-b9bc-4096-f012-bf12ee7a1e24" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Setting queue=True in a Colab notebook requires sharing enabled. Setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).\n", "\n", "Colab notebook detected. This cell will run indefinitely so that you can see errors and logs. To turn off, set debug=False in launch().\n", "Running on public URL: https://4a62505eb450484ce0.gradio.live\n", "\n", "This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from Terminal to deploy to Spaces (https://huggingface.co/spaces)\n" ] }, { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "Recommendation: (\"Charlie Gitto's On the Hill\", 'St. Louis', 'Restaurants, Italian', 4.5) \n", "Recommendation: (\"Pietro's\", 'St. Louis', 'Italian, Restaurants', 4.0) \n", "Recommendation: ('Cluster Busters', 'St. Louis', 'Italian, Restaurants, Seafood', 4.0) \n", "Recommendation: ('Cibare Italian Kitchen', 'St. Louis', 'Restaurants, Italian', 4.0) \n", "Recommendation: ('Toscana Pizza, Pasta & More', 'St. Petersburg', 'Italian, Restaurants, Pizza', 4.0) \n", "Recommendation: (\"Del Pietro's\", 'St. Louis', 'Italian, Restaurants', 4.0) \n", "Recommendation: (\"Sophia's Cucina + Enoteca\", 'St. Petersburg', 'Italian, Restaurants', 4.0) \n", "Recommendation: (\"Moscato's Bella Cucina\", 'St. Petersburg', 'Italian, Restaurants', 3.5) \n", "Recommendation: ('Bici Trattoria', 'St. Petersburg', 'Italian, Restaurants', 4.0) \n", "Recommendation: ('Goodcents Deli Fresh Subs', 'St. Louis', 'Restaurants, Sandwiches', 4.0) \n", "neutral sentiment\n" ] } ], "source": [ "# rr = recommend_restaurants(prompt, number_of_recommendations = 5)\n", "\n", "demo = gr.Interface(fn=recommend_restaurants, inputs=[\"text\", gr.Number(value=10, precision=0, minimum=1)], outputs=\"dataframe\")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch(show_api=False, debug=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Dx0SmXB8qGln" }, "outputs": [], "source": [ "# import pandas as pd\n", "# import networkx as nx\n", "# from sklearn.feature_extraction.text import TfidfVectorizer\n", "# from sklearn.metrics.pairwise import linear_kernel\n", "# import nltk\n", "# from nltk import pos_tag\n", "# from nltk.tokenize import word_tokenize\n", "# from datetime import datetime\n", "\n", "# # Download NLTK resources (if not already downloaded)\n", "# nltk.download('punkt')\n", "# nltk.download('averaged_perceptron_tagger')\n", "\n", "# # Load Yelp dataset (replace 'yelp_dataset.csv' with your actual dataset file)\n", "# yelp_data = pd.read_csv('yelp_dataset.csv')\n", "\n", "# # Load existing knowledge graph (replace 'knowledge_graph.gexf' with your actual graph file)\n", "# knowledge_graph = nx.read_gexf('knowledge_graph.gexf')\n", "\n", "# # Filter out relevant information (e.g., restaurant name, rating, location, categories, hours)\n", "# restaurants = yelp_data[['name', 'stars', 'city', 'categories', 'hours']]\n", "\n", "# # Create a TF-IDF vectorizer to convert restaurant categories into numerical features\n", "# tfidf_vectorizer = TfidfVectorizer(stop_words='english', lowercase=True)\n", "# tfidf_matrix = tfidf_vectorizer.fit_transform(restaurants['categories'].fillna(''))\n", "\n", "# # Function to check if a restaurant is open at the current time\n", "# def is_restaurant_open(hours, current_time):\n", "# for day, hours_range in hours.items():\n", "# start_time, end_time = hours_range.split('-')\n", "# if start_time <= current_time <= end_time:\n", "# return True\n", "# return False\n", "\n", "# # Function to get similar foods from the knowledge graph\n", "# def get_similar_foods(category, knowledge_graph):\n", "# similar_foods = set()\n", "\n", "# if category in knowledge_graph.nodes:\n", "# neighbors = list(knowledge_graph.neighbors(category))\n", "# similar_foods.update(neighbors)\n", "\n", "# return similar_foods\n", "\n", "# # Function to recommend restaurants based on content-based filtering and availability\n", "# def recommend_restaurants(user_input, num_recommendations=5):\n", "# # Tokenize and perform POS tagging on the user input\n", "# tokens = word_tokenize(user_input)\n", "# pos_tags = pos_tag(tokens)\n", "\n", "# # Extract nouns and locations from POS tags\n", "# user_nouns = [word for word, pos in pos_tags if pos.startswith('N') or pos.startswith('J')]\n", "# user_locations = [word for word, pos in pos_tags if pos.startswith('NNP')] # Assume proper nouns are locations\n", "\n", "# # Filter restaurants based on the user's location\n", "# location_filtered_restaurants = restaurants[restaurants['city'].isin(user_locations)]\n", "\n", "# # Transform user input into a TF-IDF vector\n", "# user_tfidf = tfidf_vectorizer.transform([user_input])\n", "\n", "# # Compute the cosine similarity between the user input and restaurant categories\n", "# cosine_similarities = linear_kernel(user_tfidf, tfidf_matrix).flatten()\n", "\n", "# # Get indices of restaurants with highest similarity scores\n", "# restaurant_indices = cosine_similarities.argsort()[:-num_recommendations-1:-1]\n", "\n", "# # Get recommended restaurants\n", "# recommended_restaurants = restaurants.iloc[restaurant_indices]\n", "\n", "# # Refine recommendations based on extracted information and location\n", "# for _, restaurant in recommended_restaurants.iterrows():\n", "# if any(category in restaurant['categories'] for category in user_nouns) and any(location in restaurant['city'] for location in user_locations):\n", "# print(f\"Refined recommendation: {restaurant['name']} based on type of food and location.\")\n", "\n", "# # Get similar foods from the knowledge graph\n", "# additional_categories = set()\n", "# for user_noun in user_nouns:\n", "# similar_foods = get_similar_foods(user_noun, knowledge_graph)\n", "# additional_categories.update(similar_foods)\n", "\n", "# # Update the categories column with similar foods\n", "# updated_categories = ', '.join(set(restaurant['categories'].split(', ') + list(additional_categories)))\n", "# print(f\"Updated Categories: {updated_categories}\")\n", "\n", "# # Check restaurant availability based on current time\n", "# current_time = datetime.now().strftime(\"%H:%M\")\n", "# if is_restaurant_open(restaurant['hours'], current_time):\n", "# print(f\"{restaurant['name']} is open right now!\")\n", "# else:\n", "# print(f\"{restaurant['name']} is currently closed.\")\n", "\n", "# # Example prompt\n", "# user_prompt = input(\"Enter your restaurant preference (e.g., I want Chinese in Brooklyn): \")\n", "\n", "# # Get recommendations based on the user's input and availability, prioritizing location\n", "# recommend_restaurants(user_prompt)\n" ] } ], "metadata": { "accelerator": "GPU", "colab": { "provenance": [] }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 0 }