Spaces:
Sleeping
Sleeping
Download utils.py from AimanGh/explore_Chinese: direct link, hf CLI and curl.
- Browser
- Download file 1.84 kB
-
https://huggingface.co/spaces/AimanGh/explore_Chinese/resolve/main/utils.py
- Command line
-
hf download hf://spaces/AimanGh/explore_Chinese/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/AimanGh/explore_Chinese/resolve/main/utils.py
1.84 kB
| # 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 | |
| # 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 | |