JaynilJaiswal commited on
Commit
5073484
Β·
verified Β·
1 Parent(s): 350b937

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +520 -0
app.py ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %%capture
2
+ # # Run this cell in your local environment to install necessary packages
3
+ # # Added chromadb, removed scikit-learn (numpy might still be needed by other libs)
4
+ # !pip install gradio langchain langchain-community sentence-transformers ctransformers torch accelerate bitsandbytes chromadb transformers[sentencepiece]
5
+
6
+ import gradio as gr
7
+ from langchain_community.vectorstores import Chroma # ADDED
8
+ from langchain_community.embeddings import HuggingFaceEmbeddings
9
+ from langchain_community.llms import CTransformers
10
+ from langchain.schema import Document
11
+ from langchain.prompts import PromptTemplate
12
+ import json
13
+ import os
14
+ # REMOVED: import numpy as np
15
+ import re
16
+ # REMOVED: from sklearn.metrics.pairwise import cosine_similarity
17
+ import chromadb # ADDED for client check
18
+ from typing import List, Dict, Any, Optional
19
+
20
+ # --- Load Structured Resume Data ---
21
+ resume_filename = "resume_corrected.json" # Using the revamped JSON
22
+ resume_data = {}
23
+ try:
24
+ with open(resume_filename, 'r', encoding='utf-8') as f:
25
+ resume_data = json.load(f)
26
+ print(f"Loaded structured resume data from {resume_filename}")
27
+ if not isinstance(resume_data, dict):
28
+ print(f"Error: Content of {resume_filename} is not a dictionary.")
29
+ resume_data = {}
30
+ except FileNotFoundError:
31
+ print(f"Error: Resume data file '{resume_filename}' not found.")
32
+ print("Ensure the revamped JSON file is present.")
33
+ exit()
34
+ except json.JSONDecodeError as e:
35
+ print(f"Error decoding JSON from {resume_filename}: {e}")
36
+ exit()
37
+ except Exception as e:
38
+ print(f"An unexpected error occurred loading resume data: {e}")
39
+ exit()
40
+
41
+ if not resume_data:
42
+ print("Error: No resume data loaded. Exiting.")
43
+ exit()
44
+
45
+ # --- Function to Sanitize Metadata ---
46
+ # --- Helper Function to Sanitize Metadata ---
47
+ def sanitize_metadata(metadata_dict: Dict[str, Any]) -> Dict[str, Any]:
48
+ """Ensures metadata values are compatible types for ChromaDB."""
49
+ sanitized = {}
50
+ if not isinstance(metadata_dict, dict):
51
+ return {} # Return empty if input is not a dict
52
+ for k, v in metadata_dict.items():
53
+ # Ensure key is string
54
+ key_str = str(k)
55
+ if isinstance(v, (str, int, float, bool)):
56
+ sanitized[key_str] = v
57
+ elif isinstance(v, (list, set)): # Convert lists/sets to string
58
+ sanitized[key_str] = "; ".join(map(str, v))
59
+ elif v is None:
60
+ sanitized[key_str] = "N/A" # Or ""
61
+ else:
62
+ sanitized[key_str] = str(v) # Convert other types to string
63
+ return sanitized
64
+
65
+
66
+ # --- Create Granular LangChain Documents from Structured Data ---
67
+ # (This entire section remains unchanged as requested)
68
+ structured_docs = []
69
+ doc_id_counter = 0
70
+ print("Processing structured data into granular documents...")
71
+ # --- Start of Unchanged Document Creation Logic ---
72
+ contact_info = resume_data.get("CONTACT INFO", {})
73
+ if contact_info:
74
+ contact_text = f"Contact Info: Phone: {contact_info.get('phone', 'N/A')}, Location: {contact_info.get('location', 'N/A')}, Email: {contact_info.get('email', 'N/A')}, GitHub: {contact_info.get('github_user', 'N/A')}, LinkedIn: {contact_info.get('linkedin_user', 'N/A')}"
75
+ metadata = {"category": "CONTACT INFO", "source_doc_id": str(doc_id_counter)} # Ensure ID is string
76
+ structured_docs.append(Document(page_content=contact_text, metadata=metadata))
77
+ doc_id_counter += 1
78
+
79
+ education_list = resume_data.get("EDUCATION", [])
80
+ for i, entry in enumerate(education_list):
81
+ edu_text = f"Education: {entry.get('degree', '')} in {entry.get('major', '')} from {entry.get('institution', '')} ({entry.get('dates', '')})."
82
+ metadata = {
83
+ "category": "EDUCATION",
84
+ "institution": entry.get('institution', 'N/A'), # Ensure N/A or actual string
85
+ "degree": entry.get('degree', 'N/A'),
86
+ "major": entry.get('major', 'N/A'),
87
+ "dates": entry.get('dates', 'N/A'),
88
+ "item_index": i,
89
+ "source_doc_id": str(doc_id_counter) # Ensure ID is string
90
+ }
91
+ # Ensure all metadata values are strings, ints, floats, or bools
92
+ metadata = {k: (v if isinstance(v, (str, int, float, bool)) else str(v)) for k, v in metadata.items()}
93
+ structured_docs.append(Document(page_content=edu_text.strip(), metadata=metadata))
94
+ doc_id_counter += 1
95
+
96
+ tech_strengths = resume_data.get("TECHNICAL STRENGTHS", {})
97
+ for sub_category, skills in tech_strengths.items():
98
+ if isinstance(skills, list) and skills:
99
+ skills_text = f"Technical Strengths - {sub_category}: {', '.join(skills)}"
100
+ metadata = {"category": "TECHNICAL STRENGTHS", "sub_category": sub_category, "source_doc_id": str(doc_id_counter)}
101
+ metadata = {k: (v if isinstance(v, (str, int, float, bool)) else str(v)) for k, v in metadata.items()}
102
+ structured_docs.append(Document(page_content=skills_text, metadata=metadata))
103
+ doc_id_counter += 1
104
+
105
+ # Process WORK EXPERIENCE (Using relevant_skills)
106
+ work_list = resume_data.get("WORK EXPERIENCE", [])
107
+ for i, entry in enumerate(work_list):
108
+ title = entry.get('title', 'N/A')
109
+ org = entry.get('organization', 'N/A')
110
+ dates = entry.get('dates', 'N/A')
111
+ points = entry.get('description_points', [])
112
+ # --- MODIFICATION START ---
113
+ skills_list = entry.get('relevant_skills', []) # Get pre-associated skills
114
+ skills_str = "; ".join(skills_list) if skills_list else "N/A"
115
+ # --- MODIFICATION END ---
116
+ entry_context = f"Work Experience: {title} at {org} ({dates})"
117
+
118
+ if not points:
119
+ base_metadata = {
120
+ "category": "WORK EXPERIENCE", "title": title, "organization": org,
121
+ "dates": dates, "item_index": i, "point_index": -1,
122
+ "source_doc_id": str(doc_id_counter),
123
+ "skills": skills_str # --- ADDED SKILLS ---
124
+ }
125
+ structured_docs.append(Document(page_content=entry_context, metadata=sanitize_metadata(base_metadata)))
126
+ doc_id_counter += 1
127
+ else:
128
+ # Create one doc for the header/context info
129
+ base_metadata = {
130
+ "category": "WORK EXPERIENCE", "title": title, "organization": org,
131
+ "dates": dates, "item_index": i, "point_index": -1, # Indicate context doc
132
+ "source_doc_id": str(doc_id_counter),
133
+ "skills": skills_str # --- ADDED SKILLS ---
134
+ }
135
+ structured_docs.append(Document(page_content=entry_context, metadata=sanitize_metadata(base_metadata)))
136
+ # Create separate docs for each point, inheriting skills
137
+ for j, point in enumerate(points):
138
+ point_text = f"{entry_context}:\n- {point.strip()}"
139
+ point_metadata = {
140
+ "category": "WORK EXPERIENCE", "title": title, "organization": org,
141
+ "dates": dates, "item_index": i, "point_index": j,
142
+ "source_doc_id": str(doc_id_counter), # Link back to original entry ID
143
+ "skills": skills_str # --- ADDED SKILLS ---
144
+ }
145
+ structured_docs.append(Document(page_content=point_text, metadata=sanitize_metadata(point_metadata)))
146
+ doc_id_counter += 1 # Increment ID only once per WORK EXPERIENCE entry
147
+
148
+ # Process PROJECTS (Using technologies field, mapping to 'skills' metadata key)
149
+ project_list = resume_data.get("PROJECTS", [])
150
+ for i, entry in enumerate(project_list):
151
+ name = entry.get('name', 'Unnamed Project')
152
+ # --- MODIFICATION START ---
153
+ # Use 'technologies' from JSON for projects, but map to 'skills' metadata key
154
+ skills_list = entry.get('technologies', [])
155
+ skills_str = "; ".join(skills_list) if skills_list else "N/A"
156
+ # --- MODIFICATION END ---
157
+ points = entry.get('description_points', [])
158
+ # Include skills string in context text as well for embedding
159
+ entry_context = f"Project: {name} (Skills: {skills_str if skills_list else 'N/A'})"
160
+
161
+ if not points:
162
+ base_metadata = {
163
+ "category": "PROJECTS", "name": name,
164
+ "item_index": i, "point_index": -1,
165
+ "source_doc_id": str(doc_id_counter),
166
+ "skills": skills_str # --- ADDED/RENAMED SKILLS ---
167
+ }
168
+ structured_docs.append(Document(page_content=entry_context, metadata=sanitize_metadata(base_metadata)))
169
+ doc_id_counter += 1
170
+ else:
171
+ # Create one doc for the header/context info
172
+ base_metadata = {
173
+ "category": "PROJECTS", "name": name,
174
+ "item_index": i, "point_index": -1, # Indicate context doc
175
+ "source_doc_id": str(doc_id_counter),
176
+ "skills": skills_str # --- ADDED/RENAMED SKILLS ---
177
+ }
178
+ structured_docs.append(Document(page_content=entry_context, metadata=sanitize_metadata(base_metadata)))
179
+ # Create separate docs for each point, inheriting skills
180
+ for j, point in enumerate(points):
181
+ point_text = f"{entry_context}:\n- {point.strip()}"
182
+ point_metadata = {
183
+ "category": "PROJECTS", "name": name,
184
+ "item_index": i, "point_index": j,
185
+ "source_doc_id": str(doc_id_counter),
186
+ "skills": skills_str # --- ADDED/RENAMED SKILLS ---
187
+ }
188
+ structured_docs.append(Document(page_content=point_text, metadata=sanitize_metadata(point_metadata)))
189
+ doc_id_counter += 1 # Increment ID only once per PROJECT entry
190
+
191
+
192
+ # Process ONLINE CERTIFICATIONS (Using relevant_skills)
193
+ cert_list = resume_data.get("ONLINE CERTIFICATIONS", [])
194
+ for i, entry in enumerate(cert_list):
195
+ name = entry.get('name', 'N/A')
196
+ issuer = entry.get('issuer', 'N/A')
197
+ date = entry.get('date', 'N/A')
198
+ points = entry.get('description_points', [])
199
+ # --- MODIFICATION START ---
200
+ skills_list = entry.get('relevant_skills', []) # Get pre-associated skills
201
+ skills_str = "; ".join(skills_list) if skills_list else "N/A"
202
+ # --- MODIFICATION END ---
203
+ entry_context = f"Certification: {name} from {issuer} ({date})"
204
+
205
+ if not points:
206
+ base_metadata = {
207
+ "category": "ONLINE CERTIFICATIONS", "name": name, "issuer": issuer,
208
+ "date": date, "item_index": i, "point_index": -1,
209
+ "source_doc_id": str(doc_id_counter),
210
+ "skills": skills_str # --- ADDED SKILLS ---
211
+ }
212
+ structured_docs.append(Document(page_content=entry_context, metadata=sanitize_metadata(base_metadata)))
213
+ doc_id_counter += 1
214
+ else:
215
+ # Create one doc for the header/context info
216
+ base_metadata = {
217
+ "category": "ONLINE CERTIFICATIONS", "name": name, "issuer": issuer,
218
+ "date": date, "item_index": i, "point_index": -1, # Indicate context doc
219
+ "source_doc_id": str(doc_id_counter),
220
+ "skills": skills_str # --- ADDED SKILLS ---
221
+ }
222
+ structured_docs.append(Document(page_content=entry_context, metadata=sanitize_metadata(base_metadata)))
223
+ # Create separate docs for each point, inheriting skills
224
+ for j, point in enumerate(points):
225
+ if point.strip().endswith(':'): continue
226
+ point_text = f"{entry_context}:\n- {point.strip().lstrip('–- ')}"
227
+ point_metadata = {
228
+ "category": "ONLINE CERTIFICATIONS", "name": name, "issuer": issuer,
229
+ "date": date, "item_index": i, "point_index": j,
230
+ "source_doc_id": str(doc_id_counter),
231
+ "skills": skills_str # --- ADDED SKILLS ---
232
+ }
233
+ structured_docs.append(Document(page_content=point_text, metadata=sanitize_metadata(point_metadata)))
234
+ doc_id_counter += 1 # Increment ID only once per CERTIFICATION entry
235
+
236
+ # Process COURSES (Using relevant_skills)
237
+ course_list = resume_data.get("COURSES", [])
238
+ for i, entry in enumerate(course_list):
239
+ code = entry.get('code', '')
240
+ name = entry.get('name', 'N/A')
241
+ inst = entry.get('institution', 'N/A')
242
+ term = entry.get('term', 'N/A')
243
+ points = entry.get('description_points', [])
244
+ # --- MODIFICATION START ---
245
+ skills_list = entry.get('relevant_skills', []) # Get pre-associated skills
246
+ skills_str = "; ".join(skills_list) if skills_list else "N/A"
247
+ # --- MODIFICATION END ---
248
+ entry_context = f"Course: {code}: {name} at {inst} ({term})"
249
+
250
+ if not points:
251
+ base_metadata = {
252
+ "category": "COURSES", "code": code, "name": name, "institution": inst,
253
+ "term": term, "item_index": i, "point_index": -1,
254
+ "source_doc_id": str(doc_id_counter),
255
+ "skills": skills_str # --- ADDED SKILLS ---
256
+ }
257
+ structured_docs.append(Document(page_content=entry_context, metadata=sanitize_metadata(base_metadata)))
258
+ doc_id_counter += 1
259
+ else:
260
+ # Create one doc for the header/context info
261
+ base_metadata = {
262
+ "category": "COURSES", "code": code, "name": name, "institution": inst,
263
+ "term": term, "item_index": i, "point_index": -1, # Indicate context doc
264
+ "source_doc_id": str(doc_id_counter),
265
+ "skills": skills_str # --- ADDED SKILLS ---
266
+ }
267
+ structured_docs.append(Document(page_content=entry_context, metadata=sanitize_metadata(base_metadata)))
268
+ # Create separate docs for each point, inheriting skills
269
+ for j, point in enumerate(points):
270
+ point_text = f"{entry_context}:\n- {point.strip()}"
271
+ point_metadata = {
272
+ "category": "COURSES", "code": code, "name": name, "institution": inst,
273
+ "term": term, "item_index": i, "point_index": j,
274
+ "source_doc_id": str(doc_id_counter),
275
+ "skills": skills_str # --- ADDED SKILLS ---
276
+ }
277
+ structured_docs.append(Document(page_content=point_text, metadata=sanitize_metadata(point_metadata)))
278
+ doc_id_counter += 1 # Increment ID only once per COURSE entry
279
+
280
+ # Process EXTRACURRICULAR ACTIVITIES (No skills assumed here)
281
+ extra_list = resume_data.get("EXTRACURRICULAR ACTIVITIES", [])
282
+ for i, entry in enumerate(extra_list):
283
+ org = entry.get('organization', 'N/A')
284
+ points = entry.get('description_points', [])
285
+ entry_context = f"Extracurricular: {org}"
286
+ if not points:
287
+ metadata = {
288
+ "category": "EXTRACURRICULAR ACTIVITIES", "organization": org,
289
+ "item_index": i, "point_index": -1,
290
+ "source_doc_id": str(doc_id_counter)
291
+ }
292
+ structured_docs.append(Document(page_content=entry_context, metadata=sanitize_metadata(metadata)))
293
+ doc_id_counter += 1
294
+ else:
295
+ # Create one doc for the header/context info
296
+ base_metadata = {
297
+ "category": "EXTRACURRICULAR ACTIVITIES", "organization": org,
298
+ "item_index": i, "point_index": -1, # Indicate context doc
299
+ "source_doc_id": str(doc_id_counter)
300
+ }
301
+ structured_docs.append(Document(page_content=entry_context, metadata=sanitize_metadata(base_metadata)))
302
+ # Create separate docs for each point
303
+ for j, point in enumerate(points):
304
+ point_text = f"{entry_context}:\n- {point.strip()}"
305
+ point_metadata = {
306
+ "category": "EXTRACURRICULAR ACTIVITIES", "organization": org,
307
+ "item_index": i, "point_index": j,
308
+ "source_doc_id": str(doc_id_counter)
309
+ }
310
+ structured_docs.append(Document(page_content=point_text, metadata=sanitize_metadata(point_metadata)))
311
+ doc_id_counter += 1
312
+
313
+
314
+ if not structured_docs:
315
+ print("Error: Failed to create any documents from the resume data. Check processing logic.")
316
+ exit()
317
+
318
+ print(f"Created {len(structured_docs)} granular Document objects.")
319
+ # Optional: Print a sample document
320
+ print("\nSample Document:")
321
+ print(structured_docs[0]) # Print first doc as example
322
+
323
+ # --- Embeddings Model ---
324
+ print("Initializing embeddings model...")
325
+ embeddings_model_name = "sentence-transformers/multi-qa-mpnet-base-dot-v1"
326
+ embeddings = HuggingFaceEmbeddings(model_name=embeddings_model_name)
327
+ print(f"Embeddings model '{embeddings_model_name}' initialized.")
328
+
329
+ # --- ChromaDB Vector Store Setup ---
330
+ CHROMA_PERSIST_DIR = "/data/cv_chroma_db_structured" # Use a different dir if needed
331
+ CHROMA_COLLECTION_NAME = "cv_structured_collection"
332
+ print(f"Connecting to ChromaDB client at '{CHROMA_PERSIST_DIR}'...")
333
+ client = chromadb.PersistentClient(path=CHROMA_PERSIST_DIR)
334
+ vectorstore = None
335
+ collection_exists = False
336
+ collection_count = 0
337
+
338
+ try:
339
+ existing_collections = [col.name for col in client.list_collections()]
340
+ if CHROMA_COLLECTION_NAME in existing_collections:
341
+ collection = client.get_collection(name=CHROMA_COLLECTION_NAME)
342
+ collection_count = collection.count()
343
+ if collection_count > 0:
344
+ collection_exists = True
345
+ print(f"Collection '{CHROMA_COLLECTION_NAME}' already exists with {collection_count} documents.")
346
+ else:
347
+ print(f"Collection '{CHROMA_COLLECTION_NAME}' exists but is empty. Will attempt to create/populate.")
348
+ collection_exists = False
349
+ try:
350
+ client.delete_collection(name=CHROMA_COLLECTION_NAME)
351
+ print(f"Deleted empty collection '{CHROMA_COLLECTION_NAME}'.")
352
+ except Exception as delete_e:
353
+ print(f"Warning: Could not delete potentially empty collection '{CHROMA_COLLECTION_NAME}': {delete_e}")
354
+ else: print(f"Collection '{CHROMA_COLLECTION_NAME}' does not exist. Will create.")
355
+ except Exception as e:
356
+ print(f"Error checking/preparing ChromaDB collection: {e}. Assuming need to create.")
357
+ collection_exists = False
358
+
359
+ # Populate Vector Store ONLY IF NEEDED
360
+ if not collection_exists:
361
+ print("\nPopulating ChromaDB vector store (this may take a moment)...")
362
+ if not structured_docs:
363
+ print("Error: No documents to add to vector store.")
364
+ exit()
365
+ try:
366
+ vectorstore = Chroma.from_documents(
367
+ documents=structured_docs,
368
+ embedding=embeddings, # Use the initialized embeddings function
369
+ collection_name=CHROMA_COLLECTION_NAME,
370
+ persist_directory=CHROMA_PERSIST_DIR
371
+ )
372
+ vectorstore.persist()
373
+ print("Vector store populated and persisted.")
374
+ except Exception as e:
375
+ print(f"\n--- Error during ChromaDB storage: {e} ---")
376
+ print("Check metadata types (should be str, int, float, bool).")
377
+ exit()
378
+ else: # Load existing store
379
+ print(f"\nLoading existing vector store from '{CHROMA_PERSIST_DIR}'...")
380
+ try:
381
+ vectorstore = Chroma(
382
+ persist_directory=CHROMA_PERSIST_DIR,
383
+ embedding_function=embeddings,
384
+ collection_name=CHROMA_COLLECTION_NAME
385
+ )
386
+ print("Existing vector store loaded successfully.")
387
+ except Exception as e:
388
+ print(f"\n--- Error loading existing ChromaDB store: {e} ---")
389
+ exit()
390
+
391
+ if not vectorstore:
392
+ print("Error: Vector store could not be loaded or created. Exiting.")
393
+ exit()
394
+
395
+
396
+ # --- Load Fine-tuned CTransformers model ---
397
+ # (This part remains unchanged)
398
+ model_path_gguf = "/data/zephyr-7b-beta.Q4_K_M.gguf" # MAKE SURE THIS PATH IS CORRECT
399
+ print(f"Initializing Fine-Tuned CTransformers LLM from: {model_path_gguf}")
400
+ config = {
401
+ 'max_new_tokens': 512, 'temperature': 0.1, 'context_length': 2048,
402
+ 'gpu_layers': 0, 'stream': False, 'threads': -1, 'top_k': 40,
403
+ 'top_p': 0.9, 'repetition_penalty': 1.1
404
+ }
405
+ llm = None
406
+ if not os.path.exists(model_path_gguf):
407
+ print(f"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
408
+ print(f"ERROR: GGUF Model file not found at: {model_path_gguf}")
409
+ print(f"Please download the model and place it at the correct path, or update model_path_gguf.")
410
+ print(f"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
411
+ print("LLM initialization skipped.")
412
+ else:
413
+ try:
414
+ llm = CTransformers(model=model_path_gguf, model_type='llama', config=config)
415
+ print("Fine-Tuned CTransformers LLM initialized.")
416
+ except Exception as e:
417
+ print(f"Error initializing CTransformers: {e}")
418
+ print("LLM initialization failed.")
419
+ # Decide if you want to exit or continue without LLM
420
+ # exit()
421
+
422
+ # --- RAG Setup ---
423
+ def format_docs(docs):
424
+ # Expects a list of Document objects
425
+ return "\n\n".join(doc.page_content for doc in docs if isinstance(doc, Document))
426
+
427
+
428
+ # --- RAG Function using ChromaDB ---
429
+ def answer_resume_question(user_question):
430
+ """Answers questions using RAG with ChromaDB similarity search."""
431
+ k_limit = 5 # Number of documents to retrieve
432
+ print(f"\nReceived question: {user_question}")
433
+
434
+ if not vectorstore:
435
+ return "Error: Vector store is not available."
436
+
437
+ print(f"Performing similarity search (top {k_limit})...")
438
+ try:
439
+ # 1. Retrieve documents using ChromaDB similarity search
440
+ # Use similarity_search_with_score to get scores if needed for logging/debugging
441
+ # results_with_scores = vectorstore.similarity_search_with_score(user_question, k=k_limit)
442
+ # retrieved_docs = [doc for doc, score in results_with_scores]
443
+ # similarity_scores = [score for doc, score in results_with_scores]
444
+
445
+ # Or simpler retrieval if scores aren't needed immediately:
446
+ retrieved_docs = vectorstore.similarity_search(user_question, k=k_limit)
447
+
448
+ if not retrieved_docs:
449
+ print("No relevant documents found via similarity search.")
450
+ # Optionally add fallback logic here if needed
451
+ return "I couldn't find relevant information in the CV for your query."
452
+
453
+ print(f"Retrieved {len(retrieved_docs)} documents.")
454
+ # Log details of top retrieved docs
455
+ for i, doc in enumerate(retrieved_docs):
456
+ # score = similarity_scores[i] # Uncomment if using similarity_search_with_score
457
+ print(f" -> Top {i+1} Doc (Cat: {doc.metadata.get('category')}, SrcID: {doc.metadata.get('source_doc_id')}) Content: {doc.page_content.replace(os.linesep, ' ')}...")
458
+
459
+ # 2. Combine content
460
+ combined_context = format_docs(retrieved_docs) # Use the existing format_docs
461
+
462
+ # 3. Check if LLM is available
463
+ if not llm:
464
+ return "LLM is not available, cannot generate a final answer. Relevant context found:\n\n" + combined_context
465
+
466
+ # 4. Final Answer Generation Step
467
+ qa_template = """
468
+ Based *only* on the following context from Jaynil Jaiswal's CV, provide a detailed and comprehensive answer to the question.
469
+ If the context does not contain the information needed to answer the question fully, please state that clearly using phrases like 'Based on the context provided, I cannot answer...' or 'The provided context does not contain information about...'.
470
+ Do not make up any information or provide generic non-answers. You are free to selectively use sources from the context to answer the question.
471
+
472
+ Context:
473
+ {context}
474
+
475
+ Question: {question}
476
+
477
+ Answer:"""
478
+ qa_prompt = PromptTemplate.from_template(qa_template)
479
+ formatted_qa_prompt = qa_prompt.format(context=combined_context, question=user_question)
480
+
481
+ print("Generating final answer...")
482
+ answer = llm.invoke(formatted_qa_prompt).strip()
483
+ print(f"LLM Response: {answer}")
484
+
485
+ # Optional: Add the insufficient answer check here if desired
486
+ # if is_answer_insufficient(answer):
487
+ # print("LLM answer seems insufficient...")
488
+ # # Return fallback or the potentially insufficient answer based on preference
489
+ # return FALLBACK_MESSAGE # Assuming FALLBACK_MESSAGE is defined
490
+
491
+ except Exception as e:
492
+ print(f"Error during RAG execution: {e}")
493
+ answer = "Sorry, I encountered an error while processing your question."
494
+
495
+ return answer
496
+ # --- End Modification ---
497
+
498
+
499
+ # --- Gradio Interface ---
500
+ # (This part remains unchanged)
501
+ iface = gr.Interface(
502
+ fn=answer_resume_question,
503
+ inputs=gr.Textbox(label="πŸ’¬ Ask about my CV", placeholder="E.g. What was done at Oracle? List my projects.", lines=2),
504
+ outputs=gr.Textbox(label="πŸ’‘ Answer", lines=8),
505
+ title="πŸ“š CV RAG Chatbot (ChromaDB + Granular Docs)",
506
+ description="Ask questions about the CV! (Uses local GGUF model via CTransformers)",
507
+ theme="soft",
508
+ allow_flagging="never"
509
+ )
510
+
511
+ # --- Run Gradio ---
512
+ if __name__ == "__main__":
513
+ print("Launching Gradio interface...")
514
+ # Make sure LLM was loaded successfully before launching
515
+ if vectorstore and llm:
516
+ iface.launch(server_name="0.0.0.0", server_port=7860)
517
+ elif not vectorstore:
518
+ print("Could not launch: Vector store failed to load.")
519
+ else: # LLM failed
520
+ print("Could not launch: LLM failed to load. Check model path and dependencies.")