Rabbit-Innotech commited on
Commit
57fd9a2
·
verified ·
1 Parent(s): bd83779

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +955 -595
app.py CHANGED
@@ -1,658 +1,932 @@
1
- # # import os
2
- # # import time
3
- # # import pandas as pd
4
- # # import gradio as gr
5
- # # from langchain_groq import ChatGroq
6
- # # from langchain_huggingface import HuggingFaceEmbeddings
7
- # # from langchain_community.vectorstores import Chroma
8
- # # from langchain_core.prompts import PromptTemplate
9
- # # from langchain_core.output_parsers import StrOutputParser
10
- # # from langchain_core.runnables import RunnablePassthrough
11
- # # from PyPDF2 import PdfReader
12
-
13
-
14
- # # # Configuration constants
15
- # # COLLECTION_NAME = "GBVRS"
16
- # # DATA_FOLDER = "./"
17
- # # APP_VERSION = "v1.0.0"
18
- # # APP_NAME = "Ijwi ry'Ubufasha"
19
- # # MAX_HISTORY_MESSAGES = 8 # Limit history to avoid token limits
20
-
21
- # # # Global variables for application state
22
- # # llm = None
23
- # # embed_model = None
24
- # # vectorstore = None
25
- # # retriever = None
26
- # # rag_chain = None
27
-
28
- # # # User session management
29
- # # class UserSession:
30
- # # def __init__(self, session_id, llm):
31
- # # """Initialize a user session with unique ID and language model."""
32
- # # self.session_id = session_id
33
- # # self.user_info = {"Nickname": "Guest"}
34
- # # self.conversation_history = []
35
- # # self.llm = llm
36
- # # self.welcome_message = None
37
- # # self.last_activity = time.time()
38
 
39
- # # def set_user(self, user_info):
40
- # # """Set user information and generate welcome message."""
41
- # # self.user_info = user_info
42
- # # self.generate_welcome_message()
43
 
44
- # # # Initialize conversation history with welcome message
45
- # # welcome = self.get_welcome_message()
46
- # # self.conversation_history = [
47
- # # {"role": "assistant", "content": welcome},
48
- # # ]
49
 
50
- # # def get_user(self):
51
- # # """Get current user information."""
52
- # # return self.user_info
53
 
54
- # # def generate_welcome_message(self):
55
- # # """Generate a dynamic welcome message using the LLM."""
56
- # # try:
57
- # # nickname = self.user_info.get("Nickname", "Guest")
58
 
59
- # # # Use the LLM to generate the message
60
- # # prompt = (
61
- # # f"Create a brief and warm welcome message for {nickname} that's about 1-2 sentences. "
62
- # # f"Emphasize this is a safe space for discussing gender-based violence issues "
63
- # # f"and that we provide support and resources. Keep it warm and reassuring."
64
- # # )
65
 
66
- # # response = self.llm.invoke(prompt)
67
- # # welcome = response.content.strip()
68
 
69
- # # # Format the message with HTML styling
70
- # # self.welcome_message = (
71
- # # f"<div style='font-size: 18px; color: #4E6BBF;'>"
72
- # # f"{welcome}"
73
- # # f"</div>"
74
- # # )
75
- # # except Exception as e:
76
- # # # Fallback welcome message
77
- # # nickname = self.user_info.get("Nickname", "Guest")
78
- # # self.welcome_message = (
79
- # # f"<div style='font-size: 18px; color: #4E6BBF;'>"
80
- # # f"Welcome, {nickname}! You're in a safe space. We're here to provide support with "
81
- # # f"gender-based violence issues and connect you with resources that can help."
82
- # # f"</div>"
83
- # # )
84
 
85
- # # def get_welcome_message(self):
86
- # # """Get the formatted welcome message."""
87
- # # if not self.welcome_message:
88
- # # self.generate_welcome_message()
89
- # # return self.welcome_message
90
 
91
- # # def add_to_history(self, role, message):
92
- # # """Add a message to the conversation history."""
93
- # # self.conversation_history.append({"role": role, "content": message})
94
- # # self.last_activity = time.time()
95
 
96
- # # # Trim history if it gets too long
97
- # # if len(self.conversation_history) > MAX_HISTORY_MESSAGES * 2: # Keep pairs of messages
98
- # # # Keep the first message (welcome) and the most recent messages
99
- # # self.conversation_history = [self.conversation_history[0]] + self.conversation_history[-MAX_HISTORY_MESSAGES*2+1:]
100
 
101
- # # def get_conversation_history(self):
102
- # # """Get the full conversation history."""
103
- # # return self.conversation_history
104
 
105
- # # def get_formatted_history(self):
106
- # # """Get conversation history formatted as a string for the LLM."""
107
- # # # Skip the welcome message and only include the last few exchanges
108
- # # recent_history = self.conversation_history[1:] if len(self.conversation_history) > 1 else []
109
 
110
- # # # Limit to last MAX_HISTORY_MESSAGES exchanges
111
- # # if len(recent_history) > MAX_HISTORY_MESSAGES * 2:
112
- # # recent_history = recent_history[-MAX_HISTORY_MESSAGES*2:]
113
 
114
- # # formatted_history = ""
115
- # # for entry in recent_history:
116
- # # role = "User" if entry["role"] == "user" else "Assistant"
117
- # # # Truncate very long messages to avoid token limits
118
- # # content = entry["content"]
119
- # # if len(content) > 500: # Limit message length
120
- # # content = content[:500] + "..."
121
- # # formatted_history += f"{role}: {content}\n\n"
122
 
123
- # # return formatted_history
124
 
125
- # # def is_expired(self, timeout_seconds=3600):
126
- # # """Check if the session has been inactive for too long."""
127
- # # return (time.time() - self.last_activity) > timeout_seconds
128
-
129
- # # # Session manager to handle multiple users
130
- # # class SessionManager:
131
- # # def __init__(self):
132
- # # """Initialize the session manager."""
133
- # # self.sessions = {}
134
- # # self.session_timeout = 3600 # 1 hour timeout
135
 
136
- # # def get_session(self, session_id):
137
- # # """Get an existing session or create a new one."""
138
- # # # Clean expired sessions first
139
- # # self._clean_expired_sessions()
140
 
141
- # # # Create new session if needed
142
- # # if session_id not in self.sessions:
143
- # # self.sessions[session_id] = UserSession(session_id, llm)
144
 
145
- # # return self.sessions[session_id]
146
 
147
- # # def _clean_expired_sessions(self):
148
- # # """Remove expired sessions to free up memory."""
149
- # # expired_keys = []
150
- # # for key, session in self.sessions.items():
151
- # # if session.is_expired(self.session_timeout):
152
- # # expired_keys.append(key)
153
 
154
- # # for key in expired_keys:
155
- # # del self.sessions[key]
156
 
157
- # # # Initialize the session manager
158
- # # session_manager = SessionManager()
159
 
160
- # # def initialize_assistant():
161
- # # """Initialize the assistant with necessary components and configurations."""
162
- # # global llm, embed_model, vectorstore, retriever, rag_chain
163
 
164
- # # # Initialize API key - try both possible key names
165
- # # groq_api_key = os.environ.get('GBV') or os.environ.get('GBV')
166
- # # if not groq_api_key:
167
- # # print("WARNING: No GROQ API key found in userdata.")
168
 
169
- # # # Initialize LLM - Default to Llama model which is more widely available
170
- # # llm = ChatGroq(
171
- # # model="llama-3.3-70b-versatile", # More reliable than whisper model
172
- # # api_key=groq_api_key
173
- # # )
174
 
175
- # # # Set up embedding model
176
- # # try:
177
- # # embed_model = HuggingFaceEmbeddings(model_name="mixedbread-ai/mxbai-embed-large-v1")
178
- # # except Exception as e:
179
- # # # Fallback to smaller model
180
- # # embed_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
181
 
182
- # # # Process data and create vector store
183
- # # print("Processing data files...")
184
- # # data = process_data_files()
185
 
186
- # # print("Creating vector store...")
187
- # # vectorstore = create_vectorstore(data)
188
- # # retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
189
 
190
- # # # Create RAG chain
191
- # # print("Setting up RAG chain...")
192
- # # rag_chain = create_rag_chain()
193
 
194
- # # print(f"✅ {APP_NAME} initialized successfully")
195
 
196
- # # def process_data_files():
197
- # # """Process all data files from the specified folder."""
198
- # # context_data = []
199
 
200
- # # try:
201
- # # if not os.path.exists(DATA_FOLDER):
202
- # # print(f"WARNING: Data folder does not exist: {DATA_FOLDER}")
203
- # # return context_data
204
 
205
- # # # Get list of data files
206
- # # all_files = os.listdir(DATA_FOLDER)
207
- # # data_files = [f for f in all_files if f.lower().endswith(('.csv', '.xlsx', '.xls'))]
208
 
209
- # # if not data_files:
210
- # # print(f"WARNING: No data files found in: {DATA_FOLDER}")
211
- # # return context_data
212
 
213
- # # # Process each file
214
- # # for index, file_name in enumerate(data_files, 1):
215
- # # print(f"Processing file {index}/{len(data_files)}: {file_name}")
216
- # # file_path = os.path.join(DATA_FOLDER, file_name)
217
 
218
- # # try:
219
- # # # Read file based on extension
220
- # # if file_name.lower().endswith('.csv'):
221
- # # df = pd.read_csv(file_path)
222
- # # else:
223
- # # df = pd.read_excel(file_path)
224
 
225
- # # # Check if column 3 exists (source data is in third column)
226
- # # if df.shape[1] > 2:
227
- # # column_data = df.iloc[:, 2].dropna().astype(str).tolist()
228
 
