Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -356,75 +356,88 @@ class UserSession:
|
|
356 |
def __init__(self):
|
357 |
self.current_user = None
|
358 |
self.welcome_message = None
|
359 |
-
|
|
|
360 |
def set_user(self, user_info):
|
361 |
self.current_user = user_info
|
362 |
-
self.set_welcome_message(user_info.get("
|
363 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
364 |
def get_user(self):
|
365 |
return self.current_user
|
366 |
-
|
367 |
-
def set_welcome_message(self,
|
368 |
self.welcome_message = (
|
369 |
-
f"<div style='font-size:
|
370 |
-
f"Welcome {
|
371 |
-
f"<div style='font-size:
|
372 |
f"We appreciate you reaching out to us. You are in a safe and trusted space designed to support you. "
|
373 |
-
f"Here, you can find guidance on gender-based violence (GBV) and legal assistance.<br><br>"
|
374 |
f"</div>"
|
375 |
)
|
376 |
|
377 |
-
|
378 |
-
# f"You don’t have to go through this alone—we are here to listen, support, and help you find the right solutions. "
|
379 |
-
# f"You deserve to be heard and helped, and we are committed to standing by your side."
|
380 |
-
#f"</div>"
|
381 |
-
|
382 |
def get_welcome_message(self):
|
383 |
return self.welcome_message
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
384 |
|
385 |
# Initialize session
|
386 |
user_session = UserSession()
|
387 |
|
388 |
# Store user details and handle session
|
389 |
-
def collect_user_info(
|
390 |
-
if not
|
391 |
-
return "
|
392 |
-
|
393 |
-
# Validate phone number (basic validation)
|
394 |
-
if not phone.replace("+", "").replace("-", "").replace(" ", "").isdigit():
|
395 |
-
return "Please enter a valid phone number.", gr.update(visible=False), gr.update(visible=True), []
|
396 |
-
|
397 |
# Store user info for chat session
|
398 |
user_info = {
|
399 |
-
"
|
400 |
-
"last_name": last_name,
|
401 |
-
"phone": phone,
|
402 |
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
|
403 |
}
|
404 |
-
|
405 |
# Set user in session
|
406 |
user_session.set_user(user_info)
|
407 |
-
|
408 |
# Generate welcome message
|
409 |
welcome_message = user_session.get_welcome_message()
|
410 |
-
|
411 |
# Add initial message to start the conversation
|
412 |
chat_history = add_initial_message([(None, welcome_message)])
|
413 |
-
|
414 |
# Return welcome message and update UI
|
415 |
return welcome_message, gr.update(visible=True), gr.update(visible=False), chat_history
|
416 |
|
417 |
# Add initial message to start the conversation
|
418 |
def add_initial_message(chatbot):
|
419 |
initial_message = (
|
420 |
-
"<div style='font-size:
|
421 |
-
f"I just want to check in and see how you are doing."
|
422 |
f"If you are going through something, please know you are not alone, I am here for you, no matter what.🤗"
|
423 |
"</div>"
|
424 |
)
|
425 |
return chatbot + [(None, initial_message)]
|
426 |
|
427 |
-
# Create RAG chain with user context
|
428 |
def create_rag_chain(retriever, template, api_key):
|
429 |
llm = OpenRouterLLM(api_key)
|
430 |
rag_prompt = PromptTemplate.from_template(template)
|
@@ -433,16 +446,20 @@ def create_rag_chain(retriever, template, api_key):
|
|
433 |
# Get context using the retriever's invoke method
|
434 |
context = retriever.invoke(input_dict["question"])
|
435 |
context_str = "\n".join([doc.page_content for doc in context])
|
436 |
-
|
437 |
# Get user info from the session
|
438 |
user_info = user_session.get_user() or {}
|
439 |
-
first_name = user_info.get("
|
440 |
|
441 |
-
#
|
|
|
|
|
|
|
442 |
prompt = rag_prompt.format(
|
443 |
context=context_str,
|
444 |
question=input_dict["question"],
|
445 |
-
first_name=first_name
|
|
|
446 |
)
|
447 |
|
448 |
# Stream response
|
@@ -451,34 +468,50 @@ def create_rag_chain(retriever, template, api_key):
|
|
451 |
return stream_func
|
452 |
|
453 |
def rag_memory_stream(message, history):
|
|
|
|
|
|
|
454 |
# Initialize with empty response
|
455 |
partial_text = ""
|
456 |
-
|
457 |
-
|
458 |
-
user_info = user_session.get_user()
|
459 |
-
|
460 |
# Use the rag_chain with the question
|
461 |
for new_text in rag_chain({"question": message}):
|
462 |
partial_text += new_text
|
|
|
463 |
yield partial_text
|
|
|
|
|
|
|
464 |
|
465 |
# Gradio Interface Setup with improved UX
|
466 |
def chatbot_interface():
|
467 |
# Get API key (in a real application, handle this more securely)
|
468 |
api_key = api # This should be properly defined or imported elsewhere
|
469 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
470 |
# Create the RAG chain with user context
|
471 |
global rag_chain
|
472 |
rag_chain = create_rag_chain(retriever, template, api_key)
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
secondary_hue="blue",
|
478 |
-
)
|
479 |
-
|
480 |
-
with gr.Blocks(theme=theme, css="""
|
481 |
-
.welcome-container {
|
482 |
text-align: center;
|
483 |
margin-bottom: 20px;
|
484 |
padding: 20px;
|
@@ -488,74 +521,45 @@ def chatbot_interface():
|
|
488 |
.feedback-btn { margin-top: 10px; }
|
489 |
footer { margin-top: 30px; text-align: center; }
|
490 |
""") as demo:
|
491 |
-
# Welcome banner
|
492 |
-
gr.Markdown("# 🤖 Ijwi ry'Ubufasha - Your AI Assistant", elem_classes=["welcome-container"])
|
493 |
-
|
494 |
# User registration section
|
495 |
registration_container = gr.Column(visible=True)
|
496 |
with registration_container:
|
497 |
-
gr.Markdown("###
|
498 |
-
|
499 |
with gr.Row():
|
500 |
first_name = gr.Textbox(
|
501 |
-
label="
|
502 |
-
placeholder="Enter your
|
503 |
scale=1
|
504 |
)
|
505 |
-
|
506 |
-
label="Last Name",
|
507 |
-
placeholder="Enter your last name",
|
508 |
-
scale=1
|
509 |
-
)
|
510 |
-
|
511 |
-
phone = gr.Textbox(
|
512 |
-
label="Phone Number",
|
513 |
-
placeholder="Enter your phone number (e.g., +250...)",
|
514 |
-
)
|
515 |
-
|
516 |
with gr.Row():
|
517 |
submit_btn = gr.Button("Start Chatting", variant="primary", scale=2)
|
518 |
-
|
519 |
response_message = gr.Markdown(elem_id="welcome-message")
|
520 |
-
|
521 |
# Chatbot section (initially hidden)
|
522 |
chatbot_container = gr.Column(visible=False)
|
523 |
with chatbot_container:
|
524 |
chat_interface = gr.ChatInterface(
|
525 |
fn=rag_memory_stream,
|
526 |
-
title="
|
527 |
fill_height=True,
|
528 |
-
theme=theme
|
529 |
)
|
530 |
-
|
531 |
-
# Feedback buttons
|
532 |
-
with gr.Row():
|
533 |
-
feedback_label = gr.Markdown("### Was this conversation helpful?")
|
534 |
-
|
535 |
-
with gr.Row():
|
536 |
-
thumbs_up = gr.Button("👍 Yes, it was helpful", elem_classes=["feedback-btn"])
|
537 |
-
thumbs_down = gr.Button("👎 No, it needs improvement", elem_classes=["feedback-btn"])
|
538 |
-
|
539 |
# Footer with version info
|
540 |
gr.Markdown("Ijwi ry'Ubufasha v1.0.0 © 2025", elem_id="footer")
|
541 |
-
|
542 |
# Handle user registration
|
543 |
submit_btn.click(
|
544 |
-
collect_user_info,
|
545 |
-
inputs=[first_name
|
546 |
outputs=[response_message, chatbot_container, registration_container, chat_interface.chatbot]
|
547 |
)
|
548 |
-
|
549 |
-
# Handle feedback (placeholder functionality)
|
550 |
-
def record_feedback(feedback_type):
|
551 |
-
# Here you could log feedback to a file or database
|
552 |
-
feedback_message = f"Thank you for your feedback! We'll use it to improve our service."
|
553 |
-
return feedback_message
|
554 |
-
|
555 |
-
thumbs_up.click(lambda: record_feedback("positive"), outputs=feedback_label)
|
556 |
-
thumbs_down.click(lambda: record_feedback("negative"), outputs=feedback_label)
|
557 |
-
|
558 |
return demo
|
559 |
|
|
|
560 |
if __name__ == "__main__":
|
|
|
561 |
chatbot_interface().launch(share=True, inbrowser=True)
|
|
|
356 |
def __init__(self):
|
357 |
self.current_user = None
|
358 |
self.welcome_message = None
|
359 |
+
self.conversation_history = [] # Add conversation history storage
|
360 |
+
|
361 |
def set_user(self, user_info):
|
362 |
self.current_user = user_info
|
363 |
+
self.set_welcome_message(user_info.get("Nickname", "Guest"))
|
364 |
+
# Initialize conversation history with welcome message
|
365 |
+
welcome = self.get_welcome_message()
|
366 |
+
initial_message = (
|
367 |
+
"<div style='font-size: 20px; font-weight: normal; color: #FFFFFF;'>"
|
368 |
+
f"If you are going through something, please know you are not alone, I am here for you, no matter what.🤗"
|
369 |
+
"</div>"
|
370 |
+
)
|
371 |
+
self.conversation_history = [
|
372 |
+
{"role": "assistant", "content": welcome},
|
373 |
+
{"role": "assistant", "content": initial_message}
|
374 |
+
]
|
375 |
+
|
376 |
def get_user(self):
|
377 |
return self.current_user
|
378 |
+
|
379 |
+
def set_welcome_message(self, Nickname):
|
380 |
self.welcome_message = (
|
381 |
+
f"<div style='font-size: 24px; font-weight: bold; color: #2E86C1;'>"
|
382 |
+
f"Welcome {Nickname}! 👋</div>"
|
383 |
+
f"<div style='font-size: 20px; color: #FFFFFF;'>"
|
384 |
f"We appreciate you reaching out to us. You are in a safe and trusted space designed to support you. "
|
385 |
+
f"Here, you can find guidance on gender-based violence (GBV) and legal assistance.<br><br>"
|
386 |
f"</div>"
|
387 |
)
|
388 |
|
|
|
|
|
|
|
|
|
|
|
389 |
def get_welcome_message(self):
|
390 |
return self.welcome_message
|
391 |
+
|
392 |
+
def add_to_history(self, role, message):
|
393 |
+
self.conversation_history.append({"role": role, "content": message})
|
394 |
+
|
395 |
+
def get_conversation_history(self):
|
396 |
+
return self.conversation_history
|
397 |
+
|
398 |
+
def get_formatted_history(self):
|
399 |
+
formatted_history = ""
|
400 |
+
for entry in self.conversation_history:
|
401 |
+
role = "User" if entry["role"] == "user" else "Assistant"
|
402 |
+
formatted_history += f"{role}: {entry['content']}\n\n"
|
403 |
+
return formatted_history
|
404 |
|
405 |
# Initialize session
|
406 |
user_session = UserSession()
|
407 |
|
408 |
# Store user details and handle session
|
409 |
+
def collect_user_info(Nickname):
|
410 |
+
if not Nickname:
|
411 |
+
return "Nickname is required to proceed.", gr.update(visible=False), gr.update(visible=True), []
|
412 |
+
|
|
|
|
|
|
|
|
|
413 |
# Store user info for chat session
|
414 |
user_info = {
|
415 |
+
"Nickname": Nickname,
|
|
|
|
|
416 |
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
|
417 |
}
|
418 |
+
|
419 |
# Set user in session
|
420 |
user_session.set_user(user_info)
|
421 |
+
|
422 |
# Generate welcome message
|
423 |
welcome_message = user_session.get_welcome_message()
|
424 |
+
|
425 |
# Add initial message to start the conversation
|
426 |
chat_history = add_initial_message([(None, welcome_message)])
|
427 |
+
|
428 |
# Return welcome message and update UI
|
429 |
return welcome_message, gr.update(visible=True), gr.update(visible=False), chat_history
|
430 |
|
431 |
# Add initial message to start the conversation
|
432 |
def add_initial_message(chatbot):
|
433 |
initial_message = (
|
434 |
+
"<div style='font-size: 20px; font-weight: normal; color: #FFFFFF;'>"
|
|
|
435 |
f"If you are going through something, please know you are not alone, I am here for you, no matter what.🤗"
|
436 |
"</div>"
|
437 |
)
|
438 |
return chatbot + [(None, initial_message)]
|
439 |
|
440 |
+
# Create RAG chain with user context and conversation history
|
441 |
def create_rag_chain(retriever, template, api_key):
|
442 |
llm = OpenRouterLLM(api_key)
|
443 |
rag_prompt = PromptTemplate.from_template(template)
|
|
|
446 |
# Get context using the retriever's invoke method
|
447 |
context = retriever.invoke(input_dict["question"])
|
448 |
context_str = "\n".join([doc.page_content for doc in context])
|
449 |
+
|
450 |
# Get user info from the session
|
451 |
user_info = user_session.get_user() or {}
|
452 |
+
first_name = user_info.get("Nickname", "User")
|
453 |
|
454 |
+
# Get conversation history
|
455 |
+
conversation_history = user_session.get_formatted_history()
|
456 |
+
|
457 |
+
# Format prompt with user context and conversation history
|
458 |
prompt = rag_prompt.format(
|
459 |
context=context_str,
|
460 |
question=input_dict["question"],
|
461 |
+
first_name=first_name,
|
462 |
+
conversation_history=conversation_history
|
463 |
)
|
464 |
|
465 |
# Stream response
|
|
|
468 |
return stream_func
|
469 |
|
470 |
def rag_memory_stream(message, history):
|
471 |
+
# Add user message to history
|
472 |
+
user_session.add_to_history("user", message)
|
473 |
+
|
474 |
# Initialize with empty response
|
475 |
partial_text = ""
|
476 |
+
full_response = ""
|
477 |
+
|
|
|
|
|
478 |
# Use the rag_chain with the question
|
479 |
for new_text in rag_chain({"question": message}):
|
480 |
partial_text += new_text
|
481 |
+
full_response = partial_text
|
482 |
yield partial_text
|
483 |
+
|
484 |
+
# After generating the complete response, add it to history
|
485 |
+
user_session.add_to_history("assistant", full_response)
|
486 |
|
487 |
# Gradio Interface Setup with improved UX
|
488 |
def chatbot_interface():
|
489 |
# Get API key (in a real application, handle this more securely)
|
490 |
api_key = api # This should be properly defined or imported elsewhere
|
491 |
|
492 |
+
# Update the template to include conversation history
|
493 |
+
global template
|
494 |
+
template = """
|
495 |
+
You are a compassionate and supportive AI assistant specializing in helping individuals affected by Gender-Based Violence (GBV).
|
496 |
+
|
497 |
+
Previous conversation:
|
498 |
+
{conversation_history}
|
499 |
+
|
500 |
+
Context information:
|
501 |
+
{context}
|
502 |
+
|
503 |
+
User {first_name} asks: {question}
|
504 |
+
|
505 |
+
Respond with empathy and provide support and resources based on the conversation and context. Always maintain a warm, supportive tone.
|
506 |
+
"""
|
507 |
+
|
508 |
# Create the RAG chain with user context
|
509 |
global rag_chain
|
510 |
rag_chain = create_rag_chain(retriever, template, api_key)
|
511 |
+
|
512 |
+
|
513 |
+
with gr.Blocks(css="""
|
514 |
+
.welcome-container {
|
|
|
|
|
|
|
|
|
|
|
515 |
text-align: center;
|
516 |
margin-bottom: 20px;
|
517 |
padding: 20px;
|
|
|
521 |
.feedback-btn { margin-top: 10px; }
|
522 |
footer { margin-top: 30px; text-align: center; }
|
523 |
""") as demo:
|
|
|
|
|
|
|
524 |
# User registration section
|
525 |
registration_container = gr.Column(visible=True)
|
526 |
with registration_container:
|
527 |
+
gr.Markdown("### To prioritize your privacy, please provide your nickname. ")
|
528 |
+
|
529 |
with gr.Row():
|
530 |
first_name = gr.Textbox(
|
531 |
+
label="Nickname",
|
532 |
+
placeholder="Enter your Nickname",
|
533 |
scale=1
|
534 |
)
|
535 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
536 |
with gr.Row():
|
537 |
submit_btn = gr.Button("Start Chatting", variant="primary", scale=2)
|
538 |
+
|
539 |
response_message = gr.Markdown(elem_id="welcome-message")
|
540 |
+
|
541 |
# Chatbot section (initially hidden)
|
542 |
chatbot_container = gr.Column(visible=False)
|
543 |
with chatbot_container:
|
544 |
chat_interface = gr.ChatInterface(
|
545 |
fn=rag_memory_stream,
|
546 |
+
title="Chat with Me",
|
547 |
fill_height=True,
|
|
|
548 |
)
|
549 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
550 |
# Footer with version info
|
551 |
gr.Markdown("Ijwi ry'Ubufasha v1.0.0 © 2025", elem_id="footer")
|
552 |
+
|
553 |
# Handle user registration
|
554 |
submit_btn.click(
|
555 |
+
collect_user_info,
|
556 |
+
inputs=[first_name],
|
557 |
outputs=[response_message, chatbot_container, registration_container, chat_interface.chatbot]
|
558 |
)
|
559 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
560 |
return demo
|
561 |
|
562 |
+
# Launch the interface
|
563 |
if __name__ == "__main__":
|
564 |
+
# Launch the interface
|
565 |
chatbot_interface().launch(share=True, inbrowser=True)
|