Follows, friends and connection suggestions for DBBasic apps: a social graph module with an admin interface.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-follows.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-follows.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-follows.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Initial commit: dbbasic-follows social graph module 85ad7cd 1 year ago History
follows.py · 11.1 KB · 361 lines
1"""Core API for dbbasic-follows - Social Graph Management"""
2
3from pathlib import Path
4from dbbasic_tsv import TSV
5from datetime import datetime
6from typing import Optional, List, Dict, Set
7
8
9class Follows:
10 """
11 Main API class for managing social graph relationships (follows & friends).
12
13 A follow is a one-directional relationship: user A follows user B.
14 A friend relationship exists when both users follow each other.
15
16 Example usage:
17 follows = Follows()
18
19 # Follow operations
20 follows.follow(user_id=1, followee_id=2)
21 follows.unfollow(user_id=1, followee_id=2)
22
23 # Check relationships
24 is_following = follows.is_following(1, 2)
25 are_friends = follows.are_friends(1, 2)
26
27 # Get lists
28 followers = follows.get_followers(user_id=2)
29 following = follows.get_following(user_id=1)
30 friends = follows.get_friends(user_id=1)
31
32 # Suggestions
33 suggestions = follows.suggest_follows(user_id=1, limit=10)
34 friend_suggestions = follows.suggest_friends(user_id=1, limit=10)
35 """
36
37 def __init__(self, data_dir: str = "data"):
38 """
39 Initialize Follows API.
40
41 Args:
42 data_dir: Directory for data storage (default: "data" in current directory)
43 """
44 self.data_dir = Path(data_dir)
45 self.data_dir.mkdir(parents=True, exist_ok=True)
46
47 # Initialize TSV table for follows
48 self.table = TSV(self.data_dir / "follows.tsv")
49
50 # Create indexes for fast lookups
51 self.table.create_index('follower_id')
52 self.table.create_index('followee_id')
53
54 def follow(self, follower_id: int, followee_id: int) -> bool:
55 """
56 Create a follow relationship.
57
58 Args:
59 follower_id: ID of the user who is following
60 followee_id: ID of the user being followed
61
62 Returns:
63 bool: True if created, False if already exists or invalid
64
65 Example:
66 follows.follow(follower_id=1, followee_id=2)
67 """
68 # Validate: can't follow yourself
69 if follower_id == followee_id:
70 raise ValueError("Cannot follow yourself")
71
72 # Check if already following
73 if self.is_following(follower_id, followee_id):
74 return False
75
76 # Create follow relationship
77 self.table.insert({
78 'follower_id': follower_id,
79 'followee_id': followee_id,
80 'created_at': datetime.now().isoformat(),
81 'status': 'active'
82 })
83
84 return True
85
86 def unfollow(self, follower_id: int, followee_id: int) -> bool:
87 """
88 Remove a follow relationship.
89
90 Args:
91 follower_id: ID of the user who is unfollowing
92 followee_id: ID of the user being unfollowed
93
94 Returns:
95 bool: True if deleted, False if didn't exist
96
97 Example:
98 follows.unfollow(follower_id=1, followee_id=2)
99 """
100 # Check if exists
101 if not self.is_following(follower_id, followee_id):
102 return False
103
104 # Delete the relationship
105 self.table.delete(where={
106 'follower_id': follower_id,
107 'followee_id': followee_id
108 })
109
110 return True
111
112 def is_following(self, follower_id: int, followee_id: int) -> bool:
113 """
114 Check if user A follows user B.
115
116 Args:
117 follower_id: ID of potential follower
118 followee_id: ID of potential followee
119
120 Returns:
121 bool: True if following relationship exists
122
123 Example:
124 if follows.is_following(1, 2):
125 print("User 1 follows user 2")
126 """
127 results = self.table.select(where={
128 'follower_id': follower_id,
129 'followee_id': followee_id,
130 'status': 'active'
131 })
132 return len(results) > 0
133
134 def are_friends(self, user_id_a: int, user_id_b: int) -> bool:
135 """
136 Check if two users are friends (mutual follow).
137
138 Args:
139 user_id_a: First user ID
140 user_id_b: Second user ID
141
142 Returns:
143 bool: True if both users follow each other
144
145 Example:
146 if follows.are_friends(1, 2):
147 print("Users are friends")
148 """
149 return (self.is_following(user_id_a, user_id_b) and
150 self.is_following(user_id_b, user_id_a))
151
152 def get_followers(self, user_id: int, limit: Optional[int] = None) -> List[Dict]:
153 """
154 Get list of users who follow the specified user.
155
156 Args:
157 user_id: ID of the user
158 limit: Maximum number of results (None = all)
159
160 Returns:
161 list: List of follower records
162
163 Example:
164 followers = follows.get_followers(user_id=2, limit=50)
165 """
166 results = self.table.select(where={
167 'followee_id': user_id,
168 'status': 'active'
169 })
170
171 if limit:
172 results = results[:limit]
173
174 return results
175
176 def get_following(self, user_id: int, limit: Optional[int] = None) -> List[Dict]:
177 """
178 Get list of users that the specified user follows.
179
180 Args:
181 user_id: ID of the user
182 limit: Maximum number of results (None = all)
183
184 Returns:
185 list: List of following records
186
187 Example:
188 following = follows.get_following(user_id=1, limit=50)
189 """
190 results = self.table.select(where={
191 'follower_id': user_id,
192 'status': 'active'
193 })
194
195 if limit:
196 results = results[:limit]
197
198 return results
199
200 def get_friends(self, user_id: int, limit: Optional[int] = None) -> List[int]:
201 """
202 Get list of friends (mutual follows) for a user.
203
204 Args:
205 user_id: ID of the user
206 limit: Maximum number of results (None = all)
207
208 Returns:
209 list: List of friend user IDs
210
211 Example:
212 friends = follows.get_friends(user_id=1)
213 """
214 # Get users this person follows
215 following = self.get_following(user_id)
216 following_ids = {row['followee_id'] for row in following}
217
218 # Get users who follow this person
219 followers = self.get_followers(user_id)
220 follower_ids = {row['follower_id'] for row in followers}
221
222 # Friends are the intersection (mutual follows)
223 friend_ids = list(following_ids & follower_ids)
224
225 if limit:
226 friend_ids = friend_ids[:limit]
227
228 return friend_ids
229
230 def get_follower_count(self, user_id: int) -> int:
231 """Get count of followers for a user."""
232 return len(self.get_followers(user_id))
233
234 def get_following_count(self, user_id: int) -> int:
235 """Get count of users being followed."""
236 return len(self.get_following(user_id))
237
238 def get_friend_count(self, user_id: int) -> int:
239 """Get count of friends (mutual follows)."""
240 return len(self.get_friends(user_id))
241
242 def suggest_follows(self, user_id: int, limit: int = 10) -> List[Dict]:
243 """
244 Suggest users to follow based on social graph.
245
246 Algorithm:
247 1. Find users followed by people you follow (2nd degree connections)
248 2. Rank by number of mutual connections
249 3. Exclude users already followed
250 4. Exclude self
251
252 Args:
253 user_id: ID of the user to generate suggestions for
254 limit: Maximum number of suggestions
255
256 Returns:
257 list: Suggested users with scores
258
259 Example:
260 suggestions = follows.suggest_follows(user_id=1, limit=10)
261 # [{'user_id': 5, 'score': 3, 'mutual_connections': [2, 3, 4]}, ...]
262 """
263 # Get users this person follows
264 following = self.get_following(user_id)
265 following_ids = {row['followee_id'] for row in following}
266
267 # Track potential suggestions and their scores
268 suggestions: Dict[int, Set[int]] = {} # user_id -> set of mutual connections
269
270 # For each person we follow, get who they follow
271 for follow_record in following:
272 followee_id = follow_record['followee_id']
273 second_degree = self.get_following(followee_id)
274
275 for second_follow in second_degree:
276 candidate_id = second_follow['followee_id']
277
278 # Skip if it's the user themselves or already following
279 if candidate_id == user_id or candidate_id in following_ids:
280 continue
281
282 # Track the mutual connection
283 if candidate_id not in suggestions:
284 suggestions[candidate_id] = set()
285 suggestions[candidate_id].add(followee_id)
286
287 # Convert to list with scores
288 suggestion_list = [
289 {
290 'user_id': uid,
291 'score': len(mutual),
292 'mutual_connections': list(mutual)
293 }
294 for uid, mutual in suggestions.items()
295 ]
296
297 # Sort by score (descending)
298 suggestion_list.sort(key=lambda x: x['score'], reverse=True)
299
300 return suggestion_list[:limit]
301
302 def suggest_friends(self, user_id: int, limit: int = 10) -> List[Dict]:
303 """
304 Suggest potential friends (users who follow you but you don't follow back).
305
306 Args:
307 user_id: ID of the user to generate suggestions for
308 limit: Maximum number of suggestions
309
310 Returns:
311 list: Suggested users to follow back
312
313 Example:
314 suggestions = follows.suggest_friends(user_id=1, limit=10)
315 """
316 # Get followers
317 followers = self.get_followers(user_id)
318 follower_ids = {row['follower_id'] for row in followers}
319
320 # Get following
321 following = self.get_following(user_id)
322 following_ids = {row['followee_id'] for row in following}
323
324 # Potential friends are followers we don't follow back
325 potential_friends = follower_ids - following_ids
326
327 # Get mutual connection counts for ranking
328 suggestions = []
329 for potential_friend_id in potential_friends:
330 # Count mutual connections (people both users follow)
331 their_following = self.get_following(potential_friend_id)
332 their_following_ids = {row['followee_id'] for row in their_following}
333 mutual_count = len(following_ids & their_following_ids)
334
335 suggestions.append({
336 'user_id': potential_friend_id,
337 'score': mutual_count,
338 'follows_you': True
339 })
340
341 # Sort by mutual connections
342 suggestions.sort(key=lambda x: x['score'], reverse=True)
343
344 return suggestions[:limit]
345
346 def get_stats(self, user_id: int) -> Dict:
347 """
348 Get social graph statistics for a user.
349
350 Returns:
351 dict: Stats including follower/following/friend counts
352
353 Example:
354 stats = follows.get_stats(user_id=1)
355 # {'followers': 100, 'following': 50, 'friends': 30}
356 """
357 return {
358 'followers': self.get_follower_count(user_id),
359 'following': self.get_following_count(user_id),
360 'friends': self.get_friend_count(user_id)
361 }