Mohamedgodz commited on
Commit
5cc92de
·
verified ·
1 Parent(s): 74421e1

Upload 3 files

Browse files
Files changed (3) hide show
  1. app_gradio.py +125 -0
  2. readme.md +3 -0
  3. requirements.txt +7 -0
app_gradio.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import random
4
+ from sentence_transformers import SentenceTransformer
5
+ from sklearn.metrics.pairwise import cosine_similarity
6
+
7
+ # Load the model
8
+ model = SentenceTransformer('intfloat/multilingual-e5-large')
9
+
10
+ # Functions from your original code
11
+
12
+
13
+ def get_user_profile(user_id):
14
+ try:
15
+ response = requests.get(
16
+ f"https://paramedia.onrender.com/myprofile/userInfo/{user_id}")
17
+ response.raise_for_status()
18
+ user_data = response.json()
19
+ if user_data.get("message") != "sucess":
20
+ raise ValueError("Failed to fetch user data")
21
+
22
+ data = user_data["data"]
23
+ interests = data["interests"]
24
+ tags = [tag["tag"] for post in interests.get(
25
+ "posts", []) for tag in post.get("tags", [])]
26
+ comments = [comment["description"]
27
+ for comment in interests.get("comments", [])]
28
+ liked_posts = [post["_id"] for post in interests.get("likedPosts", [])]
29
+
30
+ return {
31
+ "user_id": data["userId"],
32
+ "interests": {
33
+ "tags": tags,
34
+ "comments": comments,
35
+ "liked_posts": liked_posts,
36
+ "followed_accounts": []
37
+ }
38
+ }
39
+ except Exception as e:
40
+ return {
41
+ "user_id": user_id,
42
+ "interests": {
43
+ "tags": [],
44
+ "comments": [],
45
+ "liked_posts": [],
46
+ "followed_accounts": []
47
+ }
48
+ }
49
+
50
+
51
+ def fetch_posts():
52
+ try:
53
+ response = requests.get(
54
+ "https://paramedia.onrender.com/posts?size=200")
55
+ response.raise_for_status()
56
+ posts_data = response.json()
57
+ seen_descriptions = set()
58
+ posts = []
59
+ for post in posts_data["posts"]:
60
+ if "description" in post and len(post["description"]) > 10:
61
+ comments = post.get("comments", [])
62
+ comments_text = " ".join(
63
+ comment["description"] for comment in comments if "description" in comment)
64
+ description = post["description"]
65
+ combined_text = description + " " + \
66
+ comments_text if comments_text else description
67
+ tag = post.get("tag", "").lower()
68
+ if combined_text not in seen_descriptions:
69
+ seen_descriptions.add(combined_text)
70
+ posts.append((post["id"], combined_text,
71
+ post.get("images", []), tag))
72
+ return posts
73
+ except:
74
+ return []
75
+
76
+
77
+ def recommend(user_id, new_post=""):
78
+ user_profile = get_user_profile(user_id)
79
+ tags = user_profile["interests"]["tags"]
80
+ comments = user_profile["interests"]["comments"]
81
+
82
+ weighted_interests = []
83
+ for tag in tags:
84
+ weighted_interests.extend([tag] * 7)
85
+ for comment in comments:
86
+ weighted_interests.extend([comment] * 3)
87
+
88
+ posts = fetch_posts()
89
+
90
+ results = []
91
+ if not posts:
92
+ return ["No posts available"]
93
+
94
+ if weighted_interests:
95
+ user_interest = " ".join(weighted_interests)
96
+ post_texts = [text for _, text, _, _ in posts]
97
+ post_embeddings = model.encode(post_texts)
98
+ user_embedding = model.encode([user_interest])
99
+ similarities = cosine_similarity(user_embedding, post_embeddings)
100
+ top_indices = similarities[0].argsort()[-5:][::-1]
101
+ else:
102
+ top_indices = random.sample(range(len(posts)), min(5, len(posts)))
103
+
104
+ if new_post:
105
+ results.append(f"New Post: {new_post}")
106
+
107
+ for idx in top_indices:
108
+ post_id, text, _, tag = posts[idx]
109
+ results.append(f"ID: {post_id} | Tag: {tag} | Text: {text[:100]}...")
110
+
111
+ return results
112
+
113
+
114
+ # Gradio interface
115
+ demo = gr.Interface(
116
+ fn=recommend,
117
+ inputs=[
118
+ gr.Textbox(label="User ID"),
119
+ gr.Textbox(label="New Post (optional)", lines=2),
120
+ ],
121
+ outputs=gr.outputs.Textbox(label="Recommended Posts"),
122
+ title="Post Recommendation System"
123
+ )
124
+
125
+ demo.launch()
readme.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Post Recommendation System
2
+
3
+ This app recommends posts based on user interests using sentence embeddings and cosine similarity.
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ gradio
4
+ sentence-transformers
5
+ requests
6
+ pydantic
7
+ scikit-learn