corruptometre / database.py
cfcmoon's picture
Upload database.py
81bfe97 verified
Raw History Blame Contribute Delete
5.61 kB
import json
import os
import streamlit as st
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.utils import RepositoryNotFoundError, RevisionNotFoundError
from data import POLITICIANS as STATIC_DB
DB_FILE = "corruptometre_db.json"
DATASET_REPO_NAME = "corruptometre-data" # Name of the dataset repo
def get_token():
"""Retrieves the HF token from secrets or environment."""
# 1. Check Environment (Priority for Cloud/Docker)
if "HF_TOKEN" in os.environ:
return os.environ["HF_TOKEN"]
# 2. Check Streamlit Secrets (Priority for Local)
try:
if "HF_TOKEN" in st.secrets:
return st.secrets["HF_TOKEN"]
except Exception:
pass
return None
def get_repo_id(api, token):
"""Constructs the full repo ID (username/repo_name)."""
try:
user = api.whoami(token=token)
return f"{user['name']}/{DATASET_REPO_NAME}"
except Exception:
return None
def load_db():
"""Loads the dynamic database from Hugging Face Hub (or local fallback)."""
token = get_token()
if not token:
print("⚠️ No token found. Using local DB only.")
if not os.path.exists(DB_FILE):
return {}
try:
with open(DB_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except:
return {}
api = HfApi(token=token)
repo_id = get_repo_id(api, token)
if not repo_id:
return {}
print(f"☁️ Syncing from {repo_id}...")
try:
# Try to download the file
file_path = hf_hub_download(
repo_id=repo_id,
filename=DB_FILE,
repo_type="dataset",
token=token,
local_dir=".", # Download to current directory
local_dir_use_symlinks=False # Ensure we get the actual file
)
with open(file_path, "r", encoding="utf-8") as f:
return json.load(f)
except (RepositoryNotFoundError, RevisionNotFoundError, Exception) as e:
print(f"⚠️ Could not load from Cloud ({e}). Starting fresh or local.")
# If repo doesn't exist, we'll create it on save.
if os.path.exists(DB_FILE):
try:
with open(DB_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except:
return {}
return {}
def save_db(data):
"""Saves the dynamic database to JSON file AND uploads to Hugging Face Hub."""
# 1. Save Locally
try:
with open(DB_FILE, "w", encoding="utf-8") as f:
json.dump(data, f, indent=4, ensure_ascii=False)
except Exception as e:
print(f"Error saving local DB: {e}")
return
# 2. Upload to Cloud
token = get_token()
if not token:
return
api = HfApi(token=token)
repo_id = get_repo_id(api, token)
if not repo_id:
return
try:
# Create repo if it doesn't exist
api.create_repo(repo_id=repo_id, repo_type="dataset", exist_ok=True, token=token)
# Upload file
api.upload_file(
path_or_fileobj=DB_FILE,
path_in_repo=DB_FILE,
repo_id=repo_id,
repo_type="dataset",
commit_message="Update corruptometre database",
token=token
)
print("☁️ Database synced to Cloud!")
except Exception as e:
print(f"❌ Error uploading to Cloud: {e}")
def get_all_politicians():
"""
Returns a merged dictionary of politicians.
Static DB is the base, overlaid with Dynamic DB.
"""
dynamic_db = load_db()
merged_db = STATIC_DB.copy()
for name, data in dynamic_db.items():
if name in merged_db:
# Merge casseroles (union)
static_casseroles = set(merged_db[name]["casseroles"])
dynamic_casseroles = set(data.get("casseroles", []))
merged_db[name]["casseroles"] = list(static_casseroles | dynamic_casseroles)
# Update other fields if present in dynamic
if "party" in data:
merged_db[name]["party"] = data["party"]
# Store AI analysis if present
if "ai_analysis" in data:
merged_db[name]["ai_analysis"] = data["ai_analysis"]
else:
# New politician found via search
merged_db[name] = data
return merged_db
def update_politician(name, new_data):
"""
Updates a politician's entry in the dynamic DB and saves it.
"""
# Reload to get latest state (in case of concurrent edits, though simple overwrite here)
# Ideally we should merge, but for now load->update->save is okay for single user flow.
dynamic_db = load_db()
# If exists, merge. If not, create.
if name in dynamic_db:
# Merge casseroles
existing_casseroles = set(dynamic_db[name].get("casseroles", []))
new_casseroles = set(new_data.get("casseroles", []))
dynamic_db[name]["casseroles"] = list(existing_casseroles | new_casseroles)
# Update other fields
dynamic_db[name]["party"] = new_data.get("party", dynamic_db[name].get("party"))
if "ai_analysis" in new_data:
dynamic_db[name]["ai_analysis"] = new_data["ai_analysis"]
else:
dynamic_db[name] = new_data
save_db(dynamic_db)