tjwrld commited on
Commit
9e21a30
·
verified ·
1 Parent(s): c9df7b8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -270
app.py CHANGED
@@ -1,203 +1,3 @@
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
@@ -380,27 +180,29 @@ if page == "Home":
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': [],
@@ -410,8 +212,8 @@ if page == "MongoDb":
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:
@@ -423,88 +225,74 @@ if page == "MongoDb":
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}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import fitz # PyMuPDF
3
  import nltk
 
180
 
181
  if page == "MongoDb":
182
  try:
183
+ client = MongoClient("mongodb+srv://gojochan31:simple1234@cluster0.b0msc.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0")
184
  db = client['resume_database']
185
  collection = db['resumes']
186
  st.success("Connected to MongoDB Atlas!")
187
  except ConnectionFailure:
188
+ st.error("Failed to connect to MongoDB. Check your connection string.")
189
  st.stop()
190
 
 
191
  def extract_text_from_pdf(pdf_bytes):
192
+ """Extract text from a PDF file."""
193
  try:
194
+ doc = fitz.open(stream=pdf_bytes, filetype="pdf")
195
+ text = ""
196
+ for page in doc:
197
+ text += page.get_text()
198
+ return text
199
  except Exception as e:
200
+ st.error(f"Error extracting text: {e}")
201
  return None
202
 
203
+ # Split resume text into sections
204
+ def split_resume_into_sections(resume_text):
205
+ """Split the resume text into sections like Education, Experience, etc."""
206
  sections = {
207
  'education': [],
208
  'experience': [],
 
212
  }
213
 
214
  current_section = None
215
+ for sentence in sent_tokenize(resume_text): # Split text into sentences
216
+ sentence_upper = sentence.upper() # Convert to uppercase for easier matching
217
  if "EDUCATION" in sentence_upper:
218
  current_section = 'education'
219
  elif "EXPERIENCE" in sentence_upper:
 
225
  elif "CERTIFICATIONS" in sentence_upper:
226
  current_section = 'certifications'
227
 
228
+ if current_section: # Add the sentence to the appropriate section
229
  sections[current_section].append(sentence.strip())
230
 
231
  return sections
232
 
233
+ # Save resume data to MongoDB
234
+ def save_resume_to_mongodb(pdf_bytes, user_id):
235
+ """Save the resume text and sections to MongoDB."""
236
  try:
237
  resume_text = extract_text_from_pdf(pdf_bytes)
238
  if not resume_text:
239
  return None
240
+ resume_sections = split_resume_into_sections(resume_text)
241
 
242
+ # Prepare data to save
 
243
  resume_data = {
244
  'user_id': user_id,
245
+ 'resume': resume_sections
246
  }
247
 
248
+ # Insert data into MongoDB
249
  result = collection.insert_one(resume_data)
250
+ return result.inserted_id
251
  except OperationFailure as e:
252
+ st.error(f"Error saving data: {e}")
253
  return None
254
 
255
+ # Fetch resume data from MongoDB
256
  def fetch_resume_from_mongodb(user_id):
257
+ """Fetch resume data from MongoDB using the user ID."""
258
  try:
259
  resume_data = collection.find_one({"user_id": user_id})
260
  return resume_data
261
  except OperationFailure as e:
262
+ st.error(f"Error fetching data: {e}")
263
  return None
264
 
 
265
  st.title("Resume Extractor and MongoDB Storage")
266
+ st.write("Upload a PDF resume, extract text, and store it in MongoDB.")
267
+ st.header("Step 1: Upload and Store Resume")
268
+ pdf_file = st.file_uploader("Upload a PDF Resume", type="pdf")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
 
270
+ if pdf_file:
271
+ pdf_bytes = pdf_file.read()
272
+ resume_text = extract_text_from_pdf(pdf_bytes)
273
 
274
+ if resume_text:
275
+ st.subheader("Extracted Text")
276
+ st.write(resume_text)
277
+
278
+ user_id = st.text_input("Enter User ID", "12345")
279
+
280
+ if st.button("Save Resume to MongoDB"):
281
+ with st.spinner("Saving..."):
282
+ inserted_id = save_resume_to_mongodb(pdf_bytes, user_id)
283
+ if inserted_id:
284
+ st.success(f"Resume saved! Document ID: {inserted_id}")
285
+
286
+ #Fetch resume data from MongoDB
287
+ st.header("Step 2: Retrieve Resume Data")
288
+ user_id_to_fetch = st.text_input("Enter User ID to Fetch Data", "12345")
289
+
290
+ if st.button("Fetch Resume"):
291
+ with st.spinner("Fetching..."):
292
+ resume_data = fetch_resume_from_mongodb(user_id_to_fetch)
293
+
294
+ if resume_data:
295
+ st.subheader(f"Resume Data for User ID: {user_id_to_fetch}")
296
+ st.json(json.dumps(resume_data, default=str, indent=4)) # Show data as JSON
297
+ else:
298
+ st.warning(f"No resume found for User ID: {user_id_to_fetch}")