dvwn commited on
Commit
a5b3518
·
1 Parent(s): a099ae2

Update UI Frontend version 1.2.0 + Backend Integration

Browse files
backend/.gitignore → .gitignore RENAMED
File without changes
.streamlit/config.toml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [theme]
2
+ base="dark"
3
+ textColor="#FFFFFF"
4
+ font = "sans-serif"
5
+ headingFont = "sans-serif"
6
+ codeFont = "monospace"
7
+
8
+ [theme.sidebar]
9
+ font = "sans-serif"
10
+ headingFont = "sans-serif"
11
+ codeFont = "monospace"
app.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path: frontend/app.py
2
+ # Main application entry point, setting up the app and routing.
3
+ import sys
4
+ import os
5
+ from pathlib import Path
6
+
7
+ project_root = Path(__file__).resolve().parent
8
+ backend_dir = project_root / "backend"
9
+
10
+ if str(backend_dir) not in sys.path:
11
+ sys.path.insert(0, str(backend_dir))
12
+
13
+ # if str(current_dir) not in sys.path:
14
+ # sys.path.insert(0, str(current_dir))
15
+
16
+ import streamlit as st
17
+ from components.sidebar import render_sidebar
18
+ from components.chat import render_chat_interface
19
+
20
+ st.set_page_config(
21
+ page_icon=":material/sql:",
22
+ page_title="NL2SQL Assistant",
23
+ layout="wide",
24
+ initial_sidebar_state="expanded"
25
+ )
26
+
27
+ # def load_css():
28
+ # """Load custom CSS file"""
29
+ # css_path = os.path.join("assets", "styles.css")
30
+ # if os.path.exists(css_path):
31
+ # with open(css_path) as f:
32
+ # st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)
33
+
34
+ def init_session_state():
35
+ """Initialize global variables and authentication states"""
36
+ if 'auth_stat' not in st.session_state:
37
+ st.session_state.auth_stat = "guest"
38
+
39
+ if 'username' not in st.session_state:
40
+ st.session_state.username = "guest"
41
+
42
+ if 'messages' not in st.session_state:
43
+ st.session_state.messages = []
44
+
45
+ if 'current_model' not in st.session_state:
46
+ st.session_state.current_model = "default"
47
+
48
+ def main():
49
+ # load_css()
50
+ init_session_state()
51
+
52
+ render_sidebar()
53
+ render_chat_interface()
54
+
55
+ if __name__ == "__main__":
56
+ main()
{frontend/assets → assets}/styles.css RENAMED
File without changes
backend/app/main.py CHANGED
@@ -1,4 +1,4 @@
1
- # Path: app/main.py
2
  # Main entry point for the NL2SQL application
3
  import os
4
  from dotenv import load_dotenv
 
1
+ # Path: backend/app/main.py
2
  # Main entry point for the NL2SQL application
3
  import os
4
  from dotenv import load_dotenv
