File size: 14,981 Bytes
7b43396
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
913af42
7b43396
913af42
7b43396
913af42
7b43396
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
913af42
7b43396
 
 
 
 
 
 
 
 
 
cb6ce27
7b43396
 
 
 
 
 
 
 
cb6ce27
7b43396
 
913af42
 
7b43396
 
 
 
 
 
 
 
db0b8ce
7b43396
913af42
db0b8ce
7b43396
 
 
 
db0b8ce
7b43396
db0b8ce
7b43396
 
 
0293829
7b43396
 
db0b8ce
7b43396
 
 
 
 
913af42
7b43396
cb6ce27
7b43396
 
 
 
 
 
 
 
913af42
7b43396
 
 
 
cb6ce27
7b43396
 
 
 
 
 
 
913af42
7b43396
 
 
 
 
 
 
cb6ce27
7b43396
 
 
 
 
 
 
 
 
 
913af42
 
7b43396
913af42
7b43396
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb6ce27
7b43396
 
 
cb6ce27
7b43396
 
cb6ce27
7b43396
 
 
 
 
913af42
 
 
 
 
 
 
 
 
 
 
7b43396
 
 
cb6ce27
7b43396
 
 
 
 
 
 
 
913af42
 
 
 
 
 
 
 
cb6ce27
913af42
7b43396
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb6ce27
7b43396
 
 
 
 
 
 
 
 
 
 
 
 
 
913af42
7b43396
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f259155
7b43396
 
 
f259155
7b43396
 
 
 
 
 
 
f259155
7b43396
f259155
7b43396
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
913af42
 
 
 
 
 
 
 
 
 
 
 
7b43396
 
 
 
 
 
 
 
 
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import streamlit as st
from datetime import datetime
from hybrid_processor import HybridProcessor
import logging

# Configure Streamlit page settings
st.set_page_config(layout="wide")

# Set up logging for debugging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# Initialize the HybridProcessor
try:
    processor = HybridProcessor()
except Exception as e:
    logger.error(f"Failed to initialize HybridProcessor: {str(e)}")
    raise

# Function to compare approaches and return results
def compare_approaches(question, processor):
    try:
        vector_result = processor.vector_processor.query(question)
        logger.info(f"Vector result: {vector_result}")
        graph_result = processor.graph_processor.query(question)
        logger.info(f"Graph result: {graph_result}")
        hybrid_result = processor.query(question)
        logger.info(f"Hybrid result: {hybrid_result}")

        vector_chunks_str = '\n\n'.join(
            [f'Chunk {i + 1}: {chunk}' for i, chunk in enumerate(hybrid_result['chunks']['vector'])])
        graph_chunks_str = '\n\n'.join(
            [f'Record {i + 1}: {chunk}' for i, chunk in enumerate(hybrid_result['chunks']['graph'])])
        hybrid_chunks_formatted = f"Vector Chunks:\n{vector_chunks_str}\n\nGraph Records:\n{graph_chunks_str}"

        return {
            "vector_answer": vector_result["answer"],
            "vector_chunks": "\n\n".join(
                [f"Chunk {i + 1}: {chunk}" for i, chunk in enumerate(vector_result["chunks"])]),
            "graph_answer": graph_result["answer"],
            "graph_chunks": "\n\n".join([f"Record {i + 1}: {chunk}" for i, chunk in enumerate(graph_result["chunks"])]),
            "hybrid_answer": hybrid_result["answer"],
            "hybrid_chunks": hybrid_chunks_formatted
        }
    except Exception as e:
        logger.error(f"Error in compare_approaches: {str(e)}")
        st.error(f"Error processing query: {str(e)}")
        return {
            "vector_answer": "Error processing query.",
            "vector_chunks": "",
            "graph_answer": "Error processing query.",
            "graph_chunks": "",
            "hybrid_answer": "Error processing query.",
            "hybrid_chunks": ""
        }

