File size: 1,839 Bytes
091e192
 
c87f46d
 
 
 
 
 
 
 
 
 
091e192
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c87f46d
 
 
091e192
 
c87f46d
091e192
c87f46d
 
091e192
 
 
 
c87f46d
 
091e192
c87f46d
 
 
 
 
 
 
 
 
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
# utils.py
import os
import streamlit as st
import pandas as pd
from db import run_query


def page_header(title: str, emoji: str = "📄"):
    """Reusable page header with emoji."""
    st.markdown(f"# {emoji} {title}")


def _has_db_config() -> bool:
    """True if a DB connection string is configured (HF env vars or Streamlit secrets)."""
    # 1) HF Spaces: env vars
    if any(os.getenv(k) for k in ("DB_CONNECTION", "db_connection", "DATABASE_URL", "database_url")):
        return True
    # 2) Streamlit Cloud/local: secrets.toml
    try:
        return any(k in st.secrets for k in ("db_connection", "DATABASE_URL", "database_url"))
    except Exception:
        # No secrets.toml present
        return False


@st.cache_data(ttl=86400)  # cache for 1 day
def load_data(
    local_csv: str = "data/two_char_verbs_with_Tr_Pro_with_UMAP.csv",
    table_name: str = "verbs",
    use_local: bool = False,
):
    """
    Load verbs data:
    - If use_local=True -> always load local CSV
    - Else if DB config exists -> query DB
    - Else -> fallback to CSV
    """
    if not use_local and _has_db_config() and run_query is not None:
        try:
            df = run_query(f"SELECT * FROM {table_name};")
            # Safety: if run_query accidentally returns (df,), unwrap it
            if isinstance(df, tuple):
                df = df[0]
            st.info("Loaded data from database ✅")
            return df
        except Exception as e:
            st.warning(f"Failed to query DB: {e}\nFalling back to local CSV…")

    # Local CSV fallback
    try:
        df = pd.read_csv(local_csv)
        st.info("Loaded data from local CSV ✅")
        return df
    except FileNotFoundError:
        st.error("Local CSV not found. Please add it to your project folder.")
        return pd.DataFrame()  # empty DataFrame