backend/server/api_server.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path: backend/server/api_server.py
2
+ # FatAPI entry point
3
+ import pandas as pd
4
+ from dotenv import load_dotenv
5
+ from fastapi import FastAPI, HTTPException
6
+ from pydantic import BaseModel
7
+ from typing import List, Dict, Any, Optional
8
+ from src.database.db_manager import get_db_connection
9
+ from src.nl2sql.hf_engine import get_models, DEFAULT_MODEL_ID
10
+ from src.nl2sql.sql_agent import nl2sql_agent
11
+
12
+ load_dotenv()
13
+ app = FastAPI(title="NL2SQL Backend API")
14
+
15
+ class chatRequest(BaseModel):
16
+ question: str
17
+ model_id: Optional[str] = DEFAULT_MODEL_ID
18
+
19
+ class chatResponse(BaseModel):
20
+ status: str
21
+ sql: str
22
+ answer: str
23
+ data: List[Dict[str, Any]]
24
+ error: str
25
+
26
+ @app.get("/models", response_model=List[str])
27
+ def api_get_models():
28
+ """ Endpoint to fetch available models """
29
+ try:
30
+ models = get_models()
31
+ return models if models else [DEFAULT_MODEL_ID]
32
+ except Exception as e:
33
+ return [DEFAULT_MODEL_ID, "Qwen/Qwen2.5-Coder-7B-Instruct:featherless-ai"]
34
+
35
+ @app.post("/chat", response_model=chatResponse)
36
+ def api_process_chat(request: chatRequest):
37
+ """ Endpoint to process NL2SQL question and return data """
38
+ try:
39
+ resp = nl2sql_agent(user_question=request.question, model_id=request.model_id)
40
+
41
+ sql_query = resp.get('query', 'N/A')
42
+ nl_response = resp.get('nl_response', 'Could not synthesize text answer')
43
+ status = resp.get('status', 'error')
44
+ error_msg = resp.get('error', '')
45
+
46
+ results_list = []
47
+ execution_error = ""
48
+
49
+ if status != 'error' and sql_query != 'N/A':
50
+ conn = get_db_connection()
51
+ if conn:
52
+ try:
53
+ df = pd.read_sql_query(sql_query, conn)
54
+ results_list = df.to_dict(orient="records")
55
+ except Exception as e:
56
+ execution_error = str(e)
57
+ status = "error"
58
+ finally:
59
+ conn.close()
60
+ else:
61
+ execution_error = ":material/warning: Failed to connect to the database."
62
+ status = "error"
63
+ return chatResponse(
64
+ status = status,
65
+ sql = sql_query,
66
+ answer = nl_response,
67
+ data = results_list,
68
+ error = execution_error if execution_error else error_msg
69
+ )
70
+ except Exception as e:
71
+ return chatResponse(
72
+ status = "error",
73
+ sql = "N/A",
74
+ answer = "An unexpected error occurred.",
75
+ data = [],
76
+ error = str(e)
77
+ )
backend/src/database/auth_db.json ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "admin": {
3
+ "password": "c1596a39b4dba28985cce3cb1bd83df3fb0730d09a4f28a830fda8764da71193",
4
+ "history": []
5
+ },
6
+ "dvwn": {
7
+ "password": "508f236e3d89d38a24689b345c0138f6667a6f18f305bd5f57255730c3869c0c",
8
+ "history": [],
9
+ "sessions": [
10
+ {
11
+ "title": "Which genres have more th",
12
+ "messages": [
13
+ {
14
+ "role": "user",
15
+ "content": "Which genres have more than 100 tracks? List the genre name and count."
16
+ },
17
+ {
18
+ "role": "assistant",
19
+ "content": "Failed to compute response due to error: Execution failed on sql 'SELECT G.Name, COUNT(T.TrackId) AS TrackCount FROM Genre G JOIN Album A ON G.GenreId = A.GenreId JOIN Track T ON A.AlbumId = T.AlbumId GROUP BY G.Name HAVING COUNT(T.TrackId) > 100': no such column: A.GenreId"
20
+ },
21
+ {
22
+ "role": "user",
23
+ "content": "List the first and last names of all employees who are Sales Support Agents."
24
+ },
25
+ {
26
+ "role": "assistant",
27
+ "content": "The Sales Support Agents are Jane Peacock, Margaret Park, and Steve Johnson.\n\n```sql\nSELECT FirstName, LastName FROM Employee WHERE Title = 'Sales Support Agent'\n```",
28
+ "dataframe": [
29
+ {
30
+ "FirstName": "Jane",
31
+ "LastName": "Peacock"
32
+ },
33
+ {
34
+ "FirstName": "Margaret",
35
+ "LastName": "Park"
36
+ },
37
+ {
38
+ "FirstName": "Steve",
39
+ "LastName": "Johnson"
40
+ }
41
+ ]
42
+ }
43
+ ]
44
+ },
45
+ {
46
+ "title": "Find the total number of ",
47
+ "messages": [
48
+ {
49
+ "role": "user",
50
+ "content": "Find the total number of items sold for each media type."
51
+ },
52
+ {
53
+ "role": "assistant",
54
+ "content": "There was a total of 5 items sold across all media types.\n\n```sql\nSELECT mt.Name, COUNT(*) AS total_items_sold FROM MediaType mt JOIN (SELECT t.MediaTypeId, COUNT(*) AS items_sold FROM Track t JOIN Album a ON t.AlbumId = a.AlbumId GROUP BY t.MediaTypeId) AS m ON mt.MediaTypeId = m.MediaTypeId GROUP BY mt.Name;\n```",
55
+ "dataframe": [
56
+ {
57
+ "Name": "AAC audio file",
58
+ "total_items_sold": 1
59
+ },
60
+ {
61
+ "Name": "MPEG audio file",
62
+ "total_items_sold": 1
63
+ },
64
+ {
65
+ "Name": "Protected AAC audio file",
66
+ "total_items_sold": 1
67
+ },
68
+ {
69
+ "Name": "Protected MPEG-4 video file",
70
+ "total_items_sold": 1
71
+ },
72
+ {
73
+ "Name": "Purchased AAC audio file",
74
+ "total_items_sold": 1
75
+ }
76
+ ]
77
+ }
78
+ ]
79
+ }
80
+ ]
81
+ }
82
+ }
backend/src/nl2sql/hf_engine.py CHANGED
@@ -15,7 +15,7 @@ MODEL_REGISTRY = {
15
  #"deepseek-ai/DeepSeek-R1-Distill-Qwen-32B:featherless-ai": "chat"
16
  }
