Spaces:
Sleeping
Sleeping
File size: 2,198 Bytes
e9f26bb 4e6e76d a0f1888 9254798 a0f1888 bc7afbc a0f1888 9254798 a0f1888 9254798 4e6e76d 9254798 4e6e76d 9254798 a0f1888 9254798 a0f1888 9254798 a0f1888 9254798 a0f1888 9254798 a0f1888 93658e1 a0f1888 9254798 e9f26bb 9254798 e9f26bb a0f1888 9254798 |
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 |
import streamlit as st
import psycopg2
import google.generativeai as genai
# Function to connect to PostgreSQL
def connect_to_db():
try:
conn = psycopg2.connect(
dbname="postgres",
user="postgres",
password="database",
host="localhost",
port="5432"
)
return conn
except Exception as e:
st.error(f"Error connecting to the database: {e}")
return None
# Function to generate SQL query from natural language using Google Gemini
def generate_sql_from_text(prompt):
try:
# Initialize the Gemini client
genai.configure(api_key="AIzaSyCzQ1u1RfAOEgYy2RVyFGGGSzEsiKEtWMk")
model = genai.GenerativeModel('gemini-pro')
# Send the prompt to the Gemini model
response = model.generate_text(prompt)
# Extract the SQL query from the response
sql_query = response["generated_text"]
return sql_query
except Exception as e:
st.error(f"Error generating SQL query: {e}")
return None
# Function to execute SQL query and return results
def execute_sql_query(conn, query):
try:
cursor = conn.cursor()
cursor.execute(query)
results = cursor.fetchall()
cursor.close()
return results
except Exception as e:
st.error(f"Error executing SQL query: {e}")
return None
# Streamlit UI
st.title("Natural Language to SQL with Google Gemini")
# Input prompt from the user
user_prompt = st.text_input("Enter your query in natural language:")
# Connect to the PostgreSQL database
conn = connect_to_db()
if conn and user_prompt:
# Generate SQL query from natural language prompt
st.write("Generating SQL query using Google Gemini...")
sql_query = generate_sql_from_text(user_prompt)
if sql_query:
st.write(f"Generated SQL Query: {sql_query}")
# Execute the generated SQL query
results = execute_sql_query(conn, sql_query)
# Display the results
if results:
st.write("Query Results:")
st.dataframe(results)
# Close the database connection
conn.close()
|