File size: 5,846 Bytes
8a89da7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | import requests
from bs4 import BeautifulSoup
import pandas as pd
import gradio as gr
import torch
from transformers import BertTokenizer, BertModel
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
# Step 1: Scrape the free courses from Analytics Vidhya
url = "https://courses.analyticsvidhya.com/pages/all-free-courses"
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
courses = []
# Extract course titles, images, and links
for course_card in soup.find_all('header', class_='course-card__img-container'):
img_tag = course_card.find('img', class_='course-card__img')
if img_tag:
title = img_tag.get('alt')
image_url = img_tag.get('src')
link_tag = course_card.find_previous('a')
if link_tag:
course_link = link_tag.get('href')
if not course_link.startswith('http'):
course_link = 'https://courses.analyticsvidhya.com' + course_link
courses.append({
'title': title,
'image_url': image_url,
'course_link': course_link
})
# Step 2: Create DataFrame
df = pd.DataFrame(courses)
# Load pre-trained BERT model and tokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained('bert-base-uncased')
# Function to generate embeddings using BERT
def get_bert_embedding(text):
inputs = tokenizer(text, return_tensors='pt', truncation=True, padding=True)
with torch.no_grad():
outputs = model(**inputs)
return outputs.last_hidden_state.mean(dim=1).numpy()
# Create embeddings for course titles
df['embedding'] = df['title'].apply(lambda x: get_bert_embedding(x))
# Function to perform search using BERT-based similarity
def search_courses(query):
query_embedding = get_bert_embedding(query)
course_embeddings = np.vstack(df['embedding'].values)
# Compute cosine similarity
similarities = cosine_similarity(query_embedding, course_embeddings).flatten()
# Add similarity scores to the DataFrame
df['score'] = similarities
# Sort by similarity score in descending order
top_results = df.sort_values(by='score', ascending=False).head(10)
return top_results[['title', 'image_url', 'course_link', 'score']].to_dict(orient='records')
# Gradio function for search
def gradio_search(query):
result_list = search_courses(query)
if result_list:
html_output = '<div class="result-wrapper">'
for item in result_list:
course_title = item['title']
course_image = item['image_url']
course_link = item['course_link']
relevance_score = round(item['score'] * 100, 2)
html_output += f'''
<div class="course-item">
<img src="{course_image}" alt="{course_title}" class="course-image"/>
<div class="course-details">
<h3>{course_title}</h3>
<p class="score">Relevance: {relevance_score}%</p>
<a href="{course_link}" target="_blank" class="course-link">View Course</a>
</div>
</div>'''
html_output += '</div>'
return html_output
else:
return '<p class="no-results">No results found.</p>'
# Custom CSS for the Gradio interface
custom_css = """
body {
font-family: 'Segoe UI', sans-serif;
background: linear-gradient(90deg, #e3ffe7 0%, #d9e7ff 100%);
color: #333;
margin: 0;
padding: 0;
}
.result-wrapper {
display: flex;
flex-wrap: wrap;
gap: 15px;
justify-content: center;
padding: 20px;
}
.course-item {
background: #fff;
border: 3px solid #444; /* Thick border */
border-radius: 12px;
width: 300px;
overflow: hidden;
box-shadow: 0 6px 8px rgba(0, 0, 0, 0.2); /* Enhanced shadow */
transition: transform 0.3s ease, box-shadow 0.3s ease, border-color 0.3s ease;
}
.course-item:hover {
transform: translateY(-5px);
box-shadow: 0 8px 12px rgba(0, 0, 0, 0.3);
border-color: #007bff; /* Change border color on hover */
}
.course-image {
width: 100%;
height: 180px;
object-fit: cover;
}
.course-details {
padding: 15px;
text-align: center;
}
.course-details h3 {
font-size: 20px;
font-weight: bold; /* Thicker text for the title */
color: #222;
margin-bottom: 10px;
}
.course-link {
text-decoration: none;
font-size: 16px; /* Slightly larger font */
font-weight: bold; /* Bold link text */
color: #007bff;
border: 2px solid #007bff; /* Thicker border for buttons */
padding: 8px 15px;
border-radius: 25px;
transition: background 0.3s, color 0.3s, border-color 0.3s;
}
.course-link:hover {
background: #007bff;
color: #fff;
border-color: #0056b3; /* Darker border on hover */
}
.score {
margin-top: 10px;
font-size: 14px;
color: #555; /* Darker text for scores */
font-weight: bold; /* Bold score text */
}
"""
# Gradio interface
iface = gr.Interface(
fn=gradio_search,
inputs=gr.Textbox(label="Enter your search query", placeholder="e.g., machine learning, data science, python"),
outputs=gr.HTML(label="Search Results"),
title="Analytics Vidhya Enhanced Course Search",
description="Find relevant courses from Analytics Vidhya with a modern UI.",
css=custom_css,
examples=[
["machine learning for beginners"],
["advanced data visualization techniques"],
["python programming basics"],
["Business Analytics"]
]
)
if __name__ == "__main__":
iface.launch()
|