# Custom CSS for a modern dark theme UI
# Custom CSS for a modern dark theme UI with reduced font sizes
st.markdown("""
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
        @import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css');

        * {
            font-family: 'Poppins', sans-serif !important;
            box-sizing: border-box;
            font-size: 13px !important; /* Reduced base font size from 16px (implicit default) to 13px */
        }
        body, .stApp {
            background: #1A1B26 !important;
            color: #E0E0E0 !important;
            margin: 0 !important;
            padding: 0 !important;
        }
        .main {
            background: #1A1B26 !important;
            padding: 24px !important;
        }
        .header h1 {
            font-size: 32px !important; /* Reduced from 24px to 20px */
            font-weight: 600 !important;
            color: #60A5FA !important;
            margin-bottom: 4px !important;
            text-align: center !important;
        }
        .header-text {
            color: #A0AEC0 !important;
            font-size: 12px !important; /* Reduced from 16px to 13px */
            text-align: center !important;
            margin-bottom: 4px !important;
        }
        .warning-text {
            color: #F87171 !important;
            font-size: 10px !important; /* Reduced from 14px to 11px */
            font-weight: 500 !important;
            text-align: center !important;
            margin-bottom: 10px !important;
        }
        .stTextInput > div > div > input {
            background-color: #2A2B37 !important;
            color: #E0E0E0 !important;
            border: 1px solid #3B82F6 !important;
            border-radius: 12px !important;
            padding: 14px !important;
            font-size: 13px !important; /* Reduced from 16px to 13px */
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2) !important;
            transition: all 0.3s ease !important;
        }
        .stTextInput > div > div > input:focus {
            border-color: #60A5FA !important;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2) !important;
        }
        .stButton > button {
            background: linear-gradient(90deg, #3B82F6 0%, #A855F7 100%) !important;
            color: white !important;
            border: none !important;
            border-radius: 12px !important;
            padding: 12px 24px !important;
            font-size: 13px !important; /* Reduced from 16px to 13px */
            font-weight: 500 !important;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2) !important;
            transition: all 0.3s ease !important;
        }
        .stButton > button:hover {
            background: linear-gradient(90deg, #60A5FA 0%, #C084FC 100%) !important;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3) !important;
            transform: scale(1.05) !important;
        }
        .clear-button > button {
            background: linear-gradient(90deg, #F87171 0%, #EF4444 100%) !important;
            color: white !important;
            border: none !important;
            border-radius: 12px !important;
            padding: 12px 24px !important;
            font-size: 13px !important; /* Reduced from 16px to 13px */
            font-weight: 500 !important;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2) !important;
            transition: all 0.3s ease !important;
        }
        .clear-button > button:hover {
            background: linear-gradient(90deg, #EF4444 0%, #F87171 100%) !important;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3) !important;
            transform: scale(1.05) !important;
        }
        .chat-container, .info-box {
            background: rgba(42, 43, 55, 0.8) !important;
            backdrop-filter: blur(10px) !important;
            border: 1px solid rgba(255, 255, 255, 0.1) !important;
            border-radius: 16px !important;
            padding: 20px !important;
            color: #E0E0E0 !important;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2) !important;
        }
        .chat-container {
            height: 400px !important;
            overflow-y: auto !important;
            margin-bottom: 20px !important;
            scroll-behavior: smooth !important;
        }
        .stChatMessage {
            background: #3A3B47 !important;
            color: #E0E0E0 !important;
            border-radius: 12px !important;
            padding: 14px 18px !important;
            font-size: 13px !important; /* Reduced from 16px to 13px */
            line-height: 1.6 !important;
            white-space: pre-wrap !important;
            margin: 12px 0 !important;
            opacity: 1 !important;
        }
        .info-box {
            font-size: 13px !important; /* Reduced from 16px to 13px */
            line-height: 1.6 !important;
            margin-bottom: 20px !important;
            padding: 20px !important;
            white-space: pre-wrap !important;
        }
        .chunks-container {
            background: rgba(42, 43, 55, 0.8) !important;
            backdrop-filter: blur(10px) !important;
            border: 1px solid rgba(255, 255, 255, 0.1) !important;
            border-radius: 16px !important;
            padding: 20px !important;
            color: #E0E0E0 !important;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2) !important;
            margin-top: 24px !important;
            width: 100% !important;
        }
        .footer {
            text-align: center !important;
            color: #A0AEC0 !important;
            font-size: 11px !important; /* Reduced from 14px to 11px */
            padding: 24px 0 !important;
        }
        .stColumns {
            gap: 24px !important;
        }
        .stColumns > div {
            flex: 1 !important;
        }
        .stExpander {
            background: #2A2B37 !important;
            border: 1px solid rgba(255, 255, 255, 0.1) !important;
            border-radius: 12px !important;
            margin-bottom: 12px !important;
        }
        .stExpander > div > div > div > p {
            color: #E0E0E0 !important;
            font-size: 13px !important; /* Reduced from 16px to 13px */
            font-weight: 500 !important;
        }
    </style>
""", unsafe_allow_html=True)

# Streamlit App Layout
st.markdown('<div class="header">', unsafe_allow_html=True)
st.title("RAG vs GraphRAG")
st.markdown('<p class="header-text">Compare Vector DB, Graph DB, and Hybrid approaches for document querying</p>', unsafe_allow_html=True)
st.markdown('<p class="warning-text"><b>Do not upload personal or private data</b></p>', unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)

# Initialize session state
if "chat_history" not in st.session_state:
    st.session_state.chat_history = []
if "vector_chunks" not in st.session_state:
    st.session_state.vector_chunks = "Vector DB results will appear here"
if "graph_chunks" not in st.session_state:
    st.session_state.graph_chunks = "Graph DB results will appear here"
if "hybrid_chunks" not in st.session_state:
    st.session_state.hybrid_chunks = "Hybrid results will appear here"

# Create two columns for the split layout
col1, col2 = st.columns(2)

