-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain2.py
197 lines (163 loc) · 6.55 KB
/
main2.py
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import numpy as np
import google.generativeai as palm
import pandas as pd
import os
import matplotlib.pyplot as plt
import json
import re
import seaborn as sns
from sklearn.manifold import TSNE
import spacy
from ftfy import fix_text
nlp = spacy.load("en_core_web_sm")
# palm.configure(api_key='AIzaSyCTQWAShWf9v52yCNwrXjkn5vivRVNMv1s')
palm.configure(api_key='AIzaSyDnUxKaSdabi0rNjxdcKtSvSuKWE-zDkNo')
# path = "C:/Users/limah/OneDrive/Desktop/nasaSpaceApp/users.json"
def plot_word_embeddings(x):
embeddings = []
for i in x:
emp = get_embedding(i)
embeddings.append(emp)
embeddings = np.array(embeddings, dtype=np.float32)
tsne = TSNE(random_state=0, perplexity=1, n_iter=1000)
tsne_results = tsne.fit_transform(embeddings)
df_tsne = pd.DataFrame(tsne_results, columns=['TSNE1', 'TSNE2'])
df_tsne['Class Name'] = x
fig, ax = plt.subplots(figsize=(8, 6)) # Set figsize
sns.set_style('darkgrid', {"grid.color": ".6", "grid.linestyle": ":"})
sns.scatterplot(data=df_tsne, x='TSNE1', y='TSNE2', hue='Class Name', palette='hls')
sns.move_legend(ax, "upper left", bbox_to_anchor=(1, 1))
plt.title('Scatter plot of words embeddings');
plt.xlabel('TSNE1');
plt.ylabel('TSNE2');
plt.axis('equal')
for i, txt in enumerate(x):
ax.annotate(txt, (df_tsne['TSNE1'][i], df_tsne['TSNE2'][i]), fontsize=5)
plt.show()
def ngrams(string, n=3):
string = fix_text(string) # fix text
string = string.encode("ascii", errors="ignore").decode() # remove non ascii chars
string = string.lower()
chars_to_remove = [")", "(", ".", "|", "[", "]", "{", "}", "'"]
rx = '[' + re.escape(''.join(chars_to_remove)) + ']'
string = re.sub(rx, '', string)
string = string.replace('&', 'and')
string = string.replace(',', ' ')
string = string.replace('-', ' ')
string = string.title() # normalise case - capital at start of each word
string = re.sub(' +', ' ', string).strip() # get rid of multiple spaces and replace with a single
string = ' ' + string + ' ' # pad names for ngrams...
string = re.sub(r'[,-./]|\sBD', r'', string)
ngrams = zip(*[string[i:] for i in range(n)])
return [''.join(ngram) for ngram in ngrams]
def save_skills(existing_data, name, skills, embedding, email):
new_row_data = {'name': name, 'skills': skills, 'email': email, 'embeddings': f"{embedding}"}
new_row_df = pd.DataFrame(new_row_data, index=[0])
existing_data = pd.concat([existing_data, new_row_df], ignore_index=True)
existing_data.to_json(path)
# new_row_df.to_json(path, orient='records')
print("saved")
def check(skills):
while len(skills) < 20:
print("Enter some more details")
inp = input()
skills += " "
skills += inp
return skills
def check_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if re.match(pattern, email):
return email
else:
print("invalid email , retry")
email = input()
check_email(email)
return email
def promt_skills(email):
existing_data = pd.read_json(path)
name = input("what is your name")
x = input("What skills do you have and what type of projects do you want to work in?")
x = check(x)
x = nlp(x)
keywords = [token.text for token in x if not token.is_stop]
x = ""
for i in keywords:
x += i
embeddings = get_embedding(x)
# plot_word_embeddings(keywords)
# save_skills(existing_data, name, x, embeddings, email)
def get_projects_save(email):
# loading data
# df_proj = pd.read_json("C:/Users/limah/OneDrive/Desktop/nasaSpaceApp/projects.json")
existing_data = pd.read_json(path)
name_details = existing_data[existing_data["email"] == email]
if name_details.empty:
print("name not found")
promt_skills(email)
existing_data = pd.read_json(path)
indx = existing_data[existing_data["email"] == email].index[0]
measures = []
for i in range(0, len(df_proj)):
project_des = df_proj["descriptions"].iloc[i]
project_URL = df_proj["URL"].iloc[i]
project_name = df_proj["title"].iloc[i]
project_embeddings = df_proj["embeddings"].iloc[i]
project_embeddings = json.loads(project_embeddings)
embedding_user = existing_data["embeddings"].iloc[indx]
# embedding_user = name_details["embeddings"]
print(embedding_user)
embedding_user = json.loads(embedding_user)
similar_measure = np.dot(embedding_user, project_embeddings)
measures.append((similar_measure, project_name, project_URL))
print(similar_measure)
measures.sort(reverse=True)
# print(measures)
for i in measures[0: 5]:
print(i[1])
print(i[2])
arr = []
def get_embedding(skills):
model = "models/embedding-gecko-001"
x = skills
embedding = palm.generate_embeddings(model=model, text=x)
embedding = embedding['embedding']
return embedding
# def save_skills( name, skills, embedding, email):
def get_recommended_projects(embeddings):
measures = []
df_proj = pd.read_json(r"excel_projects2.json")
# print(f"embeddings {embedding}")
# df_proj["embeddings"] = None
for i in range(0, len(df_proj)):
project_des = df_proj["descriptions"].iloc[i]
# project_URL = df_proj["URL"].iloc[i]
# project_name = df_proj["title"].iloc[i]
project_name = df_proj["projects-name"].iloc[i]
# project_embeddings = df_proj["embeddings"].iloc[i]
# project_embeddings = json.loads(project_embeddings)
# project_embeddings = get_embedding(project_des)
project_embeddings = df_proj["embeddings"].iloc[i]
project_embeddings = json.loads(project_embeddings)
# embedding_user = existing_data["embeddings"].iloc[indx]
df_proj["embeddings"].iloc[i] = f"{project_embeddings}"
embedding_user = embeddings
# embedding_user = name_details["embeddings"]
# embedding_user = json.loads(embedding_user)
similar_measure = np.dot(embedding_user, project_embeddings)
measures.append((similar_measure, project_name))
print(similar_measure)
measures.sort(reverse=True)
top_projects = []
for i in measures[0: 5]:
print(i[1])
top_projects.append(i[1])
print("saved")
return top_projects
def get_recommendation(skills):
skills = nlp(skills)
keywords = [token.text for token in skills if not token.is_stop]
skills = ""
for i in keywords:
skills += i
embeddings = get_embedding(skills)
return get_recommended_projects(embeddings)