File size: 6,886 Bytes
d11c1ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# import streamlit as st
# import requests
# import json

# st.set_page_config(page_title="QueryMate: Text to SQL & CSV")

# st.markdown("# QueryMate: Text to SQL & CSV πŸ’¬πŸŒπŸ—„οΈ")
# st.description('''Welcome to QueryMate, your friendly assistant for converting natural language queries into SQL statements and CSV outputs!
#                Let's get started with your data queries!''')
# # Load chat history
# def load_chat_history():
#     try:
#         with open('chat_history.json', 'r') as f:
#             return json.load(f)
#     except FileNotFoundError:
#         return []

# def save_chat_history(history):
#     with open('chat_history.json', 'w') as f:
#         json.dump(history, f)

# chat_history = load_chat_history()

# # Data source selection
# data_source = st.radio("Select Data Source:", ('SQL Database', 'Employee CSV'))

# # Predefined queries
# predefined_queries = {
#     'SQL Database': [
#         'Print all students',
#         'Count total number of students',
#         'List students in Data Science class'
#     ],
#     'Employee CSV': [
#         'Print employees having the department id equal to 100',
#         'Count total number of employees',
#         'List Top 5 employees according to salary in descending order'
#     ]
# }

# st.markdown(f"### Predefined Queries for {data_source}")

# # Create buttons for predefined queries
# for query in predefined_queries[data_source]:
#     if st.button(query):
#         st.session_state.predefined_query = query

# st.markdown("### Enter Your Question")
# question = st.text_input("Input: ", key="input", value=st.session_state.get('predefined_query', ''))

# # Submit button
# submit = st.button("Submit")

# if submit:
#     # Send request to FastAPI backend
#     response = requests.post("http://localhost:8000/query", 
#                              json={"question": question, "data_source": data_source})
#     if response.status_code == 200:
#         data = response.json()
#         st.markdown(f"## Generated {'SQL' if data_source == 'SQL Database' else 'Pandas'} Query")
#         st.code(data['query'])
        
#         st.markdown("## Query Results")
#         st.write(data['result'])

#         if data_source == 'Employee CSV':
#             st.markdown("## Available CSV Columns")
#             st.write(data['columns'])

#         # Update chat history
#         chat_history.append(f"User ({data_source}): {question}")
#         chat_history.append(f"AI: {data['query']}")
#         save_chat_history(chat_history)
#     else:
#         st.error(f"Error processing your request: {response.text}")

#     # Clear the predefined query from session state
#     st.session_state.pop('predefined_query', None)

# # Display chat history
# st.markdown("## Chat History")
# for message in chat_history:
#     st.text(message)

# # Option to clear chat history
# if st.button("Clear Chat History"):
#     chat_history.clear()
#     save_chat_history(chat_history)
#     st.success("Chat history cleared!")





import streamlit as st
import requests
import json
import pandas as pd

st.set_page_config(page_title="QueryMate: Text to SQL & CSV")

st.markdown("# QueryMate: Text to SQL & CSV πŸ’¬πŸ—„οΈ")
st.markdown('''Welcome to QueryMate, your friendly assistant for converting natural language queries into SQL statements and CSV outputs!

               Let's get started with your data queries!''')

# Load chat history
def load_chat_history():
    try:
        with open('chat_history.json', 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        return []

def save_chat_history(history):
    with open('chat_history.json', 'w') as f:
        json.dump(history, f)

chat_history = load_chat_history()

# Data source selection
data_source = st.radio("Select Data Source:", ('SQL Database', 'Employee CSV'))

# Predefined queries
predefined_queries = {
    'SQL Database': [
        'Print all students',
        'Count total number of students',
        'List students in Data Science class'
    ],
    'Employee CSV': [
        'Print employees having the department id equal to 100',
        'Count total number of employees',
        'List Top 5 employees according to salary in descending order'
    ]
}

st.markdown(f"### Predefined Queries for {data_source}")

# Create buttons for predefined queries
for query in predefined_queries[data_source]:
    if st.button(query):
        st.session_state.predefined_query = query

st.markdown("### Enter Your Question")
question = st.text_input("Input: ", key="input", value=st.session_state.get('predefined_query', ''))

# Submit button
submit = st.button("Submit")

if submit:
    # Send request to FastAPI backend
    response = requests.post("http://localhost:8000/query", 
                             json={"question": question, "data_source": data_source})
    if response.status_code == 200:
        data = response.json()
        st.markdown(f"## Generated {'SQL' if data_source == 'SQL Database' else 'Pandas'} Query")
        st.code(data['query'])
        
        st.markdown("## Query Results")
        result = data['result']
        
        if isinstance(result, list) and len(result) > 0:
            if isinstance(result[0], dict):
                # For CSV queries that return a list of dictionaries
                df = pd.DataFrame(result)
                st.dataframe(df)
            elif isinstance(result[0], list):
                # For SQL queries that return a list of lists
                df = pd.DataFrame(result)
                st.dataframe(df)
            else:
                # For single column results
                st.dataframe(pd.DataFrame(result, columns=['Result']))
        elif isinstance(result, dict):
            # For single row results
            st.table(result)
        else:
            # For scalar results or empty results
            st.write(result)

        if data_source == 'Employee CSV':
            st.markdown("## Available CSV Columns")
            st.write(data['columns'])

        # Update chat history
        chat_history.append(f"πŸ‘¨β€πŸ’»({data_source}): {question}")
        chat_history.append(f"πŸ€–: {data['query']}")
        save_chat_history(chat_history)
    else:
        st.error(f"Error processing your request: {response.text}")

    # Clear the predefined query from session state
    st.session_state.pop('predefined_query', None)

# Display chat history
st.markdown("## Chat History")
for message in chat_history:
    st.text(message)

# Option to clear chat history
if st.button("Clear Chat History"):
    chat_history.clear()
    save_chat_history(chat_history)
    st.success("Chat history cleared!")