Spaces:
Sleeping
Sleeping
| #this was not the original storage py file, and was created for Huggging Face. If this fails consider using storage_local.py | |
| import os | |
| import json | |
| import streamlit as st | |
| from google.cloud import storage | |
| from google.oauth2 import service_account | |
| # ✅ YOUR BUCKET NAME | |
| BUCKET_NAME = "piranaware20251227841ph" | |
| def get_storage_client(): | |
| """ | |
| Authenticates with Google Cloud. | |
| Priority: | |
| 1. Local File (Codespaces) | |
| 2. Environment Variable (Hugging Face Docker) | |
| 3. Streamlit Secrets (Streamlit Cloud fallback) | |
| """ | |
| # 1. Local Dev: Check for local file | |
| if os.path.exists("gcp_key.json"): | |
| return storage.Client.from_service_account_json("gcp_key.json") | |
| # 2. Hugging Face / Docker: Check Environment Variable | |
| # In HF, secrets are stored as Env Vars, so we parse the JSON string. | |
| env_key = os.environ.get("gcp_service_account") | |
| if env_key: | |
| try: | |
| creds_dict = json.loads(env_key) | |
| creds = service_account.Credentials.from_service_account_info(creds_dict) | |
| return storage.Client(credentials=creds) | |
| except Exception as e: | |
| st.error(f"⚠️ Credential Error: {e}") | |
| return None | |
| # 3. Streamlit Cloud: Check Secrets (Fallback) | |
| if "gcp_service_account" in st.secrets: | |
| try: | |
| creds_dict = dict(st.secrets["gcp_service_account"]) | |
| creds = service_account.Credentials.from_service_account_info(creds_dict) | |
| return storage.Client(credentials=creds) | |
| except Exception: | |
| pass | |
| # 4. If nothing works | |
| st.error("⚠️ No Google Cloud credentials found. Cannot save/load models.") | |
| return None | |
| def upload_file(local_path, boat_id, filename): | |
| client = get_storage_client() | |
| if not client: return False | |
| try: | |
| bucket = client.bucket(BUCKET_NAME) | |
| # Creates folder structure: boat_id/filename | |
| blob_name = f"{boat_id}/{filename}" | |
| blob = bucket.blob(blob_name) | |
| blob.upload_from_filename(local_path) | |
| return True | |
| except Exception as e: | |
| st.error(f"Upload failed: {e}") | |
| return False | |
| def download_file(boat_id, filename, local_dest): | |
| client = get_storage_client() | |
| if not client: return False | |
| try: | |
| bucket = client.bucket(BUCKET_NAME) | |
| blob_name = f"{boat_id}/{filename}" | |
| blob = bucket.blob(blob_name) | |
| if not blob.exists(): | |
| return False | |
| blob.download_to_filename(local_dest) | |
| return True | |
| except Exception as e: | |
| st.error(f"Download failed: {e}") | |
| return False |