229
- # # # Each row becomes one chunk with metadata
230
- # # for i, text in enumerate(column_data):
231
- # # if text and len(text.strip()) > 0:
232
- # # context_data.append({
233
- # # "page_content": text,
234
- # # "metadata": {
235
- # # "source": file_name,
236
- # # "row": i+1
237
- # # }
238
- # # })
239
- # # else:
240
- # # print(f"WARNING: File {file_name} has fewer than 3 columns.")
241
 
242
- # # except Exception as e:
243
- # # print(f"ERROR processing file {file_name}: {e}")
244
 
245
- # # print(f"✅ Created {len(context_data)} chunks from {len(data_files)} files.")
246
 
247
- # # except Exception as e:
248
- # # print(f"ERROR accessing data folder: {e}")
249
 
250
- # # return context_data
251
 
252
- # # def create_vectorstore(data):
253
- # # """
254
- # # Creates and returns a Chroma vector store populated with the provided data.
255
-
256
- # # Parameters:
257
- # # data (list): A list of dictionaries, each containing 'page_content' and 'metadata'.
258
-
259
- # # Returns:
260
- # # Chroma: The populated Chroma vector store instance.
261
- # # """
262
- # # # Initialize the vector store
263
- # # vectorstore = Chroma(
264
- # # collection_name=COLLECTION_NAME,
265
- # # embedding_function=embed_model,
266
- # # persist_directory="./"
267
- # # )
268
-
269
- # # if not data:
270
- # # print("⚠️ No data provided. Returning an empty vector store.")
271
- # # return vectorstore
272
-
273
- # # try:
274
- # # # Extract text and metadata from the data
275
- # # texts = [doc["page_content"] for doc in data]
276
-
277
- # # # Add the texts and metadata to the vector store
278
- # # vectorstore.add_texts(texts)
279
- # # except Exception as e:
280
- # # print(f"❌ Failed to add documents to vector store: {e}")
281
-
282
- # # # Fix: Return vectorstore instead of vs
283
- # # return vectorstore # Changed from 'return vs' to 'return vectorstore'
284
-
285
-
286
- # # def create_rag_chain():
287
- # # """Create the RAG chain for processing user queries."""
288
- # # # Define the prompt template
289
- # # template = """
290
- # # You are a compassionate and supportive AI assistant specializing in helping individuals affected by Gender-Based Violence (GBV). Your responses must be based EXCLUSIVELY on the information provided in the context. Your primary goal is to provide emotionally intelligent support while maintaining appropriate boundaries.
291
 
292
- # # **Previous conversation:** {conversation_history}
293
- # # **Context information:** {context}
294
- # # **User's Question:** {question}
295
 
296
- # # When responding follow these guidelines:
297
 
298
- # # 1. **Strict Context Adherence**
299
- # # - Only use information that appears in the provided {context}
300
- # # - If the answer is not found in the context, state "I don't have that information in my available resources" rather than generating a response
301
 
302
- # # 2. **Personalized Communication**
303
- # # - Avoid contractions (e.g., use I am instead of I'm)
304
- # # - Incorporate thoughtful pauses or reflective questions when the conversation involves difficult topics
305
- # # - Use selective emojis (😊, 🤗, ❤️) only when tone-appropriate and not during crisis discussions
306
- # # - Balance warmth with professionalism
307
 
308
- # # 3. **Emotional Intelligence**
309
- # # - Validate feelings without judgment
310
- # # - Offer reassurance when appropriate, always centered on empowerment
311
- # # - Adjust your tone based on the emotional state conveyed
312
 
313
- # # 4. **Conversation Management**
314
- # # - Refer to {conversation_history} to maintain continuity and avoid repetition
315
- # # - Use clear paragraph breaks for readability
316
 
317
- # # 5. **Information Delivery**
318
- # # - Extract only relevant information from {context} that directly addresses the question
319
- # # - Present information in accessible, non-technical language
320
- # # - When information is unavailable, respond with: "I don't have that specific information right now, {first_name}. Would it be helpful if I focus on [alternative support option]?"
321
 
322
- # # 6. **Safety and Ethics**
323
- # # - Do not generate any speculative content or advice not supported by the context
324
- # # - If the context contains safety information, prioritize sharing that information
325
 
326
- # # Your response must come entirely from the provided context, maintaining the supportive tone while never introducing information from outside the provided materials.
327
- # # **Context:** {context}
328
- # # **User's Question:** {question}
329
- # # **Your Response:**
330
- # # """
331
 
332
 
333
- # # rag_prompt = PromptTemplate.from_template(template)
334
 
335
- # # def get_context_and_question(query_with_session):
336
- # # # Extract query and session_id
337
- # # query = query_with_session["query"]
338
- # # session_id = query_with_session["session_id"]
339
 
340
- # # # Get the user session
341
- # # session = session_manager.get_session(session_id)
342
- # # user_info = session.get_user()
343
- # # first_name = user_info.get("Nickname", "User")
344
- # # conversation_hist = session.get_formatted_history()
345
 
346
- # # try:
347
- # # # Retrieve relevant documents
348
- # # retrieved_docs = retriever.invoke(query)
349
- # # context_str = format_context(retrieved_docs)
350
- # # except Exception as e:
351
- # # print(f"ERROR retrieving documents: {e}")
352
- # # context_str = "No relevant information found."
353
 
354
- # # # Return the combined inputs for the prompt
355
- # # return {
356
- # # "context": context_str,
357
- # # "question": query,
358
- # # "first_name": first_name,
359
- # # "conversation_history": conversation_hist
360
- # # }
361
 
362
- # # # Build the chain
363
- # # try:
364
- # # chain = (
365
- # # RunnablePassthrough()
366
- # # | get_context_and_question
367
- # # | rag_prompt
368
- # # | llm
369
- # # | StrOutputParser()
370
- # # )
371
- # # return chain
372
- # # except Exception as e:
373
- # # print(f"ERROR creating RAG chain: {e}")
374
 
375
- # # # Return a simple function as fallback
376
- # # def fallback_chain(query_with_session):
377
- # # session_id = query_with_session["session_id"]
378
- # # session = session_manager.get_session(session_id)
379
- # # nickname = session.get_user().get("Nickname", "there")
380
- # # return f"I'm here to help you, {nickname}, but I'm experiencing some technical difficulties right now. Please try again shortly."
381
 
382
- # # return fallback_chain
383
-
384
- # # def format_context(retrieved_docs):
385
- # # """Format retrieved documents into a string context."""
386
- # # if not retrieved_docs:
387
- # # return "No relevant information available."
388
- # # return "\n\n".join([doc.page_content for doc in retrieved_docs])
389
-
390
- # # def rag_memory_stream(message, history, session_id):
391
- # # """Process user message and generate response with memory."""
392
- # # # Get the user session
393
- # # session = session_manager.get_session(session_id)
394
 
395
- # # # Add user message to history
396
- # # session.add_to_history("user", message)
397
 
398
- # # try:
399
- # # # Get response from RAG chain
400
- # # print(f"Processing message for session {session_id}: {message[:50]}...")
401
 
402
- # # # Pass both query and session_id to the chain
403
- # # response = rag_chain.invoke({
404
- # # "query": message,
405
- # # "session_id": session_id
406
- # # })
407
 
408
- # # print(f"Generated response: {response[:50]}...")
409
 
410
- # # # Add assistant response to history
411
- # # session.add_to_history("assistant", response)
412
 
413
- # # # Yield the response
414
- # # yield response
415
 
416
- # # except Exception as e:
417
- # # import traceback
418
- # # print(f"ERROR in rag_memory_stream: {e}")
419
- # # print(f"Detailed error: {traceback.format_exc()}")
420
 
421
- # # nickname = session.get_user().get("Nickname", "there")
422
- # # error_msg = f"I'm sorry, {nickname}. I encountered an error processing your request. Let's try a different question."
423
- # # session.add_to_history("assistant", error_msg)
424
- # # yield error_msg
425
-
426
- # # def collect_user_info(nickname, session_id):
427
- # # """Store user details and initialize session."""
428
- # # if not nickname or nickname.strip() == "":
429
- # # return "Nickname is required to proceed.", gr.update(visible=False), gr.update(visible=True), []
430
-
431
- # # # Store user info for chat session
432
- # # user_info = {
433
- # # "Nickname": nickname.strip(),
434
- # # "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
435
- # # }
436
-
437
- # # # Get the session and set user info
438
- # # session = session_manager.get_session(session_id)
439
- # # session.set_user(user_info)
440
-
441
- # # # Generate welcome message
442
- # # welcome_message = session.get_welcome_message()
443
-
444
- # # # Return welcome message and update UI
445
- # # return welcome_message, gr.update(visible=True), gr.update(visible=False), [(None, welcome_message)]
446
-
447
- # # def get_css():
448
- # # """Define CSS for the UI."""
449
- # # return """
450
- # # :root {
451
- # # --primary: #4E6BBF;
452
- # # --primary-light: #697BBF;
453
- # # --text-primary: #333333;
454
- # # --text-secondary: #666666;
455
- # # --background: #F9FAFC;
456
- # # --card-bg: #FFFFFF;
457
- # # --border: #E1E5F0;
458
- # # --shadow: rgba(0, 0, 0, 0.05);
459
- # # }
460
-
461
- # # body, .gradio-container {
462
- # # margin: 0;
463
- # # padding: 0;
464
- # # width: 100vw;
465
- # # height: 100vh;
466
- # # display: flex;
467
- # # flex-direction: column;
468
- # # justify-content: center;
469
- # # align-items: center;
470
- # # background: var(--background);
471
- # # color: var(--text-primary);
472
- # # font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
473
- # # }
474
-
475
- # # .gradio-container {
476
- # # max-width: 100%;
477
- # # max-height: 100%;
478
- # # }
479
-
480
- # # .gr-box {
481
- # # background: var(--card-bg);
482
- # # color: var(--text-primary);
483
- # # border-radius: 12px;
484
- # # padding: 2rem;
485
- # # border: 1px solid var(--border);
486
- # # box-shadow: 0 4px 12px var(--shadow);
487
- # # }
488
-
489
- # # .gr-button-primary {
490
- # # background: var(--primary);
491
- # # color: white;
492
- # # padding: 12px 24px;
493
- # # border-radius: 8px;
494
- # # transition: all 0.3s ease;
495
- # # border: none;
496
- # # font-weight: bold;
497
- # # }
498
-
499
- # # .gr-button-primary:hover {
500
- # # transform: translateY(-1px);
501
- # # box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
502
- # # background: var(--primary-light);
503
- # # }
504
-
505
- # # footer {
506
- # # text-align: center;
507
- # # color: var(--text-secondary);
508
- # # padding: 1rem;
509
- # # font-size: 0.9em;
510
- # # }
511
-
512
- # # .gr-markdown h2 {
513
- # # color: var(--primary);
514
- # # margin-bottom: 0.5rem;
515
- # # font-size: 1.8em;
516
- # # }
517
-
518
- # # .gr-markdown h3 {
519
- # # color: var(--text-secondary);
520
- # # margin-bottom: 1.5rem;
521
- # # font-weight: normal;
522
- # # }
523
-
524
- # # #chatbot_container .chat-title h1,
525
- # # #chatbot_container .empty-chatbot {
526
- # # color: var(--primary);
527
- # # }
528
-
529
- # # #input_nickname {
530
- # # padding: 12px;
531
- # # border-radius: 8px;
532
- # # border: 1px solid var(--border);
533
- # # background: var(--card-bg);
534
- # # transition: all 0.3s ease;
535
- # # }
536
 
