TuneedTG commited on
Commit
9d9d2f1
·
verified ·
1 Parent(s): e976e1b

Full code to be run

Browse files
Files changed (1) hide show
  1. app.py +48 -0
app.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #Library install
2
+ !pip install transformers sentence-transformers gradio
3
+ import pandas as pd
4
+ from sentence_transformers import SentenceTransformer
5
+ from sklearn.metrics.pairwise import cosine_similarity
6
+ import gradio as gr
7
+
8
+ # Load the dataset
9
+ df = pd.read_csv('/content/courses.csv') # Replace with actual path to courses.csv
10
+ # Load a pre-trained sentence transformer model
11
+ model = SentenceTransformer('all-MiniLM-L6-v2')
12
+
13
+ # Create a combined column for embedding (e.g., title + description + keywords)
14
+ df['combined_text'] = df['title'] + " " + df['description'] + " " + df['keywords']
15
+ course_embeddings = model.encode(df['combined_text'].tolist(), convert_to_tensor=True)
16
+ def search_courses(user_query):
17
+ # Encode the user query
18
+ query_embedding = model.encode(user_query, convert_to_tensor=True)
19
+
20
+ # Compute cosine similarities between the query and each course embedding
21
+ similarities = cosine_similarity(
22
+ query_embedding.cpu().detach().numpy().reshape(1, -1),
23
+ course_embeddings.cpu().detach().numpy()
24
+ )
25
+
26
+ # Get indices of top matching courses (top 5 results)
27
+ top_matches = similarities.argsort()[0][-5:][::-1]
28
+
29
+ # Retrieve top matching courses
30
+ results = [{"title": df.iloc[i]["title"], "description": df.iloc[i]["description"]} for i in top_matches]
31
+ return results
32
+
33
+ # Define Gradio function for user interaction
34
+ def gradio_search(query):
35
+ results = search_courses(query)
36
+ return results
37
+
38
+ # Set up Gradio interface
39
+ iface = gr.Interface(
40
+ fn=gradio_search,
41
+ inputs="text",
42
+ outputs="json",
43
+ title="Smart Course Search",
44
+ description="Find the most relevant courses based on your query."
45
+ )
46
+
47
+ # Launch the app (for local testing or deploying in Hugging Face Spaces)
48
+ iface.launch()