amaraditya/text2sql1
0
1import streamlit as st2import requests3import pandas as pd4from datetime import datetime5 6# =====================================================7# CONFIG8# =====================================================9 10API_URL = "https://boundless-underline-product.ngrok-free.dev/query"11 12st.set_page_config(13 page_title="Text2SQL Agent",14 page_icon="๐ง ",15 layout="wide",16 initial_sidebar_state="expanded"17)18 19# =====================================================20# CUSTOM CSS21# =====================================================22 23st.markdown("""24<style>25 26.main {27 background-color: #0E1117;28}29 30.block-container {31 padding-top: 2rem;32 padding-bottom: 2rem;33}34 35h1, h2, h3 {36 color: white;37}38 39.stTextInput > div > div > input {40 background-color: #1E1E1E;41 color: white;42 border-radius: 10px;43 border: 1px solid #444;44 padding: 12px;45}46 47.stButton>button {48 width: 100%;49 border-radius: 10px;50 height: 3em;51 background-color: #6C63FF;52 color: white;53 border: none;54 font-weight: 600;55}56 57.stButton>button:hover {58 background-color: #5A52E0;59 color: white;60}61 62.sql-box {63 background-color: #1E1E1E;64 padding: 1rem;65 border-radius: 10px;66 border: 1px solid #333;67}68 69.metric-card {70 background-color: #1A1D24;71 padding: 1rem;72 border-radius: 12px;73 border: 1px solid #2D2F36;74}75 76.success-box {77 background-color: #132A13;78 padding: 1rem;79 border-radius: 10px;80}81 82.error-box {83 background-color: #3A1111;84 padding: 1rem;85 border-radius: 10px;86}87 88</style>89""", unsafe_allow_html=True)90 91# =====================================================92# HEADER93# =====================================================94 95col1, col2 = st.columns([6,1])96 97with col1:98 st.title(" Text2SQL Agent")99 100 101 102st.markdown("""103Convert natural language questions into executable SQLite queries using a multi-agent AI pipeline.104""")105 106st.divider()107 108# =====================================================109# SIDEBAR110# =====================================================111 112with st.sidebar:113 114 st.header("โก Example Queries")115 116 examples = [117 "Top 5 customers by revenue",118 "Monthly sales trend",119 "Revenue by country",120 "Which artist has most tracks?",121 "Find average invoice amount by country",122 "Which year generated highest revenue?",123 "Find customers with purchases in multiple years",124 "Top genres by revenue"125 ]126 127 for ex in examples:128 if st.button(ex):129 st.session_state["example_question"] = ex130 131 st.divider()132 133 st.header("๐ System Architecture")134 135 st.markdown("""136 - Schema Retrieval137 - Planner Agent138 - SQL Generator139 - Validator Agent140 - SQLite Execution141 """)142 143 st.divider()144 145 st.header("๐ Backend")146 147 st.success("Connected to Colab GPU")148 149# =====================================================150# INPUT SECTION151# =====================================================152 153default_question = st.session_state.get("example_question", "")154 155question = st.text_input(156 "Ask your business question",157 value=default_question,158 placeholder="Example: Show monthly revenue trend"159)160 161# =====================================================162# EXECUTE BUTTON163# =====================================================164 165run = st.button(" Generate SQL & Execute")166 167# =====================================================168# MAIN EXECUTION169# =====================================================170 171if run:172 173 if not question.strip():174 175 st.warning("Please enter a question.")176 177 else:178 179 with st.spinner("Agents are reasoning over your query..."):180 181 start_time = datetime.now()182 183 try:184 185 response = requests.post(186 API_URL,187 json={"question": question},188 timeout=180189 )190 191 output = response.json()192 193 except Exception as e:194 195 st.error(f"Backend connection failed:\n{e}")196 st.stop()197 198 end_time = datetime.now()199 200 latency = round(201 (end_time - start_time).total_seconds(),202 2203 )204 205 # =================================================206 # SUCCESS207 # =================================================208 209 if output.get("status") == "PASS":210 211 st.success(" Query executed successfully")212 213 # =============================================214 # METRICS215 # =============================================216 217 c1, c2, c3 = st.columns(3)218 219 with c1:220 st.metric(221 "Execution Time",222 f"{latency}s"223 )224 225 with c2:226 st.metric(227 "Rows Returned",228 len(output["result"])229 )230 231 with c3:232 st.metric(233 "Status",234 "PASS"235 )236 237 st.divider()238 239 # =============================================240 # SQL241 # =============================================242 243 st.subheader(" Generated SQL")244 245 st.code(246 output["sql"],247 language="sql"248 )249 250 # =============================================251 # RESULT252 # =============================================253 254 st.subheader(" Query Result")255 256 df = pd.DataFrame(output["result"])257 258 st.dataframe(259 df,260 use_container_width=True,261 height=450262 )263 264 # =============================================265 # DOWNLOAD266 # =============================================267 268 csv = df.to_csv(index=False)269 270 st.download_button(271 label="โฌ Download Result CSV",272 data=csv,273 file_name="query_result.csv",274 mime="text/csv"275 )276 277 # =============================================278 # DEBUG SECTIONS279 # =============================================280 281 with st.expander("Planner Output"):282 283 if "plan" in output:284 st.write(output["plan"])285 286 with st.expander("Retrieved Schema"):287 288 if "schema" in output:289 st.write(output["schema"])290 291 with st.expander("๐ Full Backend Output"):292 293 st.json(output)294 295 # =================================================296 # FAILURE297 # =================================================298 299 else:300 301 # st.error("Failed to generate valid SQL")302 st.error("Result not found")303 304 # if "sql" in output:305 306 # st.subheader("Generated SQL")307 308 # st.code(309 # output["sql"],310 # language="sql"311 # )312 313 # if "error" in output:314 315 # st.subheader("Error Details")316 317 # st.error(output["error"])318 319 # with st.expander("๐ Full Backend Output"):320 321 # st.json(output)