Spaces:
Runtime error
Runtime error
| #!/usr/bin/env python3 | |
| """ | |
| Sync secrets from GitHub Actions to HuggingFace Space. | |
| Reads configuration from environment variables: | |
| HF_SPACE: HuggingFace Space repository ID (e.g., "InstaDeepAI/sentinel") | |
| HF_TOKEN: HuggingFace API token | |
| RUNTIME_SECRETS: Multi-line string with secrets in format "KEY: value" | |
| """ | |
| import logging | |
| import os | |
| from huggingface_hub import HfApi | |
| # Configure logging | |
| logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") | |
| def extract(payload): | |
| """Parse secrets from YAML-like format. | |
| Args: | |
| payload: Multi-line string with secrets in format "KEY: value" | |
| Returns: | |
| Dictionary mapping secret keys to values | |
| """ | |
| secrets = {} | |
| if not payload: | |
| return secrets | |
| for line in payload.strip().split("\n"): | |
| line = line.strip() | |
| if ":" in line and line: | |
| key, value = line.split(":", 1) | |
| key = key.strip() | |
| value = value.strip() | |
| if key and value: # Only add if both key and value are non-empty | |
| secrets[key] = value | |
| return secrets | |
| def upload(repository, token, payload): | |
| """Sync secrets to HuggingFace Space. | |
| Args: | |
| repository: HuggingFace Space repository ID | |
| token: HuggingFace API token | |
| payload: Multi-line string with secrets in format "KEY: value" | |
| Raises: | |
| RuntimeError: If any secret fails to sync | |
| """ | |
| client = HfApi(token=token) | |
| secrets = extract(payload) | |
| if not secrets: | |
| logging.info("No runtime secrets to configure") | |
| return | |
| count = 0 | |
| for key, value in secrets.items(): | |
| try: | |
| client.add_space_secret(repo_id=repository, key=key, value=value) | |
| logging.info("Added %s secret to HuggingFace Space", key) | |
| count += 1 | |
| except Exception as e: | |
| logging.error("Failed to add %s: %s", key, e) | |
| raise RuntimeError(f"Failed to sync secret {key}") from e | |
| logging.info("Successfully configured %d secret(s)", count) | |
| if __name__ == "__main__": | |
| # Read configuration from environment variables | |
| repository = os.getenv("HF_SPACE") | |
| token = os.getenv("HF_TOKEN") | |
| payload = os.getenv("RUNTIME_SECRETS", "") | |
| # Validate required environment variables | |
| if not repository: | |
| raise ValueError("HF_SPACE environment variable is required") | |
| if not token: | |
| raise ValueError("HF_TOKEN environment variable is required") | |
| # Run the sync - any exceptions will naturally exit with code 1 | |
| upload(repository, token, payload) | |