File size: 1,694 Bytes
1017fb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import os
import streamlit as st
import firebase_admin
from firebase_admin import credentials, firestore

def initialize_firebase():
    """

    Initializes Firebase Admin SDK and returns Firestore client.

    Ensures initialization happens only once.

    """
    # Check if Firebase is already initialized
    if not firebase_admin._apps:
        try:
            # 1. Try to load from Streamlit Secrets (for Cloud Deployment)
            has_secrets = False
            try:
                if "firebase_key" in st.secrets:
                    has_secrets = True
            except Exception:
                pass

            if has_secrets:
                # Convert AttrDict to regular dict if needed
                key_dict = dict(st.secrets["firebase_key"])
                cred = credentials.Certificate(key_dict)
                firebase_admin.initialize_app(cred)
            
            # 2. Try to load from local file (for Local Development)
            else:
                current_dir = os.path.dirname(os.path.abspath(__file__))
                key_path = os.path.join(current_dir, "serviceAccountKey.json")

                if os.path.exists(key_path):
                    cred = credentials.Certificate(key_path)
                    firebase_admin.initialize_app(cred)
                else:
                    st.error("Firebase credentials not found (checked secrets and local file).")
                    st.stop()
            
        except Exception as e:
            st.error(f"Failed to initialize Firebase: {e}")
            st.stop()
            
    # Return Firestore client instance
    return firestore.client()