Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from sentence_transformers import SentenceTransformer
|
| 3 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 4 |
+
import numpy as np
|
| 5 |
+
import gradio as gr
|
| 6 |
+
|
| 7 |
+
# Load the SentenceTransformer model
|
| 8 |
+
model = SentenceTransformer('sentence-transformers/all-mpnet-base-v2')
|
| 9 |
+
|
| 10 |
+
# Load the embeddings from the JSON file
|
| 11 |
+
with open('/content/drive/My Drive/final_data_with_embeddings.json', 'r') as f:
|
| 12 |
+
data = json.load(f)
|
| 13 |
+
|
| 14 |
+
# Function to perform the search
|
| 15 |
+
def search_courses(user_query):
|
| 16 |
+
query_embedding = model.encode(user_query) # Get the embedding for user query
|
| 17 |
+
similarity_scores = [] # Array to store similarity scores
|
| 18 |
+
|
| 19 |
+
# Compare the user query embedding with each stored embedding
|
| 20 |
+
for dets in data:
|
| 21 |
+
embed = np.array(dets['embedding'])
|
| 22 |
+
similarity = cosine_similarity([query_embedding], [embed])
|
| 23 |
+
similarity_scores.append((similarity[0][0], dets))
|
| 24 |
+
|
| 25 |
+
# Sort the similarity scores in descending order
|
| 26 |
+
similarity_scores.sort(key=lambda x: x[0], reverse=True)
|
| 27 |
+
|
| 28 |
+
# Get the top 4 courses
|
| 29 |
+
top_4_dets = [item[1] for item in similarity_scores[:4]]
|
| 30 |
+
|
| 31 |
+
results = []
|
| 32 |
+
for i,det in enumerate(top_4_dets,1):
|
| 33 |
+
course_info = f"{i}. " \
|
| 34 |
+
f"**Category**: {det['Course Category']}\n\n" \
|
| 35 |
+
f"**Course Name**: {det['Course Name']}\n\n" \
|
| 36 |
+
f"**Course URL**: {det['Course Url']}\n\n" \
|
| 37 |
+
f"**Description**: {det['Course Description']}\n\n"
|
| 38 |
+
results.append(course_info)
|
| 39 |
+
|
| 40 |
+
return "\n\n\n".join(results)
|
| 41 |
+
|
| 42 |
+
# Create the Gradio interface
|
| 43 |
+
iface = gr.Interface(fn=search_courses,
|
| 44 |
+
inputs="text",
|
| 45 |
+
outputs="markdown",
|
| 46 |
+
title="Course Search with Sentence Transformers",
|
| 47 |
+
description="Enter a query to find the top 4 most similar courses.")
|
| 48 |
+
|
| 49 |
+
# Launch the Gradio app
|
| 50 |
+
iface.launch()
|