import gradio as gr import requests import random from sentence_transformers import SentenceTransformer from sklearn.metrics.pairwise import cosine_similarity # Load the model model = SentenceTransformer('intfloat/multilingual-e5-large') # Functions from your original code def get_user_profile(user_id): try: response = requests.get( f"https://paramedia.onrender.com/myprofile/userInfo/{user_id}") response.raise_for_status() user_data = response.json() if user_data.get("message") != "sucess": raise ValueError("Failed to fetch user data") data = user_data["data"] interests = data["interests"] tags = [tag["tag"] for post in interests.get( "posts", []) for tag in post.get("tags", [])] comments = [comment["description"] for comment in interests.get("comments", [])] liked_posts = [post["_id"] for post in interests.get("likedPosts", [])] return { "user_id": data["userId"], "interests": { "tags": tags, "comments": comments, "liked_posts": liked_posts, "followed_accounts": [] } } except Exception as e: return { "user_id": user_id, "interests": { "tags": [], "comments": [], "liked_posts": [], "followed_accounts": [] } } def fetch_posts(): try: response = requests.get( "https://paramedia.onrender.com/posts?size=200") response.raise_for_status() posts_data = response.json() seen_descriptions = set() posts = [] for post in posts_data["posts"]: if "description" in post and len(post["description"]) > 10: comments = post.get("comments", []) comments_text = " ".join( comment["description"] for comment in comments if "description" in comment) description = post["description"] combined_text = description + " " + \ comments_text if comments_text else description tag = post.get("tag", "").lower() if combined_text not in seen_descriptions: seen_descriptions.add(combined_text) posts.append((post["id"], combined_text, post.get("images", []), tag)) return posts except: return [] def recommend(user_id, new_post=""): user_profile = get_user_profile(user_id) tags = user_profile["interests"]["tags"] comments = user_profile["interests"]["comments"] weighted_interests = [] for tag in tags: weighted_interests.extend([tag] * 7) for comment in comments: weighted_interests.extend([comment] * 3) posts = fetch_posts() results = [] if not posts: return ["No posts available"] if weighted_interests: user_interest = " ".join(weighted_interests) post_texts = [text for _, text, _, _ in posts] post_embeddings = model.encode(post_texts) user_embedding = model.encode([user_interest]) similarities = cosine_similarity(user_embedding, post_embeddings) top_indices = similarities[0].argsort()[-5:][::-1] else: top_indices = random.sample(range(len(posts)), min(5, len(posts))) if new_post: results.append(f"New Post: {new_post}") for idx in top_indices: post_id, text, _, tag = posts[idx] results.append(f"ID: {post_id} | Tag: {tag} | Text: {text[:100]}...") return "\n\n".join(results) # Gradio interface demo = gr.Interface( fn=recommend, inputs=[ gr.Textbox(label="User ID"), gr.Textbox(label="New Post (optional)", lines=2), ], # outputs=gr.outputs.Textbox(label="Recommended Posts"), outputs=gr.Textbox(label="Recommended Posts"), title="Post Recommendation System" ) demo.launch()