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 
 
 
 
 
 
 
 
7ec4f40
b75fb8f
 
7ec4f40
b75fb8f
 
b422889
 
 
 
 
 
 
 
 
 
 
 
b75fb8f
7ec4f40
 
 
b422889
7ec4f40
 
 
b422889
7ec4f40
 
 
 
 
 
 
b422889
 
7ec4f40
 
 
 
 
 
 
 
 
 
 
b422889
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b75fb8f
 
b422889
 
 
 
 
 
 
 
 
 
 
 
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541

# # utils.py
# import os
# import json
# from langchain_groq import ChatGroq
# from langchain_text_splitters import RecursiveCharacterTextSplitter
# # from langchain.schema import Document
# # from langchain.chains import RetrievalQA
# # from langchain_huggingface import HuggingFaceEmbeddings
# # from langchain_community.vectorstores import Chroma
# # from langchain.prompts import PromptTemplate

# from langchain_core.documents import Document
# from langchain_chroma import Chroma
# from langchain_huggingface import HuggingFaceEmbeddings
# from langchain_core.prompts import PromptTemplate
# # from langchain.chains import RetrievalQA
# from langchain_classic.chains import create_retrieval_chain
# from langchain_classic.chains.combine_documents import create_stuff_documents_chain
# from configure import USER_DATA_PATH, RAG_BASE_DIRECTORY, RAG_CATEGORIES
# import shutil
# from dotenv import load_dotenv
# from pymongo import MongoClient
# import certifi
# import re

# load_dotenv()


# def get_mongo_collection():
#     CONNECTION_STRING = os.getenv("CONNECTION_STRING")
#     DB_NAME = os.getenv("DB_NAME")
#     COLLECTION_NAME = os.getenv("COLLECTION_NAME")
#     try:
#         # Connect with certifi to avoid SSL errors
#         client = MongoClient(CONNECTION_STRING, tlsCAFile=certifi.where())
#         db = client[DB_NAME]
#         return db[COLLECTION_NAME]
#     except Exception as e:
#         print(f"Error connecting to Mongo: {e}")
#         return None
    

# def LLMChunking():
#     pass




# # LLM setup
# llm = ChatGroq(
#     api_key="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",
#     model="llama-3.3-70b-versatile",
#     temperature=0,
#     max_tokens=4000
# )

# # Text splitter
# text_splitter = RecursiveCharacterTextSplitter(
#     separators=["\n\n", "\n", ".", " ", ""],
#     chunk_size=500,
#     chunk_overlap=100,
#     length_function=len
# )
# # text_splitter = LLMChunking()

# # Embeddings
# embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
# # embeddings = None

# # Load user data
# def load_user_data():
#     try:
#         if os.path.exists(USER_DATA_PATH) and os.path.getsize(USER_DATA_PATH) > 0:
#             with open(USER_DATA_PATH, 'r') as f:
#                 return json.load(f)
#     except Exception:
#         pass
#     return {"users": {}, "user_info": {}}

# # Save user data
# def save_user_data(data):
#     with open(USER_DATA_PATH, 'w') as f:
#         json.dump(data, f, indent=2)

# # Initialize RAG with per-category vector stores and QA chains
# def initialize_rag():
#     """
#     Initialize RAG vector stores and chains using modern LangChain (LCEL).
#     Args:
#         llm: The initialized ChatGroq (or other) LLM object.
#         embeddings: The initialized HuggingFaceEmbeddings object.
#         text_splitter: The initialized RecursiveCharacterTextSplitter object.
#     """
#     vector_stores = {}
#     qa_chains = {}
    
#     # 1. Define Prompt Template (Modern LCEL Format)
#     # Note: Modern chains typically look for "context" and "input" variables.
#     base_prompt_template = """You are a {category} wellness expert. Provide helpful advice with specific actions:

# 1. Start with a brief empathetic response to the user's concern
# 2. Offer 1-3 actionable suggestions with brief explanations
# 3. End with an open-ended question to continue conversation

# Guidelines:
# - Keep responses conversational and supportive
# - Avoid clinical jargon
# - Focus on practical, implementable advice
# - Maintain hopeful and encouraging tone

# Context:
# {context}

# Question: {input}
# """
    
#     for category in RAG_CATEGORIES:
#         persist_dir = f"./chroma_db_{category}"
#         vector_store = None 

