Spaces:
Sleeping
Sleeping
some major updates on UI and backend
Browse files
app.py
CHANGED
|
@@ -11,24 +11,32 @@ from typing import List, Dict
|
|
| 11 |
load_dotenv()
|
| 12 |
SUPABASE_URL = os.getenv("DB_URL")
|
| 13 |
SUPABASE_KEY = os.getenv("DB_KEY")
|
| 14 |
-
supabase_client = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 15 |
-
|
| 16 |
pinecone_api_key = os.getenv("PINECONE")
|
|
|
|
|
|
|
| 17 |
pc = Pinecone(api_key=pinecone_api_key)
|
| 18 |
index = pc.Index("focus-guru")
|
| 19 |
-
model = SentenceTransformer(
|
| 20 |
|
| 21 |
-
def ingest_user_progress(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
data = {
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
}
|
| 31 |
-
response = supabase_client.table(
|
| 32 |
return response.data
|
| 33 |
|
| 34 |
def gradio_ingest(user_input):
|
|
@@ -41,9 +49,9 @@ def gradio_ingest(user_input):
|
|
| 41 |
play_count = int(data.get("play_count", 0))
|
| 42 |
completed = bool(data.get("completed", False))
|
| 43 |
except Exception as e:
|
| 44 |
-
return f"<
|
| 45 |
res = ingest_user_progress(supabase_client, user_id, video_id, rating, time_spent, play_count, completed)
|
| 46 |
-
return f"<
|
| 47 |
|
| 48 |
def recommend_playlists_by_package_and_module(assessment_output, index, model):
|
| 49 |
report_text = assessment_output.get("report", "")
|
|
@@ -74,125 +82,100 @@ def gradio_recommend_playlist(input_json):
|
|
| 74 |
try:
|
| 75 |
assessment_data = json.loads(input_json)
|
| 76 |
except json.JSONDecodeError:
|
| 77 |
-
return "<
|
| 78 |
if "package" not in assessment_data or "report" not in assessment_data:
|
| 79 |
-
return "<
|
| 80 |
recs = recommend_playlists_by_package_and_module(assessment_data, index, model)
|
| 81 |
-
html_output = ""
|
| 82 |
-
<div style="
|
| 83 |
-
display: flex;
|
| 84 |
-
flex-direction: column;
|
| 85 |
-
gap: 30px;
|
| 86 |
-
padding: 20px;
|
| 87 |
-
font-family: Arial, sans-serif;
|
| 88 |
-
">
|
| 89 |
-
"""
|
| 90 |
for pkg, mod_recs in recs.items():
|
| 91 |
-
html_output += f"<h2 style='
|
| 92 |
-
html_output += "<div style='display: flex; flex-wrap: wrap; gap: 20px;'>"
|
| 93 |
for mod, rec in mod_recs.items():
|
| 94 |
-
|
| 95 |
-
<div style="
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
background: white;
|
| 100 |
-
width: 300px;
|
| 101 |
-
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
| 102 |
-
">
|
| 103 |
-
<h3 style="margin: 0 0 12px 0; color: #0984e3;">{mod} Module</h3>
|
| 104 |
-
<h4 style="margin: 0 0 8px 0; color: #2d3436;">{rec['title']}</h4>
|
| 105 |
-
<p style="margin: 0; color: #636e72; line-height: 1.5;">{rec['description']}</p>
|
| 106 |
</div>
|
| 107 |
"""
|
| 108 |
-
html_output += card_html
|
| 109 |
html_output += "</div>"
|
| 110 |
html_output += "</div>"
|
| 111 |
return html_output
|
| 112 |
|
| 113 |
-
def recommend_videos(user_id: int, K: int = 5, M: int = 10, N: int = 5) ->
|
| 114 |
-
response = supabase_client.table(
|
| 115 |
interactions = response.data
|
| 116 |
if not interactions:
|
| 117 |
-
return
|
|
|
|
|
|
|
|
|
|
| 118 |
for inter in interactions:
|
| 119 |
-
rating = inter[
|
| 120 |
-
completed_val = 1 if inter[
|
| 121 |
-
play_count = inter[
|
| 122 |
-
engagement = rating + 2 * completed_val + play_count
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
candidates = {}
|
| 127 |
for top_video in top_videos:
|
| 128 |
query_id = f"video_{top_video['video_id']}"
|
| 129 |
response = index.query(id=query_id, top_k=M + 1, include_metadata=True)
|
| 130 |
-
for match in response.get(
|
| 131 |
-
if match[
|
| 132 |
continue
|
| 133 |
-
metadata = match.get(
|
| 134 |
-
vid = metadata.get(
|
| 135 |
if not vid:
|
| 136 |
continue
|
| 137 |
if vid in watched_completed_videos:
|
| 138 |
continue
|
| 139 |
-
similarity = match[
|
| 140 |
-
pid = metadata.get(
|
| 141 |
-
boost = 1.1 if pid == top_video[
|
| 142 |
-
partial_score = top_video[
|
| 143 |
if vid in candidates:
|
| 144 |
-
candidates[vid][
|
| 145 |
else:
|
| 146 |
-
candidates[vid] = {
|
| 147 |
-
sorted_candidates = sorted(candidates.items(), key=lambda x: x[1][
|
| 148 |
recommendations = []
|
| 149 |
for vid, data in sorted_candidates:
|
| 150 |
-
metadata = data[
|
|
|
|
|
|
|
|
|
|
| 151 |
recommendations.append({
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
})
|
| 157 |
-
|
|
|
|
| 158 |
|
| 159 |
def gradio_recommend_videos(user_id_input):
|
| 160 |
try:
|
| 161 |
user_id = int(user_id_input)
|
| 162 |
except Exception as e:
|
| 163 |
-
return f"
|
| 164 |
-
|
|
|
|
|
|
|
| 165 |
if not recs:
|
| 166 |
-
return
|
| 167 |
-
html_output = ""
|
| 168 |
-
|
| 169 |
-
display: flex;
|
| 170 |
-
flex-direction: column;
|
| 171 |
-
gap: 30px;
|
| 172 |
-
padding: 20px;
|
| 173 |
-
font-family: Arial, sans-serif;
|
| 174 |
-
">
|
| 175 |
-
"""
|
| 176 |
-
html_output += "<h2 style='color: #2d3436;'>Recommended Videos</h2>"
|
| 177 |
-
html_output += "<div style='display: flex; flex-wrap: wrap; gap: 20px;'>"
|
| 178 |
for rec in recs:
|
| 179 |
-
|
| 180 |
-
<div style="
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
background: white;
|
| 185 |
-
width: 300px;
|
| 186 |
-
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
| 187 |
-
">
|
| 188 |
-
<h3 style="margin: 0 0 12px 0; color: #0984e3;">{rec['title']}</h3>
|
| 189 |
-
<p style="margin: 0 0 8px 0; color: #636e72;">{rec['description']}</p>
|
| 190 |
-
<p style="margin: 0; color: #2d3436;">Score: {rec['score']:.2f}</p>
|
| 191 |
</div>
|
| 192 |
"""
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
return html_output
|
| 196 |
|
| 197 |
with gr.Blocks() as demo:
|
| 198 |
with gr.Tabs():
|
|
@@ -202,17 +185,18 @@ with gr.Blocks() as demo:
|
|
| 202 |
label="Assessment Data (JSON)",
|
| 203 |
placeholder='''{
|
| 204 |
"package": ["Focus", "Insomnia"],
|
| 205 |
-
"report": "Based on your responses, you may struggle with focus, anxiety, and burnout
|
| 206 |
}'''
|
| 207 |
)
|
| 208 |
playlist_output = gr.HTML(label="Recommended Playlists")
|
| 209 |
playlist_btn = gr.Button("Get Playlist Recommendations")
|
| 210 |
-
playlist_btn.click(gradio_recommend_playlist, playlist_input, playlist_output)
|
| 211 |
with gr.TabItem("Video Recommendation"):
|
| 212 |
user_id_input = gr.Textbox(lines=1, label="User ID", placeholder="1")
|
|
|
|
| 213 |
videos_output = gr.HTML(label="Recommended Videos")
|
| 214 |
videos_btn = gr.Button("Get Video Recommendations")
|
| 215 |
-
videos_btn.click(gradio_recommend_videos, user_id_input, videos_output)
|
| 216 |
with gr.TabItem("User Interaction Ingestion"):
|
| 217 |
ingest_input = gr.Textbox(
|
| 218 |
lines=10,
|
|
@@ -228,6 +212,6 @@ with gr.Blocks() as demo:
|
|
| 228 |
)
|
| 229 |
ingest_output = gr.HTML(label="Ingestion Result")
|
| 230 |
ingest_btn = gr.Button("Ingest Data")
|
| 231 |
-
ingest_btn.click(gradio_ingest, ingest_input, ingest_output)
|
| 232 |
|
| 233 |
demo.launch()
|
|
|
|
| 11 |
load_dotenv()
|
| 12 |
SUPABASE_URL = os.getenv("DB_URL")
|
| 13 |
SUPABASE_KEY = os.getenv("DB_KEY")
|
|
|
|
|
|
|
| 14 |
pinecone_api_key = os.getenv("PINECONE")
|
| 15 |
+
|
| 16 |
+
supabase_client = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 17 |
pc = Pinecone(api_key=pinecone_api_key)
|
| 18 |
index = pc.Index("focus-guru")
|
| 19 |
+
model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 20 |
|
| 21 |
+
def ingest_user_progress(
|
| 22 |
+
supabase_client: Client,
|
| 23 |
+
user_id: int,
|
| 24 |
+
video_id: str,
|
| 25 |
+
rating: float,
|
| 26 |
+
time_spent: int,
|
| 27 |
+
play_count: int,
|
| 28 |
+
completed: bool
|
| 29 |
+
):
|
| 30 |
data = {
|
| 31 |
+
"user_id": user_id,
|
| 32 |
+
"video_id": video_id,
|
| 33 |
+
"rating": rating,
|
| 34 |
+
"time_spent": time_spent,
|
| 35 |
+
"play_count": play_count,
|
| 36 |
+
"completed": completed,
|
| 37 |
+
"updated_at": datetime.now().isoformat()
|
| 38 |
}
|
| 39 |
+
response = supabase_client.table("user_progress").insert(data, upsert=True).execute()
|
| 40 |
return response.data
|
| 41 |
|
| 42 |
def gradio_ingest(user_input):
|
|
|
|
| 49 |
play_count = int(data.get("play_count", 0))
|
| 50 |
completed = bool(data.get("completed", False))
|
| 51 |
except Exception as e:
|
| 52 |
+
return f"<p style='color: red;'>Error parsing input: {e}</p>"
|
| 53 |
res = ingest_user_progress(supabase_client, user_id, video_id, rating, time_spent, play_count, completed)
|
| 54 |
+
return f"<p style='color: green;'>Ingested data: {res}</p>"
|
| 55 |
|
| 56 |
def recommend_playlists_by_package_and_module(assessment_output, index, model):
|
| 57 |
report_text = assessment_output.get("report", "")
|
|
|
|
| 82 |
try:
|
| 83 |
assessment_data = json.loads(input_json)
|
| 84 |
except json.JSONDecodeError:
|
| 85 |
+
return "<p style='color: red;'>Error: Invalid JSON format</p>"
|
| 86 |
if "package" not in assessment_data or "report" not in assessment_data:
|
| 87 |
+
return "<p style='color: red;'>Error: Missing 'package' or 'report' field</p>"
|
| 88 |
recs = recommend_playlists_by_package_and_module(assessment_data, index, model)
|
| 89 |
+
html_output = "<div style='padding: 20px; font-family: Arial, sans-serif;'>"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
for pkg, mod_recs in recs.items():
|
| 91 |
+
html_output += f"<h2>{pkg} Package</h2><div style='display: flex; flex-wrap: wrap; gap: 20px;'>"
|
|
|
|
| 92 |
for mod, rec in mod_recs.items():
|
| 93 |
+
html_output += f"""
|
| 94 |
+
<div style="border: 1px solid #ccc; border-radius: 8px; padding: 15px; width: 260px;">
|
| 95 |
+
<h3>{mod} Module</h3>
|
| 96 |
+
<strong>{rec['title']}</strong>
|
| 97 |
+
<p>{rec['description']}</p>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
</div>
|
| 99 |
"""
|
|
|
|
| 100 |
html_output += "</div>"
|
| 101 |
html_output += "</div>"
|
| 102 |
return html_output
|
| 103 |
|
| 104 |
+
def recommend_videos(user_id: int, K: int = 5, M: int = 10, N: int = 5) -> Dict:
|
| 105 |
+
response = supabase_client.table("user_progress").select("video_id, rating, completed, play_count, videos!inner(playlist_id)").eq("user_id", user_id).execute()
|
| 106 |
interactions = response.data
|
| 107 |
if not interactions:
|
| 108 |
+
return {
|
| 109 |
+
"note": "No interactions recorded for this user yet. Please watch or rate some videos.",
|
| 110 |
+
"recommendations": []
|
| 111 |
+
}
|
| 112 |
for inter in interactions:
|
| 113 |
+
rating = inter["rating"] if inter["rating"] is not None else 0
|
| 114 |
+
completed_val = 1 if inter["completed"] else 0
|
| 115 |
+
play_count = inter["play_count"]
|
| 116 |
+
inter["engagement"] = rating + 2 * completed_val + play_count
|
| 117 |
+
top_videos = sorted(interactions, key=lambda x: x["engagement"], reverse=True)[:K]
|
| 118 |
+
watched_completed_videos = {i["video_id"] for i in interactions if i["completed"]}
|
| 119 |
+
watched_incomplete_videos = {i["video_id"] for i in interactions if not i["completed"]}
|
| 120 |
candidates = {}
|
| 121 |
for top_video in top_videos:
|
| 122 |
query_id = f"video_{top_video['video_id']}"
|
| 123 |
response = index.query(id=query_id, top_k=M + 1, include_metadata=True)
|
| 124 |
+
for match in response.get("matches", []):
|
| 125 |
+
if match["id"] == query_id:
|
| 126 |
continue
|
| 127 |
+
metadata = match.get("metadata", {})
|
| 128 |
+
vid = metadata.get("vid")
|
| 129 |
if not vid:
|
| 130 |
continue
|
| 131 |
if vid in watched_completed_videos:
|
| 132 |
continue
|
| 133 |
+
similarity = match["score"]
|
| 134 |
+
pid = metadata.get("PID")
|
| 135 |
+
boost = 1.1 if pid == top_video["videos"]["playlist_id"] else 1.0
|
| 136 |
+
partial_score = top_video["engagement"] * similarity * boost
|
| 137 |
if vid in candidates:
|
| 138 |
+
candidates[vid]["total_score"] += partial_score
|
| 139 |
else:
|
| 140 |
+
candidates[vid] = {"total_score": partial_score, "metadata": metadata}
|
| 141 |
+
sorted_candidates = sorted(candidates.items(), key=lambda x: x[1]["total_score"], reverse=True)[:N]
|
| 142 |
recommendations = []
|
| 143 |
for vid, data in sorted_candidates:
|
| 144 |
+
metadata = data["metadata"]
|
| 145 |
+
video_title = metadata.get("video_title", "Untitled Video")
|
| 146 |
+
if vid in watched_incomplete_videos:
|
| 147 |
+
video_title += " (Incomplete)"
|
| 148 |
recommendations.append({
|
| 149 |
+
"video_id": vid,
|
| 150 |
+
"title": video_title,
|
| 151 |
+
"description": metadata.get("video_description", ""),
|
| 152 |
+
"score": data["total_score"]
|
| 153 |
})
|
| 154 |
+
note_text = "Based on your engagement, here are some recommended videos from the same playlist."
|
| 155 |
+
return {"note": note_text, "recommendations": recommendations}
|
| 156 |
|
| 157 |
def gradio_recommend_videos(user_id_input):
|
| 158 |
try:
|
| 159 |
user_id = int(user_id_input)
|
| 160 |
except Exception as e:
|
| 161 |
+
return f"Error: {e}", ""
|
| 162 |
+
result = recommend_videos(user_id)
|
| 163 |
+
note_text = result["note"]
|
| 164 |
+
recs = result["recommendations"]
|
| 165 |
if not recs:
|
| 166 |
+
return note_text, ""
|
| 167 |
+
html_output = "<div>"
|
| 168 |
+
# Use black cards with white text and orange border for visibility
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
for rec in recs:
|
| 170 |
+
html_output += f"""
|
| 171 |
+
<div style="background: #000; color: #fff; border: 2px solid orange; border-radius: 8px; margin-bottom: 10px; padding: 15px;">
|
| 172 |
+
<h3 style="margin-top: 0;">{rec['title']}</h3>
|
| 173 |
+
<p style="margin: 0;">{rec['description']}</p>
|
| 174 |
+
<p style="margin: 0;"><strong>Score:</strong> {rec['score']:.2f}</p>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
</div>
|
| 176 |
"""
|
| 177 |
+
html_output += "</div>"
|
| 178 |
+
return note_text, html_output
|
|
|
|
| 179 |
|
| 180 |
with gr.Blocks() as demo:
|
| 181 |
with gr.Tabs():
|
|
|
|
| 185 |
label="Assessment Data (JSON)",
|
| 186 |
placeholder='''{
|
| 187 |
"package": ["Focus", "Insomnia"],
|
| 188 |
+
"report": "Based on your responses, you may struggle with focus, anxiety, and burnout..."
|
| 189 |
}'''
|
| 190 |
)
|
| 191 |
playlist_output = gr.HTML(label="Recommended Playlists")
|
| 192 |
playlist_btn = gr.Button("Get Playlist Recommendations")
|
| 193 |
+
playlist_btn.click(fn=gradio_recommend_playlist, inputs=playlist_input, outputs=playlist_output)
|
| 194 |
with gr.TabItem("Video Recommendation"):
|
| 195 |
user_id_input = gr.Textbox(lines=1, label="User ID", placeholder="1")
|
| 196 |
+
note_output = gr.Textbox(label="Recommendation Note", interactive=False)
|
| 197 |
videos_output = gr.HTML(label="Recommended Videos")
|
| 198 |
videos_btn = gr.Button("Get Video Recommendations")
|
| 199 |
+
videos_btn.click(fn=gradio_recommend_videos, inputs=user_id_input, outputs=[note_output, videos_output])
|
| 200 |
with gr.TabItem("User Interaction Ingestion"):
|
| 201 |
ingest_input = gr.Textbox(
|
| 202 |
lines=10,
|
|
|
|
| 212 |
)
|
| 213 |
ingest_output = gr.HTML(label="Ingestion Result")
|
| 214 |
ingest_btn = gr.Button("Ingest Data")
|
| 215 |
+
ingest_btn.click(fn=gradio_ingest, inputs=ingest_input, outputs=ingest_output)
|
| 216 |
|
| 217 |
demo.launch()
|