File size: 5,610 Bytes
663439a
 
 
 
 
 
 
 
 
 
 
 
81bfe97
 
 
 
 
 
 
 
 
 
 
 
663439a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
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)