537
- # # #input_nickname:focus {
538
- # # border-color: var(--primary);
539
- # # box-shadow: 0 0 0 2px rgba(78, 107, 191, 0.2);
540
- # # outline: none;
541
- # # }
542
-
543
- # # .chatbot-container .message.user {
544
- # # background: #E8F0FE;
545
- # # border-radius: 12px 12px 0 12px;
546
- # # }
547
-
548
- # # .chatbot-container .message.bot {
549
- # # background: #F5F7FF;
550
- # # border-radius: 12px 12px 12px 0;
551
- # # }
552
- # # """
553
-
554
- # # def create_ui():
555
- # # """Create and configure the Gradio UI."""
556
- # # with gr.Blocks(css=get_css(), theme=gr.themes.Soft()) as demo:
557
- # # # Create a unique session ID for this browser tab
558
- # # session_id = gr.State(value=f"session_{int(time.time())}_{os.urandom(4).hex()}")
559
 
560
- # # # Registration section
561
- # # with gr.Column(visible=True, elem_id="registration_container") as registration_container:
562
- # # gr.Markdown(f"## Welcome to {APP_NAME}")
563
- # # gr.Markdown("### Your privacy is important to us. Please provide a nickname to continue.")
564
-
565
- # # with gr.Row():
566
- # # first_name = gr.Textbox(
567
- # # label="Nickname",
568
- # # placeholder="Enter your nickname",
569
- # # scale=1,
570
- # # elem_id="input_nickname"
571
- # # )
572
-
573
- # # with gr.Row():
574
- # # submit_btn = gr.Button("Start Chatting", variant="primary", scale=2)
575
-
576
- # # response_message = gr.Markdown()
577
-
578
- # # # Chatbot section (initially hidden)
579
- # # with gr.Column(visible=False, elem_id="chatbot_container") as chatbot_container:
580
- # # # Create a custom chat interface to pass session_id to our function
581
- # # chatbot = gr.Chatbot(
582
- # # elem_id="chatbot",
583
- # # height=500,
584
- # # show_label=False
585
- # # )
 
 
 
 
 
 
 
 
 
586
 
587
- # # with gr.Row():
588
- # # msg = gr.Textbox(
589
- # # placeholder="Type your message here...",
590
- # # show_label=False,
591
- # # container=False,
592
- # # scale=9
593
- # # )
594
- # # submit = gr.Button("Send", scale=1, variant="primary")
 
 
 
 
595
 
596
- # # examples = gr.Examples(
597
- # # examples=[
598
- # # "What resources are available for GBV victims?",
599
- # # "How can I report an incident?",
600
- # # "What are my legal rights?",
601
- # # "I need help, what should I do first?"
602
- # # ],
603
- # # inputs=msg
604
- # # )
605
-
606
- # # # Footer with version info
607
- # # gr.Markdown(f"{APP_NAME} {APP_VERSION} © 2025")
608
 
609
- # # # Handle chat message submission
610
- # # def respond(message, chat_history, session_id):
611
- # # bot_message = ""
612
- # # for chunk in rag_memory_stream(message, chat_history, session_id):
613
- # # bot_message += chunk
614
- # # chat_history.append((message, bot_message))
615
- # # return "", chat_history
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
616
 
617
- # # msg.submit(respond, [msg, chatbot, session_id], [msg, chatbot])
618
- # # submit.click(respond, [msg, chatbot, session_id], [msg, chatbot])
619
 
620
- # # # Handle user registration
621
- # # submit_btn.click(
622
- # # collect_user_info,
623
- # # inputs=[first_name, session_id],
624
- # # outputs=[response_message, chatbot_container, registration_container, chatbot]
625
- # # )
626
 
627
- # # return demo
628
 
629
- # # def launch_app():
630
- # # """Launch the Gradio interface."""
631
- # # ui = create_ui()
632
- # # ui.launch(share=True)
633
 
634
- # # # Main execution
635
- # # if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
636
  # # try:
637
- # # # Initialize and launch the assistant
638
- # # initialize_assistant()
639
- # # launch_app()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
640
  # # except Exception as e:
641
- # # import traceback
642
- # # print(f"❌ Fatal error initializing GBV Assistant: {e}")
643
- # # print(traceback.format_exc())
644
-
645
- # # # Create a minimal emergency UI to display the error
646
- # # with gr.Blocks() as error_demo:
647
- # # gr.Markdown("## System Error")
648
- # # gr.Markdown(f"An error occurred while initializing the application: {str(e)}")
649
- # # gr.Markdown("Please check your configuration and try again.")
650
-
651
- # # error_demo.launch(share=True, inbrowser=True, debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
652
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
653
 
 
 
 
654
 
655
- # ############################################################################################################
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
656
 
657
 
658
  # import os
@@ -669,6 +943,36 @@
669
  # import gradio as gr
670
  # from PyPDF2 import PdfReader
671
  # from langchain_huggingface import HuggingFaceEmbeddings
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
672
 
673
  # groq_api_key= os.environ.get('GBV')
674
 
@@ -809,9 +1113,6 @@
809
  # chunked_texts.extend(chunk_string(text))
810
 
811
 
812
-
813
-
814
-
815
  # vectorstore = Chroma(
816
  # collection_name="GBVR_Dataset",
817
  # embedding_function=embed_model,
@@ -822,7 +1123,7 @@
822
 
823
  # vectorstore.add_texts(chunked_texts)
824
 
825
-
826
  # template = ("""
827
  # You are a friendly, intelligent, and conversational AI assistant designed to provide accurate, engaging, and human-like responses based on the given context. Your goal is to extract relevant details from the provided context: {context} and assist the user effectively. Follow these guidelines:
828
 
@@ -848,7 +1149,8 @@
848
  # - "I don't have that information at the moment, but I'm happy to help with something else! 😊"
849
 
850
  # 6. **Personalized Interaction**
851
- # - If user history is available, tailor responses based on their previous interactions for a more natural and engaging conversation.
 
852
 
853
  # 7. **Direct, Concise Responses**
854
  # - If the user requests specific data, provide only the requested details without unnecessary explanations unless asked.
@@ -868,30 +1170,62 @@
868
 
869
  # retriever = vectorstore.as_retriever()
870
 
871
- # from langchain_core.output_parsers import StrOutputParser
872
- # from langchain_core.runnables import RunnablePassthrough
873
 
874
- # llm = ChatGroq(model="llama-3.3-70b-versatile", api_key=groq_api_key )
875
-
876
- # rag_chain = (
877
- # {"context": retriever, "question": RunnablePassthrough()}
878
- # | rag_prompt
879
- # | llm
880
- # | StrOutputParser()
881
- # )
882
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
883
 
884
  # # Define the RAG memory stream function
885
  # def rag_memory_stream(message, history):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
886
  # partial_text = ""
887
- # for new_text in rag_chain.stream(message): # Replace with actual streaming logic
888
- # partial_text += new_text
889
- # yield partial_text
 
890
 
891
  # # Title with emojis
892
  # title = "GBVR Chatbot"
893
 
894
-
895
  # # Custom CSS for styling the interface
896
  # custom_css = """
897
  # body {
@@ -912,7 +1246,6 @@
912
  # .gr-textbox:focus, .gr-button:focus {
913
  # outline: none; /* Remove outline focus for a cleaner look */
914
  # }
915
-
916
  # """
917
 
918
  # # Create the Chat Interface
@@ -927,8 +1260,6 @@
927
  # # Launch the app
928
  # if __name__ == "__main__":
929
  # demo.launch(share=True, inbrowser=True, debug=True)
930
-
931
-
932
  import os
933
  from langchain_groq import ChatGroq
934
  from langchain.prompts import ChatPromptTemplate, PromptTemplate
@@ -1114,7 +1445,7 @@ for text in processed_texts:
1114
 
