File size: 3,164 Bytes
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101

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()