PraneshJs commited on
Commit
4da2489
Β·
verified Β·
1 Parent(s): 74935ca

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +569 -0
app.py ADDED
@@ -0,0 +1,569 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import plotly.graph_objects as go
4
+ import plotly.express as px
5
+ import pandas as pd
6
+ import math
7
+ import random
8
+ from datetime import datetime, timedelta
9
+ import json
10
+
11
+ # ---------------------------
12
+ # GLOBAL DATA (SIMULATION)
13
+ # ---------------------------
14
+
15
+ TOPICS = ["AI/Tech", "Music", "Travel", "Food", "Gaming", "Fitness", "Fashion", "Art", "Business", "Comedy"]
16
+
17
+ # More complex global trends with temporal variations
18
+ GLOBAL_TRENDING = {
19
+ "AI/Tech": {"base": 0.95, "volatility": 0.1, "seasonal": 1.2},
20
+ "Music": {"base": 0.90, "volatility": 0.15, "seasonal": 1.1},
21
+ "Travel": {"base": 0.88, "volatility": 0.2, "seasonal": 0.8},
22
+ "Food": {"base": 0.85, "volatility": 0.05, "seasonal": 1.0},
23
+ "Gaming": {"base": 0.82, "volatility": 0.12, "seasonal": 1.0},
24
+ "Fitness": {"base": 0.80, "volatility": 0.08, "seasonal": 1.3},
25
+ "Fashion": {"base": 0.87, "volatility": 0.18, "seasonal": 1.1},
26
+ "Art": {"base": 0.75, "volatility": 0.10, "seasonal": 0.9},
27
+ "Business": {"base": 0.78, "volatility": 0.07, "seasonal": 0.95},
28
+ "Comedy": {"base": 0.92, "volatility": 0.20, "seasonal": 1.0}
29
+ }
30
+
31
+ # Content creator tiers
32
+ CREATOR_TIERS = {
33
+ "Micro": {"followers": 1000, "engagement_mult": 1.2, "reach_mult": 0.8},
34
+ "Mid": {"followers": 50000, "engagement_mult": 1.0, "reach_mult": 1.0},
35
+ "Macro": {"followers": 500000, "engagement_mult": 0.8, "reach_mult": 1.5},
36
+ "Celebrity": {"followers": 5000000, "engagement_mult": 0.6, "reach_mult": 2.0}
37
+ }
38
+
39
+ # User demographics
40
+ DEMOGRAPHICS = ["Gen Z", "Millennial", "Gen X", "Boomer"]
41
+ REGIONS = ["North America", "Europe", "Asia", "South America", "Africa"]
42
+
43
+ np.random.seed(42)
44
+
45
+ # More complex embedding space (higher dimensional)
46
+ EMBEDDING_DIM = 8
47
+ POST_EMBEDDINGS = {}
48
+ USER_DEMOGRAPHICS = {}
49
+
50
+ for topic in TOPICS:
51
+ base_trend = GLOBAL_TRENDING[topic]["base"]
52
+ volatility = GLOBAL_TRENDING[topic]["volatility"]
53
+ embedding = np.random.randn(EMBEDDING_DIM) * base_trend + np.random.randn(EMBEDDING_DIM) * volatility
54
+ POST_EMBEDDINGS[topic] = embedding
55
+
56
+ GLOBAL_EMBEDDING = np.mean(list(POST_EMBEDDINGS.values()), axis=0)
57
+
58
+ # ---------------------------
59
+ # ENHANCED UTILS
60
+ # ---------------------------
61
+
62
+ def sigmoid(x, steepness=1.0):
63
+ return 1 / (1 + math.exp(-steepness * x))
64
+
65
+ def attention_mechanism(query, keys, values, temperature=1.0):
66
+ """Simplified attention mechanism for content ranking"""
67
+ scores = np.dot(keys, query) / temperature
68
+ weights = np.exp(scores) / np.sum(np.exp(scores))
69
+ return np.dot(weights, values), weights
70
+
71
+ def temporal_decay(time_diff_hours, half_life=24):
72
+ """Content freshness decay"""
73
+ return 0.5 ** (time_diff_hours / half_life)
74
+
75
+ def diversity_penalty(selected_topics, candidate_topic, penalty_strength=0.1):
76
+ """Penalty for showing too much of the same content"""
77
+ count = selected_topics.count(candidate_topic)
78
+ return math.exp(-penalty_strength * count)
79
+
80
+ # ---------------------------
81
+ # ENHANCED VALUE MODEL
82
+ # ---------------------------
83
+
84
+ def enhanced_value_model(like_signal, comment_signal, share_signal, save_signal,
85
+ watch_time, creator_tier, recency_hours, user_history_match):
86
+ """More sophisticated value model with multiple signals"""
87
+
88
+ # Base probabilities
89
+ p_like = sigmoid(like_signal - 1, steepness=0.8)
90
+ p_comment = sigmoid(comment_signal - 0.5, steepness=1.2)
91
+ p_share = sigmoid(share_signal - 0.3, steepness=1.5)
92
+ p_save = sigmoid(save_signal - 0.2, steepness=1.0)
93
+ p_watch = sigmoid(watch_time - 2, steepness=0.6)
94
+
95
+ # Creator influence
96
+ creator_mult = CREATOR_TIERS[creator_tier]["engagement_mult"]
97
+
98
+ # Recency factor
99
+ recency_factor = temporal_decay(recency_hours)
100
+
101
+ # User history matching
102
+ history_boost = sigmoid(user_history_match - 0.5, steepness=2.0)
103
+
104
+ # Weighted scoring
105
+ base_score = (
106
+ 1.0 * p_like +
107
+ 3.0 * p_comment +
108
+ 4.0 * p_share +
109
+ 2.5 * p_save +
110
+ 1.5 * p_watch
111
+ )
112
+
113
+ # Apply modifiers
114
+ final_score = base_score * creator_mult * recency_factor * (0.5 + 0.5 * history_boost)
115
+
116
+ return round(final_score, 4), {
117
+ "P(Like)": round(p_like, 3),
118
+ "P(Comment)": round(p_comment, 3),
119
+ "P(Share)": round(p_share, 3),
120
+ "P(Save)": round(p_save, 3),
121
+ "P(Watch)": round(p_watch, 3),
122
+ "Creator Multiplier": round(creator_mult, 3),
123
+ "Recency Factor": round(recency_factor, 3),
124
+ "History Match": round(history_boost, 3)
125
+ }
126
+
127
+ # ---------------------------
128
+ # ENHANCED COLD START WITH EXPLORATION
129
+ # ---------------------------
130
+
131
+ def enhanced_cold_start(interactions, preferred_topics, demographics, region,
132
+ exploration_factor=0.2):
133
+ """Enhanced cold start with demographic targeting and exploration"""
134
+
135
+ # Blending factor based on interactions
136
+ alpha = min(interactions / 50.0, 0.9) # More gradual transition
137
+
138
+ # Create personal embedding from multiple preferences
139
+ if len(preferred_topics) > 0:
140
+ personal_embeddings = [POST_EMBEDDINGS[topic] for topic in preferred_topics]
141
+ personal_embedding = np.mean(personal_embeddings, axis=0)
142
+ else:
143
+ personal_embedding = GLOBAL_EMBEDDING
144
+
145
+ # Demographic influence
146
+ demo_noise = np.random.randn(EMBEDDING_DIM) * 0.1
147
+ if demographics == "Gen Z":
148
+ demo_noise += np.array([0.2, -0.1, 0.3, 0.1, 0.2, -0.1, 0.1, 0.2])
149
+ elif demographics == "Millennial":
150
+ demo_noise += np.array([0.1, 0.2, 0.1, 0.2, 0.1, 0.2, 0.1, 0.0])
151
+
152
+ # Regional trends
153
+ regional_bias = np.zeros(EMBEDDING_DIM)
154
+ if region == "Asia":
155
+ regional_bias += np.array([0.3, 0.1, -0.2, 0.2, 0.1, 0.0, 0.1, 0.1])
156
+ elif region == "North America":
157
+ regional_bias += np.array([0.1, 0.2, 0.1, 0.1, 0.3, 0.1, 0.2, 0.1])
158
+
159
+ # Exploration component (random discovery)
160
+ exploration_noise = np.random.randn(EMBEDDING_DIM) * exploration_factor
161
+
162
+ # Final blended embedding
163
+ user_embedding = (
164
+ alpha * personal_embedding +
165
+ (1 - alpha) * GLOBAL_EMBEDDING +
166
+ demo_noise +
167
+ regional_bias +
168
+ exploration_noise
169
+ )
170
+
171
+ return user_embedding
172
+
173
+ # ---------------------------
174
+ # CONTENT RANKING SYSTEM
175
+ # ---------------------------
176
+
177
+ def rank_content_feed(user_embedding, content_pool_size=20, diversity_weight=0.3):
178
+ """Simulate full feed ranking with diversity considerations"""
179
+
180
+ # Generate synthetic content
181
+ content_items = []
182
+ for i in range(content_pool_size):
183
+ topic = random.choice(TOPICS)
184
+ creator_tier = random.choices(
185
+ list(CREATOR_TIERS.keys()),
186
+ weights=[40, 35, 20, 5]
187
+ )[0]
188
+
189
+ # Content embedding with some noise
190
+ content_emb = POST_EMBEDDINGS[topic] + np.random.randn(EMBEDDING_DIM) * 0.1
191
+
192
+ # Relevance score (cosine similarity)
193
+ relevance = np.dot(user_embedding, content_emb) / (
194
+ np.linalg.norm(user_embedding) * np.linalg.norm(content_emb)
195
+ )
196
+
197
+ # Random engagement signals
198
+ engagement_signals = {
199
+ "likes": max(0, np.random.normal(5, 2)),
200
+ "comments": max(0, np.random.normal(2, 1)),
201
+ "shares": max(0, np.random.normal(1, 0.5)),
202
+ "saves": max(0, np.random.normal(0.8, 0.3)),
203
+ "watch_time": max(0, np.random.normal(4, 1.5)),
204
+ "recency": np.random.uniform(0.1, 48)
205
+ }
206
+
207
+ # Calculate value score
208
+ value_score, _ = enhanced_value_model(
209
+ engagement_signals["likes"],
210
+ engagement_signals["comments"],
211
+ engagement_signals["shares"],
212
+ engagement_signals["saves"],
213
+ engagement_signals["watch_time"],
214
+ creator_tier,
215
+ engagement_signals["recency"],
216
+ max(0, relevance)
217
+ )
218
+
219
+ content_items.append({
220
+ "id": i,
221
+ "topic": topic,
222
+ "creator_tier": creator_tier,
223
+ "relevance": relevance,
224
+ "value_score": value_score,
225
+ "embedding": content_emb,
226
+ **engagement_signals
227
+ })
228
+
229
+ # Rank with diversity
230
+ ranked_items = []
231
+ remaining_items = content_items.copy()
232
+ selected_topics = []
233
+
234
+ for position in range(min(10, len(remaining_items))):
235
+ best_item = None
236
+ best_score = -float('inf')
237
+
238
+ for item in remaining_items:
239
+ # Combined score: relevance + diversity
240
+ diversity_score = diversity_penalty(selected_topics, item["topic"])
241
+ combined_score = (
242
+ (1 - diversity_weight) * item["value_score"] +
243
+ diversity_weight * diversity_score
244
+ )
245
+
246
+ if combined_score > best_score:
247
+ best_score = combined_score
248
+ best_item = item
249
+
250
+ if best_item:
251
+ ranked_items.append(best_item)
252
+ selected_topics.append(best_item["topic"])
253
+ remaining_items.remove(best_item)
254
+
255
+ return ranked_items
256
+
257
+ # ---------------------------
258
+ # ENHANCED UI FUNCTIONS
259
+ # ---------------------------
260
+
261
+ def tab_enhanced_value_model(likes, comments, shares, saves, watch_time, creator_tier, recency, history_match):
262
+ score, metrics = enhanced_value_model(
263
+ likes, comments, shares, saves, watch_time, creator_tier, recency, history_match
264
+ )
265
+
266
+ # Create metrics visualization
267
+ fig = go.Figure()
268
+
269
+ metric_names = list(metrics.keys())[:5] # First 5 are probabilities
270
+ metric_values = [metrics[name] for name in metric_names]
271
+
272
+ fig.add_trace(go.Bar(
273
+ x=metric_names,
274
+ y=metric_values,
275
+ marker_color=['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FECA57']
276
+ ))
277
+
278
+ fig.update_layout(
279
+ title="Signal Probabilities",
280
+ yaxis_title="Probability",
281
+ height=400
282
+ )
283
+
284
+ text = f"""
285
+ ### πŸ”’ Enhanced Value Model Output
286
+
287
+ **Final Ranking Score: {score}**
288
+
289
+ #### πŸ“Š Signal Probabilities:
290
+ - πŸ‘ Like: **{metrics['P(Like)']}**
291
+ - πŸ’¬ Comment: **{metrics['P(Comment)']}**
292
+ - πŸ”„ Share: **{metrics['P(Share)']}**
293
+ - πŸ“Œ Save: **{metrics['P(Save)']}**
294
+ - πŸ‘€ Watch: **{metrics['P(Watch)']}**
295
+
296
+ #### 🎯 Modifiers:
297
+ - Creator Influence: **{metrics['Creator Multiplier']}**
298
+ - Content Freshness: **{metrics['Recency Factor']}**
299
+ - User History Match: **{metrics['History Match']}**
300
+ """
301
+
302
+ return text, fig
303
+
304
+ def tab_enhanced_cold_start(interactions, topics, demographics, region, exploration):
305
+ user_vec = enhanced_cold_start(interactions, topics, demographics, region, exploration)
306
+
307
+ # Calculate distances to different content types
308
+ distances = {}
309
+ for topic, embedding in POST_EMBEDDINGS.items():
310
+ distance = np.linalg.norm(user_vec - embedding)
311
+ distances[topic] = distance
312
+
313
+ # Sort by proximity
314
+ sorted_topics = sorted(distances.items(), key=lambda x: x[1])
315
+
316
+ explanation = f"""
317
+ ### 🧊 Enhanced Cold Start Analysis
318
+
319
+ **User Profile:**
320
+ - Interactions: **{interactions}**
321
+ - Demographics: **{demographics}** in **{region}**
322
+ - Exploration Factor: **{exploration}**
323
+ - Preferred Topics: **{', '.join(topics) if topics else 'None selected'}**
324
+
325
+ #### 🎯 Content Affinity (Closest β†’ Farthest):
326
+ """
327
+
328
+ for i, (topic, dist) in enumerate(sorted_topics[:5]):
329
+ explanation += f"{i+1}. **{topic}** (distance: {dist:.3f})\n"
330
+
331
+ return explanation, user_vec
332
+
333
+ def tab_feed_ranking(user_vec):
334
+ if user_vec is None:
335
+ return "Please generate a user profile first in the Cold Start tab.", None
336
+
337
+ ranked_content = rank_content_feed(user_vec)
338
+
339
+ # Create feed visualization
340
+ df_feed = pd.DataFrame([
341
+ {
342
+ "Position": i+1,
343
+ "Topic": item["topic"],
344
+ "Creator": item["creator_tier"],
345
+ "Relevance": round(item["relevance"], 3),
346
+ "Value Score": round(item["value_score"], 3),
347
+ "Likes": round(item["likes"], 1),
348
+ "Comments": round(item["comments"], 1),
349
+ "Shares": round(item["shares"], 1)
350
+ }
351
+ for i, item in enumerate(ranked_content)
352
+ ])
353
+
354
+ # Create ranking visualization
355
+ fig = px.scatter(
356
+ df_feed,
357
+ x="Relevance",
358
+ y="Value Score",
359
+ size="Likes",
360
+ color="Topic",
361
+ hover_data=["Creator", "Comments", "Shares"],
362
+ title="Content Ranking: Relevance vs Value Score"
363
+ )
364
+
365
+ return df_feed, fig
366
+
367
+ def tab_advanced_analytics(user_vec):
368
+ if user_vec is None:
369
+ return None, None, "Generate user profile first"
370
+
371
+ # Topic affinity radar chart
372
+ topic_scores = []
373
+ for topic, embedding in POST_EMBEDDINGS.items():
374
+ similarity = np.dot(user_vec, embedding) / (
375
+ np.linalg.norm(user_vec) * np.linalg.norm(embedding)
376
+ )
377
+ topic_scores.append(similarity)
378
+
379
+ fig_radar = go.Figure()
380
+
381
+ fig_radar.add_trace(go.Scatterpolar(
382
+ r=topic_scores,
383
+ theta=TOPICS,
384
+ fill='toself',
385
+ name='User Affinity'
386
+ ))
387
+
388
+ fig_radar.update_layout(
389
+ polar=dict(
390
+ radialaxis=dict(
391
+ visible=True,
392
+ range=[-1, 1]
393
+ )),
394
+ showlegend=True,
395
+ title="User Topic Affinity Profile"
396
+ )
397
+
398
+ # Embedding visualization (PCA to 2D)
399
+ all_embeddings = list(POST_EMBEDDINGS.values()) + [user_vec]
400
+ all_labels = TOPICS + ["User"]
401
+
402
+ # Simple 2D projection (first two dimensions)
403
+ x_coords = [emb[0] for emb in all_embeddings]
404
+ y_coords = [emb[1] for emb in all_embeddings]
405
+
406
+ fig_embed = go.Figure()
407
+
408
+ # Plot topics
409
+ for i, (x, y, label) in enumerate(zip(x_coords[:-1], y_coords[:-1], all_labels[:-1])):
410
+ fig_embed.add_trace(go.Scatter(
411
+ x=[x], y=[y],
412
+ mode='markers+text',
413
+ text=[label],
414
+ textposition="top center",
415
+ marker=dict(size=10),
416
+ name=label
417
+ ))
418
+
419
+ # Plot user
420
+ fig_embed.add_trace(go.Scatter(
421
+ x=[x_coords[-1]], y=[y_coords[-1]],
422
+ mode='markers+text',
423
+ text=["You"],
424
+ textposition="top center",
425
+ marker=dict(size=15, color='red'),
426
+ name="User"
427
+ ))
428
+
429
+ fig_embed.update_layout(
430
+ title="2D Embedding Space Projection",
431
+ xaxis_title="Dimension 1",
432
+ yaxis_title="Dimension 2"
433
+ )
434
+
435
+ # Statistics
436
+ stats = f"""
437
+ ### πŸ“ˆ Advanced Analytics
438
+
439
+ **User Vector Statistics:**
440
+ - Vector Magnitude: {np.linalg.norm(user_vec):.3f}
441
+ - Dominant Dimensions: {np.argmax(np.abs(user_vec))}, {np.argsort(np.abs(user_vec))[-2]}
442
+ - Diversity Score: {np.std(topic_scores):.3f}
443
+ - Global Alignment: {np.dot(user_vec, GLOBAL_EMBEDDING) / (np.linalg.norm(user_vec) * np.linalg.norm(GLOBAL_EMBEDDING)):.3f}
444
+ """
445
+
446
+ return fig_radar, fig_embed, stats
447
+
448
+ # ---------------------------
449
+ # ENHANCED GRADIO UI
450
+ # ---------------------------
451
+
452
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
453
+ gr.Markdown("# πŸ“Έ Advanced Instagram Recommendation Algorithm Simulator")
454
+ gr.Markdown("### Explore the complex mechanics behind social media content ranking")
455
+
456
+ with gr.Tabs():
457
+
458
+ # ---------------- TAB A: Enhanced Value Model ----------------
459
+ with gr.Tab("πŸ”’ Value Model"):
460
+ gr.Markdown("### Multi-Signal Content Scoring System")
461
+
462
+ with gr.Row():
463
+ with gr.Column():
464
+ likes = gr.Slider(0, 20, 5, label="πŸ‘ Likes Signal")
465
+ comments = gr.Slider(0, 10, 2, label="πŸ’¬ Comments Signal")
466
+ shares = gr.Slider(0, 5, 1, label="πŸ”„ Shares Signal")
467
+ saves = gr.Slider(0, 3, 0.5, label="πŸ“Œ Saves Signal")
468
+
469
+ with gr.Column():
470
+ watch_time = gr.Slider(0, 15, 5, label="πŸ‘€ Watch Time (seconds)")
471
+ creator_tier = gr.Dropdown(list(CREATOR_TIERS.keys()), value="Mid", label="πŸ‘€ Creator Tier")
472
+ recency = gr.Slider(0.1, 48, 2, label="⏰ Hours Since Posted")
473
+ history_match = gr.Slider(0, 1, 0.5, label="🎯 User History Match")
474
+
475
+ value_output = gr.Markdown()
476
+ value_chart = gr.Plot()
477
+
478
+ gr.Button("πŸš€ Calculate Ranking Score", variant="primary").click(
479
+ tab_enhanced_value_model,
480
+ inputs=[likes, comments, shares, saves, watch_time, creator_tier, recency, history_match],
481
+ outputs=[value_output, value_chart]
482
+ )
483
+
484
+ # ---------------- TAB B: Enhanced Cold Start ----------------
485
+ with gr.Tab("🧊 Cold Start & Personalization"):
486
+ gr.Markdown("### From Generic β†’ Personalized Content")
487
+
488
+ with gr.Row():
489
+ with gr.Column():
490
+ interactions = gr.Slider(0, 100, 0, label="πŸ“± Total User Interactions")
491
+ topics = gr.CheckboxGroup(TOPICS, label="❀️ Preferred Topics")
492
+
493
+ with gr.Column():
494
+ demographics = gr.Dropdown(DEMOGRAPHICS, value="Gen Z", label="πŸ‘₯ Demographics")
495
+ region = gr.Dropdown(REGIONS, value="North America", label="🌍 Region")
496
+ exploration = gr.Slider(0, 0.5, 0.2, label="🎲 Exploration Factor")
497
+
498
+ cold_start_output = gr.Markdown()
499
+ user_vec_state = gr.State()
500
+
501
+ gr.Button("🎭 Generate User Profile", variant="primary").click(
502
+ tab_enhanced_cold_start,
503
+ inputs=[interactions, topics, demographics, region, exploration],
504
+ outputs=[cold_start_output, user_vec_state]
505
+ )
506
+
507
+ # ---------------- TAB C: Feed Ranking ----------------
508
+ with gr.Tab("πŸ“± Feed Ranking Simulation"):
509
+ gr.Markdown("### See Your Personalized Feed in Action")
510
+
511
+ feed_table = gr.Dataframe()
512
+ feed_chart = gr.Plot()
513
+
514
+ gr.Button("πŸ”„ Generate My Feed", variant="primary").click(
515
+ tab_feed_ranking,
516
+ inputs=[user_vec_state],
517
+ outputs=[feed_table, feed_chart]
518
+ )
519
+
520
+ # ---------------- TAB D: Advanced Analytics ----------------
521
+ with gr.Tab("πŸ“Š Advanced Analytics"):
522
+ gr.Markdown("### Deep Dive into Algorithm Mechanics")
523
+
524
+ analytics_stats = gr.Markdown()
525
+
526
+ with gr.Row():
527
+ radar_chart = gr.Plot()
528
+ embedding_chart = gr.Plot()
529
+
530
+ gr.Button("πŸ”¬ Analyze User Profile", variant="primary").click(
531
+ tab_advanced_analytics,
532
+ inputs=[user_vec_state],
533
+ outputs=[radar_chart, embedding_chart, analytics_stats]
534
+ )
535
+
536
+ # ---------------- Information Panel ----------------
537
+ with gr.Accordion("πŸ“š Algorithm Insights", open=False):
538
+ gr.Markdown("""
539
+ ### How This Simulation Works:
540
+
541
+ 1. **Value Model**: Converts user engagement signals into probability scores using sigmoid functions
542
+ 2. **Cold Start**: Blends global trends with personal preferences based on interaction history
543
+ 3. **Embeddings**: Represents users and content in high-dimensional vector space
544
+ 4. **Ranking**: Combines relevance scores with diversity penalties for balanced feeds
545
+ 5. **Personalization**: Gradually shifts from trending to personalized content
546
+
547
+ ### Key Concepts:
548
+ - **Attention Mechanism**: Weighted content selection based on user interests
549
+ - **Temporal Decay**: Newer content gets priority boost
550
+ - **Diversity Penalty**: Prevents echo chambers by promoting content variety
551
+ - **Demographic Targeting**: Adjusts recommendations based on user demographics
552
+ - **Exploration vs Exploitation**: Balance between showing familiar and new content
553
+ """)
554
+
555
+ with gr.Accordion("βš™οΈ Technical Implementation", open=False):
556
+ gr.Markdown("""
557
+ ### Advanced Features:
558
+
559
+ - **8-Dimensional Embedding Space** for richer content representation
560
+ - **Multi-Signal Value Model** with 5 engagement types
561
+ - **Demographic & Regional Biases** in recommendation
562
+ - **Dynamic Exploration Factor** for content discovery
563
+ - **Attention-Based Ranking** with diversity constraints
564
+ - **Temporal Content Decay** for freshness prioritization
565
+ - **Creator Tier Influence** on engagement predictions
566
+ """)
567
+
568
+ if __name__ == "__main__":
569
+ demo.launch(debug=True)