-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_handlers.py
307 lines (239 loc) · 9.79 KB
/
data_handlers.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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
from typing import Dict, Union, Any
from pymongo import MongoClient
from models import JobMappingGithubS2, JobMappingKaggleS1, JobMappingGithubS4, JobMappingKaggleS3, \
SearchJobRequestModel, CompanyMappingDS2, SearchCompanyRequestModel, DataBaseMapModel, job_col_mappings, \
DB_Class_Mappings
from bson import ObjectId, json_util
import json
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
from fuzzywuzzy import fuzz
connection_string = "mongodb+srv://jayan20071:[email protected]/"
newconnection = "mongodb+srv://admin:[email protected]/"
class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, ObjectId):
return str(o)
return json.JSONEncoder.default(self, o)
def get_DB(DB_Name):
if DB_Name in ["Kaggle_S1", "Github_S2", "Kaggle_S3", "Github_S4"]:
connection_string = "mongodb+srv://jayan20071:[email protected]/"
elif DB_Name == "NewJobs":
connection_string = "mongodb+srv://admin:[email protected]/"
elif DB_Name == "DS_2":
connection_string = "mongodb+srv://jayan20071:[email protected]/"
client = MongoClient(connection_string)
db = client[DataBaseMapModel.company]
collection = db[DB_Name]
return collection
client = MongoClient(connection_string)
db = client[DataBaseMapModel.job]
collection = db[DB_Name]
return collection
def Transform(DatasetName, query):
if (type(query) != dict):
query = query[0]
Transformed = {}
for enum_val in DB_Class_Mappings[DatasetName]:
if (enum_val.value == "" or (enum_val.value not in query)):
Transformed[enum_val.name] = ""
else:
Transformed[enum_val.name] = query[enum_val.value]
L = []
L.append(Transformed)
return L
def DB_Match(query, DB_Name):
Database = get_DB(DB_Name)
cursor = Database.find({})
query = Transform(DB_Name, query)[0]
for entry in cursor:
entry = Transform(DB_Name, entry)[0]
if entity_matching(query, entry):
return True
return False
def entity_matching(row1, row2, threshold_tfidf=0.5, threshold_fuzzy=50):
if not row1 or not row2:
return False
# Convert dictionaries to DataFrames
df1 = pd.DataFrame([row1])
df2 = pd.DataFrame([row2])
# Create a 'text' column by concatenating values in each row
df1['text'] = df1.apply(lambda row: ' '.join(row.astype(str)), axis=1)
df2['text'] = df2.apply(lambda row: ' '.join(row.astype(str)), axis=1)
# Create TF-IDF vectorizers
tfidf_vectorizer = TfidfVectorizer()
# Fit and transform the text data in the table
tfidf_matrix_table = tfidf_vectorizer.fit_transform(df2["text"])
# Transform the text data in the query
tfidf_matrix_query = tfidf_vectorizer.transform(df1["text"])
# Compute the cosine similarities between the query and table using TF-IDF
cosine_sim = linear_kernel(tfidf_matrix_query, tfidf_matrix_table)
# Create an empty list to store matching rows
avg_similarity = 0
for key_query, value_query in row1.items():
key_table = key_query
value_table = row2.get(key_query, "")
# Use FuzzyWuzzy to compare values
value_similarity = fuzz.token_sort_ratio(str(value_query), str(value_table))
avg_similarity += value_similarity
print(cosine_sim[0][0])
print(value_similarity)
if cosine_sim[0][0] < threshold_tfidf:
break # Exit the loop as soon as one pair falls below either threshold
avg_similarity = avg_similarity / len(row1)
# Check if all key-value pairs meet the thresholds
if avg_similarity >= threshold_fuzzy:
return True
return False
def entity_matching_for_search(query, results):
if not results:
return False
for result in results:
if entity_matching(query, result):
return True
return False
def job_search_results(query_dict: Dict[str, Any]):
try:
final_results = []
for key in ["Kaggle_S1", "Github_S2", "Kaggle_S3", "Github_S4", "NewJobs"]:
flag = True
query_for_db = {}
collection_name = key
for enum_val in job_col_mappings[key]:
if ("" + enum_val.name) in query_dict.keys():
if(query_dict["" + enum_val.name]==""):
continue
if enum_val.value == "":
flag = False
break
query_for_db[enum_val.value] = query_dict["" + enum_val.name]
if flag:
#print(query_for_db)
#results = find_query_in_database(query_for_db,collection_name)
collection = get_DB(collection_name)
results = list(collection.find(query_for_db))
if not results:
continue
newres=[]
for r in results:
r = Transform(key, r)
newres.append(r)
results=newres
if not entity_matching_for_search(results, final_results):
final_results.extend(results)
else:
print("Duplicate result")
for i in range(0, len(final_results)):
dump = json.dumps(final_results[i], default=str)
final_results[i] = json.loads(dump)
display = []
for result in final_results:
result = result[0]
display.append(result)
print(display)
return display
except Exception as e:
print("Error:", str(e))
return []
def company_search_results(query_dict: Dict[str, Any]):
try:
client = MongoClient(connection_string)
db = client[DataBaseMapModel.company]
final_results = []
for key in ["DS_2"]:
flag = True
query_for_db = {}
collection_name = key
if key == "DS_2":
for enum_val in CompanyMappingDS2:
if ("" + enum_val.name) in query_dict.keys():
if enum_val.value == "":
flag = False
break
if(query_dict["" + enum_val.name]==""):
continue
query_for_db[enum_val.value] = query_dict["" + enum_val.name]
# print(query_dict)
print('query ', query_for_db)
if flag:
collection = db[collection_name]
results = list(collection.find(query_for_db))
if not results:
continue
results = Transform(key, results)
if not entity_matching_for_search(results, final_results):
final_results.extend(results)
else:
print("Duplicate result")
for i in range(0, len(final_results)):
dump = json.dumps(final_results[i], default=str)
final_results[i] = json.loads(dump)
return final_results
except Exception as e:
print("Error:", str(e))
return []
def job_addition_to_existing(query_dict: Dict[str, Any], table):
collection = get_DB(table)
query_for_db = {}
for enum_val in job_col_mappings[table]:
if ("" + enum_val.name) in query_dict.keys():
if enum_val.value == "":
flag = False
break
query_for_db[enum_val.value] = query_dict["" + enum_val.name]
if not DB_Match(query_for_db, table):
result = collection.insert_one(query_for_db)
else:
print("Duplicate entry")
return []
def job_addition(query_dict: Dict[str, Any]):
collection = get_DB('NewJobs')
if not DB_Match(query_dict, "NewJobs"):
result = collection.insert_one(query_dict)
else:
print("Duplicate entry")
return []
def delete_job_source(table_name: str) -> str:
collection = get_DB(table_name)
try:
collection.drop()
return "Data Source: " + table_name + " has been removed."
except Exception as e:
return "Could not delete collection. Error - " + str(e)
def delete_from_existing_table(query_dict: Dict[str, Any]):
try:
final_result = []
for table_name in ['Kaggle_S1', 'Github_S2', 'Kaggle_S3', 'Github_S4']:
collection = get_DB(table_name)
print(table_name)
query_for_db = {}
for enum_val in job_col_mappings[table_name]:
if ("" + enum_val.name) in query_dict.keys():
if enum_val.value == "":
continue
else:
query_for_db[enum_val.value] = query_dict["" + enum_val.name]
print(query_for_db)
records = collection.count_documents(query_for_db)
if records != 0:
result = collection.delete_many(query_for_db)
print(str(records) + "Record(s) deleted!")
final_result.append(result)
else:
result = []
return final_result
except Exception as e:
print("Error:", str(e))
return []
def get_user_data(email):
print("Hello")
newconnection = "mongodb+srv://admin:[email protected]/"
client = MongoClient(newconnection)
db = client["Jobs"]
DB_Name = "NewUsers"
collection = db[DB_Name]
cursor = list(collection.find({"Email":email}) )
return cursor
if __name__ == "__main__":
print(get_user_data("[email protected]"))