#         # --- 2. Check/Load Existing Vector Store ---
#         if os.path.exists(persist_dir):
#             print(f"Found existing vector store for {category}. Attempting to load...")
#             try:
#                 vector_store = Chroma(
#                     persist_directory=persist_dir,
#                     embedding_function=embeddings  # UPDATED: 'embedding_function', not 'embedding'
#                 )
#                 vector_stores[category] = vector_store
#             except Exception as e:
#                 print(f"Error loading existing store {persist_dir}: {e}")
#                 print("Will delete and attempt to re-build.")
#                 shutil.rmtree(persist_dir)
        
#         # --- 3. Create Vector Store if needed ---
#         if vector_store is None: 
#             print(f"No valid vector store for {category} found. Creating new one...")
            
#             dir_path = os.path.join(RAG_BASE_DIRECTORY, category)
#             docs = []
            
#             if os.path.exists(dir_path):
#                 for filename in os.listdir(dir_path):
#                     if filename.endswith('.txt'):
#                         file_path = os.path.join(dir_path, filename)
#                         try:
#                             with open(file_path, 'r', encoding='utf-8') as f:
#                                 text = f.read()
                            
#                             chunks = text_splitter.split_text(text)
#                             for chunk in chunks:
#                                 if chunk.strip():
#                                     metadata = {
#                                         "source": filename,
#                                         "category": category
#                                     }
#                                     docs.append(Document(
#                                         page_content=chunk.strip(),
#                                         metadata=metadata
#                                     ))
#                         except Exception as e:
#                             print(f"Error processing {file_path}: {e}")
            
#             if docs:
#                 # UPDATED: Use 'embedding_function' instead of 'embedding'
#                 # UPDATED: Removed .persist() call (Auto-persists in new version)
#                 vector_store = Chroma.from_documents(
#                     documents=docs,
#                     embedding=embeddings, 
#                     persist_directory=persist_dir
#                 )
#                 vector_stores[category] = vector_store
#                 print(f"Created new vector store for {category} with {len(docs)} documents.")
#             else:
#                 print(f"No documents found for {category}. Skipping QA chain setup.")
#                 continue 

#         # --- 4. Create QA Chain (LCEL Style) ---
#         if vector_store:
#             # A. Create the Prompt
#             # We inject the specific category into the template string immediately
#             category_specific_template = base_prompt_template.replace("{category}", category)
            
#             prompt = PromptTemplate(
#                 template=category_specific_template,
#                 input_variables=["context", "input"] # LCEL standard variables
#             )

#             # B. Create the Document Chain (LLM + Prompt)
#             question_answer_chain = create_stuff_documents_chain(llm, prompt)

#             # C. Create the Retrieval Chain (Retriever + Document Chain)
#             retriever = vector_store.as_retriever(search_kwargs={"k": 5})
#             rag_chain = create_retrieval_chain(retriever, question_answer_chain)

#             qa_chains[category] = rag_chain
#             print(f"Initialized {category} QA chain.")

#     return qa_chains



# # Classify question to category
# def classify_question_category(question):
#     prompt = f"""
#     Classify this question into one category: {', '.join(RAG_CATEGORIES)}
#     Question: {question}
#     Respond with only the category name.
#     """
#     response = llm.invoke(prompt)
#     print(response)
#     return response.content.strip()

# # Get RAG response using category-specific QA chain
# def get_rag_response(question, qa_chains):
#     # Classify question
#     category = classify_question_category(question)
    
#     if category not in qa_chains:
#         # Fallback to first available chain
#         category = list(qa_chains.keys())[0]
    
#     # Get response
#     result = qa_chains[category].invoke({"input": question})
#     return result['answer']


# # Classify user input
# def classify_input(user_input):
#     prompt = f"""
#     Classify the following user input into one of these categories:
#     1. "question" - If the user is asking a factual question that could be answered with knowledge
#     2. "general" - If the user is just chatting or expressing feelings

#     User Input: {user_input}

#     Respond with only one word: either "question" or "general"
#     """
#     response = llm.invoke(prompt)
#     return response.content.strip().lower()



# def parse_weird_json(text_data):
#     fixed_json_string = re.sub(r'\]\s*\[', ', ', text_data.strip())
    
