andykr1k commited on
Commit
6e96e6d
·
1 Parent(s): 739b5c0

Fixed suggestions

Browse files
Files changed (1) hide show
  1. app.py +54 -15
app.py CHANGED
@@ -2,7 +2,6 @@ import os
2
  import random
3
  import itertools
4
  import numpy as np
5
- import pandas as pd
6
  import networkx as nx
7
  import torch
8
  import torch.nn as nn
@@ -45,20 +44,26 @@ if torch.cuda.is_available():
45
  torch.cuda.manual_seed_all(SEED)
46
 
47
  # Global variables
48
- global G, features, user_ids, pyg_data, trained_model
49
- G = features = user_ids = pyg_data = trained_model = None
 
 
 
50
 
51
  SUPABASE_URL = os.getenv('supabaseUrl')
52
  SUPABASE_KEY = os.getenv('supabaseAnonKey')
53
 
54
  def get_supabase_client():
 
55
  return create_client(SUPABASE_URL, SUPABASE_KEY)
56
 
57
  def load_and_preprocess_data():
 
58
  supabase = get_supabase_client()
59
  logger.info("Loading data from Supabase")
60
 
61
  def fetch_table(table, columns, chunk_size=1000):
 
62
  offset = 0
63
  all_data = []
64
  while True:
@@ -73,29 +78,47 @@ def load_and_preprocess_data():
73
  followers = fetch_table('followers', 'id, following')
74
  users = fetch_table('profiles', 'id')
75
 
76
- follower_dict = {f['id']: f['following'] for f in followers}
77
- user_set = {u['id'] for u in users}
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  merged = [
79
- {'follower_id': follower_dict[fid], 'followed_id': fid}
80
- for fid in follower_dict if fid in user_set and follower_dict[fid] != '' and fid != ''
 
 
81
  ]
82
  logger.info(f"Loaded {len(merged)} follower relationships")
83
  return merged
84
 
85
  def create_graph_dataframe(merged_data):
 
 
86
  G = nx.DiGraph()
87
  edges = [(d['follower_id'], d['followed_id']) for d in merged_data]
88
  G.add_edges_from(edges)
89
  user_ids = sorted(G.nodes())
90
 
91
- # Use dense identity matrix for features (sparse not supported by SAGEConv)
92
  features = torch.eye(len(user_ids))
93
  logger.info(f"Created graph with {len(user_ids)} nodes")
94
  return G, features, user_ids
95
 
96
  def prepare_training_data(G, user_ids):
 
97
  pos_edges = [(user_ids.index(u), user_ids.index(v)) for u, v in G.edges()]
98
- pos_edge_index = torch.tensor(pos_edges, dtype=torch.long).T
99
 
100
  num_nodes = len(user_ids)
101
  all_possible_edges = set(itertools.permutations(range(num_nodes), 2))
@@ -104,9 +127,10 @@ def prepare_training_data(G, user_ids):
104
  negative_edges = random.sample(list(all_possible_edges - existing_edges), neg_sample_size)
105
 
106
  logger.info(f"Prepared {len(pos_edges)} positive and {len(negative_edges)} negative edges")
107
- return pos_edge_index, torch.tensor(negative_edges, dtype=torch.long).T
108
 
109
  class GraphRecommender(nn.Module):
 
110
  def __init__(self, input_dim, hidden_dim=128, output_dim=64):
111
  super().__init__()
112
  self.conv1 = SAGEConv(input_dim, hidden_dim)
@@ -120,6 +144,7 @@ class GraphRecommender(nn.Module):
120
  return x
121
 
122
  def train_model(model, data, pos_edges, neg_edges, epochs=200, patience=20):
 
123
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
124
  model = model.to(device)
125
  data = data.to(device)
@@ -137,8 +162,8 @@ def train_model(model, data, pos_edges, neg_edges, epochs=200, patience=20):
137
 
138
  embeddings = model(data.x, data.edge_index)
139
 
140
- pos_scores = (embeddings[pos_edges[0]] * embeddings[pos_edges[1]]).sum(1)
141
- neg_scores = (embeddings[neg_edges[0]] * embeddings[neg_edges[1]]).sum(1)
142
 
143
  pos_loss = F.binary_cross_entropy_with_logits(pos_scores, torch.ones_like(pos_scores))
144
  neg_loss = F.binary_cross_entropy_with_logits(neg_scores, torch.zeros_like(neg_scores))
@@ -162,13 +187,19 @@ def train_model(model, data, pos_edges, neg_edges, epochs=200, patience=20):
162
  return model.to('cpu')
163
 
164
  def get_recommendations(user_id, model, data, G, user_ids, top_k=10):
 
165
  if user_id not in user_ids:
 
166
  return []
167
 
168
  user_idx = user_ids.index(user_id)
169
- current_follows = set(G.successors(user_id))
170
  candidate_indices = [i for i, u in enumerate(user_ids) if u != user_id and u not in current_follows]
171
 
 
 
 
 
