datafreak commited on
Commit
b4dfce4
·
verified ·
1 Parent(s): 2964773

some major updates on UI and backend

Browse files
Files changed (1) hide show
  1. app.py +84 -100
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('all-MiniLM-L6-v2')
20
 
21
- def ingest_user_progress(supabase_client: Client, user_id: int, video_id: str, rating: float, time_spent: int, play_count: int, completed: bool):
 
 
 
 
 
 
 
 
22
  data = {
23
- 'user_id': user_id,
24
- 'video_id': video_id,
25
- 'rating': rating,
26
- 'time_spent': time_spent,
27
- 'play_count': play_count,
28
- 'completed': completed,
29
- 'updated_at': datetime.now().isoformat()
30
  }
31
- response = supabase_client.table('user_progress').insert(data, upsert=True).execute()
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"<div style='color: red;'>Error parsing input: {e}</div>"
45
  res = ingest_user_progress(supabase_client, user_id, video_id, rating, time_spent, play_count, completed)
46
- return f"<div style='color: green;'>Ingested data: {res}</div>"
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 "<div style='color: red;'>Error: Invalid JSON format</div>"
78
  if "package" not in assessment_data or "report" not in assessment_data:
79
- return "<div style='color: red;'>Error: Missing 'package' or 'report' field</div>"
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='color: #2d3436;'>{pkg} Package</h2>"
92
- html_output += "<div style='display: flex; flex-wrap: wrap; gap: 20px;'>"
93
  for mod, rec in mod_recs.items():
94
- card_html = f"""
95
- <div style="
96
- border: 1px solid #e0e0e0;
97
- border-radius: 10px;
98
- padding: 20px;
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) -> List[Dict]:
114
- response = supabase_client.table('user_progress').select('video_id, rating, completed, play_count, videos!inner(playlist_id)').eq('user_id', user_id).execute()
115
  interactions = response.data
116
  if not interactions:
117
- return []
 
 
 
118
  for inter in interactions:
119
- rating = inter['rating'] if inter['rating'] is not None else 0
120
- completed_val = 1 if inter['completed'] else 0
121
- play_count = inter['play_count']
122
- engagement = rating + 2 * completed_val + play_count
123
- inter['engagement'] = engagement
124
- top_videos = sorted(interactions, key=lambda x: x['engagement'], reverse=True)[:K]
125
- watched_completed_videos = {i['video_id'] for i in interactions if i['completed']}
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('matches', []):
131
- if match['id'] == query_id:
132
  continue
133
- metadata = match.get('metadata', {})
134
- vid = metadata.get('vid')
135
  if not vid:
136
  continue
137
  if vid in watched_completed_videos:
138
  continue
139
- similarity = match['score']
140
- pid = metadata.get('PID')
141
- boost = 1.1 if pid == top_video['videos']['playlist_id'] else 1.0
142
- partial_score = top_video['engagement'] * similarity * boost
143
  if vid in candidates:
144
- candidates[vid]['total_score'] += partial_score
145
  else:
146
- candidates[vid] = {'total_score': partial_score, 'metadata': metadata}
147
- sorted_candidates = sorted(candidates.items(), key=lambda x: x[1]['total_score'], reverse=True)[:N]
148
  recommendations = []
149
  for vid, data in sorted_candidates:
150
- metadata = data['metadata']
 
 
 
151
  recommendations.append({
152
- 'video_id': vid,
153
- 'title': metadata.get('video_title'),
154
- 'description': metadata.get('video_description'),
155
- 'score': data['total_score']
156
  })
157
- return recommendations
 
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"<div style='color: red;'>Error: {e}</div>"
164
- recs = recommend_videos(user_id)
 
 
165
  if not recs:
166
- return "<div style='color: #636e72;'>No video recommendations found for this user.</div>"
167
- html_output = """
168
- <div style="
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
- card_html = f"""
180
- <div style="
181
- border: 1px solid #e0e0e0;
182
- border-radius: 10px;
183
- padding: 20px;
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
- html_output += card_html
194
- html_output += "</div></div>"
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. The Focus and Insomnia packages can help improve your mental clarity and sleep quality."
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()