17
 
18
- DEFAULT_MODEL_ID = "Qwen/Qwen2.5-Coder-32B-Instruct:featherless-ai"
19
 
20
  # Custom LangChain wrapper for HuggingFace Inference API
21
  class HFChatWrapper(LLM):
 
15
  #"deepseek-ai/DeepSeek-R1-Distill-Qwen-32B:featherless-ai": "chat"
16
  }
17
 
18
+ DEFAULT_MODEL_ID = "Qwen/Qwen2.5-Coder-7B-Instruct:featherless-ai"
19
 
20
  # Custom LangChain wrapper for HuggingFace Inference API
21
  class HFChatWrapper(LLM):
components/auth.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path: frontend/components/auth.py
2
+ # Authentication component for handling user login and registration.
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import streamlit as st
7
+ import pandas as pd
8
+ from typing import Tuple
9
+ from pathlib import Path
10
+ from dotenv import load_dotenv
11
+
12
+ load_dotenv()
13
+
14
+ AUTH_DB_PATH = Path("backend/src/database/auth_db.json")
15
+
16
+ # Hashing password
17
+ def hash_password(password):
18
+ """ Securely hashes a password """
19
+ return hashlib.sha256(password.encode()).hexdigest()
20
+
21
+ # Load user JSON-databases
22
+ def load_userDB():
23
+ """ Load authenticated credentials from local JSON file """
24
+ if not AUTH_DB_PATH.exists():
25
+ AUTH_DB_PATH.parent.mkdir(parents=True, exist_ok=True)
26
+ admin_user = os.getenv("DEFAULT_ADMIN_PASS")
27
+ if not admin_user:
28
+ raise ValueError("SECURITY HALT: DEFAULT_ADMIN_PASS environment is missing. Cannot initialize database securely.")
29
+
30
+ default_db = {
31
+ "admin": {
32
+ "password": hash_password(admin_user),
33
+ "history": []
34
+ }
35
+ }
36
+
37
+ with open(AUTH_DB_PATH, "w") as f:
38
+ json.dump(default_db, f, indent=4)
39
+ return default_db
40
+
41
+ with open(AUTH_DB_PATH, "r") as f:
42
+ return json.load(f)
43
+
44
+ # Sace user data into the JSON-databases
45
+ def save_userDB(db_data: dict):
46
+ with open(AUTH_DB_PATH, "w") as f:
47
+ json.dump(db_data, f, indent=4)
48
+
49
+ # User registration/create new account
50
+ def register_user(username: str, password: str) -> Tuple[bool, str]:
51
+ """ Registers a new user record safely into the system """
52
+ if not username or not password:
53
+ return False, "Fields cannot be empty."
54
+
55
+ db = load_userDB()
56
+ if username in db:
57
+ return False, "Username already exists. Please choose a different one."
58
+
59
+ db[username] = {
60
+ "password": hash_password(password),
61
+ "history": []
62
+ }
63
+ save_userDB(db)
64
+ return True, "Account registered successfully!"
65
+
66
+ # User login
67
+ def verify_login(username: str, password: str) -> bool:
68
+ """ Verifies credentials against the authentication store """
69
+ db = load_userDB()
70
+ if username not in db:
71
+ return False
72
+ return db[username]["password"] == hash_password(password)
73
+
74
+ # Save user's conversation
75
+ def save_chat_history(username: str, session_messages: list):
76
+ """ Saves user's conversation logs to history """
77
+ if not username or username == "guest" or not session_messages:
78
+ return
79
+
80
+ db = load_userDB()
81
+ if username in db:
82
+ if "sessions" not in db[username]:
83
+ db[username]["sessions"] = []
84
+
85
+ # Sanitize messages to make df JSON-serializable
86
+ sanitized_msg = []
87
+ for msg in session_messages:
88
+ clean_msg = {}
89
+ for key, value in msg.items():
90
+ if isinstance(value, pd.DataFrame):
91
+ clean_msg[key] = value.to_dict(orient="records")
92
+ else:
93
+ clean_msg[key] = value
94
+ sanitized_msg.append(clean_msg)
95
+
96
+ first_prompt = next((m["content"] for m in session_messages if m["role"] == "user"), "New Query")
97
+ truncated_title = first_prompt[:25]
98
+
99
+ # Check whether update an existing session / append new history
100
+ existing_sessions = db[username]["sessions"]
101
+ session_exists = False
102
+
103
+ for ses in existing_sessions:
104
+ if ses.get("title") == truncated_title:
105
+ ses["messages"] = sanitized_msg
106
+ session_exists = True
107
+ break
108
+
109
+ if not session_exists:
110
+ existing_sessions.append({
111
+ "title": truncated_title,
112
+ "messages": sanitized_msg
113
+ })
114
+
115
+ db[username]["sessions"] = existing_sessions
116
+ save_userDB(db)
117
+ st.session_state.chat_sessions = existing_sessions
118
+
119
+ # Retrieves user's history
120
+ def get_history(username: str) -> list:
121
+ """ Retrieves saved conversation history for verified users """
122
+ db = load_userDB()
123
+ if username in db:
124
+ return db[username].get("sessions", [])
125
+ return []
126
+
127
+ @st.dialog("Account Access Panel")
128
+ def render_auth_dialog():
129
+ """
130
+ Streamlit UI native dialog: Handle custom login & signup cleanly without template injection
131
+ """
132
+ st.subheader("Sign In or Register")
133
+ tab1, tab2 = st.tabs([":material/lock: Login", ":material/new: Create Account"])
134
+
135
+ with tab1:
136
+ login_user = st.text_input("Username", key="login_user_input")
137
+ login_pass = st.text_input("Password", type="password", key="login_pass_input")
138
+ if st.button("Authenticate", type="primary", use_container_width=True):
139
+ if verify_login(login_user, login_pass):
140
+ st.session_state.auth_stat = "logged_in"
141
+ st.session_state.username = login_user
142
+ st.session_state.messages = get_history(login_user)
143
+ st.success(f"Welcome back, {login_user}!")
144
+ st.rerun()
145
+ else:
146
+ st.error("Invalid username or password credentials.")
147
+
148
+ with tab2:
149
+ reg_user = st.text_input("Username", key="reg_user_input")
150
+ reg_pass = st.text_input("Password", type="password", key="reg_user_pass")
151
+ reg_pass_confirm = st.text_input("Re-enter Password", type="password", key="reg_user_pass_confirm")
152
+ if st.button("Sign Up Now", use_container_width=True):
153
+ if reg_pass != reg_pass_confirm:
154
+ st.error("Password does not match!")
155
+ else:
156
+ success, msg = register_user(reg_user, reg_pass)
157
+ if success:
158
+ st.success(msg)
159
+ # Login user automatically
160
+ st.session_state.auth_stat = "logged_in"
161
+ st.session_state.username = reg_user
162
+ st.session_state.messages = []
163
+ st.rerun()
164
+ else:
165
+ st.error(msg)
components/chat.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path: frontend/components/chat.py
2
+ # Chat component for handling user interactions and displaying chat history.
3
+ import streamlit as st
4
+ import pandas as pd
5
+ from utils.api import process_userPrompt
6
+ from components.auth import save_chat_history
7
+
8
+ def render_chat_interface():
9
+ st.title(":material/sql: NL2SQL Assistant")
10
+ st.divider()
11
+
12
+ if not st.session_state.messages:
13
+ for _ in range(5):
14
+ st.write("")
15
+ _, center_col, _ = st.columns([1, 2, 1])
16
+ with center_col:
17
+ st.subheader(":material/calendar_view_month: Ask a question about your data (e.g., 'What is the top revenue in 2020')", anchor=False)
18
+
19
+ for idx, message in enumerate(st.session_state.messages):
20
+ role = message.get("role", "assistant")
21
+ content = message.get("content", "")
22
+
23
+ with st.chat_message(role):
24
+ st.markdown(content)
25
+
26
+ if message.get("dataframe") is not None:
27
+ raw_data = message["dataframe"]
28
+
29
+ if isinstance(raw_data, list):
30
+ display_df = pd.DataFrame(raw_data)
31
+ else:
32
+ display_df = raw_data
33
+
34
+ st.dataframe(display_df, use_container_width=True)
35
+ # display_df = message["dataframe"]
36
+ # st.dataframe(message["dataframe"], use_container_width=True)
37
+
38
+ csv_data = display_df.to_csv().encode('utf-8')
39
+ if st.download_button(
40
+ label=":material/download: Download CSV",
41
+ data=csv_data,
42
+ file_name=f'query_results_{idx}.csv',
43
+ mime='text/csv',
44
+ key=f"download_{idx}"
45
+ ):
46
+ st.toast("The file has been downloaded!")
47
+
48
+ if prompt := st.chat_input("Ask a question about yout data..."):
49
+ # Append user message
50
+ st.session_state.messages.append({"role": "user", "content": prompt})
51
+ st.rerun()
52
+
53
+ if st.session_state.messages and st.session_state.messages[-1]["role"] == "user":
54
+ with st.chat_message("assistant"):
55
+ with st.spinner("Analyzing schema metadata and generating execution context..."):
56
+ payload = process_userPrompt(
57
+ question=st.session_state.messages[-1]["content"],
58
+ model_id=st.session_state.current_model
59
+ )
60
+
61
+ if payload["status"] == "error":
62
+ st.error(f"Interrupted:\n{payload['error']}")
63
+ response_text = f"Failed to compute response due to error: {payload['error']}"
64
+ st.session_state.messages.append({"role": "assistant", "content": response_text})
65
+ else:
66
+ st.markdown(payload["answer"])
67
+ st.code(payload["sql"], language="sql")
68
+
69
+ display_df = payload["data"]
70
+ if not display_df.empty:
71
+ display_df = display_df.copy()
72
+ display_df.index = range(1, len(display_df) + 1)
73
+ display_df.index.name = "No."
74
+
75
+ st.session_state.messages.append({
76
+ "role": "assistant",
77
+ "content": f"{payload['answer']}\n\n```sql\n{payload['sql']}\n```",
78
+ "dataframe": display_df if not display_df.empty else None
79
+ })
80
+
81
+ if st.session_state.auth_stat != 'guest':
82
+ save_chat_history(st.session_state.username, st.session_state.messages)
83
+
84
+ st.rerun()
components/sidebar.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path: frontend/components/sidebar.py
2
+ # Sidebar component for navigation and additional options.
3
+ import streamlit as st
4
+ from utils.api import get_available_models
5
+ from components.auth import render_auth_dialog, save_chat_history, save_userDB, load_userDB
6
+
7
+ @st.dialog("Delete Confirmation")
8
+ def confirm_delete(idx, session_title):
9
+ st.warning(f"Are you sure you want to delete '{session_title}'?")
10
+ st.write(":material/warning: This action cannot be undone!")
11
+
12
+ col1, col2 = st.columns(2)
13
+ with col1:
14
+ if st.button("Cancel", use_container_width=True):
15
+ st.rerun()
16
+
17
+ with col2:
18
+ if st.button("Delete", type="primary", use_container_width=True):
19
+ deleted_session = st.session_state.chat_sessions.pop(idx)
20
+ st.toast("Item permanently deleted!", icon=":material/delete:")
21
+
22
+ if st.session_state.messages == deleted_session.get("messages", []):
23
+ st.session_state.messages = []
24
+
25
+ db = load_userDB()
26
+ if st.session_state.username in db:
27
+ db[st.session_state.username]["sessions"] = st.session_state.chat_sessions
28
+ save_userDB(db)
29
+ st.rerun()
30
+
31
+ def render_sidebar():
32
+ with st.sidebar:
33
+ #st.subheader(":material/sql:", anchor=False)
34
+ if st.session_state.auth_stat == 'guest':
35
+ if st.button(":material/login: Login / Sign Up", type="secondary", use_container_width=True):
36
+ render_auth_dialog()
37
+ else:
38
+ if st.button(":material/logout: Logout", use_container_width=True):
39
+ st.session_state.auth_stat = 'guest'
40
+ st.session_state.username = 'guest'
41
+ st.session_state.messages = []
42
+ if "chat_sessions" in st.session_state:
43
+ del st.session_state.chat_sessions
44
+ st.rerun()
45
+
46
+ if st.button(":material/add: New Chat", use_container_width=True):
47
+ if st.session_state.auth_stat != 'guest':
48
+ save_chat_history(st.session_state.username, st.session_state.messages)
49
+ st.session_state.messages = []
50
+ st.rerun()
51
+ st.divider()
52
+
53
+ st.caption("Database Connection")
54
+ st.success(icon=":material/circle:", body="Connected")
55
+
56
+ st.caption("Model Selector")
57
+ available_models = get_available_models()
58
+ st.session_state.current_model = st.selectbox(
59
+ "Select model:",
60
+ available_models,
61
+ label_visibility="collapsed"
62
+ )
63
+ st.divider()
64
+
65
+ st.caption("History")
66
+ if st.session_state.auth_stat == 'guest':
67
+ st.info("You are in Guest Mode. Your conversation history will not be saved.")
68
+ else:
69
+ st.caption(f"Authenticated as: {st.session_state.username}")
70
+ if "chat_sessions" not in st.session_state:
71
+ db = load_userDB()
72
+ st.session_state.chat_sessions = db.get(st.session_state.username, {}).get("sessions", [])
73
+
74
+ if st.session_state.messages:
75
+ st.button(f":material/chat_bubble: Active Session Logs", disabled=True, use_container_width=True)
76
+
77
+ if not st.session_state.chat_sessions:
78
+ st.caption('Query your database now')
79
+ else:
80
+ for idx, session in enumerate(st.session_state.chat_sessions):
81
+ col1, col2 = st.columns([0.80, 0.20])
82
+
83
+ with col1:
84
+ session_title = session.get("title", f"Chat {idx + 1}")
85
+ if st.button(
86
+ f":material/history: {session_title[:15]}...",
87
+ key=f"load_session_{idx}",
88
+ use_container_width=True
89
+ ):
90
+ st.session_state.messages = session.get("messages", [])
91
+ st.rerun()
92
+
93
+ with col2:
94
+ if st.button(":material/delete:", key=f"delete_session_{idx}"):
95
+ confirm_delete(idx, session_title)
frontend/app.py DELETED
@@ -1,27 +0,0 @@
1
- # Path: frontend/app.py
2
- # Main application entry point, setting up the app and routing.
3
- import streamlit as st
4
- from components import auth, sidebar, chat
5
-
6
- st.set_page_config(page_icon=":material/sql:", page_title="NL2SQL Assistant", layout="wide")
7
-
8
- # Initialize global session state variables
9
- if 'user_id' not in st.session_state:
10
- st.session_state['user_id'] = None
11
- if 'guest_mode' not in st.session_state:
12
- st.session_state['guest_mode'] = False
13
- if 'current_session_id' not in st.session_state:
14
- st.session_state['current_session_id'] = None
15
- if 'messages' not in st.session_state:
16
- st.session_state['messages'] = []
17
-
18
- def main():
19
- if st.session_state['user_id'] is None and not st.session_state['guest_mode']:
20
- # User not logged in, show authentication page
21
- auth.render_auth()
22
- else:
23
- sidebar.render_sidebar()
24
- chat.render_chat_interface()
25
-
26
- if __name__ == "__main__":
27
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/components/__pycache__/__init__.cpython-313.pyc DELETED
Binary file (166 Bytes)
 
