File size: 1,607 Bytes
d3a33c8
 
 
23381bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3a33c8
 
23381bb
 
d3a33c8
 
23381bb
d3a33c8
23381bb
 
 
d3a33c8
 
 
23381bb
d3a33c8
 
 
23381bb
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

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.")