Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,14 +4,14 @@ import numpy as np
|
|
| 4 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 5 |
from sentence_transformers import SentenceTransformer
|
| 6 |
|
| 7 |
-
# β
|
| 8 |
-
model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 9 |
|
| 10 |
-
# Load posts dataset
|
| 11 |
-
posts_df = pd.read_csv("posts_cleaned.csv")
|
| 12 |
post_texts = posts_df["post_text"].astype(str).tolist()
|
| 13 |
|
| 14 |
-
# Cache embeddings
|
| 15 |
post_embeddings = None
|
| 16 |
|
| 17 |
def get_embeddings():
|
|
@@ -21,21 +21,25 @@ def get_embeddings():
|
|
| 21 |
post_embeddings = model.encode(post_texts, convert_to_tensor=False)
|
| 22 |
return post_embeddings
|
| 23 |
|
| 24 |
-
|
|
|
|
| 25 |
if not user_text.strip():
|
| 26 |
-
return []
|
| 27 |
|
| 28 |
embeddings = get_embeddings()
|
| 29 |
user_vec = model.encode([user_text])
|
| 30 |
sims = cosine_similarity(user_vec, embeddings)[0]
|
| 31 |
top_idxs = sims.argsort()[-5:][::-1]
|
| 32 |
-
|
|
|
|
|
|
|
| 33 |
|
|
|
|
| 34 |
interface = gr.Interface(
|
| 35 |
-
fn=
|
| 36 |
inputs=gr.Textbox(label="What are you interested in?"),
|
| 37 |
-
outputs=gr.
|
| 38 |
-
title="π AI Content Recommender"
|
| 39 |
)
|
| 40 |
|
| 41 |
-
interface.launch(
|
|
|
|
| 4 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 5 |
from sentence_transformers import SentenceTransformer
|
| 6 |
|
| 7 |
+
# β
Load the model
|
| 8 |
+
model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 9 |
|
| 10 |
+
# β
Load posts dataset
|
| 11 |
+
posts_df = pd.read_csv("posts_cleaned.csv")
|
| 12 |
post_texts = posts_df["post_text"].astype(str).tolist()
|
| 13 |
|
| 14 |
+
# β
Cache embeddings
|
| 15 |
post_embeddings = None
|
| 16 |
|
| 17 |
def get_embeddings():
|
|
|
|
| 21 |
post_embeddings = model.encode(post_texts, convert_to_tensor=False)
|
| 22 |
return post_embeddings
|
| 23 |
|
| 24 |
+
# β
Main recommender logic with JSON output
|
| 25 |
+
def recommend_json(user_text):
|
| 26 |
if not user_text.strip():
|
| 27 |
+
return { "data": [[]] }
|
| 28 |
|
| 29 |
embeddings = get_embeddings()
|
| 30 |
user_vec = model.encode([user_text])
|
| 31 |
sims = cosine_similarity(user_vec, embeddings)[0]
|
| 32 |
top_idxs = sims.argsort()[-5:][::-1]
|
| 33 |
+
recommendations = posts_df.iloc[top_idxs]["post_text"].tolist()
|
| 34 |
+
|
| 35 |
+
return { "data": [recommendations] }
|
| 36 |
|
| 37 |
+
# β
Gradio JSON interface
|
| 38 |
interface = gr.Interface(
|
| 39 |
+
fn=recommend_json,
|
| 40 |
inputs=gr.Textbox(label="What are you interested in?"),
|
| 41 |
+
outputs=gr.JSON(label="Structured Recommendations"),
|
| 42 |
+
title="π AI Content Recommender (API Mode)"
|
| 43 |
)
|
| 44 |
|
| 45 |
+
interface.launch()
|