Skip to content

Commit

Permalink
Update medapp.py
Browse files Browse the repository at this point in the history
  • Loading branch information
Sudhendra committed Oct 17, 2024
1 parent 11ff6da commit e68584b
Showing 1 changed file with 37 additions and 11 deletions.
48 changes: 37 additions & 11 deletions medapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,52 +4,78 @@
import json
import tempfile
from dotenv import load_dotenv
import logging

# Set up logging
logging.basicConfig(level=logging.INFO)

# Load environment variables for local development
load_dotenv()

def get_firebase_key_path():
def get_firebase_key():
"""
Retrieves the Firebase key path from Streamlit secrets or environment variables.
For deployed apps, writes the JSON key to a temporary file and returns the path.
Retrieves the Firebase key from Streamlit secrets or environment variables.
For deployed apps, returns the JSON key directly or writes it to a temporary file.
For local development, returns the path from FIREBASE_KEY_PATH.
"""
logging.info("Attempting to retrieve Firebase key...")

# Check if FIREBASE_KEY_JSON exists in Streamlit secrets
if 'FIREBASE_KEY_JSON' in st.secrets:
logging.info("Found FIREBASE_KEY_JSON in secrets")
firebase_key_json = st.secrets['FIREBASE_KEY_JSON']

# Create a temporary file to store the JSON key
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.json') as temp_key_file:
temp_key_file.write(firebase_key_json)
temp_key_path = temp_key_file.name

return temp_key_path
try:
# Try to parse it as JSON
json.loads(firebase_key_json)
logging.info("Successfully parsed FIREBASE_KEY_JSON as JSON")
return firebase_key_json # Return the JSON string directly
except json.JSONDecodeError:
logging.info("FIREBASE_KEY_JSON is not valid JSON, treating as file path")
# If it's not valid JSON, treat it as a file path
if os.path.exists(firebase_key_json):
return firebase_key_json

# For local development, use FIREBASE_KEY_PATH from environment variables
firebase_key_path = os.getenv("FIREBASE_KEY_PATH")
if firebase_key_path and os.path.exists(firebase_key_path):
logging.info(f"Using local Firebase key path: {firebase_key_path}")
return firebase_key_path

# If neither method works, raise an error
raise ValueError("Firebase key path not found in secrets or local environment")
logging.error("Firebase key not found in secrets or local environment")
raise ValueError("Firebase key not found in secrets or local environment")

def main():
# Retrieve Firebase credentials
try:
firebase_key_path = get_firebase_key_path()
firebase_key = get_firebase_key()
firebase_collection = st.secrets.get('FIREBASE_COLLECTION', 'counts')
logging.info(f"Firebase collection: {firebase_collection}")
except ValueError as e:
st.error(str(e))
logging.error(f"Error retrieving Firebase key: {str(e)}")
st.stop()

# Initialize Firebase Analytics Tracking
try:
if isinstance(firebase_key, str) and firebase_key.startswith('{'):
# If firebase_key is a JSON string, write it to a temporary file
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.json') as temp_file:
temp_file.write(firebase_key)
firebase_key_path = temp_file.name
else:
firebase_key_path = firebase_key

logging.info(f"Initializing tracking with key path: {firebase_key_path}")
streamlit_analytics.track(
firestore_key_file=firebase_key_path,
firestore_collection_name=firebase_collection
)
logging.info("Successfully initialized analytics tracking")
except Exception as e:
st.error(f"Error initializing analytics tracking: {e}")
logging.error(f"Error initializing analytics tracking: {str(e)}")
st.stop()

st.title("Step 1 Buddy")
Expand Down

0 comments on commit e68584b

Please sign in to comment.