File size: 8,960 Bytes
9c467d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5a2f78
c8fdefc
00f351b
9c467d0
e5cae3b
9c467d0
00f351b
9c467d0
00f351b
9c467d0
 
 
fa6d8a6
9c467d0
 
 
 
00f351b
 
9c467d0
ea5c0eb
00f351b
9c467d0
 
00f351b
ea5c0eb
9c467d0
 
 
ea5c0eb
613a234
ea5c0eb
 
 
9c467d0
 
 
 
 
 
 
 
00f351b
 
9c467d0
00f351b
9c467d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
460e12a
021d87d
 
 
 
460e12a
021d87d
460e12a
 
 
 
 
021d87d
460e12a
 
 
 
 
 
 
 
 
 
021d87d
9c467d0
ae71a96
 
021d87d
9c467d0
8c296fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7441e7
9c467d0
 
 
 
 
021d87d
 
9c467d0
 
 
 
021d87d
 
 
 
9c467d0
021d87d
 
9c467d0
 
460e12a
5d65301
021d87d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d65301
124afe5
021d87d
730fe3a
 
 
021d87d
 
 
 
 
9c467d0
021d87d
9c467d0
00f351b
fa4a854
3908f13
021d87d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# import gradio as gr
# import kagglehub
# import pickle
# import numpy as np
# import os
# from surprise import SVDpp
# from sklearn.metrics.pairwise import cosine_similarity

# # --- Download model from KaggleHub ---
# def download_kagglehub_model():
#     user = os.getenv("KAGGLE_USERNAME")         
#     MODEL_SLUG = 'book-recommender-svd' 
#     VARIATION_SLUG = 'v1' 
#     framework = "keras"
    
#     model_handle = f"{user}/{MODEL_SLUG}/{framework}/{VARIATION_SLUG}"
#     print("πŸ“₯ Downloading model from KaggleHub:", model_handle)
#     model_path = kagglehub.model_download(model_handle)
#     print("βœ… Model downloaded to:", model_path)
#     return model_path

# # --- Load Models ---
# def load_models(model_dir):
#     with open(f"{model_dir}/svd_model.pkl", "rb") as f:
#         svdpp_model = pickle.load(f)

#     with open(f"{model_dir}/content_features.pkl", "rb") as f:
#         content_features = pickle.load(f)

#     with open(f"{model_dir}/book_metadata.pkl", "rb") as f:
#         mappings = pickle.load(f)

#     return svdpp_model, content_features, mappings

# # --- Hybrid Prediction ---
# def hybrid_predict(user_id, book_id, alpha=0.7):
#     try:
#     #     uid = user_encoder.transform([user_id])[0]
#     #     iid = item_encoder.transform([book_id])[0]
#         uid = user_id
#         iid = book_id
#     except:
#         return "❌ Unknown user_id or book_id"

#     svd_pred = svdpp_model.predict(uid, iid).est

#     user_liked = np.where(svdpp_model.trainset.ur[uid])[0]
#     if len(user_liked) == 0:
#         content_score = 0
#     else:
#         similarities = cosine_similarity(content_features[iid], content_features[user_liked])
#         content_score = np.mean(similarities)

#     hybrid_score = alpha * svd_pred + (1 - alpha) * content_score * 5
#     return round(hybrid_score, 2)

# # --- Gradio Interface ---
# def recommend(user_id, book_id, alpha=0.7):
#     return f"⭐ Predicted Rating: {hybrid_predict(user_id, book_id, alpha)}"

# # Download and load model
# model_dir = download_kagglehub_model()
# svdpp_model, content_features, mappings = load_models(model_dir)
# # user_encoder = mappings["user_encoder"]
# # item_encoder = mappings["item_encoder"]

# # Start Gradio app
# demo = gr.Interface(
#     fn=recommend,
#     inputs=[
#         gr.Textbox(label="User ID"),
#         gr.Textbox(label="Book ID"),
#         gr.Slider(0, 1, value=0.7, step=0.1, label="Hybrid Weight (alpha)")
#     ],
#     outputs="text",
#     title="πŸ“š Hybrid Book Recommender",
#     description="Enter a user_id and book_id to get a predicted rating using a Hybrid SVD++ and Content-based model."
# )

# demo.launch()

import os
import pickle
import gradio as gr
import pandas as pd
import kagglehub
from surprise import SVDpp, Dataset, Reader
from sklearn.metrics.pairwise import cosine_similarity
import joblib

# πŸ”₯ Load Hybrid Model from KaggleHub
user = os.getenv("KAGGLE_USERNAME")         
model_slug = 'book-recommender-svd' 
variation_slug = 'v2' 
framework = "keras"

model_handle = f"{user}/{model_slug}/{framework}/{variation_slug}"
model_dir = kagglehub.model_download(model_handle)


with open(f"{model_dir}/svd_model.pkl", "rb") as f:
    svdpp = pickle.load(f)

with open(f"{model_dir}/content_features.pkl", "rb") as f:
    content_features = pickle.load(f)

with open(f"{model_dir}/mappings.pkl", "rb") as f:
    mappings = pickle.load(f)


ratings_df = mappings['ratings_df']
features_df = mappings['feature_df']
user_encoder = mappings['user_encoder']
item_encoder = mappings['item_encoder']