1115
 
1116
  vectorstore = Chroma(
1117
- collection_name="GBVR_Dataset",
1118
  embedding_function=embed_model,
1119
  persist_directory="./",
1120
  )
@@ -1228,12 +1559,15 @@ title = "GBVR Chatbot"
1228
 
1229
  # Custom CSS for styling the interface
1230
  custom_css = """
 
1231
  body {
1232
  font-family: "Arial", serif;
1233
  }
 
1234
  .gradio-container {
1235
  font-family: "Times New Roman", serif;
1236
  }
 
1237
  .gr-button {
1238
  background-color: #007bff; /* Blue button */
1239
  color: white;
@@ -1243,18 +1577,44 @@ body {
1243
  padding: 10px 20px;
1244
  cursor: pointer;
1245
  }
 
1246
  .gr-textbox:focus, .gr-button:focus {
1247
  outline: none; /* Remove outline focus for a cleaner look */
1248
  }
 
 
 
 
 
 
 
 
 
1249
  """
1250
 
1251
- # Create the Chat Interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1252
  demo = gr.ChatInterface(
1253
  fn=rag_memory_stream,
1254
  title=title,
1255
  fill_height=True,
1256
  theme="soft",
1257
  css=custom_css, # Apply the custom CSS
 
1258
  )
1259
 
1260
  # Launch the app
 
1
+ # # # import os
2
+ # # # import time
3
+ # # # import pandas as pd
4
+ # # # import gradio as gr
5
+ # # # from langchain_groq import ChatGroq
6
+ # # # from langchain_huggingface import HuggingFaceEmbeddings
7
+ # # # from langchain_community.vectorstores import Chroma
8
+ # # # from langchain_core.prompts import PromptTemplate
9
+ # # # from langchain_core.output_parsers import StrOutputParser
10
+ # # # from langchain_core.runnables import RunnablePassthrough
11
+ # # # from PyPDF2 import PdfReader
12
+
13
+
14
+ # # # # Configuration constants
15
+ # # # COLLECTION_NAME = "GBVRS"
16
+ # # # DATA_FOLDER = "./"
17
+ # # # APP_VERSION = "v1.0.0"
18
+ # # # APP_NAME = "Ijwi ry'Ubufasha"
19
+ # # # MAX_HISTORY_MESSAGES = 8 # Limit history to avoid token limits
20
+
21
+ # # # # Global variables for application state
22
+ # # # llm = None
23
+ # # # embed_model = None
24
+ # # # vectorstore = None
25
+ # # # retriever = None
26
+ # # # rag_chain = None
27
+
28
+ # # # # User session management
29
+ # # # class UserSession:
30
+ # # # def __init__(self, session_id, llm):
31
+ # # # """Initialize a user session with unique ID and language model."""
32
+ # # # self.session_id = session_id
33
+ # # # self.user_info = {"Nickname": "Guest"}
34
+ # # # self.conversation_history = []
35
+ # # # self.llm = llm
36
+ # # # self.welcome_message = None
37
+ # # # self.last_activity = time.time()
38
 
39
+ # # # def set_user(self, user_info):
40
+ # # # """Set user information and generate welcome message."""
41
+ # # # self.user_info = user_info
42
+ # # # self.generate_welcome_message()
43
 
44
+ # # # # Initialize conversation history with welcome message
45
+ # # # welcome = self.get_welcome_message()
46
+ # # # self.conversation_history = [
47
+ # # # {"role": "assistant", "content": welcome},
48
+ # # # ]
49
 
50
+ # # # def get_user(self):
51
+ # # # """Get current user information."""
52
+ # # # return self.user_info
53
 
54
+ # # # def generate_welcome_message(self):
55
+ # # # """Generate a dynamic welcome message using the LLM."""
56
+ # # # try:
57
+ # # # nickname = self.user_info.get("Nickname", "Guest")
58
 
59
+ # # # # Use the LLM to generate the message
60
+ # # # prompt = (
61
+ # # # f"Create a brief and warm welcome message for {nickname} that's about 1-2 sentences. "
62
+ # # # f"Emphasize this is a safe space for discussing gender-based violence issues "
63
+ # # # f"and that we provide support and resources. Keep it warm and reassuring."
64
+ # # # )
65
 
66
+ # # # response = self.llm.invoke(prompt)
67
+ # # # welcome = response.content.strip()
68
 
69
+ # # # # Format the message with HTML styling
70
+ # # # self.welcome_message = (
71
+ # # # f"<div style='font-size: 18px; color: #4E6BBF;'>"
72
+ # # # f"{welcome}"
73
+ # # # f"</div>"
74
+ # # # )
75
+ # # # except Exception as e:
76
+ # # # # Fallback welcome message
77
+ # # # nickname = self.user_info.get("Nickname", "Guest")
78
+ # # # self.welcome_message = (
79
+ # # # f"<div style='font-size: 18px; color: #4E6BBF;'>"
80
+ # # # f"Welcome, {nickname}! You're in a safe space. We're here to provide support with "
81
+ # # # f"gender-based violence issues and connect you with resources that can help."
82
+ # # # f"</div>"
83
+ # # # )
84
 
85
+ # # # def get_welcome_message(self):
86
+ # # # """Get the formatted welcome message."""
87
+ # # # if not self.welcome_message:
88
+ # # # self.generate_welcome_message()
89
+ # # # return self.welcome_message
90
 
91
+ # # # def add_to_history(self, role, message):
92
+ # # # """Add a message to the conversation history."""
93
+ # # # self.conversation_history.append({"role": role, "content": message})
94
+ # # # self.last_activity = time.time()
95
 
96
+ # # # # Trim history if it gets too long
97
+ # # # if len(self.conversation_history) > MAX_HISTORY_MESSAGES * 2: # Keep pairs of messages
98
+ # # # # Keep the first message (welcome) and the most recent messages
99
+ # # # self.conversation_history = [self.conversation_history[0]] + self.conversation_history[-MAX_HISTORY_MESSAGES*2+1:]
100
 
101
+ # # # def get_conversation_history(self):
102
+ # # # """Get the full conversation history."""
103
+ # # # return self.conversation_history
104
 
105
+ # # # def get_formatted_history(self):
106
+ # # # """Get conversation history formatted as a string for the LLM."""
107
+ # # # # Skip the welcome message and only include the last few exchanges
108
+ # # # recent_history = self.conversation_history[1:] if len(self.conversation_history) > 1 else []
109
 
110
+ # # # # Limit to last MAX_HISTORY_MESSAGES exchanges
111
+ # # # if len(recent_history) > MAX_HISTORY_MESSAGES * 2:
112
+ # # # recent_history = recent_history[-MAX_HISTORY_MESSAGES*2:]
113
 
114
+ # # # formatted_history = ""
115
+ # # # for entry in recent_history:
116
+ # # # role = "User" if entry["role"] == "user" else "Assistant"
117
+ # # # # Truncate very long messages to avoid token limits
118
+ # # # content = entry["content"]
119
+ # # # if len(content) > 500: # Limit message length
120
+ # # # content = content[:500] + "..."
121
+ # # # formatted_history += f"{role}: {content}\n\n"
122
 
123
+ # # # return formatted_history
124
 
125
+ # # # def is_expired(self, timeout_seconds=3600):
126
+ # # # """Check if the session has been inactive for too long."""
127
+ # # # return (time.time() - self.last_activity) > timeout_seconds
128
+
129
+ # # # # Session manager to handle multiple users
130
+ # # # class SessionManager:
131
+ # # # def __init__(self):
132
+ # # # """Initialize the session manager."""
133
+ # # # self.sessions = {}
134
+ # # # self.session_timeout = 3600 # 1 hour timeout
135
 
136
+ # # # def get_session(self, session_id):
137
+ # # # """Get an existing session or create a new one."""
138
+ # # # # Clean expired sessions first
139
+ # # # self._clean_expired_sessions()
140
 
141
+ # # # # Create new session if needed
142
+ # # # if session_id not in self.sessions:
143
+ # # # self.sessions[session_id] = UserSession(session_id, llm)
144
 
145
+ # # # return self.sessions[session_id]
146
 
147
+ # # # def _clean_expired_sessions(self):
148
+ # # # """Remove expired sessions to free up memory."""
149
+ # # # expired_keys = []
150
+ # # # for key, session in self.sessions.items():
151
+ # # # if session.is_expired(self.session_timeout):
152
+ # # # expired_keys.append(key)
153
 
154
+ # # # for key in expired_keys:
155
+ # # # del self.sessions[key]
156
 
157
+ # # # # Initialize the session manager
158
+ # # # session_manager = SessionManager()
159
 
160
+ # # # def initialize_assistant():
161
+ # # # """Initialize the assistant with necessary components and configurations."""
162
+ # # # global llm, embed_model, vectorstore, retriever, rag_chain
163
 
164
+ # # # # Initialize API key - try both possible key names
165
+ # # # groq_api_key = os.environ.get('GBV') or os.environ.get('GBV')
166
+ # # # if not groq_api_key:
167
+ # # # print("WARNING: No GROQ API key found in userdata.")
168
 
169
+ # # # # Initialize LLM - Default to Llama model which is more widely available
170
+ # # # llm = ChatGroq(
171
+ # # # model="llama-3.3-70b-versatile", # More reliable than whisper model
172
+ # # # api_key=groq_api_key
173
+ # # # )
174
 
175
+ # # # # Set up embedding model
176
+ # # # try:
177
+ # # # embed_model = HuggingFaceEmbeddings(model_name="mixedbread-ai/mxbai-embed-large-v1")
178
+ # # # except Exception as e:
179
+ # # # # Fallback to smaller model
180
+ # # # embed_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
181
 
