krishnaveni76 commited on
Commit
c3c7748
·
1 Parent(s): ab6b19a

Final changes

Browse files
.gitattributes CHANGED
@@ -32,4 +32,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
32
  *.xz filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text assets/project_architecture.gif filter=lfs diff=lfs merge=lfs -text
 
 
32
  *.xz filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/project_architecture.gif filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,153 +1,153 @@
1
- ---
2
- title: Anime Recommendation System
3
- emoji: 📚
4
- colorFrom: purple
5
- colorTo: yellow
6
- sdk: streamlit
7
- sdk_version: 1.41.1
8
- app_file: app.py
9
- pinned: false
10
- license: apache-2.0
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
14
-
15
- # Anime Recommendation system
16
-
17
- This is an **Anime Recommendation System** that combines multiple recommendation techniques such as **Collaborative Filtering**, **Content-Based Filtering**, and **Popularity-Based Filtering**. We used the **AnimeList 2023 dataset**, but to optimize computational cost and storage, we included only animes with an average rating above **6.0**. The system is designed for **continuous data ingestion and transformation** and is fully **dockerized** for seamless deployment.
18
-
19
- The system is hosted on **Hugging Face Spaces** and fetches datasets and pre-trained models from **Hugging Face Hub** to generate **personalized anime recommendations** based on user preferences and anime features.
20
-
21
- ![assets/animes.jpg](assets/animes.jpg)
22
-
23
- ## Live Demo 🤗
24
- [Anime Recommendation System App](https://huggingface.co/spaces/krishnaveni76/Anime-Recommendation-System)
25
-
26
- ## Tech Stacks 🛠️
27
-
28
- - **Python**: Main programming language used for building recommendation algorithms and Streamlit app.
29
- - **Docker**: Containerizes the application to ensure a consistent environment across different platforms.
30
- - **Streamlit**: For building and deploying the web app that serves the recommendations.
31
- - **Hugging Face Spaces**: Hosts the Streamlit-based recommendation system.
32
- - **Hugging Face Datasets**: Stores and retrieves anime datasets for processing.
33
- - **Hugging Face Models**: Stores the pre-trained recommendation models for inference.
34
-
35
- ## Pipeline 🚀
36
-
37
- ![assets/project_architecture.gif](assets/project_architecture.gif)
38
-
39
- The pipeline follows a structured sequence of steps to build an **Anime Recommendation System**, including data ingestion, transformation, and multiple recommendation models.
40
-
41
- ### 1. Data Ingestion 📥
42
- - Initiates the **data ingestion process**, where anime data is loaded from Hugging Face datasets.
43
- - The ingested data is saved as artifacts in a local folder for further processing.
44
-
45
- ### 2. Data Transformation 🔄
46
- - Cleans, transforms, and processes the raw data into a structured format.
47
- - Extracts important features required for **Content-Based Filtering** and prepares data for **Collaborative Filtering**.
48
-
49
- ### 3. Collaborative Filtering 🤝
50
- - Implements **three collaborative filtering models** to recommend anime based on user preferences:
51
- - **Singular Value Decomposition (SVD)**: Factorizes the user-item interaction matrix to make personalized recommendations.
52
- - **Item-Based K-Nearest Neighbors (Item-KNN)**: Recommends anime similar to a given anime based on user ratings.
53
- - **User-Based K-Nearest Neighbors (User-KNN)**: Suggests anime that users with similar preferences have liked.
54
- - The chosen model is trained using **transformed data**, and the final trained model is stored as an artifact.
55
- - Once trained, it can generate recommendations for users or anime titles.
56
-
57
- ![assets/collaborative and contentbased filtering.png](assets/collaborative_and_contentbased_filtering.png)
58
-
59
- ### 4. Content-Based Filtering 🎭
60
- - Uses extracted anime features like genres to train a **Content-Based Recommendation Model**.
61
- - This model recommends anime similar to those a user has watched or liked.
62
-
63
- ### 5. Popularity-Based Filtering ⭐
64
- This recommendation system ranks anime based on various **popularity metrics**, making it ideal for users who want to discover trending or highly-rated shows **without needing personalized preferences**.
65
-
66
- The system applies different filters to sort anime based on:
67
-
68
- - **Most Popular** 🎭: Anime ranked by **popularity score**, highlighting the most widely recognized titles.
69
- - **Top Ranked** 🏆: Highest-rated anime, based on **official ranking metrics**.
70
- - **Overall Top Rated** ⭐: Best-rated anime, sorted by **average user ratings**.
71
- - **Most Favorited** ❤️: Anime with the highest number of **favorites**, indicating strong fan appreciation.
72
- - **Highest Member Count** 👥: Anime with the largest **viewer base**, showing widespread appeal.
73
- - **Popular Among Members** 🔥: Anime with a **high number of members and strong ratings**, making them community favorites.
74
- - **Highest Average Rating** 🎖️: Shows that have the **best average rating** after handling missing values.
75
-
76
- ## Artifacts Storage 📂
77
-
78
- All intermediate and final outputs, including processed datasets and trained models, are first saved locally in the **Artifacts** folder. These artifacts are then uploaded to **Hugging Face** for efficient storage and easy access.
79
-
80
- When building the **Streamlit** app, these datasets and trained models are retrieved directly from **Hugging Face**, ensuring seamless integration and scalability.
81
-
82
- ![assets/Artifacts.png](assets/artifacts.png)
83
-
84
- - The datasets used in this project are available at:
85
- - [Anime and User Ratings](https://www.kaggle.com/datasets/krishnaveniponna/anime-and-ratings-list-dataset-2023)
86
-
87
- - You can find the Artifacts of trained models here:
88
- - [Pre-trained Models](https://huggingface.co/krishnaveni76/anime-recommendation-models)
89
-
90
- ## Deployment on Hugging Face Spaces 🚀
91
-
92
- This project is deployed using **Hugging Face Spaces**, which provides a seamless way to host **Streamlit applications**. The application pulls the datasets and trained models from Hugging Face and runs inside a **Docker container**.
93
-
94
- ### Pre-requisites
95
- - Docker
96
- - Hugging Face (for datasets and trained models)
97
- - Python 3.8+
98
- - Hugging Face Spaces account
99
-
100
- ### Local step 🔧
101
- 1. **Clone the repository**
102
- ```bash
103
- git clone https://huggingface.co/spaces/krishnaveni76/Anime-Recommendation-System
104
- cd Anime-Recommendation-System
105
- ```
106
- 2. **Set Up a Virtual Environment**:
107
- ```bash
108
- # For macOS and Linux:
109
- python3 -m venv venv
110
- # For Windows:
111
- python -m venv venv
112
- ```
113
- 3. **Activate the Virtual Environment**:
114
- ```bash
115
- # For macOS and Linux:
116
- source venv/bin/activate
117
- # For Windows:
118
- .\venv\Scripts\activate
119
- ```
120
- 4. **Install Required Dependencies**:
121
- ```bash
122
- pip install -r requirements.txt
123
- ```
124
-
125
- ### Running the Pipeline 🔄
126
- To process the data and train the recommendation models, run the following command:
127
-
128
- ```bash
129
- python run_pipeline.py
130
- ```
131
- This will execute the pipeline, ingest and transform data, and train the models before making recommendations.
132
-
133
- ### Running with Docker 🚀
134
- To run the application inside a Docker container, follow these steps:
135
-
136
- 1. Build the Docker Image
137
- ```bash
138
- docker build -t anime-recommendation-system .
139
- ```
140
- 2. Run the Docker Container
141
- ```bash
142
- docker run -p 8501:8501 anime-recommendation-system
143
- ```
144
- This will start the Streamlit application, which can be accessed at `http://localhost:8501`.
145
-
146
- ### Contact 📫
147
- For any questions, suggestions, or collaboration opportunities, feel free to reach out:
148
-
149
- 📧Email: [email protected]
150
-
151
- 🌐 LinkedIn: [Krishnaveni Ponna](https://www.linkedin.com/in/krishnaveni-ponna-28ab93239)
152
-
153
  🐦 Twitter: [@Krishnaveni076](https://x.com/Krishnaveni076)
 
1
+ ---
2
+ title: Anime Recommendation System
3
+ emoji: 📚
4
+ colorFrom: purple
5
+ colorTo: yellow
6
+ sdk: streamlit
7
+ sdk_version: 1.41.1
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
14
+
15
+ # Anime Recommendation system
16
+
17
+ This is an **Anime Recommendation System** that combines multiple recommendation techniques such as **Collaborative Filtering**, **Content-Based Filtering**, and **Popularity-Based Filtering**. We used the **AnimeList 2023 dataset**, but to optimize computational cost and storage, we included only animes with an average rating above **6.0**. The system is designed for **continuous data ingestion and transformation** and is fully **dockerized** for seamless deployment.
18
+
19
+ The system is hosted on **Hugging Face Spaces** and fetches datasets and pre-trained models from **Hugging Face Hub** to generate **personalized anime recommendations** based on user preferences and anime features.
20
+
21
+ ![assets/animes.jpg](assets/animes.jpg)
22
+
23
+ ## Live Demo 🤗
24
+ [Anime Recommendation System App](https://huggingface.co/spaces/krishnaveni76/Anime-Recommendation-System)
25
+
26
+ ## Tech Stacks 🛠️
27
+
28
+ - **Python**: Main programming language used for building recommendation algorithms and Streamlit app.
29
+ - **Docker**: Containerizes the application to ensure a consistent environment across different platforms.
30
+ - **Streamlit**: For building and deploying the web app that serves the recommendations.
31
+ - **Hugging Face Spaces**: Hosts the Streamlit-based recommendation system.
32
+ - **Hugging Face Datasets**: Stores and retrieves anime datasets for processing.
33
+ - **Hugging Face Models**: Stores the pre-trained recommendation models for inference.
34
+
35
+ ## Pipeline 🚀
36
+
37
+ ![assets/project_architecture.gif](assets/project_architecture.gif)
38
+
39
+ The pipeline follows a structured sequence of steps to build an **Anime Recommendation System**, including data ingestion, transformation, and multiple recommendation models.
40
+
41
+ ### 1. Data Ingestion 📥
42
+ - Initiates the **data ingestion process**, where anime data is loaded from Hugging Face datasets.
43
+ - The ingested data is saved as artifacts in a local folder for further processing.
44
+
45
+ ### 2. Data Transformation 🔄
46
+ - Cleans, transforms, and processes the raw data into a structured format.
47
+ - Extracts important features required for **Content-Based Filtering** and prepares data for **Collaborative Filtering**.
48
+
49
+ ### 3. Collaborative Filtering 🤝
50
+ - Implements **three collaborative filtering models** to recommend anime based on user preferences:
51
+ - **Singular Value Decomposition (SVD)**: Factorizes the user-item interaction matrix to make personalized recommendations.
52
+ - **Item-Based K-Nearest Neighbors (Item-KNN)**: Recommends anime similar to a given anime based on user ratings.
53
+ - **User-Based K-Nearest Neighbors (User-KNN)**: Suggests anime that users with similar preferences have liked.
54
+ - The chosen model is trained using **transformed data**, and the final trained model is stored as an artifact.
55
+ - Once trained, it can generate recommendations for users or anime titles.
56
+
57
+ ![assets/collaborative and contentbased filtering.png](assets/collaborative_and_contentbased_filtering.png)
58
+
59
+ ### 4. Content-Based Filtering 🎭
60
+ - Uses extracted anime features like genres to train a **Content-Based Recommendation Model**.
61
+ - This model recommends anime similar to those a user has watched or liked.
62
+
63
+ ### 5. Popularity-Based Filtering ⭐
64
+ This recommendation system ranks anime based on various **popularity metrics**, making it ideal for users who want to discover trending or highly-rated shows **without needing personalized preferences**.
65
+
66
+ The system applies different filters to sort anime based on:
67
+
68
+ - **Most Popular** 🎭: Anime ranked by **popularity score**, highlighting the most widely recognized titles.
69
+ - **Top Ranked** 🏆: Highest-rated anime, based on **official ranking metrics**.
70
+ - **Overall Top Rated** ⭐: Best-rated anime, sorted by **average user ratings**.
71
+ - **Most Favorited** ❤️: Anime with the highest number of **favorites**, indicating strong fan appreciation.
72
+ - **Highest Member Count** 👥: Anime with the largest **viewer base**, showing widespread appeal.
73
+ - **Popular Among Members** 🔥: Anime with a **high number of members and strong ratings**, making them community favorites.
74
+ - **Highest Average Rating** 🎖️: Shows that have the **best average rating** after handling missing values.
75
+
76
+ ## Artifacts Storage 📂
77
+
78
+ All intermediate and final outputs, including processed datasets and trained models, are first saved locally in the **Artifacts** folder. These artifacts are then uploaded to **Hugging Face** for efficient storage and easy access.
79
+
80
+ When building the **Streamlit** app, these datasets and trained models are retrieved directly from **Hugging Face**, ensuring seamless integration and scalability.
81
+
82
+ ![assets/Artifacts.png](assets/artifacts.png)
83
+
84
+ - The datasets used in this project are available at:
85
+ - [Anime and User Ratings](https://www.kaggle.com/datasets/krishnaveniponna/anime-and-ratings-list-dataset-2023)
86
+
87
+ - You can find the Artifacts of trained models here:
88
+ - [Pre-trained Models](https://huggingface.co/krishnaveni76/anime-recommendation-models)
89
+
90
+ ## Deployment on Hugging Face Spaces 🚀
91
+
92
+ This project is deployed using **Hugging Face Spaces**, which provides a seamless way to host **Streamlit applications**. The application pulls the datasets and trained models from Hugging Face and runs inside a **Docker container**.
93
+
94
+ ### Pre-requisites
95
+ - Docker
96
+ - Hugging Face (for datasets and trained models)
97
+ - Python 3.8+
98
+ - Hugging Face Spaces account
99
+
100
+ ### Local step 🔧
101
+ 1. **Clone the repository**
102
+ ```bash
103
+ git clone https://huggingface.co/spaces/krishnaveni76/Anime-Recommendation-System
104
+ cd Anime-Recommendation-System
105
+ ```
106
+ 2. **Set Up a Virtual Environment**:
107
+ ```bash
108
+ # For macOS and Linux:
109
+ python3 -m venv venv
110
+ # For Windows:
111
+ python -m venv venv
112
+ ```
113
+ 3. **Activate the Virtual Environment**:
114
+ ```bash
115
+ # For macOS and Linux:
116
+ source venv/bin/activate
117
+ # For Windows:
118
+ .\venv\Scripts\activate
119
+ ```
120
+ 4. **Install Required Dependencies**:
121
+ ```bash
122
+ pip install -r requirements.txt
123
+ ```
124
+
125
+ ### Running the Pipeline 🔄
126
+ To process the data and train the recommendation models, run the following command:
127
+
128
+ ```bash
129
+ python run_pipeline.py
130
+ ```
131
+ This will execute the pipeline, ingest and transform data, and train the models before making recommendations.
132
+
133
+ ### Running with Docker 🚀
134
+ To run the application inside a Docker container, follow these steps:
135
+
136
+ 1. Build the Docker Image
137
+ ```bash
138
+ docker build -t anime-recommendation-system .
139
+ ```
140
+ 2. Run the Docker Container
141
+ ```bash
142
+ docker run -p 8501:8501 anime-recommendation-system
143
+ ```
144
+ This will start the Streamlit application, which can be accessed at `http://localhost:8501`.
145
+
146
+ ### Contact 📫
147
+ For any questions, suggestions, or collaboration opportunities, feel free to reach out:
148
+
149
+ 📧Email: [email protected]
150
+
151
+ 🌐 LinkedIn: [Krishnaveni Ponna](https://www.linkedin.com/in/krishnaveni-ponna-28ab93239)
152
+
153
  🐦 Twitter: [@Krishnaveni076](https://x.com/Krishnaveni076)
anime_recommender/components/collaborative_recommender.py CHANGED
@@ -3,9 +3,10 @@ from anime_recommender.loggers.logging import logging
3
  from anime_recommender.exception.exception import AnimeRecommendorException
4
  from anime_recommender.entity.config_entity import CollaborativeModelConfig
5
  from anime_recommender.entity.artifact_entity import DataTransformationArtifact, CollaborativeModelArtifact
6
- from anime_recommender.utils.main_utils.utils import load_csv_data, save_model, load_object
7
  from anime_recommender.model_trainer.collaborative_modelling import CollaborativeAnimeRecommender
8
-
 
9
  class CollaborativeModelTrainer:
10
  """
11
  Trains and saves collaborative filtering recommendation models.
@@ -29,63 +30,67 @@ class CollaborativeModelTrainer:
29
  except Exception as e:
30
  raise AnimeRecommendorException(e, sys)
31
 
32
- def initiate_model_trainer(self, model_type: str) -> CollaborativeModelArtifact:
33
  """
34
- Trains and saves the specified collaborative filtering model.
35
- Args:
36
- model_type (str): The type of model to train.
37
- Choices: 'svd', 'item_knn', 'user_knn'.
38
  Returns:
39
- CollaborativeModelArtifact: Object containing the file path of the trained model.
40
  """
41
  try:
42
  logging.info("Loading transformed data...")
43
  df = load_csv_data(self.data_transformation_artifact.merged_file_path)
44
- recommender = CollaborativeAnimeRecommender(df)
45
-
46
- if model_type == 'svd':
47
- logging.info("Training and saving SVD model...")
48
- recommender.train_svd()
49
- save_model(recommender.svd, self.collaborative_model_trainer_config.svd_trained_model_file_path)
50
-
51
- logging.info("Loading pre-trained SVD model...")
52
- svd_model = load_object(self.collaborative_model_trainer_config.svd_trained_model_file_path)
53
- svd_recommendations = recommender.get_svd_recommendations(user_id=436, n=10, svd_model=svd_model)
54
- logging.info(f"SVD recommendations: {svd_recommendations}")
55
- return CollaborativeModelArtifact(
56
- svd_file_path=self.collaborative_model_trainer_config.svd_trained_model_file_path
57
- )
58
-
59
- elif model_type == 'item_knn':
60
- logging.info("Training and saving KNN item-based model...")
61
- recommender.train_knn_item_based()
62
- save_model(recommender.knn_item_based, self.collaborative_model_trainer_config.item_knn_trained_model_file_path)
63
 
64
- logging.info("Loading pre-trained item-based KNN model...")
65
- item_knn_model = load_object(self.collaborative_model_trainer_config.item_knn_trained_model_file_path)
66
- item_based_recommendations = recommender.get_item_based_recommendations(
67
- anime_name='One Piece', n_recommendations=10, knn_item_model=item_knn_model
68
- )
69
- logging.info(f"Item Based recommendations: {item_based_recommendations}")
70
- return CollaborativeModelArtifact(
71
- item_based_knn_file_path=self.collaborative_model_trainer_config.item_knn_trained_model_file_path
72
- )
73
-
74
- elif model_type == 'user_knn':
75
- logging.info("Training and saving KNN user-based model...")
76
- recommender.train_knn_user_based()
77
- save_model(recommender.knn_user_based, self.collaborative_model_trainer_config.user_knn_trained_model_file_path)
78
 
79
- logging.info("Loading pre-trained user-based KNN model...")
80
- user_knn_model = load_object(self.collaborative_model_trainer_config.user_knn_trained_model_file_path)
81
- user_based_recommendations = recommender.get_user_based_recommendations(
82
- user_id=817, n_recommendations=10, knn_user_model=user_knn_model
83
- )
84
- logging.info(f"User Based recommendations: {user_based_recommendations}")
85
- return CollaborativeModelArtifact(
86
- user_based_knn_file_path=self.collaborative_model_trainer_config.user_knn_trained_model_file_path
87
- )
88
- else:
89
- raise ValueError("Invalid model_type. Choose from 'svd', 'item_knn', or 'user_knn'.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  except Exception as e:
91
- raise AnimeRecommendorException(f"Error in CollaborativeModelTrainer: {str(e)}", sys)
 
3
  from anime_recommender.exception.exception import AnimeRecommendorException
4
  from anime_recommender.entity.config_entity import CollaborativeModelConfig
5
  from anime_recommender.entity.artifact_entity import DataTransformationArtifact, CollaborativeModelArtifact
6
+ from anime_recommender.utils.main_utils.utils import load_csv_data, save_model, load_object, upload_model_to_huggingface
7
  from anime_recommender.model_trainer.collaborative_modelling import CollaborativeAnimeRecommender
8
+ from anime_recommender.constant import *
9
+
10
  class CollaborativeModelTrainer:
11
  """
12
  Trains and saves collaborative filtering recommendation models.
 
30
  except Exception as e:
31
  raise AnimeRecommendorException(e, sys)
32
 
33
+ def initiate_model_trainer(self) -> CollaborativeModelArtifact:
34
  """
35
+ Trains and saves all collaborative filtering models.
36
+
 
 
37
  Returns:
38
+ CollaborativeModelArtifact: Object containing file paths of all trained models.
39
  """
40
  try:
41
  logging.info("Loading transformed data...")
42
  df = load_csv_data(self.data_transformation_artifact.merged_file_path)
43
+ recommender = CollaborativeAnimeRecommender(df)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
+ # Train and save SVD model
46
+ logging.info("Training and saving SVD model...")
47
+ recommender.train_svd()
48
+ save_model(model=recommender.svd,file_path= self.collaborative_model_trainer_config.svd_trained_model_file_path)
49
+ upload_model_to_huggingface(
50
+ model_path=self.collaborative_model_trainer_config.svd_trained_model_file_path,
51
+ repo_id=MODELS_FILEPATH,
52
+ filename=MODEL_TRAINER_SVD_TRAINED_MODEL_NAME
53
+ )
54
+ logging.info("Loading pre-trained SVD model...")
55
+ svd_model = load_object(self.collaborative_model_trainer_config.svd_trained_model_file_path)
56
+ svd_recommendations = recommender.get_svd_recommendations(user_id=436, n=10, svd_model=svd_model)
57
+ logging.info(f"SVD recommendations: {svd_recommendations}")
 
58
 
59
+ # Train and save Item-Based KNN model
60
+ logging.info("Training and saving KNN item-based model...")
61
+ recommender.train_knn_item_based()
62
+ save_model(model=recommender.knn_item_based, file_path=self.collaborative_model_trainer_config.item_knn_trained_model_file_path)
63
+ upload_model_to_huggingface(
64
+ model_path=self.collaborative_model_trainer_config.item_knn_trained_model_file_path,
65
+ repo_id=MODELS_FILEPATH,
66
+ filename=MODEL_TRAINER_ITEM_KNN_TRAINED_MODEL_NAME
67
+ )
68
+ logging.info("Loading pre-trained item-based KNN model...")
69
+ item_knn_model = load_object(self.collaborative_model_trainer_config.item_knn_trained_model_file_path)
70
+ item_based_recommendations = recommender.get_item_based_recommendations(
71
+ anime_name='One Piece', n_recommendations=10, knn_item_model=item_knn_model
72
+ )
73
+ logging.info(f"Item Based recommendations: {item_based_recommendations}")
74
+
75
+ # Train and save User-Based KNN model
76
+ logging.info("Training and saving KNN user-based model...")
77
+ recommender.train_knn_user_based()
78
+ save_model(model=recommender.knn_user_based,file_path= self.collaborative_model_trainer_config.user_knn_trained_model_file_path)
79
+ upload_model_to_huggingface(
80
+ model_path=self.collaborative_model_trainer_config.user_knn_trained_model_file_path,
81
+ repo_id=MODELS_FILEPATH,
82
+ filename=MODEL_TRAINER_USER_KNN_TRAINED_MODEL_NAME
83
+ )
84
+ logging.info("Loading pre-trained user-based KNN model...")
85
+ user_knn_model = load_object(self.collaborative_model_trainer_config.user_knn_trained_model_file_path)
86
+ user_based_recommendations = recommender.get_user_based_recommendations(
87
+ user_id=817, n_recommendations=10, knn_user_model=user_knn_model
88
+ )
89
+ logging.info(f"User Based recommendations: {user_based_recommendations}")
90
+ return CollaborativeModelArtifact(
91
+ svd_file_path=self.collaborative_model_trainer_config.svd_trained_model_file_path,
92
+ item_based_knn_file_path=self.collaborative_model_trainer_config.item_knn_trained_model_file_path,
93
+ user_based_knn_file_path=self.collaborative_model_trainer_config.user_knn_trained_model_file_path
94
+ )
95
  except Exception as e:
96
+ raise AnimeRecommendorException(f"Error in CollaborativeModelTrainer: {str(e)}", sys)
anime_recommender/components/content_based_recommender.py CHANGED
@@ -3,7 +3,7 @@ from anime_recommender.loggers.logging import logging
3
  from anime_recommender.exception.exception import AnimeRecommendorException
4
  from anime_recommender.entity.config_entity import ContentBasedModelConfig
5
  from anime_recommender.entity.artifact_entity import ContentBasedModelArtifact, DataIngestionArtifact
6
- from anime_recommender.utils.main_utils.utils import load_csv_data
7
  from anime_recommender.model_trainer.content_based_modelling import ContentBasedRecommender
8
  from anime_recommender.constant import *
9
 
@@ -42,7 +42,12 @@ class ContentBasedModelTrainer:
42
  recommender = ContentBasedRecommender(df=df )
43
 
44
  # Save the model (TF-IDF and cosine similarity matrix)
45
- recommender.save_model(self.content_based_model_trainer_config.cosine_similarity_model_file_path)
 
 
 
 
 
46
  logging.info("Model saved successfully.")
47
 
48
  logging.info("Loading saved model to get recommendations...")
 
3
  from anime_recommender.exception.exception import AnimeRecommendorException
4
  from anime_recommender.entity.config_entity import ContentBasedModelConfig
5
  from anime_recommender.entity.artifact_entity import ContentBasedModelArtifact, DataIngestionArtifact
6
+ from anime_recommender.utils.main_utils.utils import load_csv_data, upload_model_to_huggingface
7
  from anime_recommender.model_trainer.content_based_modelling import ContentBasedRecommender
8
  from anime_recommender.constant import *
9
 
 
42
  recommender = ContentBasedRecommender(df=df )
43
 
44
  # Save the model (TF-IDF and cosine similarity matrix)
45
+ recommender.save_model(model_path=self.content_based_model_trainer_config.cosine_similarity_model_file_path)
46
+ upload_model_to_huggingface(
47
+ model_path=self.content_based_model_trainer_config.cosine_similarity_model_file_path,
48
+ repo_id=MODELS_FILEPATH,
49
+ filename=MODEL_TRAINER_COSINESIMILARITY_MODEL_NAME
50
+ )
51
  logging.info("Model saved successfully.")
52
 
53
  logging.info("Loading saved model to get recommendations...")
anime_recommender/constant/__init__.py CHANGED
@@ -36,5 +36,4 @@ MODEL_TRAINER_ITEM_KNN_TRAINED_MODEL_NAME: str = "itembasedknn.pkl"
36
  MODEL_TRAINER_USER_KNN_TRAINED_MODEL_NAME: str = "userbasedknn.pkl"
37
 
38
  MODEL_TRAINER_CON_TRAINED_MODEL_DIR:str = "content_based_recommenders"
39
- MODEL_TRAINER_COSINESIMILARITY_MODEL_NAME:str = "cosine_similarity.pkl"
40
-
 
36
  MODEL_TRAINER_USER_KNN_TRAINED_MODEL_NAME: str = "userbasedknn.pkl"
37
 
38
  MODEL_TRAINER_CON_TRAINED_MODEL_DIR:str = "content_based_recommenders"
39
+ MODEL_TRAINER_COSINESIMILARITY_MODEL_NAME:str = "cosine_similarity.pkl"
 
anime_recommender/exception/exception.py CHANGED
@@ -2,14 +2,14 @@ import sys
2
 
3
  class AnimeRecommendorException(Exception):
4
  """
5
- Custom exception class for handling errors in the Energy Generation Prediction project.
6
 
7
  This class captures the error message, file name, and line number where an exception occurred.
8
  It is useful for debugging and identifying the source of the error in a structured way.
9
  """
10
  def __init__(self,error_message, error_details:sys):
11
  """
12
- Initialize the EnergyGenerationException instance.
13
 
14
  Args:
15
  error_message (str): The error message describing the exception.
 
2
 
3
  class AnimeRecommendorException(Exception):
4
  """
5
+ Custom exception class for handling errors in the Anime Recommendation project.
6
 
7
  This class captures the error message, file name, and line number where an exception occurred.
8
  It is useful for debugging and identifying the source of the error in a structured way.
9
  """
10
  def __init__(self,error_message, error_details:sys):
11
  """
12
+ Initialize the AnimeRecommendorException instance.
13
 
14
  Args:
15
  error_message (str): The error message describing the exception.
anime_recommender/pipelines/training_pipeline.py CHANGED
@@ -1,7 +1,6 @@
1
  import sys
2
  from anime_recommender.loggers.logging import logging
3
  from anime_recommender.exception.exception import AnimeRecommendorException
4
-
5
  from anime_recommender.components.data_ingestion import DataIngestion
6
  from anime_recommender.components.data_transformation import DataTransformation
7
  from anime_recommender.components.collaborative_recommender import CollaborativeModelTrainer
@@ -80,7 +79,7 @@ class TrainingPipeline:
80
  collaborative_model_trainer_config=collaborative_model_config,
81
  data_transformation_artifact=data_transformation_artifact
82
  )
83
- collaborative_model_trainer_artifact = collaborative_model_trainer.initiate_model_trainer(model_type='user_knn')
84
  logging.info(f"Collaborative Model Training completed: {collaborative_model_trainer_artifact}")
85
  return collaborative_model_trainer_artifact
86
  except Exception as e:
 
1
  import sys
2
  from anime_recommender.loggers.logging import logging
3
  from anime_recommender.exception.exception import AnimeRecommendorException
 
4
  from anime_recommender.components.data_ingestion import DataIngestion
5
  from anime_recommender.components.data_transformation import DataTransformation
6
  from anime_recommender.components.collaborative_recommender import CollaborativeModelTrainer
 
79
  collaborative_model_trainer_config=collaborative_model_config,
80
  data_transformation_artifact=data_transformation_artifact
81
  )
82
+ collaborative_model_trainer_artifact = collaborative_model_trainer.initiate_model_trainer()
83
  logging.info(f"Collaborative Model Training completed: {collaborative_model_trainer_artifact}")
84
  return collaborative_model_trainer_artifact
85
  except Exception as e:
anime_recommender/utils/main_utils/utils.py CHANGED
@@ -5,6 +5,7 @@ import joblib
5
  from anime_recommender.loggers.logging import logging
6
  from anime_recommender.exception.exception import AnimeRecommendorException
7
  from anime_recommender.constant import *
 
8
 
9
  def export_data_to_dataframe(dataframe: pd.DataFrame, file_path: str) -> pd.DataFrame:
10
  """
@@ -86,4 +87,26 @@ def load_object(file_path: str) -> object:
86
  return joblib.load(file_obj)
87
  except Exception as e:
88
  logging.error(f"Error loading object from {file_path}: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  raise AnimeRecommendorException(e, sys) from e
 
5
  from anime_recommender.loggers.logging import logging
6
  from anime_recommender.exception.exception import AnimeRecommendorException
7
  from anime_recommender.constant import *
8
+ from huggingface_hub import HfApi, HfFolder
9
 
10
  def export_data_to_dataframe(dataframe: pd.DataFrame, file_path: str) -> pd.DataFrame:
11
  """
 
87
  return joblib.load(file_obj)
88
  except Exception as e:
89
  logging.error(f"Error loading object from {file_path}: {e}")
90
+ raise AnimeRecommendorException(e, sys) from e
91
+
92
+ def upload_model_to_huggingface(model_path: str, repo_id: str, filename: str):
93
+ """
94
+ Uploads a trained model file to the specified Hugging Face repository.
95
+
96
+ Args:
97
+ model_path (str): Local path of the trained model file.
98
+ repo_id (str): Hugging Face repository ID (e.g., 'krishnaveni76/anime-recommendation-models').
99
+ filename (str): Name of the file when uploaded to Hugging Face.
100
+ """
101
+ try:
102
+ api = HfApi()
103
+ api.upload_file(
104
+ path_or_fileobj=model_path,
105
+ path_in_repo=filename,
106
+ repo_id=repo_id,
107
+ repo_type="model"
108
+ )
109
+ logging.info(f"Successfully uploaded {filename} to Hugging Face: {repo_id}")
110
+ except Exception as e:
111
+ logging.info(f"Error uploading model to Hugging Face: {str(e)}")
112
  raise AnimeRecommendorException(e, sys) from e
app.py CHANGED
@@ -1,242 +1,242 @@
1
- import pandas as pd
2
- import streamlit as st
3
- from anime_recommender.model_trainer.content_based_modelling import ContentBasedRecommender
4
- from anime_recommender.model_trainer.collaborative_modelling import CollaborativeAnimeRecommender
5
- from anime_recommender.model_trainer.top_anime_filtering import PopularityBasedFiltering
6
- import joblib
7
- from anime_recommender.constant import *
8
- from huggingface_hub import hf_hub_download
9
- from datasets import load_dataset
10
-
11
- def run_app():
12
- """
13
- Initializes the Streamlit app, loads necessary datasets and models,
14
- and provides a UI for anime recommendations based on three methods:
15
- Content-Based, Collaborative, and Popularity-Based Filtering. 🎬🎮
16
- """
17
-
18
- # Set page configuration
19
- st.set_page_config(page_title="Anime Recommendation System", layout="wide")
20
-
21
- # Load datasets if not present in session state
22
- if "anime_data" not in st.session_state or "anime_user_ratings" not in st.session_state:
23
- # Load datasets from Hugging Face (assuming no splits)
24
- animedataset = load_dataset(ANIME_FILE_PATH, split=None)
25
- mergeddataset = load_dataset(ANIMEUSERRATINGS_FILE_PATH, split=None)
26
-
27
- # Convert the dataset to Pandas DataFrame
28
- st.session_state.anime_data = pd.DataFrame(animedataset["train"])
29
- st.session_state.anime_user_ratings = pd.DataFrame(mergeddataset["train"])
30
-
31
- # Load models only once
32
- if "models_loaded" not in st.session_state:
33
- st.session_state.models_loaded = {}
34
- # Load models
35
- st.session_state.models_loaded["cosine_similarity_model"] = hf_hub_download(MODELS_FILEPATH, MODEL_TRAINER_COSINESIMILARITY_MODEL_NAME)
36
- st.session_state.models_loaded["item_based_knn_model_path"] = hf_hub_download(MODELS_FILEPATH, MODEL_TRAINER_ITEM_KNN_TRAINED_MODEL_NAME)
37
- st.session_state.models_loaded["user_based_knn_model_path"] = hf_hub_download(MODELS_FILEPATH, MODEL_TRAINER_USER_KNN_TRAINED_MODEL_NAME)
38
- st.session_state.models_loaded["svd_model_path"] = hf_hub_download(MODELS_FILEPATH, MODEL_TRAINER_SVD_TRAINED_MODEL_NAME)
39
-
40
- # Load the models using joblib
41
- with open(st.session_state.models_loaded["item_based_knn_model_path"], "rb") as f:
42
- st.session_state.models_loaded["item_based_knn_model"] = joblib.load(f)
43
-
44
- with open(st.session_state.models_loaded["user_based_knn_model_path"], "rb") as f:
45
- st.session_state.models_loaded["user_based_knn_model"] = joblib.load(f)
46
-
47
- with open(st.session_state.models_loaded["svd_model_path"], "rb") as f:
48
- st.session_state.models_loaded["svd_model"] = joblib.load(f)
49
-
50
- print("Models loaded successfully!")
51
-
52
- # Access the data from session state
53
- anime_data = st.session_state.anime_data
54
- anime_user_ratings = st.session_state.anime_user_ratings
55
-
56
- # # Display dataset info
57
- # st.write("Anime Data:")
58
- # st.dataframe(anime_data.head())
59
-
60
- # st.write("Anime User Ratings Data:")
61
- # st.dataframe(anime_user_ratings.head())
62
-
63
- # Access the models from session state
64
- cosine_similarity_model_path = hf_hub_download(MODELS_FILEPATH, MODEL_TRAINER_COSINESIMILARITY_MODEL_NAME)
65
- item_based_knn_model = st.session_state.models_loaded["item_based_knn_model"]
66
- user_based_knn_model = st.session_state.models_loaded["user_based_knn_model"]
67
- svd_model = st.session_state.models_loaded["svd_model"]
68
- print("Models loaded successfully!")
69
-
70
- # Streamlit UI
71
- app_selector = st.sidebar.radio(
72
- "Select App", ("Content-Based Recommender", "Collaborative Recommender", "Top Anime Recommender")
73
- )
74
-
75
- # Content-Based Recommender App
76
- if app_selector == "Content-Based Recommender":
77
- st.title("Content-Based Recommendation System")
78
- try:
79
-
80
- anime_list = anime_data["name"].tolist()
81
- anime_name = st.selectbox("Pick an anime..unlock similar anime recommendations..", anime_list)
82
-
83
- # Set number of recommendations
84
- max_recommendations = min(len(anime_data), 100)
85
- n_recommendations = st.slider("Number of Recommendations", 1, max_recommendations, 10)
86
-
87
- # Inject custom CSS for anime name font size
88
- st.markdown(
89
- """
90
- <style>
91
- .anime-title {
92
- font-size: 14px !important;
93
- font-weight: bold;
94
- text-align: center;
95
- margin-top: 5px;
96
- }
97
- </style>
98
- """,
99
- unsafe_allow_html=True,
100
- )
101
- # Get Recommendations
102
- if st.button("Get Recommendations"):
103
- try:
104
- recommender = ContentBasedRecommender(anime_data)
105
- recommendations = recommender.get_rec_cosine(anime_name, n_recommendations=n_recommendations,model_path=cosine_similarity_model_path)
106
-
107
- if isinstance(recommendations, str):
108
- st.warning(recommendations)
109
- elif recommendations.empty:
110
- st.warning("No recommendations found.🧐")
111
- else:
112
- st.write(f"Here are the Content-based Recommendations for {anime_name}:")
113
- cols = st.columns(5)
114
- for i, row in enumerate(recommendations.iterrows()):
115
- col = cols[i % 5]
116
- with col:
117
- st.image(row[1]['Image URL'], use_container_width=True)
118
- st.markdown(
119
- f"<div class='anime-title'>{row[1]['Anime name']}</div>",
120
- unsafe_allow_html=True,
121
- )
122
- st.caption(f"Genres: {row[1]['Genres']} | Rating: {row[1]['Rating']}")
123
- except Exception as e:
124
- st.error(f"Unexpected error: {str(e)}")
125
-
126
- except Exception as e:
127
- st.error(f"Unexpected error: {str(e)}")
128
-
129
- elif app_selector == "Collaborative Recommender":
130
- st.title("Collaborative Recommender System 🧑‍🤝‍🧑💬")
131
-
132
- try:
133
- # Sidebar for choosing the collaborative filtering method
134
- collaborative_method = st.sidebar.selectbox(
135
- "Choose a collaborative filtering method:",
136
- ["SVD Collaborative Filtering", "User-Based Collaborative Filtering", "Anime-Based KNN Collaborative Filtering"]
137
- )
138
-
139
- # User input
140
- if collaborative_method == "SVD Collaborative Filtering" or collaborative_method == "User-Based Collaborative Filtering":
141
- user_ids = anime_user_ratings['user_id'].unique()
142
- user_id = st.selectbox("Select your MyAnimeList user ID to get anime recommendations based on similar users", user_ids)
143
- n_recommendations = st.slider("Number of Recommendations:", min_value=1, max_value=50, value=10)
144
- elif collaborative_method == "Anime-Based KNN Collaborative Filtering":
145
- anime_list = anime_user_ratings["name"].dropna().unique().tolist()
146
- anime_name = st.selectbox("Pick an anime, and we'll suggest more titles you'll love", anime_list)
147
- n_recommendations = st.slider("Number of Recommendations:", min_value=1, max_value=50, value=10)
148
-
149
- # Get recommendations
150
- if st.button("Get Recommendations"):
151
- # Load the recommender
152
- recommender = CollaborativeAnimeRecommender(anime_user_ratings)
153
- if collaborative_method == "SVD Collaborative Filtering":
154
- recommendations = recommender.get_svd_recommendations(user_id, n=n_recommendations, svd_model=svd_model)
155
- elif collaborative_method == "User-Based Collaborative Filtering":
156
- recommendations = recommender.get_user_based_recommendations(user_id, n_recommendations=n_recommendations, knn_user_model=user_based_knn_model)
157
- elif collaborative_method == "Anime-Based KNN Collaborative Filtering":
158
- if anime_name:
159
- recommendations = recommender.get_item_based_recommendations(anime_name, n_recommendations=n_recommendations, knn_item_model=item_based_knn_model)
160
- else:
161
- st.error("Invalid Anime Name. Please enter a valid anime title.")
162
-
163
- if isinstance(recommendations, pd.DataFrame) and not recommendations.empty:
164
- if len(recommendations) < n_recommendations:
165
- st.warning(f"Oops...Only {len(recommendations)} recommendations available, fewer than the requested {n_recommendations}.")
166
- st.write(f"Here are the {collaborative_method} Recommendations:")
167
- cols = st.columns(5)
168
- for i, row in enumerate(recommendations.iterrows()):
169
- col = cols[i % 5]
170
- with col:
171
- st.image(row[1]['Image URL'], use_container_width=True)
172
- st.markdown(
173
- f"<div class='anime-title'>{row[1]['Anime Name']}</div>",
174
- unsafe_allow_html=True,
175
- )
176
- st.caption(f"Genres: {row[1]['Genres']} | Rating: {row[1]['Rating']}")
177
- else:
178
- st.error("No recommendations found.")
179
- except Exception as e:
180
- st.error(f"An error occurred: {e}")
181
-
182
- elif app_selector == "Top Anime Recommender":
183
- st.title("Top Anime Recommender System 🔥")
184
-
185
- try:
186
- popularity_method = st.sidebar.selectbox(
187
- "Choose a Popularity-Based Filtering method:",
188
- [
189
- "Popular Animes",
190
- "Top Ranked Animes",
191
- "Overall Top Rated Animes",
192
- "Favorite Animes",
193
- "Top Animes by Members",
194
- "Popular Anime Among Members",
195
- "Top Average Rated Animes",
196
- ]
197
- )
198
-
199
- n_recommendations = st.slider("Number of Recommendations:", min_value=1, max_value=500 , value=10)
200
-
201
- if st.button("Get Recommendations"):
202
- recommender = PopularityBasedFiltering(anime_data)
203
-
204
- # Get recommendations based on selected method
205
- if popularity_method == "Popular Animes":
206
- recommendations = recommender.popular_animes(n=n_recommendations)
207
- elif popularity_method == "Top Ranked Animes":
208
- recommendations = recommender.top_ranked_animes(n=n_recommendations)
209
- elif popularity_method == "Overall Top Rated Animes":
210
- recommendations = recommender.overall_top_rated_animes(n=n_recommendations)
211
- elif popularity_method == "Favorite Animes":
212
- recommendations = recommender.favorite_animes(n=n_recommendations)
213
- elif popularity_method == "Top Animes by Members":
214
- recommendations = recommender.top_animes_members(n=n_recommendations)
215
- elif popularity_method == "Popular Anime Among Members":
216
- recommendations = recommender.popular_anime_among_members(n=n_recommendations)
217
- elif popularity_method == "Top Average Rated Animes":
218
- recommendations = recommender.top_avg_rated(n=n_recommendations)
219
- else:
220
- st.error("Invalid selection. Please choose a valid method.")
221
- recommendations = None
222
-
223
- # Display recommendations
224
- if isinstance(recommendations, pd.DataFrame) and not recommendations.empty:
225
- st.write(f" Here are the Recommendations:")
226
- cols = st.columns(5)
227
- for i, row in recommendations.iterrows():
228
- col = cols[i % 5]
229
- with col:
230
- st.image(row['Image URL'], use_container_width=True)
231
- st.markdown(
232
- f"<div class='anime-title'>{row['Anime name']}</div>",
233
- unsafe_allow_html=True,
234
- )
235
- st.caption(f"Genres: {row['Genres']} | Rating: {row['Rating']}")
236
- else:
237
- st.error("No recommendations found.")
238
- except Exception as e:
239
- st.error(f"An error occurred: {e}")
240
-
241
- if __name__ == "__main__":
242
  run_app()
 
1
+ import pandas as pd
2
+ import streamlit as st
3
+ from anime_recommender.model_trainer.content_based_modelling import ContentBasedRecommender
4
+ from anime_recommender.model_trainer.collaborative_modelling import CollaborativeAnimeRecommender
5
+ from anime_recommender.model_trainer.top_anime_filtering import PopularityBasedFiltering
6
+ import joblib
7
+ from anime_recommender.constant import *
8
+ from huggingface_hub import hf_hub_download
9
+ from datasets import load_dataset
10
+
11
+ def run_app():
12
+ """
13
+ Initializes the Streamlit app, loads necessary datasets and models,
14
+ and provides a UI for anime recommendations based on three methods:
15
+ Content-Based, Collaborative, and Popularity-Based Filtering. 🎬🎮
16
+ """
17
+
18
+ # Set page configuration
19
+ st.set_page_config(page_title="Anime Recommendation System", layout="wide")
20
+
21
+ # Load datasets if not present in session state
22
+ if "anime_data" not in st.session_state or "anime_user_ratings" not in st.session_state:
23
+ # Load datasets from Hugging Face (assuming no splits)
24
+ animedataset = load_dataset(ANIME_FILE_PATH, split=None)
25
+ mergeddataset = load_dataset(ANIMEUSERRATINGS_FILE_PATH, split=None)
26
+
27
+ # Convert the dataset to Pandas DataFrame
28
+ st.session_state.anime_data = pd.DataFrame(animedataset["train"])
29
+ st.session_state.anime_user_ratings = pd.DataFrame(mergeddataset["train"])
30
+
31
+ # Load models only once
32
+ if "models_loaded" not in st.session_state:
33
+ st.session_state.models_loaded = {}
34
+ # Load models
35
+ st.session_state.models_loaded["cosine_similarity_model"] = hf_hub_download(MODELS_FILEPATH, MODEL_TRAINER_COSINESIMILARITY_MODEL_NAME)
36
+ st.session_state.models_loaded["item_based_knn_model_path"] = hf_hub_download(MODELS_FILEPATH, MODEL_TRAINER_ITEM_KNN_TRAINED_MODEL_NAME)
37
+ st.session_state.models_loaded["user_based_knn_model_path"] = hf_hub_download(MODELS_FILEPATH, MODEL_TRAINER_USER_KNN_TRAINED_MODEL_NAME)
38
+ st.session_state.models_loaded["svd_model_path"] = hf_hub_download(MODELS_FILEPATH, MODEL_TRAINER_SVD_TRAINED_MODEL_NAME)
39
+
40
+ # Load the models using joblib
41
+ with open(st.session_state.models_loaded["item_based_knn_model_path"], "rb") as f:
42
+ st.session_state.models_loaded["item_based_knn_model"] = joblib.load(f)
43
+
44
+ with open(st.session_state.models_loaded["user_based_knn_model_path"], "rb") as f:
45
+ st.session_state.models_loaded["user_based_knn_model"] = joblib.load(f)
46
+
47
+ with open(st.session_state.models_loaded["svd_model_path"], "rb") as f:
48
+ st.session_state.models_loaded["svd_model"] = joblib.load(f)
49
+
50
+ print("Models loaded successfully!")
51
+
52
+ # Access the data from session state
53
+ anime_data = st.session_state.anime_data
54
+ anime_user_ratings = st.session_state.anime_user_ratings
55
+
56
+ # # Display dataset info
57
+ # st.write("Anime Data:")
58
+ # st.dataframe(anime_data.head())
59
+
60
+ # st.write("Anime User Ratings Data:")
61
+ # st.dataframe(anime_user_ratings.head())
62
+
63
+ # Access the models from session state
64
+ cosine_similarity_model_path = hf_hub_download(MODELS_FILEPATH, MODEL_TRAINER_COSINESIMILARITY_MODEL_NAME)
65
+ item_based_knn_model = st.session_state.models_loaded["item_based_knn_model"]
66
+ user_based_knn_model = st.session_state.models_loaded["user_based_knn_model"]
67
+ svd_model = st.session_state.models_loaded["svd_model"]
68
+ print("Models loaded successfully!")
69
+
70
+ # Streamlit UI
71
+ app_selector = st.sidebar.radio(
72
+ "Select App", ("Content-Based Recommender", "Collaborative Recommender", "Top Anime Recommender")
73
+ )
74
+
75
+ # Content-Based Recommender App
76
+ if app_selector == "Content-Based Recommender":
77
+ st.title("Content-Based Recommendation System")
78
+ try:
79
+
80
+ anime_list = anime_data["name"].tolist()
81
+ anime_name = st.selectbox("Pick an anime..unlock similar anime recommendations..", anime_list)
82
+
83
+ # Set number of recommendations
84
+ max_recommendations = min(len(anime_data), 100)
85
+ n_recommendations = st.slider("Number of Recommendations", 1, max_recommendations, 10)
86
+
87
+ # Inject custom CSS for anime name font size
88
+ st.markdown(
89
+ """
90
+ <style>
91
+ .anime-title {
92
+ font-size: 14px !important;
93
+ font-weight: bold;
94
+ text-align: center;
95
+ margin-top: 5px;
96
+ }
97
+ </style>
98
+ """,
99
+ unsafe_allow_html=True,
100
+ )
101
+ # Get Recommendations
102
+ if st.button("Get Recommendations"):
103
+ try:
104
+ recommender = ContentBasedRecommender(anime_data)
105
+ recommendations = recommender.get_rec_cosine(anime_name, n_recommendations=n_recommendations,model_path=cosine_similarity_model_path)
106
+
107
+ if isinstance(recommendations, str):
108
+ st.warning(recommendations)
109
+ elif recommendations.empty:
110
+ st.warning("No recommendations found.🧐")
111
+ else:
112
+ st.write(f"Here are the Content-based Recommendations for {anime_name}:")
113
+ cols = st.columns(5)
114
+ for i, row in enumerate(recommendations.iterrows()):
115
+ col = cols[i % 5]
116
+ with col:
117
+ st.image(row[1]['Image URL'], use_container_width=True)
118
+ st.markdown(
119
+ f"<div class='anime-title'>{row[1]['Anime name']}</div>",
120
+ unsafe_allow_html=True,
121
+ )
122
+ st.caption(f"Genres: {row[1]['Genres']} | Rating: {row[1]['Rating']}")
123
+ except Exception as e:
124
+ st.error(f"Unexpected error: {str(e)}")
125
+
126
+ except Exception as e:
127
+ st.error(f"Unexpected error: {str(e)}")
128
+
129
+ elif app_selector == "Collaborative Recommender":
130
+ st.title("Collaborative Recommender System 🧑‍🤝‍🧑💬")
131
+
132
+ try:
133
+ # Sidebar for choosing the collaborative filtering method
134
+ collaborative_method = st.sidebar.selectbox(
135
+ "Choose a collaborative filtering method:",
136
+ ["SVD Collaborative Filtering", "User-Based Collaborative Filtering", "Anime-Based KNN Collaborative Filtering"]
137
+ )
138
+
139
+ # User input
140
+ if collaborative_method == "SVD Collaborative Filtering" or collaborative_method == "User-Based Collaborative Filtering":
141
+ user_ids = anime_user_ratings['user_id'].unique()
142
+ user_id = st.selectbox("Select your MyAnimeList user ID to get anime recommendations based on similar users", user_ids)
143
+ n_recommendations = st.slider("Number of Recommendations:", min_value=1, max_value=50, value=10)
144
+ elif collaborative_method == "Anime-Based KNN Collaborative Filtering":
145
+ anime_list = anime_user_ratings["name"].dropna().unique().tolist()
146
+ anime_name = st.selectbox("Pick an anime, and we'll suggest more titles you'll love", anime_list)
147
+ n_recommendations = st.slider("Number of Recommendations:", min_value=1, max_value=50, value=10)
148
+
149
+ # Get recommendations
150
+ if st.button("Get Recommendations"):
151
+ # Load the recommender
152
+ recommender = CollaborativeAnimeRecommender(anime_user_ratings)
153
+ if collaborative_method == "SVD Collaborative Filtering":
154
+ recommendations = recommender.get_svd_recommendations(user_id, n=n_recommendations, svd_model=svd_model)
155
+ elif collaborative_method == "User-Based Collaborative Filtering":
156
+ recommendations = recommender.get_user_based_recommendations(user_id, n_recommendations=n_recommendations, knn_user_model=user_based_knn_model)
157
+ elif collaborative_method == "Anime-Based KNN Collaborative Filtering":
158
+ if anime_name:
159
+ recommendations = recommender.get_item_based_recommendations(anime_name, n_recommendations=n_recommendations, knn_item_model=item_based_knn_model)
160
+ else:
161
+ st.error("Invalid Anime Name. Please enter a valid anime title.")
162
+
163
+ if isinstance(recommendations, pd.DataFrame) and not recommendations.empty:
164
+ if len(recommendations) < n_recommendations:
165
+ st.warning(f"Oops...Only {len(recommendations)} recommendations available, fewer than the requested {n_recommendations}.")
166
+ st.write(f"Here are the {collaborative_method} Recommendations:")
167
+ cols = st.columns(5)
168
+ for i, row in enumerate(recommendations.iterrows()):
169
+ col = cols[i % 5]
170
+ with col:
171
+ st.image(row[1]['Image URL'], use_container_width=True)
172
+ st.markdown(
173
+ f"<div class='anime-title'>{row[1]['Anime Name']}</div>",
174
+ unsafe_allow_html=True,
175
+ )
176
+ st.caption(f"Genres: {row[1]['Genres']} | Rating: {row[1]['Rating']}")
177
+ else:
178
+ st.error("No recommendations found.")
179
+ except Exception as e:
180
+ st.error(f"An error occurred: {e}")
181
+
182
+ elif app_selector == "Top Anime Recommender":
183
+ st.title("Top Anime Recommender System 🔥")
184
+
185
+ try:
186
+ popularity_method = st.sidebar.selectbox(
187
+ "Choose a Popularity-Based Filtering method:",
188
+ [
189
+ "Popular Animes",
190
+ "Top Ranked Animes",
191
+ "Overall Top Rated Animes",
192
+ "Favorite Animes",
193
+ "Top Animes by Members",
194
+ "Popular Anime Among Members",
195
+ "Top Average Rated Animes",
196
+ ]
197
+ )
198
+
199
+ n_recommendations = st.slider("Number of Recommendations:", min_value=1, max_value=500 , value=10)
200
+
201
+ if st.button("Get Recommendations"):
202
+ recommender = PopularityBasedFiltering(anime_data)
203
+
204
+ # Get recommendations based on selected method
205
+ if popularity_method == "Popular Animes":
206
+ recommendations = recommender.popular_animes(n=n_recommendations)
207
+ elif popularity_method == "Top Ranked Animes":
208
+ recommendations = recommender.top_ranked_animes(n=n_recommendations)
209
+ elif popularity_method == "Overall Top Rated Animes":
210
+ recommendations = recommender.overall_top_rated_animes(n=n_recommendations)
211
+ elif popularity_method == "Favorite Animes":
212
+ recommendations = recommender.favorite_animes(n=n_recommendations)
213
+ elif popularity_method == "Top Animes by Members":
214
+ recommendations = recommender.top_animes_members(n=n_recommendations)
215
+ elif popularity_method == "Popular Anime Among Members":
216
+ recommendations = recommender.popular_anime_among_members(n=n_recommendations)
217
+ elif popularity_method == "Top Average Rated Animes":
218
+ recommendations = recommender.top_avg_rated(n=n_recommendations)
219
+ else:
220
+ st.error("Invalid selection. Please choose a valid method.")
221
+ recommendations = None
222
+
223
+ # Display recommendations
224
+ if isinstance(recommendations, pd.DataFrame) and not recommendations.empty:
225
+ st.write(f" Here are the Recommendations:")
226
+ cols = st.columns(5)
227
+ for i, row in recommendations.iterrows():
228
+ col = cols[i % 5]
229
+ with col:
230
+ st.image(row['Image URL'], use_container_width=True)
231
+ st.markdown(
232
+ f"<div class='anime-title'>{row['Anime name']}</div>",
233
+ unsafe_allow_html=True,
234
+ )
235
+ st.caption(f"Genres: {row['Genres']} | Rating: {row['Rating']}")
236
+ else:
237
+ st.error("No recommendations found.")
238
+ except Exception as e:
239
+ st.error(f"An error occurred: {e}")
240
+
241
+ if __name__ == "__main__":
242
  run_app()
logs/{02_03_2025_11_40_31.log → 02_08_2025_12_23_10.log} RENAMED
@@ -1,51 +1,51 @@
1
- [ 2025-02-03 11:40:38,249 ] 8 root - INFO - Starting the Anime Recommendation System Training Pipeline...
2
- [ 2025-02-03 11:40:38,249 ] 42 root - INFO - Initiating Data Ingestion...
3
- [ 2025-02-03 11:40:38,249 ] 40 root - INFO - Fetching data from Hugging Face dataset: krishnaveni76/Animes
4
- [ 2025-02-03 11:40:50,688 ] 48 root - INFO - Shape of the dataframe: (12194, 18)
5
- [ 2025-02-03 11:40:50,689 ] 49 root - INFO - Column names: Index(['anime_id', 'genres', 'name', 'average_rating', 'overview', 'type',
6
  'episodes', 'producers', 'licensors', 'studios', 'source',
7
  'anime_rating', 'rank', 'popularity', 'favorites', 'scored by',
8
  'members', 'image url'],
9
  dtype='object')
10
- [ 2025-02-03 11:40:50,718 ] 50 root - INFO - Preview of the DataFrame:
11
- anime_id genres name ... scored by members image url
12
- 0 32281 Drama, Romance, School, Supernatural Kimi no Na wa. ... 1807089 2597495 https://cdn.myanimelist.net/images/anime/5/870...
13
- 1 5114 Action, Adventure, Drama, Fantasy, Magic, Mili... Fullmetal Alchemist: Brotherhood ... 2020030 3176556 https://cdn.myanimelist.net/images/anime/1208/...
14
- 2 28977 Action, Comedy, Historical, Parody, Samurai, S... Gintama° ... 237957 595767 https://cdn.myanimelist.net/images/anime/3/720...
15
- 3 9253 Sci-Fi, Thriller Steins;Gate ... 1336233 2440369 https://cdn.myanimelist.net/images/anime/1935/...
16
- 4 9969 Action, Comedy, Historical, Parody, Samurai, S... Gintama' ... 226175 525688 https://cdn.myanimelist.net/images/anime/4/503...
17
 
18
  [5 rows x 18 columns]
19
- [ 2025-02-03 11:40:50,718 ] 51 root - INFO - Data fetched successfully from Hugging Face.
20
- [ 2025-02-03 11:40:50,719 ] 40 root - INFO - Fetching data from Hugging Face dataset: krishnaveni76/UserRatings
21
- [ 2025-02-03 11:42:21,881 ] 48 root - INFO - Shape of the dataframe: (1112830, 4)
22
- [ 2025-02-03 11:42:21,881 ] 49 root - INFO - Column names: Index(['user_id', 'username', 'anime_id', 'rating'], dtype='object')
23
- [ 2025-02-03 11:42:21,889 ] 50 root - INFO - Preview of the DataFrame:
24
  user_id username anime_id rating
25
  0 357 zhambi 35427 5
26
  1 357 zhambi 28391 6
27
  2 357 zhambi 36649 7
28
  3 357 zhambi 530 6
29
  4 357 zhambi 37451 7
30
- [ 2025-02-03 11:42:21,889 ] 51 root - INFO - Data fetched successfully from Hugging Face.
31
- [ 2025-02-03 11:42:21,894 ] 21 root - INFO - Saving DataFrame to file: Artifacts/02_03_2025_11_40_35/data_ingestion/feature_store/Animes.csv
32
- [ 2025-02-03 11:42:22,227 ] 25 root - INFO - DataFrame saved successfully to Artifacts/02_03_2025_11_40_35/data_ingestion/feature_store/Animes.csv.
33
- [ 2025-02-03 11:42:22,227 ] 21 root - INFO - Saving DataFrame to file: Artifacts/02_03_2025_11_40_35/data_ingestion/feature_store/UserRatings.csv
34
- [ 2025-02-03 11:42:24,690 ] 25 root - INFO - DataFrame saved successfully to Artifacts/02_03_2025_11_40_35/data_ingestion/feature_store/UserRatings.csv.
35
- [ 2025-02-03 11:42:24,820 ] 46 root - INFO - Data Ingestion completed: DataIngestionArtifact(feature_store_anime_file_path='Artifacts/02_03_2025_11_40_35/data_ingestion/feature_store/Animes.csv', feature_store_userrating_file_path='Artifacts/02_03_2025_11_40_35/data_ingestion/feature_store/UserRatings.csv')
36
- [ 2025-02-03 11:42:24,820 ] 58 root - INFO - Initiating Data Transformation...
37
- [ 2025-02-03 11:42:24,821 ] 95 root - INFO - Entering initiate_data_transformation method of DataTransformation class.
38
- [ 2025-02-03 11:42:29,247 ] 54 root - INFO - Shape of the Merged dataframe:(916416, 21)
39
- [ 2025-02-03 11:42:29,247 ] 55 root - INFO - Column names: Index(['user_id', 'username', 'anime_id', 'rating', 'genres', 'name',
40
  'average_rating', 'overview', 'type', 'episodes', 'producers',
41
  'licensors', 'studios', 'source', 'anime_rating', 'rank', 'popularity',
42
  'favorites', 'scored by', 'members', 'image url'],
43
  dtype='object')
44
- [ 2025-02-03 11:42:31,342 ] 81 root - INFO - Shape of the Merged dataframe:(862804, 8)
45
- [ 2025-02-03 11:42:31,342 ] 82 root - INFO - Column names: Index(['user_id', 'anime_id', 'rating', 'genres', 'name', 'average_rating',
46
  'anime_rating', 'image url'],
47
  dtype='object')
48
- [ 2025-02-03 11:42:31,361 ] 83 root - INFO - Preview of the merged DataFrame:
49
  user_id anime_id rating ... average_rating anime_rating image url
50
  0 357 28391 6 ... 6.65 PG-13 - Teens 13 or older https://cdn.myanimelist.net/images/anime/9/778...
51
  1 357 530 6 ... 7.73 PG-13 - Teens 13 or older https://cdn.myanimelist.net/images/anime/1440/...
@@ -54,25 +54,70 @@
54
  5 357 31798 9 ... 7.38 PG-13 - Teens 13 or older https://cdn.myanimelist.net/images/anime/6/784...
55
 
56
  [5 rows x 8 columns]
57
- [ 2025-02-03 11:42:31,399 ] 21 root - INFO - Saving DataFrame to file: Artifacts/02_03_2025_11_40_35/data_transformation/transformed/Anime_UserRatings.csv
58
- [ 2025-02-03 11:42:38,424 ] 25 root - INFO - DataFrame saved successfully to Artifacts/02_03_2025_11_40_35/data_transformation/transformed/Anime_UserRatings.csv.
59
- [ 2025-02-03 11:42:38,583 ] 65 root - INFO - Data Transformation completed: DataTransformationArtifact(merged_file_path='Artifacts/02_03_2025_11_40_35/data_transformation/transformed/Anime_UserRatings.csv')
60
- [ 2025-02-03 11:42:38,584 ] 77 root - INFO - Initiating Collaborative Model Training...
61
- [ 2025-02-03 11:42:38,584 ] 42 root - INFO - Loading transformed data...
62
- [ 2025-02-03 11:42:38,585 ] 42 root - INFO - Loading CSV data from file: Artifacts/02_03_2025_11_40_35/data_transformation/transformed/Anime_UserRatings.csv
63
- [ 2025-02-03 11:42:40,977 ] 44 root - INFO - CSV file loaded successfully.
64
- [ 2025-02-03 11:42:40,979 ] 26 root - INFO - Initializing CollaborativeAnimeRecommender
65
- [ 2025-02-03 11:42:44,796 ] 45 root - INFO - Data preparation completed...
66
- [ 2025-02-03 11:42:44,796 ] 75 root - INFO - Training and saving KNN user-based model...
67
- [ 2025-02-03 11:42:44,797 ] 78 root - INFO - Training KNN model
68
- [ 2025-02-03 11:42:44,987 ] 82 root - INFO - KNN model training completed
69
- [ 2025-02-03 11:42:44,988 ] 59 root - INFO - Entered the save_model method.
70
- [ 2025-02-03 11:42:45,031 ] 63 root - INFO - Model saved successfully to Artifacts/02_03_2025_11_40_35/trained_models/collaborative_recommenders/userbasedknn.pkl.
71
- [ 2025-02-03 11:42:45,031 ] 79 root - INFO - Loading pre-trained user-based KNN model...
72
- [ 2025-02-03 11:42:45,031 ] 79 root - INFO - Attempting to load object from Artifacts/02_03_2025_11_40_35/trained_models/collaborative_recommenders/userbasedknn.pkl
73
- [ 2025-02-03 11:42:45,031 ] 85 root - INFO - Object loaded successfully.
74
- [ 2025-02-03 11:42:45,157 ] 253 root - INFO - Shape of filtered df: (10, 8)
75
- [ 2025-02-03 11:42:45,171 ] 84 root - INFO - User Based recommendations: Anime Name Image URL Genres Rating
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  0 Little Busters! Refrain https://cdn.myanimelist.net/images/anime/10/55... Comedy, Drama, Romance, School, Slice of Life,... 8.19
77
  1 Chuunibyou demo Koi ga Shitai! Ren https://cdn.myanimelist.net/images/anime/7/566... Comedy, Drama, Romance, School, Slice of Life 7.55
78
  2 Clannad: Mou Hitotsu no Sekai, Tomoyo-hen https://cdn.myanimelist.net/images/anime/12/19... Drama, Romance, School, Slice of Life 7.93
@@ -83,20 +128,21 @@
83
  7 Motto To LOVE-Ru https://cdn.myanimelist.net/images/anime/4/598... Comedy, Ecchi, Harem, School, Sci-Fi, Shounen 7.28
84
  8 Overlord https://cdn.myanimelist.net/images/anime/7/880... Action, Adventure, Fantasy, Game, Magic, Super... 7.91
85
  9 No.6 https://cdn.myanimelist.net/images/anime/1474/... Action, Sci-Fi 7.56
86
- [ 2025-02-03 11:42:45,315 ] 84 root - INFO - Collaborative Model Training completed: CollaborativeModelArtifact(svd_file_path=None, item_based_knn_file_path=None, user_based_knn_file_path='Artifacts/02_03_2025_11_40_35/trained_models/collaborative_recommenders/userbasedknn.pkl')
87
- [ 2025-02-03 11:42:45,315 ] 96 root - INFO - Initiating Content-Based Model Training...
88
- [ 2025-02-03 11:42:45,316 ] 37 root - INFO - Loading ingested data...
89
- [ 2025-02-03 11:42:45,316 ] 42 root - INFO - Loading CSV data from file: Artifacts/02_03_2025_11_40_35/data_ingestion/feature_store/Animes.csv
90
- [ 2025-02-03 11:42:45,499 ] 44 root - INFO - CSV file loaded successfully.
91
- [ 2025-02-03 11:42:45,500 ] 39 root - INFO - Training ContentBasedRecommender model...
92
- [ 2025-02-03 11:43:06,457 ] 35 root - INFO - Saving model to Artifacts/02_03_2025_11_40_35/trained_models/content_based_recommenders/cosine_similarity.pkl
93
- [ 2025-02-03 11:43:41,225 ] 39 root - INFO - Content recommender Model saved successfully
94
- [ 2025-02-03 11:43:41,244 ] 46 root - INFO - Model saved successfully.
95
- [ 2025-02-03 11:43:41,245 ] 48 root - INFO - Loading saved model to get recommendations...
96
- [ 2025-02-03 11:43:41,250 ] 46 root - INFO - Loading model from Artifacts/02_03_2025_11_40_35/trained_models/content_based_recommenders/cosine_similarity.pkl
97
- [ 2025-02-03 11:44:23,930 ] 50 root - INFO - Model loaded successfully
98
- [ 2025-02-03 11:44:24,814 ] 64 root - INFO - Recommendations generated successfully
99
- [ 2025-02-03 11:44:27,761 ] 50 root - INFO - Cosine similarity recommendations: Anime name Image URL Genres Rating
 
100
  0 One Piece: Episode of Merry - Mou Hitori no Na... https://cdn.myanimelist.net/images/anime/9/610... Action, Adventure, Comedy, Drama, Fantasy, Sho... 8.19
101
  1 One Piece: Episode of Nami - Koukaishi no Nami... https://cdn.myanimelist.net/images/anime/5/414... Action, Adventure, Comedy, Drama, Fantasy, Sho... 8.12
102
  2 One Piece: Episode of Sabo - 3 Kyoudai no Kizu... https://cdn.myanimelist.net/images/anime/1373/... Action, Adventure, Comedy, Drama, Fantasy, Sho... 7.71
@@ -107,14 +153,14 @@
107
  7 Digimon Frontier https://cdn.myanimelist.net/images/anime/1048/... Action, Adventure, Comedy, Drama, Fantasy, Sho... 7.15
108
  8 Digimon Tamers https://cdn.myanimelist.net/images/anime/7/736... Adventure, Comedy, Drama, Fantasy, Shounen 7.63
109
  9 Digimon Savers https://cdn.myanimelist.net/images/anime/1415/... Adventure, Comedy, Drama, Fantasy, Shounen 6.95
110
- [ 2025-02-03 11:44:29,361 ] 103 root - INFO - Content-Based Model Training completed: ContentBasedModelArtifact(cosine_similarity_model_file_path='Artifacts/02_03_2025_11_40_35/trained_models/content_based_recommenders/cosine_similarity.pkl')
111
- [ 2025-02-03 11:44:29,366 ] 113 root - INFO - Initiating Popularity-Based Filtering...
112
- [ 2025-02-03 11:44:29,371 ] 41 root - INFO - Loading transformed data...
113
- [ 2025-02-03 11:44:29,376 ] 42 root - INFO - Loading CSV data from file: Artifacts/02_03_2025_11_40_35/data_ingestion/feature_store/Animes.csv
114
- [ 2025-02-03 11:44:30,775 ] 44 root - INFO - CSV file loaded successfully.
115
- [ 2025-02-03 11:44:30,776 ] 17 root - INFO - Initializing PopularityBasedFiltering class
116
- [ 2025-02-03 11:44:30,905 ] 29 root - INFO - Fetching top 10 most popular animes
117
- [ 2025-02-03 11:44:31,089 ] 48 root - INFO - Popular Anime recommendations: Anime name Image URL Genres Rating
118
  0 Shingeki no Kyojin https://cdn.myanimelist.net/images/anime/10/47... Action, Drama, Fantasy, Shounen, Super Power 8.54
119
  1 Death Note https://cdn.myanimelist.net/images/anime/9/945... Mystery, Police, Psychological, Supernatural, ... 8.62
120
  2 Fullmetal Alchemist: Brotherhood https://cdn.myanimelist.net/images/anime/1208/... Action, Adventure, Drama, Fantasy, Magic, Mili... 9.10
@@ -125,5 +171,5 @@
125
  7 Tokyo Ghoul https://cdn.myanimelist.net/images/anime/1498/... Action, Drama, Horror, Mystery, Psychological,... 7.79
126
  8 Hunter x Hunter (2011) https://cdn.myanimelist.net/images/anime/1337/... Action, Adventure, Shounen, Super Power 9.04
127
  9 Kimi no Na wa. https://cdn.myanimelist.net/images/anime/5/870... Drama, Romance, School, Supernatural 8.85
128
- [ 2025-02-03 11:44:31,094 ] 116 root - INFO - Popularity-Based Filtering completed.
129
- [ 2025-02-03 11:44:31,094 ] 141 root - INFO - Training Pipeline executed successfully.
 
1
+ [ 2025-02-08 12:23:14,445 ] 8 root - INFO - Starting the Anime Recommendation System Training Pipeline...
2
+ [ 2025-02-08 12:23:14,445 ] 41 root - INFO - Initiating Data Ingestion...
3
+ [ 2025-02-08 12:23:14,445 ] 40 root - INFO - Fetching data from Hugging Face dataset: krishnaveni76/Animes
4
+ [ 2025-02-08 12:23:20,052 ] 48 root - INFO - Shape of the dataframe: (12194, 18)
5
+ [ 2025-02-08 12:23:20,052 ] 49 root - INFO - Column names: Index(['anime_id', 'genres', 'name', 'average_rating', 'overview', 'type',
6
  'episodes', 'producers', 'licensors', 'studios', 'source',
7
  'anime_rating', 'rank', 'popularity', 'favorites', 'scored by',
8
  'members', 'image url'],
9
  dtype='object')
10
+ [ 2025-02-08 12:23:20,072 ] 50 root - INFO - Preview of the DataFrame:
11
+ anime_id genres ... members image url
12
+ 0 32281 Drama, Romance, School, Supernatural ... 2597495 https://cdn.myanimelist.net/images/anime/5/870...
13
+ 1 5114 Action, Adventure, Drama, Fantasy, Magic, Mili... ... 3176556 https://cdn.myanimelist.net/images/anime/1208/...
14
+ 2 28977 Action, Comedy, Historical, Parody, Samurai, S... ... 595767 https://cdn.myanimelist.net/images/anime/3/720...
15
+ 3 9253 Sci-Fi, Thriller ... 2440369 https://cdn.myanimelist.net/images/anime/1935/...
16
+ 4 9969 Action, Comedy, Historical, Parody, Samurai, S... ... 525688 https://cdn.myanimelist.net/images/anime/4/503...
17
 
18
  [5 rows x 18 columns]
19
+ [ 2025-02-08 12:23:20,072 ] 51 root - INFO - Data fetched successfully from Hugging Face.
20
+ [ 2025-02-08 12:23:20,073 ] 40 root - INFO - Fetching data from Hugging Face dataset: krishnaveni76/UserRatings
21
+ [ 2025-02-08 12:24:00,180 ] 48 root - INFO - Shape of the dataframe: (1112830, 4)
22
+ [ 2025-02-08 12:24:00,181 ] 49 root - INFO - Column names: Index(['user_id', 'username', 'anime_id', 'rating'], dtype='object')
23
+ [ 2025-02-08 12:24:00,184 ] 50 root - INFO - Preview of the DataFrame:
24
  user_id username anime_id rating
25
  0 357 zhambi 35427 5
26
  1 357 zhambi 28391 6
27
  2 357 zhambi 36649 7
28
  3 357 zhambi 530 6
29
  4 357 zhambi 37451 7
30
+ [ 2025-02-08 12:24:00,184 ] 51 root - INFO - Data fetched successfully from Hugging Face.
31
+ [ 2025-02-08 12:24:00,187 ] 22 root - INFO - Saving DataFrame to file: Artifacts/02_08_2025_12_23_12/data_ingestion/feature_store/Animes.csv
32
+ [ 2025-02-08 12:24:00,356 ] 26 root - INFO - DataFrame saved successfully to Artifacts/02_08_2025_12_23_12/data_ingestion/feature_store/Animes.csv.
33
+ [ 2025-02-08 12:24:00,356 ] 22 root - INFO - Saving DataFrame to file: Artifacts/02_08_2025_12_23_12/data_ingestion/feature_store/UserRatings.csv
34
+ [ 2025-02-08 12:24:01,514 ] 26 root - INFO - DataFrame saved successfully to Artifacts/02_08_2025_12_23_12/data_ingestion/feature_store/UserRatings.csv.
35
+ [ 2025-02-08 12:24:01,581 ] 45 root - INFO - Data Ingestion completed: DataIngestionArtifact(feature_store_anime_file_path='Artifacts/02_08_2025_12_23_12/data_ingestion/feature_store/Animes.csv', feature_store_userrating_file_path='Artifacts/02_08_2025_12_23_12/data_ingestion/feature_store/UserRatings.csv')
36
+ [ 2025-02-08 12:24:01,582 ] 57 root - INFO - Initiating Data Transformation...
37
+ [ 2025-02-08 12:24:01,582 ] 95 root - INFO - Entering initiate_data_transformation method of DataTransformation class.
38
+ [ 2025-02-08 12:24:02,365 ] 54 root - INFO - Shape of the Merged dataframe:(916416, 21)
39
+ [ 2025-02-08 12:24:02,366 ] 55 root - INFO - Column names: Index(['user_id', 'username', 'anime_id', 'rating', 'genres', 'name',
40
  'average_rating', 'overview', 'type', 'episodes', 'producers',
41
  'licensors', 'studios', 'source', 'anime_rating', 'rank', 'popularity',
42
  'favorites', 'scored by', 'members', 'image url'],
43
  dtype='object')
44
+ [ 2025-02-08 12:24:03,520 ] 81 root - INFO - Shape of the Merged dataframe:(862804, 8)
45
+ [ 2025-02-08 12:24:03,520 ] 82 root - INFO - Column names: Index(['user_id', 'anime_id', 'rating', 'genres', 'name', 'average_rating',
46
  'anime_rating', 'image url'],
47
  dtype='object')
48
+ [ 2025-02-08 12:24:03,526 ] 83 root - INFO - Preview of the merged DataFrame:
49
  user_id anime_id rating ... average_rating anime_rating image url
50
  0 357 28391 6 ... 6.65 PG-13 - Teens 13 or older https://cdn.myanimelist.net/images/anime/9/778...
51
  1 357 530 6 ... 7.73 PG-13 - Teens 13 or older https://cdn.myanimelist.net/images/anime/1440/...
 
54
  5 357 31798 9 ... 7.38 PG-13 - Teens 13 or older https://cdn.myanimelist.net/images/anime/6/784...
55
 
56
  [5 rows x 8 columns]
57
+ [ 2025-02-08 12:24:03,549 ] 22 root - INFO - Saving DataFrame to file: Artifacts/02_08_2025_12_23_12/data_transformation/transformed/Anime_UserRatings.csv
58
+ [ 2025-02-08 12:24:07,286 ] 26 root - INFO - DataFrame saved successfully to Artifacts/02_08_2025_12_23_12/data_transformation/transformed/Anime_UserRatings.csv.
59
+ [ 2025-02-08 12:24:07,400 ] 64 root - INFO - Data Transformation completed: DataTransformationArtifact(merged_file_path='Artifacts/02_08_2025_12_23_12/data_transformation/transformed/Anime_UserRatings.csv')
60
+ [ 2025-02-08 12:24:07,401 ] 76 root - INFO - Initiating Collaborative Model Training...
61
+ [ 2025-02-08 12:24:07,401 ] 41 root - INFO - Loading transformed data...
62
+ [ 2025-02-08 12:24:07,401 ] 43 root - INFO - Loading CSV data from file: Artifacts/02_08_2025_12_23_12/data_transformation/transformed/Anime_UserRatings.csv
63
+ [ 2025-02-08 12:24:08,571 ] 45 root - INFO - CSV file loaded successfully.
64
+ [ 2025-02-08 12:24:08,572 ] 26 root - INFO - Initializing CollaborativeAnimeRecommender
65
+ [ 2025-02-08 12:24:10,797 ] 45 root - INFO - Data preparation completed...
66
+ [ 2025-02-08 12:24:10,797 ] 46 root - INFO - Training and saving SVD model...
67
+ [ 2025-02-08 12:24:10,797 ] 54 root - INFO - Training SVD model
68
+ [ 2025-02-08 12:25:13,802 ] 59 root - INFO - SVD model training completed
69
+ [ 2025-02-08 12:25:13,803 ] 60 root - INFO - Entered the save_model method.
70
+ [ 2025-02-08 12:25:23,132 ] 64 root - INFO - Model saved successfully to Artifacts/02_08_2025_12_23_12/trained_models/collaborative_recommenders/svd.pkl.
71
+ [ 2025-02-08 12:25:31,079 ] 109 root - INFO - Successfully uploaded svd.pkl to Hugging Face: krishnaveni76/anime-recommendation-models
72
+ [ 2025-02-08 12:25:31,079 ] 54 root - INFO - Loading pre-trained SVD model...
73
+ [ 2025-02-08 12:25:31,079 ] 80 root - INFO - Attempting to load object from Artifacts/02_08_2025_12_23_12/trained_models/collaborative_recommenders/svd.pkl
74
+ [ 2025-02-08 12:25:31,079 ] 86 root - INFO - Object loaded successfully.
75
+ [ 2025-02-08 12:25:35,137 ] 134 root - INFO - Shape of recommended_anime: (10, 8)
76
+ [ 2025-02-08 12:25:35,142 ] 57 root - INFO - SVD recommendations: Anime Name Genres Image URL Rating
77
+ 0 Clannad: After Story Drama, Fantasy, Romance, Slice of Life, Supern... https://cdn.myanimelist.net/images/anime/1299/... 8.93
78
+ 1 Fate/Zero 2nd Season Action, Fantasy, Supernatural, Thriller https://cdn.myanimelist.net/images/anime/1522/... 8.55
79
+ 2 Fullmetal Alchemist: Brotherhood Action, Adventure, Drama, Fantasy, Magic, Mili... https://cdn.myanimelist.net/images/anime/1208/... 9.10
80
+ 3 Mushishi Adventure, Fantasy, Historical, Mystery, Seine... https://cdn.myanimelist.net/images/anime/2/738... 8.66
81
+ 4 Tengen Toppa Gurren Lagann Action, Adventure, Comedy, Mecha, Sci-Fi https://cdn.myanimelist.net/images/anime/4/512... 8.63
82
+ 5 Evangelion: 2.0 You Can (Not) Advance Action, Mecha, Sci-Fi https://cdn.myanimelist.net/images/anime/5/749... 8.31
83
+ 6 Hunter x Hunter (2011) Action, Adventure, Shounen, Super Power https://cdn.myanimelist.net/images/anime/1337/... 9.04
84
+ 7 Kara no Kyoukai Movie 5: Mujun Rasen Action, Drama, Mystery, Romance, Supernatural,... https://cdn.myanimelist.net/images/anime/1574/... 8.53
85
+ 8 Rurouni Kenshin: Meiji Kenkaku Romantan - Tsui... Action, Drama, Historical, Martial Arts, Roman... https://cdn.myanimelist.net/images/anime/1391/... 8.71
86
+ 9 Ginga Eiyuu Densetsu Drama, Military, Sci-Fi, Space https://cdn.myanimelist.net/images/anime/13/13... 9.02
87
+ [ 2025-02-08 12:25:35,142 ] 60 root - INFO - Training and saving KNN item-based model...
88
+ [ 2025-02-08 12:25:35,142 ] 68 root - INFO - Training KNN model
89
+ [ 2025-02-08 12:25:35,219 ] 60 root - INFO - Entered the save_model method.
90
+ [ 2025-02-08 12:25:35,245 ] 64 root - INFO - Model saved successfully to Artifacts/02_08_2025_12_23_12/trained_models/collaborative_recommenders/itembasedknn.pkl.
91
+ [ 2025-02-08 12:25:36,067 ] 4009 huggingface_hub.hf_api - WARNING - No files have been modified since last commit. Skipping to prevent empty commit.
92
+ [ 2025-02-08 12:25:36,344 ] 109 root - INFO - Successfully uploaded itembasedknn.pkl to Hugging Face: krishnaveni76/anime-recommendation-models
93
+ [ 2025-02-08 12:25:36,344 ] 68 root - INFO - Loading pre-trained item-based KNN model...
94
+ [ 2025-02-08 12:25:36,344 ] 80 root - INFO - Attempting to load object from Artifacts/02_08_2025_12_23_12/trained_models/collaborative_recommenders/itembasedknn.pkl
95
+ [ 2025-02-08 12:25:36,345 ] 86 root - INFO - Object loaded successfully.
96
+ [ 2025-02-08 12:25:36,373 ] 185 root - INFO - Top 10 recommendations: ['Bleach', 'Naruto', 'One Piece Film: Strong World', 'Fairy Tail', 'Soul Eater', 'Death Note', 'Code Geass: Hangyaku no Lelouch', 'Naruto: Shippuuden', 'Code Geass: Hangyaku no Lelouch R2', 'Fullmetal Alchemist: Brotherhood']
97
+ [ 2025-02-08 12:25:36,408 ] 187 root - INFO - Shape of filtered df: (10, 8)
98
+ [ 2025-02-08 12:25:36,412 ] 73 root - INFO - Item Based recommendations: Anime Name Image URL Genres Rating
99
+ 0 Code Geass: Hangyaku no Lelouch https://cdn.myanimelist.net/images/anime/1032/... Action, Mecha, Military, School, Sci-Fi, Super... 8.70
100
+ 1 Code Geass: Hangyaku no Lelouch R2 https://cdn.myanimelist.net/images/anime/1088/... Action, Drama, Mecha, Military, Sci-Fi, Super ... 8.91
101
+ 2 Fullmetal Alchemist: Brotherhood https://cdn.myanimelist.net/images/anime/1208/... Action, Adventure, Drama, Fantasy, Magic, Mili... 9.10
102
+ 3 Soul Eater https://cdn.myanimelist.net/images/anime/9/780... Action, Adventure, Comedy, Fantasy, Shounen, S... 7.84
103
+ 4 Bleach https://cdn.myanimelist.net/images/anime/3/404... Action, Comedy, Shounen, Super Power, Supernat... 7.92
104
+ 5 Death Note https://cdn.myanimelist.net/images/anime/9/945... Mystery, Police, Psychological, Supernatural, ... 8.62
105
+ 6 Naruto https://cdn.myanimelist.net/images/anime/13/17... Action, Comedy, Martial Arts, Shounen, Super P... 7.99
106
+ 7 Naruto: Shippuuden https://cdn.myanimelist.net/images/anime/1565/... Action, Comedy, Martial Arts, Shounen, Super P... 8.26
107
+ 8 Fairy Tail https://cdn.myanimelist.net/images/anime/5/181... Action, Adventure, Comedy, Fantasy, Magic, Sho... 7.57
108
+ 9 One Piece Film: Strong World https://cdn.myanimelist.net/images/anime/1192/... Action, Adventure, Comedy, Drama, Fantasy, Sho... 8.08
109
+ [ 2025-02-08 12:25:36,412 ] 76 root - INFO - Training and saving KNN user-based model...
110
+ [ 2025-02-08 12:25:36,412 ] 78 root - INFO - Training KNN model
111
+ [ 2025-02-08 12:25:36,535 ] 82 root - INFO - KNN model training completed
112
+ [ 2025-02-08 12:25:36,535 ] 60 root - INFO - Entered the save_model method.
113
+ [ 2025-02-08 12:25:36,558 ] 64 root - INFO - Model saved successfully to Artifacts/02_08_2025_12_23_12/trained_models/collaborative_recommenders/userbasedknn.pkl.
114
+ [ 2025-02-08 12:25:37,249 ] 4009 huggingface_hub.hf_api - WARNING - No files have been modified since last commit. Skipping to prevent empty commit.
115
+ [ 2025-02-08 12:25:37,598 ] 109 root - INFO - Successfully uploaded userbasedknn.pkl to Hugging Face: krishnaveni76/anime-recommendation-models
116
+ [ 2025-02-08 12:25:37,598 ] 84 root - INFO - Loading pre-trained user-based KNN model...
117
+ [ 2025-02-08 12:25:37,598 ] 80 root - INFO - Attempting to load object from Artifacts/02_08_2025_12_23_12/trained_models/collaborative_recommenders/userbasedknn.pkl
118
+ [ 2025-02-08 12:25:37,598 ] 86 root - INFO - Object loaded successfully.
119
+ [ 2025-02-08 12:25:37,649 ] 253 root - INFO - Shape of filtered df: (10, 8)
120
+ [ 2025-02-08 12:25:37,654 ] 89 root - INFO - User Based recommendations: Anime Name Image URL Genres Rating
121
  0 Little Busters! Refrain https://cdn.myanimelist.net/images/anime/10/55... Comedy, Drama, Romance, School, Slice of Life,... 8.19
122
  1 Chuunibyou demo Koi ga Shitai! Ren https://cdn.myanimelist.net/images/anime/7/566... Comedy, Drama, Romance, School, Slice of Life 7.55
123
  2 Clannad: Mou Hitotsu no Sekai, Tomoyo-hen https://cdn.myanimelist.net/images/anime/12/19... Drama, Romance, School, Slice of Life 7.93
 
128
  7 Motto To LOVE-Ru https://cdn.myanimelist.net/images/anime/4/598... Comedy, Ecchi, Harem, School, Sci-Fi, Shounen 7.28
129
  8 Overlord https://cdn.myanimelist.net/images/anime/7/880... Action, Adventure, Fantasy, Game, Magic, Super... 7.91
130
  9 No.6 https://cdn.myanimelist.net/images/anime/1474/... Action, Sci-Fi 7.56
131
+ [ 2025-02-08 12:25:38,100 ] 83 root - INFO - Collaborative Model Training completed: CollaborativeModelArtifact(svd_file_path='Artifacts/02_08_2025_12_23_12/trained_models/collaborative_recommenders/svd.pkl', item_based_knn_file_path='Artifacts/02_08_2025_12_23_12/trained_models/collaborative_recommenders/itembasedknn.pkl', user_based_knn_file_path='Artifacts/02_08_2025_12_23_12/trained_models/collaborative_recommenders/userbasedknn.pkl')
132
+ [ 2025-02-08 12:25:38,100 ] 95 root - INFO - Initiating Content-Based Model Training...
133
+ [ 2025-02-08 12:25:38,100 ] 37 root - INFO - Loading ingested data...
134
+ [ 2025-02-08 12:25:38,100 ] 43 root - INFO - Loading CSV data from file: Artifacts/02_08_2025_12_23_12/data_ingestion/feature_store/Animes.csv
135
+ [ 2025-02-08 12:25:38,208 ] 45 root - INFO - CSV file loaded successfully.
136
+ [ 2025-02-08 12:25:38,209 ] 39 root - INFO - Training ContentBasedRecommender model...
137
+ [ 2025-02-08 12:25:52,919 ] 35 root - INFO - Saving model to Artifacts/02_08_2025_12_23_12/trained_models/content_based_recommenders/cosine_similarity.pkl
138
+ [ 2025-02-08 12:26:00,731 ] 39 root - INFO - Content recommender Model saved successfully
139
+ [ 2025-02-08 12:28:18,967 ] 109 root - INFO - Successfully uploaded cosine_similarity.pkl to Hugging Face: krishnaveni76/anime-recommendation-models
140
+ [ 2025-02-08 12:28:18,969 ] 51 root - INFO - Model saved successfully.
141
+ [ 2025-02-08 12:28:18,969 ] 53 root - INFO - Loading saved model to get recommendations...
142
+ [ 2025-02-08 12:28:18,972 ] 46 root - INFO - Loading model from Artifacts/02_08_2025_12_23_12/trained_models/content_based_recommenders/cosine_similarity.pkl
143
+ [ 2025-02-08 12:28:28,483 ] 50 root - INFO - Model loaded successfully
144
+ [ 2025-02-08 12:28:28,626 ] 64 root - INFO - Recommendations generated successfully
145
+ [ 2025-02-08 12:28:28,804 ] 55 root - INFO - Cosine similarity recommendations: Anime name Image URL Genres Rating
146
  0 One Piece: Episode of Merry - Mou Hitori no Na... https://cdn.myanimelist.net/images/anime/9/610... Action, Adventure, Comedy, Drama, Fantasy, Sho... 8.19
147
  1 One Piece: Episode of Nami - Koukaishi no Nami... https://cdn.myanimelist.net/images/anime/5/414... Action, Adventure, Comedy, Drama, Fantasy, Sho... 8.12
148
  2 One Piece: Episode of Sabo - 3 Kyoudai no Kizu... https://cdn.myanimelist.net/images/anime/1373/... Action, Adventure, Comedy, Drama, Fantasy, Sho... 7.71
 
153
  7 Digimon Frontier https://cdn.myanimelist.net/images/anime/1048/... Action, Adventure, Comedy, Drama, Fantasy, Sho... 7.15
154
  8 Digimon Tamers https://cdn.myanimelist.net/images/anime/7/736... Adventure, Comedy, Drama, Fantasy, Shounen 7.63
155
  9 Digimon Savers https://cdn.myanimelist.net/images/anime/1415/... Adventure, Comedy, Drama, Fantasy, Shounen 6.95
156
+ [ 2025-02-08 12:28:29,200 ] 102 root - INFO - Content-Based Model Training completed: ContentBasedModelArtifact(cosine_similarity_model_file_path='Artifacts/02_08_2025_12_23_12/trained_models/content_based_recommenders/cosine_similarity.pkl')
157
+ [ 2025-02-08 12:28:29,201 ] 112 root - INFO - Initiating Popularity-Based Filtering...
158
+ [ 2025-02-08 12:28:29,205 ] 41 root - INFO - Loading transformed data...
159
+ [ 2025-02-08 12:28:29,206 ] 43 root - INFO - Loading CSV data from file: Artifacts/02_08_2025_12_23_12/data_ingestion/feature_store/Animes.csv
160
+ [ 2025-02-08 12:28:29,762 ] 45 root - INFO - CSV file loaded successfully.
161
+ [ 2025-02-08 12:28:29,765 ] 17 root - INFO - Initializing PopularityBasedFiltering class
162
+ [ 2025-02-08 12:28:29,820 ] 29 root - INFO - Fetching top 10 most popular animes
163
+ [ 2025-02-08 12:28:29,873 ] 48 root - INFO - Popular Anime recommendations: Anime name Image URL Genres Rating
164
  0 Shingeki no Kyojin https://cdn.myanimelist.net/images/anime/10/47... Action, Drama, Fantasy, Shounen, Super Power 8.54
165
  1 Death Note https://cdn.myanimelist.net/images/anime/9/945... Mystery, Police, Psychological, Supernatural, ... 8.62
166
  2 Fullmetal Alchemist: Brotherhood https://cdn.myanimelist.net/images/anime/1208/... Action, Adventure, Drama, Fantasy, Magic, Mili... 9.10
 
171
  7 Tokyo Ghoul https://cdn.myanimelist.net/images/anime/1498/... Action, Drama, Horror, Mystery, Psychological,... 7.79
172
  8 Hunter x Hunter (2011) https://cdn.myanimelist.net/images/anime/1337/... Action, Adventure, Shounen, Super Power 9.04
173
  9 Kimi no Na wa. https://cdn.myanimelist.net/images/anime/5/870... Drama, Romance, School, Supernatural 8.85
174
+ [ 2025-02-08 12:28:29,877 ] 115 root - INFO - Popularity-Based Filtering completed.
175
+ [ 2025-02-08 12:28:29,877 ] 140 root - INFO - Training Pipeline executed successfully.
notebooks/EDA.ipynb CHANGED
The diff for this file is too large to render. See raw diff
 
notebooks/final_ARS.ipynb CHANGED
The diff for this file is too large to render. See raw diff
 
run_pipeline.py CHANGED
@@ -13,6 +13,9 @@ if __name__ == "__main__":
13
  raise AnimeRecommendorException(e, sys)
14
 
15
 
 
 
 
16
  # import sys
17
  # from anime_recommender.loggers.logging import logging
18
  # from anime_recommender.exception.exception import AnimeRecommendorException
@@ -46,7 +49,7 @@ if __name__ == "__main__":
46
  # collaborative_model_trainer_config = CollaborativeModelConfig(training_pipeline_config)
47
  # collaborative_model_trainer = CollaborativeModelTrainer(collaborative_model_trainer_config= collaborative_model_trainer_config,data_transformation_artifact=data_transformation_artifact)
48
  # logging.info("Initiating Collaborative Model training.")
49
- # collaborative_model_trainer_artifact = collaborative_model_trainer.initiate_model_trainer(model_type='user_knn')
50
  # logging.info("Collaborative Model training completed.")
51
  # print(collaborative_model_trainer_artifact)
52
 
 
13
  raise AnimeRecommendorException(e, sys)
14
 
15
 
16
+
17
+
18
+
19
  # import sys
20
  # from anime_recommender.loggers.logging import logging
21
  # from anime_recommender.exception.exception import AnimeRecommendorException
 
49
  # collaborative_model_trainer_config = CollaborativeModelConfig(training_pipeline_config)
50
  # collaborative_model_trainer = CollaborativeModelTrainer(collaborative_model_trainer_config= collaborative_model_trainer_config,data_transformation_artifact=data_transformation_artifact)
51
  # logging.info("Initiating Collaborative Model training.")
52
+ # collaborative_model_trainer_artifact = collaborative_model_trainer.initiate_model_trainer()
53
  # logging.info("Collaborative Model training completed.")
54
  # print(collaborative_model_trainer_artifact)
55