srf_chatbot_v2 / app.py
nadaaaita's picture
fixed bug in second tab
c6e47c7
raw
history blame
11.6 kB
import gradio as gr
from langchain_core.messages import HumanMessage
import src.passage_finder as pf
import src.srf_bot as sb
import src.generic_bot as gb
import prompts.system_prompts as sp
import os
# Initialize PassageFinder, SRFChatbot, and GenericChatbot
passage_finder = pf.PassageFinder()
chatbot = sb.SRFChatbot()
generic_chatbot = gb.GenericChatbot()
# Passage Finder functions
def respond_passage_finder(message):
config = passage_finder.get_configurable()
results = passage_finder.graph.invoke({"messages": [HumanMessage(content=message)]}, config)
documents = results.get('documents', [])
output = []
for doc in documents:
quotes = doc.metadata.get('matched_quotes', [])
publication = doc.metadata.get('publication_name', 'Unknown Publication')
chapter = doc.metadata.get('chapter_name', 'Unknown Chapter')
full_passage = doc.metadata.get('highlighted_content', '')
quote_text = "\n".join([f"• \"{q.quote}\"" for q in quotes])
output.append({
"quotes": quote_text,
"reference": f"{publication}: {chapter}",
"full_passage": full_passage
})
return output
def process_input_passage_finder(message):
results = respond_passage_finder(message)
html_output = "<div class='response-container'>"
for result in results:
html_output += f"""
<div class='result-item'>
<h3 class='reference'>{result['reference']}</h3>
<div class='quotes'>{result['quotes'].replace("• ", "<br>• ")}</div>
<details>
<summary>Show full passage</summary>
<div class='full-passage'>{result['full_passage']}</div>
</details>
</div>
"""
html_output += "</div>"
return html_output
# Chatbot functions
def respond_chatbot(query, history):
formatted_query = [HumanMessage(content=query)]
result = chatbot.graph.invoke({"messages": formatted_query}, chatbot.config)
state = chatbot.graph.get_state(config=chatbot.config).values
documents = state.get("documents")
passages = ''
if documents and len(documents) > 0:
for d in documents:
passages += f'<b>{d.metadata["publication_name"]} - {d.metadata["chapter_name"]}</b>\n{d.page_content}\n\n'
history.append((f'Passages: {query}', passages))
response = result["messages"][-1].content
system_message_dropdown = state.get("system_message_dropdown")
history.append((query, f"<i>[{system_message_dropdown}]</i>\n" + response))
return history
# Generic Chatbot function
def respond_genericchatbot(query, history):
formatted_query = [HumanMessage(content=query)]
result = generic_chatbot.graph.invoke({"messages": formatted_query}, generic_chatbot.config)
state = generic_chatbot.graph.get_state(config=generic_chatbot.config).values
documents = state.get("documents")
passages = ''
if documents and len(documents) > 0:
for d in documents:
passages += f'<b>{d.metadata["publication_name"]} - {d.metadata["chapter_name"]}</b>\n{d.page_content}\n\n'
history.append((f'Passages: {query}', passages))
response = result["messages"][-1].content
history.append((query, response))
return history
# Define the CSS
css = """
body { background-color: #f0f0f0; }
.gradio-container { background-color: #ffffff; }
.response-container { border: 1px solid #e0e0e0; border-radius: 8px; padding: 20px; background-color: #f9f9f9; }
.result-item { margin-bottom: 20px; background-color: white; padding: 15px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
.reference { color: #2c3e50; margin-bottom: 10px; }
.quotes { font-style: italic; margin-bottom: 10px; }
.full-passage { margin-top: 10px; padding: 10px; background-color: #f0f0f0; border-radius: 5px; }
details summary { cursor: pointer; color: #3498db; font-weight: bold; }
details summary:hover { text-decoration: underline; }
/* Chatbot specific styles */
.gr-button { background-color: #333333; color: white; font-size: 18px; padding: 10px; }
.gr-textbox textarea { font-size: 18px; color: black; }
.gr-dropdown { font-size: 18px; color: black; }
.source-box { background-color: white; padding: 10px; border-radius: 8px; margin-top: 20px; color: black; border: 1px solid #D0D0D0; }
/* Dark mode and responsive styles */
@media (prefers-color-scheme: dark) {
.gradio-container { background-color: #1e1e1e; color: white; }
h1, h2, p { color: white; }
.gr-textbox textarea { background-color: #333333; color: white; }
.gr-button { background-color: #555555; color: white; }
.gr-dropdown { background-color: #333333; color: white; }
.source-box { background-color: #333333; color: white; border: 1px solid #555555; }
}
@media (max-width: 600px) {
.gr-row { flex-direction: column !important; }
.gr-column { width: 100% !important; }
}
"""
with gr.Blocks(css=css) as demo:
gr.Markdown("# SRF Teachings App")
with gr.Tabs():
with gr.TabItem("Passage Finder"):
gr.Markdown("Ask questions about Self-Realization Fellowship teachings and receive responses with relevant quotes.")
with gr.Row():
input_text_pf = gr.Textbox(
placeholder="Ask about the meaning of life, spirituality, or any other topic...",
label="Your Question"
)
submit_btn_pf = gr.Button("Submit", variant="primary")
output_area_pf = gr.HTML()
gr.Markdown("### Sources")
gr.Textbox(value="Journey to Self Realization, Second Coming of Christ, and Autobiography of a Yogi",
label="Available Sources", interactive=False)
submit_btn_pf.click(process_input_passage_finder, inputs=input_text_pf, outputs=output_area_pf)
gr.Examples(
examples=[
"What is the meaning of life?",
"Importance of good posture",
"How can I find inner peace?",
"What does Paramahansa Yogananda say about meditation?",
],
inputs=input_text_pf,
)
with gr.TabItem("Custom Chatbots"):
with gr.Row():
with gr.Column(scale=4):
chatbot_output = gr.Chatbot(height=600)
user_input_cb = gr.Textbox(placeholder="Type your question here...", label="Your Question", value="What is the meaning of life?")
submit_button_cb = gr.Button("Submit")
with gr.Column(scale=1):
system_prompt_dropdown = gr.Dropdown(
choices=list(sp.system_prompt_templates.keys()),
label="Select Chatbot",
value=list(sp.system_prompt_templates.keys())[0],
)
chatbot_description = gr.Textbox(
value=sp.chatbot_descriptions[list(sp.system_prompt_templates.keys())[0]],
label="Chatbot Description",
lines=3,
interactive=False
)
system_prompt_display = gr.Textbox(
value=sp.system_prompt_templates[list(sp.system_prompt_templates.keys())[0]],
label="Chatbot Instructions",
lines=5,
interactive=False
)
gr.Markdown("""
<div class="source-box">
<strong>Available sources:</strong>
<ul>
<li>Journey to Self-Realization</li>
<li>The Second Coming of Christ</li>
<li>Autobiography of a Yogi</li>
</ul>
</div>
""")
# system_prompt_dropdown.change(
# fn=lambda x: (sp.chatbot_descriptions[x], sp.system_prompt_templates[x]),
# inputs=[system_prompt_dropdown],
# outputs=[chatbot_description, system_prompt_display]
# )
def update_chatbot_info(selected_prompt):
chatbot.reset_system_prompt(selected_prompt)
return sp.chatbot_descriptions[selected_prompt], sp.system_prompt_templates[selected_prompt]
system_prompt_dropdown.change(
fn=update_chatbot_info,
inputs=[system_prompt_dropdown],
outputs=[chatbot_description, system_prompt_display]
)
submit_button_cb.click(
fn=respond_chatbot,
inputs=[user_input_cb, chatbot_output],
outputs=[chatbot_output]
)
gr.Examples(
examples=[
"importance of meditation",
"How can I develop unconditional love?",
"concept of karma",
"What are some techniques for spiritual growth?",
],
inputs=user_input_cb,
)
with gr.TabItem("Generic Chatbot"):
with gr.Row():
with gr.Column(scale=4):
generic_chatbot_output = gr.Chatbot(height=600)
user_input_gc = gr.Textbox(placeholder="Type your question here...", label="Your Question", value="Loaves and fishes")
submit_button_gc = gr.Button("Submit")
with gr.Column(scale=1):
gr.Markdown("""
<div class="source-box">
<strong>About this chatbot:</strong>
<p>This chatbot has access to a vector database of some SRF publications that it can use if necessary, but it receives no other specific instructions. You can ask it anything. If you want quotes and references, you need to explicitly request them in your query.</p>
</div>
""")
with gr.Column(scale=1):
gr.Markdown("""
<div class="source-box">
<strong>Available sources:</strong>
<ul>
<li>Journey to Self-Realization</li>
<li>The Second Coming of Christ</li>
<li>Autobiography of a Yogi</li>
</ul>
</div>
""")
submit_button_gc.click(
fn=respond_genericchatbot,
inputs=[user_input_gc, generic_chatbot_output],
outputs=[generic_chatbot_output]
)
gr.Examples(
examples=[
"Tell me about Paramahansa Yogananda's life",
"What are the main teachings of Self-Realization Fellowship?",
"Explain the concept of Kriya Yoga",
"Can you provide quotes about the importance of meditation?",
],
inputs=user_input_gc,
)
# Access the secrets
username = os.getenv("USERNAME")
password = os.getenv("PASSWORD")
# Launch the interface
demo.launch(share=True, auth=(username, password), debug=True)