Spaces:
Sleeping
Sleeping
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") | |
def get_data(): | |
try: | |
conn = psycopg2.connect( | |
host=DB_HOST, | |
port=DB_PORT, | |
dbname=DB_NAME, | |
user=DB_USER, | |
password=DB_PASSWORD, | |
sslmode="require" | |
) | |
query = "SELECT country, year, section, question_code, question_text, answer_code, answer_text FROM survey_info;" | |
df = pd.read_sql_query(query, conn) | |
conn.close() | |
return df | |
except Exception as e: | |
st.error(f"Failed to connect to the database: {e}") | |
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.") | |