172
  with torch.no_grad():
173
  embeddings = model(data.x, data.edge_index)
174
  user_embed = embeddings[user_idx].unsqueeze(0)
@@ -181,6 +212,7 @@ def get_recommendations(user_id, model, data, G, user_ids, top_k=10):
181
  return recommendations
182
 
183
  def rebuild_model():
 
184
  global G, features, user_ids, pyg_data, trained_model
185
  logger.info("Starting model rebuild at 3:30 AM Pacific Time")
186
  try:
@@ -199,13 +231,17 @@ def rebuild_model():
199
 
200
  @app.post("/rebuild")
201
  async def rebuild_handler():
 
202
  rebuild_model()
203
  return {"status": "success", "message": "Model and data rebuilt successfully"}
204
 
205
  @app.get("/recommend/network")
206
  async def get_recommendations_handler(user_id: str = Query(...)):
 
207
  if not trained_model:
208
  raise HTTPException(status_code=500, detail="Model not initialized, please rebuild first.")
 
 
209
 
210
  recommendations = get_recommendations(user_id, trained_model, pyg_data, G, user_ids)
211
 
@@ -221,25 +257,28 @@ async def get_recommendations_handler(user_id: str = Query(...)):
221
 
222
  @app.get("/")
223
  async def health_check():
 
224
  return {"status": "success", "message": "Recommendation service operational"}
225
 
226
  # Scheduler setup with Pacific Time Zone
227
  scheduler = BackgroundScheduler(timezone="America/Los_Angeles")
228
  scheduler.add_job(
229
  rebuild_model,
230
- trigger=CronTrigger(hour=3, minute=30), # Run at 3:30 AM Pacific Time every day
231
  id='daily_model_rebuild',
232
  replace_existing=True
233
  )
234
 
235
  @app.on_event("startup")
236
  async def startup_event():
237
- rebuild_model() # Initial build on startup
 
238
  scheduler.start()
239
  logger.info("Scheduler started, model will rebuild daily at 3:30 AM Pacific Time")
240
 
241
  @app.on_event("shutdown")
242
  async def shutdown_event():
 
243
  scheduler.shutdown()
244
  logger.info("Scheduler shut down")
245
 
 
2
  import random
3
  import itertools
4
  import numpy as np
 
5
  import networkx as nx
6
  import torch
7
  import torch.nn as nn
 
44
  torch.cuda.manual_seed_all(SEED)
45
 
46
  # Global variables
47
+ G = None
48
+ features = None
49
+ user_ids = None
50
+ pyg_data = None
51
+ trained_model = None
52
 
53
  SUPABASE_URL = os.getenv('supabaseUrl')
54
  SUPABASE_KEY = os.getenv('supabaseAnonKey')
55
 
56
  def get_supabase_client():
57
+ """Initialize and return a Supabase client."""
58
  return create_client(SUPABASE_URL, SUPABASE_KEY)
59
 
60
  def load_and_preprocess_data():
61
+ """Load and preprocess follower data from Supabase."""
62
  supabase = get_supabase_client()
63
  logger.info("Loading data from Supabase")
64
 
65
  def fetch_table(table, columns, chunk_size=1000):
66
+ """Fetch data from a Supabase table in chunks."""
67
  offset = 0
68
  all_data = []
69
  while True:
 
78
  followers = fetch_table('followers', 'id, following')
79
  users = fetch_table('profiles', 'id')
80
 
81
+ # Build follower_dict: id (followed) -> list of following (followers)
82
+ follower_dict = {}
83
+ for f in followers:
84
+ followed_id = f['id'] # The user being followed
85
+ follower_id = f['following'] # The user following the id
86
+ if not follower_id or not followed_id: # Skip invalid entries
87
+ logger.warning(f"Skipping invalid entry: follower_id={follower_id}, followed_id={followed_id}")
88
+ continue
89
+ if followed_id in follower_dict:
90
+ follower_dict[followed_id].append(follower_id)
91
+ else:
92
+ follower_dict[followed_id] = [follower_id]
93
+
94
+ user_set = set(u['id'] for u in users if u['id']) # Valid user IDs
95
+ # Create edge list: follower (following) -> followed (id)
96
  merged = [
97
+ {'follower_id': follower, 'followed_id': fid}
98
+ for fid in follower_dict
99
+ for follower in follower_dict[fid]
100
+ if fid in user_set and follower in user_set
101
  ]
102
  logger.info(f"Loaded {len(merged)} follower relationships")
103
  return merged
104
 
105
  def create_graph_dataframe(merged_data):
106
+ """Create a directed graph and feature matrix from merged data."""
107
+ global G, features, user_ids
108
  G = nx.DiGraph()
109
  edges = [(d['follower_id'], d['followed_id']) for d in merged_data]
110
  G.add_edges_from(edges)
111
  user_ids = sorted(G.nodes())
112
 
113
+ # Use identity matrix as node features
114
  features = torch.eye(len(user_ids))