182
+ # # # # Process data and create vector store
183
+ # # # print("Processing data files...")
184
+ # # # data = process_data_files()
185
 
186
+ # # # print("Creating vector store...")
187
+ # # # vectorstore = create_vectorstore(data)
188
+ # # # retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
189
 
190
+ # # # # Create RAG chain
191
+ # # # print("Setting up RAG chain...")
192
+ # # # rag_chain = create_rag_chain()
193
 
194
+ # # # print(f"✅ {APP_NAME} initialized successfully")
195
 
196
+ # # # def process_data_files():
197
+ # # # """Process all data files from the specified folder."""
198
+ # # # context_data = []
199
 
200
+ # # # try:
201
+ # # # if not os.path.exists(DATA_FOLDER):
202
+ # # # print(f"WARNING: Data folder does not exist: {DATA_FOLDER}")
203
+ # # # return context_data
204
 
205
+ # # # # Get list of data files
206
+ # # # all_files = os.listdir(DATA_FOLDER)
207
+ # # # data_files = [f for f in all_files if f.lower().endswith(('.csv', '.xlsx', '.xls'))]
208
 
209
+ # # # if not data_files:
210
+ # # # print(f"WARNING: No data files found in: {DATA_FOLDER}")
211
+ # # # return context_data
212
 
213
+ # # # # Process each file
214
+ # # # for index, file_name in enumerate(data_files, 1):
215
+ # # # print(f"Processing file {index}/{len(data_files)}: {file_name}")
216
+ # # # file_path = os.path.join(DATA_FOLDER, file_name)
217
 
218
+ # # # try:
219
+ # # # # Read file based on extension
220
+ # # # if file_name.lower().endswith('.csv'):
221
+ # # # df = pd.read_csv(file_path)
222
+ # # # else:
223
+ # # # df = pd.read_excel(file_path)
224
 
225
+ # # # # Check if column 3 exists (source data is in third column)
226
+ # # # if df.shape[1] > 2:
227
+ # # # column_data = df.iloc[:, 2].dropna().astype(str).tolist()
228
 
229
+ # # # # Each row becomes one chunk with metadata
230
+ # # # for i, text in enumerate(column_data):
231
+ # # # if text and len(text.strip()) > 0:
232
+ # # # context_data.append({
233
+ # # # "page_content": text,
234
+ # # # "metadata": {
235
+ # # # "source": file_name,
236
+ # # # "row": i+1
237
+ # # # }
238
+ # # # })
239
+ # # # else:
240
+ # # # print(f"WARNING: File {file_name} has fewer than 3 columns.")
241
 
242
+ # # # except Exception as e:
243
+ # # # print(f"ERROR processing file {file_name}: {e}")
244
 
245
+ # # # print(f"✅ Created {len(context_data)} chunks from {len(data_files)} files.")
246
 
247
+ # # # except Exception as e:
248
+ # # # print(f"ERROR accessing data folder: {e}")
249
 
250
+ # # # return context_data
251
 
252
+ # # # def create_vectorstore(data):
253
+ # # # """
254
+ # # # Creates and returns a Chroma vector store populated with the provided data.
255
+
256
+ # # # Parameters:
257
+ # # # data (list): A list of dictionaries, each containing 'page_content' and 'metadata'.
258
+
259
+ # # # Returns:
260
+ # # # Chroma: The populated Chroma vector store instance.
261
+ # # # """
262
+ # # # # Initialize the vector store
263
+ # # # vectorstore = Chroma(
264
+ # # # collection_name=COLLECTION_NAME,
265
+ # # # embedding_function=embed_model,
266
+ # # # persist_directory="./"
267
+ # # # )
268
+
269
+ # # # if not data:
270
+ # # # print("⚠️ No data provided. Returning an empty vector store.")
271
+ # # # return vectorstore
272
+
273
+ # # # try:
274
+ # # # # Extract text and metadata from the data
275
+ # # # texts = [doc["page_content"] for doc in data]
276
+
277
+ # # # # Add the texts and metadata to the vector store
278
+ # # # vectorstore.add_texts(texts)
279
+ # # # except Exception as e:
280
+ # # # print(f"❌ Failed to add documents to vector store: {e}")
281
+
282
+ # # # # Fix: Return vectorstore instead of vs
283
+ # # # return vectorstore # Changed from 'return vs' to 'return vectorstore'
284
+
285
+
286
+ # # # def create_rag_chain():
287
+ # # # """Create the RAG chain for processing user queries."""
288
+ # # # # Define the prompt template
289
+ # # # template = """
290
+ # # # You are a compassionate and supportive AI assistant specializing in helping individuals affected by Gender-Based Violence (GBV). Your responses must be based EXCLUSIVELY on the information provided in the context. Your primary goal is to provide emotionally intelligent support while maintaining appropriate boundaries.
291
 
292
+ # # # **Previous conversation:** {conversation_history}
293
+ # # # **Context information:** {context}
294
+ # # # **User's Question:** {question}
295
 
296
+ # # # When responding follow these guidelines:
297
 
298
+ # # # 1. **Strict Context Adherence**
299
+ # # # - Only use information that appears in the provided {context}
300
+ # # # - If the answer is not found in the context, state "I don't have that information in my available resources" rather than generating a response
301
 
302
+ # # # 2. **Personalized Communication**
303
+ # # # - Avoid contractions (e.g., use I am instead of I'm)
304
+ # # # - Incorporate thoughtful pauses or reflective questions when the conversation involves difficult topics
305
+ # # # - Use selective emojis (😊, 🤗, ❤️) only when tone-appropriate and not during crisis discussions
306
+ # # # - Balance warmth with professionalism
307
 
308
+ # # # 3. **Emotional Intelligence**
309
+ # # # - Validate feelings without judgment
310
+ # # # - Offer reassurance when appropriate, always centered on empowerment
311
+ # # # - Adjust your tone based on the emotional state conveyed
312
 
313
+ # # # 4. **Conversation Management**
314
+ # # # - Refer to {conversation_history} to maintain continuity and avoid repetition
315
+ # # # - Use clear paragraph breaks for readability
316
 
317
+ # # # 5. **Information Delivery**
318
+ # # # - Extract only relevant information from {context} that directly addresses the question
319
+ # # # - Present information in accessible, non-technical language
320
+ # # # - When information is unavailable, respond with: "I don't have that specific information right now, {first_name}. Would it be helpful if I focus on [alternative support option]?"
321
 
322
+ # # # 6. **Safety and Ethics**
323
+ # # # - Do not generate any speculative content or advice not supported by the context
324
+ # # # - If the context contains safety information, prioritize sharing that information
325
 
326
+ # # # Your response must come entirely from the provided context, maintaining the supportive tone while never introducing information from outside the provided materials.
327
+ # # # **Context:** {context}
328
+ # # # **User's Question:** {question}
329
+ # # # **Your Response:**
330
+ # # # """
331
 
332
 
333
+ # # # rag_prompt = PromptTemplate.from_template(template)
334
 
335
+ # # # def get_context_and_question(query_with_session):
336
+ # # # # Extract query and session_id
337
+ # # # query = query_with_session["query"]
338
+ # # # session_id = query_with_session["session_id"]
339
 
340
+ # # # # Get the user session
341
+ # # # session = session_manager.get_session(session_id)
342
+ # # # user_info = session.get_user()
343
+ # # # first_name = user_info.get("Nickname", "User")
344
+ # # # conversation_hist = session.get_formatted_history()
345
 
346
+ # # # try:
347
+ # # # # Retrieve relevant documents
348
+ # # # retrieved_docs = retriever.invoke(query)
349
+ # # # context_str = format_context(retrieved_docs)
350
+ # # # except Exception as e:
351
+ # # # print(f"ERROR retrieving documents: {e}")
352
+ # # # context_str = "No relevant information found."
353
 
354
+ # # # # Return the combined inputs for the prompt
355
+ # # # return {
356
+ # # # "context": context_str,
357
+ # # # "question": query,
358
+ # # # "first_name": first_name,
359
+ # # # "conversation_history": conversation_hist
360
+ # # # }
361
 
362
+ # # # # Build the chain
363
+ # # # try:
364
+ # # # chain = (
365
+ # # # RunnablePassthrough()
366
+ # # # | get_context_and_question
367
+ # # # | rag_prompt
368
+ # # # | llm
369
+ # # # | StrOutputParser()
370
+ # # # )
371
+ # # # return chain
372
+ # # # except Exception as e:
373
+ # # # print(f"ERROR creating RAG chain: {e}")
374
 
375
+ # # # # Return a simple function as fallback
376
+ # # # def fallback_chain(query_with_session):
377
+ # # # session_id = query_with_session["session_id"]
378
+ # # # session = session_manager.get_session(session_id)
379
+ # # # nickname = session.get_user().get("Nickname", "there")
380
+ # # # return f"I'm here to help you, {nickname}, but I'm experiencing some technical difficulties right now. Please try again shortly."
381
 
382
+ # # # return fallback_chain
383
+
384
+ # # # def format_context(retrieved_docs):
385
+ # # # """Format retrieved documents into a string context."""
386
+ # # # if not retrieved_docs:
387
+ # # # return "No relevant information available."
388
+ # # # return "\n\n".join([doc.page_content for doc in retrieved_docs])
389
+
390
+ # # # def rag_memory_stream(message, history, session_id):
391
+ # # # """Process user message and generate response with memory."""
392
+ # # # # Get the user session
393
+ # # # session = session_manager.get_session(session_id)
394
 
395
+ # # # # Add user message to history
396
+ # # # session.add_to_history("user", message)
397
 
