cgd-ui-TEST / app.py
myshirk's picture
add option for AWS database
23381bb verified
raw
history blame
1.61 kB
import streamlit as st
import pandas as pd
import psycopg2
import os
# Load DB credentials from Hugging Face secrets or environment variables
DB_HOST = os.getenv("DB_HOST")
DB_PORT = os.getenv("DB_PORT", "5432")
DB_NAME = os.getenv("DB_NAME")
DB_USER = os.getenv("DB_USER")
DB_PASSWORD = os.getenv("DB_PASSWORD")
@st.cache_data(ttl=600)
def get_data():
try:
conn = psycopg2.connect(
host=DB_HOST,
port=DB_PORT,
dbname=DB_NAME,
user=DB_USER,
password=DB_PASSWORD
)
query = "SELECT country, year, section, question_code, question_text, answer_code, answer_text FROM survey_data;"
df = pd.read_sql_query(query, conn)
conn.close()
return df
except Exception as e:
st.error("Failed to connect to the database.")
st.stop()
# Load data
df = get_data()
# Streamlit UI
st.title("🌍 CGD Survey Explorer (Live DB)")
st.sidebar.header("πŸ”Ž Filter Questions")
selected_country = st.sidebar.selectbox("Select Country", sorted(df["country"].unique()))
selected_year = st.sidebar.selectbox("Select Year", sorted(df["year"].unique()))
keyword = st.sidebar.text_input("Keyword Search", "")
# Filtered data
filtered = df[
(df["country"] == selected_country) &
(df["year"] == selected_year) &
(df["question_text"].str.contains(keyword, case=False, na=False))
]
st.markdown(f"### Results for **{selected_country}** in **{selected_year}**")
st.dataframe(filtered[["country", "question_text", "answer_text"]])
if filtered.empty:
st.info("No matching questions found.")