frontend/components/__pycache__/auth.cpython-313.pyc DELETED
Binary file (2.48 kB)
 
frontend/components/__pycache__/chat.cpython-313.pyc DELETED
Binary file (3.23 kB)
 
frontend/components/__pycache__/sidebar.cpython-313.pyc DELETED
Binary file (3.75 kB)
 
frontend/components/auth.py DELETED
@@ -1,33 +0,0 @@
1
- # Path: frontend/components/auth.py
2
- # Authentication component for handling user login and registration.
3
- import streamlit as st
4
- from utils import api
5
-
6
- def render_auth():
7
- st.title("Welcome to NL2SQL Assistant Demo")
8
- tab_login, tab_signup = st.tabs(["Login", "Sign Up"])
9
-
10
- with tab_login:
11
- with st.form("login_form"):
12
- email = st.text_input("Email")
13
- password = st.text_input("Password", type="password")
14
- if st.form_submit_button("Login"):
15
- response = api.user_login(email, password)
16
- if response.get("success"):
17
- st.session_state['user_id'] = response.get("user_id")
18
- st.rerun()
19
- else:
20
- st.error("Invalid email or password. Please try again.")
21
-
22
- with tab_signup:
23
- with st.form("signup_form"):
24
- email = st.text_input("Email")
25
- new_password = st.text_input("Password", type="password")
26
- if st.form_submit_button("Sign Up"):
27
- st.success("Account created successfully! Plase login to continue.")
28
-
29
- st.divider()
30
- st.markdown("Or continue as a guest:")
31
- if st.button("Continue as Guest", use_container_width=True):
32
- st.session_state['guest_mode'] = True
33
- st.rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/components/chat.py DELETED
@@ -1,52 +0,0 @@
1
- # Path: frontend/components/chat.py
2
- # Chat component for handling user interactions and displaying chat history.
3
- import streamlit as st
4
- import pandas as pd
5
- from utils import api
6
-
7
- def render_chat_interface():
8
- st.title(":material/sql: NL2SQL Assistant")
9
- st.divider()
10
-
11
- # Render existing messages
12
- for msg in st.session_state['messages']:
13
- with st.chat_message(msg["role"]):
14
- st.markdown(msg["content"])
15
- if "sql" in msg and msg["sql"]:
16
- st.code(msg["sql"], language="sql")
17
- if "data" in msg and msg["data"]:
18
- st.dataframe(pd.DataFrame(msg["data"]))
19
-
20
- # Input area for new messages
21
- if prompt := st.chat_input("Ask a question about your database (e.g., 'Show me top revenue in 2020')"):
22
- # Display user prompt
23
- st.session_state['messages'].append({"role": "user", "content": prompt})
24
- with st.chat_message("user"):
25
- st.markdown(prompt)
26
-
27
- # Process and get assistant response
28
- with st.chat_message("assistant"):
29
- with st.spinner("Executing LangChain pipeline for RAG-based schema retrieval..."):
30
- response = api.send_chat_message(
31
- user_id = st.session_state['user_id'],
32
- session_id = st.session_state.get('current_session_id'),
33
- message = prompt
34
- )
35
-
36
- # Render results
37
- st.markdown(response.get("answer", "Generated SQL based on the query:"))
38
- st.code(response["sql"], language="sql")
39
- if response.get("data"):
40
- st.dataframe(pd.DataFrame(response["data"]))
41
-
42
- # Save conversations to session state
43
- st.session_state['messages'].append({
44
- "role": "assistant",
45
- "content": response.get("answer", ""),
46
- "sql": response["sql"],
47
- "data": response.get("data")
48
- })
49
-
50
- # Save session ID automatically if user is authenticated and it's a new session
51
- if not st.session_state['guest_mode'] and st.session_state['current_session_id'] is None:
52
- st.session_state['current_session_id'] = response.get("session_id")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/components/sidebar.py DELETED
@@ -1,58 +0,0 @@
1
- # Path: frontend/components/sidebar.py
2
- # Sidebar component for navigation and additional options.
3
- import streamlit as st
4
- from utils import api
5
-
6
- def render_sidebar():
7
- with st.sidebar:
8
- st.header(":material/sql:")
9
-
10
- if st.button(":material/add: New Chat", use_container_width=True):
11
- st.session_state['current_session_id'] = None
12
- st.session_state['messages'] = []
13
- st.rerun()
14
- st.divider()
15
-
16
- st.subheader("Model Selection")
17
- model_options = st.selectbox(
18
- "Choose a model:",
19
- ["Model A", "Model B"],
20
- label_visibility="collapsed"
21
- )
22
-
23
- # Guest View
24
- if st.session_state['guest_mode']:
25
- st.info("You are in Guest Mode. Your conversation history will not be saved.")
26
- st.write("Create an account to save your queries.")
27
- if st.button("Log In / Sign Up", use_container_width=True):
28
- st.session_state['guest_mode'] = False
29
- st.rerun()
30
- # Authenticated User View
31
- else:
32
- st.header(":material/history: History")
33
- # Fetch history
34
- history = api.get_user_history(st.session_state['user_id'])
35
-
36
- for time_label, sessions in history.items():
37
- if sessions:
38
- st.caption(time_label)
39
- for session in sessions:
40
- col1, col2 = st.columns([5, 1])
41
-
42
- with col1:
43
- if st.button(f":material/chat_bubble: {session['title'][:20]}", key=f"sel_{session['id']}", use_container_width=True):
44
- st.session_state['current_session_id'] = session['id']
45
- st.session_state['messages'] = api.get_session_messages(session['id'])
46
- st.rerun()
47
- with col2:
48
- if st.button(":material/delete:", key=f"del_{session['id']}", help="Delete Chat History"):
49
- if api.del_conversation(session['id']):
50
- if st.session_state['current_session_id'] == session['id']:
51
- st.session_state['current_session_id'] = None
52
- st.session_state['messages'] = []
53
- st.rerun()
54
- st.divider()
55
- if st.button(":material/logout: Logout", use_container_width=True):
56
- st.session_state['user_id'] = None
57
- st.session_state['messages'] = []
58
- st.rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/requirements.txt DELETED
Binary file (1.59 kB)
 