# Left Column: Chat Interface
# Left Column: Chat Interface
with col1:
    # Chat display area using st.chat_message
    with st.container():
        # Placeholder if chat history is empty
        if not st.session_state.chat_history:
            st.markdown(
                '<div style="text-align: center; color: #A0AEC0; font-size: 16px; margin-top: 20px;">Start the conversation by asking a question!</div>',
                unsafe_allow_html=True
            )
        # Render chat history using st.chat_message
        for message in st.session_state.chat_history:
            with st.chat_message(message["role"], avatar="user" if message["role"] == "user" else "assistant"):
                st.markdown(message["content"])
                logger.info(f"Rendering chat message: {message}")

    # Input area with Send and Clear buttons
    with st.container():
        query = st.text_input(
            label="Ask a question",
            placeholder="Ask in the format: 'What is the relationship between [Entity1] and [Entity2]?' (e.g., 'What is the relationship between Alice and TechCorp?')",
            label_visibility="collapsed"
        )
        btn_col1, btn_col2 = st.columns([1, 1])
        with btn_col1:
            send_button = st.button("Send", key="send")
        with btn_col2:
            clear_button = st.button("Clear Chat", key="clear", help="Reset the conversation", type="secondary")

# Right Column: Single plain box with source text and use case questions
with col2:
    st.markdown("""
        <div class="info-box">
            <b>Questions to Try:</b><br>
            - What are the key achievements of TechCorp?<br>
            - Who works for TechCorp?
             <br><b>**** Below source document has already been loaded for testing****  </b>
            <b>TechCorp Annual Report Summary</b>
            <i>April 27, 2025</i><br>
            TechCorp, a leading AI company headquartered in San Francisco, achieved significant milestones in 2024. Founded by Alice Johnson, TechCorp employs 500 people and specializes in machine learning solutions. Alice, the CEO, collaborated with Bob Smith, CTO of InnovateAI, on a joint project to develop a new AI model. This partnership strengthened TechCorp's presence in New York, where InnovateAI is based.<br><br>
            The company expanded its operations to London, appointing Claire Brown as the regional director. Claire previously worked with Alice at Quantum Dynamics, a Boston-based firm. TechCorp's revenue grew by 20%, driven by contracts with GlobalTech in Seattle and DataSolutions in Chicago.<br><br>
            <b>Key Achievements:</b>
            - Launched AI platform "NeuraNet" in San Francisco.<br>
            - Partnered with InnovateAI in New York.<br>
            - Opened a new office in London led by Claire Brown.<br>
        </div>
    """, unsafe_allow_html=True)

# Handle the Send button click
if send_button and query:
    # Add user message to chat history
    st.session_state.chat_history.append({"role": "user", "content": query})
    logger.info(f"User query added to chat history: {query}")

    # Get responses from the processor
    response = compare_approaches(query, processor)
    logger.info(f"Compare approaches response: {response}")

    # Add assistant response to chat history (only the answers)
    assistant_response = (
        f"**Vector DB Answer**: {response['vector_answer']}\n\n"
        f"**Graph DB Answer**: {response['graph_answer']}\n\n"
        f"**Hybrid Answer**: {response['hybrid_answer']}"
    )
    logger.info(f"Assistant response: {assistant_response}")
    st.session_state.chat_history.append({"role": "assistant", "content": assistant_response})
    logger.info(f"Chat history after update: {st.session_state.chat_history}")

    # Update the result displays (only chunks/records)
    st.session_state.vector_chunks = response["vector_chunks"]
    st.session_state.graph_chunks = response["graph_chunks"]
    st.session_state.hybrid_chunks = response["hybrid_chunks"]

    # Rerender the page
    st.rerun()

# Handle the Clear Chat button
if clear_button:
    st.session_state.chat_history = []
    st.session_state.vector_chunks = "Vector DB results will appear here"
    st.session_state.graph_chunks = "Graph DB results will appear here"
    st.session_state.hybrid_chunks = "Hybrid results will appear here"
    st.rerun()

# Chunks display at the bottom in accordion style
with st.container():
    st.markdown('<div class="chunks-container">', unsafe_allow_html=True)
    st.markdown("### Chunks and Records", unsafe_allow_html=True)
    with st.expander("Vector DB Chunks"):
        st.markdown(st.session_state.vector_chunks)
    with st.expander("Graph DB Records"):
        st.markdown(st.session_state.graph_chunks)
    with st.expander("Hybrid Chunks/Records"):
        st.markdown(st.session_state.hybrid_chunks)
    st.markdown('</div>', unsafe_allow_html=True)

# Footer
st.markdown("""
    <div class="footer">
        Interested in more of my thoughts and projects? <a href="https://dipenvekaria.com" target="_blank">Click here</a> to visit my website!
    </div>
""", unsafe_allow_html=True)

if __name__ == "__main__":
    logger.info(f"===== Application Startup at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} =====")