398
+ # # # try:
399
+ # # # # Get response from RAG chain
400
+ # # # print(f"Processing message for session {session_id}: {message[:50]}...")
401
 
402
+ # # # # Pass both query and session_id to the chain
403
+ # # # response = rag_chain.invoke({
404
+ # # # "query": message,
405
+ # # # "session_id": session_id
406
+ # # # })
407
 
408
+ # # # print(f"Generated response: {response[:50]}...")
409
 
410
+ # # # # Add assistant response to history
411
+ # # # session.add_to_history("assistant", response)
412
 
413
+ # # # # Yield the response
414
+ # # # yield response
415
 
416
+ # # # except Exception as e:
417
+ # # # import traceback
418
+ # # # print(f"ERROR in rag_memory_stream: {e}")
419
+ # # # print(f"Detailed error: {traceback.format_exc()}")
420
 
421
+ # # # nickname = session.get_user().get("Nickname", "there")
422
+ # # # error_msg = f"I'm sorry, {nickname}. I encountered an error processing your request. Let's try a different question."
423
+ # # # session.add_to_history("assistant", error_msg)
424
+ # # # yield error_msg
425
+
426
+ # # # def collect_user_info(nickname, session_id):
427
+ # # # """Store user details and initialize session."""
428
+ # # # if not nickname or nickname.strip() == "":
429
+ # # # return "Nickname is required to proceed.", gr.update(visible=False), gr.update(visible=True), []
430
+
431
+ # # # # Store user info for chat session
432
+ # # # user_info = {
433
+ # # # "Nickname": nickname.strip(),
434
+ # # # "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
435
+ # # # }
436
+
437
+ # # # # Get the session and set user info
438
+ # # # session = session_manager.get_session(session_id)
439
+ # # # session.set_user(user_info)
440
+
441
+ # # # # Generate welcome message
442
+ # # # welcome_message = session.get_welcome_message()
443
+
444
+ # # # # Return welcome message and update UI
445
+ # # # return welcome_message, gr.update(visible=True), gr.update(visible=False), [(None, welcome_message)]
446
+
447
+ # # # def get_css():
448
+ # # # """Define CSS for the UI."""
449
+ # # # return """
450
+ # # # :root {
451
+ # # # --primary: #4E6BBF;
452
+ # # # --primary-light: #697BBF;
453
+ # # # --text-primary: #333333;
454
+ # # # --text-secondary: #666666;
455
+ # # # --background: #F9FAFC;
456
+ # # # --card-bg: #FFFFFF;
457
+ # # # --border: #E1E5F0;
458
+ # # # --shadow: rgba(0, 0, 0, 0.05);
459
+ # # # }
460
+
461
+ # # # body, .gradio-container {
462
+ # # # margin: 0;
463
+ # # # padding: 0;
464
+ # # # width: 100vw;
465
+ # # # height: 100vh;
466
+ # # # display: flex;
467
+ # # # flex-direction: column;
468
+ # # # justify-content: center;
469
+ # # # align-items: center;
470
+ # # # background: var(--background);
471
+ # # # color: var(--text-primary);
472
+ # # # font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
473
+ # # # }
474
+
475
+ # # # .gradio-container {
476
+ # # # max-width: 100%;
477
+ # # # max-height: 100%;
478
+ # # # }
479
+
480
+ # # # .gr-box {
481
+ # # # background: var(--card-bg);
482
+ # # # color: var(--text-primary);
483
+ # # # border-radius: 12px;
484
+ # # # padding: 2rem;
485
+ # # # border: 1px solid var(--border);
486
+ # # # box-shadow: 0 4px 12px var(--shadow);
487
+ # # # }
488
+
489
+ # # # .gr-button-primary {
490
+ # # # background: var(--primary);
491
+ # # # color: white;
492
+ # # # padding: 12px 24px;
493
+ # # # border-radius: 8px;
494
+ # # # transition: all 0.3s ease;
495
+ # # # border: none;
496
+ # # # font-weight: bold;
497
+ # # # }
498
+
499
+ # # # .gr-button-primary:hover {
500
+ # # # transform: translateY(-1px);
501
+ # # # box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
502
+ # # # background: var(--primary-light);
503
+ # # # }
504
+
505
+ # # # footer {
506
+ # # # text-align: center;
507
+ # # # color: var(--text-secondary);
508
+ # # # padding: 1rem;
509
+ # # # font-size: 0.9em;
510
+ # # # }
511
+
512
+ # # # .gr-markdown h2 {
513
+ # # # color: var(--primary);
514
+ # # # margin-bottom: 0.5rem;
515
+ # # # font-size: 1.8em;
516
+ # # # }
517
+
518
+ # # # .gr-markdown h3 {
519
+ # # # color: var(--text-secondary);
520
+ # # # margin-bottom: 1.5rem;
521
+ # # # font-weight: normal;
522
+ # # # }
523
+
524
+ # # # #chatbot_container .chat-title h1,
525
+ # # # #chatbot_container .empty-chatbot {
526
+ # # # color: var(--primary);
527
+ # # # }
528
+
529
+ # # # #input_nickname {
530
+ # # # padding: 12px;
531
+ # # # border-radius: 8px;
532
+ # # # border: 1px solid var(--border);
533
+ # # # background: var(--card-bg);
534
+ # # # transition: all 0.3s ease;
535
+ # # # }
536
 
537
+ # # # #input_nickname:focus {
538
+ # # # border-color: var(--primary);
539
+ # # # box-shadow: 0 0 0 2px rgba(78, 107, 191, 0.2);
540
+ # # # outline: none;
541
+ # # # }
542
+
543
+ # # # .chatbot-container .message.user {
544
+ # # # background: #E8F0FE;
545
+ # # # border-radius: 12px 12px 0 12px;
546
+ # # # }
547
+
548
+ # # # .chatbot-container .message.bot {
549
+ # # # background: #F5F7FF;
550
+ # # # border-radius: 12px 12px 12px 0;
551
+ # # # }
552
+ # # # """
553
+
554
+ # # # def create_ui():
555
+ # # # """Create and configure the Gradio UI."""
556
+ # # # with gr.Blocks(css=get_css(), theme=gr.themes.Soft()) as demo:
557
+ # # # # Create a unique session ID for this browser tab
558
+ # # # session_id = gr.State(value=f"session_{int(time.time())}_{os.urandom(4).hex()}")
559
 
560
+ # # # # Registration section
561
+ # # # with gr.Column(visible=True, elem_id="registration_container") as registration_container:
562
+ # # # gr.Markdown(f"## Welcome to {APP_NAME}")
563
+ # # # gr.Markdown("### Your privacy is important to us. Please provide a nickname to continue.")
564
+
565
+ # # # with gr.Row():
566
+ # # # first_name = gr.Textbox(
567
+ # # # label="Nickname",
568
+ # # # placeholder="Enter your nickname",
569
+ # # # scale=1,
570
+ # # # elem_id="input_nickname"
571
+ # # # )
572
+
573
+ # # # with gr.Row():
574
+ # # # submit_btn = gr.Button("Start Chatting", variant="primary", scale=2)
575
+
576
+ # # # response_message = gr.Markdown()
577
+
578
+ # # # # Chatbot section (initially hidden)
579
+ # # # with gr.Column(visible=False, elem_id="chatbot_container") as chatbot_container:
580
+ # # # # Create a custom chat interface to pass session_id to our function
581
+ # # # chatbot = gr.Chatbot(
582
+ # # # elem_id="chatbot",
583
+ # # # height=500,
584
+ # # # show_label=False
585
+ # # # )
586
+
587
+ # # # with gr.Row():
588
+ # # # msg = gr.Textbox(
589
+ # # # placeholder="Type your message here...",
590
+ # # # show_label=False,
591
+ # # # container=False,
592
+ # # # scale=9
593
+ # # # )
594
+ # # # submit = gr.Button("Send", scale=1, variant="primary")
595
 
596
+ # # # examples = gr.Examples(
597
+ # # # examples=[
598
+ # # # "What resources are available for GBV victims?",
599
+ # # # "How can I report an incident?",
600
+ # # # "What are my legal rights?",
601
+ # # # "I need help, what should I do first?"
602
+ # # # ],
603
+ # # # inputs=msg
604
+ # # # )
605
+
606
+ # # # # Footer with version info
607
+ # # # gr.Markdown(f"{APP_NAME} {APP_VERSION} © 2025")
608
 
609
+ # # # # Handle chat message submission
610
+ # # # def respond(message, chat_history, session_id):
611
+ # # # bot_message = ""
612
+ # # # for chunk in rag_memory_stream(message, chat_history, session_id):
613
+ # # # bot_message += chunk
614
+ # # # chat_history.append((message, bot_message))
615
+ # # # return "", chat_history
 
 
 
 
 
616
 
617
+ # # # msg.submit(respond, [msg, chatbot, session_id], [msg, chatbot])
618
+ # # # submit.click(respond, [msg, chatbot, session_id], [msg, chatbot])
619
+
620
+ # # # # Handle user registration
621
+ # # # submit_btn.click(
622
+ # # # collect_user_info,
623
+ # # # inputs=[first_name, session_id],
624
+ # # # outputs=[response_message, chatbot_container, registration_container, chatbot]
625
+ # # # )
626
+
627
+ # # # return demo
628
+
629
+ # # # def launch_app():
630
+ # # # """Launch the Gradio interface."""
631
+ # # # ui = create_ui()
632
+ # # # ui.launch(share=True)
633
+
634
+ # # # # Main execution
635
+ # # # if __name__ == "__main__":
636
+ # # # try:
637
+ # # # # Initialize and launch the assistant
638
+ # # # initialize_assistant()
639
+ # # # launch_app()
640
+ # # # except Exception as e:
641
+ # # # import traceback
642
+ # # # print(f"❌ Fatal error initializing GBV Assistant: {e}")
643
+ # # # print(traceback.format_exc())
644
+
645
+ # # # # Create a minimal emergency UI to display the error
646
+ # # # with gr.Blocks() as error_demo:
647
+ # # # gr.Markdown("## System Error")
648
+ # # # gr.Markdown(f"An error occurred while initializing the application: {str(e)}")
649
+ # # # gr.Markdown("Please check your configuration and try again.")
650
 