frontend/utils/__pycache__/__init__.cpython-313.pyc DELETED
Binary file (161 Bytes)
 
frontend/utils/__pycache__/api.cpython-313.pyc DELETED
Binary file (156 Bytes)
 
frontend/utils/api.py DELETED
@@ -1,2 +0,0 @@
1
- # Path: frontend/utils/api.py
2
- # API utility functions for making requests to the backend server.
 
 
 
requirements.txt CHANGED
Binary files a/requirements.txt and b/requirements.txt differ
 
utils/api.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path: frontend/utils/api.py
2
+ # API utility functions for making requests to the backend server.
3
+ import pandas as pd
4
+ import streamlit as st
5
+ import requests
6
+ from typing import List, Dict, Any, Tuple
7
+
8
+ FASTAPI_BASE_URL = "http://localhost:8000"
9
+
10
+ @st.cache_data(ttl=600)
11
+ def get_available_models() -> List[str]:
12
+ """ Fetches available models via FastAPI """
13
+ try:
14
+ resp = requests.get(f"{FASTAPI_BASE_URL}/models", timeout=10)
15
+ resp.raise_for_status()
16
+ return resp.json()
17
+ except Exception as e:
18
+ st.warning(f"Backend unreachable. Using fallback models. Error: {e}")
19
+ return ["Qwen/Qwen2.5-Coder-7B-Instruct:featherless-ai"]
20
+
21
+ def process_userPrompt(question: str, model_id: str) -> Dict[str, Any]:
22
+ """ Send user's question to FastAPI and parses the response """
23
+ try:
24
+ payload = {
25
+ "question": question,
26
+ "model_id": model_id
27
+ }
28
+
29
+ resp = requests.post(f"{FASTAPI_BASE_URL}/chat", json=payload, timeout=60)
30
+ resp.raise_for_status()
31
+ data = resp.json()
32
+
33
+ df_results = pd.DataFrame(data["data"]) if data.get("data") else pd.DataFrame()
34
+
35
+ return {
36
+ "status": data["status"],
37
+ "sql": data["sql"],
38
+ "answer": data["answer"],
39
+ "data": df_results,
40
+ "error": data["error"]
41
+ }
42
+ except requests.exceptions.RequestException as e:
43
+ return {
44
+ "status": "error",
45
+ "sql": "N/A",
46
+ "answer": "Failed to connect to the backend server.",
47
+ "data": pd.DataFrame(),
48
+ "error": str(e)
49
+ }