Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import pandas as pd | |
| import numpy as np | |
| from sklearn.metrics.pairwise import cosine_similarity | |
| from sentence_transformers import SentenceTransformer | |
| # β Load the model | |
| model = SentenceTransformer("all-MiniLM-L6-v2") | |
| # β Load posts dataset | |
| posts_df = pd.read_csv("posts_cleaned.csv") | |
| post_texts = posts_df["post_text"].astype(str).tolist() | |
| # β Cache embeddings | |
| post_embeddings = None | |
| def get_embeddings(): | |
| global post_embeddings | |
| if post_embeddings is None: | |
| print("Computing embeddings...") | |
| post_embeddings = model.encode(post_texts, convert_to_tensor=False) | |
| return post_embeddings | |
| # β Main recommender logic with JSON output | |
| def recommend_json(user_text): | |
| if not user_text.strip(): | |
| return { "data": [[]] } | |
| embeddings = get_embeddings() | |
| user_vec = model.encode([user_text]) | |
| sims = cosine_similarity(user_vec, embeddings)[0] | |
| top_idxs = sims.argsort()[-5:][::-1] | |
| recommendations = posts_df.iloc[top_idxs]["post_text"].tolist() | |
| return { "data": [recommendations] } | |
| # β Gradio JSON interface | |
| interface = gr.Interface( | |
| fn=recommend_json, | |
| inputs=gr.Textbox(label="What are you interested in?"), | |
| outputs=gr.JSON(label="Structured Recommendations"), | |
| title="π AI Content Recommender (API Mode)" | |
| ) | |
| interface.launch() | |