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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from dotenv import load_dotenv
|
| 3 |
+
import os
|
| 4 |
+
import sqlite3
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import google.generativeai as genai
|
| 7 |
+
import re
|
| 8 |
+
from langchain import hub
|
| 9 |
+
from langchain_chroma import Chroma
|
| 10 |
+
from langchain_community.document_loaders import PyPDFLoader
|
| 11 |
+
from langchain_openai import OpenAIEmbeddings
|
| 12 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 13 |
+
from langchain_groq import ChatGroq
|
| 14 |
+
from langchain.prompts import PromptTemplate
|
| 15 |
+
from langchain.schema.runnable import RunnablePassthrough
|
| 16 |
+
import tempfile
|
| 17 |
+
|
| 18 |
+
# Load environment variables
|
| 19 |
+
load_dotenv()
|
| 20 |
+
|
| 21 |
+
# Configure API keys
|
| 22 |
+
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
| 23 |
+
groq_api_key = os.getenv("GROQ_API_KEY")
|
| 24 |
+
|
| 25 |
+
# Function to load Google Gemini Model and get response
|
| 26 |
+
def get_gemini_response(question, prompt, schema_info):
|
| 27 |
+
model = genai.GenerativeModel('gemini-pro')
|
| 28 |
+
response = model.generate_content([prompt, schema_info, question])
|
| 29 |
+
return response.text
|
| 30 |
+
|
| 31 |
+
# Function to retrieve query from the database
|
| 32 |
+
def read_sql_query(sql, db):
|
| 33 |
+
try:
|
| 34 |
+
conn = sqlite3.connect(db)
|
| 35 |
+
df = pd.read_sql_query(sql, conn)
|
| 36 |
+
conn.close()
|
| 37 |
+
return df
|
| 38 |
+
except sqlite3.Error as e:
|
| 39 |
+
st.error(f"An error occurred: {e.args[0]}")
|
| 40 |
+
return None
|
| 41 |
+
|
| 42 |
+
# Function to convert DataFrame to SQLite database
|
| 43 |
+
def dataframe_to_sqlite(df, db_name, table_name):
|
| 44 |
+
conn = sqlite3.connect(db_name)
|
| 45 |
+
df.to_sql(table_name, conn, if_exists='replace', index=False)
|
| 46 |
+
conn.close()
|
| 47 |
+
st.success("Data successfully loaded into the database!")
|
| 48 |
+
|
| 49 |
+
# Function to get schema information
|
| 50 |
+
def get_schema_info(df):
|
| 51 |
+
columns = df.columns.tolist()
|
| 52 |
+
dtypes = df.dtypes.astype(str).tolist()
|
| 53 |
+
schema_info = "Table name: DATA\nColumns:\n"
|
| 54 |
+
for col, dtype in zip(columns, dtypes):
|
| 55 |
+
schema_info += f"- {col} ({dtype})\n"
|
| 56 |
+
return schema_info
|
| 57 |
+
|
| 58 |
+
# Function to clean SQL query
|
| 59 |
+
def clean_sql_query(query):
|
| 60 |
+
query = re.sub(r'```sql|```', '', query)
|
| 61 |
+
query = query.strip()
|
| 62 |
+
return query
|
| 63 |
+
|
| 64 |
+
# Function to process PDF file
|
| 65 |
+
def process_document(file):
|
| 66 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
|
| 67 |
+
tmp_file.write(file.getvalue())
|
| 68 |
+
tmp_file_path = tmp_file.name
|
| 69 |
+
|
| 70 |
+
loader = PyPDFLoader(tmp_file_path)
|
| 71 |
+
documents = loader.load()
|
| 72 |
+
|
| 73 |
+
os.unlink(tmp_file_path) # Delete the temporary file
|
| 74 |
+
|
| 75 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
|
| 76 |
+
splits = text_splitter.split_documents(documents)
|
| 77 |
+
|
| 78 |
+
vectorstore = Chroma.from_documents(documents=splits, embedding=OpenAIEmbeddings())
|
| 79 |
+
return vectorstore.as_retriever()
|
| 80 |
+
|
| 81 |
+
# Streamlit App
|
| 82 |
+
st.set_page_config(page_title="AI-Powered Data Assistant")
|
| 83 |
+
st.header("AI-Powered Data Assistant")
|
| 84 |
+
|
| 85 |
+
# File upload section
|
| 86 |
+
st.subheader("Upload Your Data")
|
| 87 |
+
excel_file = st.file_uploader("Choose an Excel or CSV file", type=["xlsx", "csv"])
|
| 88 |
+
pdf_file = st.file_uploader("Choose a PDF file", type=["pdf"])
|
| 89 |
+
|
| 90 |
+
if excel_file:
|
| 91 |
+
try:
|
| 92 |
+
if excel_file.name.endswith('.csv'):
|
| 93 |
+
df = pd.read_csv(excel_file)
|
| 94 |
+
else:
|
| 95 |
+
df = pd.read_excel(excel_file)
|
| 96 |
+
|
| 97 |
+
dataframe_to_sqlite(df, "data.db", "DATA")
|
| 98 |
+
st.write(df.head())
|
| 99 |
+
st.success("Excel/CSV file successfully uploaded and data loaded into the database!")
|
| 100 |
+
|
| 101 |
+
st.session_state['schema_info'] = get_schema_info(df)
|
| 102 |
+
except Exception as e:
|
| 103 |
+
st.error(f"Error processing the Excel/CSV file: {str(e)}")
|
| 104 |
+
|
| 105 |
+
if pdf_file:
|
| 106 |
+
try:
|
| 107 |
+
retriever = process_document(pdf_file)
|
| 108 |
+
st.success("PDF file successfully processed!")
|
| 109 |
+
st.session_state['retriever'] = retriever
|
| 110 |
+
except Exception as e:
|
| 111 |
+
st.error(f"Error processing the PDF file: {str(e)}")
|
| 112 |
+
|
| 113 |
+
# Add radio button for data source selection
|
| 114 |
+
data_source = st.radio(
|
| 115 |
+
"Choose your data source for the query:",
|
| 116 |
+
("PDF", "Excel/CSV"),
|
| 117 |
+
index=None,
|
| 118 |
+
key="data_source"
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
# User query input
|
| 122 |
+
question = st.text_input("Ask a question about your data:", key="input")
|
| 123 |
+
submit = st.button("Get Answer")
|
| 124 |
+
|
| 125 |
+
if submit and question:
|
| 126 |
+
if not data_source:
|
| 127 |
+
st.error("Please select a data source (PDF or Excel/CSV) before submitting your question.")
|
| 128 |
+
elif data_source == "PDF" and 'retriever' in st.session_state:
|
| 129 |
+
with st.spinner("Processing your question using the PDF content..."):
|
| 130 |
+
llm = ChatGroq(temperature=0, model_name="mixtral-8x7b-32768")
|
| 131 |
+
pdf_prompt = PromptTemplate.from_template("""
|
| 132 |
+
You are an AI assistant specialized in analyzing and answering questions about PDF documents.
|
| 133 |
+
Use the provided context to answer the user's question accurately and concisely.
|
| 134 |
+
If the answer is not directly stated in the context, use your knowledge to provide a reasonable response,
|
| 135 |
+
but make it clear when you're inferring or speculating.
|
| 136 |
+
If you cannot answer the question based on the given context, say so clearly.
|
| 137 |
+
|
| 138 |
+
Context: {context}
|
| 139 |
+
|
| 140 |
+
Question: {input}
|
| 141 |
+
|
| 142 |
+
Provide a clear, concise, and informative answer:
|
| 143 |
+
""")
|
| 144 |
+
|
| 145 |
+
rag_chain = (
|
| 146 |
+
{"context": st.session_state['retriever'], "input": RunnablePassthrough()}
|
| 147 |
+
| pdf_prompt
|
| 148 |
+
| llm
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
response = rag_chain.invoke(question)
|
| 152 |
+
|
| 153 |
+
st.subheader("Answer:")
|
| 154 |
+
st.write(response.content)
|
| 155 |
+
|
| 156 |
+
elif data_source == "Excel/CSV" and 'schema_info' in st.session_state:
|
| 157 |
+
with st.spinner("Generating SQL query..."):
|
| 158 |
+
sql_query = get_gemini_response(question, "Generate SQL for this query:", st.session_state['schema_info'])
|
| 159 |
+
clean_query = clean_sql_query(sql_query)
|
| 160 |
+
|
| 161 |
+
st.subheader("Generated SQL Query:")
|
| 162 |
+
st.code(clean_query, language="sql")
|
| 163 |
+
|
| 164 |
+
with st.spinner("Executing query and fetching results..."):
|
| 165 |
+
result_df = read_sql_query(clean_query, "data.db")
|
| 166 |
+
|
| 167 |
+
if result_df is not None and not result_df.empty:
|
| 168 |
+
st.subheader("Query Result:")
|
| 169 |
+
st.dataframe(result_df)
|
| 170 |
+
else:
|
| 171 |
+
st.warning("No data found or an error occurred while executing the query.")
|
| 172 |
+
|
| 173 |
+
else:
|
| 174 |
+
st.error(f"Unable to process the query. Please make sure you've uploaded the appropriate file ({data_source}).")
|
requirements.txt
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
python-dotenv
|
| 2 |
+
streamlit
|
| 3 |
+
google-generativeai
|
| 4 |
+
pandas
|
| 5 |
+
python-dotenv
|
| 6 |
+
openpyxl
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
langchain_openai
|
| 10 |
+
langchain_core
|
| 11 |
+
langchain_community
|
| 12 |
+
langserve
|
| 13 |
+
|
| 14 |
+
pypdf
|
| 15 |
+
langchain_text_splitters
|
| 16 |
+
langchain_chroma
|
| 17 |
+
langchainhub
|
| 18 |
+
langchain-groq
|
| 19 |
+
PyPDF2
|
| 20 |
+
crewai
|