Spaces:
Sleeping
Sleeping
File size: 9,206 Bytes
5818dbb f1b601b 32d2a84 e3884a1 1abc275 f1b601b 9f13856 1225834 e3884a1 1f1ff08 e3884a1 26a8b59 e3884a1 1abc275 26a8b59 32d2a84 1abc275 8382c94 756ed25 8382c94 1225834 756ed25 1abc275 0dceb1e 1abc275 6ba5f50 83338db 80d2e7b f1b601b c4c7ccc 80d2e7b 83338db 756ed25 83338db 6ba5f50 1abc275 756ed25 1abc275 5818dbb 26a8b59 1abc275 5818dbb 1abc275 26a8b59 5818dbb 1225834 756ed25 1225834 1abc275 5818dbb 1abc275 5142863 5818dbb 5142863 5818dbb 2128ded 5142863 5818dbb 5142863 1060ca8 5142863 1225834 5142863 2128ded 5142863 83338db 5142863 5818dbb 9f13856 |
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 308 309 310 311 312 313 |
from bson import ObjectId
from pymongo import MongoClient
from typing import Dict, Optional
from datetime import datetime
import requests
from pymongo import MongoClient
from gamification.logic import create_points_func
from gamification.objects import PlatformEngagement, Points
from controller.password import *
from controller.streaksManagement import streaks_manager
from concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor(max_workers=5)
def google_search(query, api_key, cx):
url = f"https://www.googleapis.com/customsearch/v1?q={query}&key={api_key}&cx={cx}"
response = requests.get(url)
if response.status_code == 200:
search_results = response.json()
print(search_results)
return search_results
else:
print(f"Error: {response.status_code}")
return None
def generate_embedding_for_user_resume(data,user_id):
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("nomic-ai/nomic-embed-text-v1", trust_remote_code=True)
def get_embedding(data, precision="float32"):
return model.encode(data, precision=precision)
from pinecone import Vector
def create_docs_with_vector_embeddings(bson_float32, data):
docs = []
for i, (bson_f32_emb, text) in enumerate(zip(bson_float32, data)):
doc =Vector(
id=f"{i}",
values= bson_f32_emb.tolist(),
metadata={"text":text,"user_id":user_id},
)
docs.append(doc)
return docs
float32_embeddings = get_embedding(data, "float32")
docs = create_docs_with_vector_embeddings(float32_embeddings, data)
return docs
def insert_embeddings_into_pinecone_database(doc,api_key,name_space):
from pinecone import Pinecone
pc = Pinecone(api_key=api_key)
index_name = "resumes"
index = pc.Index(index_name)
upsert_response = index.upsert(namespace=name_space,vectors=doc)
return upsert_response
def query_vector_database(query,api_key,name_space):
from pinecone import Pinecone
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("nomic-ai/nomic-embed-text-v1", trust_remote_code=True)
ret=[]
pc = Pinecone(api_key=api_key)
index_name = "resumes"
index = pc.Index(index_name)
# Define a function to generate embeddings in multiple precisions
def get_embedding(data, precision="float32"):
return model.encode(data, precision=precision)
query_embedding = get_embedding(query, precision="float32")
response = index.query(
namespace=name_space,
vector=query_embedding.tolist(),
top_k=5,
include_metadata=True
)
for doc in response['matches']:
ret.append(doc['metadata']['text'])
return ret
def delete_vector_namespace(name_space,api_key):
from pinecone import Pinecone
pc = Pinecone(api_key=api_key)
index_name = "resumes"
index = pc.Index(index_name)
response = index.delete(delete_all=True,namespace=name_space)
return response
def split_text_into_chunks(text, chunk_size=400):
# Split the text into words using whitespace.
words = text.split()
# Group the words into chunks of size 'chunk_size'.
chunks = [' '.join(words[i:i + chunk_size]) for i in range(0, len(words), chunk_size)]
return chunks
def create_user(db_uri: str, db_name: str, collection_name: str, document: dict) -> str:
"""
Inserts a new document into the specified MongoDB collection.
Parameters:
db_uri (str): MongoDB connection URI.
db_name (str): Name of the database.
collection_name (str): Name of the collection.
document (dict): The document to insert.
Returns:
str: The ID of the inserted document.
"""
# Connect to MongoDB
client = MongoClient(db_uri)
db = client[db_name]
collection = db[collection_name]
# Insert the document
s = collection.find_one({"email":document.get('email')})
password = hash_password(document.get('password'))
document['password']= password
document['date_Joined'] = datetime.now()
if s==None:
result = collection.insert_one(document)
streaks_doc={}
streaks_doc['user_id'] = str(result.inserted_id)
# executor.submit(streaks_manager,db_uri=db_uri,document=streaks_doc)
streaks_manager(db_uri=db_uri,document=streaks_doc)
return str(result.inserted_id)
else:
client.close()
return False
# Close the connection
def create_questionaire(db_uri: str, db_name: str, collection_name: str, document: dict) -> str:
"""
Inserts a new document into the specified MongoDB collection.
Parameters:
db_uri (str): MongoDB connection URI.
db_name (str): Name of the database.
collection_name (str): Name of the collection.
document (dict): The document to insert.
Returns:
str: The ID of the inserted document.
"""
# Connect to MongoDB
client = MongoClient(db_uri)
db = client[db_name]
collection = db[collection_name]
# Insert the document
result= collection.find_one_and_replace(filter={"userId":document.get("userId")},replacement=document)
print(result)
if result==None:
# give points for the completness of a profile
completProfilePoints= Points(userId=document.get('userId'),platformEngagement=PlatformEngagement(profile_completion=50))
wasCreated= create_points_func(document=completProfilePoints)
result = collection.insert_one(document)
print(result)
return str(result.inserted_id)
client.close()
return str(result)
# Close the connection
def login_user(db_uri: str, db_name: str, collection_name: str, document: dict) -> str:
streaks_doc={}
"""
Inserts a new document into the specified MongoDB collection.
Parameters:
db_uri (str): MongoDB connection URI.
db_name (str): Name of the database.
collection_name (str): Name of the collection.
document (dict): The document to insert.
Returns:
str: The ID of the inserted document.
"""
# Connect to MongoDB
client = MongoClient(db_uri)
db = client[db_name]
collection = db[collection_name]
# Insert the document
s = collection.find_one({"email":document["email"]})
print(s)
print(document.get('email'))
if s==None:
return False
else:
if check_password(password=document['password'],hashed_password=s['password']):
streaks_doc['user_id'] = str(s["_id"])
# executor.submit(streaks_manager,db_uri=db_uri,document=streaks_doc)
streaks_manager(db_uri=db_uri,document=streaks_doc)
return str(s['_id'])
else:
return False
# Close the connection
def user_details_func(db_uri: str, document: Dict) -> Optional[Dict]:
"""
Retrieve and process user details from MongoDB collections.
Args:
db_uri (str): MongoDB connection URI
document (dict): Document containing user_id
Returns:
dict: Processed user details or None if user not found
"""
streaks_doc = {}
# Connect to MongoDB
client = MongoClient(db_uri)
db = client["crayonics"]
# Define collections
users_collection = db["users"]
streaks_collection = db["Streaks"]
questionaire_collection = db["Questionaire"]
# Find user document
user_id = document.get("user_id")
user_doc = users_collection.find_one({"_id": ObjectId(user_id)})
if not user_doc:
return None
# Prepare base user document
user_doc['userId'] = str(user_doc['_id'])
user_doc.pop('_id')
user_doc.pop('password', None) # Use default None in case password doesn't exist
# Get streaks data
streaks_collection_doc = streaks_collection.find_one({"user_id": user_id})
streaks_doc['user_id'] = user_id
# Call streaks_manager (assuming this function exists elsewhere)
# executor.submit(streaks_manager,db_uri=db_uri,document=streaks_doc)
streaks_manager(db_uri=db_uri, document=streaks_doc)
if streaks_collection_doc:
streaks_collection_doc.pop("_id", None)
streaks_collection_doc.pop("user_id", None)
user_doc['streak_dates'] = streaks_collection_doc.get('streak_dates', [])
# Try to get questionnaire data
questionaire_doc = questionaire_collection.find_one({"userId": user_id})
if questionaire_doc:
print(f"in questionaire retrieval:")
try:
questionaire_doc.pop("_id", None)
questionaire_doc.pop("userId", None)
user_doc['career_questions'] = questionaire_doc
except Exception as e:
# If questionnaire fails, continue with what we have
print(f"Error in questionaire retrieval: {str(e)}")
print(questionaire_doc)
pass
client.close()
return user_doc
|