import os from huggingface_hub import HfApi import sys # Configuration HF_TOKEN = os.environ.get("HF_TOKEN") SPACE_NAME = "Kraft102/widgetdc-cortex" ENV_FILE = ".env" def parse_env_file(filepath): """Parse .env file manually to avoid dependencies""" env_vars = {} try: with open(filepath, 'r', encoding='utf-8') as f: for line in f: line = line.strip() # Skip comments and empty lines if not line or line.startswith('#'): continue # Parse KEY=VALUE if '=' in line: key, value = line.split('=', 1) key = key.strip() value = value.strip() # Remove quotes if present if (value.startswith('"') and value.endswith('"')) or \ (value.startswith("'") and value.endswith("'")): value = value[1:-1] env_vars[key] = value except Exception as e: print(f"Error reading .env file: {e}") sys.exit(1) return env_vars def main(): print(f"šŸ”„ Syncing {ENV_FILE} to Hugging Face Space: {SPACE_NAME}") # 1. Parse local .env env_vars = parse_env_file(ENV_FILE) print(f"šŸ“ Found {len(env_vars)} variables in .env") # 2. Add specific overrides for Deployment overrides = { 'NODE_ENV': 'production', 'PORT': '7860', # Ensure we don't accidentally use localhost for critical services # (Though we can't fix them if real values aren't in .env, we can at least set defaults) } # Update with overrides for k, v in overrides.items(): if k not in env_vars: print(f"āž• Adding default: {k}={v}") env_vars[k] = v # 3. Initialize API try: api = HfApi(token=HF_TOKEN) user = api.whoami() print(f"āœ… Authenticated as: {user['name']}") except Exception as e: print(f"āŒ Authentication failed: {e}") sys.exit(1) # 4. Upload Secrets success = 0 failed = 0 print("\nšŸš€ Uploading secrets...") for key, value in env_vars.items(): # Skip if value is clearly a placeholder or localhost (optional check?) # For "autonomous" mode, we upload EVERYTHING found in .env as requested. try: api.add_space_secret( repo_id=SPACE_NAME, key=key, value=value, token=HF_TOKEN ) # Mask value for log masked = value[:4] + "..." + value[-4:] if len(value) > 10 else "***" print(f" āœ… Set {key}") success += 1 except Exception as e: print(f" āŒ Failed {key}: {e}") failed += 1 print(f"\nšŸ“Š Summary: {success} added, {failed} failed") if success > 0: print("šŸ”„ Triggering Space restart (happens automatically on secret update)...") if __name__ == "__main__": main()