115
  logger.info(f"Created graph with {len(user_ids)} nodes")
116
  return G, features, user_ids
117
 
118
  def prepare_training_data(G, user_ids):
119
+ """Prepare positive and negative edge indices for training."""
120
  pos_edges = [(user_ids.index(u), user_ids.index(v)) for u, v in G.edges()]
121
+ pos_edge_index = torch.tensor(pos_edges, dtype=torch.long).t()
122
 
123
  num_nodes = len(user_ids)
124
  all_possible_edges = set(itertools.permutations(range(num_nodes), 2))
 
127
  negative_edges = random.sample(list(all_possible_edges - existing_edges), neg_sample_size)
128
 
129
  logger.info(f"Prepared {len(pos_edges)} positive and {len(negative_edges)} negative edges")
130
+ return pos_edge_index, torch.tensor(negative_edges, dtype=torch.long).t()
131
 
132
  class GraphRecommender(nn.Module):
133
+ """GraphSAGE-based recommendation model."""
134
  def __init__(self, input_dim, hidden_dim=128, output_dim=64):
135
  super().__init__()
136
  self.conv1 = SAGEConv(input_dim, hidden_dim)
 
144
  return x
145
 
146
  def train_model(model, data, pos_edges, neg_edges, epochs=200, patience=20):
147
+ """Train the GraphRecommender model."""
148
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
149
  model = model.to(device)
150
  data = data.to(device)
 
162
 
163
  embeddings = model(data.x, data.edge_index)
164
 
165
+ pos_scores = (embeddings[pos_edges[0]] * embeddings[pos_edges[1]]).sum(dim=1)
166
+ neg_scores = (embeddings[neg_edges[0]] * embeddings[neg_edges[1]]).sum(dim=1)
167
 
168
  pos_loss = F.binary_cross_entropy_with_logits(pos_scores, torch.ones_like(pos_scores))
169
  neg_loss = F.binary_cross_entropy_with_logits(neg_scores, torch.zeros_like(neg_scores))
 
187
  return model.to('cpu')
188
 
189
  def get_recommendations(user_id, model, data, G, user_ids, top_k=10):
190
+ """Generate top-k user recommendations excluding current follows."""
191
  if user_id not in user_ids:
192
+ logger.warning(f"User {user_id} not found in graph")
193
  return []
194
 
195
  user_idx = user_ids.index(user_id)
196
+ current_follows = set(G.successors(user_id)) # Users this user follows
197
  candidate_indices = [i for i, u in enumerate(user_ids) if u != user_id and u not in current_follows]
198
 
199
+ if not candidate_indices:
200
+ logger.info(f"No new recommendations available for user {user_id}")
201
+ return []
202
+
203
  with torch.no_grad():
204
  embeddings = model(data.x, data.edge_index)
205
  user_embed = embeddings[user_idx].unsqueeze(0)
 
212
  return recommendations
213
 
214
  def rebuild_model():
215
+ """Rebuild the graph and retrain the model."""
216
  global G, features, user_ids, pyg_data, trained_model
217
  logger.info("Starting model rebuild at 3:30 AM Pacific Time")
218
  try:
 
231
 
232
  @app.post("/rebuild")
233
  async def rebuild_handler():
234
+ """API endpoint to manually trigger model rebuild."""
235
  rebuild_model()
236
  return {"status": "success", "message": "Model and data rebuilt successfully"}
237
 
238
  @app.get("/recommend/network")
239
  async def get_recommendations_handler(user_id: str = Query(...)):
240
+ """API endpoint to get recommendations for a user."""
241
  if not trained_model:
242
  raise HTTPException(status_code=500, detail="Model not initialized, please rebuild first.")
243
+ if not user_id.strip():
244
+ raise HTTPException(status_code=400, detail="Invalid user_id")
245
 
246
  recommendations = get_recommendations(user_id, trained_model, pyg_data, G, user_ids)
247
 
 
257
 
258
  @app.get("/")
259
  async def health_check():
260
+ """API endpoint for health check."""
261
  return {"status": "success", "message": "Recommendation service operational"}
262
 
263
  # Scheduler setup with Pacific Time Zone
264
  scheduler = BackgroundScheduler(timezone="America/Los_Angeles")
265
  scheduler.add_job(
266
  rebuild_model,
267
+ trigger=CronTrigger(hour=3, minute=30), # Run at 3:30 AM Pacific Time daily
268
  id='daily_model_rebuild',
269
  replace_existing=True
270
  )
271
 
272
  @app.on_event("startup")
273
  async def startup_event():
274
+ """Startup event to initialize model and scheduler."""
275
+ rebuild_model()
276
  scheduler.start()
277
  logger.info("Scheduler started, model will rebuild daily at 3:30 AM Pacific Time")
278
 
279
  @app.on_event("shutdown")
280
  async def shutdown_event():
281
+ """Shutdown event to stop scheduler."""
282
  scheduler.shutdown()
283
  logger.info("Scheduler shut down")
284