Josh Strupp commited on
Commit
077a7f8
Β·
1 Parent(s): b0e35b7

update app

Browse files
Files changed (1) hide show
  1. app.py +211 -96
app.py CHANGED
@@ -1,113 +1,228 @@
1
  import gradio as gr
2
  import pandas as pd
3
  import numpy as np
 
4
  from sklearn.feature_extraction.text import TfidfVectorizer
5
  from sklearn.metrics.pairwise import cosine_similarity
6
 
7
- def recommend_books(concern, top_n=5, reviews_per_book=2):
8
- # Load and preprocess data
9
- df = pd.read_csv('self_help_books.csv')
10
-
11
- # Create TF-IDF vectors from reviews
12
- tfidf = TfidfVectorizer(stop_words='english')
13
- review_vectors = tfidf.fit_transform(df['Review'].fillna(''))
14
- concern_vector = tfidf.transform([concern])
15
-
16
- # Calculate similarity scores
17
- similarities = cosine_similarity(concern_vector, review_vectors).flatten()
18
-
19
- # Get top books based on review similarity
20
- top_indices = np.argsort(similarities)[-top_n:][::-1]
21
- recommended_books = df.iloc[top_indices].copy()
22
-
23
- # Add helpful and harmful reviews
24
- for idx, row in recommended_books.iterrows():
25
- book_reviews = df[df['Book'] == row['Book']]
26
-
27
- # Get helpful reviews
28
- helpful_reviews = book_reviews.nlargest(reviews_per_book, 'Helpful_Ratio')['Review'].tolist()
29
- recommended_books.at[idx, 'Helpful Reviews'] = helpful_reviews
30
-
31
- # Get critical reviews
32
- harmful_reviews = book_reviews.nsmallest(reviews_per_book, 'Helpful_Ratio')['Review'].tolist()
33
- recommended_books.at[idx, 'Harmful Reviews'] = harmful_reviews
34
-
35
- return recommended_books
36
-
37
- def recommend_authors(concern, top_n=5):
38
- df = pd.read_csv('self_help_books.csv')
39
-
40
- # Calculate author metrics
41
- author_stats = df.groupby('author_clean').agg({
42
- 'Helpful_Ratio': ['mean', 'count']
43
- }).reset_index()
44
-
45
- author_stats.columns = ['author_clean', 'helpful_ratio', 'review_count']
46
-
47
- # Filter authors with minimum reviews
48
- min_reviews = 5
49
- author_stats = author_stats[author_stats['review_count'] >= min_reviews]
50
-
51
- # Get top and bottom authors
52
- good_authors = author_stats.nlargest(top_n, 'helpful_ratio')
53
- risky_authors = author_stats.nsmallest(top_n, 'helpful_ratio')
54
-
55
- return good_authors, risky_authors
56
-
57
- def recommend_for_concern(concern, num_books=5, num_reviews=2):
58
- """Wrapper function to format recommendations for Gradio"""
59
- books_df = recommend_books(concern, top_n=num_books, reviews_per_book=num_reviews)
60
- good_authors, risky_authors = recommend_authors(concern, top_n=num_books)
61
-
62
- # Format book recommendations
63
- book_output = "=== RECOMMENDED BOOKS ===\n\n"
64
- for _, book in books_df.iterrows():
65
- book_output += f"πŸ“š {book['Book']}\n"
66
- book_output += f"πŸ‘€ Author: {book['Author']}\n"
67
- book_output += f"⭐ Rating: {book['Star_Rating']}\n"
68
- book_output += f"πŸ’° Price: ${book['Price']}\n"
69
- book_output += f"πŸ“Š Helpful Ratio: {book['Helpful_Ratio']:.2f}\n"
70
-
71
- if book['Helpful Reviews']:
72
- book_output += "\nβœ… Helpful Reviews:\n"
73
- for review in book['Helpful Reviews']:
74
- book_output += f"β€’ {review}\n"
75
-
76
- if book['Harmful Reviews']:
77
- book_output += "\n⚠️ Critical Reviews:\n"
78
- for review in book['Harmful Reviews']:
79
- book_output += f"β€’ {review}\n"
80
-
81
- book_output += "\n" + "-"*50 + "\n\n"
82
-
83
- # Format author recommendations
84
- author_output = "=== RECOMMENDED AUTHORS ===\n\n"
85
- author_output += "βœ… Authors Likely to be Helpful:\n"
86
- for _, author in good_authors.iterrows():
87
- author_output += f"β€’ {author['author_clean']} (Helpful ratio: {author['helpful_ratio']:.2f})\n"
88
-
89
- author_output += "\n⚠️ Authors to Approach with Caution:\n"
90
- for _, author in risky_authors.iterrows():
91
- author_output += f"β€’ {author['author_clean']} (Helpful ratio: {author['helpful_ratio']:.2f})\n"
92
-
93
- return book_output + "\n\n" + author_output
94
-
95
- # Create the Gradio interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  iface = gr.Interface(
97
  fn=recommend_for_concern,
