Spaces:
Running
Running
File size: 10,858 Bytes
43139c6 5299cfa 973ae4d 16273f5 973ae4d 8d810fe 16273f5 5299cfa 973ae4d 16273f5 8d810fe 973ae4d 5299cfa 43139c6 973ae4d 5299cfa 43139c6 973ae4d c6e47c7 973ae4d c6e47c7 16273f5 973ae4d dfbf21d 973ae4d 6e96b49 973ae4d 16273f5 973ae4d 16273f5 973ae4d 16273f5 973ae4d 16273f5 973ae4d c6e47c7 973ae4d c6e47c7 973ae4d 16273f5 973ae4d c6e47c7 973ae4d 43139c6 16273f5 bc652b7 16273f5 973ae4d 8d810fe 973ae4d 16273f5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 |
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")
# ... (existing code for the column with markdown)
def respond_and_clear(query, history):
updated_history = respond_genericchatbot(query, history)
return updated_history, "" # Return updated history and empty string for input
submit_button_gc.click(
fn=respond_and_clear,
inputs=[user_input_gc, generic_chatbot_output],
outputs=[generic_chatbot_output, user_input_gc]
)
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)
|