Josh Strupp
commited on
Commit
Β·
077a7f8
1
Parent(s):
b0e35b7
update app
Browse files
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 |
-
|
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 |
-
author_stats
|
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 |
iface = gr.Interface(
|
97 |
fn=recommend_for_concern,
|
98 |
inputs=[
|
99 |
-
gr.Textbox(label="What concern or fear would you like help with?",
|
100 |
-
|
101 |
-
gr.Slider(
|
|
|
|
|
|
|
102 |
],
|
103 |
outputs=gr.Textbox(label="Recommendations", lines=20),
|
104 |
-
title="Self-Help Book
|
105 |
-
description="
|
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()
|