ubaid975 commited on
Commit
f49089c
·
verified ·
1 Parent(s): e40bd04

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +28 -36
src/streamlit_app.py CHANGED
@@ -5,13 +5,13 @@ from langchain.agents import create_sql_agent
5
  from langchain_groq import ChatGroq
6
  from langchain_community.agent_toolkits import SQLDatabaseToolkit
7
  from dotenv import load_dotenv
 
8
  import sqlite3
9
  import pandas as pd
10
  import os
11
 
12
  load_dotenv()
13
 
14
-
15
  def is_valid_sqlite(file_path):
16
  try:
17
  with sqlite3.connect(file_path) as conn:
@@ -20,7 +20,6 @@ def is_valid_sqlite(file_path):
20
  except sqlite3.DatabaseError:
21
  return False
22
 
23
-
24
  def text_to_sql(query: str, db_path: str, llm_provider: str, api_key: str, model_name: str):
25
  try:
26
  db = SQLDatabase.from_uri(f"sqlite:///{db_path}")
@@ -41,7 +40,6 @@ def text_to_sql(query: str, db_path: str, llm_provider: str, api_key: str, model
41
  except Exception as e:
42
  return f"Error: {str(e)}"
43
 
44
-
45
  def show_tables_as_df(db_path):
46
  conn = sqlite3.connect(db_path)
47
  cursor = conn.cursor()
@@ -61,46 +59,40 @@ def show_tables_as_df(db_path):
61
 
62
 
63
  # Streamlit UI
64
- st.title('🗃️ Chat with SQLite Database')
65
 
66
- st.write("Interact with your SQLite databases stored on server using LLM-powered queries.")
67
 
68
- # List of .db files in "data" folder
69
- db_folder = "data"
70
- os.makedirs(db_folder, exist_ok=True)
71
- db_files = [f for f in os.listdir(db_folder) if f.endswith('.db')]
72
-
73
- selected_db = st.selectbox("Select Database", options=db_files)
74
 
75
  llm_provider = st.radio("Choose LLM Provider", options=['OPEN_ROUTER', 'GROQ', 'OPENAI'])
76
  model_name = st.text_input("Enter the Model Name", value='nousresearch/deephermes-3-mistral-24b-preview:free')
77
  api_key = st.text_input("Enter Your API Key", type="password")
78
  query = st.text_area("Enter Your Query")
79
 
80
- try:
81
- if selected_db:
82
- tmp_db_path = os.path.join(db_folder, selected_db)
 
83
 
84
- if not is_valid_sqlite(tmp_db_path):
85
- st.error("The selected file is not a valid SQLite database.")
86
- else:
87
- st.success("Valid SQLite database selected!")
88
-
89
- # Show tables
90
- st.info("Displaying first 10 rows from each table:")
91
- show_tables_as_df(tmp_db_path)
92
-
93
- if st.button("RUN Query"):
94
- if not api_key or not model_name:
95
- st.error("Please provide API key and model name.")
96
- elif not query.strip():
97
- st.error("Please enter a query.")
98
- else:
99
- st.info(f"Running query on `{selected_db}`...")
100
- result = text_to_sql(query, tmp_db_path, llm_provider, api_key, model_name)
101
- st.success("Query Result:")
102
- st.write(result)
103
-
104
- except Exception as e:
105
- st.error(f"Error: {str(e)}")
106
 
 
5
  from langchain_groq import ChatGroq
6
  from langchain_community.agent_toolkits import SQLDatabaseToolkit
7
  from dotenv import load_dotenv
8
+ import tempfile
9
  import sqlite3
10
  import pandas as pd
11
  import os
12
 
13
  load_dotenv()
14
 
 
15
  def is_valid_sqlite(file_path):
16
  try:
17
  with sqlite3.connect(file_path) as conn:
 
20
  except sqlite3.DatabaseError:
21
  return False
22
 
 
23
  def text_to_sql(query: str, db_path: str, llm_provider: str, api_key: str, model_name: str):
24
  try:
25
  db = SQLDatabase.from_uri(f"sqlite:///{db_path}")
 
40
  except Exception as e:
41
  return f"Error: {str(e)}"
42
 
 
43
  def show_tables_as_df(db_path):
44
  conn = sqlite3.connect(db_path)
45
  cursor = conn.cursor()
 
59
 
60
 
61
  # Streamlit UI
62
+ st.title('🗃️ Chat with YOUR SQLite Database')
63
 
64
+ st.write("Upload your `.db` file and interact using natural language queries powered by LLMs.")
65
 
66
+ uploaded_file = st.file_uploader("Upload SQLite Database (.db file)", type=["db"])
 
 
 
 
 
67
 
68
  llm_provider = st.radio("Choose LLM Provider", options=['OPEN_ROUTER', 'GROQ', 'OPENAI'])
69
  model_name = st.text_input("Enter the Model Name", value='nousresearch/deephermes-3-mistral-24b-preview:free')
70
  api_key = st.text_input("Enter Your API Key", type="password")
71
  query = st.text_area("Enter Your Query")
72
 
73
+ if uploaded_file:
74
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".db", dir="/tmp") as tmpfile:
75
+ tmpfile.write(uploaded_file.read())
76
+ tmp_db_path = tmpfile.name
77
 
78
+ if not is_valid_sqlite(tmp_db_path):
79
+ st.error("Uploaded file is not a valid SQLite database.")
80
+ else:
81
+ st.success(f"Valid database `{uploaded_file.name}` uploaded!")
82
+
83
+ st.info("Displaying first 10 rows from each table:")
84
+ show_tables_as_df(tmp_db_path)
85
+
86
+ if st.button("RUN Query"):
87
+ if not api_key or not model_name:
88
+ st.error("Please provide API key and model name.")
89
+ elif not query.strip():
90
+ st.error("Please enter a query.")
91
+ else:
92
+ st.info(f"Running query on `{uploaded_file.name}`...")
93
+ result = text_to_sql(query, tmp_db_path, llm_provider, api_key, model_name)
94
+ st.success("Query Result:")
95
+ st.write(result)
96
+ else:
97
+ st.info("Please upload a SQLite `.db` file to begin.")
 
 
98