File size: 3,722 Bytes
bd180df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
102
103
104
105
106
107
108
109
#!/usr/bin/env python3
"""
Test script for PRIVATE Hugging Face Spaces with authentication.
Usage: uv run python test_private_space.py [space-url] [hf-token]
"""

import sys
import requests
import json
import os

# ANSI color codes
GREEN = '\033[0;32m'
RED = '\033[0;31m'
YELLOW = '\033[1;33m'
BLUE = '\033[0;34m'
NC = '\033[0m'  # No Color


def get_headers(token: str = None) -> dict:
    """Get headers with authentication if token provided"""
    headers = {"Content-Type": "application/json"}
    if token:
        headers["Authorization"] = f"Bearer {token}"
    return headers


def test_with_auth(base_url: str, token: str = None):
    """Test space with optional authentication"""
    print("=" * 50)
    print(f"Testing Space: {base_url}")
    if token:
        print(f"Using token: {token[:10]}...{token[-5:]}")
    else:
        print("No token provided (testing public access)")
    print("=" * 50)
    print()

    headers = get_headers(token)

    # Test health endpoint
    print(f"{YELLOW}Test: Health Check{NC}")
    try:
        response = requests.get(f"{base_url}/health", headers=headers, timeout=10)
        
        if response.status_code == 200:
            print(f"{GREEN}βœ“ SUCCESS{NC} - Space is accessible!")
            print(f"Response: {response.json()}")
            return True
        elif response.status_code == 404:
            print(f"{RED}βœ— 404 ERROR{NC}")
            print(f"\n{YELLOW}Possible reasons:{NC}")
            print("1. Space is PRIVATE and needs authentication token")
            print("2. Space is still building")
            print("3. Space build failed")
            print("\nTo fix:")
            print("β€’ Make space public in settings, OR")
            print("β€’ Use: uv run python test_private_space.py [url] [your-hf-token]")
            return False
        elif response.status_code == 401:
            print(f"{RED}βœ— 401 UNAUTHORIZED{NC}")
            print("Space is PRIVATE. You need a valid Hugging Face token.")
            print("\nGet your token:")
            print("1. Go to https://huggingface.co/settings/tokens")
            print("2. Create a new token with 'read' permissions")
            print("3. Run: uv run python test_private_space.py [url] [token]")
            return False
        else:
            print(f"{RED}βœ— ERROR{NC} - Status: {response.status_code}")
            print(f"Response: {response.text[:200]}")
            return False
    except Exception as e:
        print(f"{RED}βœ— ERROR{NC} - {str(e)}")
        return False


def main():
    # Get space URL and token
    base_url = sys.argv[1] if len(sys.argv) > 1 else "https://ocx2025-basicsearch.hf.space"
    token = sys.argv[2] if len(sys.argv) > 2 else os.getenv("HF_TOKEN")
    
    # Remove trailing slash
    base_url = base_url.rstrip('/')
    
    # Test
    success = test_with_auth(base_url, token)
    
    if success:
        print(f"\n{GREEN}βœ… Space is working!{NC}")
        print(f"You can now run the full test suite:")
        if token:
            print(f"HF_TOKEN={token} uv run python test_deployment.py")
        else:
            print("uv run python test_deployment.py")
    else:
        print(f"\n{YELLOW}πŸ“ Next Steps:{NC}")
        print("\n1. Check if space is private:")
        print(f"   Visit: {base_url.replace('.hf.space', '').replace('https://', 'https://huggingface.co/spaces/').replace('-', '/', 1)}")
        print("\n2. Make it PUBLIC:")
        print("   Settings β†’ Make public")
        print("\n3. OR get your HF token:")
        print("   https://huggingface.co/settings/tokens")
        print(f"   Then run: uv run python test_private_space.py {base_url} YOUR_TOKEN")


if __name__ == "__main__":
    main()