98
  inputs=[
99
- gr.Textbox(label="What concern or fear would you like help with?", placeholder="e.g. I'm a lonely teenager"),
100
- gr.Slider(minimum=1, maximum=10, value=5, step=1, label="Number of recommendations"),
101
- gr.Slider(minimum=1, maximum=5, value=2, step=1, label="Reviews per book")
 
 
 
102
  ],
103
  outputs=gr.Textbox(label="Recommendations", lines=20),
104
- title="Self-Help Book Recommender",
105
- description="Get personalized book recommendations based on your concerns or fears.",
106
  examples=[
107
  ["I'm a lonely teenager", 5, 2],
108
  ["I'm worried about my career", 5, 2],
109
- ["I have anxiety about the future", 5, 2]
110
- ]
111
  )
112
 
113
  iface.launch()
 
1
  import gradio as gr
2
  import pandas as pd
3
  import numpy as np
4
+ from pathlib import Path
5
  from sklearn.feature_extraction.text import TfidfVectorizer
6
  from sklearn.metrics.pairwise import cosine_similarity
7
 
8
+ # ---------------------------------------------------------------------------
9
+ # 0. LOAD DATA PRE-GENERATED BY THE OFFLINE PIPELINE
10
+ # ---------------------------------------------------------------------------
11
+ BOOKS_CSV = Path("self_help_books.csv")
12
+ REVIEWS_CSV = Path("self_help_reviews.csv") # may be absent - optional
13
+
14
+ df_books = pd.read_csv(BOOKS_CSV)
15
+ df_reviews = pd.read_csv(REVIEWS_CSV) if REVIEWS_CSV.exists() else pd.DataFrame()
16
+
17
+ # ---------------------------------------------------------------------------
18
+ # 1. VERY LIGHT TEXT PRE-PROCESSING + TF-IDF FEATURES
19
+ # ---------------------------------------------------------------------------
20
+ def _prep(text: str) -> str:
21
+ """Lower-case & cast NaNs to an empty string."""
22
+ return str(text).lower() if pd.notnull(text) else ""
23
+
24
+ # Build the text that summarises each book (only if not already present)
25
+ if "combined_text" not in df_books.columns:
26
+ df_books["combined_text"] = (
27
+ df_books["summary"].apply(_prep) + " " +
28
+ df_books["genres"].apply(_prep) + " " +
29
+ df_books["key_cat_primary"].apply(_prep)
30
+ )
31
+
32
+ vectorizer = TfidfVectorizer(stop_words="english", max_features=50_000)
33
+ X_BOOKS = vectorizer.fit_transform(df_books["combined_text"])
34
+
35
+ # ---------------------------------------------------------------------------
36
+ # 2. AUTHOR-LEVEL AGGREGATION (fallbacks if columns are missing)
37
+ # ---------------------------------------------------------------------------
38
+ if {"helpful_ratio", "total_reviews"}.issubset(df_books.columns):
39
+ author_stats = (
40
+ df_books.groupby("author_clean")
41
+ .agg(helpful_ratio=("helpful_ratio", "mean"),
42
+ total_reviews=("total_reviews", "sum"))
43
+ .reset_index()
44
+ )
45
+ else: # keep the code functional even without those columns
46
+ author_stats = pd.DataFrame(
47
+ columns=["author_clean", "helpful_ratio", "total_reviews"]
48
+ )
49
+
50
+ # ---------------------------------------------------------------------------
51
+ # 3. MAIN RECOMMENDATION FUNCTIONS
52
+ # ---------------------------------------------------------------------------
53
+ def recommend_books(user_issue: str,
54
+ top_n: int = 5,
55
+ reviews_per_book: int = 2,
56
+ min_reviews: int = 10) -> pd.DataFrame:
57
+ """
58
+ Blend topical similarity (70 %) with helpfulness (30 %)
59
+ and return the `top_n` books best suited to `user_issue`.
60
+ """
61
+ # ---- similarity -------------------------------------------------------
62
+ query_vec = vectorizer.transform([user_issue.lower()])
63
+ similarity = cosine_similarity(query_vec, X_BOOKS).ravel()
64
+
65
+ df_temp = df_books.copy()
66
+ df_temp["similarity"] = similarity
67
+ df_temp["helpful_ratio_filled"] = df_temp.get("helpful_ratio", 0).fillna(0)
68
+
69
+ if "total_reviews" in df_temp.columns:
70
+ df_temp = df_temp[df_temp["total_reviews"] >= min_reviews]
71
+
72
+ df_temp["score"] = (
73
+ 0.70 * df_temp["similarity"] +
74
+ 0.30 * df_temp["helpful_ratio_filled"]
75
+ )
76
+
77
+ top_books = df_temp.nlargest(top_n, "score").reset_index(drop=True)
78
+
79
+ # ---- representative reviews ------------------------------------------
80
+ results = []
81
+ for _, row in top_books.iterrows():
82
+ name = row.get("name", row.get("Book", ""))
83
+ author = row.get("author_clean", row.get("Author", ""))
84
+ # sample reviews only if we actually have them
85
+ if not df_reviews.empty and {"is_helpful", "is_harmful"}.issubset(df_reviews.columns):
86
+ helpful_mask = (df_reviews["name"] == name) & (df_reviews["is_helpful"])
87
+ harmful_mask = (df_reviews["name"] == name) & (df_reviews["is_harmful"])
88
+
89
+ helpful_reviews = (
90
+ df_reviews[helpful_mask]
91
+ .sample(min(reviews_per_book, helpful_mask.sum()), random_state=42)
92
+ ["review_text"].tolist()
93
+ if helpful_mask.any() else []
94
+ )
95
+ harmful_reviews = (
96
+ df_reviews[harmful_mask]
97
+ .sample(min(reviews_per_book, harmful_mask.sum()), random_state=42)
98
+ ["review_text"].tolist()
99
+ if harmful_mask.any() else []
100
+ )
101
+ else:
102
+ helpful_reviews, harmful_reviews = [], []
103
+
104
+ results.append({
105
+ "Book" : name,
106
+ "Author" : author,
107
+ "Star_Rating" : row.get("star_rating", np.nan),
108
+ "Price" : row.get("kindle_price_clean", np.nan),
109
+ "Helpful_Ratio" : round(row.get("helpful_ratio", 0), 3),
110
+ "Similarity" : round(row["similarity"], 3),
111
+ "Helpful Reviews" : helpful_reviews,
112
+ "Harmful Reviews" : harmful_reviews
113
+ })
114
+
115
+ return pd.DataFrame(results)
116
+
117
+
118
+ def recommend_authors(user_issue: str,
119
+ top_n: int = 5,
120
+ min_reviews: int = 30):
121
+ """
122
+ Return two DataFrames:
123
+ β€’ authors likely to be helpful
124
+ β€’ authors you might approach with caution
125
+ Ranking = 70 % topical relevance + 30 % helpfulness.
126
+ """
127
+ query_vec = vectorizer.transform([user_issue.lower()])
128
+ similarity = cosine_similarity(query_vec, X_BOOKS).ravel()
129
+
130
+ rel_df = pd.DataFrame({
131
+ "author_clean": df_books["author_clean"],
132
+ "sim_to_issue": similarity
133
+ })
134
+
135
+ author_relevance = (
136
+ rel_df.groupby("author_clean")
137
+ .agg(max_sim=("sim_to_issue", "max"))
138
+ .reset_index()
139
+ )
140
+
141
+ merged = author_relevance.merge(author_stats, on="author_clean", how="left")
142
+ merged["helpful_ratio"] = merged["helpful_ratio"].fillna(0)
143
+ merged["total_reviews"] = merged["total_reviews"].fillna(0)
144
+ merged = merged[merged["total_reviews"] >= min_reviews]
145
+
146
+ merged["score"] = 0.70 * merged["max_sim"] + 0.30 * merged["helpful_ratio"]
147
+
148
+ helpful_authors = (
149
+ merged[merged["helpful_ratio"] >= 0.5]
150
+ .nlargest(top_n, "score")
151
+ .reset_index(drop=True)
152
+ )
153
+
154
+ risky_authors = (
155
+ merged[merged["helpful_ratio"] < 0.5]
156
+ .nlargest(top_n, "score")
157
+ .reset_index(drop=True)
158
+ )
159
+
160
+ return helpful_authors, risky_authors
161
+
162
+
163
+ # ---------------------------------------------------------------------------
164
+ # 4. GRADIO GLUE – format nicely & expose a simple interface
165
+ # ---------------------------------------------------------------------------
166
+ def _format_output(books_df, good_authors, bad_authors) -> str:
167
+ txt = "=== RECOMMENDED BOOKS ===\n\n"
168
+ for _, bk in books_df.iterrows():
169
+ txt += f"πŸ“š {bk['Book']}\n"
170
+ txt += f"πŸ‘€ Author: {bk['Author']}\n"
171
+ txt += f"⭐ Rating: {bk['Star_Rating']}\n"
172
+ txt += f"πŸ’° Price: ${bk['Price']}\n"
173
+ txt += f"πŸ“Š Helpful Ratio: {bk['Helpful_Ratio']:.2f}\n"
174
+ if bk["Helpful Reviews"]:
175
+ txt += "\nβœ… Helpful Reviews:\n"
176
+ for rv in bk["Helpful Reviews"]:
177
+ txt += f"β€’ {rv}\n"
178
+ if bk["Harmful Reviews"]:
179
+ txt += "\n⚠️ Critical Reviews:\n"
180
+ for rv in bk["Harmful Reviews"]:
181
+ txt += f"β€’ {rv}\n"
182
+ txt += "\n" + "-" * 50 + "\n\n"
183
+
184
+ txt += "=== RECOMMENDED AUTHORS ===\n\n"
185
+ txt += "βœ… Authors Likely to be Helpful:\n"
186
+ for _, au in good_authors.iterrows():
187
+ txt += f"β€’ {au['author_clean']} (Helpful ratio: {au['helpful_ratio']:.2f})\n"
188
+ txt += "\n⚠️ Authors to Approach with Caution:\n"
189
+ for _, au in bad_authors.iterrows():
190
+ txt += f"β€’ {au['author_clean']} (Helpful ratio: {au['helpful_ratio']:.2f})\n"
191
+ return txt
192
+
193
+
194
+ def recommend_for_concern(concern: str,
195
+ num_books: int = 5,
196
+ num_reviews: int = 2) -> str:
197
+ books_df = recommend_books(concern,
198
+ top_n=num_books,
199
+ reviews_per_book=num_reviews)
200
+ good_authors, bad_authors = recommend_authors(concern,
201
+ top_n=num_books)
202
+ return _format_output(books_df, good_authors, bad_authors)
203
+
204
+
205
+ # ---------------------------------------------------------------------------
206
+ # 5. LAUNCH GRADIO
207
+ # ---------------------------------------------------------------------------
208
  iface = gr.Interface(
209
  fn=recommend_for_concern,
210
  inputs=[
211
+ gr.Textbox(label="What concern or fear would you like help with?",
212
+ placeholder="e.g. I'm a lonely teenager"),
213
+ gr.Slider(label="Number of recommendations",
214
+ minimum=1, maximum=10, step=1, value=5),
215
+ gr.Slider(label="Reviews per book",
216
+ minimum=1, maximum=5, step=1, value=2),
217
  ],
218
  outputs=gr.Textbox(label="Recommendations", lines=20),
219
+ title="Self-Help Book Recommendation Engine",
220
+ description="Personalised, review-aware book & author suggestions.",
221
  examples=[
222
  ["I'm a lonely teenager", 5, 2],
223
  ["I'm worried about my career", 5, 2],
224
+ ["I have anxiety about the future", 5, 2],
225
+ ],
226
  )
227
 
228
  iface.launch()