Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import fitz # PyMuPDF
|
| 3 |
import nltk
|
|
@@ -5,6 +205,10 @@ from nltk.tokenize import word_tokenize
|
|
| 5 |
import google.generativeai as genai
|
| 6 |
import faiss
|
| 7 |
import numpy as np
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
import os
|
| 9 |
|
| 10 |
nltk.download('punkt_tab')
|
|
@@ -12,28 +216,6 @@ nltk.download('punkt')
|
|
| 12 |
nltk.download('wordnet')
|
| 13 |
nltk.download('omw-1.4')
|
| 14 |
|
| 15 |
-
# # Ensure NLTK resources are downloaded
|
| 16 |
-
# # Set NLTK data path to a writable directory
|
| 17 |
-
# nltk_data_dir = "/tmp/nltk_data"
|
| 18 |
-
# os.environ["NLTK_DATA"] = nltk_data_dir
|
| 19 |
-
# nltk.data.path.append(nltk_data_dir)
|
| 20 |
-
|
| 21 |
-
# # Ensure NLTK resources are downloaded
|
| 22 |
-
# try:
|
| 23 |
-
# # Check if punkt is already downloaded
|
| 24 |
-
# if not os.path.exists(os.path.join(nltk_data_dir, "tokenizers/punkt")):
|
| 25 |
-
# st.write("Downloading NLTK punkt data...")
|
| 26 |
-
# nltk.download("punkt", download_dir=nltk_data_dir)
|
| 27 |
-
# else:
|
| 28 |
-
# st.write("NLTK punkt data already exists.")
|
| 29 |
-
# except Exception as e:
|
| 30 |
-
# st.error(f"Error downloading NLTK data: {e}")
|
| 31 |
-
# st.stop()
|
| 32 |
-
|
| 33 |
-
# Configure Gemini API (use environment variable or Streamlit secrets for API key)
|
| 34 |
-
|
| 35 |
-
# GEMINI_API_KEY = "" # Replace with your actual API key
|
| 36 |
-
# genai.configure(api_key=GEMINI_API_KEY)
|
| 37 |
|
| 38 |
genai.configure(api_key=os.environ["AI_API_KEY"])
|
| 39 |
gemini_model = genai.GenerativeModel('gemini-1.5-flash')
|
|
@@ -110,10 +292,8 @@ def generate_answer(query, context_chunks):
|
|
| 110 |
prompt = f"""
|
| 111 |
Context:
|
| 112 |
{context}
|
| 113 |
-
|
| 114 |
Question:
|
| 115 |
{query}
|
| 116 |
-
|
| 117 |
Answer the question based on the context provided above.
|
| 118 |
"""
|
| 119 |
response = gemini_model.generate_content(prompt)
|
|
@@ -133,7 +313,7 @@ with st.sidebar:
|
|
| 133 |
</style>
|
| 134 |
'''
|
| 135 |
st.markdown(hide_st_style, unsafe_allow_html=True)
|
| 136 |
-
page = st.radio("Options", ["Home", "Privacy Policy"], label_visibility="collapsed")
|
| 137 |
|
| 138 |
if page == "Home":
|
| 139 |
st.title("Gemini RAG Application")
|
|
@@ -196,4 +376,135 @@ if page == "Home":
|
|
| 196 |
else:
|
| 197 |
st.error("No chunks generated from the text.")
|
| 198 |
else:
|
| 199 |
-
st.error("No text extracted. The document might be image-based or corrupted.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# import streamlit as st
|
| 2 |
+
# import fitz # PyMuPDF
|
| 3 |
+
# import nltk
|
| 4 |
+
# from nltk.tokenize import word_tokenize
|
| 5 |
+
# import google.generativeai as genai
|
| 6 |
+
# import faiss
|
| 7 |
+
# import numpy as np
|
| 8 |
+
# import os
|
| 9 |
+
|
| 10 |
+
# nltk.download('punkt_tab')
|
| 11 |
+
# nltk.download('punkt')
|
| 12 |
+
# nltk.download('wordnet')
|
| 13 |
+
# nltk.download('omw-1.4')
|
| 14 |
+
|
| 15 |
+
# # # Ensure NLTK resources are downloaded
|
| 16 |
+
# # # Set NLTK data path to a writable directory
|
| 17 |
+
# # nltk_data_dir = "/tmp/nltk_data"
|
| 18 |
+
# # os.environ["NLTK_DATA"] = nltk_data_dir
|
| 19 |
+
# # nltk.data.path.append(nltk_data_dir)
|
| 20 |
+
|
| 21 |
+
# # # Ensure NLTK resources are downloaded
|
| 22 |
+
# # try:
|
| 23 |
+
# # # Check if punkt is already downloaded
|
| 24 |
+
# # if not os.path.exists(os.path.join(nltk_data_dir, "tokenizers/punkt")):
|
| 25 |
+
# # st.write("Downloading NLTK punkt data...")
|
| 26 |
+
# # nltk.download("punkt", download_dir=nltk_data_dir)
|
| 27 |
+
# # else:
|
| 28 |
+
# # st.write("NLTK punkt data already exists.")
|
| 29 |
+
# # except Exception as e:
|
| 30 |
+
# # st.error(f"Error downloading NLTK data: {e}")
|
| 31 |
+
# # st.stop()
|
| 32 |
+
|
| 33 |
+
# # Configure Gemini API (use environment variable or Streamlit secrets for API key)
|
| 34 |
+
|
| 35 |
+
# # GEMINI_API_KEY = "" # Replace with your actual API key
|
| 36 |
+
# # genai.configure(api_key=GEMINI_API_KEY)
|
| 37 |
+
|
| 38 |
+
# genai.configure(api_key=os.environ["AI_API_KEY"])
|
| 39 |
+
# gemini_model = genai.GenerativeModel('gemini-1.5-flash')
|
| 40 |
+
|
| 41 |
+
# # Function to extract text from the uploaded PDF using PyMuPDF (fitz)
|
| 42 |
+
# def extract_text_from_pdf(pdf_file):
|
| 43 |
+
# try:
|
| 44 |
+
# doc = fitz.open(stream=pdf_file.read(), filetype="pdf")
|
| 45 |
+
# text = ""
|
| 46 |
+
# for page_num in range(len(doc)):
|
| 47 |
+
# page = doc.load_page(page_num)
|
| 48 |
+
# text += page.get_text()
|
| 49 |
+
# return text
|
| 50 |
+
# except Exception as e:
|
| 51 |
+
# st.error(f"Error extracting text from PDF: {e}")
|
| 52 |
+
# return None
|
| 53 |
+
|
| 54 |
+
# # Function to split text into overlapping chunks using NLTK tokenization
|
| 55 |
+
# def split_text_into_chunks(text, chunk_size=500, overlap=100):
|
| 56 |
+
# try:
|
| 57 |
+
# words = word_tokenize(text)
|
| 58 |
+
# chunks = []
|
| 59 |
+
# for i in range(0, len(words), chunk_size - overlap):
|
| 60 |
+
# chunk = " ".join(words[i:i + chunk_size])
|
| 61 |
+
# chunks.append(chunk)
|
| 62 |
+
# return chunks
|
| 63 |
+
# except Exception as e:
|
| 64 |
+
# st.error(f"Error splitting text into chunks: {e}")
|
| 65 |
+
# return []
|
| 66 |
+
|
| 67 |
+
# # Function to generate embeddings for a list of text chunks
|
| 68 |
+
# def generate_embeddings(chunks, title="PDF Document"):
|
| 69 |
+
# embeddings = []
|
| 70 |
+
# for chunk in chunks:
|
| 71 |
+
# try:
|
| 72 |
+
# embedding = genai.embed_content(
|
| 73 |
+
# model="models/embedding-001",
|
| 74 |
+
# content=chunk,
|
| 75 |
+
# task_type="retrieval_document",
|
| 76 |
+
# title=title
|
| 77 |
+
# )
|
| 78 |
+
# embeddings.append(embedding["embedding"])
|
| 79 |
+
# except Exception as e:
|
| 80 |
+
# st.error(f"Error generating embedding for chunk: {e}")
|
| 81 |
+
# return embeddings
|
| 82 |
+
|
| 83 |
+
# # Function to store embeddings in FAISS
|
| 84 |
+
# def store_embeddings_in_faiss(embeddings):
|
| 85 |
+
# try:
|
| 86 |
+
# embeddings_array = np.array(embeddings).astype('float32')
|
| 87 |
+
# dimension = embeddings_array.shape[1]
|
| 88 |
+
# index = faiss.IndexFlatL2(dimension)
|
| 89 |
+
# index.add(embeddings_array)
|
| 90 |
+
# return index
|
| 91 |
+
# except Exception as e:
|
| 92 |
+
# st.error(f"Error storing embeddings in FAISS: {e}")
|
| 93 |
+
# return None
|
| 94 |
+
|
| 95 |
+
# # Function to retrieve relevant chunks using FAISS
|
| 96 |
+
# def retrieve_relevant_chunks(query_embedding, index, chunks, top_k=3):
|
| 97 |
+
# try:
|
| 98 |
+
# query_embedding = np.array(query_embedding).astype('float32').reshape(1, -1)
|
| 99 |
+
# distances, indices = index.search(query_embedding, top_k)
|
| 100 |
+
# relevant_chunks = [chunks[i] for i in indices[0]]
|
| 101 |
+
# return relevant_chunks
|
| 102 |
+
# except Exception as e:
|
| 103 |
+
# st.error(f"Error retrieving relevant chunks: {e}")
|
| 104 |
+
# return []
|
| 105 |
+
|
| 106 |
+
# # Function to generate an answer using Gemini API
|
| 107 |
+
# def generate_answer(query, context_chunks):
|
| 108 |
+
# try:
|
| 109 |
+
# context = "\n".join(context_chunks)
|
| 110 |
+
# prompt = f"""
|
| 111 |
+
# Context:
|
| 112 |
+
# {context}
|
| 113 |
+
|
| 114 |
+
# Question:
|
| 115 |
+
# {query}
|
| 116 |
+
|
| 117 |
+
# Answer the question based on the context provided above.
|
| 118 |
+
# """
|
| 119 |
+
# response = gemini_model.generate_content(prompt)
|
| 120 |
+
# return response.text
|
| 121 |
+
# except Exception as e:
|
| 122 |
+
# st.error(f"Error generating answer: {e}")
|
| 123 |
+
# return "Unable to generate an answer due to an error."
|
| 124 |
+
|
| 125 |
+
# # Streamlit UI
|
| 126 |
+
# with st.sidebar:
|
| 127 |
+
# st.title("Navigation")
|
| 128 |
+
# hide_st_style = '''
|
| 129 |
+
# <style>
|
| 130 |
+
# MainMenu {visibility: hidden;}
|
| 131 |
+
# footer {visibility: hidden;}
|
| 132 |
+
# header {visibility: hidden;}
|
| 133 |
+
# </style>
|
| 134 |
+
# '''
|
| 135 |
+
# st.markdown(hide_st_style, unsafe_allow_html=True)
|
| 136 |
+
# page = st.radio("Options", ["Home", "Privacy Policy"], label_visibility="collapsed")
|
| 137 |
+
|
| 138 |
+
# if page == "Home":
|
| 139 |
+
# st.title("Gemini RAG Application")
|
| 140 |
+
# st.markdown("Upload a PDF document and ask questions to get answers using Google's Gemini API.")
|
| 141 |
+
|
| 142 |
+
# pdf_file = st.file_uploader("Choose a PDF file", type="pdf")
|
| 143 |
+
|
| 144 |
+
# if pdf_file is not None:
|
| 145 |
+
# with st.spinner("Extracting text..."):
|
| 146 |
+
# extracted_text = extract_text_from_pdf(pdf_file)
|
| 147 |
+
|
| 148 |
+
# if extracted_text:
|
| 149 |
+
# with st.spinner("Splitting text into overlapping chunks..."):
|
| 150 |
+
# chunks = split_text_into_chunks(extracted_text, chunk_size=500, overlap=100)
|
| 151 |
+
|
| 152 |
+
# if chunks:
|
| 153 |
+
# with st.status(f"Total chunks: {len(chunks)}"):
|
| 154 |
+
# for i, chunk in enumerate(chunks):
|
| 155 |
+
# st.subheader(f"Chunk {i + 1}")
|
| 156 |
+
# st.text_area(f"Chunk {i + 1} Text", chunk, height=200, key=f"chunk_{i}")
|
| 157 |
+
|
| 158 |
+
# with st.spinner("Generating embeddings..."):
|
| 159 |
+
# embeddings = generate_embeddings(chunks)
|
| 160 |
+
|
| 161 |
+
# if embeddings:
|
| 162 |
+
# with st.spinner("Storing embeddings in FAISS..."):
|
| 163 |
+
# index = store_embeddings_in_faiss(embeddings)
|
| 164 |
+
|
| 165 |
+
# if index:
|
| 166 |
+
# st.success("Embeddings have been successfully stored in the FAISS vector database.")
|
| 167 |
+
|
| 168 |
+
# query = st.text_input("Enter your question:")
|
| 169 |
+
# if query:
|
| 170 |
+
# with st.spinner("Generating query embedding..."):
|
| 171 |
+
# query_embedding = genai.embed_content(
|
| 172 |
+
# model="models/embedding-001",
|
| 173 |
+
# content=query,
|
| 174 |
+
# task_type="retrieval_query"
|
| 175 |
+
# )["embedding"]
|
| 176 |
+
|
| 177 |
+
# with st.spinner("Retrieving relevant chunks..."):
|
| 178 |
+
# relevant_chunks = retrieve_relevant_chunks(query_embedding, index, chunks, top_k=3)
|
| 179 |
+
|
| 180 |
+
# if relevant_chunks:
|
| 181 |
+
# with st.status("### Relevant Context Chunks:"):
|
| 182 |
+
# for i, chunk in enumerate(relevant_chunks):
|
| 183 |
+
# st.subheader(f"Chunk {i + 1}")
|
| 184 |
+
# st.text_area(f"Relevant Chunk {i + 1} Text", chunk, height=200, key=f"relevant_chunk_{i}")
|
| 185 |
+
|
| 186 |
+
# with st.spinner("Generating answer..."):
|
| 187 |
+
# answer = generate_answer(query, relevant_chunks)
|
| 188 |
+
# st.write("### Answer:")
|
| 189 |
+
# st.write(answer)
|
| 190 |
+
# else:
|
| 191 |
+
# st.warning("No relevant chunks found.")
|
| 192 |
+
# else:
|
| 193 |
+
# st.error("Failed to store embeddings in FAISS.")
|
| 194 |
+
# else:
|
| 195 |
+
# st.error("Failed to generate embeddings.")
|
| 196 |
+
# else:
|
| 197 |
+
# st.error("No chunks generated from the text.")
|
| 198 |
+
# else:
|
| 199 |
+
# st.error("No text extracted. The document might be image-based or corrupted.")
|
| 200 |
+
|
| 201 |
import streamlit as st
|
| 202 |
import fitz # PyMuPDF
|
| 203 |
import nltk
|
|
|
|
| 205 |
import google.generativeai as genai
|
| 206 |
import faiss
|
| 207 |
import numpy as np
|
| 208 |
+
from pymongo import MongoClient
|
| 209 |
+
from nltk.tokenize import sent_tokenize
|
| 210 |
+
import json
|
| 211 |
+
from pymongo.errors import ConnectionFailure, OperationFailure
|
| 212 |
import os
|
| 213 |
|
| 214 |
nltk.download('punkt_tab')
|
|
|
|
| 216 |
nltk.download('wordnet')
|
| 217 |
nltk.download('omw-1.4')
|
| 218 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
genai.configure(api_key=os.environ["AI_API_KEY"])
|
| 221 |
gemini_model = genai.GenerativeModel('gemini-1.5-flash')
|
|
|
|
| 292 |
prompt = f"""
|
| 293 |
Context:
|
| 294 |
{context}
|
|
|
|
| 295 |
Question:
|
| 296 |
{query}
|
|
|
|
| 297 |
Answer the question based on the context provided above.
|
| 298 |
"""
|
| 299 |
response = gemini_model.generate_content(prompt)
|
|
|
|
| 313 |
</style>
|
| 314 |
'''
|
| 315 |
st.markdown(hide_st_style, unsafe_allow_html=True)
|
| 316 |
+
page = st.radio("Options", ["Home","MongoDb", "Privacy Policy"], label_visibility="collapsed")
|
| 317 |
|
| 318 |
if page == "Home":
|
| 319 |
st.title("Gemini RAG Application")
|
|
|
|
| 376 |
else:
|
| 377 |
st.error("No chunks generated from the text.")
|
| 378 |
else:
|
| 379 |
+
st.error("No text extracted. The document might be image-based or corrupted.")
|
| 380 |
+
|
| 381 |
+
if page == "MongoDb":
|
| 382 |
+
try:
|
| 383 |
+
client = MongoClient(os.environ["MONGO_API_KEY"])
|
| 384 |
+
db = client['resume_database']
|
| 385 |
+
collection = db['resumes']
|
| 386 |
+
st.success("Connected to MongoDB Atlas!")
|
| 387 |
+
except ConnectionFailure:
|
| 388 |
+
st.error("Failed to connect to MongoDB Atlas. Please check your connection string.")
|
| 389 |
+
st.stop()
|
| 390 |
+
|
| 391 |
+
# Function to extract text from the uploaded PDF
|
| 392 |
+
def extract_text_from_pdf(pdf_bytes):
|
| 393 |
+
"""Extract text from the PDF."""
|
| 394 |
+
try:
|
| 395 |
+
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
|
| 396 |
+
return ''.join(page.get_text() for page in doc)
|
| 397 |
+
except Exception as e:
|
| 398 |
+
st.error(f"Error extracting text from PDF: {e}")
|
| 399 |
+
return None
|
| 400 |
+
|
| 401 |
+
# Function to chunk the resume text into sections based on keywords
|
| 402 |
+
def chunk_resume_text(resume_text):
|
| 403 |
+
"""Chunk the resume text into sections based on keywords."""
|
| 404 |
+
sections = {
|
| 405 |
+
'education': [],
|
| 406 |
+
'experience': [],
|
| 407 |
+
'technical_skills': [],
|
| 408 |
+
'projects': [],
|
| 409 |
+
'certifications': []
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
current_section = None
|
| 413 |
+
for sentence in sent_tokenize(resume_text):
|
| 414 |
+
sentence_upper = sentence.upper()
|
| 415 |
+
if "EDUCATION" in sentence_upper:
|
| 416 |
+
current_section = 'education'
|
| 417 |
+
elif "EXPERIENCE" in sentence_upper:
|
| 418 |
+
current_section = 'experience'
|
| 419 |
+
elif "TECHNICAL SKILLS" in sentence_upper:
|
| 420 |
+
current_section = 'technical_skills'
|
| 421 |
+
elif "PROJECTS" in sentence_upper:
|
| 422 |
+
current_section = 'projects'
|
| 423 |
+
elif "CERTIFICATIONS" in sentence_upper:
|
| 424 |
+
current_section = 'certifications'
|
| 425 |
+
|
| 426 |
+
if current_section:
|
| 427 |
+
sections[current_section].append(sentence.strip())
|
| 428 |
+
|
| 429 |
+
return sections
|
| 430 |
+
|
| 431 |
+
# Function to store the extracted resume data into MongoDB
|
| 432 |
+
def store_resume_in_mongodb(pdf_bytes, user_id):
|
| 433 |
+
"""Store the extracted and chunked resume data in MongoDB."""
|
| 434 |
+
try:
|
| 435 |
+
resume_text = extract_text_from_pdf(pdf_bytes)
|
| 436 |
+
if not resume_text:
|
| 437 |
+
return None
|
| 438 |
+
|
| 439 |
+
chunked_resume = chunk_resume_text(resume_text)
|
| 440 |
+
|
| 441 |
+
resume_data = {
|
| 442 |
+
'user_id': user_id,
|
| 443 |
+
'resume': chunked_resume
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
result = collection.insert_one(resume_data)
|
| 447 |
+
return result.inserted_id
|
| 448 |
+
except OperationFailure as e:
|
| 449 |
+
st.error(f"Error storing data in MongoDB: {e}")
|
| 450 |
+
return None
|
| 451 |
+
|
| 452 |
+
# Function to fetch resume data from MongoDB
|
| 453 |
+
def fetch_resume_from_mongodb(user_id):
|
| 454 |
+
"""Fetch resume data from MongoDB based on user_id."""
|
| 455 |
+
try:
|
| 456 |
+
resume_data = collection.find_one({"user_id": user_id})
|
| 457 |
+
return resume_data
|
| 458 |
+
except OperationFailure as e:
|
| 459 |
+
st.error(f"Error fetching data from MongoDB: {e}")
|
| 460 |
+
return None
|
| 461 |
+
|
| 462 |
+
# Streamlit UI
|
| 463 |
+
st.title("Resume Extractor and MongoDB Storage")
|
| 464 |
+
st.write("Upload a PDF to extract text and store it in MongoDB.")
|
| 465 |
+
|
| 466 |
+
# Step 1: Upload PDF and store it in MongoDB
|
| 467 |
+
with st.expander("Step 1: Upload and Store Resume"):
|
| 468 |
+
pdf_file = st.file_uploader("Upload Resume PDF", type="pdf")
|
| 469 |
+
|
| 470 |
+
if pdf_file:
|
| 471 |
+
# Extract text and display the tokenized sentences
|
| 472 |
+
pdf_bytes = pdf_file.read()
|
| 473 |
+
resume_text = extract_text_from_pdf(pdf_bytes)
|
| 474 |
+
|
| 475 |
+
if resume_text:
|
| 476 |
+
tokenized_sentences = sent_tokenize(resume_text)
|
| 477 |
+
|
| 478 |
+
st.subheader("Tokenized Sentences")
|
| 479 |
+
for idx, sentence in enumerate(tokenized_sentences):
|
| 480 |
+
st.write(f"{idx + 1}. {sentence}")
|
| 481 |
+
|
| 482 |
+
# User ID input
|
| 483 |
+
user_id = st.text_input("Enter User ID", "12345")
|
| 484 |
+
|
| 485 |
+
if st.button("Store Resume in MongoDB"):
|
| 486 |
+
with st.spinner("Storing resume in MongoDB..."):
|
| 487 |
+
inserted_id = store_resume_in_mongodb(pdf_bytes, user_id)
|
| 488 |
+
if inserted_id:
|
| 489 |
+
st.success(f"Resume stored successfully with ID: {inserted_id}")
|
| 490 |
+
|
| 491 |
+
# Step 2: Fetch resume data from MongoDB
|
| 492 |
+
with st.expander("Step 2: Retrieve Resume Data"):
|
| 493 |
+
st.write("Enter the User ID to fetch the resume data from MongoDB.")
|
| 494 |
+
|
| 495 |
+
# User input for user_id
|
| 496 |
+
user_id_to_fetch = st.text_input("Enter User ID to fetch data", "12345")
|
| 497 |
+
|
| 498 |
+
if st.button("Fetch Resume Data"):
|
| 499 |
+
with st.spinner("Fetching resume data..."):
|
| 500 |
+
resume_data = fetch_resume_from_mongodb(user_id_to_fetch)
|
| 501 |
+
|
| 502 |
+
if resume_data:
|
| 503 |
+
# Display resume data in JSON format
|
| 504 |
+
st.subheader(f"Resume Data for User ID: {user_id_to_fetch}")
|
| 505 |
+
|
| 506 |
+
# Convert MongoDB result to JSON string and display it
|
| 507 |
+
json_data = json.dumps(resume_data, default=str, indent=4) # default=str to handle ObjectId
|
| 508 |
+
st.json(json_data) # Display JSON in a readable format
|
| 509 |
+
else:
|
| 510 |
+
st.warning(f"No resume found for User ID: {user_id_to_fetch}")
|