Spaces:
Running
Running
File size: 5,217 Bytes
dd36c44 5d15658 029bf9e ca8e3f6 5d15658 029bf9e 5d15658 029bf9e ca8e3f6 dd36c44 5d15658 867b3d0 5d15658 f334e2b 5d15658 dd36c44 5d15658 dd36c44 5d15658 dd36c44 5d15658 dd36c44 5d15658 dd36c44 5d15658 dd36c44 5d15658 dd36c44 5d15658 dd36c44 5d15658 dd36c44 5d15658 dd36c44 5d15658 dd36c44 5d15658 dd36c44 5d15658 dd36c44 5d15658 f334e2b 5d15658 f334e2b 5d15658 f334e2b 5d15658 f334e2b 5d15658 | 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 | import streamlit as st
import requests
import uuid
import time
import os
# --- CONFIGURATION ---
# Your FastAPI server URL on Hugging Face
API_URL = "https://lightrt-text2sql-backend.hf.space"
st.set_page_config(page_title="Text2SQL Agent", page_icon="π€", layout="centered")
# --- HUGGING FACE FIREWALL BYPASS (CHROME SPOOFING) ---
HF_TOKEN = os.getenv("HF_TOKEN")
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept": "application/json",
"Content-Type": "application/json"
}
if HF_TOKEN:
HEADERS["Authorization"] = f"Bearer {HF_TOKEN}"
# (Optional) A quick UI check so you know the token loaded in the cloud
if not HF_TOKEN:
st.sidebar.error("β οΈ HF_TOKEN missing from Space Secrets!")
else:
st.sidebar.success("π Token Loaded! Ready for cloud connection.")
# --- SESSION STATE INITIALIZATION ---
if "thread_id" not in st.session_state:
st.session_state.thread_id = str(uuid.uuid4())
if "user_id" not in st.session_state:
st.session_state.user_id = "tenant_" + str(uuid.uuid4())[:8]
if "is_db_connected" not in st.session_state:
st.session_state.is_db_connected = False
if "connection_url" not in st.session_state:
st.session_state.connection_url = ""
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
# --- SIDEBAR: DATABASE CONNECTION ---
with st.sidebar:
st.header("βοΈ Database Setup")
db_input = st.text_input(
"Enter Database URL:",
disabled=st.session_state.is_db_connected
)
if not st.session_state.is_db_connected:
if st.button("Connect & Initialize", type="primary", use_container_width=True):
if not db_input:
st.error("Please enter a valid URL.")
else:
with st.spinner("Building embeddings and initializing agent..."):
try:
payload = {"connection_url": db_input, "user_id": st.session_state.user_id}
# Added headers=HEADERS here!
response = requests.post(f"{API_URL}/upload_url", json=payload, headers=HEADERS)
if response.status_code == 200:
st.session_state.is_db_connected = True
st.session_state.connection_url = db_input
time.sleep(15)
st.success("Database connected securely!")
st.rerun()
elif response.status_code == 429:
st.error("π¨ Rate Limited! Waiting for HF firewall cooldown.")
else:
st.error(f"Failed to connect: {response.text}")
except requests.exceptions.ConnectionError:
st.error("π¨ Cannot connect to backend. Is FastAPI running?")
else:
st.success("β
Connected to Database")
st.caption(f"URL: {st.session_state.connection_url}")
if st.button("Disconnect & Reset", use_container_width=True):
st.session_state.clear()
st.rerun()
# --- MAIN CHAT INTERFACE ---
st.title("π£οΈ Text2SQL Agent")
if not st.session_state.is_db_connected:
st.info("π Please connect your database in the sidebar to begin analyzing data.")
else:
for msg in st.session_state.chat_history:
with st.chat_message(msg["role"]):
st.markdown(msg["content"])
if user_query := st.chat_input("Ask a question about your data..."):
st.session_state.chat_history.append({"role": "user", "content": user_query})
with st.chat_message("user"):
st.markdown(user_query)
with st.chat_message("assistant"):
with st.spinner("Analyzing schema and generating SQL..."):
try:
payload = {
"message": user_query,
"thread_id": st.session_state.thread_id,
"user_id": st.session_state.user_id,
"connection_url": st.session_state.connection_url
}
# Added headers=HEADERS here!
response = requests.post(f"{API_URL}/chat", json=payload, headers=HEADERS)
if response.status_code == 200:
answer = response.json().get("response", "No response found.")
st.markdown(answer)
st.session_state.chat_history.append({"role": "assistant", "content": answer})
elif response.status_code == 429:
st.error("π¨ Rate Limited by Hugging Face firewall.")
else:
st.error(f"Agent Error: {response.text}")
except requests.exceptions.ConnectionError:
st.error("π¨ Connection dropped. Ensure FastAPI is running.") |