#     # Step B: Load it as standard JSON
#     try:
#         data_list = json.loads(fixed_json_string)
#         return data_list
#     except json.JSONDecodeError as e:
#         print(f"❌ JSON Parsing Error: {e}")
#         return []







# utils.py
import os
import json
from langchain_groq import ChatGroq
from langchain_text_splitters import RecursiveCharacterTextSplitter
# from langchain.schema import Document
# from langchain.chains import RetrievalQA
# from langchain_huggingface import HuggingFaceEmbeddings
# from langchain_community.vectorstores import Chroma
# from langchain.prompts import PromptTemplate

from langchain_core.documents import Document
from langchain_chroma import Chroma
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_core.prompts import PromptTemplate
# from langchain.chains import RetrievalQA
from langchain_classic.chains import create_retrieval_chain
from langchain_classic.chains.combine_documents import create_stuff_documents_chain
from configure import USER_DATA_PATH, RAG_BASE_DIRECTORY, RAG_CATEGORIES
import shutil
from dotenv import load_dotenv
from pymongo import MongoClient
import certifi
import re

load_dotenv()
GROQ_API_KEY = os.getenv("GROQ_API_KEY")

def get_mongo_collection():
    CONNECTION_STRING = os.getenv("CONNECTION_STRING")
    DB_NAME = os.getenv("DB_NAME")
    COLLECTION_NAME = os.getenv("COLLECTION_NAME")
    try:
        # Connect with certifi to avoid SSL errors
        client = MongoClient(CONNECTION_STRING, tlsCAFile=certifi.where())
        db = client[DB_NAME]
        return db[COLLECTION_NAME]
    except Exception as e:
        print(f"Error connecting to Mongo: {e}")
        return None
    

def LLMChunking():
    pass




# LLM setup
llm = ChatGroq(
    api_key=GROQ_API_KEY,
    model="llama-3.3-70b-versatile",
    temperature=0.7,
    max_tokens=500,
    model_kwargs={
        "top_p": 0.9,
        "presence_penalty": 0.5,
        "frequency_penalty": 0.4
    }
)


# Text splitter
text_splitter = RecursiveCharacterTextSplitter(
    separators=["\n\n", "\n", ".", " ", ""],
    chunk_size=500,
    chunk_overlap=100,
    length_function=len
)
# text_splitter = LLMChunking()

# Embeddings
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
# embeddings = None

# Load user data
def load_user_data():
    try:
        if os.path.exists(USER_DATA_PATH) and os.path.getsize(USER_DATA_PATH) > 0:
            with open(USER_DATA_PATH, 'r') as f:
                return json.load(f)
    except Exception:
        pass
    return {"users": {}, "user_info": {}}

# Save user data
def save_user_data(data):
    with open(USER_DATA_PATH, 'w') as f:
        json.dump(data, f, indent=2)

