Download app.py from ssnd/se: direct link, hf CLI and curl.
- Browser
- Download file 5.85 kB
-
https://huggingface.co/spaces/ssnd/se/resolve/main/app.py
- Command line
-
hf download hf://spaces/ssnd/se/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ssnd/se/resolve/main/app.py
5.85 kB
| 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() | |