# Create mappings
item_id_to_idx = {bid: idx for idx, bid in enumerate(features_df['book_id'])}
global_mean_rating = ratings_df['rating'].mean()

# User liked books mapping (for content-based filtering)
user_liked_books = ratings_df[ratings_df['rating'] >= 4].groupby('user_id')['book_id'].apply(list).to_dict()

# πŸ”₯ Hybrid Predict Function
def hybrid_predict(user_id, book_id, alpha=0.7):
    try:
        cf_score = svdpp.predict(user_id, book_id).est
    except:
        cf_score = global_mean_rating

    try:
        idx_target = item_id_to_idx[book_id]
        liked_books = user_liked_books.get(user_id, [])
        if not liked_books:
            content_score = global_mean_rating
        else:
            liked_indices = [item_id_to_idx[b] for b in liked_books if b in item_id_to_idx]
            if not liked_indices:
                content_score = global_mean_rating
            else:
                sims = cosine_similarity(content_features[idx_target], content_features[liked_indices])
                content_score = sims.mean()
    except:
        content_score = global_mean_rating

    return alpha * cf_score + (1 - alpha) * content_score


# def recommend_books(user_id, top_n):

#     # uid = user_encoder.transform([user_id])[0]
#     user_id = int(user_id)
    
#     if user_id not in ratings_df['user_id'].unique():
#         return pd.DataFrame([["Error", f"User {user_id} not found."]], columns=["Book Title", "Predicted Rating"])

#     rated_books = set(ratings_df[ratings_df['user_id'] == user_id]['book_id'])
#     unseen_books = set(features_df['book_id']) - rated_books

#     if not unseen_books:
#         return pd.DataFrame([["Error", "No unseen books left to recommend."]], columns=["Book Title", "Predicted Rating"])

#     recommendations = []
#     for book_id in unseen_books:
#         score = hybrid_predict(user_id, book_id)
#         title = features_df.loc[features_df['book_id'] == book_id, 'title'].values[0]
#         recommendations.append((title, round(score, 3)))

#     recommendations.sort(key=lambda x: x[1], reverse=True)
#     return pd.DataFrame(recommendations[:top_n], columns=["Book Title", "Predicted Rating"])


def recommend_books(user_id, top_n):

    user_id = int(user_id)

    if user_id not in ratings_df['user_id'].unique():
        
        # Cold start fallback β†’ Top-N highest-rated books
        top_books = (
            ratings_df.groupby('book_id')['rating']
            .mean()
            .reset_index()
            .sort_values(by='rating', ascending=False)
            .head(top_n)
        )

        recommendations = []
        for _, row in top_books.iterrows():
            book_id = row['book_id']
            avg_rating = row['rating']
            book_info = features_df.loc[features_df['book_id'] == book_id]
            if book_info.empty:
                continue
            title = book_info['title'].values[0]
            image_url = book_info['image_url'].values[0] if 'image_url' in book_info else ""
            recommendations.append(
                (f"<img src='{image_url}' width='60'>", title, round(avg_rating, 3))
            )

        return pd.DataFrame(recommendations, columns=["Book Cover", "Book Title",  "Predicted Rating"])

    rated_books = set(ratings_df[ratings_df['user_id'] == user_id]['book_id'])
    unseen_books = set(features_df['book_id']) - rated_books

    if not unseen_books:
        return pd.DataFrame([["", "No unseen books left to recommend.", ""]], 
                            columns=["Book Cover", "Book Title", "Predicted Rating"])

    recommendations = []
    for book_id in unseen_books:
        score = hybrid_predict(user_id, book_id)
        row = features_df.loc[features_df['book_id'] == book_id]
        title = row['title'].values[0]
        image_url = row['image_url'].values[0] if 'image_url' in row else ""
        recommendations.append((f"<img src='{image_url}' width='60'>", title, round(score, 3)))

    recommendations.sort(key=lambda x: x[2], reverse=True)
    return pd.DataFrame(recommendations[:top_n], columns=["Book Cover", "Book Title", "Predicted Rating"])



# Gradio UI
# with gr.Blocks() as demo:
#     gr.Markdown("## πŸ“š Hybrid Book Recommendation System")
#     user_id_input = gr.Textbox(label="Enter User ID", placeholder="e.g. 123")
#     top_n_input = gr.Slider(5, 20, value=10, step=1, label="Number of Recommendations")
#     recommend_button = gr.Button("Get Recommendations")
#     output_table = gr.Dataframe(headers=["Book Title", "Predicted Rating"], datatype=["str", "number"])

#     recommend_button.click(
#         recommend_books,
#         inputs=[user_id_input, top_n_input],
#         outputs=output_table
#     )

# demo.launch()

with gr.Blocks() as app_ui:
    gr.Markdown("## πŸ“š Hybrid Book Recommendation System")
    user_id_input = gr.Textbox(label="User ID", placeholder="Enter user ID")
    # top_n_input = gr.Number(label="Number of Recommendations", value=5, precision=0)
    top_n_input = gr.Slider(5, 20, value=10, step=1, label="Number of Recommendations")
    
    recommend_btn = gr.Button("Recommend Books")
    output = gr.HTML(label="Recommendations")

    recommend_btn.click(
        lambda uid, n: recommend_books(uid, int(n)).to_html(escape=False, index=False),
        inputs=[user_id_input, top_n_input],
        outputs=output
    )


app_ui.launch()