651
+ # # # error_demo.launch(share=True, inbrowser=True, debug=True)
 
652
 
 
 
 
 
 
 
653
 
 
654
 
655
+ # # ############################################################################################################
 
 
 
656
 
657
+
658
+ # # import os
659
+ # # from langchain_groq import ChatGroq
660
+ # # from langchain.prompts import ChatPromptTemplate, PromptTemplate
661
+ # # from langchain.output_parsers import ResponseSchema, StructuredOutputParser
662
+ # # from urllib.parse import urljoin, urlparse
663
+ # # import requests
664
+ # # from io import BytesIO
665
+ # # from langchain_chroma import Chroma
666
+ # # import requests
667
+ # # from bs4 import BeautifulSoup
668
+ # # from langchain_core.prompts import ChatPromptTemplate
669
+ # # import gradio as gr
670
+ # # from PyPDF2 import PdfReader
671
+ # # from langchain_huggingface import HuggingFaceEmbeddings
672
+
673
+ # # groq_api_key= os.environ.get('GBV')
674
+
675
+ # # embed_model = HuggingFaceEmbeddings(model_name="mixedbread-ai/mxbai-embed-large-v1")
676
+
677
+ # # def scrape_websites(base_urls):
678
  # # try:
679
+ # # visited_links = set() # To avoid revisiting the same link
680
+ # # content_by_url = {} # Store content from each URL
681
+
682
+ # # for base_url in base_urls:
683
+ # # if not base_url.strip():
684
+ # # continue # Skip empty or invalid URLs
685
+
686
+ # # print(f"Scraping base URL: {base_url}")
687
+ # # html_content = fetch_page_content(base_url)
688
+ # # if html_content:
689
+ # # cleaned_content = clean_body_content(html_content)
690
+ # # content_by_url[base_url] = cleaned_content
691
+ # # visited_links.add(base_url)
692
+
693
+ # # # Extract and process all internal links
694
+ # # soup = BeautifulSoup(html_content, "html.parser")
695
+ # # links = extract_internal_links(base_url, soup)
696
+
697
+ # # for link in links:
698
+ # # if link not in visited_links:
699
+ # # print(f"Scraping link: {link}")
700
+ # # page_content = fetch_page_content(link)
701
+ # # if page_content:
702
+ # # cleaned_content = clean_body_content(page_content)
703
+ # # content_by_url[link] = cleaned_content
704
+ # # visited_links.add(link)
705
+
706
+ # # # If the link is a PDF file, extract its content
707
+ # # if link.lower().endswith('.pdf'):
708
+ # # print(f"Extracting PDF content from: {link}")
709
+ # # pdf_content = extract_pdf_text(link)
710
+ # # if pdf_content:
711
+ # # content_by_url[link] = pdf_content
712
+
713
+ # # return content_by_url
714
+
715
  # # except Exception as e:
716
+ # # print(f"Error during scraping: {e}")
717
+ # # return {}
718
+
719
+
720
+ # # def fetch_page_content(url):
721
+ # # try:
722
+ # # response = requests.get(url, timeout=10)
723
+ # # response.raise_for_status()
724
+ # # return response.text
725
+ # # except requests.exceptions.RequestException as e:
726
+ # # print(f"Error fetching {url}: {e}")
727
+ # # return None
728
+
729
+
730
+ # # def extract_internal_links(base_url, soup):
731
+ # # links = set()
732
+ # # for anchor in soup.find_all("a", href=True):
733
+ # # href = anchor["href"]
734
+ # # full_url = urljoin(base_url, href)
735
+ # # if is_internal_link(base_url, full_url):
736
+ # # links.add(full_url)
737
+ # # return links
738
+
739
+
740
+ # # def is_internal_link(base_url, link_url):
741
+ # # base_netloc = urlparse(base_url).netloc
742
+ # # link_netloc = urlparse(link_url).netloc
743
+ # # return base_netloc == link_netloc
744
+
745
+
746
+ # # def extract_pdf_text(pdf_url):
747
+ # # try:
748
+ # # response = requests.get(pdf_url)
749
+ # # response.raise_for_status()
750
+ # # with BytesIO(response.content) as file:
751
+ # # reader = PdfReader(file)
752
+ # # pdf_text = ""
753
+ # # for page in reader.pages:
754
+ # # pdf_text += page.extract_text()
755
+
756
+ # # return pdf_text if pdf_text else None
757
+ # # except requests.exceptions.RequestException as e:
758
+ # # print(f"Error fetching PDF {pdf_url}: {e}")
759
+ # # return None
760
+ # # except Exception as e:
761
+ # # print(f"Error reading PDF {pdf_url}: {e}")
762
+ # # return None
763
+
764
+
765
+ # # def clean_body_content(html_content):
766
+ # # soup = BeautifulSoup(html_content, "html.parser")
767
+
768
+
769
+ # # for script_or_style in soup(["script", "style"]):
770
+ # # script_or_style.extract()
771
+
772
+
773
+ # # cleaned_content = soup.get_text(separator="\n")
774
+ # # cleaned_content = "\n".join(
775
+ # # line.strip() for line in cleaned_content.splitlines() if line.strip()
776
+ # # )
777
+ # # return cleaned_content
778
+
779
+
780
+ # # if __name__ == "__main__":
781
+ # # website = ["https://haguruka.org.rw/"
782
+
783
+ # # ]
784
+ # # all_content = scrape_websites(website)
785
+
786
+ # # temp_list = []
787
+ # # for url, content in all_content.items():
788
+ # # temp_list.append((url, content))
789
+
790
+
791
+ # # processed_texts = []
792
 
793
+
794
+ # # for element in temp_list:
795
+ # # if isinstance(element, tuple):
796
+ # # url, content = element
797
+ # # processed_texts.append(f"url: {url}, content: {content}")
798
+ # # elif isinstance(element, str):
799
+ # # processed_texts.append(element)
800
+ # # else:
801
+ # # processed_texts.append(str(element))
802
+
803
+ # # def chunk_string(s, chunk_size=1000):
804
+ # # return [s[i:i+chunk_size] for i in range(0, len(s), chunk_size)]
805
+
806
+ # # chunked_texts = []
807
+
808
+ # # for text in processed_texts:
809
+ # # chunked_texts.extend(chunk_string(text))
810
+
811
+
812
+
813
+
814
+
815
+ # # vectorstore = Chroma(
816
+ # # collection_name="GBVR_Dataset",
817
+ # # embedding_function=embed_model,
818
+ # # persist_directory="./",
819
+ # # )
820
+
821
+ # # vectorstore.get().keys()
822
+
823
+ # # vectorstore.add_texts(chunked_texts)
824
+
825
+
826
+ # # template = ("""
827
+ # # You are a friendly, intelligent, and conversational AI assistant designed to provide accurate, engaging, and human-like responses based on the given context. Your goal is to extract relevant details from the provided context: {context} and assist the user effectively. Follow these guidelines:
828
+
829
+ # # 1. **Warm & Natural Interaction**
830
+ # # - If the user greets you (e.g., "Hello," "Hi," "Good morning"), respond warmly and acknowledge them.
831
+ # # - Example responses:
832
+ # # - "😊 Good morning! How can I assist you today?"
833
+ # # - "Hello! What can I do for you? 🚀"
834
+
835
+ # # 2. **Precise Information Extraction**
836
+ # # - Provide only the relevant details from the given context: {context}.
837
+ # # - Do not generate extra content or assumptions beyond the provided information.
838
+
839
+ # # 3. **Conversational & Engaging Tone**
840
+ # # - Keep responses friendly, natural, and engaging.
841
+ # # - Use occasional emojis (e.g., 😊, 🚀) to make interactions more lively.
842
+
843
+ # # 4. **Awareness of Real-Time Context**
844
+ # # - If necessary, acknowledge the current date and time to show awareness of real-world updates.
845
 
846
+ # # 5. **Handling Missing Information**
847
+ # # - If no relevant information exists in the context, respond politely:
848
+ # # - "I don't have that information at the moment, but I'm happy to help with something else! 😊"
849
 
