Spaces:
Sleeping
Sleeping
# -*- coding: utf-8 -*- | |
"""Copy of Mona_Raghad_Lujin_projcect.ipynb | |
Automatically generated by Colab. | |
Original file is located at | |
https://colab.research.google.com/drive/1qn3CfGuoWA8ghVrJ2l8KifSOj7A2RI6J | |
# Smart Travel: Discover Your Perfect Hotel Using AI ✈ | |
 | |
**Objective:** | |
The Project Search Agent is designed to revolutionize the way users find and interact with information by leveraging advanced artificial intelligence (AI) and natural language processing (NLP) technologies. The search agent aims to provide intelligent, personalized, and efficient search experiences across various domains, such as hotels, products, or content, by understanding user intent and delivering relevant results. | |
**Architecture and Workflow:** | |
**Data Ingestion and Preparation:** | |
Datasets: Utilize datasets containing structured and unstructured data related to user queries, items, or subjects of interest (e.g., hotel reviews, product descriptions). | |
Data Cleaning: Implement data preprocessing using pandas to handle missing values, remove noise, and standardize text data for further analysis. | |
**Natural Language Processing (NLP):** | |
Text Preprocessing: Use libraries like nltk or spaCy to tokenize, lemmatize, and remove stopwords from the text data, ensuring it is clean and consistent for analysis. | |
Sentiment Analysis: Apply sentiment analysis models to understand user sentiments and extract meaningful insights that guide the search recommendations. | |
**transformers Models:** | |
Semantic Search: Employ models from the transformers library, such as BERT or Sentence Transformers, to convert text into embeddings for semantic analysis. | |
Similarity Calculation: Use sklearn.metrics.pairwise to compute cosine similarity between query embeddings and item embeddings, identifying the most relevant matches. | |
**Recommendation System:** | |
Content-Based Filtering: Recommend items based on the semantic similarity of user queries to item attributes or reviews. | |
Personalized Suggestions: Incorporate user preferences and feedback to refine recommendations, ensuring a personalized experience. | |
**Data Visualization:** | |
Visual Insights: Use matplotlib and seaborn to create visual representations of search results, sentiment trends, and item ratings. | |
Comparative Analysis: Provide visual comparisons to help users understand the context and relevance of recommended items. | |
**Interactive User Interface:** | |
Gradio Integration: Develop an interactive web-based interface using Gradio, allowing users to input queries and view results in real-time. | |
User Interaction: Enable seamless interaction and instant feedback through an intuitive, user-friendly design that facilitates exploration and discovery. | |
# Installing Required Libraries | |
""" | |
!pip install datasets | |
!pip install keyphrase-vectorizers | |
!pip install transformers | |
!pip install sentence-transformers | |
!pip install gradio | |
"""# Data Preparation and Cleaning""" | |
import pandas as pd | |
df = pd.DataFrame(ds["train"]) | |
df.info() | |
missing_values_per_column = df.isnull().sum() | |
print("Missing values per column:") | |
print(missing_values_per_column) | |
import pandas as pd | |
# Assuming df is your DataFrame | |
# Display initial missing value counts | |
print("Initial missing values per column:") | |
print(df.isnull().sum()) | |
# Fill missing values in 'review_text' with an empty string and 'rate' with a specific value | |
df['review_text'].fillna('', inplace=True) | |
df['rate'].fillna(df['rate'].mean(), inplace=True) # Filling with mean for example | |
# Fill missing values in 'hotel_description' with a placeholder | |
df['hotel_description'].fillna('Description not available', inplace=True) | |
# Verify the cleaning | |
print("\nMissing values after cleaning:") | |
print(df.isnull().sum()) | |
# Display the cleaned DataFrame (first few rows) | |
print("\nCleaned DataFrame sample:") | |
print(df.head()) | |
df.hotel_name.value_counts() | |
import re | |
import nltk | |
from nltk.corpus import stopwords | |
from nltk.tokenize import word_tokenize | |
from nltk.stem import WordNetLemmatizer | |
import pandas as pd | |
# Download necessary NLTK resources | |
nltk.download('punkt') | |
nltk.download('stopwords') | |
nltk.download('wordnet') | |
# Load your DataFrame (assuming it's named df) | |
# Ensure that df is defined elsewhere in your code with the appropriate data | |
# Normalize country names | |
df['country'] = df['country'].replace({'Türkiye': 'Turkiye'}) | |
# Check the value counts to verify the replacement | |
print(df['country'].value_counts()) | |
def clean_text(text): | |
""" | |
Cleans text data by removing punctuation, converting to lowercase, removing stopwords, and lemmatizing. | |
Args: | |
text: The text string to be cleaned. | |
Returns: | |
The cleaned text string. | |
""" | |
# Handle None or empty values | |
if pd.isnull(text): | |
return "" | |
# Lowercase the text | |
text = text.lower() | |
# Remove special characters and numbers | |
text = re.sub(r'[^a-zA-Z\s]', '', text) | |
# Tokenize the text | |
tokens = word_tokenize(text) | |
# Remove stop words | |
stop_words = set(stopwords.words('english')) | |
tokens = [word for word in tokens if word not in stop_words] | |
# Lemmatize the tokens | |
lemmatizer = WordNetLemmatizer() | |
tokens = [lemmatizer.lemmatize(word) for word in tokens] | |
# Join the tokens back into a string | |
cleaned_text = ' '.join(tokens) | |
return cleaned_text | |
# Apply text cleaning to the 'review_text' column | |
df['cleaned_reviews'] = df['review_text'].apply(clean_text) | |
print(df.columns) | |
print(df.isnull().sum()) | |
"""# Sentiment Analysis and Visualization""" | |
from datasets import load_dataset | |
from nltk.sentiment import SentimentIntensityAnalyzer | |
import nltk | |
import matplotlib.pyplot as plt | |
import seaborn as sns | |
# Download necessary NLTK resources | |
nltk.download('vader_lexicon') | |
# Initialize SentimentIntensityAnalyzer | |
sia = SentimentIntensityAnalyzer() | |
def classify_sentiment(review): | |
""" | |
Classifies the sentiment of a review as positive, negative, or neutral. | |
Args: | |
review: The text of the review. | |
Returns: | |
A string indicating the sentiment category: 'positive', 'negative', or 'neutral'. | |
""" | |
# Handle None values | |
if review is None: | |
return 'neutral' # Or any default value you prefer | |
# Get sentiment scores | |
sentiment = sia.polarity_scores(review) | |
# Determine sentiment category | |
if sentiment['compound'] > 0.05: | |
return 'positive' | |
elif sentiment['compound'] < -0.05: | |
return 'negative' | |
else: | |
return 'neutral' | |
# Apply sentiment analysis to classify each review using the correct column name 'cleaned_reviews' | |
df['Sentiment'] = df['cleaned_reviews'].apply(classify_sentiment) | |
# Group reviews by sentiment | |
positive_reviews = df[df['Sentiment'] == 'positive'] | |
neutral_reviews = df[df['Sentiment'] == 'neutral'] | |
negative_reviews = df[df['Sentiment'] == 'negative'] | |
# Display results in a structured table | |
def display_table(df, sentiment, title): | |
print(f"\n{title} Reviews:") | |
display_df = df[['hotel_name', 'cleaned_reviews', 'Sentiment']].head(5) | |
print(display_df.to_markdown(index=False)) | |
# Display structured tables for each sentiment category | |
display_table(positive_reviews, 'positive', "Positive") | |
display_table(neutral_reviews, 'neutral', "Neutral") | |
display_table(negative_reviews, 'negative', "Negative") | |
"""# Analyzing and Visualizing Top-Rated Hotels in a Selected Locality""" | |
# Check for unique localities | |
unique_localities = df['locality'].unique() | |
print(f"Number of unique localities: {len(unique_localities)}") | |
print("Sample localities:", unique_localities) | |
# Prompt user to choose a locality | |
print("\nAvailable localities:") | |
for index, locality in enumerate(unique_localities): | |
print(f"{index + 1}. {locality}") | |
selected_index = int(input("\nSelect a locality by number: ")) - 1 | |
selected_locality = unique_localities[selected_index] | |
print(f"\nYou selected: {selected_locality}") | |
# Filter DataFrame by the selected locality | |
df_selected_locality = df[df['locality'] == selected_locality] | |
# Analyze and plot the selected locality | |
positive_review_counts_locality = df_selected_locality[df_selected_locality['Sentiment'] == 'positive'].groupby('hotel_name').size().reset_index(name='Positive Review Count') | |
top_hotels_locality = positive_review_counts_locality.sort_values(by='Positive Review Count', ascending=False).head(15) | |
plt.figure(figsize=(10, 6)) | |
ax = sns.barplot(data=top_hotels_locality, y='hotel_name', x='Positive Review Count', palette='viridis') | |
plt.title(f'Top Hotels in {selected_locality} with the Most Positive Reviews') | |
plt.xlabel('Number of Positive Reviews') | |
plt.ylabel('Hotel Name') | |
plt.xlim(0, top_hotels_locality['Positive Review Count'].max() * 1.1) # Adjust x-axis limit | |
plt.show() | |
"""# Hotel Review Summarization and Rating Visualization""" | |
from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM | |
# Load the tokenizer and model explicitly | |
tokenizer = AutoTokenizer.from_pretrained("mrm8488/bert-mini2bert-mini-finetuned-cnn_daily_mail-summarization") | |
model = AutoModelForSeq2SeqLM.from_pretrained("mrm8488/bert-mini2bert-mini-finetuned-cnn_daily_mail-summarization") | |
# Initialize the summarization pipeline with the tokenizer and model | |
pipe = pipeline("summarization", model=model, tokenizer=tokenizer) | |
# Group reviews by hotel | |
hotel_reviews = df.groupby('hotel_name')['cleaned_reviews'].apply(list).to_dict() | |
# Generate summaries for each hotel | |
hotel_summaries_detailed = {} | |
for hotel, reviews in hotel_reviews.items(): | |
all_reviews_text = ' '.join(reviews) | |
# Tokenize the input text and truncate to the model's maximum length | |
inputs = tokenizer(all_reviews_text, truncation=True, max_length=512, return_tensors="pt") # Adjust max_length if needed | |
# Summarize using the model | |
summary_ids = model.generate(**inputs, max_length=100) # Adjust max summary length as needed | |
summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True) | |
hotel_summaries_detailed[hotel] = { | |
"summary": summary | |
} | |
# Print detailed summaries | |
for hotel, data in hotel_summaries_detailed.items(): | |
print(f"Hotel: {hotel}") | |
print(f"Summary: {data['summary']}\n") | |
df.rating_value.value_counts() | |
import pandas as pd | |
import matplotlib.pyplot as plt | |
# Sample DataFrame setup with rating counts | |
rating_data = { | |
'rating_value': [4.5, 5.0, 4.0, 3.5, 3.0], | |
'count': [2677, 1520, 1520, 200, 80] | |
} | |
df_ratings = pd.DataFrame(rating_data) | |
# Calculate total count and percentage for each rating | |
df_ratings['percentage'] = (df_ratings['count'] / df_ratings['count'].sum()) * 100 | |
# Plotting the pie chart | |
plt.figure(figsize=(8, 8)) | |
plt.pie(df_ratings['percentage'], labels=df_ratings['rating_value'], autopct='%1.1f%%', startangle=140, colors=plt.cm.Paired.colors) | |
plt.title('Distribution of Hotel Ratings', fontsize=16, fontweight='bold') | |
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. | |
plt.show() | |
import pandas as pd | |
# Create a list to store the data | |
summary_data = [] | |
# Iterate through the hotel summaries and extract data | |
for hotel, summary_info in hotel_summaries_detailed.items(): | |
summary_data.append({ | |
'hotel_name': hotel, | |
'summary': summary_info['summary'] | |
}) | |
# Create a DataFrame from the extracted data | |
summary_df = pd.DataFrame(summary_data) | |
# Calculate average rating for each hotel | |
average_ratings = df.groupby('hotel_name')['rating_value'].mean() | |
# Add average rating to summary_df | |
summary_df = summary_df.merge(average_ratings, on='hotel_name', how='left') | |
summary_df.rename(columns={'rating_value': 'average_rating'}, inplace=True) | |
# Merge hotel_description and city from original DataFrame | |
summary_df = summary_df.merge(df[['hotel_name', 'hotel_description', 'locality']].drop_duplicates('hotel_name'), on='hotel_name', how='left') | |
# Merge hotel_image from original DataFrame | |
# Get unique hotel images | |
hotel_images = df[['hotel_name', 'hotel_image']].drop_duplicates('hotel_name') | |
# Merge hotel images into summary_df | |
summary_df = summary_df.merge(hotel_images, on='hotel_name', how='left') | |
summary_df | |
# Plot locality vs average_rating using a box plot | |
figsize = (8, 1.2 * len(summary_df['locality'].unique())) | |
plt.figure(figsize=figsize) | |
sns.boxplot(data=summary_df, x='average_rating', y='locality', palette='Dark2') | |
sns.despine(top=True, right=True, bottom=True, left=True) | |
# Add title and labels | |
plt.title('Distribution of Average Hotel Ratings by Locality') | |
"""By using insights from the box plot, businesses can better understand customer preferences and satisfaction levels. This helps them improve service quality and meet customer expectations, leading to happier customers and stronger customer relationships. Ultimately, this benefits both the business and its customers, creating a positive outcome for everyone involved. | |
# Semantic Search and Similarity | |
""" | |
from sentence_transformers import SentenceTransformer, util | |
embedding = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2') | |
#sample= summary_df[:20] | |
summary_df["embedding"] = summary_df["summary"].apply(lambda x: embedding.encode(x)) | |
from sklearn.metrics.pairwise import cosine_similarity | |
from PIL import Image | |
from IPython.display import display | |
import requests | |
def search(query): | |
query_embedding = embedding.encode(query) | |
summary_df["similarity"] = summary_df["embedding"].apply(lambda x: cosine_similarity([query_embedding], [x])[0][0]) | |
results = summary_df.sort_values("similarity", ascending=False).head(3)# we can chage top | |
print("Top 3 most similar hotels:") | |
for index, row in results.iterrows(): | |
print(f"Hotel Name: {row['hotel_name']}") | |
print(f"hotel description: {row['hotel_description']}") | |
print(f"summary: {row['summary']}") | |
print(f"locality: {row['locality']}") | |
print(f"Similarity Score: {row['similarity']}\n") | |
# Open the image using Image.open() and display it | |
image = Image.open(requests.get(row['hotel_image'], stream=True).raw) # Assuming 'hotel_image' contains a URL | |
display(image.resize((200, 200))) # Resize and display the image | |
print("\n") | |
# Example usage | |
query = 'a hotel in london and great food nearby but not too expensive' | |
q_cleaned = clean_text(query) | |
results = search(q_cleaned) | |
print(results) | |
"""# Interactive Search Interface""" | |
import gradio as gr | |
from sklearn.metrics.pairwise import cosine_similarity | |
from PIL import Image | |
import requests | |
import pandas as pd | |
from sentence_transformers import SentenceTransformer | |
# تحميل نموذج Sentence Transformer لاستخراج المتجهات | |
embedding_model = SentenceTransformer('all-MiniLM-L6-v2') | |
# إعداد البيانات - هذه مجرد عينة من البيانات | |
data = { | |
"hotel_name": ["Hotel A", "Hotel B", "Hotel C"], | |
"hotel_description": [ | |
"Beautiful hotel with sea view", | |
"Luxury hotel with great amenities", | |
"Affordable hotel with excellent location" | |
], | |
"summary": [ | |
"Sea view and modern rooms.", | |
"Luxurious and spacious.", | |
"Economical and well-located." | |
], | |
"locality": ["London", "Paris", "New York"], | |
"hotel_image": [ | |
"https://example.com/hotelA.jpg", # استبدل هذه الروابط بروابط صور حقيقية | |
"https://example.com/hotelB.jpg", | |
"https://example.com/hotelC.jpg" | |
] | |
} | |
summary_df = pd.DataFrame(data) | |
summary_df["embedding"] = summary_df["hotel_description"].apply(lambda x: embedding_model.encode(x)) | |
def search(query): | |
query_embedding = embedding_model.encode(query) | |
summary_df["similarity"] = summary_df["embedding"].apply(lambda x: cosine_similarity([query_embedding], [x])[0][0]) | |
results = summary_df.sort_values("similarity", ascending=False).head(3) # نعرض أفضل 3 نتائج | |
output = [] | |
for index, row in results.iterrows(): | |
hotel_info = f"**Hotel Name:** {row['hotel_name']}\n" \ | |
f"**Description:** {row['hotel_description']}\n" \ | |
f"**Summary:** {row['summary']}\n" \ | |
f"**Locality:** {row['locality']}\n" \ | |
f"**Similarity Score:** {row['similarity']:.2f}\n" | |
image_url = row['hotel_image'] | |
image = Image.open(requests.get(image_url, stream=True).raw).resize((200, 200)) | |
output.append((hotel_info, image)) | |
return output | |
def gradio_interface(query): | |
results = search(query) | |
return results | |
# Create a Gradio interface | |
# Update to use gr.Textbox for both inputs and outputs | |
demo = gr.Interface( | |
fn=search_gradio, | |
inputs=gr.Textbox(lines=2, label="Enter your query"), # Use gr.Textbox directly | |
outputs=gr.Textbox(label="Search Results") # Use gr.Textbox directly | |
) | |
demo.launch() |