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airwise import cosine_similarity
|
| 4 |
+
from typing_extensions import Doc
|
| 5 |
+
import gradio as gr
|
| 6 |
+
df = pd.read_csv('dataframe.csv')
|
| 7 |
+
tfidf_matrix = pd.read_csv('tfidf_matrix.csv', header=None).values
|
| 8 |
+
tfidf_matrix.shape
|
| 9 |
+
word2vec_matrix = pd.read_csv('word2vecmatrix.csv',header=None).values
|
| 10 |
+
word2vec_matrix.shape
|
| 11 |
+
|
| 12 |
+
sbert1_matrix = pd.read_csv('sentencetransformer1.csv',header=None).values
|
| 13 |
+
sbert1_matrix.shape
|
| 14 |
+
|
| 15 |
+
sbert2_matrix = pd.read_csv('sentencetransformer2 copy.csv',header=None).values
|
| 16 |
+
sbert2_matrix.shape
|
| 17 |
+
|
| 18 |
+
def course_recommendation(model, course_subject_code, course_number, whether_not_lower_level=False, whether_only_sameorlower_level = False, whether_not_same_subject=False, whether_only_same_subject=False, recomendations_number = 5):
|
| 19 |
+
if model == "tf-idf":
|
| 20 |
+
docmatrix = tfidf_matrix
|
| 21 |
+
elif model == "word2vec":
|
| 22 |
+
docmatrix = word2vec_matrix
|
| 23 |
+
elif model == "sbert1":
|
| 24 |
+
docmatrix = sbert1_matrix # This appears to have been a typo in the original code
|
| 25 |
+
elif model == "sbert2":
|
| 26 |
+
docmatrix = sbert2_matrix
|
| 27 |
+
|
| 28 |
+
# Check if the course exists in the dataframe
|
| 29 |
+
if not ((df['Course Subject Code'] == course_subject_code) & (df['Course Number'] == course_number)).any():
|
| 30 |
+
return pd.DataFrame({'Message': ["The course you input does not exist in this semester or we do not have enough course description information about it. Please try another course. "]})
|
| 31 |
+
|
| 32 |
+
if whether_not_lower_level == True and whether_only_sameorlower_level == True:
|
| 33 |
+
return pd.DataFrame({'Message': ["There seems to be a conflict in the filtering logic. Please double-check the checkboxes for filtering carefully."]})
|
| 34 |
+
if whether_not_same_subject == True and whether_only_same_subject == True:
|
| 35 |
+
return pd.DataFrame({'Message': ["There seems to be a conflict in the filtering logic. Please double-check the checkboxes for filtering carefully."]})
|
| 36 |
+
|
| 37 |
+
# Get the index and level of the course in the dataframe
|
| 38 |
+
course_info = df[(df['Course Subject Code'] == course_subject_code) & (df['Course Number'] == course_number)]
|
| 39 |
+
course_index = course_info.index[0]
|
| 40 |
+
course_level = course_info.iloc[0]['Course Level']
|
| 41 |
+
# Normalize "First-year Student Seminar" to "100-level"
|
| 42 |
+
course_level = "100-level" if course_level == "First-year Student Seminar" else course_level
|
| 43 |
+
|
| 44 |
+
df_filtered = df.copy()
|
| 45 |
+
if whether_not_same_subject:
|
| 46 |
+
df_filtered = df_filtered[df_filtered['Course Subject Code'] != course_subject_code]
|
| 47 |
+
if whether_only_same_subject:
|
| 48 |
+
df_filtered = df_filtered[df_filtered['Course Subject Code'] == course_subject_code]
|
| 49 |
+
|
| 50 |
+
if whether_not_lower_level:
|
| 51 |
+
levels_to_include = ['100-level', '200-level', '300-level', '400-level', 'Graduate level']
|
| 52 |
+
current_level_index = levels_to_include.index(course_level)
|
| 53 |
+
allowed_levels = levels_to_include[current_level_index:] # Include current and higher levels
|
| 54 |
+
df_filtered = df_filtered[df_filtered['Course Level'].isin(allowed_levels)]
|
| 55 |
+
|
| 56 |
+
if whether_only_sameorlower_level:
|
| 57 |
+
levels_to_include = ['100-level', '200-level', '300-level', '400-level', 'Graduate level']
|
| 58 |
+
current_level_index = levels_to_include.index(course_level)
|
| 59 |
+
allowed_levels = levels_to_include[:current_level_index + 1] # Include current and lower levels
|
| 60 |
+
df_filtered = df_filtered[df_filtered['Course Level'].isin(allowed_levels)]
|
| 61 |
+
|
| 62 |
+
# Retrieve the vector for the specified course
|
| 63 |
+
course_vector = docmatrix[course_index]
|
| 64 |
+
|
| 65 |
+
# Calculate the cosine similarity with filtered courses
|
| 66 |
+
cosine_similarities = cosine_similarity(docmatrix[df_filtered.index], course_vector.reshape(1, -1)).flatten()
|
| 67 |
+
|
| 68 |
+
# Get the indices of the courses with the highest cosine similarity scores
|
| 69 |
+
similar_courses_indices = np.argsort(-cosine_similarities)[:int(recomendations_number)+1]
|
| 70 |
+
|
| 71 |
+
# Retrieve the course details for the most similar courses
|
| 72 |
+
similar_courses = df_filtered.iloc[similar_courses_indices][['Course Code', 'Course Title', 'Course Description Text']]
|
| 73 |
+
if similar_courses.index[0] == course_index:
|
| 74 |
+
similar_courses = similar_courses.iloc[1:] # Exclude the original course if it is the highest ranked
|
| 75 |
+
else:
|
| 76 |
+
similar_courses = similar_courses.head(int(recomendations_number))
|
| 77 |
+
|
| 78 |
+
# Insert a column for similarity rank
|
| 79 |
+
|
| 80 |
+
input_course_details = course_info[['Course Code', 'Course Title', 'Course Description Text']]
|
| 81 |
+
result_df = pd.concat([input_course_details, similar_courses]).reset_index(drop=True)
|
| 82 |
+
result_df .insert(0, 'Similar Rank', range(0, len(similar_courses) + 1))
|
| 83 |
+
return result_df
|
| 84 |
+
|
| 85 |
+
import gradio as gr
|
| 86 |
+
import pandas as pd
|
| 87 |
+
from functools import partial
|
| 88 |
+
|
| 89 |
+
def highlight_first_row(s, props=''):
|
| 90 |
+
return [props if s.name == 0 else '' for _ in range(len(s))]
|
| 91 |
+
|
| 92 |
+
def recommend(model_name, course_subject_code, course_number, exclude_lower_levels, exclude_upper_levels, exclude_same_subject, exclude_other_subject, recomendations_number):
|
| 93 |
+
outputdf = course_recommendation(model_name, course_subject_code, course_number, exclude_lower_levels, exclude_upper_levels, exclude_same_subject, exclude_other_subject, recomendations_number)
|
| 94 |
+
outputdf = outputdf.style.apply(highlight_first_row, props='background-color: orange;', axis=1)
|
| 95 |
+
return outputdf
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def main():
|
| 100 |
+
with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
|
| 101 |
+
gr.Markdown("# Course Recommendation System - For UIUC fall 2024 semester")
|
| 102 |
+
gr.Markdown("This project provides course recommendations using different NLP models. Select a model and enter course details to see recommendations.")
|
| 103 |
+
gr.Markdown("Want to know how these models work? Check out the **ABOUT** tab:)")
|
| 104 |
+
with gr.Row():
|
| 105 |
+
with gr.Column(scale=2):
|
| 106 |
+
gr.Markdown("*Choose the course you want to explore:*" )
|
| 107 |
+
with gr.Row():
|
| 108 |
+
subject = gr.Dropdown(choices=sorted(df['Course Subject Code'].unique()), label="Course Subject Code")
|
| 109 |
+
number = gr.Textbox(label="Course Number")
|
| 110 |
+
recommendation_no = gr.Slider(3, 100, step = 1, label="Recommendation Number", info="Choose between 3 and 100")
|
| 111 |
+
with gr.Column(scale=1):
|
| 112 |
+
gr.Markdown("*You may want to add a filter:*")
|
| 113 |
+
with gr.Row():
|
| 114 |
+
exclude_lower = gr.Checkbox(label="Only Upper Level", info = "Same level and higher level courses will be shown")
|
| 115 |
+
exclude_upper = gr.Checkbox(label="Only Lower Level", info = "Same level and lower level courses will be shown")
|
| 116 |
+
with gr.Row():
|
| 117 |
+
exclude_same = gr.Checkbox(label="Only Different Subject")
|
| 118 |
+
exclude_other = gr.Checkbox(label="Only Same Subject")
|
| 119 |
+
tf_idf_submit = gr.Button("Recommend", variant="primary")
|
| 120 |
+
with gr.Tabs() as tabs:
|
| 121 |
+
|
| 122 |
+
# Setting up the interface for each model
|
| 123 |
+
with gr.Tab("Word2Vec Model"):
|
| 124 |
+
tf_idf_submit.click(
|
| 125 |
+
fn=partial(recommend, "word2vec"),
|
| 126 |
+
inputs=[subject, number, exclude_lower, exclude_upper, exclude_same, exclude_other, recommendation_no],
|
| 127 |
+
outputs=gr.Dataframe(wrap = True, column_widths = ["10%","10%", "20%", "63%"])
|
| 128 |
+
)
|
| 129 |
+
with gr.Tab("TF-IDF Model"):
|
| 130 |
+
tf_idf_submit.click(
|
| 131 |
+
fn=partial(recommend, "tf-idf"),
|
| 132 |
+
inputs=[subject, number, exclude_lower, exclude_upper, exclude_same, exclude_other, recommendation_no],
|
| 133 |
+
outputs=gr.Dataframe(wrap = True, column_widths = ["10%","10%", "20%", "63%"])
|
| 134 |
+
)
|
| 135 |
+
with gr.Tab("SBERT Model1"):
|
| 136 |
+
tf_idf_submit.click(
|
| 137 |
+
fn=partial(recommend, "sbert1"),
|
| 138 |
+
inputs=[subject, number, exclude_lower, exclude_upper, exclude_same, exclude_other, recommendation_no],
|
| 139 |
+
outputs=gr.Dataframe(wrap = True, column_widths = ["10%","10%", "20%", "63%"])
|
| 140 |
+
)
|
| 141 |
+
with gr.Tab("SBERT Model2"):
|
| 142 |
+
tf_idf_submit.click(
|
| 143 |
+
fn=partial(recommend, "sbert2"),
|
| 144 |
+
inputs=[subject, number, exclude_lower, exclude_upper, exclude_same, exclude_other, recommendation_no],
|
| 145 |
+
outputs=gr.Dataframe(wrap = True, column_widths = ["10%","10%", "20%", "63%"])
|
| 146 |
+
)
|
| 147 |
+
with gr.Tab("ABOUT"):
|
| 148 |
+
gr.Markdown("This project provides course recommendations using different NLP models. Select a model and enter course details to see recommendations.")
|
| 149 |
+
return demo
|
| 150 |
+
|
| 151 |
+
# Launch the interface
|
| 152 |
+
if __name__ == "__main__":
|
| 153 |
+
main().launch(share=True)
|
| 154 |
+
|