# Initialize RAG with per-category vector stores and QA chains
def initialize_rag():
    """
    Initialize RAG vector stores and chains using modern LangChain (LCEL).
    Args:
        llm: The initialized ChatGroq (or other) LLM object.
        embeddings: The initialized HuggingFaceEmbeddings object.
        text_splitter: The initialized RecursiveCharacterTextSplitter object.
    """
    vector_stores = {}
    qa_chains = {}
    retrievers = {}
    
    # 1. Define Prompt Template (Modern LCEL Format)
    # Note: Modern chains typically look for "context" and "input" variables.
    base_prompt_template = """You are a {category} wellness expert. Provide helpful advice with specific actions:

1. Start with a brief empathetic response to the user's concern
2. Offer 1-3 actionable suggestions with brief explanations
3. End with an open-ended question to continue conversation

Guidelines:
- Keep responses conversational and supportive
- Avoid clinical jargon
- Focus on practical, implementable advice
- Maintain hopeful and encouraging tone

Context:
{context}

Question: {input}
"""
    
    for category in RAG_CATEGORIES:
        persist_dir = f"./chroma_db_{category}"
        vector_store = None 

        # --- 2. Check/Load Existing Vector Store ---
        if os.path.exists(persist_dir):
            print(f"Found existing vector store for {category}. Attempting to load...")
            try:
                vector_store = Chroma(
                    persist_directory=persist_dir,
                    embedding_function=embeddings  # UPDATED: 'embedding_function', not 'embedding'
                )
                vector_stores[category] = vector_store
            except Exception as e:
                print(f"Error loading existing store {persist_dir}: {e}")
                print("Will delete and attempt to re-build.")
                shutil.rmtree(persist_dir)
        
        # --- 3. Create Vector Store if needed ---
        if vector_store is None: 
            print(f"No valid vector store for {category} found. Creating new one...")
            
            dir_path = os.path.join(RAG_BASE_DIRECTORY, category)
            docs = []
            
            if os.path.exists(dir_path):
                for filename in os.listdir(dir_path):
                    if filename.endswith('.txt'):
                        file_path = os.path.join(dir_path, filename)
                        try:
                            with open(file_path, 'r', encoding='utf-8') as f:
                                text = f.read()
                            
                            chunks = text_splitter.split_text(text)
                            for chunk in chunks:
                                if chunk.strip():
                                    metadata = {
                                        "source": filename,
                                        "category": category
                                    }
                                    docs.append(Document(
                                        page_content=chunk.strip(),
                                        metadata=metadata
                                    ))
                        except Exception as e:
                            print(f"Error processing {file_path}: {e}")
            
            if docs:
                # UPDATED: Use 'embedding_function' instead of 'embedding'
                # UPDATED: Removed .persist() call (Auto-persists in new version)
                vector_store = Chroma.from_documents(
                    documents=docs,
                    embedding=embeddings, 
                    persist_directory=persist_dir
                )
                vector_stores[category] = vector_store
                print(f"Created new vector store for {category} with {len(docs)} documents.")
            else:
                print(f"No documents found for {category}. Skipping QA chain setup.")
                continue 

        # --- 4. Create QA Chain (LCEL Style) ---
        if vector_store:
            # A. Create the Prompt
            # We inject the specific category into the template string immediately
            category_specific_template = base_prompt_template.replace("{category}", category)
            
            prompt = PromptTemplate(
                template=category_specific_template,
                input_variables=["context", "input"] # LCEL standard variables
            )

            # B. Create the Document Chain (LLM + Prompt)
            question_answer_chain = create_stuff_documents_chain(llm, prompt)

            # C. Create the Retrieval Chain (Retriever + Document Chain)
            retriever = vector_store.as_retriever(search_kwargs={"k": 5})
            rag_chain = create_retrieval_chain(retriever, question_answer_chain)

            qa_chains[category] = rag_chain
            retrievers[category] = retriever
            print(f"Initialized {category} QA chain.")

    return qa_chains, retrievers



# Classify question to category
def classify_question_category(question):
    prompt = f"""
    Classify this question into one category: {', '.join(RAG_CATEGORIES)}
    Question: {question}
    Respond with only the category name.
    """
    response = llm.invoke(prompt)
    print(response)
    return response.content.strip()

# Get RAG response using category-specific QA chain
# def get_rag_response(question, qa_chains):
#     # Classify question
#     category = classify_question_category(question)
    
#     if category not in qa_chains:
#         # Fallback to first available chain
#         category = list(qa_chains.keys())[0]
    
#     # Get response
#     # result = qa_chains[category].invoke({"input": question})
#     retriever = qa_chains[category].retriever
#     docs = retriever.invoke(question)

#     # return result['answer']
#     return [doc.page_content for doc in docs]



def get_rag_response(question, retrievers_dict):
    category = classify_question_category(question)
    
    if category not in retrievers_dict:
        category = list(retrievers_dict.keys())[0]
    
    docs = retrievers_dict[category].invoke(question)
    
    return "\n\n".join([doc.page_content for doc in docs])

# Classify user input
def classify_input(user_input):
    prompt = f"""
    Classify the following user input into one of these categories:
    1. "question" - If the user is asking a factual question that could be answered with knowledge
    2. "general" - If the user is just chatting or expressing feelings

    User Input: {user_input}

    Respond with only one word: either "question" or "general"
    """
    response = llm.invoke(prompt)
    return response.content.strip().lower()



def parse_weird_json(text_data):
    fixed_json_string = re.sub(r'\]\s*\[', ', ', text_data.strip())
    
    # Step B: Load it as standard JSON
    try:
        data_list = json.loads(fixed_json_string)
        return data_list
    except json.JSONDecodeError as e:
        print(f"❌ JSON Parsing Error: {e}")
        return []