850
+ # # 6. **Personalized Interaction**
851
+ # # - If user history is available, tailor responses based on their previous interactions for a more natural and engaging conversation.
852
+
853
+ # # 7. **Direct, Concise Responses**
854
+ # # - If the user requests specific data, provide only the requested details without unnecessary explanations unless asked.
855
+
856
+ # # 8. **Extracting Relevant Links**
857
+ # # - If the user asks for a link related to their request `{question}`, extract the most relevant URL from `{context}` and provide it directly.
858
+ # # - Example response:
859
+ # # - "Here is the link you requested: [URL]"
860
+
861
+ # # **Context:** {context}
862
+ # # **User's Question:** {question}
863
+ # # **Your Response:**
864
+ # # """)
865
+
866
+
867
+ # # rag_prompt = PromptTemplate.from_template(template)
868
+
869
+ # # retriever = vectorstore.as_retriever()
870
+
871
+ # # from langchain_core.output_parsers import StrOutputParser
872
+ # # from langchain_core.runnables import RunnablePassthrough
873
+
874
+ # # llm = ChatGroq(model="llama-3.3-70b-versatile", api_key=groq_api_key )
875
+
876
+ # # rag_chain = (
877
+ # # {"context": retriever, "question": RunnablePassthrough()}
878
+ # # | rag_prompt
879
+ # # | llm
880
+ # # | StrOutputParser()
881
+ # # )
882
+
883
+
884
+ # # # Define the RAG memory stream function
885
+ # # def rag_memory_stream(message, history):
886
+ # # partial_text = ""
887
+ # # for new_text in rag_chain.stream(message): # Replace with actual streaming logic
888
+ # # partial_text += new_text
889
+ # # yield partial_text
890
+
891
+ # # # Title with emojis
892
+ # # title = "GBVR Chatbot"
893
+
894
+
895
+ # # # Custom CSS for styling the interface
896
+ # # custom_css = """
897
+ # # body {
898
+ # # font-family: "Arial", serif;
899
+ # # }
900
+ # # .gradio-container {
901
+ # # font-family: "Times New Roman", serif;
902
+ # # }
903
+ # # .gr-button {
904
+ # # background-color: #007bff; /* Blue button */
905
+ # # color: white;
906
+ # # border: none;
907
+ # # border-radius: 5px;
908
+ # # font-size: 16px;
909
+ # # padding: 10px 20px;
910
+ # # cursor: pointer;
911
+ # # }
912
+ # # .gr-textbox:focus, .gr-button:focus {
913
+ # # outline: none; /* Remove outline focus for a cleaner look */
914
+ # # }
915
+
916
+ # # """
917
+
918
+ # # # Create the Chat Interface
919
+ # # demo = gr.ChatInterface(
920
+ # # fn=rag_memory_stream,
921
+ # # title=title,
922
+ # # fill_height=True,
923
+ # # theme="soft",
924
+ # # css=custom_css, # Apply the custom CSS
925
+ # # )
926
+
927
+ # # # Launch the app
928
+ # # if __name__ == "__main__":
929
+ # # demo.launch(share=True, inbrowser=True, debug=True)
930
 
931
 
932
  # import os
 
943
  # import gradio as gr
944
  # from PyPDF2 import PdfReader
945
  # from langchain_huggingface import HuggingFaceEmbeddings
946
+ # from langchain_core.output_parsers import StrOutputParser
947
+ # from langchain_core.runnables import RunnablePassthrough
948
+
949
+ # # Simple session management
950
+ # class SessionManager:
951
+ # def __init__(self):
952
+ # self.sessions = {}
953
+
954
+ # def get_or_create_session(self, session_id):
955
+ # if session_id not in self.sessions:
956
+ # self.sessions[session_id] = []
957
+ # return self.sessions[session_id]
958
+
959
+ # def add_interaction(self, session_id, user_message, ai_response):
960
+ # session = self.get_or_create_session(session_id)
961
+ # session.append({"user": user_message, "ai": ai_response})
962
+
963
+ # def get_history(self, session_id, max_turns=5):
964
+ # session = self.get_or_create_session(session_id)
965
+ # recent_history = session[-max_turns:] if len(session) > max_turns else session
966
+
967
+ # history_text = ""
968
+ # for interaction in recent_history:
969
+ # history_text += f"User: {interaction['user']}\n"
970
+ # history_text += f"Assistant: {interaction['ai']}\n\n"
971
+
972
+ # return history_text.strip()
973
+
974
+ # # Initialize session manager
975
+ # session_manager = SessionManager()
976
 
977
  # groq_api_key= os.environ.get('GBV')
978
 
 
1113
  # chunked_texts.extend(chunk_string(text))
1114
 
1115
 
 
 
 
1116
  # vectorstore = Chroma(
1117
  # collection_name="GBVR_Dataset",
1118
  # embedding_function=embed_model,
 
1123
 
1124
  # vectorstore.add_texts(chunked_texts)
1125
 
1126
+ # # Updated template to include conversation history
1127
  # template = ("""
1128
  # You are a friendly, intelligent, and conversational AI assistant designed to provide accurate, engaging, and human-like responses based on the given context. Your goal is to extract relevant details from the provided context: {context} and assist the user effectively. Follow these guidelines:
1129
 
 
1149
  # - "I don't have that information at the moment, but I'm happy to help with something else! 😊"
1150
 
1151
  # 6. **Personalized Interaction**
1152
+ # - Use the conversation history to provide more personalized and contextually relevant responses.
1153
+ # - Previous conversation history: {conversation_history}
1154
 
1155
  # 7. **Direct, Concise Responses**
1156
  # - If the user requests specific data, provide only the requested details without unnecessary explanations unless asked.
 
1170
 
1171
  # retriever = vectorstore.as_retriever()
1172
 
1173
+ # llm = ChatGroq(model="llama-3.3-70b-versatile", api_key=groq_api_key)
 
1174
 
1175
+ # # Dictionary to store user sessions with session IDs
1176
+ # user_sessions = {}
 
 
 
 
 
 
1177
 
1178
+ # # Define the RAG chain with session history
1179
+ # def rag_chain(question, session_id="default"):
1180
+ # # Get conversation history if available
1181
+ # conversation_history = session_manager.get_history(session_id)
1182
+
1183
+ # # Get context from retriever
1184
+ # context_docs = retriever.invoke(question)
1185
+ # context = "\n".join(doc.page_content for doc in context_docs)
1186
+
1187
+ # # Create prompt with history
1188
+ # prompt = rag_prompt.format(
1189
+ # context=context,
1190
+ # question=question,
1191
+ # conversation_history=conversation_history
1192
+ # )
1193
+
1194
+ # # Generate response
1195
+ # response = llm.invoke(prompt).content
1196
+
1197
+ # # Store the interaction
1198
+ # session_manager.add_interaction(session_id, question, response)
1199
+
1200
+ # return response
1201
 
1202
  # # Define the RAG memory stream function
1203
  # def rag_memory_stream(message, history):
1204
+ # # Generate a session ID based on the first message if not exists
1205
+ # session_id = None
1206
+ # for msg in history:
1207
+ # if msg[0]: # If there's a user message
1208
+ # # Use first few characters of first message as simple session ID
1209
+ # session_id = hash(msg[0][:20]) if session_id is None else session_id
1210
+ # break
1211
+
1212
+ # # Default session ID if history is empty
1213
+ # if session_id is None:
1214
+ # session_id = "default_session"
1215
+
1216
+ # # Process the message and get response
1217
+ # response = rag_chain(message, str(session_id))
1218
+
1219
+ # # Stream the response word by word
1220
  # partial_text = ""
1221
+ # words = response.split(' ')
1222
+ # for word in words:
1223
+ # partial_text += word + " "
1224
+ # yield partial_text.strip()
1225
 
1226
  # # Title with emojis
1227
  # title = "GBVR Chatbot"
1228
 
 
1229
  # # Custom CSS for styling the interface
1230
  # custom_css = """
1231
  # body {
 
1246
  # .gr-textbox:focus, .gr-button:focus {
1247
  # outline: none; /* Remove outline focus for a cleaner look */
1248
  # }
 
1249
  # """
1250
 
1251
  # # Create the Chat Interface
 
1260
  # # Launch the app
1261
  # if __name__ == "__main__":
1262
  # demo.launch(share=True, inbrowser=True, debug=True)
 
 
1263
  import os
1264
  from langchain_groq import ChatGroq
1265
  from langchain.prompts import ChatPromptTemplate, PromptTemplate
 
1445
 
1446
 
1447
  vectorstore = Chroma(
1448
+ collection_name="GBVR_Datast",
1449
  embedding_function=embed_model,
1450
  persist_directory="./",
1451
  )
 
1559
 
1560
  # Custom CSS for styling the interface
1561
  custom_css = """
1562
+ /* Custom CSS for styling the interface */
1563
  body {
1564
  font-family: "Arial", serif;
1565
  }
1566
+
1567
  .gradio-container {
1568
  font-family: "Times New Roman", serif;
1569
  }
1570
+
1571
  .gr-button {
1572
  background-color: #007bff; /* Blue button */
1573
  color: white;
 
1577
  padding: 10px 20px;
1578
  cursor: pointer;
1579
  }
1580
+
1581
  .gr-textbox:focus, .gr-button:focus {
1582
  outline: none; /* Remove outline focus for a cleaner look */
1583
  }
1584
+
1585
+ /* Specific CSS for the welcome message */
1586
+ .gradio-description {
1587
+ font-size: 30px; /* Set font size for the welcome message */
1588
+ font-family: "Arial", sans-serif;
1589
+ text-align: center; /* Optional: Center-align the text */
1590
+ padding: 20px; /* Optional: Add padding around the welcome message */
1591
+ }
1592
+
1593
  """
1594
 
1595
+ # Generate a simple welcome message using the LLM
1596
+ def generate_welcome_message():
1597
+ welcome_prompt = """
1598
+ Generate a short, simple welcome message for a chatbot about Gender-Based Violence Resources in Rwanda.
1599
+ Keep it under 3 sentences, and use simple language.
1600
+ Make it warm and supportive but direct and easy to read.
1601
+ """
1602
+
1603
+ # Get the welcome message from the LLM
1604
+ welcome_message = llm.invoke(welcome_prompt).content
1605
+ return welcome_message
1606
+
1607
+ # Create simple welcome message
1608
+ welcome_msg = generate_welcome_message()
1609
+
1610
+ # Create the Chat Interface with welcome message
1611
  demo = gr.ChatInterface(
1612
  fn=rag_memory_stream,
1613
  title=title,
1614
  fill_height=True,
1615
  theme="soft",
1616
  css=custom_css, # Apply the custom CSS
1617
+ description=welcome_msg
1618
  )
1619
 
1620
  # Launch the app