Spaces:
Configuration error
Configuration error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ==============================
|
| 2 |
+
# Explainable Recommendation System
|
| 3 |
+
# Group 15 Project
|
| 4 |
+
# ==============================
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import json
|
| 8 |
+
import numpy as np
|
| 9 |
+
from fastapi import FastAPI
|
| 10 |
+
from pydantic import BaseModel
|
| 11 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 12 |
+
from openai import OpenAI
|
| 13 |
+
|
| 14 |
+
# ------------------------------
|
| 15 |
+
# Initialize OpenAI client
|
| 16 |
+
# ------------------------------
|
| 17 |
+
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
| 18 |
+
|
| 19 |
+
# ------------------------------
|
| 20 |
+
# Small Local Dataset
|
| 21 |
+
# ------------------------------
|
| 22 |
+
dataset = [
|
| 23 |
+
{
|
| 24 |
+
"id": 1,
|
| 25 |
+
"title": "Introduction to Machine Learning",
|
| 26 |
+
"description": "Learn supervised and unsupervised learning, regression, and classification.",
|
| 27 |
+
"tags": ["machine learning", "ai", "beginner"]
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"id": 2,
|
| 31 |
+
"title": "Deep Learning with Neural Networks",
|
| 32 |
+
"description": "Advanced deep learning concepts including CNNs and RNNs.",
|
| 33 |
+
"tags": ["deep learning", "neural networks", "ai"]
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"id": 3,
|
| 37 |
+
"title": "Data Science with Python",
|
| 38 |
+
"description": "Data analysis, visualization, and machine learning using Python.",
|
| 39 |
+
"tags": ["python", "data science"]
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"id": 4,
|
| 43 |
+
"title": "Natural Language Processing",
|
| 44 |
+
"description": "Text processing, embeddings, and transformer models.",
|
| 45 |
+
"tags": ["nlp", "transformers", "ai"]
|
| 46 |
+
}
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
# ------------------------------
|
| 50 |
+
# Generate Embedding
|
| 51 |
+
# ------------------------------
|
| 52 |
+
def get_embedding(text: str):
|
| 53 |
+
response = client.embeddings.create(
|
| 54 |
+
model="text-embedding-3-small",
|
| 55 |
+
input=text
|
| 56 |
+
)
|
| 57 |
+
return np.array(response.data[0].embedding)
|
| 58 |
+
|
| 59 |
+
# ------------------------------
|
| 60 |
+
# Precompute Dataset Embeddings
|
| 61 |
+
# ------------------------------
|
| 62 |
+
for item in dataset:
|
| 63 |
+
combined_text = (
|
| 64 |
+
item["title"] + " " +
|
| 65 |
+
item["description"] + " " +
|
| 66 |
+
" ".join(item["tags"])
|
| 67 |
+
)
|
| 68 |
+
item["embedding"] = get_embedding(combined_text)
|
| 69 |
+
|
| 70 |
+
# ------------------------------
|
| 71 |
+
# Recommendation Function
|
| 72 |
+
# ------------------------------
|
| 73 |
+
def recommend(user_query: str, top_k: int = 2):
|
| 74 |
+
query_embedding = get_embedding(user_query)
|
| 75 |
+
|
| 76 |
+
similarities = []
|
| 77 |
+
for item in dataset:
|
| 78 |
+
score = cosine_similarity(
|
| 79 |
+
[query_embedding],
|
| 80 |
+
[item["embedding"]]
|
| 81 |
+
)[0][0]
|
| 82 |
+
similarities.append((item, score))
|
| 83 |
+
|
| 84 |
+
similarities.sort(key=lambda x: x[1], reverse=True)
|
| 85 |
+
return similarities[:top_k]
|
| 86 |
+
|
| 87 |
+
# ------------------------------
|
| 88 |
+
# LLM Explanation Function
|
| 89 |
+
# ------------------------------
|
| 90 |
+
def generate_explanation(user_query, recommended_items):
|
| 91 |
+
|
| 92 |
+
items_text = "\n".join([
|
| 93 |
+
f"- {item['title']}: {item['description']}"
|
| 94 |
+
for item, score in recommended_items
|
| 95 |
+
])
|
| 96 |
+
|
| 97 |
+
prompt = f"""
|
| 98 |
+
User interest: {user_query}
|
| 99 |
+
|
| 100 |
+
Recommended items:
|
| 101 |
+
{items_text}
|
| 102 |
+
|
| 103 |
+
Explain clearly why these recommendations match the user's interest.
|
| 104 |
+
Make it personalized and easy to understand.
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
response = client.chat.completions.create(
|
| 108 |
+
model="gpt-4o-mini",
|
| 109 |
+
messages=[{"role": "user", "content": prompt}]
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
return response.choices[0].message.content
|
| 113 |
+
|
| 114 |
+
# ------------------------------
|
| 115 |
+
# FastAPI App
|
| 116 |
+
# ------------------------------
|
| 117 |
+
app = FastAPI(title="Explainable Recommendation System")
|
| 118 |
+
|
| 119 |
+
class QueryRequest(BaseModel):
|
| 120 |
+
user_query: str
|
| 121 |
+
|
| 122 |
+
@app.post("/recommend")
|
| 123 |
+
def get_recommendation(request: QueryRequest):
|
| 124 |
+
|
| 125 |
+
recommended = recommend(request.user_query)
|
| 126 |
+
explanation = generate_explanation(request.user_query, recommended)
|
| 127 |
+
|
| 128 |
+
return {
|
| 129 |
+
"query": request.user_query,
|
| 130 |
+
"recommendations": [
|
| 131 |
+
{
|
| 132 |
+
"title": item["title"],
|
| 133 |
+
"description": item["description"],
|
| 134 |
+
"score": float(score)
|
| 135 |
+
}
|
| 136 |
+
for item, score in recommended
|
| 137 |
+
],
|
| 138 |
+
"explanation": explanation
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
# ------------------------------
|
| 142 |
+
# Root Endpoint
|
| 143 |
+
# ------------------------------
|
| 144 |
+
@app.get("/")
|
| 145 |
+
def home():
|
| 146 |
+
return {"message": "Explainable Recommendation System is running 🚀"}
|