Spaces:
Sleeping
Sleeping
File size: 3,438 Bytes
22f883a 2e8eb5b 22f883a | 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 | import streamlit as st
import PyPDF2
import docx
from langchain_core.prompts import ChatPromptTemplate
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.output_parsers import StrOutputParser
# Secure API key handling
api_key = "AIzaSyBuhWQHGfMQewIY_gdnmbzzYoori6faeUo" # Store in .streamlit/secrets.toml
# Database options
db_options = ["MySQL", "PostgreSQL", "SQLite", "MSSQL", "Oracle", "MongoDB", "Firebase"]
# Function to read PDF files
def read_pdf(file):
reader = PyPDF2.PdfReader(file)
text = "\n".join([page.extract_text() for page in reader.pages if page.extract_text()])
return text
# Function to read DOCX files
def read_docx(file):
doc = docx.Document(file)
text = "\n".join([para.text for para in doc.paragraphs])
return text
# System prompt for SQL and NoSQL problem solving
prompt_template = ChatPromptTemplate.from_messages([
("system", """
You are an expert in database problem solving. Given a database-related problem statement,
provide the most efficient solution using SQL or NoSQL depending on the selected database system.
Ensure the query follows best practices, is optimized for performance, and works across multiple RDBMS like MySQL, PostgreSQL, SQLite, MSSQL, and Oracle.
Additionally, support NoSQL databases such as MongoDB and Firebase by providing appropriate queries.
Output format:
**Query:**
```sql or NoSQL
-- Database query
```
**Explanation:**
- Step-by-step breakdown of the query logic.
- Performance considerations and optimizations if applicable.
- Compatibility notes for the selected database.
"""),
("human", """
Database Problem: {sql_problem}
Selected Database: {db_type}
""")
])
chat_model = ChatGoogleGenerativeAI(google_api_key=api_key, model='models/gemini-2.0-flash-exp')
parser = StrOutputParser()
chain = prompt_template | chat_model | parser
def solve_sql_problem(sql_problem, db_type):
"""Generates an AI-powered database solution based on the selected database type."""
try:
response = chain.invoke({"sql_problem": sql_problem, "db_type": db_type})
return response if response else "No solution available."
except Exception as e:
return f"Error: {str(e)}"
# Streamlit UI
st.title("🛠️ AI-Powered Database Problem Solver")
st.write("Enter a database-related problem statement, select the database type, and AI will generate an optimized solution for you.")
col1, col2 = st.columns(2)
with col1:
sql_problem = st.text_area("Database Problem Statement", placeholder="Describe your database problem here...")
uploaded_file = st.file_uploader("Upload a DOCX or PDF file", type=["pdf", "docx"])
if uploaded_file is not None:
if uploaded_file.type == "application/pdf":
sql_problem = read_pdf(uploaded_file)
elif uploaded_file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
sql_problem = read_docx(uploaded_file)
st.success("File uploaded successfully!")
with col2:
db_type = st.selectbox("Select Database Type", db_options)
if st.button("Generate Solution") and sql_problem:
with st.spinner("Generating solution..."):
sql_solution = solve_sql_problem(sql_problem, db_type)
st.subheader("AI-Generated Database Solution")
st.markdown(sql_solution, unsafe_allow_html=True)
|