abhiixxhek commited on
Commit
9eb86cf
1 Parent(s): fb2baaa

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +198 -0
app.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from bs4 import BeautifulSoup
3
+ import pandas as pd
4
+ import gradio as gr
5
+ from groq import Groq
6
+
7
+ # Step 1: Scrape free courses from Analytics Vidhya
8
+ def fetch_free_courses():
9
+ url = "https://courses.analyticsvidhya.com/pages/all-free-courses"
10
+ response = requests.get(url)
11
+ soup = BeautifulSoup(response.content, 'html.parser')
12
+
13
+ courses_data = []
14
+
15
+ # Extract course details
16
+ for card in soup.select('header.course-card__img-container'):
17
+ image_element = card.find('img', class_='course-card__img')
18
+
19
+ if image_element:
20
+ title = image_element.get('alt')
21
+ img_url = image_element.get('src')
22
+
23
+ link = card.find_previous('a')
24
+ if link:
25
+ course_link = link.get('href')
26
+ if not course_link.startswith('http'):
27
+ course_link = 'https://courses.analyticsvidhya.com' + course_link
28
+
29
+ courses_data.append({
30
+ 'title': title,
31
+ 'image_url': img_url,
32
+ 'course_link': course_link
33
+ })
34
+ return courses_data
35
+
36
+ courses = fetch_free_courses()
37
+
38
+ # Step 2: Load data into a DataFrame
39
+ df = pd.DataFrame(courses)
40
+
41
+ client = Groq()
42
+
43
+ # Course search function using Groq
44
+ def course_recommendation(query):
45
+ try:
46
+ print(f"Search query: {query}")
47
+ print(f"Total available courses: {len(df)}")
48
+
49
+ # Prompt construction for Groq
50
+ prompt = f"""
51
+ Based on the query: "{query}",
52
+ Rank the courses below based on relevance (0 to 1), with 1 being highly relevant.
53
+ Filter out courses with relevance scores below 0.5.
54
+
55
+ Courses:
56
+ {df['title'].to_string(index=False)}
57
+ """
58
+
59
+ print("Sending query to Groq for recommendation...")
60
+ # Sending the request to Groq for results
61
+ response = client.chat.completions.create(
62
+ model="mixtral-8x7b-32768",
63
+ messages=[
64
+ {"role": "system", "content": "You are a course recommendation assistant."},
65
+ {"role": "user", "content": prompt}
66
+ ],
67
+ temperature=0.3,
68
+ max_tokens=800
69
+ )
70
+ print("Response received from Groq.")
71
+
72
+ # Parse the Groq response
73
+ recommended_courses = []
74
+ content = response.choices[0].message.content
75
+ print("Groq's response:\n", content)
76
+
77
+ for line in content.split('\n'):
78
+ if line.startswith('Title:'):
79
+ course_title = line.split('Title:')[1].strip()
80
+ elif line.startswith('Relevance:'):
81
+ score = float(line.split('Relevance:')[1].strip())
82
+ if score >= 0.5:
83
+ matching_course = df[df['title'] == course_title]
84
+ if not matching_course.empty:
85
+ course_data = matching_course.iloc[0]
86
+ recommended_courses.append({
87
+ 'title': course_title,
88
+ 'image_url': course_data['image_url'],
89
+ 'course_link': course_data['course_link'],
90
+ 'score': score
91
+ })
92
+
93
+ return sorted(recommended_courses, key=lambda x: x['score'], reverse=True)[:10]
94
+
95
+ except Exception as e:
96
+ print(f"Error during course search: {e}")
97
+ return []
98
+
99
+ # Gradio function to search and display courses
100
+ def gradio_search_interface(query):
101
+ results = course_recommendation(query)
102
+
103
+ if results:
104
+ html_output = '<div class="results-section">'
105
+ for course in results:
106
+ html_output += f"""
107
+ <div class="course-item">
108
+ <img src="{course['image_url']}" alt="{course['title']}" class="course-thumbnail"/>
109
+ <div class="course-details">
110
+ <h4>{course['title']}</h4>
111
+ <p>Relevance: {round(course['score'] * 100, 2)}%</p>
112
+ <a href="{course['course_link']}" target="_blank" class="course-link-button">Explore Course</a>
113
+ </div>
114
+ </div>"""
115
+ html_output += '</div>'
116
+ return html_output
117
+ else:
118
+ return '<p class="no-courses-message">No matching courses found. Try another search.</p>'
119
+
120
+ # Custom CSS to make the interface attractive
121
+ custom_css = """
122
+ body {
123
+ background-color: #eaeef3;
124
+ font-family: 'Montserrat', sans-serif;
125
+ }
126
+ .results-section {
127
+ display: flex;
128
+ flex-wrap: wrap;
129
+ gap: 20px;
130
+ }
131
+ .course-item {
132
+ background-color: white;
133
+ border-radius: 12px;
134
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
135
+ overflow: hidden;
136
+ width: 48%;
137
+ transition: transform 0.3s ease;
138
+ }
139
+ .course-item:hover {
140
+ transform: translateY(-10px);
141
+ }
142
+ .course-thumbnail {
143
+ width: 100%;
144
+ height: 160px;
145
+ object-fit: cover;
146
+ }
147
+ .course-details {
148
+ padding: 15px;
149
+ text-align: center;
150
+ }
151
+ .course-details h4 {
152
+ font-size: 18px;
153
+ color: #333;
154
+ margin: 10px 0;
155
+ }
156
+ .course-details p {
157
+ color: #555;
158
+ font-size: 14px;
159
+ }
160
+ .course-link-button {
161
+ display: inline-block;
162
+ background-color: #ff5733;
163
+ color: white;
164
+ padding: 8px 16px;
165
+ text-decoration: none;
166
+ border-radius: 6px;
167
+ margin-top: 10px;
168
+ }
169
+ .course-link-button:hover {
170
+ background-color: #c44524;
171
+ }
172
+ .no-courses-message {
173
+ text-align: center;
174
+ color: #777;
175
+ font-size: 16px;
176
+ }
177
+ """
178
+
179
+ # Setting up the Gradio interface
180
+ iface = gr.Interface(
181
+ fn=gradio_search_interface,
182
+ inputs=gr.Textbox(label="Search for a course", placeholder="e.g., Python for data analysis, ML basics"),
183
+ outputs=gr.HTML(label="Course Results"),
184
+ title="Analytics Vidhya Course Finder",
185
+ description="Discover the best free courses from Analytics Vidhya tailored to your query.",
186
+ theme="compact",
187
+ css=custom_css,
188
+ examples=[
189
+ ["Data Science for Beginners"],
190
+ ["Python Programming"],
191
+ ["Advanced Machine Learning"],
192
+ ["Business Analytics"],
193
+ ]
194
+ )
195
+
196
+ # Run the Gradio interface
197
+ if __name__ == "__main__":
198
+ iface.launch()