Spaces:
Running
Running
File size: 9,066 Bytes
3c12613 d4296c2 3c12613 9fe38b7 98b1ce4 9fe38b7 dc7e67e 3c12613 66c82c6 3c12613 d4296c2 3c12613 dc7e67e d4296c2 dc7e67e d4296c2 dc7e67e d4296c2 dc7e67e 3c12613 98b1ce4 3c12613 dc7e67e 0a149f9 dc7e67e 3c12613 d4296c2 9fe38b7 d4296c2 9fe38b7 3c12613 9fe38b7 3c12613 9fe38b7 d4296c2 3c12613 dc7e67e d4296c2 dc7e67e d4296c2 dc7e67e d4296c2 42ec9ca d4296c2 |
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 |
from io import BytesIO
from dotenv import load_dotenv
import os
from utils import google_search,split_text_into_chunks,insert_embeddings_into_pinecone_database,query_vector_database,generate_embedding_for_user_resume,delete_vector_namespace,create_user,login_user
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse
import docx
import fitz
from scraper import scrapeCourse
import asyncio
from google import genai
from pydantic import BaseModel
load_dotenv()
CX = os.getenv("SEARCH_ENGINE_ID")
API_KEY = os.getenv("GOOGLE_API_KEY")
PINECONE_API_KEY=os.getenv("PINECONE_API_KEY")
GEMINI_API_KEY=os.getenv("GEMINI_API_KEY")
MONGO_URI=os.getenv("MONGO_URI")
app = FastAPI()
import re
class UserBody(BaseModel):
Email:str
Password:str
class AiAnalysis(BaseModel):
UserId:str
Query:str
class UserCourse(BaseModel):
EmploymentStatus:str
InterimRole:str
DesiredRole:str
Motivation:str
LearningPreference:str
HoursSpentLearning:str
Challenges:str
TimeframeToAchieveDreamRole:str
userId:str
class CourseRecommendation(BaseModel):
CourseName: str
CompletionTime: str
def extract_course_info(text: str) -> CourseRecommendation:
# Example regex patterns – adjust these as needed based on the response format.
course_pattern =r'"coursename":\s*"([^"]+)"'
time_pattern = r"(\d+\s*-\s*\d+\s*months)"
course_match = re.search(course_pattern, text)
time_match = re.search(time_pattern, text)
coursename = course_match.group(1).strip() if course_match else "Unknown"
completiontime = time_match.group(0).strip() if time_match else "Unknown"
return CourseRecommendation(CourseName=coursename, CompletionTime=completiontime)
@app.get("/get/course")
def get_course(query):
# Example search query
results = google_search(query, API_KEY, CX)
content=[]
if results:
for item in results.get('items', []):
title = item.get('title')
link = item.get('link')
snippet = item.get('snippet')
content_structure={}
content_structure["Course_Title"]=title
content_structure["Course_Link"]=link
content_structure["Course_Snippet"]= snippet
content_structure["Scraped_Course_Details"]= scrapeCourse(url=link)
content.append(content_structure)
return JSONResponse(content,status_code=200)
def get_course_func(query):
# Example search query
results = google_search(query, API_KEY, CX)
content=[]
if results:
for item in results.get('items', []):
title = item.get('title')
link = item.get('link')
snippet = item.get('snippet')
content_structure={}
content_structure["Course_Title"]=title
content_structure["Course_Link"]=link
content_structure["Course_Snippet"]= snippet
content_structure["Scraped_Course_Details"]= scrapeCourse(url=link)
content.append(content_structure)
return content
@app.post("/upload")
async def upload_file(user_id,file: UploadFile = File(...)):
content = await file.read() # Read the file content (this will return bytes)
sentences=[]
print(f"File name: {file.filename}")
print(f"File content type: {file.content_type}")
print(f"File size: {file.size} bytes")
if "pdf" == file.filename.split('.')[1]:
pdf_document = fitz.open(stream=BytesIO(content), filetype="pdf")
extracted_text = ""
for page_num in range(pdf_document.page_count):
page = pdf_document.load_page(page_num)
extracted_text += page.get_text()
elif "docx" == file.filename.split('.')[1]:
docx_file = BytesIO(content)
doc = docx.Document(docx_file)
extracted_text = ""
for para in doc.paragraphs:
extracted_text += para.text + "\n"
sentences = split_text_into_chunks(extracted_text,chunk_size=200)
docs = generate_embedding_for_user_resume(data=sentences,user_id=file.filename)
response= insert_embeddings_into_pinecone_database(doc=docs,api_key=PINECONE_API_KEY,name_space=user_id)
return {"filename": file.filename,"response":str(response) }
@app.post("/ask")
def ask_ai_about_resume(req:AiAnalysis):
# Retrieve context from your vector database
context = query_vector_database(query=req.Query, api_key=PINECONE_API_KEY, name_space=req.UserId)
# Ensure that an event loop is present in this thread.
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# Create the Gemini client after the event loop is set up
client = genai.Client(api_key=GEMINI_API_KEY)
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=f"""
Answer this question using the context provided:
question: {req.Query}
context: {context}
"""
)
return {"Ai_Response":response.text}
@app.post("/recommend/courses")
def ask_ai_about_resume(request:UserCourse):
"""
User Profile Information for Career Development
This section defines the parameters used to gather information from the user to understand their current employment situation, learning preferences, challenges, and goals related to achieving their dream role.
Parameters:
employment_status (str):
A description of the user's current employment situation (e.g., "unemployed", "part-time", "full-time").
interim_role (str):
Indicates whether the user is willing to prepare for an interim role to gain experience and income while pursuing their dream role (e.g., "yes" or "no").
desired_role (str):
The role the user ultimately wishes to obtain (e.g., "Full-Stack Developer", "Data Scientist").
motivation (str):
The user's reasons or motivations for pursuing the desired role.
learning_preference (str):
Describes how the user prefers to learn new skills (e.g., "online courses", "self-study", "bootcamp").
hours_spent_learning (str or int):
The number of hours per day the user can dedicate to learning.
challenges (str):
Outlines any obstacles or challenges the user faces in reaching their dream role.
timeframe_to_achieve_dream_role (str):
The ideal timeframe the user has in mind for achieving their dream role (e.g., "6-12 months").
user_id (str):
A unique identifier for the user; used to query personalized data from a vector database or other services.
"""
# Retrieve context from your vector database
# Ensure that an event loop is present in this thread.
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# Create the Gemini client after the event loop is set up
client = genai.Client(api_key=GEMINI_API_KEY)
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=f"""
please respond with a JSON object that contains the following keys as a response:
- "coursename": the name of the recommended course,
- "completiontime": an estimate of how long it would take to complete the course.
Do not include any extra text.
Recommend a course using this information below :
Which of the following best describes you?: {request.EmploymentStatus}
Would you like to prepare for an interim role to gain experience and income while pursuing your dream job?: {request.InterimRole}
What is your desired role?: {request.DesiredRole}
Why do you want to achieve this desired role?: {request.Motivation}
How do you prefer to learn new skills?: {request.LearningPreference}
How many hours per day can you dedicate to learning?: {request.HoursSpentLearning}
What are the biggest challenges or obstacles you face in reaching your dream role?: {request.Challenges}
What is your ideal timeframe for achieving your dream role?: {request.TimeframeToAchieveDreamRole}
"""
)
course_info = extract_course_info(response.text)
courses = get_course_func(query=course_info.CourseName)
return {"CourseInfo":course_info,"Courses":courses}
@app.post("/login")
def login(user:UserBody):
user ={"email":user.Email,"password":user.Password}
user_id= login_user(db_uri=MONGO_URI,db_name="crayonics",collection_name="users",document=user)
return {"user_id":user_id}
@app.post("/signup")
def signUp(user:UserBody):
user ={"email":user.Email,"password":user.Password}
user_id= create_user(db_uri=MONGO_URI,db_name="crayonics",collection_name="users",document=user)
return {"user_id":user_id} |