File size: 7,795 Bytes
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
import gradio as gr
from langchain_core.messages import HumanMessage
import src.passage_finder as pf
import src.srf_bot as sb
import prompts.system_prompts as sp
import os

# Initialize PassageFinder and Chatbot
passage_finder = pf.PassageFinder()
chatbot = sb.SRFChatbot()

# 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)]
    # Invoke the graph with properly formatted input
    result = chatbot.graph.invoke({"messages": formatted_query}, chatbot.config)
    # Get the passages from the graph and append to history if documents exist
    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))
    # Extract the assistant's response and append to history
    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

# 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 Instructions",
                        value=list(sp.system_prompt_templates.keys())[0],
                    )
                    system_prompt_display = gr.Textbox(
                        value=sp.system_prompt_templates[list(sp.system_prompt_templates.keys())[0]],
                        label="Current 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=chatbot.reset_system_prompt,
                inputs=[system_prompt_dropdown],
                outputs=[system_prompt_display]
            )
            
            submit_button_cb.click(
                fn=respond_chatbot,
                inputs=[user_input_cb, chatbot_output],
                outputs=[chatbot_output]
            )

# Access the secrets
username = os.getenv("USERNAME")
password = os.getenv("PASSWORD")

# Launch the interface
demo.launch(share=True, auth=(username, password), debug=True)