Spaces:
Running
Running
import streamlit as st | |
import requests | |
import pandas as pd | |
import matplotlib.pyplot as plt | |
import seaborn as sns | |
st.set_page_config( | |
page_title="SQL Agent with Streamlit", | |
page_icon=":bar_chart:", | |
layout="wide" | |
) | |
with st.sidebar: | |
st.write("## About Me") | |
st.write("**Mahmoud Hassanen**") | |
st.write("**[LinkedIn Profile](https://www.linkedin.com/in/mahmoudhassanen99//)**") | |
st.title("SQL Agent with Streamlit") | |
st.header("Analyze Sales Data with Natural Language Queries") | |
API_URL = "https://14d0-34-27-134-153.ngrok-free.app/query" | |
question = st.text_input("Enter your question:") | |
if st.button("Generate SQL"): | |
if question: | |
response = requests.post(API_URL, json={"question": question}) | |
if response.status_code == 200: | |
data = response.json() | |
generated_sql = data["sql_query"] | |
st.session_state.generated_sql = generated_sql # Store the generated SQL in session state | |
st.write("### Generated SQL Query:") | |
st.code(generated_sql, language="sql") | |
else: | |
st.error(f"API Error: Status Code {response.status_code}") | |
else: | |
st.warning("Please enter a question.") | |
# Allow the user to modify the SQL query | |
if "generated_sql" in st.session_state: | |
modified_sql = st.text_area("Modify the SQL query (if needed):", st.session_state.generated_sql, height=200) | |
if st.button("Execute Modified Query"): | |
try: | |
# Execute the modified SQL query | |
result = execute_sql(modified_sql) # Use your existing execute_sql function | |
st.write("### Query Results:") | |
st.dataframe(result) | |
# Visualize the data (if applicable) | |
if 'region' in result.columns and 'total_sales' in result.columns: | |
st.write("### Total Sales by Region") | |
fig, ax = plt.subplots() | |
sns.barplot(x='region', y='total_sales', data=result, ax=ax) | |
st.pyplot(fig) | |
except Exception as e: | |
st.error(f"Error executing SQL: {e}") | |
# Function to execute SQL and return results | |
def execute_sql(sql_query): | |
# Create a SQLAlchemy connection string | |
connection_string = f"mssql+pyodbc://{username}:{password}@{server}/{database}?driver={driver.replace(' ', '+')}" | |
engine = create_engine(connection_string) | |
# Execute the query and fetch results | |
df = pd.read_sql(sql_query, engine) | |
return df |